<commit_before>/*
 * Software License Agreement (BSD License)
 *
 *  Point Cloud Library (PCL) - www.pointclouds.org
 *  Copyright (c) 2012, Jeremie Papon
 *
 *  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 copyright holder(s) 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.
 *
 */

#ifndef PCL_OCTREE_POINTCLOUD_ADJACENCY_HPP_
#define PCL_OCTREE_POINTCLOUD_ADJACENCY_HPP_

#include <pcl/octree/octree_pointcloud_adjacency.h>

//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
template<typename PointT, typename LeafContainerT, typename BranchContainerT>
pcl::octree::OctreePointCloudAdjacency<PointT, LeafContainerT, BranchContainerT>::OctreePointCloudAdjacency (const double resolution_arg)
: OctreePointCloud<PointT, LeafContainerT, BranchContainerT
, OctreeBase<LeafContainerT, BranchContainerT> > (resolution_arg)
{

}

////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
template<typename PointT, typename LeafContainerT, typename BranchContainerT> void
pcl::octree::OctreePointCloudAdjacency<PointT, LeafContainerT, BranchContainerT>::addPointsFromInputCloud ()
{
  //double t1,t2;
  float minX = std::numeric_limits<float>::max (), minY = std::numeric_limits<float>::max (), minZ = std::numeric_limits<float>::max ();
  float maxX = -std::numeric_limits<float>::max(), maxY = -std::numeric_limits<float>::max(), maxZ = -std::numeric_limits<float>::max();

  for (int i = 0; i < input_->size (); ++i)
  {
    PointT temp (input_->points[i]);
    if (transform_func_) //Search for point with
      transform_func_ (temp);
    if (temp.x < minX)
      minX = temp.x;
    if (temp.y < minY)
      minY = temp.y;
    if (temp.z < minZ)
      minZ = temp.z;
    if (temp.x > maxX)
      maxX = temp.x;
    if (temp.y > maxY)
      maxY = temp.y;
    if (temp.z > maxZ)
      maxZ = temp.z;
  }
  this->defineBoundingBox (minX, minY, minZ, maxX, maxY, maxZ);
  //t1 = timer_.getTime ();
  OctreePointCloud<PointT, LeafContainerT, BranchContainerT>::addPointsFromInputCloud ();

  //t2 = timer_.getTime ();
  //std::cout << "Add Points:"<<t2-t1<<" ms  Num leaves ="<<this->getLeafCount ()<<"\n";

  std::list <std::pair<OctreeKey,LeafContainerT*> > delete_list;
  //double t_temp, t_neigh, t_compute, t_getLeaf;
  //t_neigh = t_compute = t_getLeaf = 0;
  LeafContainerT *leaf_container;
  typename OctreeAdjacencyT::LeafNodeIterator leaf_itr;
  leaf_vector_.reserve (this->getLeafCount ());
  for ( leaf_itr = this->leaf_begin () ; leaf_itr != this->leaf_end (); ++leaf_itr)
  {
    //t_temp = timer_.getTime ();
    OctreeKey leaf_key = leaf_itr.getCurrentOctreeKey ();
    leaf_container = &(leaf_itr.getLeafContainer ());
    //t_getLeaf += timer_.getTime () - t_temp;

    //t_temp = timer_.getTime ();
    //Run the leaf's compute function
    leaf_container->computeData ();
    //t_compute += timer_.getTime () - t_temp;

    //t_temp = timer_.getTime ();
    //  std::cout << "Computing neighbors\n";
    computeNeighbors (leaf_key, leaf_container);
    //t_neigh += timer_.getTime () - t_temp;

    leaf_vector_.push_back (leaf_container);

  }
  //Go through and delete voxels scheduled
  for (typename std::list<std::pair<OctreeKey,LeafContainerT*> >::iterator delete_itr = delete_list.begin (); delete_itr != delete_list.end (); ++delete_itr)
  {
    leaf_container = delete_itr->second;
    //Remove pointer to it from all neighbors
    typename std::set<LeafContainerT*>::iterator neighbor_itr = leaf_container->begin ();
    typename std::set<LeafContainerT*>::iterator neighbor_end = leaf_container->end ();
    for ( ; neighbor_itr != neighbor_end; ++neighbor_itr)
    {
      //Don't delete self neighbor
      if (*neighbor_itr != leaf_container)
        (*neighbor_itr)->removeNeighbor (leaf_container);
    }
    this->removeLeaf (delete_itr->first);
  }

  //Make sure our leaf vector is correctly sized
  assert (leaf_vector_.size () == this->getLeafCount ());

 //  std::cout << "Time spent getting leaves ="<<t_getLeaf<<"\n";
 // std::cout << "Time spent computing data in leaves="<<t_compute<<"\n";
 // std::cout << "Time spent computing neighbors="<<t_neigh<<"\n";

}

//////////////////////////////////////////////////////////////////////////////////////////////
template<typename PointT, typename LeafContainerT, typename BranchContainerT> void
pcl::octree::OctreePointCloudAdjacency<PointT, LeafContainerT, BranchContainerT>::genOctreeKeyforPoint (const PointT& point_arg,OctreeKey & key_arg) const
{
  if (transform_func_)
  {
    PointT temp (point_arg);
    transform_func_ (temp);
   // calculate integer key for transformed point coordinates
    key_arg.x = static_cast<unsigned int> ((temp.x - this->min_x_) / this->resolution_);
    key_arg.y = static_cast<unsigned int> ((temp.y - this->min_y_) / this->resolution_);
    key_arg.z = static_cast<unsigned int> ((temp.z - this->min_z_) / this->resolution_);
  }
  else
  {
    // calculate integer key for point coordinates
    key_arg.x = static_cast<unsigned int> ((point_arg.x - this->min_x_) / this->resolution_);
    key_arg.y = static_cast<unsigned int> ((point_arg.y - this->min_y_) / this->resolution_);
    key_arg.z = static_cast<unsigned int> ((point_arg.z - this->min_z_) / this->resolution_);
  }
}

//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
template<typename PointT, typename LeafContainerT, typename BranchContainerT> void
pcl::octree::OctreePointCloudAdjacency<PointT, LeafContainerT, BranchContainerT>::addPointIdx (const int pointIdx_arg)
{
  OctreeKey key;

  assert (pointIdx_arg < static_cast<int> (this->input_->points.size ()));

  const PointT& point = this->input_->points[pointIdx_arg];
  if (!pcl::isFinite (point))
    return;

  // generate key
  this->genOctreeKeyforPoint (point, key);
  // add point to octree at key
  LeafContainerT* container = this->createLeaf(key);
  container->addPoint (point);
}

//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
template<typename PointT, typename LeafContainerT, typename BranchContainerT> void
pcl::octree::OctreePointCloudAdjacency<PointT, LeafContainerT, BranchContainerT>::computeNeighbors (OctreeKey &key_arg, LeafContainerT* leaf_container)
{

  OctreeKey neighbor_key;

  for (int dx = -1; dx <= 1; ++dx)
  {
    for (int dy = -1; dy <= 1; ++dy)
    {
      for (int dz = -1; dz <= 1; ++dz)
      {
        neighbor_key.x = key_arg.x + dx;
        neighbor_key.y = key_arg.y + dy;
        neighbor_key.z = key_arg.z + dz;
        LeafContainerT *neighbor = this->findLeaf (neighbor_key);
        if (neighbor)
        {
          leaf_container->addNeighbor (neighbor);
        }
      }
    }
  }
}

//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
template<typename PointT, typename LeafContainerT, typename BranchContainerT> LeafContainerT*
pcl::octree::OctreePointCloudAdjacency<PointT, LeafContainerT, BranchContainerT>::getLeafContainerAtPoint (
  const PointT& point_arg) const
{
  OctreeKey key;
  LeafContainerT* leaf = 0;
  // generate key
  this->genOctreeKeyforPoint (point_arg, key);

  leaf = this->findLeaf (key);

  return leaf;
}

//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
template<typename PointT, typename LeafContainerT, typename BranchContainerT> void
pcl::octree::OctreePointCloudAdjacency<PointT, LeafContainerT, BranchContainerT>::computeVoxelAdjacencyGraph (VoxelAdjacencyList &voxel_adjacency_graph)
{
  //TODO Change this to use leaf centers, not centroids!

  voxel_adjacency_graph.clear ();
  //Add a vertex for each voxel, store ids in map
  std::map <LeafContainerT*, VoxelID> leaf_vertex_id_map;
  for (typename OctreeAdjacencyT::LeafNodeIterator leaf_itr = this->leaf_begin () ; leaf_itr != this->leaf_end (); ++leaf_itr)
  {
    OctreeKey leaf_key = leaf_itr.getCurrentOctreeKey ();
    PointT centroid_point;
    this->genLeafNodeCenterFromOctreeKey (leaf_key, centroid_point);
    VoxelID node_id = add_vertex (voxel_adjacency_graph);

    voxel_adjacency_graph[node_id] = centroid_point;
    LeafContainerT* leaf_container = &(leaf_itr.getLeafContainer ());
    leaf_vertex_id_map[leaf_container] = node_id;
  }

  //Iterate through and add edges to adjacency graph
  for ( typename std::vector<LeafContainerT*>::iterator leaf_itr = leaf_vector_.begin (); leaf_itr != leaf_vector_.end (); ++leaf_itr)
  {
    typename LeafContainerT::iterator neighbor_itr = (*leaf_itr)->begin ();
    typename LeafContainerT::iterator neighbor_end = (*leaf_itr)->end ();
    LeafContainerT* neighbor_container;
    VoxelID u = (leaf_vertex_id_map.find (*leaf_itr))->second;
    PointT p_u = voxel_adjacency_graph[u];
    for ( ; neighbor_itr != neighbor_end; ++neighbor_itr)
    {
      neighbor_container = *neighbor_itr;
      EdgeID edge;
      bool edge_added;
      VoxelID v = (leaf_vertex_id_map.find (neighbor_container))->second;
      boost::tie (edge, edge_added) = add_edge (u,v,voxel_adjacency_graph);

      PointT p_v = voxel_adjacency_graph[v];
      float dist = (p_v.getVector3fMap () - p_u.getVector3fMap ()).norm ();
      voxel_adjacency_graph[edge] = dist;

    }

  }

}

//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
template<typename PointT, typename LeafContainerT, typename BranchContainerT> bool
pcl::octree::OctreePointCloudAdjacency<PointT, LeafContainerT, BranchContainerT>::testForOcclusion (const PointT& point_arg, const PointXYZ &camera_pos)
{
  OctreeKey key;
  this->genOctreeKeyforPoint (point_arg, key);
  // This code follows the method in Octree::PointCloud
  Eigen::Vector3f sensor(camera_pos.x,
                         camera_pos.y,
                         camera_pos.z);

  Eigen::Vector3f leaf_centroid(static_cast<float> ((static_cast<double> (key.x) + 0.5f) * this->resolution_ + this->min_x_),
                                static_cast<float> ((static_cast<double> (key.y) + 0.5f) * this->resolution_ + this->min_y_),
                                static_cast<float> ((static_cast<double> (key.z) + 0.5f) * this->resolution_ + this->min_z_));
  Eigen::Vector3f direction = sensor - leaf_centroid;

  float norm = direction.norm ();
  direction.normalize ();
  float precision = 1.0f;
  const float step_size = static_cast<const float> (resolution_) * precision;
  const int nsteps = std::max (1, static_cast<int> (norm / step_size));

  OctreeKey prev_key = key;
  // Walk along the line segment with small steps.
  Eigen::Vector3f p = leaf_centroid;
  PointT octree_p;
  for (int i = 0; i < nsteps; ++i)
  {
    //Start at the leaf voxel, and move back towards sensor.
    p += (direction * step_size);

    octree_p.x = p.x ();
    octree_p.y = p.y ();
    octree_p.z = p.z ();
    //  std::cout << octree_p<< "\n";
    OctreeKey key;
    this->genOctreeKeyforPoint (octree_p, key);

    // Not a new key, still the same voxel (starts at self).
    if ((key == prev_key))
      continue;

    prev_key = key;

    LeafContainerT *leaf = this->findLeaf (key);
    //If the voxel is occupied, there is a possible occlusion
    if (leaf)
    {
     return true;
    }
  }

  //If we didn't run into a voxel on the way to this camera, it can't be occluded.
  return false;

}

#define PCL_INSTANTIATE_OctreePointCloudAdjacency(T) template class PCL_EXPORTS pcl::octree::OctreePointCloudAdjacency<T>;

#endif

<commit_msg>Fix a bug in `OctreePointCloudAdjacency::computeNeighbors()`<commit_after>/*
 * Software License Agreement (BSD License)
 *
 *  Point Cloud Library (PCL) - www.pointclouds.org
 *  Copyright (c) 2012, Jeremie Papon
 *
 *  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 copyright holder(s) 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.
 *
 */

#ifndef PCL_OCTREE_POINTCLOUD_ADJACENCY_HPP_
#define PCL_OCTREE_POINTCLOUD_ADJACENCY_HPP_

#include <pcl/octree/octree_pointcloud_adjacency.h>

//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
template<typename PointT, typename LeafContainerT, typename BranchContainerT>
pcl::octree::OctreePointCloudAdjacency<PointT, LeafContainerT, BranchContainerT>::OctreePointCloudAdjacency (const double resolution_arg)
: OctreePointCloud<PointT, LeafContainerT, BranchContainerT
, OctreeBase<LeafContainerT, BranchContainerT> > (resolution_arg)
{

}

////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
template<typename PointT, typename LeafContainerT, typename BranchContainerT> void
pcl::octree::OctreePointCloudAdjacency<PointT, LeafContainerT, BranchContainerT>::addPointsFromInputCloud ()
{
  //double t1,t2;
  float minX = std::numeric_limits<float>::max (), minY = std::numeric_limits<float>::max (), minZ = std::numeric_limits<float>::max ();
  float maxX = -std::numeric_limits<float>::max(), maxY = -std::numeric_limits<float>::max(), maxZ = -std::numeric_limits<float>::max();

  for (int i = 0; i < input_->size (); ++i)
  {
    PointT temp (input_->points[i]);
    if (transform_func_) //Search for point with
      transform_func_ (temp);
    if (temp.x < minX)
      minX = temp.x;
    if (temp.y < minY)
      minY = temp.y;
    if (temp.z < minZ)
      minZ = temp.z;
    if (temp.x > maxX)
      maxX = temp.x;
    if (temp.y > maxY)
      maxY = temp.y;
    if (temp.z > maxZ)
      maxZ = temp.z;
  }
  this->defineBoundingBox (minX, minY, minZ, maxX, maxY, maxZ);
  //t1 = timer_.getTime ();
  OctreePointCloud<PointT, LeafContainerT, BranchContainerT>::addPointsFromInputCloud ();

  //t2 = timer_.getTime ();
  //std::cout << "Add Points:"<<t2-t1<<" ms  Num leaves ="<<this->getLeafCount ()<<"\n";

  std::list <std::pair<OctreeKey,LeafContainerT*> > delete_list;
  //double t_temp, t_neigh, t_compute, t_getLeaf;
  //t_neigh = t_compute = t_getLeaf = 0;
  LeafContainerT *leaf_container;
  typename OctreeAdjacencyT::LeafNodeIterator leaf_itr;
  leaf_vector_.reserve (this->getLeafCount ());
  for ( leaf_itr = this->leaf_begin () ; leaf_itr != this->leaf_end (); ++leaf_itr)
  {
    //t_temp = timer_.getTime ();
    OctreeKey leaf_key = leaf_itr.getCurrentOctreeKey ();
    leaf_container = &(leaf_itr.getLeafContainer ());
    //t_getLeaf += timer_.getTime () - t_temp;

    //t_temp = timer_.getTime ();
    //Run the leaf's compute function
    leaf_container->computeData ();
    //t_compute += timer_.getTime () - t_temp;

    //t_temp = timer_.getTime ();
    //  std::cout << "Computing neighbors\n";
    computeNeighbors (leaf_key, leaf_container);
    //t_neigh += timer_.getTime () - t_temp;

    leaf_vector_.push_back (leaf_container);

  }
  //Go through and delete voxels scheduled
  for (typename std::list<std::pair<OctreeKey,LeafContainerT*> >::iterator delete_itr = delete_list.begin (); delete_itr != delete_list.end (); ++delete_itr)
  {
    leaf_container = delete_itr->second;
    //Remove pointer to it from all neighbors
    typename std::set<LeafContainerT*>::iterator neighbor_itr = leaf_container->begin ();
    typename std::set<LeafContainerT*>::iterator neighbor_end = leaf_container->end ();
    for ( ; neighbor_itr != neighbor_end; ++neighbor_itr)
    {
      //Don't delete self neighbor
      if (*neighbor_itr != leaf_container)
        (*neighbor_itr)->removeNeighbor (leaf_container);
    }
    this->removeLeaf (delete_itr->first);
  }

  //Make sure our leaf vector is correctly sized
  assert (leaf_vector_.size () == this->getLeafCount ());

 //  std::cout << "Time spent getting leaves ="<<t_getLeaf<<"\n";
 // std::cout << "Time spent computing data in leaves="<<t_compute<<"\n";
 // std::cout << "Time spent computing neighbors="<<t_neigh<<"\n";

}

//////////////////////////////////////////////////////////////////////////////////////////////
template<typename PointT, typename LeafContainerT, typename BranchContainerT> void
pcl::octree::OctreePointCloudAdjacency<PointT, LeafContainerT, BranchContainerT>::genOctreeKeyforPoint (const PointT& point_arg,OctreeKey & key_arg) const
{
  if (transform_func_)
  {
    PointT temp (point_arg);
    transform_func_ (temp);
   // calculate integer key for transformed point coordinates
    key_arg.x = static_cast<unsigned int> ((temp.x - this->min_x_) / this->resolution_);
    key_arg.y = static_cast<unsigned int> ((temp.y - this->min_y_) / this->resolution_);
    key_arg.z = static_cast<unsigned int> ((temp.z - this->min_z_) / this->resolution_);
  }
  else
  {
    // calculate integer key for point coordinates
    key_arg.x = static_cast<unsigned int> ((point_arg.x - this->min_x_) / this->resolution_);
    key_arg.y = static_cast<unsigned int> ((point_arg.y - this->min_y_) / this->resolution_);
    key_arg.z = static_cast<unsigned int> ((point_arg.z - this->min_z_) / this->resolution_);
  }
}

//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
template<typename PointT, typename LeafContainerT, typename BranchContainerT> void
pcl::octree::OctreePointCloudAdjacency<PointT, LeafContainerT, BranchContainerT>::addPointIdx (const int pointIdx_arg)
{
  OctreeKey key;

  assert (pointIdx_arg < static_cast<int> (this->input_->points.size ()));

  const PointT& point = this->input_->points[pointIdx_arg];
  if (!pcl::isFinite (point))
    return;

  // generate key
  this->genOctreeKeyforPoint (point, key);
  // add point to octree at key
  LeafContainerT* container = this->createLeaf(key);
  container->addPoint (point);
}

//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
template<typename PointT, typename LeafContainerT, typename BranchContainerT> void
pcl::octree::OctreePointCloudAdjacency<PointT, LeafContainerT, BranchContainerT>::computeNeighbors (OctreeKey &key_arg, LeafContainerT* leaf_container)
{

  OctreeKey neighbor_key;

  for (int dx = -1; dx <= 1; ++dx)
  {
    int x = dx + key_arg.x;
    if (x < 0 || x > this->max_key_.x)
      continue;
    neighbor_key.x = static_cast<uint32_t> (x);
    for (int dy = -1; dy <= 1; ++dy)
    {
      int y = dy + key_arg.y;
      if (y < 0 || y > this->max_key_.y)
        continue;
      neighbor_key.y = static_cast<uint32_t> (y);
      for (int dz = -1; dz <= 1; ++dz)
      {
        int z = dz + key_arg.z;
        if (z < 0 || z > this->max_key_.z)
          continue;
        neighbor_key.z = static_cast<uint32_t> (z);
        LeafContainerT *neighbor = this->findLeaf (neighbor_key);
        if (neighbor)
        {
          leaf_container->addNeighbor (neighbor);
        }
      }
    }
  }
}

//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
template<typename PointT, typename LeafContainerT, typename BranchContainerT> LeafContainerT*
pcl::octree::OctreePointCloudAdjacency<PointT, LeafContainerT, BranchContainerT>::getLeafContainerAtPoint (
  const PointT& point_arg) const
{
  OctreeKey key;
  LeafContainerT* leaf = 0;
  // generate key
  this->genOctreeKeyforPoint (point_arg, key);

  leaf = this->findLeaf (key);

  return leaf;
}

//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
template<typename PointT, typename LeafContainerT, typename BranchContainerT> void
pcl::octree::OctreePointCloudAdjacency<PointT, LeafContainerT, BranchContainerT>::computeVoxelAdjacencyGraph (VoxelAdjacencyList &voxel_adjacency_graph)
{
  //TODO Change this to use leaf centers, not centroids!

  voxel_adjacency_graph.clear ();
  //Add a vertex for each voxel, store ids in map
  std::map <LeafContainerT*, VoxelID> leaf_vertex_id_map;
  for (typename OctreeAdjacencyT::LeafNodeIterator leaf_itr = this->leaf_begin () ; leaf_itr != this->leaf_end (); ++leaf_itr)
  {
    OctreeKey leaf_key = leaf_itr.getCurrentOctreeKey ();
    PointT centroid_point;
    this->genLeafNodeCenterFromOctreeKey (leaf_key, centroid_point);
    VoxelID node_id = add_vertex (voxel_adjacency_graph);

    voxel_adjacency_graph[node_id] = centroid_point;
    LeafContainerT* leaf_container = &(leaf_itr.getLeafContainer ());
    leaf_vertex_id_map[leaf_container] = node_id;
  }

  //Iterate through and add edges to adjacency graph
  for ( typename std::vector<LeafContainerT*>::iterator leaf_itr = leaf_vector_.begin (); leaf_itr != leaf_vector_.end (); ++leaf_itr)
  {
    typename LeafContainerT::iterator neighbor_itr = (*leaf_itr)->begin ();
    typename LeafContainerT::iterator neighbor_end = (*leaf_itr)->end ();
    LeafContainerT* neighbor_container;
    VoxelID u = (leaf_vertex_id_map.find (*leaf_itr))->second;
    PointT p_u = voxel_adjacency_graph[u];
    for ( ; neighbor_itr != neighbor_end; ++neighbor_itr)
    {
      neighbor_container = *neighbor_itr;
      EdgeID edge;
      bool edge_added;
      VoxelID v = (leaf_vertex_id_map.find (neighbor_container))->second;
      boost::tie (edge, edge_added) = add_edge (u,v,voxel_adjacency_graph);

      PointT p_v = voxel_adjacency_graph[v];
      float dist = (p_v.getVector3fMap () - p_u.getVector3fMap ()).norm ();
      voxel_adjacency_graph[edge] = dist;

    }

  }

}

//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
template<typename PointT, typename LeafContainerT, typename BranchContainerT> bool
pcl::octree::OctreePointCloudAdjacency<PointT, LeafContainerT, BranchContainerT>::testForOcclusion (const PointT& point_arg, const PointXYZ &camera_pos)
{
  OctreeKey key;
  this->genOctreeKeyforPoint (point_arg, key);
  // This code follows the method in Octree::PointCloud
  Eigen::Vector3f sensor(camera_pos.x,
                         camera_pos.y,
                         camera_pos.z);

  Eigen::Vector3f leaf_centroid(static_cast<float> ((static_cast<double> (key.x) + 0.5f) * this->resolution_ + this->min_x_),
                                static_cast<float> ((static_cast<double> (key.y) + 0.5f) * this->resolution_ + this->min_y_),
                                static_cast<float> ((static_cast<double> (key.z) + 0.5f) * this->resolution_ + this->min_z_));
  Eigen::Vector3f direction = sensor - leaf_centroid;

  float norm = direction.norm ();
  direction.normalize ();
  float precision = 1.0f;
  const float step_size = static_cast<const float> (resolution_) * precision;
  const int nsteps = std::max (1, static_cast<int> (norm / step_size));

  OctreeKey prev_key = key;
  // Walk along the line segment with small steps.
  Eigen::Vector3f p = leaf_centroid;
  PointT octree_p;
  for (int i = 0; i < nsteps; ++i)
  {
    //Start at the leaf voxel, and move back towards sensor.
    p += (direction * step_size);

    octree_p.x = p.x ();
    octree_p.y = p.y ();
    octree_p.z = p.z ();
    //  std::cout << octree_p<< "\n";
    OctreeKey key;
    this->genOctreeKeyforPoint (octree_p, key);

    // Not a new key, still the same voxel (starts at self).
    if ((key == prev_key))
      continue;

    prev_key = key;

    LeafContainerT *leaf = this->findLeaf (key);
    //If the voxel is occupied, there is a possible occlusion
    if (leaf)
    {
     return true;
    }
  }

  //If we didn't run into a voxel on the way to this camera, it can't be occluded.
  return false;

}

#define PCL_INSTANTIATE_OctreePointCloudAdjacency(T) template class PCL_EXPORTS pcl::octree::OctreePointCloudAdjacency<T>;

#endif

<|endoftext|>


<commit_before>6cf7916b-ad59-11e7-8785-ac87a332f658<commit_msg>roselyn added more bugs<commit_after>6df1291e-ad59-11e7-8a0c-ac87a332f658<|endoftext|>


<commit_before>3324e254-ad58-11e7-986b-ac87a332f658<commit_msg>Tuesday, turns out it was tuesday<commit_after>338c5a61-ad58-11e7-8667-ac87a332f658<|endoftext|>


<commit_before>#include "blp.h"
#include <SimpleOpt.h>
#include <iostream>
#include <string>

using namespace std;

/**************************** COMMAND-LINE PARSING ****************************/

// The valid options
enum
{
    OPT_HELP,
    OPT_INFOS,
};

const CSimpleOpt::SOption COMMAND_LINE_OPTIONS[] = {
    { OPT_HELP,  "-h",      SO_NONE },
    { OPT_HELP,  "--help",  SO_NONE },
    { OPT_INFOS, "-i",      SO_NONE },
    { OPT_INFOS, "--infos", SO_NONE },

    SO_END_OF_OPTIONS
};

/********************************** FUNCTIONS *********************************/

void showUsage(const std::string& strApplicationName)
{
    cout << "BLPConverter" << endl
         << "Usage: " << strApplicationName << " [options] <blp_filename> [<destination>]" << endl
         << endl;
}

void showInfos(const std::string& strFileName, tBLP2Header* pHeader)
{
    cout << endl
         << "Infos about '" << strFileName << "':" << endl
         << "  - Format:     " << blp_asString(blp_format(pHeader)) << endl
         << "  - Dimensions: " << pHeader->width << "x" << pHeader->height << endl
         << "  - Mip levels: " << blp_nbMipLevels(pHeader) << endl
         << endl;
}

int main(int argc, char** argv)
{
    bool bInfos = false;

    // Parse the command-line parameters
    CSimpleOpt args(argc, argv, COMMAND_LINE_OPTIONS);
    while (args.Next())
    {
        if (args.LastError() == SO_SUCCESS)
        {
            switch (args.OptionId())
            {
                case OPT_HELP:
                    showUsage(argv[0]);
                    return 0;

                case OPT_INFOS:
                    bInfos = true;
                    break;
            }
        }
        else
        {
            cerr << "Invalid argument: " << args.OptionText() << endl;
            return -1;
        }
    }

    if (args.FileCount() == 0)
    {
        cerr << "No BLP file specified" << endl;
        return -1;
    }

    // Only support the '--infos' option at the moment
    if (!bInfos)
    {
        cerr << "The conversion of BLP files isn't implemented yet" << endl;
        return -1;
    }

    FILE* pFile = fopen(args.File(0), "rb");
    if (!pFile)
    {
        cerr << "Failed to open the file '" << args.File(0) << "'" << endl;
        return -1;
    }

    tBLP2Header header;

    if (!blp_processFile(pFile, &header))
    {
        cerr << "Failed to process the file '" << args.File(0) << "'" << endl;
        fclose(pFile);
        return -1;
    }

    showInfos(args.File(0), &header);

    fclose(pFile);

    return 0;
}
<commit_msg>Can work on several input files now<commit_after>#include "blp.h"
#include <SimpleOpt.h>
#include <iostream>
#include <string>

using namespace std;

/**************************** COMMAND-LINE PARSING ****************************/

// The valid options
enum
{
    OPT_HELP,
    OPT_INFOS,
};

const CSimpleOpt::SOption COMMAND_LINE_OPTIONS[] = {
    { OPT_HELP,  "-h",      SO_NONE },
    { OPT_HELP,  "--help",  SO_NONE },
    { OPT_INFOS, "-i",      SO_NONE },
    { OPT_INFOS, "--infos", SO_NONE },

    SO_END_OF_OPTIONS
};

/********************************** FUNCTIONS *********************************/

void showUsage(const std::string& strApplicationName)
{
    cout << "BLPConverter" << endl
         << "Usage: " << strApplicationName << " [options] <blp_filename> [<blp_filename> ... <blp_filename>]" << endl
         << endl;
}

void showInfos(const std::string& strFileName, tBLP2Header* pHeader)
{
    cout << endl
         << "Infos about '" << strFileName << "':" << endl
         << "  - Format:     " << blp_asString(blp_format(pHeader)) << endl
         << "  - Dimensions: " << pHeader->width << "x" << pHeader->height << endl
         << "  - Mip levels: " << blp_nbMipLevels(pHeader) << endl
         << endl;
}

int main(int argc, char** argv)
{
    bool bInfos = false;

    // Parse the command-line parameters
    CSimpleOpt args(argc, argv, COMMAND_LINE_OPTIONS);
    while (args.Next())
    {
        if (args.LastError() == SO_SUCCESS)
        {
            switch (args.OptionId())
            {
                case OPT_HELP:
                    showUsage(argv[0]);
                    return 0;

                case OPT_INFOS:
                    bInfos = true;
                    break;
            }
        }
        else
        {
            cerr << "Invalid argument: " << args.OptionText() << endl;
            return -1;
        }
    }

    if (args.FileCount() == 0)
    {
        cerr << "No BLP file specified" << endl;
        return -1;
    }

    // Only support the '--infos' option at the moment
    if (!bInfos)
    {
        cerr << "The conversion of BLP files isn't implemented yet" << endl;
        return -1;
    }

    for (unsigned int i = 0; i < args.FileCount(); ++i)
    {
        tBLP2Header header;

        FILE* pFile = fopen(args.File(i), "rb");
        if (!pFile)
        {
            cerr << "Failed to open the file '" << args.File(i) << "'" << endl;
            continue;
        }

        if (!blp_processFile(pFile, &header))
        {
            cerr << "Failed to process the file '" << args.File(i) << "'" << endl;
            fclose(pFile);
            continue;
        }

        showInfos(args.File(i), &header);

        fclose(pFile);
    }

    return 0;
}
<|endoftext|>


<commit_before>#include <cassert>
#include <cstdio>
#include <stack>

#include <llvm/LLVMContext.h>
#include <llvm/Module.h>
#include <llvm/Support/IRBuilder.h>
#include <llvm/Support/raw_ostream.h>

using namespace llvm;

static const uint64_t DATA_SIZE = 30000;
static const char *DATA_NAME = "data";
static const char *PTR_NAME = "ptr";

struct Loop {
  BasicBlock *Entry, *Body, *Exit;
  PHINode *DataPtrBody, *DataPtrExit;
};

int main() {
  // LLVM context.
  LLVMContext &Context = getGlobalContext();
  Module MainModule("brainfuck program", Context);
  IRBuilder<> Builder(Context);

  // Some useful constants.
  const IntegerType *CellType = Type::getInt8Ty(Context);
  Constant *One = ConstantInt::get(CellType, 1);

  // Function prototypes for the shim.
  FunctionType *PutFunctionType = FunctionType::get(
      Type::getVoidTy(Context) /* return type */,
      std::vector<const Type *>(1, CellType) /* argument types */,
      false /* var args */);
  Function *PutFunction = Function::Create(PutFunctionType,
      Function::ExternalLinkage, "brainfuck_put", &MainModule);
  FunctionType *GetFunctionType = FunctionType::get(
      CellType /* return type */,
      std::vector<const Type *>() /* argument types */,
      false /* var args */);
  Function *GetFunction = Function::Create(GetFunctionType,
      Function::ExternalLinkage, "brainfuck_get", &MainModule);

  // Global data for a brainfuck program.
  ArrayType *DataType = ArrayType::get(CellType, DATA_SIZE);
  GlobalVariable *Data = new GlobalVariable(
      MainModule, DataType, false /* constant */,
      GlobalVariable::InternalLinkage, Constant::getNullValue(DataType),
      DATA_NAME);
  Value *DataPtr = Builder.CreateConstInBoundsGEP2_32(Data, 0, 0, PTR_NAME);

  // Main function definition.
  FunctionType *MainFunctionType = FunctionType::get(
      Type::getVoidTy(Context) /* return type */,
      std::vector<const Type *>() /* argument types */,
      false /* var args */);
  Function *MainFunction = Function::Create(MainFunctionType,
      Function::ExternalLinkage, "brainfuck_main", &MainModule);
  BasicBlock *MainBlock = BasicBlock::Create(Context, "entry", MainFunction);
  Builder.SetInsertPoint(MainBlock);

  // Code generation.
  int c;
  Value *Value;
  std::stack<Loop> Loops;
  Loop ThisLoop;
  while ((c = getchar()) != EOF) {
    switch (c) {
      case '>':
        DataPtr = Builder.CreateConstGEP1_32(DataPtr, 1, PTR_NAME);
        break;
      case '<':
        DataPtr = Builder.CreateConstGEP1_32(DataPtr, -1, PTR_NAME);
        break;
      case '+':
        Value = Builder.CreateLoad(DataPtr);
        Value = Builder.CreateAdd(Value, One);
        Builder.CreateStore(Value, DataPtr);
        break;
      case '-':
        Value = Builder.CreateLoad(DataPtr);
        Value = Builder.CreateSub(Value, One);
        Builder.CreateStore(Value, DataPtr);
        break;
      case '.':
        Value = Builder.CreateLoad(DataPtr);
        Builder.CreateCall(PutFunction, Value);
        break;
      case ',':
        Value = Builder.CreateCall(GetFunction);
        Builder.CreateStore(Value, DataPtr);
        break;

      case '[':
        // Prepare data for the stack.
        ThisLoop.Entry = Builder.GetInsertBlock();
        ThisLoop.Body = BasicBlock::Create(Context, "loop", MainFunction);
        ThisLoop.Exit = BasicBlock::Create(Context, "exit", MainFunction);

        // Emit the beginning conditional branch.
        Value = Builder.CreateLoad(DataPtr);
        Value = Builder.CreateIsNotNull(Value);
        Builder.CreateCondBr(Value, ThisLoop.Body, ThisLoop.Exit);

        // Define the pointer after the loop.
        Builder.SetInsertPoint(ThisLoop.Exit);
        ThisLoop.DataPtrExit = Builder.CreatePHI(DataPtr->getType(), PTR_NAME);
        ThisLoop.DataPtrExit->addIncoming(DataPtr, ThisLoop.Entry);

        // Define the pointer within the loop.
        Builder.SetInsertPoint(ThisLoop.Body);
        ThisLoop.DataPtrBody = Builder.CreatePHI(DataPtr->getType(), PTR_NAME);
        ThisLoop.DataPtrBody->addIncoming(DataPtr, ThisLoop.Entry);

        // Continue generating code within the loop.
        DataPtr = ThisLoop.DataPtrBody;
        Loops.push(ThisLoop);
        break;

      case ']':
        // Pop data off the stack.
        if (Loops.empty()) {
          fputs("] requires matching [\n", stderr);
          abort();
        }
        ThisLoop = Loops.top();
        Loops.pop();

        // Finish off the phi nodes.
        ThisLoop.DataPtrBody->addIncoming(DataPtr, Builder.GetInsertBlock());
        ThisLoop.DataPtrExit->addIncoming(DataPtr, Builder.GetInsertBlock());

        // Emit the ending conditional branch.
        Value = Builder.CreateLoad(DataPtr);
        Value = Builder.CreateIsNotNull(Value);
        Builder.CreateCondBr(Value, ThisLoop.Body, ThisLoop.Exit);

        // Move insertion after the loop.
        ThisLoop.Exit->moveAfter(Builder.GetInsertBlock());
        DataPtr = ThisLoop.DataPtrExit;
        Builder.SetInsertPoint(ThisLoop.Exit);
        break;
    }
  }

  // Ensure all loops have been closed.
  if (!Loops.empty()) {
    fputs("[ requires matching ]\n", stderr);
    abort();
  }

  // Finish off brainfuck_main and dump.
  Builder.CreateRetVoid();
  MainModule.print(outs(), NULL /* assembly annotation writer */);
}
<commit_msg>Update LLVM lib calls to conform to llvm 3.3.<commit_after>#include <cassert>
#include <cstdio>
#include <stack>

#include <llvm/IR/LLVMContext.h>
#include <llvm/IR/Module.h>
#include <llvm/IR/IRBuilder.h>
#include <llvm/Support/raw_ostream.h>

using namespace llvm;

static const uint64_t DATA_SIZE = 30000;
static const char *DATA_NAME = "data";
static const char *PTR_NAME = "ptr";

struct Loop {
  BasicBlock *Entry, *Body, *Exit;
  PHINode *DataPtrBody, *DataPtrExit;
};

int main() {
  // LLVM context.
  LLVMContext &Context = getGlobalContext();
  Module MainModule("brainfuck program", Context);
  IRBuilder<> Builder(Context);

  // Some useful constants.
  Type *CellType = Type::getInt8Ty(Context);
  Constant *One = ConstantInt::get(CellType, 1);

  // Function prototypes for the shim.
  FunctionType *PutFunctionType = FunctionType::get(
      Type::getVoidTy(Context) /* return type */,
      std::vector<Type *>(1, CellType) /* argument types */,
      false /* var args */);
  Function *PutFunction = Function::Create(PutFunctionType,
      Function::ExternalLinkage, "brainfuck_put", &MainModule);
  FunctionType *GetFunctionType = FunctionType::get(
      CellType /* return type */,
      std::vector<Type *>() /* argument types */,
      false /* var args */);
  Function *GetFunction = Function::Create(GetFunctionType,
      Function::ExternalLinkage, "brainfuck_get", &MainModule);

  // Global data for a brainfuck program.
  ArrayType *DataType = ArrayType::get(CellType, DATA_SIZE);
  GlobalVariable *Data = new GlobalVariable(
      MainModule, DataType, false /* constant */,
      GlobalVariable::InternalLinkage, Constant::getNullValue(DataType),
      DATA_NAME);
  Value *DataPtr = Builder.CreateConstInBoundsGEP2_32(Data, 0, 0, PTR_NAME);

  // Main function definition.
  FunctionType *MainFunctionType = FunctionType::get(
      Type::getVoidTy(Context) /* return type */,
      std::vector<Type *>() /* argument types */,
      false /* var args */);
  Function *MainFunction = Function::Create(MainFunctionType,
      Function::ExternalLinkage, "brainfuck_main", &MainModule);
  BasicBlock *MainBlock = BasicBlock::Create(Context, "entry", MainFunction);
  Builder.SetInsertPoint(MainBlock);

  // Code generation.
  int c;
  Value *Value;
  std::stack<Loop> Loops;
  Loop ThisLoop;
  while ((c = getchar()) != EOF) {
    switch (c) {
      case '>':
        DataPtr = Builder.CreateConstGEP1_32(DataPtr, 1, PTR_NAME);
        break;
      case '<':
        DataPtr = Builder.CreateConstGEP1_32(DataPtr, -1, PTR_NAME);
        break;
      case '+':
        Value = Builder.CreateLoad(DataPtr);
        Value = Builder.CreateAdd(Value, One);
        Builder.CreateStore(Value, DataPtr);
        break;
      case '-':
        Value = Builder.CreateLoad(DataPtr);
        Value = Builder.CreateSub(Value, One);
        Builder.CreateStore(Value, DataPtr);
        break;
      case '.':
        Value = Builder.CreateLoad(DataPtr);
        Builder.CreateCall(PutFunction, Value);
        break;
      case ',':
        Value = Builder.CreateCall(GetFunction);
        Builder.CreateStore(Value, DataPtr);
        break;

      case '[':
        // Prepare data for the stack.
        ThisLoop.Entry = Builder.GetInsertBlock();
        ThisLoop.Body = BasicBlock::Create(Context, "loop", MainFunction);
        ThisLoop.Exit = BasicBlock::Create(Context, "exit", MainFunction);

        // Emit the beginning conditional branch.
        Value = Builder.CreateLoad(DataPtr);
        Value = Builder.CreateIsNotNull(Value);
        Builder.CreateCondBr(Value, ThisLoop.Body, ThisLoop.Exit);

        // Define the pointer after the loop.
        Builder.SetInsertPoint(ThisLoop.Exit);
        ThisLoop.DataPtrExit = Builder.CreatePHI(DataPtr->getType(), 2,
            PTR_NAME);
        ThisLoop.DataPtrExit->addIncoming(DataPtr, ThisLoop.Entry);

        // Define the pointer within the loop.
        Builder.SetInsertPoint(ThisLoop.Body);
        ThisLoop.DataPtrBody = Builder.CreatePHI(DataPtr->getType(), 2,
            PTR_NAME);
        ThisLoop.DataPtrBody->addIncoming(DataPtr, ThisLoop.Entry);

        // Continue generating code within the loop.
        DataPtr = ThisLoop.DataPtrBody;
        Loops.push(ThisLoop);
        break;

      case ']':
        // Pop data off the stack.
        if (Loops.empty()) {
          fputs("] requires matching [\n", stderr);
          abort();
        }
        ThisLoop = Loops.top();
        Loops.pop();

        // Finish off the phi nodes.
        ThisLoop.DataPtrBody->addIncoming(DataPtr, Builder.GetInsertBlock());
        ThisLoop.DataPtrExit->addIncoming(DataPtr, Builder.GetInsertBlock());

        // Emit the ending conditional branch.
        Value = Builder.CreateLoad(DataPtr);
        Value = Builder.CreateIsNotNull(Value);
        Builder.CreateCondBr(Value, ThisLoop.Body, ThisLoop.Exit);

        // Move insertion after the loop.
        ThisLoop.Exit->moveAfter(Builder.GetInsertBlock());
        DataPtr = ThisLoop.DataPtrExit;
        Builder.SetInsertPoint(ThisLoop.Exit);
        break;
    }
  }

  // Ensure all loops have been closed.
  if (!Loops.empty()) {
    fputs("[ requires matching ]\n", stderr);
    abort();
  }

  // Finish off brainfuck_main and dump.
  Builder.CreateRetVoid();
  MainModule.print(outs(), NULL /* assembly annotation writer */);
}
<|endoftext|>


<commit_before>d2b37ea6-ad59-11e7-b3a5-ac87a332f658<commit_msg>NO CHANGES<commit_after>d3664766-ad59-11e7-ab81-ac87a332f658<|endoftext|>


<commit_before>6c6f32e3-2749-11e6-94da-e0f84713e7b8<commit_msg>Fixed that one bug<commit_after>6c7ea435-2749-11e6-8467-e0f84713e7b8<|endoftext|>


<commit_before>#include "gui/squaredetailwindow.hpp"

#include "gui/ng/label.hpp"

#include "gui/texturemanager.hpp"
#include "gui/guihelper.hpp"

#include "engine/square.hpp"

namespace qrw
{

SquareDetailWindow::SquareDetailWindow()
{
    setSize({400.0f, 150.0f});
    setAnchor({0.0f, 1.0f});
    setParentAnchor({0.0f, 1.0f});

    float labelHeight = 50;

    // ------------------
    // Labels for displaying unit information
    // ------------------
    namelessgui::Label* label;
    label = new namelessgui::Label();
    label->setSize({100, labelHeight});
    label->setText("Unit name");
    label->setImage(TextureManager::getInstance()->getTexture("p1swordman"));
    label->setRelativePosition({0, 0});
    _unitTitleLabel = label;
    addWidget(_unitTitleLabel);

    label = new namelessgui::Label();
    label->setSize({100, labelHeight});
    label->setText("20 / 100 HP");
    label->setImage(TextureManager::getInstance()->getTexture("health"));
    label->setRelativePosition({0, labelHeight});
    _unitHealthLabel = label;
    addWidget(_unitHealthLabel);

	label = new namelessgui::Label();
	label->setSize({100, labelHeight});
	label->setText("movement");
	label->setImage(TextureManager::getInstance()->getTexture("movement"));
	label->setRelativePosition({150, labelHeight});
	_unitMovementLabel = label;
	addWidget(_unitMovementLabel);

    label = new namelessgui::Label();
    label->setSize({100, labelHeight});
    label->setText("3");
    label->setImage(TextureManager::getInstance()->getTexture("attack"));
    label->setRelativePosition({0, 2 * labelHeight});
    _unitAttackLabel = label;
    addWidget(_unitAttackLabel);

    label = new namelessgui::Label();
    label->setSize({100, labelHeight});
    label->setText("2");
    label->setImage(TextureManager::getInstance()->getTexture("defense"));
	label->setRelativePosition({150, 2 * labelHeight});
    _unitDefenseLabel = label;
    addWidget(_unitDefenseLabel);

    // ------------------
    // Labels for displaying terrain information
    // ------------------
    label = new namelessgui::Label();
    label->setSize({100, labelHeight});
    label->setText("Wall");
    label->setImage(TextureManager::getInstance()->getTexture("wall"));
    label->setParentAnchor({1, 0});
    label->setRelativePosition({-200, 0});
    _terrainTitleLabel = label;
    addWidget(_terrainTitleLabel);

    label = new namelessgui::Label();
    label->setSize({100, labelHeight});
    label->setText("+1");
    label->setImage(TextureManager::getInstance()->getTexture("attack"));
    label->setParentAnchor({1, 0});
    label->setRelativePosition({-200, labelHeight});
    _terrainAttackLabel = label;
    addWidget(_terrainAttackLabel);

    label = new namelessgui::Label();
    label->setSize({100, labelHeight});
    label->setText("-1");
    label->setImage(TextureManager::getInstance()->getTexture("defense"));
    label->setParentAnchor({1, 0});
    label->setRelativePosition({-100, labelHeight});
    _terrainDefenseLabel = label;
    addWidget(_terrainDefenseLabel);
}

void SquareDetailWindow::setUnitAndTerrain(Unit::Ptr unit, Terrain::Ptr terrain)
{
	checkAndSetVisibility(unit, terrain);
	setUnit(unit);
	setTerrain(terrain);
}

void SquareDetailWindow::setUnit(Unit::Ptr unit)
{
	if(unit != nullptr)
    {
        _unitTitleLabel->setVisible(true);
		_unitTitleLabel->setImage(unit->getTexture());
        _unitTitleLabel->setText(GuiHelper::getUnitName(unit));

        _unitHealthLabel->setVisible(true);
		_unitHealthLabel->setText(std::to_string(unit->getHP()) + "/" + std::to_string(unit->getMaxHp()));

		_unitMovementLabel->setVisible(true);
		_unitMovementLabel->setText(std::to_string(unit->getCurrentMovement()) + "/" + std::to_string(unit->getMovement()));

        _unitAttackLabel->setVisible(true);
        _unitAttackLabel->setText(std::to_string(unit->getBaseAttack()));

        _unitDefenseLabel->setVisible(true);
        _unitDefenseLabel->setText(std::to_string(unit->getBaseDefense()));
    }
    else
    {
        _unitTitleLabel->setVisible(false);
        _unitHealthLabel->setVisible(false);
		_unitMovementLabel->setVisible(false);
        _unitAttackLabel->setVisible(false);
        _unitDefenseLabel->setVisible(false);
    }
}

void SquareDetailWindow::setTerrain(Terrain::Ptr terrain)
{
	if(terrain != nullptr)
    {
        _terrainTitleLabel->setVisible(true);
        _terrainTitleLabel->setImage(GuiHelper::getTerrainTexture(terrain));
        _terrainTitleLabel->setText(GuiHelper::getTerrainName(terrain));

        _terrainAttackLabel->setVisible(true);
        _terrainAttackLabel->setText(std::to_string(terrain->getModificator(MODIFICATORS::EM_ATTACK)));

        _terrainDefenseLabel->setVisible(true);
        _terrainDefenseLabel->setText(std::to_string(terrain->getModificator(MODIFICATORS::EM_DEFENSE)));

    }
    else
    {
        _terrainTitleLabel->setVisible(false);
        _terrainAttackLabel->setVisible(false);
        _terrainDefenseLabel->setVisible(false);
	}
}

void SquareDetailWindow::checkAndSetVisibility(Unit::Ptr unit, Terrain::Ptr terrain)
{
	setVisible(unit != nullptr || terrain != nullptr);
}

} // namespace qrw
<commit_msg>Fixed overlapping texts in square detail window.<commit_after>#include "gui/squaredetailwindow.hpp"

#include "gui/ng/label.hpp"

#include "gui/texturemanager.hpp"
#include "gui/guihelper.hpp"

#include "engine/square.hpp"

namespace qrw
{

SquareDetailWindow::SquareDetailWindow()
{
    setSize({400.0f, 150.0f});
    setAnchor({0.0f, 1.0f});
    setParentAnchor({0.0f, 1.0f});

    float labelHeight = 50;

    // ------------------
    // Labels for displaying unit information
    // ------------------
    namelessgui::Label* label;
    label = new namelessgui::Label();
    label->setSize({100, labelHeight});
    label->setText("Unit name");
    label->setImage(TextureManager::getInstance()->getTexture("p1swordman"));
    label->setRelativePosition({0, 0});
    _unitTitleLabel = label;
    addWidget(_unitTitleLabel);

    label = new namelessgui::Label();
    label->setSize({100, labelHeight});
    label->setText("20 / 100 HP");
    label->setImage(TextureManager::getInstance()->getTexture("health"));
    label->setRelativePosition({0, labelHeight});
    _unitHealthLabel = label;
    addWidget(_unitHealthLabel);

	label = new namelessgui::Label();
	label->setSize({100, labelHeight});
	label->setText("movement");
	label->setImage(TextureManager::getInstance()->getTexture("movement"));
	label->setRelativePosition({100, labelHeight});
	_unitMovementLabel = label;
	addWidget(_unitMovementLabel);

    label = new namelessgui::Label();
    label->setSize({100, labelHeight});
    label->setText("3");
    label->setImage(TextureManager::getInstance()->getTexture("attack"));
    label->setRelativePosition({0, 2 * labelHeight});
    _unitAttackLabel = label;
    addWidget(_unitAttackLabel);

    label = new namelessgui::Label();
    label->setSize({100, labelHeight});
    label->setText("2");
    label->setImage(TextureManager::getInstance()->getTexture("defense"));
	label->setRelativePosition({100, 2 * labelHeight});
    _unitDefenseLabel = label;
    addWidget(_unitDefenseLabel);

    // ------------------
    // Labels for displaying terrain information
    // ------------------
    label = new namelessgui::Label();
    label->setSize({100, labelHeight});
    label->setText("Wall");
    label->setImage(TextureManager::getInstance()->getTexture("wall"));
    label->setParentAnchor({1, 0});
    label->setRelativePosition({-200, 0});
    _terrainTitleLabel = label;
    addWidget(_terrainTitleLabel);

    label = new namelessgui::Label();
    label->setSize({100, labelHeight});
    label->setText("+1");
    label->setImage(TextureManager::getInstance()->getTexture("attack"));
    label->setParentAnchor({1, 0});
    label->setRelativePosition({-200, labelHeight});
    _terrainAttackLabel = label;
    addWidget(_terrainAttackLabel);

    label = new namelessgui::Label();
    label->setSize({100, labelHeight});
    label->setText("-1");
    label->setImage(TextureManager::getInstance()->getTexture("defense"));
    label->setParentAnchor({1, 0});
    label->setRelativePosition({-100, labelHeight});
    _terrainDefenseLabel = label;
    addWidget(_terrainDefenseLabel);
}

void SquareDetailWindow::setUnitAndTerrain(Unit::Ptr unit, Terrain::Ptr terrain)
{
	checkAndSetVisibility(unit, terrain);
	setUnit(unit);
	setTerrain(terrain);
}

void SquareDetailWindow::setUnit(Unit::Ptr unit)
{
	if(unit != nullptr)
    {
        _unitTitleLabel->setVisible(true);
		_unitTitleLabel->setImage(unit->getTexture());
        _unitTitleLabel->setText(GuiHelper::getUnitName(unit));

        _unitHealthLabel->setVisible(true);
		_unitHealthLabel->setText(std::to_string(unit->getHP()) + "/" + std::to_string(unit->getMaxHp()));

		_unitMovementLabel->setVisible(true);
		_unitMovementLabel->setText(std::to_string(unit->getCurrentMovement()) + "/" + std::to_string(unit->getMovement()));

        _unitAttackLabel->setVisible(true);
        _unitAttackLabel->setText(std::to_string(unit->getBaseAttack()));

        _unitDefenseLabel->setVisible(true);
        _unitDefenseLabel->setText(std::to_string(unit->getBaseDefense()));
    }
    else
    {
        _unitTitleLabel->setVisible(false);
        _unitHealthLabel->setVisible(false);
		_unitMovementLabel->setVisible(false);
        _unitAttackLabel->setVisible(false);
        _unitDefenseLabel->setVisible(false);
    }
}

void SquareDetailWindow::setTerrain(Terrain::Ptr terrain)
{
	if(terrain != nullptr)
    {
        _terrainTitleLabel->setVisible(true);
        _terrainTitleLabel->setImage(GuiHelper::getTerrainTexture(terrain));
        _terrainTitleLabel->setText(GuiHelper::getTerrainName(terrain));

        _terrainAttackLabel->setVisible(true);
        _terrainAttackLabel->setText(std::to_string(terrain->getModificator(MODIFICATORS::EM_ATTACK)));

        _terrainDefenseLabel->setVisible(true);
        _terrainDefenseLabel->setText(std::to_string(terrain->getModificator(MODIFICATORS::EM_DEFENSE)));

    }
    else
    {
        _terrainTitleLabel->setVisible(false);
        _terrainAttackLabel->setVisible(false);
        _terrainDefenseLabel->setVisible(false);
	}
}

void SquareDetailWindow::checkAndSetVisibility(Unit::Ptr unit, Terrain::Ptr terrain)
{
	setVisible(unit != nullptr || terrain != nullptr);
}

} // namespace qrw
<|endoftext|>


<commit_before>#include "kyheader.h"

#ifdef _WIN32
#include <windows.h>
#include <shlobj.h>
#include <Commdlg.h>
#include <ShellAPI.h>
#else
#include <iostream>
#include <stdlib.h>
#include <sys/stat.h>
#include <dirent.h>
#endif

// Get image names from a wildcard. Eg: GetNames("D:\\*.jpg", imgNames);
int CmFile::GetNames(CStr &_nameW, vecS &_names)
{
    string _dir = GetFolder(_nameW);
    _names.clear();

    DIR *dir;
    struct dirent *ent;
    if((dir = opendir(_dir.c_str()))!=NULL){
        //print all the files and directories within directory
        while((ent = readdir(dir))!=NULL){
            if(ent->d_name[0] == '.')
                continue;
            if(ent->d_type ==4)
                continue;
            _names.push_back(ent->d_name);
        }
        closedir(dir);
    } else {
        perror("");
        return EXIT_FAILURE;
    }
    return (int)_names.size();
}
int CmFile::GetNames(CStr &_nameW, vecS &_names, string &_dir)
{
    _dir = GetFolder(_nameW);
    _names.clear();

    DIR *dir;
    struct dirent *ent;
    if((dir = opendir(_dir.c_str()))!=NULL){
        //print all the files and directories within directory
        while((ent = readdir(dir))!=NULL){
            if(ent->d_name[0] == '.')
                continue;
            if(ent->d_type ==4)
                continue;
            _names.push_back(ent->d_name);
        }
        closedir(dir);
    } else {
        perror("");
        return EXIT_FAILURE;
    }
    return (int)_names.size();
}
int CmFile::GetSubFolders(CStr &folder, vecS &subFolders)
{
    subFolders.clear();
    string nameWC = GetFolder(folder);//folder + "/*";

    DIR *dir;
    struct dirent *ent;
    if((dir = opendir(nameWC.c_str()))!=NULL){
        while((ent = readdir(dir))!=NULL){
            if(ent->d_name[0] == '.')
                continue;
            if(ent->d_type == 4){
                subFolders.push_back(ent->d_name);
            }
        }
        closedir(dir);
    } else {
        perror("");
        return EXIT_FAILURE;
    }
    return (int)subFolders.size();
}
int CmFile::GetNames(CStr& rootFolder, CStr &fileW, vecS &names)
{
    GetNames(rootFolder + fileW, names);
    vecS subFolders, tmpNames;
    int subNum = CmFile::GetSubFolders(rootFolder, subFolders);//
    for (int i = 0; i < subNum; i++){
        subFolders[i] += "/";
        int subNum = GetNames(rootFolder + subFolders[i], fileW, tmpNames);
        for (int j = 0; j < subNum; j++)
            names.push_back(subFolders[i] + tmpNames[j]);
    }
    return (int)names.size();
}
int CmFile::GetNamesNE(CStr& nameWC, vecS &names)
{
    string dir = string();
    string ext = string();
    int fNum = GetNames(nameWC, names, dir);
    ext = GetExtention(nameWC);
    for (int i = 0; i < fNum; i++)
        names[i] = GetNameNE(names[i]);
    return fNum;
}
int CmFile::GetNamesNE(CStr& nameWC, vecS &names, string &dir, string &ext)
{
    int fNum = GetNames(nameWC, names, dir);
    ext = GetExtention(nameWC);
    for (int i = 0; i < fNum; i++)
        names[i] = GetNameNE(names[i]);
    return fNum;
}
int CmFile::GetNamesNE(CStr& rootFolder, CStr &fileW, vecS &names)
{
    int fNum = GetNames(rootFolder, fileW, names);
    int extS = GetExtention(fileW).size();
    for (int i = 0; i < fNum; i++)
        names[i].resize(names[i].size() - extS);
    return fNum;
}
bool CmFile::MkDir(CStr &_path)
{
    if(_path.size() == 0)
        return false;
    static char buffer[1024];
    strcpy(buffer, _S(_path));
#ifdef _WIN32
    for (int i = 0; buffer[i] != 0; i ++) {
        if (buffer[i] == '\\' || buffer[i] == '/') {
            buffer[i] = '\0';
            CreateDirectoryA(buffer, 0);
            buffer[i] = '/';
        }
    }
    return CreateDirectoryA(_S(_path), 0);
#else
    for (int i = 0; buffer[i] != 0; i ++) {
        if (buffer[i] == '\\' || buffer[i] == '/') {
            buffer[i] = '\0';
            mkdir(buffer, 0);
            buffer[i] = '/';
        }
    }
    return mkdir(_S(_path), 0);
#endif
}
vecS CmFile::loadStrList(CStr &fName)
{
    ifstream fIn(fName);
    string line;
    vecS strs;
    while(getline(fIn, line) && line.size()){
        unsigned sz = line.size();
        line.resize(sz - 1); //Please use script to convert the VOC format data into the OpenCV format data
        //line.resize(sz);
        strs.push_back(line);
    }
    return strs;
}
bool CmFile::writeStrList(CStr &fName, const vecS &strs)
{
    FILE *f = fopen(_S(fName), "w");
    if (f == NULL)
        return false;
    for (size_t i = 0; i < strs.size(); i++)
        fprintf(f, "%s\n", _S(strs[i]));
    fclose(f);
    return true;
}
<commit_msg>Update CmFile.cpp<commit_after>#include "kyheader.h"

#ifdef _WIN32
#include <windows.h>
#include <shlobj.h>
#include <Commdlg.h>
#include <ShellAPI.h>
#else
#include <iostream>
#include <stdlib.h>
#include <sys/stat.h>
#include <dirent.h>
#endif

// Get image names from a wildcard. Eg: GetNames("D:\\*.jpg", imgNames);
int CmFile::GetNames(CStr &_nameW, vecS &_names)
{
    string _dir = GetFolder(_nameW);
    _names.clear();

    DIR *dir;
    struct dirent *ent;
    if((dir = opendir(_dir.c_str()))!=NULL){
        //print all the files and directories within directory
        while((ent = readdir(dir))!=NULL){
            if(ent->d_name[0] == '.')
                continue;
            if(ent->d_type ==4)
                continue;
            _names.push_back(ent->d_name);
        }
        closedir(dir);
    } else {
        perror("");
        return EXIT_FAILURE;
    }
    return (int)_names.size();
}
int CmFile::GetNames(CStr &_nameW, vecS &_names, string &_dir)
{
    _dir = GetFolder(_nameW);
    _names.clear();

    DIR *dir;
    struct dirent *ent;
    if((dir = opendir(_dir.c_str()))!=NULL){
        //print all the files and directories within directory
        while((ent = readdir(dir))!=NULL){
            if(ent->d_name[0] == '.')
                continue;
            if(ent->d_type ==4)
                continue;
            _names.push_back(ent->d_name);
        }
        closedir(dir);
    } else {
        perror("");
        return EXIT_FAILURE;
    }
    return (int)_names.size();
}
int CmFile::GetSubFolders(CStr &folder, vecS &subFolders)
{
    subFolders.clear();
    string nameWC = GetFolder(folder);//folder + "/*";

    DIR *dir;
    struct dirent *ent;
    if((dir = opendir(nameWC.c_str()))!=NULL){
        while((ent = readdir(dir))!=NULL){
            if(ent->d_name[0] == '.')
                continue;
            if(ent->d_type == 4){
                subFolders.push_back(ent->d_name);
            }
        }
        closedir(dir);
    } else {
        perror("");
        return EXIT_FAILURE;
    }
    return (int)subFolders.size();
}
int CmFile::GetNames(CStr& rootFolder, CStr &fileW, vecS &names)
{
    GetNames(rootFolder + fileW, names);
    vecS subFolders, tmpNames;
    int subNum = CmFile::GetSubFolders(rootFolder, subFolders);//
    for (int i = 0; i < subNum; i++){
        subFolders[i] += "/";
        int subNum = GetNames(rootFolder + subFolders[i], fileW, tmpNames);
        for (int j = 0; j < subNum; j++)
            names.push_back(subFolders[i] + tmpNames[j]);
    }
    return (int)names.size();
}
int CmFile::GetNamesNE(CStr& nameWC, vecS &names)
{
    string dir = string();
    string ext = string();
    int fNum = GetNames(nameWC, names, dir);
    ext = GetExtention(nameWC);
    for (int i = 0; i < fNum; i++)
        names[i] = GetNameNE(names[i]);
    return fNum;
}
int CmFile::GetNamesNE(CStr& nameWC, vecS &names, string &dir, string &ext)
{
    int fNum = GetNames(nameWC, names, dir);
    ext = GetExtention(nameWC);
    for (int i = 0; i < fNum; i++)
        names[i] = GetNameNE(names[i]);
    return fNum;
}
int CmFile::GetNamesNE(CStr& rootFolder, CStr &fileW, vecS &names)
{
    int fNum = GetNames(rootFolder, fileW, names);
    int extS = GetExtention(fileW).size();
    for (int i = 0; i < fNum; i++)
        names[i].resize(names[i].size() - extS);
    return fNum;
}
bool CmFile::MkDir(CStr &_path)
{
    if(_path.size() == 0)
        return false;
    static char buffer[1024];
    strcpy(buffer, _S(_path));
#ifdef _WIN32
    for (int i = 0; buffer[i] != 0; i ++) {
        if (buffer[i] == '\\' || buffer[i] == '/') {
            buffer[i] = '\0';
            CreateDirectoryA(buffer, 0);
            buffer[i] = '/';
        }
    }
    return CreateDirectoryA(_S(_path), 0);
#else
    for (int i = 0; buffer[i] != 0; i ++) {
        if (buffer[i] == '\\' || buffer[i] == '/') {
            buffer[i] = '\0';
            mkdir(buffer, 0755);
            buffer[i] = '/';
        }
    }
    return mkdir(_S(_path), 0755);
#endif
}
vecS CmFile::loadStrList(CStr &fName)
{
    ifstream fIn(fName);
    string line;
    vecS strs;
    while(getline(fIn, line) && line.size()){
        unsigned sz = line.size();
        line.resize(sz - 1); //Please use script to convert the VOC format data into the OpenCV format data
        //line.resize(sz);
        strs.push_back(line);
    }
    return strs;
}
bool CmFile::writeStrList(CStr &fName, const vecS &strs)
{
    FILE *f = fopen(_S(fName), "w");
    if (f == NULL)
        return false;
    for (size_t i = 0; i < strs.size(); i++)
        fprintf(f, "%s\n", _S(strs[i]));
    fclose(f);
    return true;
}
<|endoftext|>


<commit_before>// Copyright (c) 2013-2014 Anton Kozhevnikov, Thomas Schulthess
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without modification, are permitted provided that
// the following conditions are met:
//
// 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the
//    following disclaimer.
// 2. 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.
//
// 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 HOLDER 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.

/** \file timer.cpp
 *
 *  \brief Contains remaining implementation of sirius::Timer class.
 */

#include "timer.h"

namespace sirius
{

std::map<std::string, Timer*> ftimers;

std::map<std::string, std::vector<double> > Timer::timers_;
std::map<std::string, std::vector<double> > Timer::global_timers_;

void Timer::start()
{
    if (active_)
    {
        printf("timer %s is already running\n", label_.c_str());
        Platform::abort();
    }

    gettimeofday(&starting_time_, NULL);
    active_ = true;
}

void Timer::stop()
{
    if (!active_)
    {
        printf("timer %s was not running\n", label_.c_str());
        Platform::abort();
    }

    timeval end;
    gettimeofday(&end, NULL);

    double val = double(end.tv_sec - starting_time_.tv_sec) +
                 double(end.tv_usec - starting_time_.tv_usec) / 1e6;

    switch (timer_type_)
    {
        case _local_timer_:
        {
            timers_[label_].push_back(val);
            break;
        }
        case _global_timer_:
        {
            global_timers_[label_].push_back(val);
            break;
        }
    }

    active_ = false;
}

double Timer::value()
{
    if (active_)
    {
        std::stringstream s;
        s << "timer " << label_ << " is active";
        error_local(__FILE__, __LINE__, s);
    }
    std::vector<double> values;
    switch (timer_type_)
    {
        case _local_timer_:
        {
            values = timers_[label_];
            break;
        }
        case _global_timer_:
        {
            values = global_timers_[label_];
            break;
        }
    }
    double d = 0;
    for (int i = 0; i < (int)values.size(); i++) d += values[i];
    return d;
}

extern "C" void print_cuda_timers();

void Timer::print()
{
    std::map< std::string, timer_stats> tstats = collect_timer_stats();

    if (Platform::mpi_rank() == 0)
    {
        printf("\n");
        printf("Timers\n");
        for (int i = 0; i < 115; i++) printf("-");
        printf("\n");
        printf("name                                                              count      total        min        max    average\n");
        for (int i = 0; i < 115; i++) printf("-");
        printf("\n");

        std::map<std::string, timer_stats>::iterator it;
        for (it = tstats.begin(); it != tstats.end(); it++)
        {
            auto ts = it->second;
            if (ts.timer_type == _local_timer_)
            {
                printf("%-60s :    %5i %10.4f %10.4f %10.4f %10.4f\n", it->first.c_str(), ts.count, ts.total_value,
                       ts.min_value, ts.max_value, ts.average_value);
            }
            if (ts.timer_type == _global_timer_)
            {
                printf("%-60s :    %5i %10.4f %10.4f %10.4f %10.4f +\n", it->first.c_str(), ts.count, ts.total_value,
                       ts.min_value, ts.max_value, ts.average_value);
            }
        }

        #ifdef _GPU_
        print_cuda_timers();
        #endif
    }
}

void Timer::delay(double dsec)
{
    timeval t1;
    timeval t2;
    double d;

    gettimeofday(&t1, NULL);
    do
    {
        gettimeofday(&t2, NULL);
        d = double(t2.tv_sec - t1.tv_sec) + double(t2.tv_usec - t1.tv_usec) / 1e6;
    } while (d < dsec);
}

std::map< std::string, timer_stats> Timer::collect_timer_stats()
{
    std::map< std::string, timer_stats> tstats;

    //std::map<std::string, std::vector<double> >::iterator it;

    /* collect local timers */
    for (auto& it: timers_)
    {
        timer_stats ts;

        ts.timer_type = _local_timer_;
        ts.count = (int)it.second.size();
        ts.total_value = 0.0;
        ts.min_value = 1e100;
        ts.max_value = 0.0;
        for (int i = 0; i < ts.count; i++)
        {
            ts.total_value += it.second[i];
            ts.min_value = std::min(ts.min_value, it.second[i]);
            ts.max_value = std::max(ts.max_value, it.second[i]);
        }
        ts.average_value = (ts.count == 0) ? 0.0 : ts.total_value / ts.count;
        if (ts.count == 0) ts.min_value = 0.0;

        tstats[it.first] = ts;
    }

    /* collect and broadcast global timer labels from rank#0 */
    std::vector< std::string > labels;
    std::vector<int> label_sizes;
    std::vector<char> label_str;
    if (Platform::mpi_rank() == 0)
    {
        for (auto& it: global_timers_)
        {
            /* save timer's label */
            labels.push_back(it.first);
            /* save length of the label */
            label_sizes.push_back((int)it.first.size());
            /* save label in the single array */
            for (int i = 0; i < (int)it.first.size(); i++) label_str.push_back(it.first[i]);
        }
    }

    // TODO: this can be moved to Platform::bcast

    /* broadcast the number of labels from rank#0 */
    int n = (int)label_sizes.size();
    Platform::bcast(&n, 1, 0);
    /* each MPI rank allocates space for label sizes */
    if (Platform::mpi_rank() != 0) label_sizes.resize(n);
    /* broadacst label sizes from rank#0 */
    Platform::bcast(&label_sizes[0], n, 0);

    /* broadcast the size of labels buffer from rank#0 */
    n = (int)label_str.size();
    Platform::bcast(&n, 1, 0);
    /* allocate space for labels buffer */
    if (Platform::mpi_rank() != 0) label_str.resize(n);
    /* broadcast labels buffer */
    Platform::bcast(&label_str[0], n, 0);

    /* construct list of labels exactly like on rank#0 */
    if (Platform::mpi_rank() != 0)
    {
        int offset = 0;
        for (int sz: label_sizes)
        {
            labels.push_back(std::string(&label_str[offset], sz));
            offset += sz;
        }
    }

    /* now all MPI ranks loop over the same sequence of global timer labels */
    for (auto& label: labels)
    {
        timer_stats ts;

        ts.timer_type = _global_timer_;

        /* this MPI rank doesn't have a corresponding timer */
        if (global_timers_.count(label) == 0)
        {
            ts.count = 0;
            ts.total_value = 0.0;
            ts.min_value = 0.0;
            ts.max_value = 0.0;
            ts.average_value = 0.0;
        }
        else
        {
            ts.count = (int)global_timers_[label].size();
            ts.total_value = 0.0;
            ts.min_value = 1e100;
            ts.max_value = 0.0;
            /* loop over timer measurements and collect total, min, max, average */
            for (int k = 0; k < ts.count; k++)
            {
                double v = global_timers_[label][k];
                ts.total_value += v;
                ts.min_value = std::min(ts.min_value, v);
                ts.max_value = std::max(ts.max_value, v);
            }
            ts.average_value = (ts.count == 0) ? 0.0 : ts.total_value / ts.count;
            if (ts.count == 0) ts.min_value = 0.0;
        }

        /* collect timer counts from all ranks */
        std::vector<int> counts(Platform::num_mpi_ranks());
        counts[Platform::mpi_rank()] = ts.count;
        Platform::allgather(&counts[0], Platform::mpi_rank(), 1);

        /* collect timer statistics from all ranks */
        std::vector<double> values(4 * Platform::num_mpi_ranks());
        values[4 * Platform::mpi_rank() + 0] = ts.total_value;
        values[4 * Platform::mpi_rank() + 1] = ts.min_value;
        values[4 * Platform::mpi_rank() + 2] = ts.max_value;
        values[4 * Platform::mpi_rank() + 3] = ts.average_value;

        Platform::allgather(&values[0], 4 * Platform::mpi_rank(), 4);

        double max_total_value = 0;
        double total_value = 0;
        int total_count = 0;
        for (int k = 0; k < Platform::num_mpi_ranks(); k++)
        {
            /* maximum total value across all ranks */
            max_total_value = std::max(max_total_value, values[4 * k + 0]);
            /* minimum value across all ranks */
            ts.min_value = std::min(ts.min_value, values[4 * k + 1]);
            /* maximum value across all ranks */
            ts.max_value = std::max(ts.max_value, values[4 * k + 2]);
            /* total global value */
            total_value += values[4 * k + 0];
            /* total number of counts */
            total_count += counts[k];
        }
        /* report maximum total value across all ranks */
        ts.total_value = max_total_value;
        ts.average_value = (total_count == 0) ? 0.0 : total_value / total_count;

        tstats[label] = ts;
    }

    return tstats;
}

};

<commit_msg>no namespace for Fortran timers<commit_after>// Copyright (c) 2013-2014 Anton Kozhevnikov, Thomas Schulthess
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without modification, are permitted provided that
// the following conditions are met:
//
// 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the
//    following disclaimer.
// 2. 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.
//
// 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 HOLDER 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.

/** \file timer.cpp
 *
 *  \brief Contains remaining implementation of sirius::Timer class.
 */

#include "timer.h"

std::map<std::string, sirius::Timer*> ftimers;

namespace sirius
{

std::map<std::string, std::vector<double> > Timer::timers_;
std::map<std::string, std::vector<double> > Timer::global_timers_;

void Timer::start()
{
    if (active_)
    {
        printf("timer %s is already running\n", label_.c_str());
        Platform::abort();
    }

    gettimeofday(&starting_time_, NULL);
    active_ = true;
}

void Timer::stop()
{
    if (!active_)
    {
        printf("timer %s was not running\n", label_.c_str());
        Platform::abort();
    }

    timeval end;
    gettimeofday(&end, NULL);

    double val = double(end.tv_sec - starting_time_.tv_sec) +
                 double(end.tv_usec - starting_time_.tv_usec) / 1e6;

    switch (timer_type_)
    {
        case _local_timer_:
        {
            timers_[label_].push_back(val);
            break;
        }
        case _global_timer_:
        {
            global_timers_[label_].push_back(val);
            break;
        }
    }

    active_ = false;
}

double Timer::value()
{
    if (active_)
    {
        std::stringstream s;
        s << "timer " << label_ << " is active";
        error_local(__FILE__, __LINE__, s);
    }
    std::vector<double> values;
    switch (timer_type_)
    {
        case _local_timer_:
        {
            values = timers_[label_];
            break;
        }
        case _global_timer_:
        {
            values = global_timers_[label_];
            break;
        }
    }
    double d = 0;
    for (int i = 0; i < (int)values.size(); i++) d += values[i];
    return d;
}

extern "C" void print_cuda_timers();

void Timer::print()
{
    std::map< std::string, timer_stats> tstats = collect_timer_stats();

    if (Platform::mpi_rank() == 0)
    {
        printf("\n");
        printf("Timers\n");
        for (int i = 0; i < 115; i++) printf("-");
        printf("\n");
        printf("name                                                              count      total        min        max    average\n");
        for (int i = 0; i < 115; i++) printf("-");
        printf("\n");

        std::map<std::string, timer_stats>::iterator it;
        for (it = tstats.begin(); it != tstats.end(); it++)
        {
            auto ts = it->second;
            if (ts.timer_type == _local_timer_)
            {
                printf("%-60s :    %5i %10.4f %10.4f %10.4f %10.4f\n", it->first.c_str(), ts.count, ts.total_value,
                       ts.min_value, ts.max_value, ts.average_value);
            }
            if (ts.timer_type == _global_timer_)
            {
                printf("%-60s :    %5i %10.4f %10.4f %10.4f %10.4f +\n", it->first.c_str(), ts.count, ts.total_value,
                       ts.min_value, ts.max_value, ts.average_value);
            }
        }

        #ifdef _GPU_
        print_cuda_timers();
        #endif
    }
}

void Timer::delay(double dsec)
{
    timeval t1;
    timeval t2;
    double d;

    gettimeofday(&t1, NULL);
    do
    {
        gettimeofday(&t2, NULL);
        d = double(t2.tv_sec - t1.tv_sec) + double(t2.tv_usec - t1.tv_usec) / 1e6;
    } while (d < dsec);
}

std::map< std::string, timer_stats> Timer::collect_timer_stats()
{
    std::map< std::string, timer_stats> tstats;

    //std::map<std::string, std::vector<double> >::iterator it;

    /* collect local timers */
    for (auto& it: timers_)
    {
        timer_stats ts;

        ts.timer_type = _local_timer_;
        ts.count = (int)it.second.size();
        ts.total_value = 0.0;
        ts.min_value = 1e100;
        ts.max_value = 0.0;
        for (int i = 0; i < ts.count; i++)
        {
            ts.total_value += it.second[i];
            ts.min_value = std::min(ts.min_value, it.second[i]);
            ts.max_value = std::max(ts.max_value, it.second[i]);
        }
        ts.average_value = (ts.count == 0) ? 0.0 : ts.total_value / ts.count;
        if (ts.count == 0) ts.min_value = 0.0;

        tstats[it.first] = ts;
    }

    /* collect and broadcast global timer labels from rank#0 */
    std::vector< std::string > labels;
    std::vector<int> label_sizes;
    std::vector<char> label_str;
    if (Platform::mpi_rank() == 0)
    {
        for (auto& it: global_timers_)
        {
            /* save timer's label */
            labels.push_back(it.first);
            /* save length of the label */
            label_sizes.push_back((int)it.first.size());
            /* save label in the single array */
            for (int i = 0; i < (int)it.first.size(); i++) label_str.push_back(it.first[i]);
        }
    }

    // TODO: this can be moved to Platform::bcast

    /* broadcast the number of labels from rank#0 */
    int n = (int)label_sizes.size();
    Platform::bcast(&n, 1, 0);
    /* each MPI rank allocates space for label sizes */
    if (Platform::mpi_rank() != 0) label_sizes.resize(n);
    /* broadacst label sizes from rank#0 */
    Platform::bcast(&label_sizes[0], n, 0);

    /* broadcast the size of labels buffer from rank#0 */
    n = (int)label_str.size();
    Platform::bcast(&n, 1, 0);
    /* allocate space for labels buffer */
    if (Platform::mpi_rank() != 0) label_str.resize(n);
    /* broadcast labels buffer */
    Platform::bcast(&label_str[0], n, 0);

    /* construct list of labels exactly like on rank#0 */
    if (Platform::mpi_rank() != 0)
    {
        int offset = 0;
        for (int sz: label_sizes)
        {
            labels.push_back(std::string(&label_str[offset], sz));
            offset += sz;
        }
    }

    /* now all MPI ranks loop over the same sequence of global timer labels */
    for (auto& label: labels)
    {
        timer_stats ts;

        ts.timer_type = _global_timer_;

        /* this MPI rank doesn't have a corresponding timer */
        if (global_timers_.count(label) == 0)
        {
            ts.count = 0;
            ts.total_value = 0.0;
            ts.min_value = 0.0;
            ts.max_value = 0.0;
            ts.average_value = 0.0;
        }
        else
        {
            ts.count = (int)global_timers_[label].size();
            ts.total_value = 0.0;
            ts.min_value = 1e100;
            ts.max_value = 0.0;
            /* loop over timer measurements and collect total, min, max, average */
            for (int k = 0; k < ts.count; k++)
            {
                double v = global_timers_[label][k];
                ts.total_value += v;
                ts.min_value = std::min(ts.min_value, v);
                ts.max_value = std::max(ts.max_value, v);
            }
            ts.average_value = (ts.count == 0) ? 0.0 : ts.total_value / ts.count;
            if (ts.count == 0) ts.min_value = 0.0;
        }

        /* collect timer counts from all ranks */
        std::vector<int> counts(Platform::num_mpi_ranks());
        counts[Platform::mpi_rank()] = ts.count;
        Platform::allgather(&counts[0], Platform::mpi_rank(), 1);

        /* collect timer statistics from all ranks */
        std::vector<double> values(4 * Platform::num_mpi_ranks());
        values[4 * Platform::mpi_rank() + 0] = ts.total_value;
        values[4 * Platform::mpi_rank() + 1] = ts.min_value;
        values[4 * Platform::mpi_rank() + 2] = ts.max_value;
        values[4 * Platform::mpi_rank() + 3] = ts.average_value;

        Platform::allgather(&values[0], 4 * Platform::mpi_rank(), 4);

        double max_total_value = 0;
        double total_value = 0;
        int total_count = 0;
        for (int k = 0; k < Platform::num_mpi_ranks(); k++)
        {
            /* maximum total value across all ranks */
            max_total_value = std::max(max_total_value, values[4 * k + 0]);
            /* minimum value across all ranks */
            ts.min_value = std::min(ts.min_value, values[4 * k + 1]);
            /* maximum value across all ranks */
            ts.max_value = std::max(ts.max_value, values[4 * k + 2]);
            /* total global value */
            total_value += values[4 * k + 0];
            /* total number of counts */
            total_count += counts[k];
        }
        /* report maximum total value across all ranks */
        ts.total_value = max_total_value;
        ts.average_value = (total_count == 0) ? 0.0 : total_value / total_count;

        tstats[label] = ts;
    }

    return tstats;
}

};

<|endoftext|>


<commit_before>/******************************************************************************
 *
 * timer.cpp
 *
 * @author Copyright (C) 2015 Kotone Itaya
 * @version 2.1.0
 * @created  2015/11/02 Kotone Itaya -- Created!
 * @@
 *
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements.  See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership.  The ASF licenses this file
 * to you 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 "spira/timer.hpp"

namespace spira {
  struct timer::impl {
    std::chrono::steady_clock::time_point init;
    std::chrono::steady_clock::time_point curr;
    double fps;
    unsigned long long int frame;
    unsigned long long int time;
  };

  timer::timer(double fps) : pimpl(std::shared_ptr<impl>(new impl())) {
    this->reset();
  }

  timer::timer(const timer& other) {
    this->pimpl = other.pimpl;
  }

  timer& timer::operator =(timer& other) {
    swap(*this, other);
    return *this;
  }

  void swap(timer& a, timer& b) {
    std::swap(a.pimpl, b.pimpl);
  }

  void timer::poll() {
    this->pimpl->curr = std::chrono::steady_clock::now();
    std::chrono::nanoseconds duration = (this->pimpl->curr - this->pimpl->init);
    this->pimpl->time = duration.count();
    unsigned long long int now = ((this->pimpl->time * this->pimpl->fps) / 1000000000);
    if(now > this->pimpl->frame) {
      while(now > this->pimpl->frame) this->dump(++this->pimpl->frame);
    }
  }

  void timer::reset() {
    this->pimpl->init = std::chrono::steady_clock::now();
    this->pimpl->frame = 0;
    this->pimpl->time = 0;
    this->dump(0);
  }
}
<commit_msg>Fixed bug in `timer` constructor.<commit_after>/******************************************************************************
 *
 * timer.cpp
 *
 * @author Copyright (C) 2015 Kotone Itaya
 * @version 2.1.0
 * @created  2015/11/02 Kotone Itaya -- Created!
 * @@
 *
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements.  See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership.  The ASF licenses this file
 * to you 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 "spira/timer.hpp"

namespace spira {
  struct timer::impl {
    std::chrono::steady_clock::time_point init;
    std::chrono::steady_clock::time_point curr;
    double fps;
    unsigned long long int frame;
    unsigned long long int time;
  };

  timer::timer(double fps) : pimpl(std::shared_ptr<impl>(new impl())) {
    this->pimpl->fps = fps;
    this->reset();
  }

  timer::timer(const timer& other) {
    this->pimpl = other.pimpl;
  }

  timer& timer::operator =(timer& other) {
    swap(*this, other);
    return *this;
  }

  void swap(timer& a, timer& b) {
    std::swap(a.pimpl, b.pimpl);
  }

  void timer::poll() {
    this->pimpl->curr = std::chrono::steady_clock::now();
    std::chrono::nanoseconds duration = (this->pimpl->curr - this->pimpl->init);
    this->pimpl->time = duration.count();
    unsigned long long int now = ((this->pimpl->time * this->pimpl->fps) / 1000000000);
    if(now > this->pimpl->frame) {
      while(now > this->pimpl->frame) this->dump(++this->pimpl->frame);
    }
  }

  void timer::reset() {
    this->pimpl->init = std::chrono::steady_clock::now();
    this->pimpl->frame = 0;
    this->pimpl->time = 0;
    this->dump(0);
  }
}
<|endoftext|>


<commit_before>30436c5c-2748-11e6-8a32-e0f84713e7b8<commit_msg>Fixed that one bug<commit_after>3054d542-2748-11e6-a941-e0f84713e7b8<|endoftext|>


<commit_before>#include <iostream>
#include <sched.h>
#include <stdlib.h>
#include <sys/wait.h>
#include <errno.h>
#include <unistd.h>
#include <sys/utsname.h>
#include <string>
#include <cstring>
#include <vector>
#include <algorithm>
#include "container.h"

int run(void* arg)
{
    const std::string name = "funny-name";
    char **argv = (char**) arg;

    Container::Builder builder;
    builder.set_hostname(name);
    Container container = builder.build();

    const std::vector<std::string> args(1);
    try
    {
        container.run_command((const std::string) argv[1], args);
    }
    catch (std::exception const &exc)
    {
        std::cerr << "Exception caught " << exc.what() << "\n";
    }

    struct utsname uts;
    std::cout << "This is child" << std::endl;
    uname(&uts);
    std::cout << "This is a child's nodename: " << uts.nodename << std::endl;
}

int main(int argc, char *argv[])
{
    struct utsname uts;

    char *stack = (char*) malloc(1024*1024);
    std::cout << "This is parent" << std::endl;
    pid_t pid = clone(run, (stack + 1024*1024), CLONE_NEWUTS | SIGCHLD, argv);
    if (pid == -1)
    {
        std::cout << "Creating new namespace failed. Error number: " << errno;
    }

    sleep(1);

    uname(&uts);
    std::cout << "This is a parent's nodename: " << uts.nodename << std::endl;
    waitpid(pid, NULL, 0);
}
<commit_msg>Removing unneded stuff<commit_after>#include <iostream>
#include <sched.h>
#include <stdlib.h>
#include <sys/wait.h>
#include <errno.h>
#include <unistd.h>
#include <sys/utsname.h>
#include <string>
#include <cstring>
#include <vector>
#include "container.h"

Container build_container()
{
    const std::string name = "funny-name";
    Container::Builder builder;
    builder.set_hostname(name);
    return builder.build();
}

int run(void* arg)
{
    char **argv = (char**) arg;
    const std::vector<std::string> args(1);

    Container container = build_container();
    try
    {
        container.run_command((const std::string) argv[1], args);
    }
    catch (const std::exception& exc)
    {
        std::cerr << "Exception caught " << exc.what() << "\n";
        exit(1);
    }
}

int main(int argc, char *argv[])
{
    struct utsname uts;
    char *stack = (char*) malloc(1024*1024);

    pid_t pid = clone(run, (stack + 1024*1024), CLONE_NEWUTS | SIGCHLD, argv);
    if (pid == -1)
    {
        std::cerr << "Creating new namespace failed. Error number: " << errno;
        exit(1);
    }

    sleep(1);

    uname(&uts);
    std::cout << "This is a parent's nodename: " << uts.nodename << std::endl;
    waitpid(pid, NULL, 0);
}
<|endoftext|>