<commit_before>/*
 * Software License Agreement (BSD License)
 *
 *  Point Cloud Library (PCL) - www.pointclouds.org
 *  Copyright (c) 2010-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, Inc. nor the names of its
 *     contributors may be used to endorse or promote products derived
 *     from this software without specific prior written permission.
 *
 *  THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 *  "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
 *  LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
 *  FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
 *  COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
 *  INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
 *  BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
 *  LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
 *  CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
 *  LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
 *  ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 *  POSSIBILITY OF SUCH DAMAGE.
 *
 */

#include <pcl/visualization/pcl_visualizer.h>
#include <pcl/io/pcd_io.h>
#include <pcl/registration/transforms.h>
#include <vtkPLYReader.h>
#include <vtkOBJReader.h>
#include <vtkTriangle.h>
#include <vtkTriangleFilter.h>
#include <vtkPolyDataMapper.h>
#include <pcl/filters/voxel_grid.h>
#include <pcl/console/print.h>
#include <pcl/console/parse.h>

inline double
uniform_deviate (int seed)
{
  double ran = seed * (1.0 / (RAND_MAX + 1.0));
  return ran;
}

inline void
randomPointTriangle (float a1, float a2, float a3, float b1, float b2, float b3, float c1, float c2, float c3,
                     Eigen::Vector4f& p)
{
  float r1 = uniform_deviate (rand ());
  float r2 = uniform_deviate (rand ());
  float r1sqr = sqrt (r1);
  float OneMinR1Sqr = (1 - r1sqr);
  float OneMinR2 = (1 - r2);
  a1 *= OneMinR1Sqr;
  a2 *= OneMinR1Sqr;
  a3 *= OneMinR1Sqr;
  b1 *= OneMinR2;
  b2 *= OneMinR2;
  b3 *= OneMinR2;
  c1 = r1sqr * (r2 * c1 + b1) + a1;
  c2 = r1sqr * (r2 * c2 + b2) + a2;
  c3 = r1sqr * (r2 * c3 + b3) + a3;
  p[0] = c1;
  p[1] = c2;
  p[2] = c3;
  p[3] = 0;
}

inline void
randPSurface (vtkPolyData * polydata, std::vector<double> * cumulativeAreas, double totalArea, Eigen::Vector4f& p)
{
  float r = uniform_deviate (rand ()) * totalArea;

  std::vector<double>::iterator low = std::lower_bound (cumulativeAreas->begin (), cumulativeAreas->end (), r);
  vtkIdType el = (vtkIdType)(low - cumulativeAreas->begin ());

  double A[3], B[3], C[3];
  vtkIdType npts = 0;
  vtkIdType *ptIds = NULL;
  polydata->GetCellPoints (el, npts, ptIds);
  polydata->GetPoint (ptIds[0], A);
  polydata->GetPoint (ptIds[1], B);
  polydata->GetPoint (ptIds[2], C);
  randomPointTriangle (A[0], A[1], A[2], B[0], B[1], B[2], C[0], C[1], C[2], p);
}

void
uniform_sampling (vtkSmartPointer<vtkPolyData> polydata, size_t n_samples, pcl::PointCloud<pcl::PointXYZ> & cloud_out)
{
  polydata->BuildCells ();
  vtkSmartPointer<vtkCellArray> cells = polydata->GetPolys ();

  double p1[3], p2[3], p3[3], totalArea = 0;
  std::vector<double> cumulativeAreas (cells->GetNumberOfCells (), 0);
  size_t i = 0;
  vtkIdType npts = 0, *ptIds = NULL;
  for (cells->InitTraversal (); cells->GetNextCell (npts, ptIds); i++)
  {
    polydata->GetPoint (ptIds[0], p1);
    polydata->GetPoint (ptIds[1], p2);
    polydata->GetPoint (ptIds[2], p3);
    totalArea += vtkTriangle::TriangleArea (p1, p2, p3);
    cumulativeAreas[i] = totalArea;
  }

  cloud_out.points.resize (n_samples);
  cloud_out.width = n_samples;
  cloud_out.height = 1;

  for (i = 0; i < n_samples; i++)
  {
    Eigen::Vector4f p;
    randPSurface (polydata, &cumulativeAreas, totalArea, p);
    cloud_out.points[i].x = p[0];
    cloud_out.points[i].y = p[1];
    cloud_out.points[i].z = p[2];
  }
}

using namespace pcl;
using namespace pcl::io;
using namespace pcl::console;

int default_number_samples = 100000;
float default_leaf_size = 0.01;

void
printHelp (int argc, char **argv)
{
  print_error ("Syntax is: %s input.{ply,obj} output.pcd <options>\n", argv[0]);
  print_info ("  where options are:\n");
  print_info ("                     -n_samples X      = number of samples (default: ");
  print_value ("%d", default_number_samples);
  print_info (")\n");
  print_info (
              "                     -leaf_size X  = the XYZ leaf size for the VoxelGrid -- for data reduction (default: ");
  print_value ("%f", default_leaf_size);
  print_info (" m)\n");
}

/* ---[ */
int
main (int argc, char **argv)
{
  print_info ("Convert a CAD model to a point cloud using ray tracing operations. For more information, use: %s -h\n",
              argv[0]);

  if (argc < 3)
  {
    printHelp (argc, argv);
    return (-1);
  }

  // Parse command line arguments
  int SAMPLE_POINTS_ = default_number_samples;
  parse_argument (argc, argv, "-n_samples", SAMPLE_POINTS_);
  double leaf_size = default_leaf_size;
  parse_argument (argc, argv, "-leaf_size", leaf_size);

  // Parse the command line arguments for .ply and PCD files
  std::vector<int> pcd_file_indices = parse_file_extension_argument (argc, argv, ".pcd");
  if (pcd_file_indices.size () != 1)
  {
    print_error ("Need a single output PCD file to continue.\n");
    return (-1);
  }
  std::vector<int> ply_file_indices = parse_file_extension_argument (argc, argv, ".ply");
  std::vector<int> obj_file_indices = parse_file_extension_argument (argc, argv, ".obj");
  if (ply_file_indices.size () != 1 && obj_file_indices.size () != 1)
  {
    print_error ("Need a single input PLY/OBJ file to continue.\n");
    return (-1);
  }

  vtkSmartPointer<vtkPolyData> polydata1;
  if (ply_file_indices.size () == 1)
  {
    vtkSmartPointer<vtkPLYReader> readerQuery = vtkSmartPointer<vtkPLYReader>::New ();
    readerQuery->SetFileName (argv[ply_file_indices[0]]);
  }
  else if (obj_file_indices.size () == 1)
  {
    vtkSmartPointer<vtkOBJReader> readerQuery = vtkSmartPointer<vtkOBJReader>::New ();
    readerQuery->SetFileName (argv[obj_file_indices[0]]);
    polydata1 = readerQuery->GetOutput ();
    polydata1->Update ();
  }

  //make sure that the polygons are triangles!
  vtkSmartPointer<vtkTriangleFilter> triangleFilter = vtkSmartPointer<vtkTriangleFilter>::New ();
  triangleFilter->SetInput (polydata1);
  triangleFilter->Update ();

  vtkSmartPointer<vtkPolyDataMapper> triangleMapper = vtkSmartPointer<vtkPolyDataMapper>::New ();
  triangleMapper->SetInputConnection (triangleFilter->GetOutputPort ());
  triangleMapper->Update();
  polydata1 = triangleMapper->GetInput();
  polydata1->Update ();

  bool INTER_VIS = false;
  bool VIS = true;

  if (INTER_VIS)
  {
    visualization::PCLVisualizer vis;
    vis.addModelFromPolyData (polydata1, "mesh1", 0);
    vis.setRepresentationToSurfaceForAllActors ();
    vis.spin();
  }

  pcl::PointCloud<pcl::PointXYZ>::Ptr cloud_1 (new pcl::PointCloud<pcl::PointXYZ>);
  uniform_sampling (polydata1, SAMPLE_POINTS_, *cloud_1);

  if (INTER_VIS)
  {
    visualization::PCLVisualizer vis_sampled;
    vis_sampled.addPointCloud (cloud_1);
    vis_sampled.spin ();
  }

  // Voxelgrid
  VoxelGrid<PointXYZ> grid_;
  grid_.setInputCloud (cloud_1);
  grid_.setLeafSize (leaf_size, leaf_size, leaf_size);
  grid_.filter (*cloud_1);

  if (VIS)
  {
    visualization::PCLVisualizer vis3 ("VOXELIZED SAMPLES CLOUD");
    vis3.addPointCloud (cloud_1);
    vis3.spin ();
  }

  savePCDFileASCII (argv[pcd_file_indices[0]], *cloud_1);
}
<commit_msg>Changed description.<commit_after>/*
 * Software License Agreement (BSD License)
 *
 *  Point Cloud Library (PCL) - www.pointclouds.org
 *  Copyright (c) 2010-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, Inc. nor the names of its
 *     contributors may be used to endorse or promote products derived
 *     from this software without specific prior written permission.
 *
 *  THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 *  "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
 *  LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
 *  FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
 *  COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
 *  INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
 *  BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
 *  LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
 *  CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
 *  LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
 *  ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 *  POSSIBILITY OF SUCH DAMAGE.
 *
 */

#include <pcl/visualization/pcl_visualizer.h>
#include <pcl/io/pcd_io.h>
#include <pcl/registration/transforms.h>
#include <vtkPLYReader.h>
#include <vtkOBJReader.h>
#include <vtkTriangle.h>
#include <vtkTriangleFilter.h>
#include <vtkPolyDataMapper.h>
#include <pcl/filters/voxel_grid.h>
#include <pcl/console/print.h>
#include <pcl/console/parse.h>

inline double
uniform_deviate (int seed)
{
  double ran = seed * (1.0 / (RAND_MAX + 1.0));
  return ran;
}

inline void
randomPointTriangle (float a1, float a2, float a3, float b1, float b2, float b3, float c1, float c2, float c3,
                     Eigen::Vector4f& p)
{
  float r1 = uniform_deviate (rand ());
  float r2 = uniform_deviate (rand ());
  float r1sqr = sqrt (r1);
  float OneMinR1Sqr = (1 - r1sqr);
  float OneMinR2 = (1 - r2);
  a1 *= OneMinR1Sqr;
  a2 *= OneMinR1Sqr;
  a3 *= OneMinR1Sqr;
  b1 *= OneMinR2;
  b2 *= OneMinR2;
  b3 *= OneMinR2;
  c1 = r1sqr * (r2 * c1 + b1) + a1;
  c2 = r1sqr * (r2 * c2 + b2) + a2;
  c3 = r1sqr * (r2 * c3 + b3) + a3;
  p[0] = c1;
  p[1] = c2;
  p[2] = c3;
  p[3] = 0;
}

inline void
randPSurface (vtkPolyData * polydata, std::vector<double> * cumulativeAreas, double totalArea, Eigen::Vector4f& p)
{
  float r = uniform_deviate (rand ()) * totalArea;

  std::vector<double>::iterator low = std::lower_bound (cumulativeAreas->begin (), cumulativeAreas->end (), r);
  vtkIdType el = (vtkIdType)(low - cumulativeAreas->begin ());

  double A[3], B[3], C[3];
  vtkIdType npts = 0;
  vtkIdType *ptIds = NULL;
  polydata->GetCellPoints (el, npts, ptIds);
  polydata->GetPoint (ptIds[0], A);
  polydata->GetPoint (ptIds[1], B);
  polydata->GetPoint (ptIds[2], C);
  randomPointTriangle (A[0], A[1], A[2], B[0], B[1], B[2], C[0], C[1], C[2], p);
}

void
uniform_sampling (vtkSmartPointer<vtkPolyData> polydata, size_t n_samples, pcl::PointCloud<pcl::PointXYZ> & cloud_out)
{
  polydata->BuildCells ();
  vtkSmartPointer<vtkCellArray> cells = polydata->GetPolys ();

  double p1[3], p2[3], p3[3], totalArea = 0;
  std::vector<double> cumulativeAreas (cells->GetNumberOfCells (), 0);
  size_t i = 0;
  vtkIdType npts = 0, *ptIds = NULL;
  for (cells->InitTraversal (); cells->GetNextCell (npts, ptIds); i++)
  {
    polydata->GetPoint (ptIds[0], p1);
    polydata->GetPoint (ptIds[1], p2);
    polydata->GetPoint (ptIds[2], p3);
    totalArea += vtkTriangle::TriangleArea (p1, p2, p3);
    cumulativeAreas[i] = totalArea;
  }

  cloud_out.points.resize (n_samples);
  cloud_out.width = n_samples;
  cloud_out.height = 1;

  for (i = 0; i < n_samples; i++)
  {
    Eigen::Vector4f p;
    randPSurface (polydata, &cumulativeAreas, totalArea, p);
    cloud_out.points[i].x = p[0];
    cloud_out.points[i].y = p[1];
    cloud_out.points[i].z = p[2];
  }
}

using namespace pcl;
using namespace pcl::io;
using namespace pcl::console;

int default_number_samples = 100000;
float default_leaf_size = 0.01;

void
printHelp (int argc, char **argv)
{
  print_error ("Syntax is: %s input.{ply,obj} output.pcd <options>\n", argv[0]);
  print_info ("  where options are:\n");
  print_info ("                     -n_samples X      = number of samples (default: ");
  print_value ("%d", default_number_samples);
  print_info (")\n");
  print_info (
              "                     -leaf_size X  = the XYZ leaf size for the VoxelGrid -- for data reduction (default: ");
  print_value ("%f", default_leaf_size);
  print_info (" m)\n");
}

/* ---[ */
int
main (int argc, char **argv)
{
  print_info ("Convert a CAD model to a point cloud using uniform sampling. For more information, use: %s -h\n",
              argv[0]);

  if (argc < 3)
  {
    printHelp (argc, argv);
    return (-1);
  }

  // Parse command line arguments
  int SAMPLE_POINTS_ = default_number_samples;
  parse_argument (argc, argv, "-n_samples", SAMPLE_POINTS_);
  double leaf_size = default_leaf_size;
  parse_argument (argc, argv, "-leaf_size", leaf_size);

  // Parse the command line arguments for .ply and PCD files
  std::vector<int> pcd_file_indices = parse_file_extension_argument (argc, argv, ".pcd");
  if (pcd_file_indices.size () != 1)
  {
    print_error ("Need a single output PCD file to continue.\n");
    return (-1);
  }
  std::vector<int> ply_file_indices = parse_file_extension_argument (argc, argv, ".ply");
  std::vector<int> obj_file_indices = parse_file_extension_argument (argc, argv, ".obj");
  if (ply_file_indices.size () != 1 && obj_file_indices.size () != 1)
  {
    print_error ("Need a single input PLY/OBJ file to continue.\n");
    return (-1);
  }

  vtkSmartPointer<vtkPolyData> polydata1;
  if (ply_file_indices.size () == 1)
  {
    vtkSmartPointer<vtkPLYReader> readerQuery = vtkSmartPointer<vtkPLYReader>::New ();
    readerQuery->SetFileName (argv[ply_file_indices[0]]);
  }
  else if (obj_file_indices.size () == 1)
  {
    vtkSmartPointer<vtkOBJReader> readerQuery = vtkSmartPointer<vtkOBJReader>::New ();
    readerQuery->SetFileName (argv[obj_file_indices[0]]);
    polydata1 = readerQuery->GetOutput ();
    polydata1->Update ();
  }

  //make sure that the polygons are triangles!
  vtkSmartPointer<vtkTriangleFilter> triangleFilter = vtkSmartPointer<vtkTriangleFilter>::New ();
  triangleFilter->SetInput (polydata1);
  triangleFilter->Update ();

  vtkSmartPointer<vtkPolyDataMapper> triangleMapper = vtkSmartPointer<vtkPolyDataMapper>::New ();
  triangleMapper->SetInputConnection (triangleFilter->GetOutputPort ());
  triangleMapper->Update();
  polydata1 = triangleMapper->GetInput();
  polydata1->Update ();

  bool INTER_VIS = false;
  bool VIS = true;

  if (INTER_VIS)
  {
    visualization::PCLVisualizer vis;
    vis.addModelFromPolyData (polydata1, "mesh1", 0);
    vis.setRepresentationToSurfaceForAllActors ();
    vis.spin();
  }

  pcl::PointCloud<pcl::PointXYZ>::Ptr cloud_1 (new pcl::PointCloud<pcl::PointXYZ>);
  uniform_sampling (polydata1, SAMPLE_POINTS_, *cloud_1);

  if (INTER_VIS)
  {
    visualization::PCLVisualizer vis_sampled;
    vis_sampled.addPointCloud (cloud_1);
    vis_sampled.spin ();
  }

  // Voxelgrid
  VoxelGrid<PointXYZ> grid_;
  grid_.setInputCloud (cloud_1);
  grid_.setLeafSize (leaf_size, leaf_size, leaf_size);
  grid_.filter (*cloud_1);

  if (VIS)
  {
    visualization::PCLVisualizer vis3 ("VOXELIZED SAMPLES CLOUD");
    vis3.addPointCloud (cloud_1);
    vis3.spin ();
  }

  savePCDFileASCII (argv[pcd_file_indices[0]], *cloud_1);
}
<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  $RCSfile: salbmp.cxx,v $
 *
 *  $Revision: 1.4 $
 *
 *  last change: $Author: pluby $ $Date: 2000-12-01 18:03:07 $
 *
 *  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): _______________________________________
 *
 *
 ************************************************************************/

#define _SV_SALBMP_CXX

#ifndef _SV_SALBMP_HXX
#include <salbmp.hxx>
#endif
#ifndef _SV_SALBTYPE_HXX
#include <salbtype.hxx>
#endif

// ==================================================================

SalBitmap::SalBitmap() :
        mnBitCount  ( 0 )
{
}

// ------------------------------------------------------------------

SalBitmap::~SalBitmap()
{
    Destroy();
}

// ------------------------------------------------------------------

BOOL SalBitmap::Create( const Size& rSize, USHORT nBitCount, const BitmapPalette& rPal )
{
    maSize = rSize;
    mnBitCount = nBitCount;
    return TRUE;
}

// ------------------------------------------------------------------

BOOL SalBitmap::Create( const SalBitmap& rSalBitmap )
{
    maSize = rSalBitmap.maSize;
    mnBitCount = 1;
    return TRUE;
}

// ------------------------------------------------------------------

BOOL SalBitmap::Create( const SalBitmap& rSalBmp, SalGraphics* pGraphics )
{
    maSize = rSalBmp.maSize;
    mnBitCount = rSalBmp.mnBitCount;
    return TRUE;
}

// ------------------------------------------------------------------

BOOL SalBitmap::Create( const SalBitmap& rSalBmp, USHORT nNewBitCount )
{
    maSize = rSalBmp.maSize;
    mnBitCount = nNewBitCount;
    return TRUE;
}

// ------------------------------------------------------------------

void SalBitmap::Destroy()
{
}

// ------------------------------------------------------------------

BitmapBuffer* SalBitmap::AcquireBuffer( BOOL bReadOnly )
{
    BitmapBuffer *pBuffer = new BitmapBuffer();

    // Stub code: we have not yet written any interfaces to native bitmaps.
    pBuffer->mnFormat = BMP_FORMAT_BOTTOM_UP | BMP_FORMAT_1BIT_MSB_PAL;
    pBuffer->mnWidth = maSize.Width();
    pBuffer->mnHeight = maSize.Height();
    pBuffer->mnScanlineSize = AlignedWidth4Bytes( pBuffer->mnWidth * mnBitCount );
    pBuffer->mpBits = new BYTE[ pBuffer->mnScanlineSize * pBuffer->mnHeight ];

    return pBuffer;
}

// ------------------------------------------------------------------

void SalBitmap::ReleaseBuffer( BitmapBuffer* pBuffer, BOOL bReadOnly )
{
    delete pBuffer;
}
<commit_msg>Added more stub code to eliminate numerous "missing palette" messages<commit_after>/*************************************************************************
 *
 *  $RCSfile: salbmp.cxx,v $
 *
 *  $Revision: 1.5 $
 *
 *  last change: $Author: pluby $ $Date: 2000-12-31 20:54:10 $
 *
 *  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): _______________________________________
 *
 *
 ************************************************************************/

#define _SV_SALBMP_CXX

#ifndef _SV_SALBMP_HXX
#include <salbmp.hxx>
#endif
#ifndef _SV_SALBTYPE_HXX
#include <salbtype.hxx>
#endif

// ==================================================================

SalBitmap::SalBitmap() :
        mhPixMap( 0 ),
        mnBitCount( 0 )
{
}

// ------------------------------------------------------------------

SalBitmap::~SalBitmap()
{
    Destroy();
}

// ------------------------------------------------------------------

BOOL SalBitmap::Create( const Size& rSize, USHORT nBitCount, const BitmapPalette& rPal )
{
    maSize = rSize;
    mnBitCount = nBitCount;
    return TRUE;
}

// ------------------------------------------------------------------

BOOL SalBitmap::Create( const SalBitmap& rSalBitmap )
{
    maSize = rSalBitmap.maSize;
    mnBitCount = 1;
    return TRUE;
}

// ------------------------------------------------------------------

BOOL SalBitmap::Create( const SalBitmap& rSalBmp, SalGraphics* pGraphics )
{
    maSize = rSalBmp.maSize;
    mnBitCount = rSalBmp.mnBitCount;
    return TRUE;
}

// ------------------------------------------------------------------

BOOL SalBitmap::Create( const SalBitmap& rSalBmp, USHORT nNewBitCount )
{
    maSize = rSalBmp.maSize;
    mnBitCount = nNewBitCount;
    return TRUE;
}

// ------------------------------------------------------------------

void SalBitmap::Destroy()
{
    maSize = Size();
    mnBitCount = 0;
}

// ------------------------------------------------------------------

BitmapBuffer* SalBitmap::AcquireBuffer( BOOL bReadOnly )
{
    BitmapBuffer *pBuffer = new BitmapBuffer();

    // Stub code: we have not yet written any interfaces to native bitmaps.
    pBuffer->mnFormat = BMP_FORMAT_BOTTOM_UP | BMP_FORMAT_1BIT_MSB_PAL;
    pBuffer->mnWidth = maSize.Width();
    pBuffer->mnHeight = maSize.Height();
    pBuffer->mnScanlineSize = AlignedWidth4Bytes( pBuffer->mnWidth * mnBitCount );
    pBuffer->mnFormat |= BMP_FORMAT_16BIT_TC_MASK;
    pBuffer->maColorMask = ColorMask( 0x7b00, 0x03e0, 0x001f);
    pBuffer->mpBits = new BYTE[ pBuffer->mnScanlineSize * pBuffer->mnHeight ];

    return pBuffer;
}

// ------------------------------------------------------------------

void SalBitmap::ReleaseBuffer( BitmapBuffer* pBuffer, BOOL bReadOnly )
{
    delete pBuffer;
}
<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: imgctrl.cxx,v $
 *
 *  $Revision: 1.10 $
 *
 *  last change: $Author: obo $ $Date: 2006-09-17 11:53:48 $
 *
 *  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_vcl.hxx"

#ifndef _SV_EVENT_HXX
#include <event.hxx>
#endif
#include <imgctrl.hxx>

// -----------------------------------------------------------------------

ImageControl::ImageControl( Window* pParent, WinBits nStyle ) :
    FixedImage( pParent, nStyle )
{
    mbScaleImage = TRUE;
}

// -----------------------------------------------------------------------

void ImageControl::SetScaleImage( BOOL bScale )
{
    if ( bScale != mbScaleImage )
    {
        mbScaleImage = bScale;
        Invalidate();
    }
}

// -----------------------------------------------------------------------

BOOL ImageControl::IsScaleImage() const
{
    // Make inline when changing member from dummy...
    return mbScaleImage;
}

// -----------------------------------------------------------------------

void ImageControl::Resize()
{
    Invalidate();
}

// -----------------------------------------------------------------------

void ImageControl::UserDraw( const UserDrawEvent& rUDEvt )
{
    USHORT nStyle = 0;
    BitmapEx* pBitmap = &maBmp;
    Color aCol;
    if( !!maBmpHC && ImplGetCurrentBackgroundColor( aCol ) )
    {
        if( aCol.IsDark() )
            pBitmap = &maBmpHC;
        // #99902 no col transform required
        //if( aCol.IsBright() )
        //  nStyle |= IMAGE_DRAW_COLORTRANSFORM;
    }

    if( nStyle & IMAGE_DRAW_COLORTRANSFORM )
    {
        // only images support IMAGE_DRAW_COLORTRANSFORM
        Image aImage( maBmp );
        if ( !!aImage )
        {
            if ( mbScaleImage )
                rUDEvt.GetDevice()->DrawImage( rUDEvt.GetRect().TopLeft(),
                                                rUDEvt.GetRect().GetSize(),
                                                aImage, nStyle );
            else
            {
                // Center...
                Point aPos( rUDEvt.GetRect().TopLeft() );
                aPos.X() += ( rUDEvt.GetRect().GetWidth() - maBmp.GetSizePixel().Width() ) / 2;
                aPos.Y() += ( rUDEvt.GetRect().GetHeight() - maBmp.GetSizePixel().Height() ) / 2;
                rUDEvt.GetDevice()->DrawImage( aPos, aImage, nStyle );
            }
        }
    }
    else
    {
        if ( mbScaleImage )
        {
            maBmp.Draw( rUDEvt.GetDevice(),
                        rUDEvt.GetRect().TopLeft(),
                        rUDEvt.GetRect().GetSize() );
        }
        else
        {
            // Center...
            Point aPos( rUDEvt.GetRect().TopLeft() );
            aPos.X() += ( rUDEvt.GetRect().GetWidth() - maBmp.GetSizePixel().Width() ) / 2;
            aPos.Y() += ( rUDEvt.GetRect().GetHeight() - maBmp.GetSizePixel().Height() ) / 2;
            maBmp.Draw( rUDEvt.GetDevice(), aPos );
        }
    }
}

// -----------------------------------------------------------------------

void ImageControl::SetBitmap( const BitmapEx& rBmp )
{
    maBmp = rBmp;
    StateChanged( STATE_CHANGE_DATA );
}

// -----------------------------------------------------------------------

BOOL ImageControl::SetModeBitmap( const BitmapEx& rBitmap, BmpColorMode eMode )
{
    if( eMode == BMP_COLOR_NORMAL )
        SetBitmap( rBitmap );
    else if( eMode == BMP_COLOR_HIGHCONTRAST )
    {
        maBmpHC = rBitmap;
        StateChanged( STATE_CHANGE_DATA );
    }
    else
        return FALSE;
    return TRUE;
}

// -----------------------------------------------------------------------

const BitmapEx& ImageControl::GetModeBitmap( BmpColorMode eMode ) const
{
    if( eMode == BMP_COLOR_HIGHCONTRAST )
        return maBmpHC;
    else
        return maBmp;
}

// -----------------------------------------------------------------------

void    ImageControl::Paint( const Rectangle& rRect )
{
    FixedImage::Paint( rRect );
    if( HasFocus() )
    {
        Window *pWin = GetWindow( WINDOW_BORDER );

        BOOL bFlat = (GetBorderStyle() == 2);
        Rectangle aRect( Point(0,0), pWin->GetOutputSizePixel() );
        Color oldLineCol = pWin->GetLineColor();
        Color oldFillCol = pWin->GetFillColor();
        pWin->SetFillColor();
        pWin->SetLineColor( bFlat ? COL_WHITE : COL_BLACK );
        pWin->DrawRect( aRect );
        aRect.nLeft++;
        aRect.nRight--;
        aRect.nTop++;
        aRect.nBottom--;
        pWin->SetLineColor( bFlat ? COL_BLACK : COL_WHITE );
        pWin->DrawRect( aRect );
        pWin->SetLineColor( oldLineCol );
        pWin->SetFillColor( oldFillCol );
    }
}

// -----------------------------------------------------------------------

void ImageControl::GetFocus()
{
    FixedImage::GetFocus();
    GetWindow( WINDOW_BORDER )->Invalidate();
}

// -----------------------------------------------------------------------

void ImageControl::LoseFocus()
{
    FixedImage::GetFocus();
    GetWindow( WINDOW_BORDER )->Invalidate();
}

<commit_msg>INTEGRATION: CWS vgbugs07 (1.10.240); FILE MERGED 2007/06/04 13:29:33 vg 1.10.240.1: #i76605# Remove -I .../inc/module hack introduced by hedaburemove01<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: imgctrl.cxx,v $
 *
 *  $Revision: 1.11 $
 *
 *  last change: $Author: hr $ $Date: 2007-06-27 20:06:43 $
 *
 *  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_vcl.hxx"

#ifndef _SV_EVENT_HXX
#include <vcl/event.hxx>
#endif
#include <vcl/imgctrl.hxx>

// -----------------------------------------------------------------------

ImageControl::ImageControl( Window* pParent, WinBits nStyle ) :
    FixedImage( pParent, nStyle )
{
    mbScaleImage = TRUE;
}

// -----------------------------------------------------------------------

void ImageControl::SetScaleImage( BOOL bScale )
{
    if ( bScale != mbScaleImage )
    {
        mbScaleImage = bScale;
        Invalidate();
    }
}

// -----------------------------------------------------------------------

BOOL ImageControl::IsScaleImage() const
{
    // Make inline when changing member from dummy...
    return mbScaleImage;
}

// -----------------------------------------------------------------------

void ImageControl::Resize()
{
    Invalidate();
}

// -----------------------------------------------------------------------

void ImageControl::UserDraw( const UserDrawEvent& rUDEvt )
{
    USHORT nStyle = 0;
    BitmapEx* pBitmap = &maBmp;
    Color aCol;
    if( !!maBmpHC && ImplGetCurrentBackgroundColor( aCol ) )
    {
        if( aCol.IsDark() )
            pBitmap = &maBmpHC;
        // #99902 no col transform required
        //if( aCol.IsBright() )
        //  nStyle |= IMAGE_DRAW_COLORTRANSFORM;
    }

    if( nStyle & IMAGE_DRAW_COLORTRANSFORM )
    {
        // only images support IMAGE_DRAW_COLORTRANSFORM
        Image aImage( maBmp );
        if ( !!aImage )
        {
            if ( mbScaleImage )
                rUDEvt.GetDevice()->DrawImage( rUDEvt.GetRect().TopLeft(),
                                                rUDEvt.GetRect().GetSize(),
                                                aImage, nStyle );
            else
            {
                // Center...
                Point aPos( rUDEvt.GetRect().TopLeft() );
                aPos.X() += ( rUDEvt.GetRect().GetWidth() - maBmp.GetSizePixel().Width() ) / 2;
                aPos.Y() += ( rUDEvt.GetRect().GetHeight() - maBmp.GetSizePixel().Height() ) / 2;
                rUDEvt.GetDevice()->DrawImage( aPos, aImage, nStyle );
            }
        }
    }
    else
    {
        if ( mbScaleImage )
        {
            maBmp.Draw( rUDEvt.GetDevice(),
                        rUDEvt.GetRect().TopLeft(),
                        rUDEvt.GetRect().GetSize() );
        }
        else
        {
            // Center...
            Point aPos( rUDEvt.GetRect().TopLeft() );
            aPos.X() += ( rUDEvt.GetRect().GetWidth() - maBmp.GetSizePixel().Width() ) / 2;
            aPos.Y() += ( rUDEvt.GetRect().GetHeight() - maBmp.GetSizePixel().Height() ) / 2;
            maBmp.Draw( rUDEvt.GetDevice(), aPos );
        }
    }
}

// -----------------------------------------------------------------------

void ImageControl::SetBitmap( const BitmapEx& rBmp )
{
    maBmp = rBmp;
    StateChanged( STATE_CHANGE_DATA );
}

// -----------------------------------------------------------------------

BOOL ImageControl::SetModeBitmap( const BitmapEx& rBitmap, BmpColorMode eMode )
{
    if( eMode == BMP_COLOR_NORMAL )
        SetBitmap( rBitmap );
    else if( eMode == BMP_COLOR_HIGHCONTRAST )
    {
        maBmpHC = rBitmap;
        StateChanged( STATE_CHANGE_DATA );
    }
    else
        return FALSE;
    return TRUE;
}

// -----------------------------------------------------------------------

const BitmapEx& ImageControl::GetModeBitmap( BmpColorMode eMode ) const
{
    if( eMode == BMP_COLOR_HIGHCONTRAST )
        return maBmpHC;
    else
        return maBmp;
}

// -----------------------------------------------------------------------

void    ImageControl::Paint( const Rectangle& rRect )
{
    FixedImage::Paint( rRect );
    if( HasFocus() )
    {
        Window *pWin = GetWindow( WINDOW_BORDER );

        BOOL bFlat = (GetBorderStyle() == 2);
        Rectangle aRect( Point(0,0), pWin->GetOutputSizePixel() );
        Color oldLineCol = pWin->GetLineColor();
        Color oldFillCol = pWin->GetFillColor();
        pWin->SetFillColor();
        pWin->SetLineColor( bFlat ? COL_WHITE : COL_BLACK );
        pWin->DrawRect( aRect );
        aRect.nLeft++;
        aRect.nRight--;
        aRect.nTop++;
        aRect.nBottom--;
        pWin->SetLineColor( bFlat ? COL_BLACK : COL_WHITE );
        pWin->DrawRect( aRect );
        pWin->SetLineColor( oldLineCol );
        pWin->SetFillColor( oldFillCol );
    }
}

// -----------------------------------------------------------------------

void ImageControl::GetFocus()
{
    FixedImage::GetFocus();
    GetWindow( WINDOW_BORDER )->Invalidate();
}

// -----------------------------------------------------------------------

void ImageControl::LoseFocus()
{
    FixedImage::GetFocus();
    GetWindow( WINDOW_BORDER )->Invalidate();
}

<|endoftext|>


<commit_before>// -*- c++ -*- ///////////////////////////////////////////////////////////////
//
// This file is part of Miro (The Middleware for Robots)
// Copyright (C) 1999-2013
// Department of Neural Information Processing, University of Ulm
//
// This program is free software; you can redistribute it and/or modify
// it under the terms of the GNU Lesser General Public License as published
// by the Free Software Foundation; either version 2, or (at your option)
// any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public License
// along with this program; if not, write to the Free Software Foundation,
// Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
//

// This module
#include "ParameterDialog.h"
// This application
#include "ConfigFile.h"
#include "DeferredParameterEdit.h"
#include "SimpleParameter.h"
#include "SimpleParameterEdit.h"
#include "params/Generator.h"
#include "params/Type.h"
// The Qt library
#include <QAction>
#include <QFrame>
#include <QGridLayout>
#include <QGroupBox>
#include <qlabel.h>
#include <qlayout.h>
#include <qmessagebox.h>
#include <qobject.h>
#include <QScrollArea>
#include <qstring.h>
#include <qtooltip.h>
// The C++ Standard Library
#include <cassert>
#include <typeinfo>

ParameterDialog::ParameterDialog(Miro::CFG::Type const& _parameterType,
				 QDomNode const& _parentNode,
				 QDomNode const& _node,
				 ItemXML * _parentItem,
				 ItemXML * _item,
				 QWidget * _parent, const char * _name) :
  Super(_parentNode, _node, _parentItem, _item, _parent, _name),
  config_(ConfigFile::instance()),
  parameterType_(_parameterType),
  params_(config_->description().getFullParameterSet(parameterType_))
{
  assert(!_node.isNull());

  initDialog();

  QSize s = frame_->sizeHint();

  if (s.width() > 800 ||
      s.height() > 600) {

    // Replace the Frame with one in a ScrollArea
    delete frame_;
    // Create the ScrollArea as a child of the GroupBox
    QScrollArea * const sv = new QScrollArea;
    assert(sv != NULL);

    // Create the Frame as a child of the ScrollArea's viewport
    QWidget * const pFrameParent = sv->viewport();
    frame_ = new QFrame(pFrameParent);
    sv->setWidget(frame_);

    // Set the resize policy
    /// @todo What is the counterpart of
    /// Q3ScrollView::setResizePolicy(Q3ScrollView::AutoOneFit)?
    sv->setWidgetResizable(true);

    // Add the ScrollArea to the GroupBox's layout
    assert(groupBox_ != NULL);
    assert(groupBox_->layout() != NULL);
    groupBox_->layout()->addWidget(sv);

    initDialog();

    frame_->sizeHint();
  }

  groupBox_->sizeHint(); // we seem to need this to get the right size (hutz)
  groupBox_->setTitle("Parameters");
}

void
ParameterDialog::setXML()
{
  setModified(false);
  EditVector::const_iterator first, last = editFelds_.end();
  for (first = editFelds_.begin(); first != last; ++first) {
    if ((*first)->modified()) {
      (*first)->setXML();
      setModified(true);
    }
  }
}

void
ParameterDialog::initDialog()
{
  editFelds_.clear();

  // The GridLayout is a child of the ScrollView's viewport
  QWidget * const pGridLayoutParent = frame_;
  QGridLayout * const gridLayout = new QGridLayout(pGridLayoutParent);
  assert(gridLayout != 0);
  // Specify the margin but not the number of rows (params_.size(),
  // columns (3)
  const int margin = 5;
  gridLayout->setContentsMargins(margin, margin, margin, margin);
  const int spacing = 5;
  gridLayout->setSpacing(spacing);

  // add parameter structs:
  // Sequential position of the current parameter
  unsigned long i = 0;
  // For each parameter
  Miro::CFG::ParameterVector::const_iterator first, last = params_.end();
  for (first = params_.begin(); first != last; ++first, ++i) {

    // Create a Label the text of which is the parameter named capitalized.
    // Add the label to the Layout
    QLabel * name = new QLabel(frame_);
    QString n = first->name_;
    n[0] = n[0].upper();
    name->setText(n);
    gridLayout->addWidget(name, i, 0);

    // Search the QDomNode for a child the name of which is the parameter
    // name capitalized. If found, store it in parameterNode.
    QDomNode parameterNode;
    assert(parameterNode.isNull());

    if (!node_.isNull()) {
      parameterNode = node_.firstChild();
      while(!parameterNode.isNull()) {
	QDomElement e = parameterNode.toElement();
	if (!e.isNull() &&
	    e.attribute("name") == n)
	  break;
	parameterNode = parameterNode.nextSibling();
      }
    }

    // If there is an existing entry and we know our QTreeWidget,
    // get the corresponding QTreeWidgetItem

    ItemXML * childItem = NULL;
    if (!parameterNode.isNull() &&
	item_ != NULL) {
      // The QDomNode was found and this dialog has a parameter ItemXML
      if (!item_->children().isEmpty()) {
	// The parameter ItemXML has children
	QObjectList childList = item_->children();
	// For each child of the parameter ItemXML
        QListIterator<QObject*> it(childList);
        while (it.hasNext()) {
          QObject * const c = it.next();
	  childItem = dynamic_cast<ItemXML *>(c);
	  // The child of the parameter ItemXML must be an ItemXML
	  assert(childItem != NULL);
	  // Looking for a child ItemXML whose name is that of the parameter
	  if (childItem->node().toElement().attribute("name") == n) {
	    break;
	  }
	  childItem = NULL;
	}
      }
    }

    // create the dialog

    ParameterEdit * value;
    SimpleParameter::Type editType =
      SimpleParameter::typeFromName(first->type_);
    if (editType != SimpleParameter::NONE) {
      value = new SimpleParameterEdit(editType,
				      *first,
				      node_,
				      parameterNode,
				      item_,
				      childItem,
				      frame_,
				      n.latin1());

      // add measure
      QLabel * measure = new QLabel(frame_);
      if (!first->measure_.isEmpty()) {
	measure->setText(first->measure_);
	QToolTip::add(measure, (first->type_ != "angle")? first->type_ : QString("double"));
      }
      else
	measure->setText(first->type_);
      gridLayout->addWidget(measure, i, 2);
    }
    else {
      DeferredParameterEdit::EditType deferredEditType =
	DeferredParameterEdit::editType(first->type_);

      value = new DeferredParameterEdit(deferredEditType,
					*first,
					node_,
					parameterNode,
					item_,
					childItem,
					frame_,
					n.latin1());
    }

    gridLayout->addWidget(value->editWidget(), i, 1);
    editFelds_.push_back(value);

  }
}
<commit_msg>Removed obsolete #include<commit_after>// -*- c++ -*- ///////////////////////////////////////////////////////////////
//
// This file is part of Miro (The Middleware for Robots)
// Copyright (C) 1999-2013
// Department of Neural Information Processing, University of Ulm
//
// This program is free software; you can redistribute it and/or modify
// it under the terms of the GNU Lesser General Public License as published
// by the Free Software Foundation; either version 2, or (at your option)
// any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public License
// along with this program; if not, write to the Free Software Foundation,
// Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
//

// This module
#include "ParameterDialog.h"
// This application
#include "ConfigFile.h"
#include "DeferredParameterEdit.h"
#include "SimpleParameter.h"
#include "SimpleParameterEdit.h"
#include "params/Generator.h"
#include "params/Type.h"
// The Qt library
#include <QAction>
#include <QFrame>
#include <QGridLayout>
#include <QGroupBox>
#include <qlabel.h>
#include <qlayout.h>
#include <qmessagebox.h>
#include <qobject.h>
#include <QScrollArea>
#include <qstring.h>
#include <qtooltip.h>
// The C++ Standard Library
#include <cassert>

ParameterDialog::ParameterDialog(Miro::CFG::Type const& _parameterType,
				 QDomNode const& _parentNode,
				 QDomNode const& _node,
				 ItemXML * _parentItem,
				 ItemXML * _item,
				 QWidget * _parent, const char * _name) :
  Super(_parentNode, _node, _parentItem, _item, _parent, _name),
  config_(ConfigFile::instance()),
  parameterType_(_parameterType),
  params_(config_->description().getFullParameterSet(parameterType_))
{
  assert(!_node.isNull());

  initDialog();

  QSize s = frame_->sizeHint();

  if (s.width() > 800 ||
      s.height() > 600) {

    // Replace the Frame with one in a ScrollArea
    delete frame_;
    // Create the ScrollArea as a child of the GroupBox
    QScrollArea * const sv = new QScrollArea;
    assert(sv != NULL);

    // Create the Frame as a child of the ScrollArea's viewport
    QWidget * const pFrameParent = sv->viewport();
    frame_ = new QFrame(pFrameParent);
    sv->setWidget(frame_);

    // Set the resize policy
    /// @todo What is the counterpart of
    /// Q3ScrollView::setResizePolicy(Q3ScrollView::AutoOneFit)?
    sv->setWidgetResizable(true);

    // Add the ScrollArea to the GroupBox's layout
    assert(groupBox_ != NULL);
    assert(groupBox_->layout() != NULL);
    groupBox_->layout()->addWidget(sv);

    initDialog();

    frame_->sizeHint();
  }

  groupBox_->sizeHint(); // we seem to need this to get the right size (hutz)
  groupBox_->setTitle("Parameters");
}

void
ParameterDialog::setXML()
{
  setModified(false);
  EditVector::const_iterator first, last = editFelds_.end();
  for (first = editFelds_.begin(); first != last; ++first) {
    if ((*first)->modified()) {
      (*first)->setXML();
      setModified(true);
    }
  }
}

void
ParameterDialog::initDialog()
{
  editFelds_.clear();

  // The GridLayout is a child of the ScrollView's viewport
  QWidget * const pGridLayoutParent = frame_;
  QGridLayout * const gridLayout = new QGridLayout(pGridLayoutParent);
  assert(gridLayout != 0);
  // Specify the margin but not the number of rows (params_.size(),
  // columns (3)
  const int margin = 5;
  gridLayout->setContentsMargins(margin, margin, margin, margin);
  const int spacing = 5;
  gridLayout->setSpacing(spacing);

  // add parameter structs:
  // Sequential position of the current parameter
  unsigned long i = 0;
  // For each parameter
  Miro::CFG::ParameterVector::const_iterator first, last = params_.end();
  for (first = params_.begin(); first != last; ++first, ++i) {

    // Create a Label the text of which is the parameter named capitalized.
    // Add the label to the Layout
    QLabel * name = new QLabel(frame_);
    QString n = first->name_;
    n[0] = n[0].upper();
    name->setText(n);
    gridLayout->addWidget(name, i, 0);

    // Search the QDomNode for a child the name of which is the parameter
    // name capitalized. If found, store it in parameterNode.
    QDomNode parameterNode;
    assert(parameterNode.isNull());

    if (!node_.isNull()) {
      parameterNode = node_.firstChild();
      while(!parameterNode.isNull()) {
	QDomElement e = parameterNode.toElement();
	if (!e.isNull() &&
	    e.attribute("name") == n)
	  break;
	parameterNode = parameterNode.nextSibling();
      }
    }

    // If there is an existing entry and we know our QTreeWidget,
    // get the corresponding QTreeWidgetItem

    ItemXML * childItem = NULL;
    if (!parameterNode.isNull() &&
	item_ != NULL) {
      // The QDomNode was found and this dialog has a parameter ItemXML
      if (!item_->children().isEmpty()) {
	// The parameter ItemXML has children
	QObjectList childList = item_->children();
	// For each child of the parameter ItemXML
        QListIterator<QObject*> it(childList);
        while (it.hasNext()) {
          QObject * const c = it.next();
	  childItem = dynamic_cast<ItemXML *>(c);
	  // The child of the parameter ItemXML must be an ItemXML
	  assert(childItem != NULL);
	  // Looking for a child ItemXML whose name is that of the parameter
	  if (childItem->node().toElement().attribute("name") == n) {
	    break;
	  }
	  childItem = NULL;
	}
      }
    }

    // create the dialog

    ParameterEdit * value;
    SimpleParameter::Type editType =
      SimpleParameter::typeFromName(first->type_);
    if (editType != SimpleParameter::NONE) {
      value = new SimpleParameterEdit(editType,
				      *first,
				      node_,
				      parameterNode,
				      item_,
				      childItem,
				      frame_,
				      n.latin1());

      // add measure
      QLabel * measure = new QLabel(frame_);
      if (!first->measure_.isEmpty()) {
	measure->setText(first->measure_);
	QToolTip::add(measure, (first->type_ != "angle")? first->type_ : QString("double"));
      }
      else
	measure->setText(first->type_);
      gridLayout->addWidget(measure, i, 2);
    }
    else {
      DeferredParameterEdit::EditType deferredEditType =
	DeferredParameterEdit::editType(first->type_);

      value = new DeferredParameterEdit(deferredEditType,
					*first,
					node_,
					parameterNode,
					item_,
					childItem,
					frame_,
					n.latin1());
    }

    gridLayout->addWidget(value->editWidget(), i, 1);
    editFelds_.push_back(value);

  }
}
<|endoftext|>


<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 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.
 *
 * $Id$
 *
 */

#include <sensor_msgs/PointCloud2.h>
#include <pcl/point_types.h>
#include <pcl/io/pcd_io.h>
#include <pcl/console/print.h>
#include <pcl/console/parse.h>
#include <pcl/console/time.h>
#include <pcl/surface/mls.h>
#include <pcl/filters/voxel_grid.h>

using namespace pcl;
using namespace pcl::io;
using namespace pcl::console;

int default_polynomial_order = 2;
bool default_use_polynomial_fit = false;
double default_search_radius = 0.0,
    default_sqr_gauss_param = 0.0;

void
printHelp (int, char **argv)
{
  print_error ("Syntax is: %s input.pcd output.pcd <options>\n", argv[0]);
  print_info ("  where options are:\n");
  print_info ("                     -search_radius X = sphere radius to be used for finding the k-nearest neighbors used for fitting (default: ");
  print_value ("%f", default_search_radius); print_info (")\n");
  print_info ("                     -sqr_gauss_param X = parameter used for the distance based weighting of neighbors (recommended = search_radius^2) (default: ");
  print_value ("%f", default_sqr_gauss_param); print_info (")\n");
  print_info ("                     -use_polynomial_fit X = decides whether the surface and normal are approximated using a polynomial or only via tangent estimation (default: ");
  print_value ("%d", default_use_polynomial_fit); print_info (")\n");
  print_info ("                     -polynomial_order X = order of the polynomial to be fit (implicitly, use_polynomial_fit = 1) (default: ");
  print_value ("%d", default_polynomial_order); print_info (")\n");
}

bool
loadCloud (const std::string &filename, sensor_msgs::PointCloud2 &cloud)
{
  TicToc tt;
  print_highlight ("Loading "); print_value ("%s ", filename.c_str ());

  tt.tic ();
  if (loadPCDFile (filename, cloud) < 0)
    return (false);
  print_info ("[done, "); print_value ("%g", tt.toc ()); print_info (" ms : "); print_value ("%d", cloud.width * cloud.height); print_info (" points]\n");
  print_info ("Available dimensions: "); print_value ("%s\n", pcl::getFieldsList (cloud).c_str ());

  return (true);
}

void
compute (const sensor_msgs::PointCloud2::ConstPtr &input, sensor_msgs::PointCloud2 &output,
         double search_radius, bool sqr_gauss_param_set, double sqr_gauss_param,
         bool use_polynomial_fit, int polynomial_order)
{

  PointCloud<PointXYZ>::Ptr xyz_cloud_pre (new pcl::PointCloud<PointXYZ> ()),
      xyz_cloud (new pcl::PointCloud<PointXYZ> ());
  fromROSMsg (*input, *xyz_cloud_pre);

  // Filter the NaNs from the cloud
  for (size_t i = 0; i < xyz_cloud_pre->size (); ++i)
    if (pcl_isfinite (xyz_cloud_pre->points[i].x))
      xyz_cloud->push_back (xyz_cloud_pre->points[i]);
  xyz_cloud->header = xyz_cloud_pre->header;
  xyz_cloud->height = 1;
  xyz_cloud->width = static_cast<uint32_t> (xyz_cloud->size ());
  xyz_cloud->is_dense = false;

  PointCloud<PointNormal>::Ptr xyz_cloud_smoothed (new PointCloud<PointNormal> ());

  MovingLeastSquares<PointXYZ, PointNormal> mls;
  mls.setInputCloud (xyz_cloud);
  mls.setSearchRadius (search_radius);
  if (sqr_gauss_param_set) mls.setSqrGaussParam (sqr_gauss_param);
  mls.setPolynomialFit (use_polynomial_fit);
  mls.setPolynomialOrder (polynomial_order);

//  mls.setUpsamplingMethod (MovingLeastSquares<PointXYZ, PointNormal>::SAMPLE_LOCAL_PLANE);
//  mls.setUpsamplingMethod (MovingLeastSquares<PointXYZ, PointNormal>::RANDOM_UNIFORM_DENSITY);
//  mls.setUpsamplingMethod (MovingLeastSquares<PointXYZ, PointNormal>::VOXEL_GRID_DILATION);
  mls.setUpsamplingMethod (MovingLeastSquares<PointXYZ, PointNormal>::NONE);
  mls.setPointDensity (60000 * int (search_radius)); // 300 points in a 5 cm radius
  mls.setUpsamplingRadius (0.025);
  mls.setUpsamplingStepSize (0.015);
  mls.setDilationIterations (2);
  mls.setDilationVoxelSize (0.01f);

  search::KdTree<PointXYZ>::Ptr tree (new search::KdTree<PointXYZ> ());
  mls.setSearchMethod (tree);
  mls.setComputeNormals (true);

  PCL_INFO ("Computing smoothed surface and normals with search_radius %f , sqr_gaussian_param %f, polynomial fitting %d, polynomial order %d\n",
            mls.getSearchRadius(), mls.getSqrGaussParam(), mls.getPolynomialFit(), mls.getPolynomialOrder());
  TicToc tt;
  tt.tic ();
  mls.process (*xyz_cloud_smoothed);
  print_info ("[done, "); print_value ("%g", tt.toc ()); print_info (" ms : "); print_value ("%d", xyz_cloud_smoothed->width * xyz_cloud_smoothed->height); print_info (" points]\n");

  toROSMsg (*xyz_cloud_smoothed, output);
}

void
saveCloud (const std::string &filename, const sensor_msgs::PointCloud2 &output)
{
  TicToc tt;
  tt.tic ();

  print_highlight ("Saving "); print_value ("%s ", filename.c_str ());

  pcl::io::savePCDFile (filename, output,  Eigen::Vector4f::Zero (),
                        Eigen::Quaternionf::Identity (), true);

  print_info ("[done, "); print_value ("%g", tt.toc ()); print_info (" ms : "); print_value ("%d", output.width * output.height); print_info (" points]\n");
}

/* ---[ */
int
main (int argc, char** argv)
{
  print_info ("Moving Least Squares smoothing of a point cloud. For more information, use: %s -h\n", argv[0]);

  if (argc < 3)
  {
    printHelp (argc, argv);
    return (-1);
  }

  // Parse the command line arguments for .pcd files
  std::vector<int> p_file_indices;
  p_file_indices = parse_file_extension_argument (argc, argv, ".pcd");
  if (p_file_indices.size () != 2)
  {
    print_error ("Need one input PCD file and one output PCD file to continue.\n");
    return (-1);
  }

  // Command line parsing
  double search_radius = default_search_radius;
  double sqr_gauss_param = default_sqr_gauss_param;
  bool sqr_gauss_param_set = true;
  int polynomial_order = default_polynomial_order;
  bool use_polynomial_fit = default_use_polynomial_fit;

  parse_argument (argc, argv, "-search_radius", search_radius);
  if (parse_argument (argc, argv, "-sqr_gauss_param", sqr_gauss_param) == -1)
    sqr_gauss_param_set = false;
  if (parse_argument (argc, argv, "-polynomial_order", polynomial_order) != -1 )
    use_polynomial_fit = true;
  parse_argument (argc, argv, "-use_polynomial_fit", use_polynomial_fit);

  // Load the first file
  sensor_msgs::PointCloud2::Ptr cloud (new sensor_msgs::PointCloud2);
  if (!loadCloud (argv[p_file_indices[0]], *cloud))
    return (-1);

  // Do the smoothing
  sensor_msgs::PointCloud2 output;
  compute (cloud, output, search_radius, sqr_gauss_param_set, sqr_gauss_param,
           use_polynomial_fit, polynomial_order);

  // Save into the second file
  saveCloud (argv[p_file_indices[1]], output);
}
<commit_msg>search_radius -> radius<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 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.
 *
 * $Id$
 *
 */

#include <sensor_msgs/PointCloud2.h>
#include <pcl/point_types.h>
#include <pcl/io/pcd_io.h>
#include <pcl/console/print.h>
#include <pcl/console/parse.h>
#include <pcl/console/time.h>
#include <pcl/surface/mls.h>
#include <pcl/filters/voxel_grid.h>

using namespace pcl;
using namespace pcl::io;
using namespace pcl::console;

int default_polynomial_order = 2;
bool default_use_polynomial_fit = false;
double default_search_radius = 0.0,
    default_sqr_gauss_param = 0.0;

void
printHelp (int, char **argv)
{
  print_error ("Syntax is: %s input.pcd output.pcd <options>\n", argv[0]);
  print_info ("  where options are:\n");
  print_info ("                     -radius X          = sphere radius to be used for finding the k-nearest neighbors used for fitting (default: ");
  print_value ("%f", default_search_radius); print_info (")\n");
  print_info ("                     -sqr_gauss_param X = parameter used for the distance based weighting of neighbors (recommended = search_radius^2) (default: ");
  print_value ("%f", default_sqr_gauss_param); print_info (")\n");
  print_info ("                     -use_polynomial_fit X = decides whether the surface and normal are approximated using a polynomial or only via tangent estimation (default: ");
  print_value ("%d", default_use_polynomial_fit); print_info (")\n");
  print_info ("                     -polynomial_order X = order of the polynomial to be fit (implicitly, use_polynomial_fit = 1) (default: ");
  print_value ("%d", default_polynomial_order); print_info (")\n");
}

bool
loadCloud (const std::string &filename, sensor_msgs::PointCloud2 &cloud)
{
  TicToc tt;
  print_highlight ("Loading "); print_value ("%s ", filename.c_str ());

  tt.tic ();
  if (loadPCDFile (filename, cloud) < 0)
    return (false);
  print_info ("[done, "); print_value ("%g", tt.toc ()); print_info (" ms : "); print_value ("%d", cloud.width * cloud.height); print_info (" points]\n");
  print_info ("Available dimensions: "); print_value ("%s\n", pcl::getFieldsList (cloud).c_str ());

  return (true);
}

void
compute (const sensor_msgs::PointCloud2::ConstPtr &input, sensor_msgs::PointCloud2 &output,
         double search_radius, bool sqr_gauss_param_set, double sqr_gauss_param,
         bool use_polynomial_fit, int polynomial_order)
{

  PointCloud<PointXYZ>::Ptr xyz_cloud_pre (new pcl::PointCloud<PointXYZ> ()),
      xyz_cloud (new pcl::PointCloud<PointXYZ> ());
  fromROSMsg (*input, *xyz_cloud_pre);

  // Filter the NaNs from the cloud
  for (size_t i = 0; i < xyz_cloud_pre->size (); ++i)
    if (pcl_isfinite (xyz_cloud_pre->points[i].x))
      xyz_cloud->push_back (xyz_cloud_pre->points[i]);
  xyz_cloud->header = xyz_cloud_pre->header;
  xyz_cloud->height = 1;
  xyz_cloud->width = static_cast<uint32_t> (xyz_cloud->size ());
  xyz_cloud->is_dense = false;

  PointCloud<PointNormal>::Ptr xyz_cloud_smoothed (new PointCloud<PointNormal> ());

  MovingLeastSquares<PointXYZ, PointNormal> mls;
  mls.setInputCloud (xyz_cloud);
  mls.setSearchRadius (search_radius);
  if (sqr_gauss_param_set) mls.setSqrGaussParam (sqr_gauss_param);
  mls.setPolynomialFit (use_polynomial_fit);
  mls.setPolynomialOrder (polynomial_order);

//  mls.setUpsamplingMethod (MovingLeastSquares<PointXYZ, PointNormal>::SAMPLE_LOCAL_PLANE);
//  mls.setUpsamplingMethod (MovingLeastSquares<PointXYZ, PointNormal>::RANDOM_UNIFORM_DENSITY);
//  mls.setUpsamplingMethod (MovingLeastSquares<PointXYZ, PointNormal>::VOXEL_GRID_DILATION);
  mls.setUpsamplingMethod (MovingLeastSquares<PointXYZ, PointNormal>::NONE);
  mls.setPointDensity (60000 * int (search_radius)); // 300 points in a 5 cm radius
  mls.setUpsamplingRadius (0.025);
  mls.setUpsamplingStepSize (0.015);
  mls.setDilationIterations (2);
  mls.setDilationVoxelSize (0.01f);

  search::KdTree<PointXYZ>::Ptr tree (new search::KdTree<PointXYZ> ());
  mls.setSearchMethod (tree);
  mls.setComputeNormals (true);

  PCL_INFO ("Computing smoothed surface and normals with search_radius %f , sqr_gaussian_param %f, polynomial fitting %d, polynomial order %d\n",
            mls.getSearchRadius(), mls.getSqrGaussParam(), mls.getPolynomialFit(), mls.getPolynomialOrder());
  TicToc tt;
  tt.tic ();
  mls.process (*xyz_cloud_smoothed);
  print_info ("[done, "); print_value ("%g", tt.toc ()); print_info (" ms : "); print_value ("%d", xyz_cloud_smoothed->width * xyz_cloud_smoothed->height); print_info (" points]\n");

  toROSMsg (*xyz_cloud_smoothed, output);
}

void
saveCloud (const std::string &filename, const sensor_msgs::PointCloud2 &output)
{
  TicToc tt;
  tt.tic ();

  print_highlight ("Saving "); print_value ("%s ", filename.c_str ());

  pcl::io::savePCDFile (filename, output,  Eigen::Vector4f::Zero (),
                        Eigen::Quaternionf::Identity (), true);

  print_info ("[done, "); print_value ("%g", tt.toc ()); print_info (" ms : "); print_value ("%d", output.width * output.height); print_info (" points]\n");
}

/* ---[ */
int
main (int argc, char** argv)
{
  print_info ("Moving Least Squares smoothing of a point cloud. For more information, use: %s -h\n", argv[0]);

  if (argc < 3)
  {
    printHelp (argc, argv);
    return (-1);
  }

  // Parse the command line arguments for .pcd files
  std::vector<int> p_file_indices;
  p_file_indices = parse_file_extension_argument (argc, argv, ".pcd");
  if (p_file_indices.size () != 2)
  {
    print_error ("Need one input PCD file and one output PCD file to continue.\n");
    return (-1);
  }

  // Command line parsing
  double search_radius = default_search_radius;
  double sqr_gauss_param = default_sqr_gauss_param;
  bool sqr_gauss_param_set = true;
  int polynomial_order = default_polynomial_order;
  bool use_polynomial_fit = default_use_polynomial_fit;

  parse_argument (argc, argv, "-radius", search_radius);
  if (parse_argument (argc, argv, "-sqr_gauss_param", sqr_gauss_param) == -1)
    sqr_gauss_param_set = false;
  if (parse_argument (argc, argv, "-polynomial_order", polynomial_order) != -1 )
    use_polynomial_fit = true;
  parse_argument (argc, argv, "-use_polynomial_fit", use_polynomial_fit);

  // Load the first file
  sensor_msgs::PointCloud2::Ptr cloud (new sensor_msgs::PointCloud2);
  if (!loadCloud (argv[p_file_indices[0]], *cloud))
    return (-1);

  // Do the smoothing
  sensor_msgs::PointCloud2 output;
  compute (cloud, output, search_radius, sqr_gauss_param_set, sqr_gauss_param,
           use_polynomial_fit, polynomial_order);

  // Save into the second file
  saveCloud (argv[p_file_indices[1]], output);
}
<|endoftext|>


<commit_before>#include <cmath>
#include <cstring>
#include <fstream>
#include <iomanip>
#include <iostream>
#include <sstream>
#include <string>
#include <utility>
#include <vector>

using namespace std;

bool CompareCharacters(const char *expected, char **actual) {
  const size_t length = strlen(expected);
  bool result = true;
  for (size_t i = 0; i < length; ++i) {
    result &= expected[i] == (*actual)[i];
  }

  /*
  char buf[length + 1];
  for (size_t i = 0; i < length; ++i) {
    buf[i] = (*actual)[i];
  }
  buf[length] = '\0';
  cerr << "expected: " << expected << ", actual: " << buf << endl;
  */
  *actual += length;
  return result;
}

string ReadString(size_t size, char **buf) {
  string str(*buf, 0, size);
  *buf += size;
  return str;
}

int ReadNumber(char **buf, size_t size) {
  int result;
  unsigned int mask;
  switch (size) {
  case 2:
    result = static_cast<int>(*reinterpret_cast<short *>(*buf));
    break;
  case 3:
//    result = (*buf)[0] | ((*buf)[1] << 8) | ((*buf)[2] << 16) | (-(((*buf)[2] & 0x80) << 17));
    mask = ((*buf)[2] & 0x80) ? 0xFF000000 : 0x0;
    result = static_cast<int>((*reinterpret_cast<unsigned int *>(*buf) & 0x00FFFFFF) | mask);
//    result = static_cast<int>((*reinterpret_cast<unsigned int *>(*buf) & 0x00FFFFFF) | (-(((*buf)[2] & 0x80) << 17)));
    break;
  case 4:
    result = *reinterpret_cast<int *>(*buf);
    break;
  }
  *buf += size;
  return result;
}

short ReadShort(char **buf) {
  const short result = *reinterpret_cast<short *>(*buf);
  *buf += 2;
  return result;
}

unsigned int ReadUnsignedInt(char **buf) {
  const unsigned int result = *reinterpret_cast<int *>(*buf);
  *buf += 4;
  return result;
}

unsigned short ReadUnsignedShort(char **buf) {
  const unsigned short result = *reinterpret_cast<unsigned short *>(*buf);
  *buf += 2;
  return result;
}

string SamplingToTime(size_t sampling_counter, size_t sampling_rate) {
  stringstream ss;
  const int milli_seconds = 1000 * sampling_counter / sampling_rate;
  const int seconds = milli_seconds / 1000;
  ss << seconds << "." << setfill('0') << setw(3) << (milli_seconds % 1000);
  /*
  const int minutes = seconds / 60;
  const int hours = minutes / 60;
  ss << setfill('0') << setw(2) << hours
     << ":"
     << setfill('0') << setw(2) << minutes % 60
     << ":"
     << setfill('0') << setw(2) << seconds % 60
     << "."
     << setfill('0') << setw(3) << milli_seconds % 1000;
  */
  return ss.str();
}

int main(int argc, char *argv[]) {
  if (argc != 2) {
    cerr << "Usage: " << argv[0] << " filename" << endl;
    return -1;
  }

  ifstream ifs(argv[1]);
  if (!ifs) {
    cerr << "Failed to open file: " << argv[1] << endl;
    return -1;
  }
  ifs.seekg(0, std::ios::end);
  const size_t file_size = static_cast<size_t>(ifs.tellg());
  ifs.seekg(0, std::ios::beg);

  char *file_buf_head = new char[file_size + 1];  // + 1 is for 24bit PCM (ReadNumber)
  char *file_buf_ptr = file_buf_head;
  if (!ifs.read(file_buf_head, file_size)) {
    cerr << "Failed to read the file." << endl;
    return -1;
  }

  if (!CompareCharacters("RIFF", &file_buf_ptr)) {
    cerr << "Invalid RIFF format." << endl;
    return -1;
  }

  if (ReadUnsignedInt(&file_buf_ptr) + 8 != file_size) {
    cerr << "Invalid file size." << endl;
    cerr << "pos: " << (file_buf_ptr - file_buf_head) << endl;
    return -1;
  }

  if (!CompareCharacters("WAVEfmt ", &file_buf_ptr)) {
    cerr << "Invalid WAVE format." << endl;
    cerr << "pos: " << (file_buf_ptr - file_buf_head) << endl;
    return -1;
  }

  const size_t fmt_size = ReadUnsignedInt(&file_buf_ptr);
  const unsigned short format_id = ReadUnsignedShort(&file_buf_ptr);
  // ffmpeg output invalid format_id for 24bit or 32bit PCM.
  //  if (format_id != 1) {
  //    cerr << "Invalid format ID: " << format_id << endl;
  //    return -1;
  //  }

  const int channel_num = ReadUnsignedShort(&file_buf_ptr);
  const int sampling_rate = ReadUnsignedInt(&file_buf_ptr);
  const int sampling_bytes =
    ReadUnsignedInt(&file_buf_ptr) / channel_num / sampling_rate;
  if (sampling_bytes < 2 || 4 < sampling_bytes) {
    cerr << "Unsupported sampling bytes: " << sampling_bytes << endl;
    return -1;
  }
  if (ReadUnsignedShort(&file_buf_ptr) != channel_num * sampling_bytes) {
    cerr << "Invalid block size." << endl;
    return -1;
  }
  if (ReadUnsignedShort(&file_buf_ptr) != sampling_bytes * 8) {
    cerr << "Invalid sampling bits." << endl;
    return -1;
  }

  const size_t extend_header_size = ReadUnsignedShort(&file_buf_ptr);
  file_buf_ptr += extend_header_size;

  while (true) {
    if (file_buf_ptr - file_buf_head > 1024 - 4) {
      cerr << "Too big header." << endl;
      return -1;
    }
    if (CompareCharacters("data", &file_buf_ptr)) {
      break;
    }
    size_t chunk_size = ReadUnsignedInt(&file_buf_ptr);
    file_buf_ptr += chunk_size;
  }

  const size_t data_size = ReadUnsignedInt(&file_buf_ptr);
  if (data_size + (file_buf_ptr - file_buf_head) != file_size) {
    cerr << "Invalid data size." << endl;
    return -1;
  }

  vector<pair<size_t, size_t> > mute_ranges;
  const int kVolumeThreshold = 12 * (1 << ((sampling_bytes - 2) * 8));
  const int kVolumeDiffThreshold = 2;
  const int minimum_mute_chunk_threshold = sampling_rate / 100;  // 10msec
  int mute_counter = 0;
  const size_t max_sampling_count = data_size / (sampling_bytes * channel_num);

  for (size_t sampling_counter = 0; sampling_counter < max_sampling_count;
       ++sampling_counter) {
    const int left_sound = ReadNumber(&file_buf_ptr, sampling_bytes);
    const int right_sound = ReadNumber(&file_buf_ptr, sampling_bytes);

    // TODO: It may be better to use the differences from the previous values.
    if (abs(left_sound) <= kVolumeThreshold && abs(right_sound) <= kVolumeThreshold) {
      ++mute_counter;
      if (mute_counter == minimum_mute_chunk_threshold) {
        mute_ranges.push_back(make_pair(sampling_counter - minimum_mute_chunk_threshold + 1, 0));
      }
    } else {
      if (mute_counter >= minimum_mute_chunk_threshold) {
        mute_counter = 0;
        mute_ranges.back().second = sampling_counter - 1;
      }
    }
  }

  const size_t concat_threshold = sampling_rate / 1000;  // 1msec
  for (size_t i = 1; i < mute_ranges.size(); ++i) {
    if (mute_ranges[i].first - mute_ranges[i - 1].second < concat_threshold) {
      mute_ranges[i - 1].second = mute_ranges[i].second;
      mute_ranges.erase(mute_ranges.begin() + i);
      --i;
    }
  }
  const size_t mute_chunk_threshold = sampling_rate * 0.3;  // 300msec
  for (int i = 0; i < static_cast<int>(mute_ranges.size()); ++i) {
    if (mute_ranges[i].second - mute_ranges[i].first < mute_chunk_threshold) {
      mute_ranges.erase(mute_ranges.begin() + i);
      --i;
    }
  }

  cout << "all 0.000 " << SamplingToTime(max_sampling_count, sampling_rate) << endl;
  // Margin for body.
  // Silence ranges in some body have high-level noise.
  // On the other hand, CM doesn't have.
  // This margin improves the handling of such kind of body.
  const size_t margin = sampling_rate * 1001.0 / 30000.0 + 5;
  for (size_t i = 0; i < mute_ranges.size(); ++i) {
    const pair<size_t, size_t> &range = mute_ranges[i];
    const size_t start = (range.first > margin) ? range.first - margin : 0;
    const size_t end = min(max_sampling_count, range.second + margin);
    cout << SamplingToTime(start, sampling_rate) << " "
         << SamplingToTime(end, sampling_rate) << endl;
  }

  delete [] file_buf_head;

  return 0;
}
<commit_msg>Handle a last silence range correctly by silence_detector.<commit_after>#include <cmath>
#include <cstring>
#include <fstream>
#include <iomanip>
#include <iostream>
#include <sstream>
#include <string>
#include <utility>
#include <vector>

using namespace std;

bool CompareCharacters(const char *expected, char **actual) {
  const size_t length = strlen(expected);
  bool result = true;
  for (size_t i = 0; i < length; ++i) {
    result &= expected[i] == (*actual)[i];
  }

  *actual += length;
  return result;
}

string ReadString(size_t size, char **buf) {
  string str(*buf, 0, size);
  *buf += size;
  return str;
}

int ReadNumber(char **buf, size_t size) {
  int result;
  unsigned int mask;
  switch (size) {
  case 2:
    result = static_cast<int>(*reinterpret_cast<short *>(*buf));
    break;
  case 3:
    mask = ((*buf)[2] & 0x80) ? 0xFF000000 : 0x0;
    result = static_cast<int>((*reinterpret_cast<unsigned int *>(*buf) & 0x00FFFFFF) | mask);
    break;
  case 4:
    result = *reinterpret_cast<int *>(*buf);
    break;
  }
  *buf += size;
  return result;
}

short ReadShort(char **buf) {
  const short result = *reinterpret_cast<short *>(*buf);
  *buf += 2;
  return result;
}

unsigned int ReadUnsignedInt(char **buf) {
  const unsigned int result = *reinterpret_cast<int *>(*buf);
  *buf += 4;
  return result;
}

unsigned short ReadUnsignedShort(char **buf) {
  const unsigned short result = *reinterpret_cast<unsigned short *>(*buf);
  *buf += 2;
  return result;
}

string SamplingToTime(size_t sampling_counter, size_t sampling_rate) {
  stringstream ss;
  const int milli_seconds = 1000 * sampling_counter / sampling_rate;
  const int seconds = milli_seconds / 1000;
  ss << seconds << "." << setfill('0') << setw(3) << (milli_seconds % 1000);
  return ss.str();
}

int main(int argc, char *argv[]) {
  if (argc != 2) {
    cerr << "Usage: " << argv[0] << " filename" << endl;
    return -1;
  }

  ifstream ifs(argv[1]);
  if (!ifs) {
    cerr << "Failed to open file: " << argv[1] << endl;
    return -1;
  }
  ifs.seekg(0, std::ios::end);
  const size_t file_size = static_cast<size_t>(ifs.tellg());
  ifs.seekg(0, std::ios::beg);

  char *file_buf_head = new char[file_size + 1];  // + 1 is for 24bit PCM (ReadNumber)
  char *file_buf_ptr = file_buf_head;
  if (!ifs.read(file_buf_head, file_size)) {
    cerr << "Failed to read the file." << endl;
    return -1;
  }

  if (!CompareCharacters("RIFF", &file_buf_ptr)) {
    cerr << "Invalid RIFF format." << endl;
    return -1;
  }

  if (ReadUnsignedInt(&file_buf_ptr) + 8 != file_size) {
    cerr << "Invalid file size." << endl;
    cerr << "pos: " << (file_buf_ptr - file_buf_head) << endl;
    return -1;
  }

  if (!CompareCharacters("WAVEfmt ", &file_buf_ptr)) {
    cerr << "Invalid WAVE format." << endl;
    cerr << "pos: " << (file_buf_ptr - file_buf_head) << endl;
    return -1;
  }

  const size_t fmt_size = ReadUnsignedInt(&file_buf_ptr);
  const unsigned short format_id = ReadUnsignedShort(&file_buf_ptr);

  const int channel_num = ReadUnsignedShort(&file_buf_ptr);
  const int sampling_rate = ReadUnsignedInt(&file_buf_ptr);
  const int sampling_bytes =
    ReadUnsignedInt(&file_buf_ptr) / channel_num / sampling_rate;
  if (sampling_bytes < 2 || 4 < sampling_bytes) {
    cerr << "Unsupported sampling bytes: " << sampling_bytes << endl;
    return -1;
  }
  if (ReadUnsignedShort(&file_buf_ptr) != channel_num * sampling_bytes) {
    cerr << "Invalid block size." << endl;
    return -1;
  }
  if (ReadUnsignedShort(&file_buf_ptr) != sampling_bytes * 8) {
    cerr << "Invalid sampling bits." << endl;
    return -1;
  }

  const size_t extend_header_size = ReadUnsignedShort(&file_buf_ptr);
  file_buf_ptr += extend_header_size;

  while (true) {
    if (file_buf_ptr - file_buf_head > 1024 - 4) {
      cerr << "Too big header." << endl;
      return -1;
    }
    if (CompareCharacters("data", &file_buf_ptr)) {
      break;
    }
    size_t chunk_size = ReadUnsignedInt(&file_buf_ptr);
    file_buf_ptr += chunk_size;
  }

  const size_t data_size = ReadUnsignedInt(&file_buf_ptr);
  if (data_size + (file_buf_ptr - file_buf_head) != file_size) {
    cerr << "Invalid data size." << endl;
    return -1;
  }

  vector<pair<size_t, size_t> > mute_ranges;
  const int kVolumeThreshold = 12 * (1 << ((sampling_bytes - 2) * 8));
  const int kVolumeDiffThreshold = 2;
  const int minimum_mute_chunk_threshold = sampling_rate / 100;  // 10msec
  int mute_counter = 0;
  const size_t max_sampling_count = data_size / (sampling_bytes * channel_num);

  for (size_t sampling_counter = 0; sampling_counter < max_sampling_count;
       ++sampling_counter) {
    const int left_sound = ReadNumber(&file_buf_ptr, sampling_bytes);
    const int right_sound = ReadNumber(&file_buf_ptr, sampling_bytes);

    if (abs(left_sound) <= kVolumeThreshold && abs(right_sound) <= kVolumeThreshold) {
      ++mute_counter;
      if (mute_counter == minimum_mute_chunk_threshold) {
        mute_ranges.push_back(make_pair(sampling_counter - minimum_mute_chunk_threshold + 1,
                                        max_sampling_count));
      }
    } else {
      if (mute_counter >= minimum_mute_chunk_threshold) {
        mute_counter = 0;
        mute_ranges.back().second = sampling_counter - 1;
      }
    }
  }

  const size_t concat_threshold = sampling_rate / 1000;  // 1msec
  for (size_t i = 1; i < mute_ranges.size(); ++i) {
    if (mute_ranges[i].first - mute_ranges[i - 1].second < concat_threshold) {
      mute_ranges[i - 1].second = mute_ranges[i].second;
      mute_ranges.erase(mute_ranges.begin() + i);
      --i;
    }
  }
  const size_t mute_chunk_threshold = sampling_rate * 0.3;  // 300msec
  for (int i = 0; i < static_cast<int>(mute_ranges.size()); ++i) {
    if (mute_ranges[i].second - mute_ranges[i].first < mute_chunk_threshold) {
      mute_ranges.erase(mute_ranges.begin() + i);
      --i;
    }
  }

  cout << "all 0.000 " << SamplingToTime(max_sampling_count, sampling_rate) << endl;
  // Margin for body.
  // Silence ranges in some body have high-level noise.
  // On the other hand, CM doesn't have.
  // This margin improves the handling of such kind of body.
  const size_t margin = sampling_rate * 1001.0 / 30000.0 + 5;
  for (size_t i = 0; i < mute_ranges.size(); ++i) {
    const pair<size_t, size_t> &range = mute_ranges[i];
    const size_t start = (range.first > margin) ? range.first - margin : 0;
    const size_t end = min(max_sampling_count, range.second + margin);
    cout << SamplingToTime(start, sampling_rate) << " "
         << SamplingToTime(end, sampling_rate) << endl;
  }

  delete [] file_buf_head;

  return 0;
}
<|endoftext|>


<commit_before>/**
 * Non-metric Space Library
 *
 * Authors: Bilegsaikhan Naidan (https://github.com/bileg), Leonid Boytsov (http://boytsov.info).
 * With contributions from Lawrence Cayton (http://lcayton.com/) and others.
 *
 * For the complete list of contributors and further details see:
 * https://github.com/searchivarius/NonMetricSpaceLib
 *
 * Copyright (c) 2014
 *
 * This code is released under the
 * Apache License Version 2.0 http://www.apache.org/licenses/.
 *
 */
#ifndef _MSC_VER

#include <sys/time.h>

#include "logging.h"
#include "ztimer.h"
#include "bunit.h"

namespace similarity {

const unsigned TIMER_ERR_TOL = 1000;

/*
 * These test is intended to run only on Unix-like systems.
 */

/**
 *  author: Preston Bannister
 */
class WallClockTimerBannister {
public:
    struct timeval t1, t2;
    WallClockTimerBannister() :
        t1(), t2() {
        gettimeofday(&t1, 0);
        t2 = t1;
    }
    void reset() {
        gettimeofday(&t1, 0);
        t2 = t1;
    }
    uint64_t elapsed() {
        return ((t2.tv_sec - t1.tv_sec) * 1000ULL * 1000ULL) + ((t2.tv_usec - t1. tv_usec));
    }
    uint64_t split() {
        gettimeofday(&t2, 0);
        return elapsed();
    }
};

void BurnCPU(size_t qty = 10000000000) {
  size_t sum = 0;
  for (size_t i = 0; i < qty; ++i) {
    sum += i;
    sum *= qty;
  }
  LOG(LIB_INFO) << "Ignore: " << sum;
}

#ifdef DISABLE_LONG_TESTS
TEST(DISABLE_TestTimer) {
#else
TEST(TestTimer) {
#endif
  WallClockTimerBannister oldz;
  WallClockTimer          z;

  BurnCPU();
  oldz.split();
  z.split();

  LOG(LIB_INFO) << "Timer: " << z.elapsed() << " : " << oldz.elapsed();
  // We expect both timers to differ in at most 0.1 ms
  EXPECT_EQ(std::abs(static_cast<int64_t>(z.elapsed()) - static_cast<int64_t>(oldz.elapsed())) < TIMER_ERR_TOL, true);

  BurnCPU();
  oldz.split();
  z.split();

  LOG(LIB_INFO) << "Timer: " << z.elapsed() << " : " << oldz.elapsed();
  // We expect both timers to differ in at most 0.1 ms
  EXPECT_EQ(std::abs(static_cast<int64_t>(z.elapsed()) - static_cast<int64_t>(oldz.elapsed())) < TIMER_ERR_TOL, true);

  z.reset();
  oldz.reset();

  BurnCPU();
  oldz.split();
  z.split();

  LOG(LIB_INFO) << "Timer: " << z.elapsed() << " : " << oldz.elapsed();
  // We expect both timers to differ in at most 0.1 ms
  EXPECT_EQ(std::abs(static_cast<int64_t>(z.elapsed()) - static_cast<int64_t>(oldz.elapsed())) < TIMER_ERR_TOL, true);
}

}  // namespace similarity
#endif

<commit_msg>Further decreasing tolerance threshold in timer testing.<commit_after>/**
 * Non-metric Space Library
 *
 * Authors: Bilegsaikhan Naidan (https://github.com/bileg), Leonid Boytsov (http://boytsov.info).
 * With contributions from Lawrence Cayton (http://lcayton.com/) and others.
 *
 * For the complete list of contributors and further details see:
 * https://github.com/searchivarius/NonMetricSpaceLib
 *
 * Copyright (c) 2014
 *
 * This code is released under the
 * Apache License Version 2.0 http://www.apache.org/licenses/.
 *
 */
#ifndef _MSC_VER

#include <sys/time.h>

#include "logging.h"
#include "ztimer.h"
#include "bunit.h"

namespace similarity {

const unsigned TIMER_ERR_TOL = 2000;

/*
 * These test is intended to run only on Unix-like systems.
 */

/**
 *  author: Preston Bannister
 */
class WallClockTimerBannister {
public:
    struct timeval t1, t2;
    WallClockTimerBannister() :
        t1(), t2() {
        gettimeofday(&t1, 0);
        t2 = t1;
    }
    void reset() {
        gettimeofday(&t1, 0);
        t2 = t1;
    }
    uint64_t elapsed() {
        return ((t2.tv_sec - t1.tv_sec) * 1000ULL * 1000ULL) + ((t2.tv_usec - t1. tv_usec));
    }
    uint64_t split() {
        gettimeofday(&t2, 0);
        return elapsed();
    }
};

void BurnCPU(size_t qty = 10000000000) {
  size_t sum = 0;
  for (size_t i = 0; i < qty; ++i) {
    sum += i;
    sum *= qty;
  }
  LOG(LIB_INFO) << "Ignore: " << sum;
}

#ifdef DISABLE_LONG_TESTS
TEST(DISABLE_TestTimer) {
#else
TEST(TestTimer) {
#endif
  WallClockTimerBannister oldz;
  WallClockTimer          z;

  BurnCPU();
  oldz.split();
  z.split();

  LOG(LIB_INFO) << "Timer: " << z.elapsed() << " : " << oldz.elapsed();
  // We expect both timers to differ in at most 0.1 ms
  EXPECT_EQ(std::abs(static_cast<int64_t>(z.elapsed()) - static_cast<int64_t>(oldz.elapsed())) < TIMER_ERR_TOL, true);

  BurnCPU();
  oldz.split();
  z.split();

  LOG(LIB_INFO) << "Timer: " << z.elapsed() << " : " << oldz.elapsed();
  // We expect both timers to differ in at most 0.1 ms
  EXPECT_EQ(std::abs(static_cast<int64_t>(z.elapsed()) - static_cast<int64_t>(oldz.elapsed())) < TIMER_ERR_TOL, true);

  z.reset();
  oldz.reset();

  BurnCPU();
  oldz.split();
  z.split();

  LOG(LIB_INFO) << "Timer: " << z.elapsed() << " : " << oldz.elapsed();
  // We expect both timers to differ in at most 0.1 ms
  EXPECT_EQ(std::abs(static_cast<int64_t>(z.elapsed()) - static_cast<int64_t>(oldz.elapsed())) < TIMER_ERR_TOL, true);
}

}  // namespace similarity
#endif

<|endoftext|>


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

#include "iceoryx_posh/iceoryx_posh_types.hpp"
#include "iceoryx_posh/mepoo/memory_info.hpp"

namespace iox
{
namespace popo
{
struct ConditionVariableWaiter
{
    ConditionVariablewaiters(const mepoo::MemoryInfo& memoryInfo = mepoo::MemoryInfo()) noexcept
        : m_memoryInfo(memoryInfo)
    {
    }

    mepoo::MemoryInfo m_memoryInfo;
};

} // namespace popo
} // namespace iox

#endif // IOX_POSH_POPO_WAITSET_CONDITION_HPP
<commit_msg>iox-#25: Fix typo<commit_after>// Copyright (c) 2020 by Robert Bosch GmbH. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#ifndef IOX_POSH_POPO_WAITSET_CONDITION_HPP
#define IOX_POSH_POPO_WAITSET_CONDITION_HPP

#include "iceoryx_posh/iceoryx_posh_types.hpp"
#include "iceoryx_posh/mepoo/memory_info.hpp"

namespace iox
{
namespace popo
{
struct ConditionVariableWaiter
{
    ConditionVariableWaiter(const mepoo::MemoryInfo& memoryInfo = mepoo::MemoryInfo()) noexcept
        : m_memoryInfo(memoryInfo)
    {
    }

    mepoo::MemoryInfo m_memoryInfo;
};

} // namespace popo
} // namespace iox

#endif // IOX_POSH_POPO_WAITSET_CONDITION_HPP
<|endoftext|>