<commit_before>
#include <iterator>

#include "Representations/Infrastructure/JointData.h"
#include "Tools/Math/Common.h"
#include "PlatformInterface/Platform.h"
#include "Tools/Debug/NaoTHAssert.h"
#include "Messages/Framework-Representations.pb.h"
#include <google/protobuf/io/zero_copy_stream_impl.h>

using namespace naoth;
using namespace std;

double JointData::min[JointData::numOfJoint];
double JointData::max[JointData::numOfJoint];

JointData::JointData()
{
  // init the arrays
  for (int i = 0; i < numOfJoint; i++)
  {
    position[i] = 0.0;
    dp[i] = 0.0;
    ddp[i] = 0.0;
    stiffness[i] = 0.0;
  }
}

void JointData::loadJointLimitsFromConfig()
{
  const Configuration& cfg = Platform::getInstance().theConfiguration;
  for (int i = 0; i < JointData::numOfJoint; i++)
  {
    string jointName = JointData::getJointName((JointData::JointID)i);

    if (cfg.hasKey("joints", jointName + "Max")) {
      max[i] = Math::fromDegrees(cfg.getDouble("joints", jointName + "Max"));
    } else {
      THROW("JointData: can not get " + jointName + " max angle");
    }

    if (cfg.hasKey("joints", jointName + "Min")) {
      min[i] = Math::fromDegrees(cfg.getDouble("joints", jointName + "Min"));
    } else {
      THROW("JointData: can not get " + jointName + " min angle");
    }
  }//enf for
}//end init

string JointData::getJointName(JointID joint)
{
  switch (joint)
  {
    case HeadPitch: return string("HeadPitch");
    case HeadYaw: return string("HeadYaw");
    case RShoulderRoll: return string("RShoulderRoll");
    case LShoulderRoll: return string("LShoulderRoll");
    case RShoulderPitch: return string("RShoulderPitch");
    case LShoulderPitch: return string("LShoulderPitch");
    case RElbowRoll: return string("RElbowRoll");
    case LElbowRoll: return string("LElbowRoll");
    case RElbowYaw: return string("RElbowYaw");
    case LElbowYaw: return string("LElbowYaw");

    case LWristYaw: return string("LWristYaw");
    case RWristYaw: return string("RWristYaw");
    case LHand: return string("LHand");
    case RHand: return string("RHand");

    case LHipYawPitch: return string("LHipYawPitch");
    case RHipYawPitch: return string("RHipYawPitch");
    case RHipPitch: return string("RHipPitch");
    case LHipPitch: return string("LHipPitch");
    case RHipRoll: return string("RHipRoll");
    case LHipRoll: return string("LHipRoll");
    case RKneePitch: return string("RKneePitch");
    case LKneePitch: return string("LKneePitch");
    case RAnklePitch: return string("RAnklePitch");
    case LAnklePitch: return string("LAnklePitch");
    case RAnkleRoll: return string("RAnkleRoll");
    case LAnkleRoll: return string("LAnkleRoll");
    default: return string("Unknown Joint");
  }//end switch
}//end getJointName

double JointData::mirrorData(JointID joint) const
{
  switch (joint)
  {
      // Head (don't mirror)
    case HeadYaw: return -position[HeadYaw];
    case HeadPitch: return position[HeadPitch];

      // Arms
    case RShoulderPitch: return position[LShoulderPitch];
    case RShoulderRoll: return -position[LShoulderRoll];
    case RElbowYaw: return -position[LElbowYaw];
    case RElbowRoll: return -position[LElbowRoll];

    case LShoulderPitch: return position[RShoulderPitch];
    case LShoulderRoll: return -position[RShoulderRoll];
    case LElbowYaw: return -position[RElbowYaw];
    case LElbowRoll: return -position[RElbowRoll];

      // Legs
    case RHipYawPitch: return position[LHipYawPitch];
    case RHipPitch: return position[LHipPitch];
    case RHipRoll: return -position[LHipRoll];
    case RKneePitch: return position[LKneePitch];
    case RAnklePitch: return position[LAnklePitch];
    case RAnkleRoll: return -position[LAnkleRoll];

    case LHipYawPitch: return position[RHipYawPitch];
    case LHipPitch: return position[RHipPitch];
    case LHipRoll: return -position[RHipRoll];
    case LKneePitch: return position[RKneePitch];
    case LAnklePitch: return position[RAnklePitch];
    case LAnkleRoll: return -position[RAnkleRoll];
    default: return position[joint];
  }
}//end mirrorData

JointData::JointID JointData::jointIDFromName(std::string name)
{
  for (int i = 0; i < numOfJoint; i++) {
    if (name == getJointName((JointID) i)) return (JointID) i;
  }

  return numOfJoint;
}//end getJointName

void JointData::mirrorFrom(const JointData& jointData)
{
  for (int i = 0; i < numOfJoint; i++) {
    position[i] = jointData.mirrorData((JointID) i);
  }
}//end mirror

void JointData::mirror()
{
  JointData tmp = *this;
  mirrorFrom(tmp);
}

void JointData::clamp(JointID id)
{
  position[id] = Math::clamp(position[id], min[id], max[id]);
}

void JointData::clamp()
{
  for( int i=0; i<numOfJoint; i++) {
    clamp((JointID)i);
  }
}

bool JointData::isInRange(JointData::JointID id, double ang) const
{
    return ang <= max[id] && ang >= min[id];
}

bool JointData::isInRange(JointData::JointID id) const
{
    return isInRange(id, position[id]);
}

void JointData::updateSpeed(const JointData& lastData, double dt)
{
  const double* lastPose = lastData.position;
  double idt = 1 / dt;
  for ( int i=0; i<JointData::numOfJoint; i++)
  {
    dp[i] = (position[i] - lastPose[i]) * idt;
  }
}

void JointData::updateAcceleration(const JointData& lastData, double dt)
{
  const double* lastSpeed = lastData.dp;
  double idt = 1 / dt;
  for (int i = 0; i < JointData::numOfJoint; i++)
  {
    ddp[i] = (dp[i] - lastSpeed[i]) * idt;
  }
}

bool JointData::isLegStiffnessOn() const
{
  for ( int i=JointData::RHipYawPitch; i<JointData::numOfJoint; i++)
  {
    if ( stiffness[i] < 0 ) return false;
  }
  return true;
}

int JointData::checkStiffness() const
{
  for(int i=0; i<JointData::numOfJoint; i++)
  {
    double v = stiffness[i];
    if ( v > 1 || v < -1 )
    {
      return i;
      //THROW("Get ILLEGAL Stiffness: "<<getJointName(JointData::JointID(i))<<" = "<<v);
    }
  }
  return -1;
}

SensorJointData::SensorJointData()
  : timestamp(0)
{
  for (int i = 0; i < numOfJoint; i++)
  {
    electricCurrent[i] = 0.0;
    temperature[i] = 0.0;
  }
}

void SensorJointData::print(ostream& stream) const
{
  stream << "Timestamp: " << timestamp << endl;
  stream << "Joint [pos(deg), stiffness, temperature,current]" << endl;
  stream << "------------------------" << endl;
  for (int i = 0; i < numOfJoint; i++)
  {
    stream.precision(4);
    stream << getJointName((JointData::JointID) i) << "\t[" << fixed << Math::toDegrees(position[i]) << ", " << stiffness[i] << ", ";
    stream.precision(0);
    stream << temperature[i] << ", ";
    stream.precision(3);
    stream << electricCurrent[i] << "]" <<  endl;
  }
}//end print

SensorJointData::~SensorJointData()
{
}

MotorJointData::MotorJointData()
{
}

MotorJointData::~MotorJointData()
{
}

void MotorJointData::print(ostream& stream) const
{
  stream << "Joint [pos, stiffness]" << endl;
  stream << "------------------------" << endl;
  for (int i = 0; i < numOfJoint; i++) {
    stream << getJointName((JointData::JointID) i) << "[" << position[i] << ", " << stiffness[i] << "]" << endl;
  }
}//end print

void Serializer<SensorJointData>::serialize(const SensorJointData& representation, std::ostream& stream)
{
  naothmessages::SensorJointData message;

  for(int i=0; i < JointData::numOfJoint; i++)
  {
    message.add_electriccurrent(representation.electricCurrent[i]);
    message.add_temperature(representation.temperature[i]);

    message.mutable_jointdata()->add_position(representation.position[i]);
    message.mutable_jointdata()->add_stiffness(representation.stiffness[i]);
    message.mutable_jointdata()->add_dp(representation.dp[i]);
    message.mutable_jointdata()->add_ddp(representation.ddp[i]);
  }

  google::protobuf::io::OstreamOutputStream buf(&stream);
  message.SerializeToZeroCopyStream(&buf);
}

void Serializer<SensorJointData>::deserialize(std::istream& stream, SensorJointData& representation)
{
  naothmessages::SensorJointData message;
  google::protobuf::io::IstreamInputStream buf(&stream);
  message.ParseFromZeroCopyStream(&buf);

  // assure the integrity of the message
  ASSERT( message.electriccurrent().size() == JointData::numOfJoint ||
          message.electriccurrent().size() == JointData::numOfJoint - 4);
  ASSERT( message.temperature().size() == JointData::numOfJoint ||
          message.temperature().size() == JointData::numOfJoint - 4);
  ASSERT( message.jointdata().position().size() == JointData::numOfJoint ||
          message.jointdata().position().size() == JointData::numOfJoint - 4);
  ASSERT( message.jointdata().stiffness().size() == JointData::numOfJoint ||
          message.jointdata().stiffness().size() == JointData::numOfJoint - 4);
  ASSERT( message.jointdata().dp().size() == JointData::numOfJoint ||
          message.jointdata().dp().size() == JointData::numOfJoint - 4);
  ASSERT( message.jointdata().ddp().size() == JointData::numOfJoint ||
          message.jointdata().ddp().size() == JointData::numOfJoint - 4);

  for (int i = 0; i < JointData::numOfJoint; i++)
  {
    if(i < message.jointdata().position().size())
    {
      representation.electricCurrent[i] = message.electriccurrent(i);
      representation.temperature[i] = message.temperature(i);
      // joint data
      representation.position[i] = message.jointdata().position(i);
      representation.stiffness[i] = message.jointdata().stiffness(i);
      representation.dp[i] = message.jointdata().dp(i);
      representation.ddp[i] = message.jointdata().ddp(i);
    }
    else // LWristYaw, RWristYaw, LHand, RHand don't exist in old messages
    {
      representation.electricCurrent[i] = 0;
      representation.temperature[i] = 0;
      // joint data
      representation.position[i] = 0;
      representation.stiffness[i] = 0;
      representation.dp[i] = 0;
      representation.ddp[i] = 0;
    }
  }
}

void Serializer<MotorJointData>::serialize(const MotorJointData& representation, std::ostream& stream)
{
  naothmessages::JointData message;

  for(int i=0; i < JointData::numOfJoint; i++)
  {
    message.add_position(representation.position[i]);
    message.add_stiffness(representation.stiffness[i]);
    message.add_dp(representation.dp[i]);
    message.add_ddp(representation.ddp[i]);
  }

  google::protobuf::io::OstreamOutputStream buf(&stream);
  message.SerializeToZeroCopyStream(&buf);
}

void Serializer<MotorJointData>::deserialize(std::istream& stream, MotorJointData& representation)
{
  naothmessages::JointData message;
  google::protobuf::io::IstreamInputStream buf(&stream);
  message.ParseFromZeroCopyStream(&buf);

  // assure the integrity of the message
  ASSERT(message.position().size() == JointData::numOfJoint);
  ASSERT(message.stiffness().size() == JointData::numOfJoint);
  ASSERT(message.dp().size() == JointData::numOfJoint);
  ASSERT(message.ddp().size() == JointData::numOfJoint);

  for(int i=0; i < JointData::numOfJoint; i++)
  {
    representation.position[i] = message.position(i);
    representation.stiffness[i] = message.stiffness(i);
    representation.dp[i] = message.dp(i);
    representation.ddp[i] = message.ddp(i);
  }
}

<commit_msg>fix load the min-max positions for hands<commit_after>
#include <iterator>

#include "Representations/Infrastructure/JointData.h"
#include "Tools/Math/Common.h"
#include "PlatformInterface/Platform.h"
#include "Tools/Debug/NaoTHAssert.h"
#include "Messages/Framework-Representations.pb.h"
#include <google/protobuf/io/zero_copy_stream_impl.h>

using namespace naoth;
using namespace std;

double JointData::min[JointData::numOfJoint];
double JointData::max[JointData::numOfJoint];

JointData::JointData()
{
  // init the arrays
  for (int i = 0; i < numOfJoint; i++)
  {
    position[i] = 0.0;
    dp[i] = 0.0;
    ddp[i] = 0.0;
    stiffness[i] = 0.0;
  }
}

void JointData::loadJointLimitsFromConfig()
{
  const Configuration& cfg = Platform::getInstance().theConfiguration;
  for (int i = 0; i < JointData::numOfJoint; i++)
  {
    string jointName = JointData::getJointName((JointData::JointID)i);

    if (cfg.hasKey("joints", jointName + "Max")) {
      double v = cfg.getDouble("joints", jointName + "Max");
      max[i] = (i == LHand || i == RHand)?v:Math::fromDegrees(v);
    } else {
      THROW("JointData: can not get " + jointName + " max angle");
    }

    if (cfg.hasKey("joints", jointName + "Min")) {
      double v = cfg.getDouble("joints", jointName + "Min");
      min[i] = (i == LHand || i == RHand)?v:Math::fromDegrees(v);
    } else {
      THROW("JointData: can not get " + jointName + " min angle");
    }
  }//enf for
}//end init

string JointData::getJointName(JointID joint)
{
  switch (joint)
  {
    case HeadPitch: return string("HeadPitch");
    case HeadYaw: return string("HeadYaw");
    case RShoulderRoll: return string("RShoulderRoll");
    case LShoulderRoll: return string("LShoulderRoll");
    case RShoulderPitch: return string("RShoulderPitch");
    case LShoulderPitch: return string("LShoulderPitch");
    case RElbowRoll: return string("RElbowRoll");
    case LElbowRoll: return string("LElbowRoll");
    case RElbowYaw: return string("RElbowYaw");
    case LElbowYaw: return string("LElbowYaw");

    case LWristYaw: return string("LWristYaw");
    case RWristYaw: return string("RWristYaw");
    case LHand: return string("LHand");
    case RHand: return string("RHand");

    case LHipYawPitch: return string("LHipYawPitch");
    case RHipYawPitch: return string("RHipYawPitch");
    case RHipPitch: return string("RHipPitch");
    case LHipPitch: return string("LHipPitch");
    case RHipRoll: return string("RHipRoll");
    case LHipRoll: return string("LHipRoll");
    case RKneePitch: return string("RKneePitch");
    case LKneePitch: return string("LKneePitch");
    case RAnklePitch: return string("RAnklePitch");
    case LAnklePitch: return string("LAnklePitch");
    case RAnkleRoll: return string("RAnkleRoll");
    case LAnkleRoll: return string("LAnkleRoll");
    default: return string("Unknown Joint");
  }//end switch
}//end getJointName

double JointData::mirrorData(JointID joint) const
{
  switch (joint)
  {
      // Head (don't mirror)
    case HeadYaw: return -position[HeadYaw];
    case HeadPitch: return position[HeadPitch];

      // Arms
    case RShoulderPitch: return position[LShoulderPitch];
    case RShoulderRoll: return -position[LShoulderRoll];
    case RElbowYaw: return -position[LElbowYaw];
    case RElbowRoll: return -position[LElbowRoll];

    case LShoulderPitch: return position[RShoulderPitch];
    case LShoulderRoll: return -position[RShoulderRoll];
    case LElbowYaw: return -position[RElbowYaw];
    case LElbowRoll: return -position[RElbowRoll];

      // Legs
    case RHipYawPitch: return position[LHipYawPitch];
    case RHipPitch: return position[LHipPitch];
    case RHipRoll: return -position[LHipRoll];
    case RKneePitch: return position[LKneePitch];
    case RAnklePitch: return position[LAnklePitch];
    case RAnkleRoll: return -position[LAnkleRoll];

    case LHipYawPitch: return position[RHipYawPitch];
    case LHipPitch: return position[RHipPitch];
    case LHipRoll: return -position[RHipRoll];
    case LKneePitch: return position[RKneePitch];
    case LAnklePitch: return position[RAnklePitch];
    case LAnkleRoll: return -position[RAnkleRoll];
    default: return position[joint];
  }
}//end mirrorData

JointData::JointID JointData::jointIDFromName(std::string name)
{
  for (int i = 0; i < numOfJoint; i++) {
    if (name == getJointName((JointID) i)) return (JointID) i;
  }

  return numOfJoint;
}//end getJointName

void JointData::mirrorFrom(const JointData& jointData)
{
  for (int i = 0; i < numOfJoint; i++) {
    position[i] = jointData.mirrorData((JointID) i);
  }
}//end mirror

void JointData::mirror()
{
  JointData tmp = *this;
  mirrorFrom(tmp);
}

void JointData::clamp(JointID id)
{
  position[id] = Math::clamp(position[id], min[id], max[id]);
}

void JointData::clamp()
{
  for( int i=0; i<numOfJoint; i++) {
    clamp((JointID)i);
  }
}

bool JointData::isInRange(JointData::JointID id, double ang) const
{
    return ang <= max[id] && ang >= min[id];
}

bool JointData::isInRange(JointData::JointID id) const
{
    return isInRange(id, position[id]);
}

void JointData::updateSpeed(const JointData& lastData, double dt)
{
  const double* lastPose = lastData.position;
  double idt = 1 / dt;
  for ( int i=0; i<JointData::numOfJoint; i++)
  {
    dp[i] = (position[i] - lastPose[i]) * idt;
  }
}

void JointData::updateAcceleration(const JointData& lastData, double dt)
{
  const double* lastSpeed = lastData.dp;
  double idt = 1 / dt;
  for (int i = 0; i < JointData::numOfJoint; i++)
  {
    ddp[i] = (dp[i] - lastSpeed[i]) * idt;
  }
}

bool JointData::isLegStiffnessOn() const
{
  for ( int i = JointData::RHipYawPitch; i <= JointData::LAnkleRoll; i++)
  {
    if ( stiffness[i] < 0 ) {
      return false;
    }
  }
  return true;
}

int JointData::checkStiffness() const
{
  for(int i=0; i<JointData::numOfJoint; i++)
  {
    double v = stiffness[i];
    if ( v > 1 || v < -1 )
    {
      return i;
      //THROW("Get ILLEGAL Stiffness: "<<getJointName(JointData::JointID(i))<<" = "<<v);
    }
  }
  return -1;
}

SensorJointData::SensorJointData()
  : timestamp(0)
{
  for (int i = 0; i < numOfJoint; i++)
  {
    electricCurrent[i] = 0.0;
    temperature[i] = 0.0;
  }
}

void SensorJointData::print(ostream& stream) const
{
  stream << "Timestamp: " << timestamp << endl;
  stream << "Joint [pos(deg), stiffness, temperature,current]" << endl;
  stream << "------------------------" << endl;
  for (int i = 0; i < numOfJoint; i++)
  {
    stream.precision(4);
    stream << getJointName((JointData::JointID) i) << "\t[" << fixed << Math::toDegrees(position[i]) << ", " << stiffness[i] << ", ";
    stream.precision(0);
    stream << temperature[i] << ", ";
    stream.precision(3);
    stream << electricCurrent[i] << "]" <<  endl;
  }
}//end print

SensorJointData::~SensorJointData()
{
}

MotorJointData::MotorJointData()
{
}

MotorJointData::~MotorJointData()
{
}

void MotorJointData::print(ostream& stream) const
{
  stream << "Joint [pos, stiffness]" << endl;
  stream << "------------------------" << endl;
  for (int i = 0; i < numOfJoint; i++) {
    stream << getJointName((JointData::JointID) i) << "[" << position[i] << ", " << stiffness[i] << "]" << endl;
  }
}//end print

void Serializer<SensorJointData>::serialize(const SensorJointData& representation, std::ostream& stream)
{
  naothmessages::SensorJointData message;

  for(int i=0; i < JointData::numOfJoint; i++)
  {
    message.add_electriccurrent(representation.electricCurrent[i]);
    message.add_temperature(representation.temperature[i]);

    message.mutable_jointdata()->add_position(representation.position[i]);
    message.mutable_jointdata()->add_stiffness(representation.stiffness[i]);
    message.mutable_jointdata()->add_dp(representation.dp[i]);
    message.mutable_jointdata()->add_ddp(representation.ddp[i]);
  }

  google::protobuf::io::OstreamOutputStream buf(&stream);
  message.SerializeToZeroCopyStream(&buf);
}

void Serializer<SensorJointData>::deserialize(std::istream& stream, SensorJointData& representation)
{
  naothmessages::SensorJointData message;
  google::protobuf::io::IstreamInputStream buf(&stream);
  message.ParseFromZeroCopyStream(&buf);

  // assure the integrity of the message
  ASSERT( message.electriccurrent().size() == JointData::numOfJoint ||
          message.electriccurrent().size() == JointData::numOfJoint - 4);
  ASSERT( message.temperature().size() == JointData::numOfJoint ||
          message.temperature().size() == JointData::numOfJoint - 4);
  ASSERT( message.jointdata().position().size() == JointData::numOfJoint ||
          message.jointdata().position().size() == JointData::numOfJoint - 4);
  ASSERT( message.jointdata().stiffness().size() == JointData::numOfJoint ||
          message.jointdata().stiffness().size() == JointData::numOfJoint - 4);
  ASSERT( message.jointdata().dp().size() == JointData::numOfJoint ||
          message.jointdata().dp().size() == JointData::numOfJoint - 4);
  ASSERT( message.jointdata().ddp().size() == JointData::numOfJoint ||
          message.jointdata().ddp().size() == JointData::numOfJoint - 4);

  for (int i = 0; i < JointData::numOfJoint; i++)
  {
    if(i < message.jointdata().position().size())
    {
      representation.electricCurrent[i] = message.electriccurrent(i);
      representation.temperature[i] = message.temperature(i);
      // joint data
      representation.position[i] = message.jointdata().position(i);
      representation.stiffness[i] = message.jointdata().stiffness(i);
      representation.dp[i] = message.jointdata().dp(i);
      representation.ddp[i] = message.jointdata().ddp(i);
    }
    else // LWristYaw, RWristYaw, LHand, RHand don't exist in old messages
    {
      representation.electricCurrent[i] = 0;
      representation.temperature[i] = 0;
      // joint data
      representation.position[i] = 0;
      representation.stiffness[i] = 0;
      representation.dp[i] = 0;
      representation.ddp[i] = 0;
    }
  }
}

void Serializer<MotorJointData>::serialize(const MotorJointData& representation, std::ostream& stream)
{
  naothmessages::JointData message;

  for(int i=0; i < JointData::numOfJoint; i++)
  {
    message.add_position(representation.position[i]);
    message.add_stiffness(representation.stiffness[i]);
    message.add_dp(representation.dp[i]);
    message.add_ddp(representation.ddp[i]);
  }

  google::protobuf::io::OstreamOutputStream buf(&stream);
  message.SerializeToZeroCopyStream(&buf);
}

void Serializer<MotorJointData>::deserialize(std::istream& stream, MotorJointData& representation)
{
  naothmessages::JointData message;
  google::protobuf::io::IstreamInputStream buf(&stream);
  message.ParseFromZeroCopyStream(&buf);

  // assure the integrity of the message
  ASSERT(message.position().size() == JointData::numOfJoint);
  ASSERT(message.stiffness().size() == JointData::numOfJoint);
  ASSERT(message.dp().size() == JointData::numOfJoint);
  ASSERT(message.ddp().size() == JointData::numOfJoint);

  for(int i=0; i < JointData::numOfJoint; i++)
  {
    representation.position[i] = message.position(i);
    representation.stiffness[i] = message.stiffness(i);
    representation.dp[i] = message.dp(i);
    representation.ddp[i] = message.ddp(i);
  }
}

<|endoftext|>


<commit_before>/**************************************************************************/ /**
* @brief Message decode example.
* @file
******************************************************************************/

#include <cstdint>
#include <cstdio>
#include <fstream>

#include <point_one/fusion_engine/messages/core.h>
#include <point_one/fusion_engine/messages/crc.h>

using namespace point_one::fusion_engine::messages;

/******************************************************************************/
bool DecodeMessage(std::ifstream& stream, size_t available_bytes) {
  static uint32_t expected_sequence_number = 0;

  // Enforce a 4-byte aligned address.
  alignas(4) uint8_t storage[4096];
  char* buffer = reinterpret_cast<char*>(storage);

  // Read the message header.
  if (available_bytes < sizeof(MessageHeader)) {
    printf("Not enough data: cannot read header. [%zu bytes < %zu bytes]\n",
           available_bytes, sizeof(MessageHeader));
    return false;
  }

  stream.read(buffer, sizeof(MessageHeader));
  if (!stream) {
    printf("Unexpected error reading header.\n");
    return false;
  }

  available_bytes -= sizeof(MessageHeader);

  auto& header = *reinterpret_cast<MessageHeader*>(buffer);
  buffer += sizeof(MessageHeader);

  // Read the message payload.
  if (available_bytes < header.payload_size_bytes) {
    printf("Not enough data: cannot read payload. [%zu bytes < %u bytes]\n",
           available_bytes, header.payload_size_bytes);
    return false;
  }

  stream.read(buffer, header.payload_size_bytes);
  if (!stream) {
    printf("Unexpected error reading payload.\n");
    return false;
  }

  // Verify the message checksum.
  size_t message_size = sizeof(MessageHeader) + header.payload_size_bytes;
  if (!IsValid(storage)) {
    printf(
        "CRC failure. [type=%s (%u), size=%zu bytes (payload size=%u bytes], "
        "sequence=%u, expected_crc=0x%08x, calculated_crc=0x%08x]\n",
        to_string(header.message_type),
        static_cast<unsigned>(header.message_type), message_size,
        header.payload_size_bytes, header.sequence_number, header.crc,
        CalculateCRC(storage));
    return false;
  }

  // Check that the sequence number increments as expected.
  if (header.sequence_number != expected_sequence_number) {
    printf(
        "Warning: unexpected sequence number. [type=%s (%u), size=%zu bytes "
        "(payload size=%u bytes], crc=0x%08x, expected_sequence=%u, "
        "received_sequence=%u]\n",
        to_string(header.message_type),
        static_cast<unsigned>(header.message_type), message_size,
        header.payload_size_bytes, header.crc, expected_sequence_number,
        header.sequence_number);
  }

  expected_sequence_number = header.sequence_number + 1;

  // Interpret the payload.
  if (header.message_type == MessageType::POSE) {
    auto& contents = *reinterpret_cast<PoseMessage*>(buffer);
    buffer += sizeof(contents);

    double p1_time_sec =
        contents.p1_time.seconds + (contents.p1_time.fraction_ns * 1e-9);

    printf("Received pose message @ P1 time %.3f seconds. [sequence=%u, "
           "size=%zu B]\n",
           p1_time_sec, header.sequence_number, message_size);
    printf("  Position (LLA): %.6f, %.6f, %.3f (deg, deg, m)\n",
           contents.lla_deg[0], contents.lla_deg[1], contents.lla_deg[2]);
    printf("  Attitude (YPR): %.2f, %.2f, %.2f (deg, deg, deg)\n",
           contents.ypr_deg[0], contents.ypr_deg[1], contents.ypr_deg[2]);
    printf("  Velocity (Body): %.2f, %.2f, %.2f (m/s, m/s, m/s)\n",
           contents.velocity_body_mps[0], contents.velocity_body_mps[1],
           contents.velocity_body_mps[2]);
    printf("  Position Std Dev (ENU): %.2f, %.2f, %.2f (m, m, m)\n",
           contents.position_std_enu_m[0], contents.position_std_enu_m[1],
           contents.position_std_enu_m[2]);
    printf("  Attitude Std Dev (YPR): %.2f, %.2f, %.2f (deg, deg, deg)\n",
           contents.ypr_std_deg[0], contents.ypr_std_deg[1],
           contents.ypr_std_deg[2]);
    printf("  Velocity Std Dev (Body): %.2f, %.2f, %.2f (m/s, m/s, m/s)\n",
           contents.velocity_std_body_mps[0], contents.velocity_std_body_mps[1],
           contents.velocity_std_body_mps[2]);
    printf("  Protection Levels:\n");
    printf("    Aggregate: %.2f m\n", contents.aggregate_protection_level_m);
    printf("    Horizontal: %.2f m\n", contents.horizontal_protection_level_m);
    printf("    Vertical: %.2f m\n", contents.vertical_protection_level_m);
  } else if (header.message_type == MessageType::GNSS_INFO) {
    auto& contents = *reinterpret_cast<GNSSInfoMessage*>(buffer);
    buffer += sizeof(contents);

    double p1_time_sec =
        contents.p1_time.seconds + (contents.p1_time.fraction_ns * 1e-9);
    double gps_time_sec =
        contents.gps_time.seconds + (contents.gps_time.fraction_ns * 1e-9);
    double last_diff_time_sec =
        contents.last_differential_time.seconds +
        (contents.last_differential_time.fraction_ns * 1e-9);

    printf(
        "Received GNSS info message @ P1 time %.3f seconds. [sequence=%u, "
        "size=%zu B]\n",
        p1_time_sec, header.sequence_number, message_size);
    printf("  GPS time: %.3f\n", gps_time_sec);
    printf("  GPS time std dev: %.2e sec\n", contents.gps_time_std_sec);
    printf("  Reference station: %s\n",
           contents.reference_station_id ==
                   GNSSInfoMessage::INVALID_REFERENCE_STATION
               ? "none"
               : std::to_string(contents.reference_station_id).c_str());
    printf("  Last differential time: %.3f\n", last_diff_time_sec);
    printf("  GDOP: %.1f  PDOP: %.1f\n", contents.gdop, contents.pdop);
    printf("  HDOP: %.1f  VDOP: %.1f\n", contents.hdop, contents.vdop);
  } else if (header.message_type == MessageType::GNSS_SATELLITE) {
    auto& contents = *reinterpret_cast<GNSSSatelliteMessage*>(buffer);
    buffer += sizeof(contents);

    double p1_time_sec =
        contents.p1_time.seconds + (contents.p1_time.fraction_ns * 1e-9);

    printf(
        "Received GNSS satellite message @ P1 time %.3f seconds. [sequence=%u, "
        "size=%zu B, %u svs]\n",
        p1_time_sec, header.sequence_number, message_size,
        contents.num_satellites);

    for (unsigned i = 0; i < contents.num_satellites; ++i) {
      auto& sv = *reinterpret_cast<SatelliteInfo*>(buffer);
      buffer += sizeof(sv);

      printf("  %s PRN %u:\n", to_string(sv.system), sv.prn);
      printf("    Elevation/azimuth: (%.1f, %.1f) deg\n", sv.elevation_deg,
             sv.azimuth_deg);
      printf("    In solution: %s\n", sv.usage > 0 ? "yes" : "no");
    }
  } else {
    printf("Ignoring message type %s. [%u bytes]\n",
           to_string(header.message_type), header.payload_size_bytes);
  }

  return true;
}

/******************************************************************************/
int main(int argc, const char* argv[]) {
  if (argc != 2) {
    printf("Usage: %s FILE\n", argv[0]);
    printf(R"EOF(
Decode platform pose messages from a binary file containing FusionEngine data.
)EOF");
    return 0;
  }

  // Open the file.
  std::ifstream stream(argv[1], std::ifstream::binary);
  if (!stream) {
    printf("Error opening file '%s'.\n", argv[1]);
    return 1;
  }

  // Determine the file size.
  stream.seekg(0, stream.end);
  std::streampos file_size_bytes = stream.tellg();
  stream.seekg(0, stream.beg);

  // Decode all messages in the file.
  int return_code = 0;
  while (stream.tellg() != file_size_bytes) {
    if (!DecodeMessage(stream,
                       static_cast<size_t>(file_size_bytes - stream.tellg()))) {
      return_code = 1;
      break;
    }
  }

  // Close the file.
  stream.close();

  return return_code;
}
<commit_msg>Added GPS time to message decode example app.<commit_after>/**************************************************************************/ /**
* @brief Message decode example.
* @file
******************************************************************************/

#include <cstdint>
#include <cstdio>
#include <fstream>

#include <point_one/fusion_engine/messages/core.h>
#include <point_one/fusion_engine/messages/crc.h>

using namespace point_one::fusion_engine::messages;

/******************************************************************************/
bool DecodeMessage(std::ifstream& stream, size_t available_bytes) {
  static uint32_t expected_sequence_number = 0;

  // Enforce a 4-byte aligned address.
  alignas(4) uint8_t storage[4096];
  char* buffer = reinterpret_cast<char*>(storage);

  // Read the message header.
  if (available_bytes < sizeof(MessageHeader)) {
    printf("Not enough data: cannot read header. [%zu bytes < %zu bytes]\n",
           available_bytes, sizeof(MessageHeader));
    return false;
  }

  stream.read(buffer, sizeof(MessageHeader));
  if (!stream) {
    printf("Unexpected error reading header.\n");
    return false;
  }

  available_bytes -= sizeof(MessageHeader);

  auto& header = *reinterpret_cast<MessageHeader*>(buffer);
  buffer += sizeof(MessageHeader);

  // Read the message payload.
  if (available_bytes < header.payload_size_bytes) {
    printf("Not enough data: cannot read payload. [%zu bytes < %u bytes]\n",
           available_bytes, header.payload_size_bytes);
    return false;
  }

  stream.read(buffer, header.payload_size_bytes);
  if (!stream) {
    printf("Unexpected error reading payload.\n");
    return false;
  }

  // Verify the message checksum.
  size_t message_size = sizeof(MessageHeader) + header.payload_size_bytes;
  if (!IsValid(storage)) {
    printf(
        "CRC failure. [type=%s (%u), size=%zu bytes (payload size=%u bytes], "
        "sequence=%u, expected_crc=0x%08x, calculated_crc=0x%08x]\n",
        to_string(header.message_type),
        static_cast<unsigned>(header.message_type), message_size,
        header.payload_size_bytes, header.sequence_number, header.crc,
        CalculateCRC(storage));
    return false;
  }

  // Check that the sequence number increments as expected.
  if (header.sequence_number != expected_sequence_number) {
    printf(
        "Warning: unexpected sequence number. [type=%s (%u), size=%zu bytes "
        "(payload size=%u bytes], crc=0x%08x, expected_sequence=%u, "
        "received_sequence=%u]\n",
        to_string(header.message_type),
        static_cast<unsigned>(header.message_type), message_size,
        header.payload_size_bytes, header.crc, expected_sequence_number,
        header.sequence_number);
  }

  expected_sequence_number = header.sequence_number + 1;

  // Interpret the payload.
  if (header.message_type == MessageType::POSE) {
    auto& contents = *reinterpret_cast<PoseMessage*>(buffer);
    buffer += sizeof(contents);

    double p1_time_sec =
        contents.p1_time.seconds + (contents.p1_time.fraction_ns * 1e-9);

    static constexpr double SEC_PER_WEEK = 7 * 24 * 3600.0;
    double gps_time_sec =
        contents.gps_time.seconds + (contents.gps_time.fraction_ns * 1e-9);
    int gps_week = std::lround(gps_time_sec / SEC_PER_WEEK);
    double gps_tow_sec = gps_time_sec - (gps_week * SEC_PER_WEEK);

    printf("Received pose message @ P1 time %.3f seconds. [sequence=%u, "
           "size=%zu B]\n",
           p1_time_sec, header.sequence_number, message_size);
    printf("  Position (LLA): %.6f, %.6f, %.3f (deg, deg, m)\n",
           contents.lla_deg[0], contents.lla_deg[1], contents.lla_deg[2]);
    printf("  GPS Time: %d:%.3f (%.3f seconds)\n", gps_week, gps_tow_sec,
           gps_time_sec);
    printf("  Attitude (YPR): %.2f, %.2f, %.2f (deg, deg, deg)\n",
           contents.ypr_deg[0], contents.ypr_deg[1], contents.ypr_deg[2]);
    printf("  Velocity (Body): %.2f, %.2f, %.2f (m/s, m/s, m/s)\n",
           contents.velocity_body_mps[0], contents.velocity_body_mps[1],
           contents.velocity_body_mps[2]);
    printf("  Position Std Dev (ENU): %.2f, %.2f, %.2f (m, m, m)\n",
           contents.position_std_enu_m[0], contents.position_std_enu_m[1],
           contents.position_std_enu_m[2]);
    printf("  Attitude Std Dev (YPR): %.2f, %.2f, %.2f (deg, deg, deg)\n",
           contents.ypr_std_deg[0], contents.ypr_std_deg[1],
           contents.ypr_std_deg[2]);
    printf("  Velocity Std Dev (Body): %.2f, %.2f, %.2f (m/s, m/s, m/s)\n",
           contents.velocity_std_body_mps[0], contents.velocity_std_body_mps[1],
           contents.velocity_std_body_mps[2]);
    printf("  Protection Levels:\n");
    printf("    Aggregate: %.2f m\n", contents.aggregate_protection_level_m);
    printf("    Horizontal: %.2f m\n", contents.horizontal_protection_level_m);
    printf("    Vertical: %.2f m\n", contents.vertical_protection_level_m);
  } else if (header.message_type == MessageType::GNSS_INFO) {
    auto& contents = *reinterpret_cast<GNSSInfoMessage*>(buffer);
    buffer += sizeof(contents);

    double p1_time_sec =
        contents.p1_time.seconds + (contents.p1_time.fraction_ns * 1e-9);
    double gps_time_sec =
        contents.gps_time.seconds + (contents.gps_time.fraction_ns * 1e-9);
    double last_diff_time_sec =
        contents.last_differential_time.seconds +
        (contents.last_differential_time.fraction_ns * 1e-9);

    printf(
        "Received GNSS info message @ P1 time %.3f seconds. [sequence=%u, "
        "size=%zu B]\n",
        p1_time_sec, header.sequence_number, message_size);
    printf("  GPS time: %.3f\n", gps_time_sec);
    printf("  GPS time std dev: %.2e sec\n", contents.gps_time_std_sec);
    printf("  Reference station: %s\n",
           contents.reference_station_id ==
                   GNSSInfoMessage::INVALID_REFERENCE_STATION
               ? "none"
               : std::to_string(contents.reference_station_id).c_str());
    printf("  Last differential time: %.3f\n", last_diff_time_sec);
    printf("  GDOP: %.1f  PDOP: %.1f\n", contents.gdop, contents.pdop);
    printf("  HDOP: %.1f  VDOP: %.1f\n", contents.hdop, contents.vdop);
  } else if (header.message_type == MessageType::GNSS_SATELLITE) {
    auto& contents = *reinterpret_cast<GNSSSatelliteMessage*>(buffer);
    buffer += sizeof(contents);

    double p1_time_sec =
        contents.p1_time.seconds + (contents.p1_time.fraction_ns * 1e-9);

    printf(
        "Received GNSS satellite message @ P1 time %.3f seconds. [sequence=%u, "
        "size=%zu B, %u svs]\n",
        p1_time_sec, header.sequence_number, message_size,
        contents.num_satellites);

    for (unsigned i = 0; i < contents.num_satellites; ++i) {
      auto& sv = *reinterpret_cast<SatelliteInfo*>(buffer);
      buffer += sizeof(sv);

      printf("  %s PRN %u:\n", to_string(sv.system), sv.prn);
      printf("    Elevation/azimuth: (%.1f, %.1f) deg\n", sv.elevation_deg,
             sv.azimuth_deg);
      printf("    In solution: %s\n", sv.usage > 0 ? "yes" : "no");
    }
  } else {
    printf("Ignoring message type %s. [%u bytes]\n",
           to_string(header.message_type), header.payload_size_bytes);
  }

  return true;
}

/******************************************************************************/
int main(int argc, const char* argv[]) {
  if (argc != 2) {
    printf("Usage: %s FILE\n", argv[0]);
    printf(R"EOF(
Decode platform pose messages from a binary file containing FusionEngine data.
)EOF");
    return 0;
  }

  // Open the file.
  std::ifstream stream(argv[1], std::ifstream::binary);
  if (!stream) {
    printf("Error opening file '%s'.\n", argv[1]);
    return 1;
  }

  // Determine the file size.
  stream.seekg(0, stream.end);
  std::streampos file_size_bytes = stream.tellg();
  stream.seekg(0, stream.beg);

  // Decode all messages in the file.
  int return_code = 0;
  while (stream.tellg() != file_size_bytes) {
    if (!DecodeMessage(stream,
                       static_cast<size_t>(file_size_bytes - stream.tellg()))) {
      return_code = 1;
      break;
    }
  }

  // Close the file.
  stream.close();

  return return_code;
}
<|endoftext|>


<commit_before>
// ProxyPlayer.hpp
// This will invoke another process and waits for a return code.

#ifndef __PROXY_PLAYER_HPP__
#define __PROXY_PLAYER_HPP__

#include "Player.hpp"
#include <string>
#include <sstream>

#undef UNICODE
#define NOMINMAX
#include <Windows.h>

class ProxyPlayer : public Player
{
public:
	// Initialize with process (without .exe) and identifier of opponent.
	ProxyPlayer(std::string const &process, std::string const &script = "", size_t opponent = -1)
	    : Player(opponent), mProcess(process), mScript(script) {}

public:
	// Invoke other process.
	virtual Action fight()
	{
		unsigned choice = executeWithArguments(getArguments(3));
		switch (choice)
		{
		case 48: return load();
		case 49: return bullet();
		case 50: return plasma();
		case 45: return metal();
		case 61: return thermal();
		default: return (Action)(-1);
		}
	}

	// Notify external program of result.
	virtual void declared(Result result)
	{
		std::string arguments;
		switch (result)
		{
		case WIN:  arguments = getArguments(1);
		case LOSS: arguments = getArguments(2);
		default:   arguments = getArguments(0);
		}
		executeWithArguments(arguments);
	};

private:
	// External process name
	std::string mProcess;

	// External script name (for non binary submissions)
	std::string mScript;

	// Generates argument given game status.
	std::string getArguments(size_t status)
	{
		std::stringstream sst;
		sst << getOpponent()
			<< " " << getTurn()
			<< " " << status
			<< " " << getAmmo()
			<< " " << getAmmoOpponent();
		if (getTurn() > 0)
		{
			sst << " " << toActionString(getHistory())
				<< " " << toActionString(getHistoryOpponent());
		};
		return sst.str();
	}

	// Execute process with given arguments.
	unsigned executeWithArguments(std::string const &arguments) const
	{
		STARTUPINFO startup = { sizeof(startup) };
		PROCESS_INFORMATION process;
		LPSTR lpApplicationName;
		LPSTR lpCommandLine;

		lpApplicationName = const_cast<char *>(mProcess.c_str());
		if (mScript.length() == 0)
		{
			// Binary Proxy Player
			// name.exe arguments
			lpCommandLine = const_cast<char *>(arguments.c_str());
		}
		else
		{
			// Script Proxy Player
			// python.exe script.py arguments
			std::string actualArguments = mScript;
			actualArguments.append(1, ' ');
			actualArguments.append(arguments);
		}

		startup.cb = sizeof(startup);
		BOOL result = CreateProcess(lpApplicationName, lpCommandLine,
			NULL, NULL, TRUE, 0, NULL, NULL, &startup, &process);

		if (!result)
		{
			return -1;
		}
		else
		{
			// Wait for process to terminate and sanitize return code.
			DWORD exitCode;
			WaitForSingleObject(process.hProcess, INFINITE);
			GetExitCodeProcess(process.hProcess, &exitCode);
			return exitCode;
		}
	}
};

// Example: BINARY_PLAYER(CustomPlayer)
// Effects: Invoke CustomPlayer.exe <arguments>
#define BINARY_PLAYER(x)                                              \
	class x final : public ProxyPlayer                                \
	{                                                                 \
	public:                                                           \
		x(size_t opponent = -1) : ProxyPlayer(#x ".exe", opponent) {} \
	};

// Example: SCRIPT_PLAYER(CustomPlayer, "python", "CustomScriptPlayer.py")
// Effects: Invoke python CustomScriptPlayer.py <arguments>
#define SCRIPT_PLAYER(x, y, z)                                        \
	class x final : public ProxyPlayer                                \
	{                                                                 \
	public:                                                           \
		x(size_t opponent = -1) : ProxyPlayer(y, z, opponent) {}      \
	};

#endif // !__CUSTOM_PLAYER_HPP__
<commit_msg>Platform-agnostic implementation of ProxyPlayer (using system)<commit_after>
// ProxyPlayer.hpp
// This will invoke another process and waits for a return code.

#ifndef __PROXY_PLAYER_HPP__
#define __PROXY_PLAYER_HPP__

#include "Player.hpp"
#include <string>
#include <sstream>

#ifdef _WIN32
#undef UNICODE
#define NOMINMAX
#include <Windows.h>
#define EXE_SUFFIX ".exe"
#else
#include <cstdlib>
#define EXE_SUFFIX ""
#endif

class ProxyPlayer : public Player
{
public:
	// Initialize with process (without .exe) and identifier of opponent.
	ProxyPlayer(std::string const &process, std::string const &script = "", size_t opponent = -1)
	    : Player(opponent), mProcess(process), mScript(script) {}

public:
	// Invoke other process.
	virtual Action fight()
	{
		unsigned choice = executeWithArguments(getArguments(3));
		switch (choice)
		{
		case 48: return load();
		case 49: return bullet();
		case 50: return plasma();
		case 45: return metal();
		case 61: return thermal();
		default: return (Action)(-1);
		}
	}

	// Notify external program of result.
	virtual void declared(Result result)
	{
		std::string arguments;
		switch (result)
		{
		case WIN:  arguments = getArguments(1);
		case LOSS: arguments = getArguments(2);
		default:   arguments = getArguments(0);
		}
		executeWithArguments(arguments);
	};

private:
	// External process name
	std::string mProcess;

	// External script name (for non binary submissions)
	std::string mScript;

	// Generates argument given game status.
	std::string getArguments(size_t status)
	{
		std::stringstream sst;
		sst << getOpponent()
			<< " " << getTurn()
			<< " " << status
			<< " " << getAmmo()
			<< " " << getAmmoOpponent();
		if (getTurn() > 0)
		{
			sst << " " << toActionString(getHistory())
				<< " " << toActionString(getHistoryOpponent());
		};
		return sst.str();
	}

	// Execute process with given arguments.
	unsigned executeWithArguments(std::string const &arguments) const
	{
#ifdef _WIN32
		STARTUPINFO startup = { sizeof(startup) };
		PROCESS_INFORMATION process;
		LPSTR lpApplicationName;
		LPSTR lpCommandLine;

		lpApplicationName = const_cast<char *>(mProcess.c_str());
		if (mScript.length() == 0)
		{
			// Binary Proxy Player
			// name.exe arguments
			lpCommandLine = const_cast<char *>(arguments.c_str());
		}
		else
		{
			// Script Proxy Player
			// python.exe script.py arguments
			std::string actualArguments = mScript;
			actualArguments.append(1, ' ');
			actualArguments.append(arguments);
		}

		startup.cb = sizeof(startup);
		BOOL result = CreateProcess(lpApplicationName, lpCommandLine,
			NULL, NULL, TRUE, 0, NULL, NULL, &startup, &process);

		if (!result)
		{
			return -1;
		}
		else
		{
			// Wait for process to terminate and sanitize return code.
			DWORD exitCode;
			WaitForSingleObject(process.hProcess, INFINITE);
			GetExitCodeProcess(process.hProcess, &exitCode);
			return exitCode;
		}
#else
		return std::system((mProcess + " " + mScript + " " + arguments).c_str());
#endif
	}
};

// Example: BINARY_PLAYER(CustomPlayer)
// Effects: Invoke CustomPlayer.exe <arguments>
#define BINARY_PLAYER(x)                                              \
	class x final : public ProxyPlayer                                \
	{                                                                 \
	public:                                                           \
	    x(size_t opponent = -1) : ProxyPlayer(#x EXE_SUFFIX, opponent) {} \
	};

// Example: SCRIPT_PLAYER(CustomPlayer, "python", "CustomScriptPlayer.py")
// Effects: Invoke python CustomScriptPlayer.py <arguments>
#define SCRIPT_PLAYER(x, y, z)                                        \
	class x final : public ProxyPlayer                                \
	{                                                                 \
	public:                                                           \
		x(size_t opponent = -1) : ProxyPlayer(y, z, opponent) {}      \
	};

#endif // !__CUSTOM_PLAYER_HPP__
<|endoftext|>


<commit_before>#include "tables.h"

///////////////INITIALIZIING////////////////
////////////////////////////////////////////
namespace editor
{
    int WIN_HEIGHT, WIN_WIDTH;
    WINDOW *ptrnwin;
    WINDOW *instwin;
    WINDOW *metawin;
    WINDOW *volwin;
    WINDOW *wavewin;
    WINDOW *dialog;

    WINDOW *wingroup;
    WINDOW *inputwin;
    WINDOW *lastwin;

    bool running;

    int numBuffer;
    char charBuffer[CHARBUFFER_SIZE];
    char charInputBuffer[CMDBAR_SIZE];

    char charInputHistory[HISTORY_SIZE][CMDBAR_SIZE];
    char history_head;
    char history_size;

    char lastSongPath[LASTSONG_SIZE];
    char textCursorPos;
    bool *muted_tracks;
    float playamp;

    Song *song;
    int daemonpid;
    Song *playback;
    unsigned char playback_length;
    unsigned char playback_mark;
    Instrument *selinst;
}

//Pattern Editor
namespace patternedtr
{
    std::map<int,unsigned int> notemap;
    Pattern *selptrn;
    unsigned char viewporttrack;
    unsigned char viewportrow;

    unsigned char maxtracksviewport;
    unsigned char maxrowsviewport;

    unsigned char selrow;
    unsigned char seltrack;
    unsigned char seltrackseg;
    unsigned char selorder;

    unsigned char selinstrument;
    unsigned char edit_step;
    unsigned char row_underline;
    unsigned char octave;
    unsigned char key;
    unsigned int entryclipboard;

    //METADATA (Main controls)
    unsigned char metaobjindex;
    bool metaobjedit;

    unsigned char selobjmeta;//x
    unsigned char selrowmeta;//y

}

//Instrument Editor
namespace instedtr
{
    unsigned short waveclipboard;
    unsigned short volclipboard;

    bool instobjedit;
    unsigned char selinstrow;
    unsigned char selinstobj;
    unsigned short selwavrow;
    unsigned char selwavseg;
    unsigned short viewportwave;
    unsigned char viewportvol;

    unsigned char selvolrow;
    unsigned char selvolseg;
}
/////////////DONE INITIALIZING/////////////
///////////////////////////////////////////

<commit_msg>Updated<commit_after>#include "tables.h"

/*This information was previously in main but was moved out to make test programs
 */

///////////////INITIALIZIING////////////////
////////////////////////////////////////////
namespace editor
{
    int WIN_HEIGHT, WIN_WIDTH;
    WINDOW *ptrnwin;
    WINDOW *instwin;
    WINDOW *metawin;
    WINDOW *volwin;
    WINDOW *wavewin;
    WINDOW *dialog;

    WINDOW *wingroup;
    WINDOW *inputwin;
    WINDOW *lastwin;

    bool running;

    int numBuffer;
    char charBuffer[CHARBUFFER_SIZE];
    char charInputBuffer[CMDBAR_SIZE];

    char charInputHistory[HISTORY_SIZE][CMDBAR_SIZE];
    char history_head;
    char history_size;

    char lastSongPath[LASTSONG_SIZE];
    char textCursorPos;
    bool *muted_tracks;
    float playamp;

    Song *song;
    int daemonpid;
    Song *playback;
    unsigned char playback_length;
    unsigned char playback_mark;
    Instrument *selinst;
}

//Pattern Editor
namespace patternedtr
{
    std::map<int,unsigned int> notemap;
    Pattern *selptrn;
    unsigned char viewporttrack;
    unsigned char viewportrow;

    unsigned char maxtracksviewport;
    unsigned char maxrowsviewport;

    unsigned char selrow;
    unsigned char seltrack;
    unsigned char seltrackseg;
    unsigned char selorder;

    unsigned char selinstrument;
    unsigned char edit_step;
    unsigned char row_underline;
    unsigned char octave;
    unsigned char key;
    unsigned int entryclipboard;

    //METADATA (Main controls)
    unsigned char metaobjindex;
    bool metaobjedit;

    unsigned char selobjmeta;//x
    unsigned char selrowmeta;//y

}

//Instrument Editor
namespace instedtr
{
    unsigned short waveclipboard;
    unsigned short volclipboard;

    bool instobjedit;
    unsigned char selinstrow;
    unsigned char selinstobj;
    unsigned short selwavrow;
    unsigned char selwavseg;
    unsigned short viewportwave;
    unsigned char viewportvol;

    unsigned char selvolrow;
    unsigned char selvolseg;
}
/////////////DONE INITIALIZING/////////////
///////////////////////////////////////////

<|endoftext|>


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

#ifndef CONNECTIVITY_TKEY_HXX
#define CONNECTIVITY_TKEY_HXX

#ifndef _CONNECTIVITY_SDBCX_KEY_HXX_
#include <connectivity/sdbcx/VKey.hxx>
#endif
#ifndef _COM_SUN_STAR_SDBC_XDATABASEMETADATA_HPP_
#include <com/sun/star/sdbc/XDatabaseMetaData.hpp>
#endif

namespace connectivity
{
    class OTableHelper;
    class OTableKeyHelper : public connectivity::sdbcx::OKey
    {
        OTableHelper*   m_pTable;
    public:
        virtual void refreshColumns();
    public:
        OTableKeyHelper(    OTableHelper* _pTable);
        OTableKeyHelper(    OTableHelper* _pTable,
                const ::rtl::OUString& _Name,
                const ::rtl::OUString& _ReferencedTable,
                sal_Int32       _Type,
                sal_Int32       _UpdateRule,
                sal_Int32       _DeleteRule
            );
        inline OTableHelper* getTable() const { return m_pTable; }
    };
}
#endif // CONNECTIVITY_TKEY_HXX

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

#ifndef CONNECTIVITY_TKEY_HXX
#define CONNECTIVITY_TKEY_HXX

#include <connectivity/sdbcx/VKey.hxx>
#include <com/sun/star/sdbc/XDatabaseMetaData.hpp>

namespace connectivity
{
    class OTableHelper;
    class OTableKeyHelper : public connectivity::sdbcx::OKey
    {
        OTableHelper*   m_pTable;
    public:
        virtual void refreshColumns();
    public:
        OTableKeyHelper(    OTableHelper* _pTable);
        OTableKeyHelper(    OTableHelper* _pTable,
                const ::rtl::OUString& _Name,
                const ::rtl::OUString& _ReferencedTable,
                sal_Int32       _Type,
                sal_Int32       _UpdateRule,
                sal_Int32       _DeleteRule
            );
        inline OTableHelper* getTable() const { return m_pTable; }
    };
}
#endif // CONNECTIVITY_TKEY_HXX

<|endoftext|>


<commit_before>/*
 * Copyright (c) 2014 Samsung Electronics Co., Ltd.
 *
 * 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 <dali/public-api/dali-core.h>

#include <application.h>
#include <adaptor.h>
#include <render-surface.h>
#include <orientation.h>
#include <timer.h>

using namespace Dali;

/*****************************************************************************
 * Test to see if the dali-adaptor is linking correctly.
 */

class LinkerApp : public ConnectionTracker
{
public:
  LinkerApp(Application &app)
  {
    app.InitSignal().Connect(this, &LinkerApp::Create);
  }

public:

  void Create(Application& app)
  {
  }
};

/*****************************************************************************/

int
main(int argc, char **argv)
{
  Application app = Application::New(&argc, &argv);
  LinkerApp linkerApp (app);
  app.MainLoop();

  return 0;
}
<commit_msg>Fix prevent issue - uncaught exception<commit_after>/*
 * Copyright (c) 2014 Samsung Electronics Co., Ltd.
 *
 * 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 <dali/public-api/dali-core.h>

#include <application.h>
#include <adaptor.h>
#include <render-surface.h>
#include <orientation.h>
#include <timer.h>
#include <iostream>

using namespace Dali;

/*****************************************************************************
 * Test to see if the dali-adaptor is linking correctly.
 */

class LinkerApp : public ConnectionTracker
{
public:
  LinkerApp(Application &app)
  {
    app.InitSignal().Connect(this, &LinkerApp::Create);
  }

public:

  void Create(Application& app)
  {
  }
};

/*****************************************************************************/

int
main(int argc, char **argv)
{
  Application app = Application::New(&argc, &argv);

  try
  {
    LinkerApp linkerApp (app);
    app.MainLoop();
  }
  catch(...)
  {
    std::cout << "Exception caught";
  }

  return 0;
}
<|endoftext|>


<commit_before><commit_msg>removed unused member variable<commit_after><|endoftext|>


<commit_before><commit_msg>coverity#708338 Uninitialized scalar field<commit_after><|endoftext|>


<commit_before>/*
Copyright (C) 2007 <SWGEmu>

This File is part of Core3.

This program is free software; you can redistribute
it and/or modify it under the terms of the GNU Lesser
General Public License as published by the Free Software
Foundation; either version 2 of the License,
or (at your option) any later version.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
See the GNU Lesser General Public License for
more details.

You should have received a copy of the GNU Lesser General
Public License along with this program; if not, write to
the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA

Linking Engine3 statically or dynamically with other modules
is making a combined work based on Engine3.
Thus, the terms and conditions of the GNU Lesser General Public License
cover the whole combination.

In addition, as a special exception, the copyright holders of Engine3
give you permission to combine Engine3 program with free software
programs or libraries that are released under the GNU LGPL and with
code included in the standard release of Core3 under the GNU LGPL
license (or modified versions of such code, with unchanged license).
You may copy and distribute such a system following the terms of the
GNU LGPL for Engine3 and the licenses of the other code concerned,
provided that you include the source code of that other code when
and as the GNU LGPL requires distribution of source code.

Note that people who make modified versions of Engine3 are not obligated
to grant this special exception for their modified versions;
it is their choice whether to do so. The GNU Lesser General Public License
gives permission to release a modified version without this exception;
this exception also makes it possible to release a modified version
which carries forward this exception.
*/

#include "ServerCore.h"

#include "db/ServerDatabase.h"

#include "db/MantisDatabase.h"

#include "chat/ChatManager.h"

#include "login/LoginServer.h"

#include "features/Features.h"

#include "ping/PingServer.h"

#include "status/StatusServer.h"

#include "web/WebServer.h"

#include "zone/ZoneServer.h"

#include "zone/managers/object/ObjectManager.h"
#include "zone/managers/templates/TemplateManager.h"

#include "zone/objects/creature/CreatureObject.h"

ManagedReference<ZoneServer*> ServerCore::zoneServerRef = NULL;
SortedVector<String> ServerCore::arguments;
bool ServerCore::truncateAllData = false;

ServerCore::ServerCore(bool truncateDatabases, SortedVector<String>& args) : Core("log/core3.log"), Logger("Core") {
	orb = NULL;

	loginServer = NULL;
	zoneServerRef = NULL;
	statusServer = NULL;
	pingServer = NULL;
	webServer = NULL;
	database = NULL;

	truncateAllData = truncateDatabases;
	arguments = args;

	configManager = ConfigManager::instance();

	features = NULL;
}

class ZoneStatisticsTask : public Task {
	ManagedReference<ZoneServer*> zoneServer;

public:
	ZoneStatisticsTask(ZoneServer* server) {
		zoneServer = server;
	}

	void run() {
		zoneServer->printInfo(true);
	}
};

void ServerCore::initialize() {
	info("starting up server..");

	processConfig();

	try {
		ObjectManager* objectManager = ObjectManager::instance();

		database = new ServerDatabase(configManager);

		mantisDatabase = new MantisDatabase(configManager);

		String& orbaddr = configManager->getORBNamingDirectoryAddress();
		orb = DistributedObjectBroker::initialize(orbaddr, 44496);

		orb->setCustomObjectManager(objectManager);

		if (configManager->getMakeLogin()) {
			loginServer = new LoginServer(configManager);
			loginServer->deploy("LoginServer");
		}

		if (configManager->getMakeZone()) {
			ZoneServer* zoneServer = new ZoneServer(configManager);
			zoneServer->deploy("ZoneServer");

			zoneServerRef = zoneServer;
		}

		if (configManager->getMakePing()) {
			pingServer = new PingServer();
		}

		if (configManager->getMakeStatus()) {
			statusServer = new StatusServer(configManager, zoneServerRef);
		}

		if (configManager->getMakeWeb()) {
			webServer = WebServer::instance();
		}

		ZoneServer* zoneServer = zoneServerRef.get();

		if (zoneServer != NULL) {
			int zonePort = 44463;
			int zoneAllowedConnections = configManager->getZoneAllowedConnections();

			ObjectDatabaseManager* dbManager = ObjectDatabaseManager::instance();
			dbManager->loadDatabases(truncateDatabases());

			int galaxyID = configManager->getZoneGalaxyID();

			String query = "SELECT port FROM galaxy WHERE galaxy_id = " + String::valueOf(galaxyID);
			Reference<ResultSet*> result = database->instance()->executeQuery(query);

			if (result != NULL && result->next()) {
				zonePort = result->getInt(0);
			}

			database->instance()->executeStatement("TRUNCATE TABLE sessions");

			database->instance()->executeStatement("DELETE FROM characters_dirty WHERE galaxy_id = " + String::valueOf(galaxyID));

			zoneServer->start(zonePort, zoneAllowedConnections);
		}

		if (statusServer != NULL) {
			int statusPort = configManager->getStatusPort();
			int statusAllowedConnections = configManager->getStatusAllowedConnections();

			statusServer->start(statusPort);
		}

		if (webServer != NULL) {
			webServer->start(configManager);
		}

		if (pingServer != NULL) {
			int pingPort = configManager->getPingPort();
			int pingAllowedConnections = configManager->getPingAllowedConnections();

			pingServer->start(pingPort, pingAllowedConnections);
		}

		if (loginServer != NULL) {
			int loginPort = configManager->getLoginPort();
			int loginAllowedConnections = configManager->getLoginAllowedConnections();

			loginServer->start(loginPort, loginAllowedConnections);
		}

	#ifndef WITH_STM
		ObjectManager::instance()->scheduleUpdateToDatabase();
	#else
		Task* statiscticsTask = new ZoneStatisticsTask(zoneServerRef);
		statiscticsTask->schedulePeriodic(10000, 10000);
	#endif

		info("initialized", true);
	} catch (ServiceException& e) {
		shutdown();
	} catch (DatabaseException& e) {
		info(e.getMessage());

		exit(1);
	}
}

void ServerCore::run() {
	handleCommands();

	shutdown();
}

void ServerCore::shutdown() {
	info("shutting down server..");

	ObjectManager::instance()->cancelUpdateModifiedObjectsTask();
	ObjectDatabaseManager::instance()->checkpoint();

	info("database checkpoint done", true);

	if (statusServer != NULL) {
		statusServer->stop();

		delete statusServer;
		statusServer = NULL;
	}

	if (webServer != NULL) {
		webServer->stop();

		delete webServer;
		webServer = NULL;
	}

	ZoneServer* zoneServer = zoneServerRef.get();

	if (zoneServer != NULL) {
		zoneServer->stop();
		//zoneServer->finalize();

		zoneServer = NULL;
	}

	if (loginServer != NULL) {
		loginServer->stop();

		loginServer = NULL;
	}

	if (pingServer != NULL) {
		pingServer->stop();

		delete pingServer;
		pingServer = NULL;
	}

	if (features != NULL) {
		delete features;
		features = NULL;
	}

	if (database != NULL) {
		delete database;
		database = NULL;
	}

	if (mantisDatabase != NULL) {
		delete mantisDatabase;
		mantisDatabase = NULL;
	}

	zoneServerRef = NULL;

	info("server closed");

	//exit(1);
}

void ServerCore::handleCommands() {
	while (true) {

#ifdef WITH_STM
		Reference<Transaction*> transaction = TransactionalMemoryManager::instance()->startTransaction();
#endif

		try {
			String fullCommand;

			Thread::sleep(500);

			System::out << "> ";

			char line[256];
			fgets(line, sizeof(line), stdin);

			fullCommand = line;
			fullCommand = fullCommand.replaceFirst("\n", "");

			StringTokenizer tokenizer(fullCommand);

			String command, arguments;

			if (tokenizer.hasMoreTokens())
				tokenizer.getStringToken(command);

			if (tokenizer.hasMoreTokens())
				tokenizer.finalToken(arguments);

			ZoneServer* zoneServer = zoneServerRef.getForUpdate();

			if (command == "exit") {
				if (zoneServer != NULL) {
					ChatManager* chatManager = zoneServer->getChatManager();
					chatManager->broadcastGalaxy(NULL, "Server is shutting down NOW!");
				}

				return;
			} else if (command == "dumpmem") {
				#ifdef DEBUG_MEMORY
					DumpUnfreed(TRUE);
				#endif
			} else if (command == "logQuadTree") {
				QuadTree::setLogging(!QuadTree::doLog());
			} else if (command == "info") {
				//TaskManager::instance()->printInfo();

				if (loginServer != NULL)
					loginServer->printInfo();

				if (zoneServer != NULL)
					zoneServer->printInfo(true);

				if (pingServer != NULL)
					pingServer->printInfo();
			} else if (command == "lock") {
				if (zoneServer != NULL)
					zoneServer->setServerStateLocked();
			} else if (command == "unlock") {
				if (zoneServer != NULL)
					zoneServer->setServerStateOnline();
			} else if (command == "icap") {
				if (zoneServer != NULL)
					zoneServer->changeUserCap(50);
			} else if (command == "dcap") {
				if (zoneServer != NULL)
					zoneServer->changeUserCap(-50);
			} else if (command == "fixQueue") {
				if (zoneServer != NULL)
					zoneServer->fixScheduler();
			} else if (command == "crash") {
				zoneServer = NULL;

				zoneServer->fixScheduler();
			} else if (command == "save") {
				ObjectManager::instance()->updateModifiedObjectsToDatabase(true);
				//ObjectDatabaseManager::instance()->checkpoint();
			} else if (command == "help") {
				System::out << "available commands:\n";
				System::out << "\texit, logQuadTree, info, icap, dcap, fixQueue, crash, about.\n";
			} else if (command == "about") {
				System::out << "Core3 Uber Edition. Ultyma pwns you.\n";
			} else if (command == "lookupcrc") {
				uint32 crc = 0;
				try {
					crc = UnsignedInteger::valueOf(arguments);
				} catch (Exception& e) {
					System::out << "invalid crc number expected dec";
				}

				if (crc != 0) {
					String file = TemplateManager::instance()->getTemplateFile(crc);

					System::out << "result: " << file << endl;
				}

			} else if (command == "rev") {
				System::out << ConfigManager::instance()->getRevision() << endl;
			} else
				System::out << "unknown command (" << command << ")\n";
		} catch (SocketException& e) {
			System::out << "[ServerCore] " << e.getMessage();
		} catch (ArrayIndexOutOfBoundsException& e) {
			System::out << "[ServerCore] " << e.getMessage() << "\n";
		} catch (Exception& e) {
			System::out << "[ServerCore] unreported Exception caught\n";
		}

#ifdef WITH_STM
		try {
			TransactionalMemoryManager::commitPureTransaction(transaction);
		} catch (const TransactionAbortedException& e) {
		}
	#endif

	}
}

void ServerCore::processConfig() {
	if (!configManager->loadConfigData())
		info("missing config file.. loading default values\n");

	//if (!features->loadFeatures())
		//info("Problem occurred trying to load features.lua");
}
<commit_msg>[fixed] error message on db exception while loading<commit_after>/*
Copyright (C) 2007 <SWGEmu>

This File is part of Core3.

This program is free software; you can redistribute
it and/or modify it under the terms of the GNU Lesser
General Public License as published by the Free Software
Foundation; either version 2 of the License,
or (at your option) any later version.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
See the GNU Lesser General Public License for
more details.

You should have received a copy of the GNU Lesser General
Public License along with this program; if not, write to
the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA

Linking Engine3 statically or dynamically with other modules
is making a combined work based on Engine3.
Thus, the terms and conditions of the GNU Lesser General Public License
cover the whole combination.

In addition, as a special exception, the copyright holders of Engine3
give you permission to combine Engine3 program with free software
programs or libraries that are released under the GNU LGPL and with
code included in the standard release of Core3 under the GNU LGPL
license (or modified versions of such code, with unchanged license).
You may copy and distribute such a system following the terms of the
GNU LGPL for Engine3 and the licenses of the other code concerned,
provided that you include the source code of that other code when
and as the GNU LGPL requires distribution of source code.

Note that people who make modified versions of Engine3 are not obligated
to grant this special exception for their modified versions;
it is their choice whether to do so. The GNU Lesser General Public License
gives permission to release a modified version without this exception;
this exception also makes it possible to release a modified version
which carries forward this exception.
*/

#include "ServerCore.h"

#include "db/ServerDatabase.h"

#include "db/MantisDatabase.h"

#include "chat/ChatManager.h"

#include "login/LoginServer.h"

#include "features/Features.h"

#include "ping/PingServer.h"

#include "status/StatusServer.h"

#include "web/WebServer.h"

#include "zone/ZoneServer.h"

#include "zone/managers/object/ObjectManager.h"
#include "zone/managers/templates/TemplateManager.h"

#include "zone/objects/creature/CreatureObject.h"

ManagedReference<ZoneServer*> ServerCore::zoneServerRef = NULL;
SortedVector<String> ServerCore::arguments;
bool ServerCore::truncateAllData = false;

ServerCore::ServerCore(bool truncateDatabases, SortedVector<String>& args) : Core("log/core3.log"), Logger("Core") {
	orb = NULL;

	loginServer = NULL;
	zoneServerRef = NULL;
	statusServer = NULL;
	pingServer = NULL;
	webServer = NULL;
	database = NULL;

	truncateAllData = truncateDatabases;
	arguments = args;

	configManager = ConfigManager::instance();

	features = NULL;
}

class ZoneStatisticsTask : public Task {
	ManagedReference<ZoneServer*> zoneServer;

public:
	ZoneStatisticsTask(ZoneServer* server) {
		zoneServer = server;
	}

	void run() {
		zoneServer->printInfo(true);
	}
};

void ServerCore::initialize() {
	info("starting up server..");

	processConfig();

	try {
		ObjectManager* objectManager = ObjectManager::instance();

		database = new ServerDatabase(configManager);

		mantisDatabase = new MantisDatabase(configManager);

		String& orbaddr = configManager->getORBNamingDirectoryAddress();
		orb = DistributedObjectBroker::initialize(orbaddr, 44496);

		orb->setCustomObjectManager(objectManager);

		if (configManager->getMakeLogin()) {
			loginServer = new LoginServer(configManager);
			loginServer->deploy("LoginServer");
		}

		if (configManager->getMakeZone()) {
			ZoneServer* zoneServer = new ZoneServer(configManager);
			zoneServer->deploy("ZoneServer");

			zoneServerRef = zoneServer;
		}

		if (configManager->getMakePing()) {
			pingServer = new PingServer();
		}

		if (configManager->getMakeStatus()) {
			statusServer = new StatusServer(configManager, zoneServerRef);
		}

		if (configManager->getMakeWeb()) {
			webServer = WebServer::instance();
		}

		ZoneServer* zoneServer = zoneServerRef.get();

		if (zoneServer != NULL) {
			int zonePort = 44463;
			int zoneAllowedConnections = configManager->getZoneAllowedConnections();

			ObjectDatabaseManager* dbManager = ObjectDatabaseManager::instance();
			dbManager->loadDatabases(truncateDatabases());

			int galaxyID = configManager->getZoneGalaxyID();

			try {
				String query = "SELECT port FROM galaxy WHERE galaxy_id = " + String::valueOf(galaxyID);
				Reference<ResultSet*> result = database->instance()->executeQuery(query);

				if (result != NULL && result->next()) {
					zonePort = result->getInt(0);
				}

				database->instance()->executeStatement("TRUNCATE TABLE sessions");

				database->instance()->executeStatement("DELETE FROM characters_dirty WHERE galaxy_id = " + String::valueOf(galaxyID));
			} catch (DatabaseException& e) {
				error(e.getMessage());

				exit(1);
			}

			zoneServer->start(zonePort, zoneAllowedConnections);
		}

		if (statusServer != NULL) {
			int statusPort = configManager->getStatusPort();
			int statusAllowedConnections = configManager->getStatusAllowedConnections();

			statusServer->start(statusPort);
		}

		if (webServer != NULL) {
			webServer->start(configManager);
		}

		if (pingServer != NULL) {
			int pingPort = configManager->getPingPort();
			int pingAllowedConnections = configManager->getPingAllowedConnections();

			pingServer->start(pingPort, pingAllowedConnections);
		}

		if (loginServer != NULL) {
			int loginPort = configManager->getLoginPort();
			int loginAllowedConnections = configManager->getLoginAllowedConnections();

			loginServer->start(loginPort, loginAllowedConnections);
		}

	#ifndef WITH_STM
		ObjectManager::instance()->scheduleUpdateToDatabase();
	#else
		Task* statiscticsTask = new ZoneStatisticsTask(zoneServerRef);
		statiscticsTask->schedulePeriodic(10000, 10000);
	#endif

		info("initialized", true);
	} catch (ServiceException& e) {
		shutdown();
	} catch (DatabaseException& e) {
		info(e.getMessage());

		exit(1);
	}
}

void ServerCore::run() {
	handleCommands();

	shutdown();
}

void ServerCore::shutdown() {
	info("shutting down server..");

	ObjectManager::instance()->cancelUpdateModifiedObjectsTask();
	ObjectDatabaseManager::instance()->checkpoint();

	info("database checkpoint done", true);

	if (statusServer != NULL) {
		statusServer->stop();

		delete statusServer;
		statusServer = NULL;
	}

	if (webServer != NULL) {
		webServer->stop();

		delete webServer;
		webServer = NULL;
	}

	ZoneServer* zoneServer = zoneServerRef.get();

	if (zoneServer != NULL) {
		zoneServer->stop();
		//zoneServer->finalize();

		zoneServer = NULL;
	}

	if (loginServer != NULL) {
		loginServer->stop();

		loginServer = NULL;
	}

	if (pingServer != NULL) {
		pingServer->stop();

		delete pingServer;
		pingServer = NULL;
	}

	if (features != NULL) {
		delete features;
		features = NULL;
	}

	if (database != NULL) {
		delete database;
		database = NULL;
	}

	if (mantisDatabase != NULL) {
		delete mantisDatabase;
		mantisDatabase = NULL;
	}

	zoneServerRef = NULL;

	info("server closed");

	//exit(1);
}

void ServerCore::handleCommands() {
	while (true) {

#ifdef WITH_STM
		Reference<Transaction*> transaction = TransactionalMemoryManager::instance()->startTransaction();
#endif

		try {
			String fullCommand;

			Thread::sleep(500);

			System::out << "> ";

			char line[256];
			fgets(line, sizeof(line), stdin);

			fullCommand = line;
			fullCommand = fullCommand.replaceFirst("\n", "");

			StringTokenizer tokenizer(fullCommand);

			String command, arguments;

			if (tokenizer.hasMoreTokens())
				tokenizer.getStringToken(command);

			if (tokenizer.hasMoreTokens())
				tokenizer.finalToken(arguments);

			ZoneServer* zoneServer = zoneServerRef.getForUpdate();

			if (command == "exit") {
				if (zoneServer != NULL) {
					ChatManager* chatManager = zoneServer->getChatManager();
					chatManager->broadcastGalaxy(NULL, "Server is shutting down NOW!");
				}

				return;
			} else if (command == "dumpmem") {
				#ifdef DEBUG_MEMORY
					DumpUnfreed(TRUE);
				#endif
			} else if (command == "logQuadTree") {
				QuadTree::setLogging(!QuadTree::doLog());
			} else if (command == "info") {
				//TaskManager::instance()->printInfo();

				if (loginServer != NULL)
					loginServer->printInfo();

				if (zoneServer != NULL)
					zoneServer->printInfo(true);

				if (pingServer != NULL)
					pingServer->printInfo();
			} else if (command == "lock") {
				if (zoneServer != NULL)
					zoneServer->setServerStateLocked();
			} else if (command == "unlock") {
				if (zoneServer != NULL)
					zoneServer->setServerStateOnline();
			} else if (command == "icap") {
				if (zoneServer != NULL)
					zoneServer->changeUserCap(50);
			} else if (command == "dcap") {
				if (zoneServer != NULL)
					zoneServer->changeUserCap(-50);
			} else if (command == "fixQueue") {
				if (zoneServer != NULL)
					zoneServer->fixScheduler();
			} else if (command == "crash") {
				zoneServer = NULL;

				zoneServer->fixScheduler();
			} else if (command == "save") {
				ObjectManager::instance()->updateModifiedObjectsToDatabase(true);
				//ObjectDatabaseManager::instance()->checkpoint();
			} else if (command == "help") {
				System::out << "available commands:\n";
				System::out << "\texit, logQuadTree, info, icap, dcap, fixQueue, crash, about.\n";
			} else if (command == "about") {
				System::out << "Core3 Uber Edition. Ultyma pwns you.\n";
			} else if (command == "lookupcrc") {
				uint32 crc = 0;
				try {
					crc = UnsignedInteger::valueOf(arguments);
				} catch (Exception& e) {
					System::out << "invalid crc number expected dec";
				}

				if (crc != 0) {
					String file = TemplateManager::instance()->getTemplateFile(crc);

					System::out << "result: " << file << endl;
				}

			} else if (command == "rev") {
				System::out << ConfigManager::instance()->getRevision() << endl;
			} else
				System::out << "unknown command (" << command << ")\n";
		} catch (SocketException& e) {
			System::out << "[ServerCore] " << e.getMessage();
		} catch (ArrayIndexOutOfBoundsException& e) {
			System::out << "[ServerCore] " << e.getMessage() << "\n";
		} catch (Exception& e) {
			System::out << "[ServerCore] unreported Exception caught\n";
		}

#ifdef WITH_STM
		try {
			TransactionalMemoryManager::commitPureTransaction(transaction);
		} catch (const TransactionAbortedException& e) {
		}
	#endif

	}
}

void ServerCore::processConfig() {
	if (!configManager->loadConfigData())
		info("missing config file.. loading default values\n");

	//if (!features->loadFeatures())
		//info("Problem occurred trying to load features.lua");
}
<|endoftext|>


<commit_before>/*

Copyright (c) 2003, Arvid Norberg
All rights reserved.

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:

    * Redistributions of source code must retain the above copyright
      notice, this list of conditions and the following disclaimer.
    * Redistributions in binary form must reproduce the above copyright
      notice, this list of conditions and the following disclaimer in
      the documentation and/or other materials provided with the distribution.
    * Neither the name of the author nor the names of its
      contributors may be used to endorse or promote products derived
      from this software without specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.

*/

#include "libtorrent/entry.hpp"
#include "libtorrent/bencode.hpp"
#include "libtorrent/torrent_info.hpp"
#include "libtorrent/lazy_entry.hpp"
#include "libtorrent/magnet_uri.hpp"

int main(int argc, char* argv[])
{
	using namespace libtorrent;

	printf("sizeof(file_entry): %d\n", int(sizeof(file_entry)));

	if (argc != 2)
	{
		fputs("usage: dump_torrent torrent-file\n", stderr);
		return 1;
	}

	int size = file_size(argv[1]);
	if (size > 10 * 1000000)
	{
		fprintf(stderr, "file too big (%d), aborting\n", size);
		return 1;
	}
	std::vector<char> buf(size);
	int ret = load_file(argv[1], buf);
	if (ret != 0)
	{
		fprintf(stderr, "failed to load file: %d\n", ret);
		return 1;
	}
	lazy_entry e;
	error_code ec;
	int pos;
	ret = lazy_bdecode(&buf[0], &buf[0] + buf.size(), e, ec, &pos);

	if (ret != 0)
	{
		fprintf(stderr, "failed to decode: '%s' at character: %d\n", ec.message().c_str(), pos);
		return 1;
	}

//	printf("\n\n----- raw info -----\n\n%s\n", print_entry(e).c_str());

	torrent_info t(e, ec);
	if (ec)
	{
		fprintf(stderr, "%s\n", ec.message().c_str());
		return 1;
	}
	e.clear();
	std::vector<char>().swap(buf);

	// print info about torrent
	printf("\n\n----- torrent file info -----\n\n"
		"nodes:\n");

	typedef std::vector<std::pair<std::string, int> > node_vec;
	node_vec const& nodes = t.nodes();
	for (node_vec::const_iterator i = nodes.begin(), end(nodes.end());
		i != end; ++i)
	{
		printf("%s: %d\n", i->first.c_str(), i->second);
	}
	puts("trackers:\n");
	for (std::vector<announce_entry>::const_iterator i = t.trackers().begin();
		i != t.trackers().end(); ++i)
	{
		printf("%2d: %s\n", i->tier, i->url.c_str());
	}

	char ih[41];
	to_hex((char const*)&t.info_hash()[0], 20, ih);
	printf("number of pieces: %d\n"
		"piece length: %d\n"
		"info hash: %s\n"
		"comment: %s\n"
		"created by: %s\n"
		"magnet link: %s\n"
		"name: %s\n"
		"number of files: %d\n"
		"files:\n"
		, t.num_pieces()
		, t.piece_length()
		, ih
		, t.comment().c_str()
		, t.creator().c_str()
		, make_magnet_uri(t).c_str()
		, t.name().c_str()
		, t.num_files());
	int index = 0;
	for (torrent_info::file_iterator i = t.begin_files();
		i != t.end_files(); ++i, ++index)
	{
		int first = t.map_file(index, 0, 0).piece;
		int last = t.map_file(index, (std::max)(i->size-1, size_type(0)), 0).piece;
		printf("  %11"PRId64" %c%c%c%c [ %4d, %4d ] %7u %s %s %s%s\n"
			, i->size
			, (i->pad_file?'p':'-')
			, (i->executable_attribute?'x':'-')
			, (i->hidden_attribute?'h':'-')
			, (i->symlink_attribute?'l':'-')
			, first, last
			, boost::uint32_t(t.files().mtime(*i))
			, t.files().hash(*i) != sha1_hash(0) ? to_hex(t.files().hash(*i).to_string()).c_str() : ""
			, t.files().file_path(*i).c_str()
			, i->symlink_attribute ? "-> ": ""
			, i->symlink_attribute && i->symlink_index != -1 ? t.files().symlink(*i).c_str() : "");
	}

	return 0;
}

<commit_msg>temporary commented out code<commit_after>/*

Copyright (c) 2003, Arvid Norberg
All rights reserved.

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:

    * Redistributions of source code must retain the above copyright
      notice, this list of conditions and the following disclaimer.
    * Redistributions in binary form must reproduce the above copyright
      notice, this list of conditions and the following disclaimer in
      the documentation and/or other materials provided with the distribution.
    * Neither the name of the author nor the names of its
      contributors may be used to endorse or promote products derived
      from this software without specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.

*/

#include "libtorrent/entry.hpp"
#include "libtorrent/bencode.hpp"
#include "libtorrent/torrent_info.hpp"
#include "libtorrent/lazy_entry.hpp"
#include "libtorrent/magnet_uri.hpp"

int main(int argc, char* argv[])
{
	using namespace libtorrent;

	printf("sizeof(file_entry): %d\n", int(sizeof(file_entry)));

	if (argc != 2)
	{
		fputs("usage: dump_torrent torrent-file\n", stderr);
		return 1;
	}

	int size = file_size(argv[1]);
	if (size > 10 * 1000000)
	{
		fprintf(stderr, "file too big (%d), aborting\n", size);
		return 1;
	}
	std::vector<char> buf(size);
	int ret = load_file(argv[1], buf);
	if (ret != 0)
	{
		fprintf(stderr, "failed to load file: %d\n", ret);
		return 1;
	}
	lazy_entry e;
	error_code ec;
	int pos;
	ret = lazy_bdecode(&buf[0], &buf[0] + buf.size(), e, ec, &pos);

	if (ret != 0)
	{
		fprintf(stderr, "failed to decode: '%s' at character: %d\n", ec.message().c_str(), pos);
		return 1;
	}

	printf("\n\n----- raw info -----\n\n%s\n", print_entry(e).c_str());

	torrent_info t(e, ec);
	if (ec)
	{
		fprintf(stderr, "%s\n", ec.message().c_str());
		return 1;
	}
	e.clear();
	std::vector<char>().swap(buf);

	// print info about torrent
	printf("\n\n----- torrent file info -----\n\n"
		"nodes:\n");

	typedef std::vector<std::pair<std::string, int> > node_vec;
	node_vec const& nodes = t.nodes();
	for (node_vec::const_iterator i = nodes.begin(), end(nodes.end());
		i != end; ++i)
	{
		printf("%s: %d\n", i->first.c_str(), i->second);
	}
	puts("trackers:\n");
	for (std::vector<announce_entry>::const_iterator i = t.trackers().begin();
		i != t.trackers().end(); ++i)
	{
		printf("%2d: %s\n", i->tier, i->url.c_str());
	}

	char ih[41];
	to_hex((char const*)&t.info_hash()[0], 20, ih);
	printf("number of pieces: %d\n"
		"piece length: %d\n"
		"info hash: %s\n"
		"comment: %s\n"
		"created by: %s\n"
		"magnet link: %s\n"
		"name: %s\n"
		"number of files: %d\n"
		"files:\n"
		, t.num_pieces()
		, t.piece_length()
		, ih
		, t.comment().c_str()
		, t.creator().c_str()
		, make_magnet_uri(t).c_str()
		, t.name().c_str()
		, t.num_files());
	int index = 0;
	for (torrent_info::file_iterator i = t.begin_files();
		i != t.end_files(); ++i, ++index)
	{
		int first = t.map_file(index, 0, 0).piece;
		int last = t.map_file(index, (std::max)(i->size-1, size_type(0)), 0).piece;
		printf("  %11"PRId64" %c%c%c%c [ %4d, %4d ] %7u %s %s %s%s\n"
			, i->size
			, (i->pad_file?'p':'-')
			, (i->executable_attribute?'x':'-')
			, (i->hidden_attribute?'h':'-')
			, (i->symlink_attribute?'l':'-')
			, first, last
			, boost::uint32_t(t.files().mtime(*i))
			, t.files().hash(*i) != sha1_hash(0) ? to_hex(t.files().hash(*i).to_string()).c_str() : ""
			, t.files().file_path(*i).c_str()
			, i->symlink_attribute ? "-> ": ""
			, i->symlink_attribute && i->symlink_index != -1 ? t.files().symlink(*i).c_str() : "");
	}

	return 0;
}

<|endoftext|>


<commit_before><commit_msg>Default using display names to on for now until I can fix the code to turn them off<commit_after><|endoftext|>


<commit_before>#include "FOX_OSG_MDIView.h"

#include <osgViewer/ViewerEventHandlers>

#include <osgGA/TrackballManipulator>

#include <osgDB/ReadFile>

// Map
FXDEFMAP(FOX_OSG_MDIView) FOX_OSG_MDIView_Map[] = {
	//________Message_Type_________		___ID___						________Message_Handler________
	FXMAPFUNC(SEL_CHORE,				FOX_OSG_MDIView::ID_CHORE,		FOX_OSG_MDIView::OnIdle)
};

FXIMPLEMENT(FOX_OSG_MDIView, FXMDIChild, FOX_OSG_MDIView_Map, ARRAYNUMBER(FOX_OSG_MDIView_Map))

FOX_OSG_MDIView::FOX_OSG_MDIView(FXMDIClient *p, const FXString &name,
		FXIcon *ic, FXPopup *pup, FXuint opt,
		FXint x, FXint y, FXint w, FXint h)
		:   FXMDIChild(p, name, ic, pup, opt, x, y, w, h)
{
	// A visual to drag OpenGL in double-buffered mode; note the glvisual is
	// shared between all windows which need the same depths and numbers of buffers
	// Thus, while the first visual may take some time to initialize, each subsequent
	// window can be created very quickly; we need to determine grpaphics hardware
	// characteristics only once.
	FXGLVisual* glVisual=new FXGLVisual(getApp(),VISUAL_DOUBLEBUFFER|VISUAL_STEREO);

	m_gwFox = new GraphicsWindowFOX(this, glVisual, NULL, NULL, LAYOUT_FILL_X|LAYOUT_FILL_Y, x, y, w, h );

	osgViewer::Viewer *viewer = new osgViewer::Viewer;
	viewer->getCamera()->setGraphicsContext(m_gwFox);
	viewer->getCamera()->setViewport(0,0,w,h);
	viewer->setThreadingModel(osgViewer::Viewer::SingleThreaded);

	// load the scene.
	osg::ref_ptr<osg::Node> loadedModel = osgDB::readNodeFile("cow.osg");
	if (!loadedModel)
	{
		return ;
	}

	// add the stats handler
    viewer->addEventHandler(new osgViewer::StatsHandler);

	viewer->setSceneData(loadedModel.get());

	viewer->setCameraManipulator(new osgGA::TrackballManipulator);

	SetViewer(viewer);

	getApp()->addChore(this,ID_CHORE);

}

FOX_OSG_MDIView::~FOX_OSG_MDIView()
{
}

long FOX_OSG_MDIView::OnIdle(FXObject *sender, FXSelector sel, void* ptr)
{
	m_osgViewer->frame();
	getApp()->addChore(this, ID_CHORE);
	return 1;
}

void FOX_OSG_MDIView::SetViewer(osgViewer::Viewer* viewer)
{
	m_osgViewer = viewer;
}
<commit_msg>Fixed warning<commit_after>#include "FOX_OSG_MDIView.h"

#include <osgViewer/ViewerEventHandlers>

#include <osgGA/TrackballManipulator>

#include <osgDB/ReadFile>

// Map
FXDEFMAP(FOX_OSG_MDIView) FOX_OSG_MDIView_Map[] = {
	//________Message_Type_________		___ID___						________Message_Handler________
	FXMAPFUNC(SEL_CHORE,				FOX_OSG_MDIView::ID_CHORE,		FOX_OSG_MDIView::OnIdle)
};

FXIMPLEMENT(FOX_OSG_MDIView, FXMDIChild, FOX_OSG_MDIView_Map, ARRAYNUMBER(FOX_OSG_MDIView_Map))

FOX_OSG_MDIView::FOX_OSG_MDIView(FXMDIClient *p, const FXString &name,
		FXIcon *ic, FXPopup *pup, FXuint opt,
		FXint x, FXint y, FXint w, FXint h)
		:   FXMDIChild(p, name, ic, pup, opt, x, y, w, h)
{
	// A visual to drag OpenGL in double-buffered mode; note the glvisual is
	// shared between all windows which need the same depths and numbers of buffers
	// Thus, while the first visual may take some time to initialize, each subsequent
	// window can be created very quickly; we need to determine grpaphics hardware
	// characteristics only once.
	FXGLVisual* glVisual=new FXGLVisual(getApp(),VISUAL_DOUBLEBUFFER|VISUAL_STEREO);

	m_gwFox = new GraphicsWindowFOX(this, glVisual, NULL, 0, LAYOUT_FILL_X|LAYOUT_FILL_Y, x, y, w, h );

	osgViewer::Viewer *viewer = new osgViewer::Viewer;
	viewer->getCamera()->setGraphicsContext(m_gwFox);
	viewer->getCamera()->setViewport(0,0,w,h);
	viewer->setThreadingModel(osgViewer::Viewer::SingleThreaded);

	// load the scene.
	osg::ref_ptr<osg::Node> loadedModel = osgDB::readNodeFile("cow.osg");
	if (!loadedModel)
	{
		return ;
	}

	// add the stats handler
    viewer->addEventHandler(new osgViewer::StatsHandler);

	viewer->setSceneData(loadedModel.get());

	viewer->setCameraManipulator(new osgGA::TrackballManipulator);

	SetViewer(viewer);

	getApp()->addChore(this,ID_CHORE);

}

FOX_OSG_MDIView::~FOX_OSG_MDIView()
{
}

long FOX_OSG_MDIView::OnIdle(FXObject *sender, FXSelector sel, void* ptr)
{
	m_osgViewer->frame();
	getApp()->addChore(this, ID_CHORE);
	return 1;
}

void FOX_OSG_MDIView::SetViewer(osgViewer::Viewer* viewer)
{
	m_osgViewer = viewer;
}
<|endoftext|>


<commit_before><commit_msg>Adjustments should be precomposed, not postcomposed!<commit_after><|endoftext|>