<commit_before>/*********************************************************************
 * Software License Agreement (BSD License)
 *
 *  Copyright (c) 2011, Willow Garage, Inc.
 *  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 Willow Garage 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.
 *********************************************************************/

/* Author: Ioan Sucan */

#include <moveit/planning_scene_monitor/current_state_monitor.h>
#include <tf_conversions/tf_eigen.h>
#include <limits>

planning_scene_monitor::CurrentStateMonitor::CurrentStateMonitor(const robot_model::RobotModelConstPtr &robot_model, const boost::shared_ptr<tf::Transformer> &tf)
  : tf_(tf)
  , robot_model_(robot_model)
  , robot_state_(robot_model)
  , state_monitor_started_(false)
  , error_(std::numeric_limits<float>::epsilon())
{
  robot_state_.setToDefaultValues();
}

planning_scene_monitor::CurrentStateMonitor::~CurrentStateMonitor()
{
  stopStateMonitor();
}

robot_state::RobotStatePtr planning_scene_monitor::CurrentStateMonitor::getCurrentState() const
{
  boost::mutex::scoped_lock slock(state_update_lock_);
  robot_state::RobotState *result = new robot_state::RobotState(robot_state_);
  return robot_state::RobotStatePtr(result);
}

ros::Time planning_scene_monitor::CurrentStateMonitor::getCurrentStateTime() const
{
  boost::mutex::scoped_lock slock(state_update_lock_);
  return current_state_time_;
}

std::pair<robot_state::RobotStatePtr, ros::Time> planning_scene_monitor::CurrentStateMonitor::getCurrentStateAndTime() const
{
  boost::mutex::scoped_lock slock(state_update_lock_);
  robot_state::RobotState *result = new robot_state::RobotState(robot_state_);
  return std::make_pair(robot_state::RobotStatePtr(result), current_state_time_);
}

std::map<std::string, double> planning_scene_monitor::CurrentStateMonitor::getCurrentStateValues() const
{
  std::map<std::string, double> m;
  boost::mutex::scoped_lock slock(state_update_lock_);
  const double *pos = robot_state_.getVariablePositions();
  const std::vector<std::string> &names = robot_state_.getVariableNames();
  for (std::size_t i = 0 ; i < names.size() ; ++i)
    m[names[i]] = pos[i];
  return m;
}

void planning_scene_monitor::CurrentStateMonitor::setToCurrentState(robot_state::RobotState &upd) const
{
  boost::mutex::scoped_lock slock(state_update_lock_);
  upd = robot_state_;
}

void planning_scene_monitor::CurrentStateMonitor::addUpdateCallback(const JointStateUpdateCallback &fn)
{
  if (fn)
    update_callbacks_.push_back(fn);
}

void planning_scene_monitor::CurrentStateMonitor::clearUpdateCallbacks()
{
  update_callbacks_.clear();
}

void planning_scene_monitor::CurrentStateMonitor::startStateMonitor(const std::string &joint_states_topic)
{
  if (!state_monitor_started_ && robot_model_)
  {
    joint_time_.clear();
    if (joint_states_topic.empty())
      ROS_ERROR("The joint states topic cannot be an empty string");
    else
      joint_state_subscriber_ = nh_.subscribe(joint_states_topic, 25, &CurrentStateMonitor::jointStateCallback, this);
    state_monitor_started_ = true;
    monitor_start_time_ = ros::Time::now();
    ROS_DEBUG("Listening to joint states on topic '%s'", nh_.resolveName(joint_states_topic).c_str());
  }
}

bool planning_scene_monitor::CurrentStateMonitor::isActive() const
{
  return state_monitor_started_;
}

void planning_scene_monitor::CurrentStateMonitor::stopStateMonitor()
{
  if (state_monitor_started_)
  {
    joint_state_subscriber_.shutdown();
    ROS_DEBUG("No longer listening o joint states");
    state_monitor_started_ = false;
  }
}

std::string planning_scene_monitor::CurrentStateMonitor::getMonitoredTopic() const
{
  if (joint_state_subscriber_)
    return joint_state_subscriber_.getTopic();
  else
    return "";
}

bool planning_scene_monitor::CurrentStateMonitor::isPassiveDOF(const std::string &dof) const
{
  if (robot_model_->hasJointModel(dof))
  {
    if (robot_model_->getJointModel(dof)->isPassive())
      return true;
  }
  else
  {
    // check if this DOF is part of a multi-dof passive joint
    std::size_t slash = dof.find_last_of("/");
    if (slash != std::string::npos)
    {
      std::string joint_name = dof.substr(0, slash);
      if (robot_model_->hasJointModel(joint_name))
        if (robot_model_->getJointModel(joint_name)->isPassive())
          return true;
    }
  }
  return false;
}

bool planning_scene_monitor::CurrentStateMonitor::haveCompleteState() const
{
  bool result = true;
  const std::vector<std::string> &dof = robot_model_->getVariableNames();
  boost::mutex::scoped_lock slock(state_update_lock_);
  for (std::size_t i = 0 ; i < dof.size() ; ++i)
    if (joint_time_.find(dof[i]) == joint_time_.end())
    {
      if (!isPassiveDOF(dof[i]))
      {
        ROS_DEBUG("Joint variable '%s' has never been updated", dof[i].c_str());
        result = false;
      }
    }
  return result;
}

bool planning_scene_monitor::CurrentStateMonitor::haveCompleteState(std::vector<std::string> &missing_states) const
{
  bool result = true;
  const std::vector<std::string> &dof = robot_model_->getVariableNames();
  boost::mutex::scoped_lock slock(state_update_lock_);
  for (std::size_t i = 0 ; i < dof.size() ; ++i)
    if (joint_time_.find(dof[i]) == joint_time_.end())
      if (!isPassiveDOF(dof[i]))
      {
        ROS_DEBUG("Joint variable '%s' has never been updated", dof[i].c_str());
        missing_states.push_back(dof[i]);
        result = false;
      }
  return result;
}

bool planning_scene_monitor::CurrentStateMonitor::haveCompleteState(const ros::Duration &age) const
{
  bool result = true;
  const std::vector<std::string> &dof = robot_model_->getVariableNames();
  ros::Time now = ros::Time::now();
  ros::Time old = now - age;
  boost::mutex::scoped_lock slock(state_update_lock_);
  for (std::size_t i = 0 ; i < dof.size() ; ++i)
  {
    if (isPassiveDOF(dof[i]))
      continue;
    std::map<std::string, ros::Time>::const_iterator it = joint_time_.find(dof[i]);
    if (it == joint_time_.end())
    {
      ROS_DEBUG("Joint variable '%s' has never been updated", dof[i].c_str());
      result = false;
    }
    else
      if (it->second < old)
      {
        ROS_DEBUG("Joint variable '%s' was last updated %0.3lf seconds ago (older than the allowed %0.3lf seconds)",
                  dof[i].c_str(), (now - it->second).toSec(), age.toSec());
        result = false;
      }
  }
  return result;
}

bool planning_scene_monitor::CurrentStateMonitor::haveCompleteState(const ros::Duration &age,
                                                                    std::vector<std::string> &missing_states) const
{
  bool result = true;
  const std::vector<std::string> &dof = robot_model_->getVariableNames();
  ros::Time now = ros::Time::now();
  ros::Time old = now - age;
  boost::mutex::scoped_lock slock(state_update_lock_);
  for (std::size_t i = 0 ; i < dof.size() ; ++i)
  {
    if (isPassiveDOF(dof[i]))
      continue;
    std::map<std::string, ros::Time>::const_iterator it = joint_time_.find(dof[i]);
    if (it == joint_time_.end())
    {
      ROS_DEBUG("Joint variable '%s' has never been updated", dof[i].c_str());
      missing_states.push_back(dof[i]);
      result = false;
    }
    else
      if (it->second < old)
      {
        ROS_DEBUG("Joint variable '%s' was last updated %0.3lf seconds ago (older than the allowed %0.3lf seconds)",
                  dof[i].c_str(), (now - it->second).toSec(), age.toSec());
        missing_states.push_back(dof[i]);
        result = false;
      }
  }
  return result;
}

bool planning_scene_monitor::CurrentStateMonitor::waitForCurrentState(double wait_time) const
{
  double slept_time = 0.0;
  double sleep_step_s = std::min(0.05, wait_time / 10.0);
  ros::Duration sleep_step(sleep_step_s);
  while (!haveCompleteState() && slept_time < wait_time)
  {
    sleep_step.sleep();
    slept_time += sleep_step_s;
  }
  return haveCompleteState();
}

bool planning_scene_monitor::CurrentStateMonitor::waitForCurrentState(const std::string &group, double wait_time) const
{
  if (waitForCurrentState(wait_time))
    return true;
  bool ok = true;

  // check to see if we have a fully known state for the joints we want to record
  std::vector<std::string> missing_joints;
  if (!haveCompleteState(missing_joints))
  {
    const robot_model::JointModelGroup *jmg = robot_model_->getJointModelGroup(group);
    if (jmg)
    {
      std::set<std::string> mj;
      mj.insert(missing_joints.begin(), missing_joints.end());
      const std::vector<std::string> &names= jmg->getJointModelNames();
      bool ok = true;
      for (std::size_t i = 0 ; ok && i < names.size() ; ++i)
        if (mj.find(names[i]) != mj.end())
          ok = false;
    }
    else
      ok = false;
  }
  return ok;
}

void planning_scene_monitor::CurrentStateMonitor::jointStateCallback(const sensor_msgs::JointStateConstPtr &joint_state)
{
  if (joint_state->name.size() != joint_state->position.size())
  {
    ROS_ERROR_THROTTLE(1, "State monitor received invalid joint state (number of joint names does not match number of positions)");
    return;
  }

  {
    boost::mutex::scoped_lock _(state_update_lock_);
    // read the received values, and update their time stamps
    std::size_t n = joint_state->name.size();
    current_state_time_ = joint_state->header.stamp;
    for (std::size_t i = 0 ; i < n ; ++i)
    {
      const robot_model::JointModel* jm = robot_model_->getJointModel(joint_state->name[i]);
      if (!jm)
        continue;
      // ignore fixed joints, multi-dof joints (they should not even be in the message)
      if (jm->getVariableCount() != 1)
        continue;

      robot_state_.setJointPositions(jm, &(joint_state->position[i]));
      joint_time_[joint_state->name[i]] = joint_state->header.stamp;

      // continuous joints wrap, so we don't modify them (even if they are outside bounds!)
      if (jm->getType() == robot_model::JointModel::REVOLUTE)
        if (static_cast<const robot_model::RevoluteJointModel*>(jm)->isContinuous())
          continue;

      const robot_model::VariableBounds &b = jm->getVariableBounds()[0]; // only one variable in the joint, so we get its bounds

      // if the read variable is 'almost' within bounds (up to error_ difference), then consider it to be within bounds
      if (joint_state->position[i] < b.min_position_ && joint_state->position[i] >= b.min_position_ - error_)
        robot_state_.setJointPositions(jm, &b.min_position_);
      else
        if (joint_state->position[i] > b.max_position_ && joint_state->position[i] <= b.max_position_ + error_)
          robot_state_.setJointPositions(jm, &b.max_position_);
    }

    // read root transform, if needed
    if (tf_ && (robot_model_->getRootJoint()->getType() == robot_model::JointModel::PLANAR ||
                robot_model_->getRootJoint()->getType() == robot_model::JointModel::FLOATING))
    {
      const std::string &child_frame = robot_model_->getRootLink()->getName();
      const std::string &parent_frame = robot_model_->getModelFrame();

      std::string err;
      ros::Time tm;
      tf::StampedTransform transf;
      bool ok = false;
      if (tf_->getLatestCommonTime(parent_frame, child_frame, tm, &err) == tf::NO_ERROR)
      {
        try
        {
          tf_->lookupTransform(parent_frame, child_frame, tm, transf);
          ok = true;
        }
        catch(tf::TransformException& ex)
        {
          ROS_ERROR_THROTTLE(1, "Unable to lookup transform from %s to %s.  Exception: %s", parent_frame.c_str(), child_frame.c_str(), ex.what());
        }
      }
      else
        ROS_DEBUG_THROTTLE(1, "Unable to lookup transform from %s to %s: no common time.", parent_frame.c_str(), child_frame.c_str());
      if (ok)
      {
        const std::vector<std::string> &vars = robot_model_->getRootJoint()->getVariableNames();
        for (std::size_t j = 0; j < vars.size() ; ++j)
          joint_time_[vars[j]] = tm;
        Eigen::Affine3d eigen_transf;
        tf::transformTFToEigen(transf, eigen_transf);
        robot_state_.setJointPositions(robot_model_->getRootJoint(), eigen_transf);
      }
    }
  }

  // callbacks, if needed
  for (std::size_t i = 0 ; i < update_callbacks_.size() ; ++i)
    update_callbacks_[i](joint_state);
}
<commit_msg>Removed misleading and duplicate debug message<commit_after>/*********************************************************************
 * Software License Agreement (BSD License)
 *
 *  Copyright (c) 2011, Willow Garage, Inc.
 *  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 Willow Garage 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.
 *********************************************************************/

/* Author: Ioan Sucan */

#include <moveit/planning_scene_monitor/current_state_monitor.h>
#include <tf_conversions/tf_eigen.h>
#include <limits>

planning_scene_monitor::CurrentStateMonitor::CurrentStateMonitor(const robot_model::RobotModelConstPtr &robot_model, const boost::shared_ptr<tf::Transformer> &tf)
  : tf_(tf)
  , robot_model_(robot_model)
  , robot_state_(robot_model)
  , state_monitor_started_(false)
  , error_(std::numeric_limits<float>::epsilon())
{
  robot_state_.setToDefaultValues();
}

planning_scene_monitor::CurrentStateMonitor::~CurrentStateMonitor()
{
  stopStateMonitor();
}

robot_state::RobotStatePtr planning_scene_monitor::CurrentStateMonitor::getCurrentState() const
{
  boost::mutex::scoped_lock slock(state_update_lock_);
  robot_state::RobotState *result = new robot_state::RobotState(robot_state_);
  return robot_state::RobotStatePtr(result);
}

ros::Time planning_scene_monitor::CurrentStateMonitor::getCurrentStateTime() const
{
  boost::mutex::scoped_lock slock(state_update_lock_);
  return current_state_time_;
}

std::pair<robot_state::RobotStatePtr, ros::Time> planning_scene_monitor::CurrentStateMonitor::getCurrentStateAndTime() const
{
  boost::mutex::scoped_lock slock(state_update_lock_);
  robot_state::RobotState *result = new robot_state::RobotState(robot_state_);
  return std::make_pair(robot_state::RobotStatePtr(result), current_state_time_);
}

std::map<std::string, double> planning_scene_monitor::CurrentStateMonitor::getCurrentStateValues() const
{
  std::map<std::string, double> m;
  boost::mutex::scoped_lock slock(state_update_lock_);
  const double *pos = robot_state_.getVariablePositions();
  const std::vector<std::string> &names = robot_state_.getVariableNames();
  for (std::size_t i = 0 ; i < names.size() ; ++i)
    m[names[i]] = pos[i];
  return m;
}

void planning_scene_monitor::CurrentStateMonitor::setToCurrentState(robot_state::RobotState &upd) const
{
  boost::mutex::scoped_lock slock(state_update_lock_);
  upd = robot_state_;
}

void planning_scene_monitor::CurrentStateMonitor::addUpdateCallback(const JointStateUpdateCallback &fn)
{
  if (fn)
    update_callbacks_.push_back(fn);
}

void planning_scene_monitor::CurrentStateMonitor::clearUpdateCallbacks()
{
  update_callbacks_.clear();
}

void planning_scene_monitor::CurrentStateMonitor::startStateMonitor(const std::string &joint_states_topic)
{
  if (!state_monitor_started_ && robot_model_)
  {
    joint_time_.clear();
    if (joint_states_topic.empty())
      ROS_ERROR("The joint states topic cannot be an empty string");
    else
      joint_state_subscriber_ = nh_.subscribe(joint_states_topic, 25, &CurrentStateMonitor::jointStateCallback, this);
    state_monitor_started_ = true;
    monitor_start_time_ = ros::Time::now();
    ROS_DEBUG("Listening to joint states on topic '%s'", nh_.resolveName(joint_states_topic).c_str());
  }
}

bool planning_scene_monitor::CurrentStateMonitor::isActive() const
{
  return state_monitor_started_;
}

void planning_scene_monitor::CurrentStateMonitor::stopStateMonitor()
{
  if (state_monitor_started_)
  {
    joint_state_subscriber_.shutdown();
    ROS_DEBUG("No longer listening o joint states");
    state_monitor_started_ = false;
  }
}

std::string planning_scene_monitor::CurrentStateMonitor::getMonitoredTopic() const
{
  if (joint_state_subscriber_)
    return joint_state_subscriber_.getTopic();
  else
    return "";
}

bool planning_scene_monitor::CurrentStateMonitor::isPassiveDOF(const std::string &dof) const
{
  if (robot_model_->hasJointModel(dof))
  {
    if (robot_model_->getJointModel(dof)->isPassive())
      return true;
  }
  else
  {
    // check if this DOF is part of a multi-dof passive joint
    std::size_t slash = dof.find_last_of("/");
    if (slash != std::string::npos)
    {
      std::string joint_name = dof.substr(0, slash);
      if (robot_model_->hasJointModel(joint_name))
        if (robot_model_->getJointModel(joint_name)->isPassive())
          return true;
    }
  }
  return false;
}

bool planning_scene_monitor::CurrentStateMonitor::haveCompleteState() const
{
  bool result = true;
  const std::vector<std::string> &dof = robot_model_->getVariableNames();
  boost::mutex::scoped_lock slock(state_update_lock_);
  for (std::size_t i = 0 ; i < dof.size() ; ++i)
    if (joint_time_.find(dof[i]) == joint_time_.end())
    {
      if (!isPassiveDOF(dof[i]))
      {
        ROS_DEBUG("Joint variable '%s' has never been updated", dof[i].c_str());
        result = false;
      }
    }
  return result;
}

bool planning_scene_monitor::CurrentStateMonitor::haveCompleteState(std::vector<std::string> &missing_states) const
{
  bool result = true;
  const std::vector<std::string> &dof = robot_model_->getVariableNames();
  boost::mutex::scoped_lock slock(state_update_lock_);
  for (std::size_t i = 0 ; i < dof.size() ; ++i)
    if (joint_time_.find(dof[i]) == joint_time_.end())
      if (!isPassiveDOF(dof[i]))
      {
        missing_states.push_back(dof[i]);
        result = false;
      }
  return result;
}

bool planning_scene_monitor::CurrentStateMonitor::haveCompleteState(const ros::Duration &age) const
{
  bool result = true;
  const std::vector<std::string> &dof = robot_model_->getVariableNames();
  ros::Time now = ros::Time::now();
  ros::Time old = now - age;
  boost::mutex::scoped_lock slock(state_update_lock_);
  for (std::size_t i = 0 ; i < dof.size() ; ++i)
  {
    if (isPassiveDOF(dof[i]))
      continue;
    std::map<std::string, ros::Time>::const_iterator it = joint_time_.find(dof[i]);
    if (it == joint_time_.end())
    {
      ROS_DEBUG("Joint variable '%s' has never been updated", dof[i].c_str());
      result = false;
    }
    else
      if (it->second < old)
      {
        ROS_DEBUG("Joint variable '%s' was last updated %0.3lf seconds ago (older than the allowed %0.3lf seconds)",
                  dof[i].c_str(), (now - it->second).toSec(), age.toSec());
        result = false;
      }
  }
  return result;
}

bool planning_scene_monitor::CurrentStateMonitor::haveCompleteState(const ros::Duration &age,
                                                                    std::vector<std::string> &missing_states) const
{
  bool result = true;
  const std::vector<std::string> &dof = robot_model_->getVariableNames();
  ros::Time now = ros::Time::now();
  ros::Time old = now - age;
  boost::mutex::scoped_lock slock(state_update_lock_);
  for (std::size_t i = 0 ; i < dof.size() ; ++i)
  {
    if (isPassiveDOF(dof[i]))
      continue;
    std::map<std::string, ros::Time>::const_iterator it = joint_time_.find(dof[i]);
    if (it == joint_time_.end())
    {
      ROS_DEBUG("Joint variable '%s' has never been updated", dof[i].c_str());
      missing_states.push_back(dof[i]);
      result = false;
    }
    else
      if (it->second < old)
      {
        ROS_DEBUG("Joint variable '%s' was last updated %0.3lf seconds ago (older than the allowed %0.3lf seconds)",
                  dof[i].c_str(), (now - it->second).toSec(), age.toSec());
        missing_states.push_back(dof[i]);
        result = false;
      }
  }
  return result;
}

bool planning_scene_monitor::CurrentStateMonitor::waitForCurrentState(double wait_time) const
{
  double slept_time = 0.0;
  double sleep_step_s = std::min(0.05, wait_time / 10.0);
  ros::Duration sleep_step(sleep_step_s);
  while (!haveCompleteState() && slept_time < wait_time)
  {
    sleep_step.sleep();
    slept_time += sleep_step_s;
  }
  return haveCompleteState();
}

bool planning_scene_monitor::CurrentStateMonitor::waitForCurrentState(const std::string &group, double wait_time) const
{
  if (waitForCurrentState(wait_time))
    return true;
  bool ok = true;

  // check to see if we have a fully known state for the joints we want to record
  std::vector<std::string> missing_joints;
  if (!haveCompleteState(missing_joints))
  {
    const robot_model::JointModelGroup *jmg = robot_model_->getJointModelGroup(group);
    if (jmg)
    {
      std::set<std::string> mj;
      mj.insert(missing_joints.begin(), missing_joints.end());
      const std::vector<std::string> &names= jmg->getJointModelNames();
      bool ok = true;
      for (std::size_t i = 0 ; ok && i < names.size() ; ++i)
        if (mj.find(names[i]) != mj.end())
          ok = false;
    }
    else
      ok = false;
  }
  return ok;
}

void planning_scene_monitor::CurrentStateMonitor::jointStateCallback(const sensor_msgs::JointStateConstPtr &joint_state)
{
  if (joint_state->name.size() != joint_state->position.size())
  {
    ROS_ERROR_THROTTLE(1, "State monitor received invalid joint state (number of joint names does not match number of positions)");
    return;
  }

  {
    boost::mutex::scoped_lock _(state_update_lock_);
    // read the received values, and update their time stamps
    std::size_t n = joint_state->name.size();
    current_state_time_ = joint_state->header.stamp;
    for (std::size_t i = 0 ; i < n ; ++i)
    {
      const robot_model::JointModel* jm = robot_model_->getJointModel(joint_state->name[i]);
      if (!jm)
        continue;
      // ignore fixed joints, multi-dof joints (they should not even be in the message)
      if (jm->getVariableCount() != 1)
        continue;

      robot_state_.setJointPositions(jm, &(joint_state->position[i]));
      joint_time_[joint_state->name[i]] = joint_state->header.stamp;

      // continuous joints wrap, so we don't modify them (even if they are outside bounds!)
      if (jm->getType() == robot_model::JointModel::REVOLUTE)
        if (static_cast<const robot_model::RevoluteJointModel*>(jm)->isContinuous())
          continue;

      const robot_model::VariableBounds &b = jm->getVariableBounds()[0]; // only one variable in the joint, so we get its bounds

      // if the read variable is 'almost' within bounds (up to error_ difference), then consider it to be within bounds
      if (joint_state->position[i] < b.min_position_ && joint_state->position[i] >= b.min_position_ - error_)
        robot_state_.setJointPositions(jm, &b.min_position_);
      else
        if (joint_state->position[i] > b.max_position_ && joint_state->position[i] <= b.max_position_ + error_)
          robot_state_.setJointPositions(jm, &b.max_position_);
    }

    // read root transform, if needed
    if (tf_ && (robot_model_->getRootJoint()->getType() == robot_model::JointModel::PLANAR ||
                robot_model_->getRootJoint()->getType() == robot_model::JointModel::FLOATING))
    {
      const std::string &child_frame = robot_model_->getRootLink()->getName();
      const std::string &parent_frame = robot_model_->getModelFrame();

      std::string err;
      ros::Time tm;
      tf::StampedTransform transf;
      bool ok = false;
      if (tf_->getLatestCommonTime(parent_frame, child_frame, tm, &err) == tf::NO_ERROR)
      {
        try
        {
          tf_->lookupTransform(parent_frame, child_frame, tm, transf);
          ok = true;
        }
        catch(tf::TransformException& ex)
        {
          ROS_ERROR_THROTTLE(1, "Unable to lookup transform from %s to %s.  Exception: %s", parent_frame.c_str(), child_frame.c_str(), ex.what());
        }
      }
      else
        ROS_DEBUG_THROTTLE(1, "Unable to lookup transform from %s to %s: no common time.", parent_frame.c_str(), child_frame.c_str());
      if (ok)
      {
        const std::vector<std::string> &vars = robot_model_->getRootJoint()->getVariableNames();
        for (std::size_t j = 0; j < vars.size() ; ++j)
          joint_time_[vars[j]] = tm;
        Eigen::Affine3d eigen_transf;
        tf::transformTFToEigen(transf, eigen_transf);
        robot_state_.setJointPositions(robot_model_->getRootJoint(), eigen_transf);
      }
    }
  }

  // callbacks, if needed
  for (std::size_t i = 0 ; i < update_callbacks_.size() ; ++i)
    update_callbacks_[i](joint_state);
}
<|endoftext|>


<commit_before>/*****************************************************************************
 *
 * This file is part of Mapnik (c++ mapping toolkit)
 *
 * Copyright (C) 2014 Artem Pavlenko
 *
 * This library 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.1 of the License, or (at your option) any later version.
 *
 * 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., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
 *
 *****************************************************************************/

#ifndef MAPNIK_TIFF_IO_HPP
#define MAPNIK_TIFF_IO_HPP

#include <mapnik/global.hpp>
#include <mapnik/image_util.hpp>
#include <mapnik/image_data_any.hpp>
#include <mapnik/util/variant.hpp>

extern "C"
{
#include <tiffio.h>
#define RealTIFFOpen TIFFClientOpen
#define RealTIFFClose TIFFClose
}

namespace mapnik {

static inline tsize_t tiff_write_proc(thandle_t fd, tdata_t buf, tsize_t size)
{
    std::ostream* out = reinterpret_cast<std::ostream*>(fd);
    std::ios::pos_type pos = out->tellp();
    std::streamsize request_size = size;
    if (static_cast<tsize_t>(request_size) != size)
        return static_cast<tsize_t>(-1);
    out->write(reinterpret_cast<const char*>(buf), size);

    if( static_cast<std::streamsize>(pos) == -1 )
    {
        return size;
    }
    else
    {
        return static_cast<tsize_t>(out->tellp()-pos);
    }
}

static inline toff_t tiff_seek_proc(thandle_t fd, toff_t off, int whence)
{
    std::ostream* out = reinterpret_cast<std::ostream*>(fd);

    if( out->fail() )
        return static_cast<toff_t>(-1);

    if( static_cast<std::streamsize>(out->tellp()) == -1)
        return static_cast< toff_t >( 0 );

    switch(whence)
    {
    case SEEK_SET:
        out->seekp(off, std::ios_base::beg);
        break;
    case SEEK_CUR:
        out->seekp(off, std::ios_base::cur);
        break;
    case SEEK_END:
        out->seekp(off, std::ios_base::end);
        break;
    }
    // grow std::stringstream buffer (re: libtiff/tif_stream.cxx)
    std::ios::pos_type pos = out->tellp();
    // second check needed for clang (libcxx doesn't set failbit when seeking beyond the current buffer size

    if( out->fail() || static_cast<std::streamoff>(off) != pos)
    {
        std::ios::iostate old_state;
        std::ios::pos_type  origin;
        old_state = out->rdstate();
        // reset the fail bit or else tellp() won't work below
        out->clear(out->rdstate() & ~std::ios::failbit);
        switch( whence )
        {
        case SEEK_SET:
        default:
            origin = 0L;
            break;
        case SEEK_CUR:
            origin = out->tellp();
            break;
        case SEEK_END:
            out->seekp(0, std::ios::end);
            origin = out->tellp();
            break;
        }
        // restore original stream state
        out->clear(old_state);

        // only do something if desired seek position is valid
        if( (static_cast<uint64_t>(origin) + off) > 0L)
        {
            uint64_t num_fill;
            // clear the fail bit
            out->clear(out->rdstate() & ~std::ios::failbit);
            // extend the stream to the expected size
            out->seekp(0, std::ios::end);
            num_fill = (static_cast<uint64_t>(origin)) + off - out->tellp();
            for( uint64_t i = 0; i < num_fill; ++i)
                out->put('\0');

            // retry the seek
            out->seekp(static_cast<std::ios::off_type>(static_cast<uint64_t>(origin) + off), std::ios::beg);
        }
    }
    return static_cast<toff_t>(out->tellp());
}

static inline int tiff_close_proc(thandle_t fd)
{
    std::ostream* out = (std::ostream*)fd;
    out->flush();
    return 0;
}

static inline toff_t tiff_size_proc(thandle_t fd)
{
    std::ostream* out = reinterpret_cast<std::ostream*>(fd);
    std::ios::pos_type pos = out->tellp();
    out->seekp(0, std::ios::end);
    std::ios::pos_type len = out->tellp();
    out->seekp(pos);
    return static_cast<toff_t>(len);
}

static inline tsize_t tiff_dummy_read_proc(thandle_t , tdata_t , tsize_t)
{
    return 0;
}

static inline void tiff_dummy_unmap_proc(thandle_t , tdata_t , toff_t) {}

static inline int tiff_dummy_map_proc(thandle_t , tdata_t*, toff_t* )
{
    return 0;
}

struct tiff_config
{
    tiff_config()
        : compression(COMPRESSION_ADOBE_DEFLATE),
        zlevel(4),
        scanline(false) {}

    int compression;
    int zlevel;
    bool scanline;
};

struct tag_setter : public mapnik::util::static_visitor<>
{
    tag_setter(TIFF * output, tiff_config & config)
        : output_(output),
          config_(config) {}

    template <typename T>
    void operator() (T const&) const
    {
        // Assume this would be null type
        throw ImageWriterException("Could not write TIFF - unknown image type provided");
    }

    inline void operator() (image_data_rgba8 const&) const
    {
        TIFFSetField(output_, TIFFTAG_PHOTOMETRIC, PHOTOMETRIC_RGB);
        TIFFSetField(output_, TIFFTAG_SAMPLEFORMAT, SAMPLEFORMAT_UINT);
        TIFFSetField(output_, TIFFTAG_BITSPERSAMPLE, 8);
        TIFFSetField(output_, TIFFTAG_SAMPLESPERPIXEL, 4);
        uint16 extras[] = { EXTRASAMPLE_UNASSALPHA };
        TIFFSetField(output_, TIFFTAG_EXTRASAMPLES, 1, extras);
        if (config_.compression == COMPRESSION_DEFLATE
                || config_.compression == COMPRESSION_ADOBE_DEFLATE
                || config_.compression == COMPRESSION_LZW)
        {
            TIFFSetField(output_, TIFFTAG_PREDICTOR, PREDICTOR_HORIZONTAL);

        }
    }
    inline void operator() (image_data_gray32f const&) const
    {
        TIFFSetField(output_, TIFFTAG_PHOTOMETRIC, PHOTOMETRIC_MINISBLACK);
        TIFFSetField(output_, TIFFTAG_SAMPLEFORMAT, SAMPLEFORMAT_IEEEFP);
        TIFFSetField(output_, TIFFTAG_BITSPERSAMPLE, 32);
        TIFFSetField(output_, TIFFTAG_SAMPLESPERPIXEL, 1);
        if (config_.compression == COMPRESSION_DEFLATE
                || config_.compression == COMPRESSION_ADOBE_DEFLATE
                || config_.compression == COMPRESSION_LZW)
        {
            TIFFSetField(output_, TIFFTAG_PREDICTOR, PREDICTOR_FLOATINGPOINT);
        }
    }
    inline void operator() (image_data_gray16 const&) const
    {
        TIFFSetField(output_, TIFFTAG_PHOTOMETRIC, PHOTOMETRIC_MINISBLACK);
        TIFFSetField(output_, TIFFTAG_SAMPLEFORMAT, SAMPLEFORMAT_UINT);
        TIFFSetField(output_, TIFFTAG_BITSPERSAMPLE, 16);
        TIFFSetField(output_, TIFFTAG_SAMPLESPERPIXEL, 1);
        if (config_.compression == COMPRESSION_DEFLATE
                || config_.compression == COMPRESSION_ADOBE_DEFLATE
                || config_.compression == COMPRESSION_LZW)
        {
            TIFFSetField(output_, TIFFTAG_PREDICTOR, PREDICTOR_HORIZONTAL);

        }
    }
    inline void operator() (image_data_gray8 const&) const
    {
        TIFFSetField(output_, TIFFTAG_PHOTOMETRIC, PHOTOMETRIC_MINISBLACK);
        TIFFSetField(output_, TIFFTAG_SAMPLEFORMAT, SAMPLEFORMAT_UINT);
        TIFFSetField(output_, TIFFTAG_BITSPERSAMPLE, 8);
        TIFFSetField(output_, TIFFTAG_SAMPLESPERPIXEL, 1);
        if (config_.compression == COMPRESSION_DEFLATE
                || config_.compression == COMPRESSION_ADOBE_DEFLATE
                || config_.compression == COMPRESSION_LZW)
        {
            TIFFSetField(output_, TIFFTAG_PREDICTOR, PREDICTOR_HORIZONTAL);

        }
    }
    inline void operator() (image_data_null const&) const
    {
        // Assume this would be null type
        throw ImageWriterException("Could not write TIFF - Null image provided");
    }

    private:
        TIFF * output_;
        tiff_config config_;
};

void set_tiff_config(TIFF* output, tiff_config & config)
{
    // Set some constant tiff information that doesn't vary based on type of data
    // or image size
    TIFFSetField(output, TIFFTAG_PLANARCONFIG, PLANARCONFIG_CONTIG);

    // Set the compression for the TIFF
    TIFFSetField(output, TIFFTAG_COMPRESSION, config.compression);

    if (COMPRESSION_ADOBE_DEFLATE == config.compression || COMPRESSION_DEFLATE == config.compression)
    {
        // Set the zip level for the compression
        // http://en.wikipedia.org/wiki/DEFLATE#Encoder.2Fcompressor
        // Changes the time spent trying to compress
        TIFFSetField(output, TIFFTAG_ZIPQUALITY, config.zlevel);
    }
}

template <typename T1, typename T2>
void save_as_tiff(T1 & file, T2 const& image, tiff_config & config)
{
    using pixel_type = typename T2::pixel_type;

    const int width = image.width();
    const int height = image.height();

    TIFF* output = RealTIFFOpen("mapnik_tiff_stream",
                                "wm",
                                (thandle_t)&file,
                                tiff_dummy_read_proc,
                                tiff_write_proc,
                                tiff_seek_proc,
                                tiff_close_proc,
                                tiff_size_proc,
                                tiff_dummy_map_proc,
                                tiff_dummy_unmap_proc);
    if (! output)
    {
        throw ImageWriterException("Could not write TIFF");
    }

    TIFFSetField(output, TIFFTAG_IMAGEWIDTH, width);
    TIFFSetField(output, TIFFTAG_IMAGELENGTH, height);
    TIFFSetField(output, TIFFTAG_IMAGEDEPTH, 1);

    set_tiff_config(output, config);

    // Set tags that vary based on the type of data being provided.
    tag_setter set(output, config);
    set(image);
    //util::apply_visitor(set, image);

    // If the image is greater then 8MB uncompressed, then lets use scanline rather then
    // tile. TIFF also requires that all TIFFTAG_TILEWIDTH and TIFF_TILELENGTH all be
    // a multiple of 16, if they are not we will use scanline.
    if (image.getSize() > 8 * 32 * 1024 * 1024
            || width % 16 != 0
            || height % 16 != 0
            || config.scanline)
    {
        // Process Scanline
        TIFFSetField(output, TIFFTAG_ROWSPERSTRIP, 1);

        int next_scanline = 0;
        std::unique_ptr<pixel_type[]> row (new pixel_type[image.getRowSize()]);
        while (next_scanline < height)
        {
            memcpy(row.get(), image.getRow(next_scanline), image.getRowSize());
            //typename T2::pixel_type * row = const_cast<typename T2::pixel_type *>(image.getRow(next_scanline));
            TIFFWriteScanline(output, row.get(), next_scanline, 0);
            ++next_scanline;
        }
    }
    else
    {
        TIFFSetField(output, TIFFTAG_TILEWIDTH, width);
        TIFFSetField(output, TIFFTAG_TILELENGTH, height);
        TIFFSetField(output, TIFFTAG_TILEDEPTH, 1);
        // Process as tiles
        std::unique_ptr<pixel_type[]> image_data (new pixel_type[image.getSize()]);
        memcpy(image_data.get(), image.getData(), image.getSize());
        //typename T2::pixel_type * image_data = const_cast<typename T2::pixel_type *>(image.getData());
        TIFFWriteTile(output, image_data.get(), 0, 0, 0, 0);
    }
    // TODO - handle palette images
    // std::vector<mapnik::rgb> const& palette

    //  unsigned short r[256], g[256], b[256];
    //  for (int i = 0; i < (1 << 24); ++i)
    //  {
    //  r[i] = (unsigned short)palette[i * 3 + 0] << 8;
    //  g[i] = (unsigned short)palette[i * 3 + 1] << 8;
    //  b[i] = (unsigned short)palette[i * 3 + 2] << 8;
    //  }
    //  TIFFSetField(output, TIFFTAG_PHOTOMETRIC, PHOTOMETRIC_PALETTE);
    //  TIFFSetField(output, TIFFTAG_COLORMAP, r, g, b);

    RealTIFFClose(output);
}

}

#endif // MAPNIK_TIFF_IO_HPP
<commit_msg>correct alloc size + prefer std::copy over memcpy<commit_after>/*****************************************************************************
 *
 * This file is part of Mapnik (c++ mapping toolkit)
 *
 * Copyright (C) 2014 Artem Pavlenko
 *
 * This library 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.1 of the License, or (at your option) any later version.
 *
 * 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., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
 *
 *****************************************************************************/

#ifndef MAPNIK_TIFF_IO_HPP
#define MAPNIK_TIFF_IO_HPP

#include <mapnik/global.hpp>
#include <mapnik/image_util.hpp>
#include <mapnik/image_data_any.hpp>
#include <mapnik/util/variant.hpp>

extern "C"
{
#include <tiffio.h>
#define RealTIFFOpen TIFFClientOpen
#define RealTIFFClose TIFFClose
}

namespace mapnik {

static inline tsize_t tiff_write_proc(thandle_t fd, tdata_t buf, tsize_t size)
{
    std::ostream* out = reinterpret_cast<std::ostream*>(fd);
    std::ios::pos_type pos = out->tellp();
    std::streamsize request_size = size;
    if (static_cast<tsize_t>(request_size) != size)
        return static_cast<tsize_t>(-1);
    out->write(reinterpret_cast<const char*>(buf), size);

    if( static_cast<std::streamsize>(pos) == -1 )
    {
        return size;
    }
    else
    {
        return static_cast<tsize_t>(out->tellp()-pos);
    }
}

static inline toff_t tiff_seek_proc(thandle_t fd, toff_t off, int whence)
{
    std::ostream* out = reinterpret_cast<std::ostream*>(fd);

    if( out->fail() )
        return static_cast<toff_t>(-1);

    if( static_cast<std::streamsize>(out->tellp()) == -1)
        return static_cast< toff_t >( 0 );

    switch(whence)
    {
    case SEEK_SET:
        out->seekp(off, std::ios_base::beg);
        break;
    case SEEK_CUR:
        out->seekp(off, std::ios_base::cur);
        break;
    case SEEK_END:
        out->seekp(off, std::ios_base::end);
        break;
    }
    // grow std::stringstream buffer (re: libtiff/tif_stream.cxx)
    std::ios::pos_type pos = out->tellp();
    // second check needed for clang (libcxx doesn't set failbit when seeking beyond the current buffer size

    if( out->fail() || static_cast<std::streamoff>(off) != pos)
    {
        std::ios::iostate old_state;
        std::ios::pos_type  origin;
        old_state = out->rdstate();
        // reset the fail bit or else tellp() won't work below
        out->clear(out->rdstate() & ~std::ios::failbit);
        switch( whence )
        {
        case SEEK_SET:
        default:
            origin = 0L;
            break;
        case SEEK_CUR:
            origin = out->tellp();
            break;
        case SEEK_END:
            out->seekp(0, std::ios::end);
            origin = out->tellp();
            break;
        }
        // restore original stream state
        out->clear(old_state);

        // only do something if desired seek position is valid
        if( (static_cast<uint64_t>(origin) + off) > 0L)
        {
            uint64_t num_fill;
            // clear the fail bit
            out->clear(out->rdstate() & ~std::ios::failbit);
            // extend the stream to the expected size
            out->seekp(0, std::ios::end);
            num_fill = (static_cast<uint64_t>(origin)) + off - out->tellp();
            for( uint64_t i = 0; i < num_fill; ++i)
                out->put('\0');

            // retry the seek
            out->seekp(static_cast<std::ios::off_type>(static_cast<uint64_t>(origin) + off), std::ios::beg);
        }
    }
    return static_cast<toff_t>(out->tellp());
}

static inline int tiff_close_proc(thandle_t fd)
{
    std::ostream* out = (std::ostream*)fd;
    out->flush();
    return 0;
}

static inline toff_t tiff_size_proc(thandle_t fd)
{
    std::ostream* out = reinterpret_cast<std::ostream*>(fd);
    std::ios::pos_type pos = out->tellp();
    out->seekp(0, std::ios::end);
    std::ios::pos_type len = out->tellp();
    out->seekp(pos);
    return static_cast<toff_t>(len);
}

static inline tsize_t tiff_dummy_read_proc(thandle_t , tdata_t , tsize_t)
{
    return 0;
}

static inline void tiff_dummy_unmap_proc(thandle_t , tdata_t , toff_t) {}

static inline int tiff_dummy_map_proc(thandle_t , tdata_t*, toff_t* )
{
    return 0;
}

struct tiff_config
{
    tiff_config()
        : compression(COMPRESSION_ADOBE_DEFLATE),
        zlevel(4),
        scanline(false) {}

    int compression;
    int zlevel;
    bool scanline;
};

struct tag_setter : public mapnik::util::static_visitor<>
{
    tag_setter(TIFF * output, tiff_config & config)
        : output_(output),
          config_(config) {}

    template <typename T>
    void operator() (T const&) const
    {
        // Assume this would be null type
        throw ImageWriterException("Could not write TIFF - unknown image type provided");
    }

    inline void operator() (image_data_rgba8 const&) const
    {
        TIFFSetField(output_, TIFFTAG_PHOTOMETRIC, PHOTOMETRIC_RGB);
        TIFFSetField(output_, TIFFTAG_SAMPLEFORMAT, SAMPLEFORMAT_UINT);
        TIFFSetField(output_, TIFFTAG_BITSPERSAMPLE, 8);
        TIFFSetField(output_, TIFFTAG_SAMPLESPERPIXEL, 4);
        uint16 extras[] = { EXTRASAMPLE_UNASSALPHA };
        TIFFSetField(output_, TIFFTAG_EXTRASAMPLES, 1, extras);
        if (config_.compression == COMPRESSION_DEFLATE
                || config_.compression == COMPRESSION_ADOBE_DEFLATE
                || config_.compression == COMPRESSION_LZW)
        {
            TIFFSetField(output_, TIFFTAG_PREDICTOR, PREDICTOR_HORIZONTAL);

        }
    }
    inline void operator() (image_data_gray32f const&) const
    {
        TIFFSetField(output_, TIFFTAG_PHOTOMETRIC, PHOTOMETRIC_MINISBLACK);
        TIFFSetField(output_, TIFFTAG_SAMPLEFORMAT, SAMPLEFORMAT_IEEEFP);
        TIFFSetField(output_, TIFFTAG_BITSPERSAMPLE, 32);
        TIFFSetField(output_, TIFFTAG_SAMPLESPERPIXEL, 1);
        if (config_.compression == COMPRESSION_DEFLATE
                || config_.compression == COMPRESSION_ADOBE_DEFLATE
                || config_.compression == COMPRESSION_LZW)
        {
            TIFFSetField(output_, TIFFTAG_PREDICTOR, PREDICTOR_FLOATINGPOINT);
        }
    }
    inline void operator() (image_data_gray16 const&) const
    {
        TIFFSetField(output_, TIFFTAG_PHOTOMETRIC, PHOTOMETRIC_MINISBLACK);
        TIFFSetField(output_, TIFFTAG_SAMPLEFORMAT, SAMPLEFORMAT_UINT);
        TIFFSetField(output_, TIFFTAG_BITSPERSAMPLE, 16);
        TIFFSetField(output_, TIFFTAG_SAMPLESPERPIXEL, 1);
        if (config_.compression == COMPRESSION_DEFLATE
                || config_.compression == COMPRESSION_ADOBE_DEFLATE
                || config_.compression == COMPRESSION_LZW)
        {
            TIFFSetField(output_, TIFFTAG_PREDICTOR, PREDICTOR_HORIZONTAL);

        }
    }
    inline void operator() (image_data_gray8 const&) const
    {
        TIFFSetField(output_, TIFFTAG_PHOTOMETRIC, PHOTOMETRIC_MINISBLACK);
        TIFFSetField(output_, TIFFTAG_SAMPLEFORMAT, SAMPLEFORMAT_UINT);
        TIFFSetField(output_, TIFFTAG_BITSPERSAMPLE, 8);
        TIFFSetField(output_, TIFFTAG_SAMPLESPERPIXEL, 1);
        if (config_.compression == COMPRESSION_DEFLATE
                || config_.compression == COMPRESSION_ADOBE_DEFLATE
                || config_.compression == COMPRESSION_LZW)
        {
            TIFFSetField(output_, TIFFTAG_PREDICTOR, PREDICTOR_HORIZONTAL);

        }
    }
    inline void operator() (image_data_null const&) const
    {
        // Assume this would be null type
        throw ImageWriterException("Could not write TIFF - Null image provided");
    }

    private:
        TIFF * output_;
        tiff_config config_;
};

void set_tiff_config(TIFF* output, tiff_config & config)
{
    // Set some constant tiff information that doesn't vary based on type of data
    // or image size
    TIFFSetField(output, TIFFTAG_PLANARCONFIG, PLANARCONFIG_CONTIG);

    // Set the compression for the TIFF
    TIFFSetField(output, TIFFTAG_COMPRESSION, config.compression);

    if (COMPRESSION_ADOBE_DEFLATE == config.compression || COMPRESSION_DEFLATE == config.compression)
    {
        // Set the zip level for the compression
        // http://en.wikipedia.org/wiki/DEFLATE#Encoder.2Fcompressor
        // Changes the time spent trying to compress
        TIFFSetField(output, TIFFTAG_ZIPQUALITY, config.zlevel);
    }
}

template <typename T1, typename T2>
void save_as_tiff(T1 & file, T2 const& image, tiff_config & config)
{
    using pixel_type = typename T2::pixel_type;

    const int width = image.width();
    const int height = image.height();

    TIFF* output = RealTIFFOpen("mapnik_tiff_stream",
                                "wm",
                                (thandle_t)&file,
                                tiff_dummy_read_proc,
                                tiff_write_proc,
                                tiff_seek_proc,
                                tiff_close_proc,
                                tiff_size_proc,
                                tiff_dummy_map_proc,
                                tiff_dummy_unmap_proc);
    if (! output)
    {
        throw ImageWriterException("Could not write TIFF");
    }

    TIFFSetField(output, TIFFTAG_IMAGEWIDTH, width);
    TIFFSetField(output, TIFFTAG_IMAGELENGTH, height);
    TIFFSetField(output, TIFFTAG_IMAGEDEPTH, 1);

    set_tiff_config(output, config);

    // Set tags that vary based on the type of data being provided.
    tag_setter set(output, config);
    set(image);
    //util::apply_visitor(set, image);

    // If the image is greater then 8MB uncompressed, then lets use scanline rather then
    // tile. TIFF also requires that all TIFFTAG_TILEWIDTH and TIFF_TILELENGTH all be
    // a multiple of 16, if they are not we will use scanline.
    if (image.getSize() > 8 * 32 * 1024 * 1024
            || width % 16 != 0
            || height % 16 != 0
            || config.scanline)
    {
        // Process Scanline
        TIFFSetField(output, TIFFTAG_ROWSPERSTRIP, 1);

        int next_scanline = 0;
        std::unique_ptr<pixel_type[]> row (new pixel_type[image.width()]);
        while (next_scanline < height)
        {
            std::copy(image.getRow(next_scanline), image.getRow(next_scanline) + image.width(), row.get());
            //typename T2::pixel_type * row = const_cast<typename T2::pixel_type *>(image.getRow(next_scanline));
            TIFFWriteScanline(output, row.get(), next_scanline, 0);
            ++next_scanline;
        }
    }
    else
    {
        TIFFSetField(output, TIFFTAG_TILEWIDTH, width);
        TIFFSetField(output, TIFFTAG_TILELENGTH, height);
        TIFFSetField(output, TIFFTAG_TILEDEPTH, 1);
        // Process as tiles
        std::size_t tile_size = width * height;
        pixel_type const * image_data_in = image.getData();
        std::unique_ptr<pixel_type[]> image_data_out (new pixel_type[tile_size]);
        std::copy(image_data_in, image_data_in + tile_size, image_data_out.get());
        //typename T2::pixel_type * image_data = const_cast<typename T2::pixel_type *>(image.getData());
        TIFFWriteTile(output, image_data_out.get(), 0, 0, 0, 0);
    }
    // TODO - handle palette images
    // std::vector<mapnik::rgb> const& palette

    //  unsigned short r[256], g[256], b[256];
    //  for (int i = 0; i < (1 << 24); ++i)
    //  {
    //  r[i] = (unsigned short)palette[i * 3 + 0] << 8;
    //  g[i] = (unsigned short)palette[i * 3 + 1] << 8;
    //  b[i] = (unsigned short)palette[i * 3 + 2] << 8;
    //  }
    //  TIFFSetField(output, TIFFTAG_PHOTOMETRIC, PHOTOMETRIC_PALETTE);
    //  TIFFSetField(output, TIFFTAG_COLORMAP, r, g, b);

    RealTIFFClose(output);
}

}

#endif // MAPNIK_TIFF_IO_HPP
<|endoftext|>


<commit_before>/*****************************************************************************
 *
 * This file is part of Mapnik (c++ mapping toolkit)
 *
 * Copyright (C) 2011 Artem Pavlenko
 *
 * This library 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.1 of the License, or (at your option) any later version.
 *
 * 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., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
 *
 *****************************************************************************/

#ifndef MAPNIK_VERSION_HPP
#define MAPNIK_VERSION_HPP

#define MAPNIK_VERSION_IS_RELEASE 0

#define MAPNIK_MAJOR_VERSION 2
#define MAPNIK_MINOR_VERSION 3
#define MAPNIK_PATCH_VERSION 0

// translates to 300000
#define MAPNIK_VERSION (MAPNIK_MAJOR_VERSION*100000) + (MAPNIK_MINOR_VERSION*100) + (MAPNIK_PATCH_VERSION)

#ifndef MAPNIK_STRINGIFY
#define MAPNIK_STRINGIFY(n) MAPNIK_STRINGIFY_HELPER(n)
#define MAPNIK_STRINGIFY_HELPER(n) #n
#endif

#if MAPNIK_VERSION_IS_RELEASE
#define MAPNIK_VERSION_STRING   MAPNIK_STRINGIFY(MAPNIK_MAJOR_VERSION) "." \
                                MAPNIK_STRINGIFY(MAPNIK_MINOR_VERSION) "." \
                                MAPNIK_STRINGIFY(MAPNIK_PATCH_VERSION)

#else
#define MAPNIK_VERSION_STRING   MAPNIK_STRINGIFY(MAPNIK_MAJOR_VERSION) "." \
                                MAPNIK_STRINGIFY(MAPNIK_MINOR_VERSION) "." \
                                MAPNIK_STRINGIFY(MAPNIK_PATCH_VERSION) "-pre"
#endif

#endif // MAPNIK_VERSION_HPP
<commit_msg>fix version in code comment<commit_after>/*****************************************************************************
 *
 * This file is part of Mapnik (c++ mapping toolkit)
 *
 * Copyright (C) 2011 Artem Pavlenko
 *
 * This library 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.1 of the License, or (at your option) any later version.
 *
 * 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., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
 *
 *****************************************************************************/

#ifndef MAPNIK_VERSION_HPP
#define MAPNIK_VERSION_HPP

#define MAPNIK_VERSION_IS_RELEASE 0

#define MAPNIK_MAJOR_VERSION 2
#define MAPNIK_MINOR_VERSION 3
#define MAPNIK_PATCH_VERSION 0

// translates to 200300
#define MAPNIK_VERSION (MAPNIK_MAJOR_VERSION*100000) + (MAPNIK_MINOR_VERSION*100) + (MAPNIK_PATCH_VERSION)

#ifndef MAPNIK_STRINGIFY
#define MAPNIK_STRINGIFY(n) MAPNIK_STRINGIFY_HELPER(n)
#define MAPNIK_STRINGIFY_HELPER(n) #n
#endif

#if MAPNIK_VERSION_IS_RELEASE
#define MAPNIK_VERSION_STRING   MAPNIK_STRINGIFY(MAPNIK_MAJOR_VERSION) "." \
                                MAPNIK_STRINGIFY(MAPNIK_MINOR_VERSION) "." \
                                MAPNIK_STRINGIFY(MAPNIK_PATCH_VERSION)

#else
#define MAPNIK_VERSION_STRING   MAPNIK_STRINGIFY(MAPNIK_MAJOR_VERSION) "." \
                                MAPNIK_STRINGIFY(MAPNIK_MINOR_VERSION) "." \
                                MAPNIK_STRINGIFY(MAPNIK_PATCH_VERSION) "-pre"
#endif

#endif // MAPNIK_VERSION_HPP
<|endoftext|>


<commit_before>//Create by Christine Nattrass, Rebecca Scott, Irakli Martashvili
//University of Tennessee at Knoxville

//by default this runs locally
//With the argument true this submits jobs to the grid
//As written this requires an xml script tag.xml in the ~/et directory on the grid to submit jobs
void runHadEt(bool submit = false, bool data = false, bool PbPb = true) {
    TStopwatch timer;
    timer.Start();
    gSystem->Load("libTree.so");
    gSystem->Load("libGeom.so");
    gSystem->Load("libVMC.so");
    gSystem->Load("libXMLIO.so");

    gSystem->Load("libSTEERBase.so");
    gSystem->Load("libESD.so");
    gSystem->Load("libAOD.so");

    gSystem->Load("libANALYSIS");
    gSystem->Load("libANALYSISalice");

    gSystem->AddIncludePath("-I$ALICE_ROOT/include");
   gROOT->ProcessLine(".L AliAnalysisEtCuts.cxx+g");
   gROOT->ProcessLine(".L AliAnalysisHadEtCorrections.cxx+g");
   gROOT->ProcessLine(".L AliAnalysisEtCommon.cxx+g");
   gROOT->ProcessLine(".L AliAnalysisHadEt.cxx+g");
   gROOT->ProcessLine(".L AliAnalysisHadEtMonteCarlo.cxx+g");
   gROOT->ProcessLine(".L AliAnalysisHadEtReconstructed.cxx+g");
   gROOT->ProcessLine(".L AliAnalysisEtSelectionContainer.cxx+g");
   gROOT->ProcessLine(".L AliAnalysisEtSelectionHandler.cxx+g");
   gROOT->ProcessLine(".L AliAnalysisTaskTransverseEnergy.cxx+g");
   gROOT->ProcessLine(".L AliAnalysisTaskHadEt.cxx+g");

  char *kTreeName = "esdTree" ;
  TChain * chain   = new TChain(kTreeName,"myESDTree") ;
  if(submit){
    gSystem->Load("libNetx.so") ;
    gSystem->Load("libgapiUI.so");
    gSystem->Load("libRAliEn.so");
    TGrid::Connect("alien://") ;
  }
  chain->Add("/data/LHC10h8/137161/999/AliESDs.root");//Hijing Pb+Pb
  //chain->Add("/data/LHC11a4_bis/137161/999/AliESDs.root");//Hijing Pb+Pb
  //chain->Add("/data/LHC10h12/999/AliESDs.root");//Hijing Pb+Pb
  //chain->Add("/data/LHC10d15/1821/AliESDs.root");//simulation p+p
  //chain->Add("/data/LHC10dpass2/10000126403050.70/AliESDs.root");//data

  // Make the analysis manager
  AliAnalysisManager *mgr = new AliAnalysisManager("TotEtManager");
  if(submit){
    if(PbPb){
      gROOT->LoadMacro("CreateAlienHandlerHadEtSimPbPb.C");
      AliAnalysisGrid *alienHandler = CreateAlienHandlerHadEtSimPbPb();
    }
    else{
      gROOT->LoadMacro("CreateAlienHandlerHadEtSim.C");
      AliAnalysisGrid *alienHandler = CreateAlienHandlerHadEtSim();
    }
    if (!alienHandler) return;
    mgr->SetGridHandler(alienHandler);
  }

  AliVEventHandler* esdH = new AliESDInputHandler;
  mgr->SetInputEventHandler(esdH);
  AliMCEventHandler* handler = new AliMCEventHandler;
  if(!data){
    handler->SetReadTR(kFALSE);
    mgr->SetMCtruthEventHandler(handler);
  }

  AliAnalysisDataContainer *cinput1 = mgr->GetCommonInputContainer();

  bool isMc = true;
  if(data) isMC = false;
  gROOT->LoadMacro("$ALICE_ROOT/ANALYSIS/macros/AddTaskPhysicsSelection.C");
  AliPhysicsSelectionTask *physSelTask = AddTaskPhysicsSelection(isMc);
  gROOT->LoadMacro("$ALICE_ROOT/ANALYSIS/macros/AddTaskCentrality.C");

  AliCentralitySelectionTask *centTask;

  if(PbPb){
    AliCentralitySelectionTask *centTask = AddTaskCentrality();
   if(isMc){
     cout<<"Setting up centrality for MC"<<endl;
     centTask->SetMCInput();
   }
  }

    AliAnalysisTaskHadEt *task2 = new AliAnalysisTaskHadEt("TaskHadEt");
    if(isMc) task2->SetMcData();
    mgr->AddTask(task2);
  AliAnalysisDataContainer *coutput2 = mgr->CreateContainer("out2", TList::Class(), AliAnalysisManager::kOutputContainer,"Et.ESD.new.sim.root");
  mgr->ConnectInput(task2,0,cinput1);
  mgr->ConnectOutput(task2,1,coutput2);

  mgr->SetDebugLevel(0);

  if (!mgr->InitAnalysis()) return;
  mgr->PrintStatus();
  if(submit){
    mgr->StartAnalysis("grid");
  }
  else{
    mgr->StartAnalysis("local",chain);
  }

  timer.Stop();
  timer.Print();
}
<commit_msg>Adding options to pass macros for running different jobs<commit_after>//Create by Christine Nattrass, Rebecca Scott, Irakli Martashvili
//University of Tennessee at Knoxville

//by default this runs locally
//With the argument true this submits jobs to the grid
//As written this requires an xml script tag.xml in the ~/et directory on the grid to submit jobs
void runHadEt(bool submit = false, bool data = false, Int_t dataset = 20100, Bool_t test = kTRUE) {
    TStopwatch timer;
    timer.Start();
    gSystem->Load("libTree.so");
    gSystem->Load("libGeom.so");
    gSystem->Load("libVMC.so");
    gSystem->Load("libXMLIO.so");

    gSystem->Load("libSTEERBase.so");
    gSystem->Load("libESD.so");
    gSystem->Load("libAOD.so");

    gSystem->Load("libANALYSIS");
    gSystem->Load("libANALYSISalice");

    gSystem->AddIncludePath("-I$ALICE_ROOT/include");
   gROOT->ProcessLine(".L AliAnalysisEtCuts.cxx+g");
   gROOT->ProcessLine(".L AliAnalysisHadEtCorrections.cxx+g");
   gROOT->ProcessLine(".L AliAnalysisEtCommon.cxx+g");
   gROOT->ProcessLine(".L AliAnalysisHadEt.cxx+g");
   gROOT->ProcessLine(".L AliAnalysisHadEtMonteCarlo.cxx+g");
   gROOT->ProcessLine(".L AliAnalysisHadEtReconstructed.cxx+g");
   gROOT->ProcessLine(".L AliAnalysisEtSelectionContainer.cxx+g");
   gROOT->ProcessLine(".L AliAnalysisEtSelectionHandler.cxx+g");
   gROOT->ProcessLine(".L AliAnalysisTaskTransverseEnergy.cxx+g");
   gROOT->ProcessLine(".L AliAnalysisTaskHadEt.cxx+g");

  char *kTreeName = "esdTree" ;
  TChain * chain   = new TChain(kTreeName,"myESDTree") ;
  if(submit){
    gSystem->Load("libNetx.so") ;
    gSystem->Load("libgapiUI.so");
    gSystem->Load("libRAliEn.so");
    TGrid::Connect("alien://") ;
  }
  bool PbPb = false;
  if(dataset ==20100){
    bool PbPb = true;
    if(data){
      chain->Add("/data/LHC10h/pass2_rev15/10000137366041.860/AliESDs.root");//Data Pb+Pb
      chain->Add("/data/LHC10h/pass2_rev15/10000137366041.870/AliESDs.root");//Data Pb+Pb
      chain->Add("/data/LHC10h/pass2_rev15/10000137366041.880/AliESDs.root");//Data Pb+Pb
      chain->Add("/data/LHC10h/pass2_rev15/10000137366041.890/AliESDs.root");//Data Pb+Pb
      chain->Add("/data/LHC10h/pass2_rev15/10000137366041.900/AliESDs.root");//Data Pb+Pb
    }
    else{
      chain->Add("/data/LHC10h8/137161/999/AliESDs.root");//Hijing Pb+Pb
      chain->Add("/data/LHC10h8/137161/111/AliESDs.root");//Hijing Pb+Pb
      chain->Add("/data/LHC10h8/137161/222/AliESDs.root");//Hijing Pb+Pb
      //chain->Add("/data/LHC11a4_bis/137161/999/AliESDs.root");//Hijing Pb+Pb
      //chain->Add("/data/LHC10h12/999/AliESDs.root");//Hijing Pb+Pb
    }
  }
  else{
    if(data){
      chain->Add("/data/LHC10dpass2/10000126403050.70/AliESDs.root");//data
    }
    else{
      chain->Add("/data/LHC10d15/1821/AliESDs.root");//simulation p+p
    }
  }

  // Make the analysis manager
  AliAnalysisManager *mgr = new AliAnalysisManager("TotEtManager");
  if(submit){
      gROOT->LoadMacro("CreateAlienHandlerHadEt.C");
      AliAnalysisGrid *alienHandler = CreateAlienHandlerHadEt(dataset,data,test);//integer dataset, boolean isData, bool submit-in-test-mode
      if (!alienHandler) return;
      mgr->SetGridHandler(alienHandler);
  }

  AliVEventHandler* esdH = new AliESDInputHandler;
  mgr->SetInputEventHandler(esdH);
  AliMCEventHandler* handler = new AliMCEventHandler;
  if(!data){
    handler->SetReadTR(kFALSE);
    mgr->SetMCtruthEventHandler(handler);
  }

  AliAnalysisDataContainer *cinput1 = mgr->GetCommonInputContainer();

  gROOT->LoadMacro("$ALICE_ROOT/ANALYSIS/macros/AddTaskPhysicsSelection.C");
  AliPhysicsSelectionTask *physSelTask = AddTaskPhysicsSelection(!data);
  gROOT->LoadMacro("$ALICE_ROOT/ANALYSIS/macros/AddTaskCentrality.C");

  AliCentralitySelectionTask *centTask;

  if(PbPb){
    AliCentralitySelectionTask *centTask = AddTaskCentrality();
   if(!data){
     cout<<"Setting up centrality for MC"<<endl;
     centTask->SetMCInput();
   }
   else{
     cout<<"Setting up centrality for data"<<endl;
   }
  }

   if(dataset==20100){//PbPb 2.76 TeV
     if(data){gSystem->CopyFile("rootFiles/corrections/corrections.LHC11a4_bis.PbPb.ForData.root","corrections.root",kTRUE);}
     else{gSystem->CopyFile("rootFiles/corrections/corrections.LHC11a4_bis.PbPb.ForSimulations.root","corrections.root",kTRUE);}
   }
   else{
     if(dataset==2009){//pp 900 GeV
       cout<<"Warning! You are using 7 TeV corrections for 900 GeV data!"<<endl;}
     if(dataset==20111){//pp 2.76 TeV
       cout<<"Warning! You are using 7 TeV corrections for 2.76eV data!"<<endl;}
     if(data){gSystem->CopyFile("rootFiles/corrections/corrections.LHC10d4.pp.ForData.root","corrections.root",kTRUE);}
     else{gSystem->CopyFile("rootFiles/corrections/corrections.LHC10d4.pp.ForSimulations.root","corrections.root",kTRUE);}
   }
   TString recoFile;
   TString mcFile;
   if(dataset==20100){
     recoFile = "ConfigHadEtReconstructedPbPb.C";
     mcFile = "ConfigHadEtMonteCarloPbPb.C";
   }
   if(dataset==2009){
     recoFile = "ConfigHadEtReconstructedpp900GeV.C";
     mcFile = "ConfigHadEtMonteCarlopp900GeV.C";
   }
   if(dataset==20111){
     recoFile = "ConfigHadEtReconstructedpp276TeV.C";
     mcFile = "ConfigHadEtMonteCarlopp276TeV.C";
   }
   if(dataset==2010){
     recoFile = "ConfigHadEtReconstructedpp7TeV.C";
     mcFile = "ConfigHadEtMonteCarlopp7TeV.C";
   }
   AliAnalysisTaskHadEt *task2 = new AliAnalysisTaskHadEt("TaskHadEt",!data,recoFile,mcFile);
    if(!data) task2->SetMcData();
    mgr->AddTask(task2);
  AliAnalysisDataContainer *coutput2 = mgr->CreateContainer("out2", TList::Class(), AliAnalysisManager::kOutputContainer,"Et.ESD.new.sim.root");
  mgr->ConnectInput(task2,0,cinput1);
  mgr->ConnectOutput(task2,1,coutput2);

  mgr->SetDebugLevel(0);

  if (!mgr->InitAnalysis()) return;
  mgr->PrintStatus();
  if(submit){
    mgr->StartAnalysis("grid");
  }
  else{
    mgr->StartAnalysis("local",chain);
  }

  timer.Stop();
  timer.Print();
}
<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  $RCSfile: b2ipoint.hxx,v $
 *
 *  $Revision: 1.3 $
 *
 *  last change: $Author: thb $ $Date: 2004-02-16 17:03:05 $
 *
 *  The Contents of this file are made available subject to the terms of
 *  either of the following licenses
 *
 *         - GNU Lesser General Public License Version 2.1
 *         - Sun Industry Standards Source License Version 1.1
 *
 *  Sun Microsystems Inc., October, 2000
 *
 *  GNU Lesser General Public License Version 2.1
 *  =============================================
 *  Copyright 2000 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
 *
 *
 *  Sun Industry Standards Source License Version 1.1
 *  =================================================
 *  The contents of this file are subject to the Sun Industry Standards
 *  Source License Version 1.1 (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.openoffice.org/license.html.
 *
 *  Software provided under this License is provided on an "AS IS" basis,
 *  WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
 *  WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
 *  MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
 *  See the License for the specific provisions governing your rights and
 *  obligations concerning the Software.
 *
 *  The Initial Developer of the Original Code is: Sun Microsystems, Inc.
 *
 *  Copyright: 2000 by Sun Microsystems, Inc.
 *
 *  All Rights Reserved.
 *
 *  Contributor(s): _______________________________________
 *
 *
 ************************************************************************/

#ifndef _BGFX_POINT_B2IPOINT_HXX
#define _BGFX_POINT_B2IPOINT_HXX

#ifndef _BGFX_TUPLE_B2ITUPLE_HXX
#include <basegfx/tuple/b2ituple.hxx>
#endif

namespace basegfx
{
    // predeclaration
    class B2DHomMatrix;

    /** Base Point class with two sal_Int32 values

        This class derives all operators and common handling for
        a 2D data class from B2ITuple. All necessary extensions
        which are special for points will be added here.

        @see B2ITuple
    */
    class B2IPoint : public ::basegfx::B2ITuple
    {
    public:
        /** Create a 2D Point

            The point is initialized to (0, 0)
        */
        B2IPoint()
        :   B2ITuple()
        {}

        /** Create a 2D Point

            @param nX
            This parameter is used to initialize the X-coordinate
            of the 2D Point.

            @param nY
            This parameter is used to initialize the Y-coordinate
            of the 2D Point.
        */
        B2IPoint(sal_Int32 nX, sal_Int32 nY)
        :   B2ITuple(nX, nY)
        {}

        /** Create a copy of a 2D Point

            @param rPoint
            The 2D Point which will be copied.
        */
        B2IPoint(const B2IPoint& rPoint)
        :   B2ITuple(rPoint)
        {}

        /** constructor with tuple to allow copy-constructing
            from B2ITuple-based classes
        */
        B2IPoint(const ::basegfx::B2ITuple& rTuple)
        :   B2ITuple(rTuple)
        {}

        ~B2IPoint()
        {}

        /** *=operator to allow usage from B2IPoint, too
        */
        B2IPoint& operator*=( const B2IPoint& rPnt )
        {
            mnX *= rPnt.mnX;
            mnY *= rPnt.mnY;
            return *this;
        }

        /** *=operator to allow usage from B2IPoint, too
        */
        B2IPoint& operator*=(sal_Int32 t)
        {
            mnX *= t;
            mnY *= t;
            return *this;
        }

        /** assignment operator to allow assigning the results
            of B2ITuple calculations
        */
        B2IPoint& operator=( const ::basegfx::B2ITuple& rPoint );

        /** Transform point by given transformation matrix.

            The translational components of the matrix are, in
            contrast to B2DVector, applied.
        */
        B2IPoint& operator*=( const ::basegfx::B2DHomMatrix& rMat );

        static const B2IPoint& getEmptyPoint()
        {
            return (const B2IPoint&) ::basegfx::B2ITuple::getEmptyTuple();
        }
    };
} // end of namespace basegfx

#endif /* _BGFX_POINT_B2IPOINT_HXX */
<commit_msg>INTEGRATION: CWS ooo19126 (1.3.62); FILE MERGED 2005/09/05 17:38:21 rt 1.3.62.1: #i54170# Change license header: remove SISSL<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: b2ipoint.hxx,v $
 *
 *  $Revision: 1.4 $
 *
 *  last change: $Author: rt $ $Date: 2005-09-07 20:26:28 $
 *
 *  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 _BGFX_POINT_B2IPOINT_HXX
#define _BGFX_POINT_B2IPOINT_HXX

#ifndef _BGFX_TUPLE_B2ITUPLE_HXX
#include <basegfx/tuple/b2ituple.hxx>
#endif

namespace basegfx
{
    // predeclaration
    class B2DHomMatrix;

    /** Base Point class with two sal_Int32 values

        This class derives all operators and common handling for
        a 2D data class from B2ITuple. All necessary extensions
        which are special for points will be added here.

        @see B2ITuple
    */
    class B2IPoint : public ::basegfx::B2ITuple
    {
    public:
        /** Create a 2D Point

            The point is initialized to (0, 0)
        */
        B2IPoint()
        :   B2ITuple()
        {}

        /** Create a 2D Point

            @param nX
            This parameter is used to initialize the X-coordinate
            of the 2D Point.

            @param nY
            This parameter is used to initialize the Y-coordinate
            of the 2D Point.
        */
        B2IPoint(sal_Int32 nX, sal_Int32 nY)
        :   B2ITuple(nX, nY)
        {}

        /** Create a copy of a 2D Point

            @param rPoint
            The 2D Point which will be copied.
        */
        B2IPoint(const B2IPoint& rPoint)
        :   B2ITuple(rPoint)
        {}

        /** constructor with tuple to allow copy-constructing
            from B2ITuple-based classes
        */
        B2IPoint(const ::basegfx::B2ITuple& rTuple)
        :   B2ITuple(rTuple)
        {}

        ~B2IPoint()
        {}

        /** *=operator to allow usage from B2IPoint, too
        */
        B2IPoint& operator*=( const B2IPoint& rPnt )
        {
            mnX *= rPnt.mnX;
            mnY *= rPnt.mnY;
            return *this;
        }

        /** *=operator to allow usage from B2IPoint, too
        */
        B2IPoint& operator*=(sal_Int32 t)
        {
            mnX *= t;
            mnY *= t;
            return *this;
        }

        /** assignment operator to allow assigning the results
            of B2ITuple calculations
        */
        B2IPoint& operator=( const ::basegfx::B2ITuple& rPoint );

        /** Transform point by given transformation matrix.

            The translational components of the matrix are, in
            contrast to B2DVector, applied.
        */
        B2IPoint& operator*=( const ::basegfx::B2DHomMatrix& rMat );

        static const B2IPoint& getEmptyPoint()
        {
            return (const B2IPoint&) ::basegfx::B2ITuple::getEmptyTuple();
        }
    };
} // end of namespace basegfx

#endif /* _BGFX_POINT_B2IPOINT_HXX */
<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: dinfedt.cxx,v $
 *
 *  $Revision: 1.7 $
 *
 *  last change: $Author: hr $ $Date: 2007-06-27 23:11:03 $
 *
 *  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
 *
 ************************************************************************/

// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_sfx2.hxx"

#ifndef GCC
#endif

#include "dinfedt.hxx"
#include "sfxresid.hxx"

#include <sfx2/sfx.hrc>
#include "dinfedt.hrc"

// class InfoEdit_Impl ---------------------------------------------------

void InfoEdit_Impl::KeyInput( const KeyEvent& rKEvent )
{
    if ( rKEvent.GetCharCode() != '~' )
        Edit::KeyInput( rKEvent );
}

// class SfxDocInfoEditDlg -----------------------------------------------

SfxDocInfoEditDlg::SfxDocInfoEditDlg( Window* pParent ) :

    ModalDialog( pParent, SfxResId( DLG_DOCINFO_EDT ) ),

    aInfoFL     ( this, SfxResId( FL_INFO ) ),
    aInfo1ED    ( this, SfxResId( ED_INFO1 ) ),
    aInfo2ED    ( this, SfxResId( ED_INFO2 ) ),
    aInfo3ED    ( this, SfxResId( ED_INFO3 ) ),
    aInfo4ED    ( this, SfxResId( ED_INFO4 ) ),
    aOkBT       ( this, SfxResId( BT_OK ) ),
    aCancelBT   ( this, SfxResId( BT_CANCEL ) ),
    aHelpBtn    ( this, SfxResId( BTN_HELP ) )

{
    FreeResource();
}

<commit_msg>INTEGRATION: CWS changefileheader (1.7.216); FILE MERGED 2008/03/31 13:38:13 rt 1.7.216.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: dinfedt.cxx,v $
 * $Revision: 1.8 $
 *
 * 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.
 *
 ************************************************************************/

// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_sfx2.hxx"

#ifndef GCC
#endif

#include "dinfedt.hxx"
#include "sfxresid.hxx"

#include <sfx2/sfx.hrc>
#include "dinfedt.hrc"

// class InfoEdit_Impl ---------------------------------------------------

void InfoEdit_Impl::KeyInput( const KeyEvent& rKEvent )
{
    if ( rKEvent.GetCharCode() != '~' )
        Edit::KeyInput( rKEvent );
}

// class SfxDocInfoEditDlg -----------------------------------------------

SfxDocInfoEditDlg::SfxDocInfoEditDlg( Window* pParent ) :

    ModalDialog( pParent, SfxResId( DLG_DOCINFO_EDT ) ),

    aInfoFL     ( this, SfxResId( FL_INFO ) ),
    aInfo1ED    ( this, SfxResId( ED_INFO1 ) ),
    aInfo2ED    ( this, SfxResId( ED_INFO2 ) ),
    aInfo3ED    ( this, SfxResId( ED_INFO3 ) ),
    aInfo4ED    ( this, SfxResId( ED_INFO4 ) ),
    aOkBT       ( this, SfxResId( BT_OK ) ),
    aCancelBT   ( this, SfxResId( BT_CANCEL ) ),
    aHelpBtn    ( this, SfxResId( BTN_HELP ) )

{
    FreeResource();
}

<|endoftext|>