text
stringlengths 54
60.6k
|
---|
<commit_before>/*=========================================================================
Program: ORFEO Toolbox
Language: C++
Date: $Date$
Version: $Revision$
Copyright (c) Centre National d'Etudes Spatiales. All rights reserved.
See OTBCopyright.txt for details.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE. See the above copyright notices for more information.
=========================================================================*/
#include "otbWrapperApplication.h"
#include "otbWrapperApplicationFactory.h"
#include "otbStereorectificationDeformationFieldSource.h"
// Elevation handler
#include "otbWrapperElevationParametersHandler.h"
namespace otb
{
namespace Wrapper
{
class StereoRectificationGridGenerator : public Application
{
public:
/** Standard class typedefs. */
typedef StereoRectificationGridGenerator Self;
typedef Application Superclass;
typedef itk::SmartPointer<Self> Pointer;
typedef itk::SmartPointer<const Self> ConstPointer;
typedef otb::StereorectificationDeformationFieldSource
<FloatVectorImageType,FloatVectorImageType> DeformationFieldSourceType;
/** Standard macro */
itkNewMacro(Self);
itkTypeMacro(StereoRectificationGridGenerator, otb::Application);
private:
StereoRectificationGridGenerator()
{
// Instanciate deformation field source
m_DeformationFieldSource = DeformationFieldSourceType::New();
}
void DoInit()
{
SetName("StereoRectificationGridGenerator");
SetDescription("Generates two deformation fields to stereo-rectify (i.e. resample in epipolar geometry) a pair of stereo images up to the sensor model precision");
SetDocName("Stereo-rectification deformation grid generator");
SetDocLongDescription("This application generates a pair of deformation grid to stereo-rectify a pair of stereo images according to sensor modelling and a mean elevation hypothesis. The deformation grids can be passed to the StereoRectificationGridGenerator application for actual resampling in epipolar geometry.");
SetDocLimitations("Generation of the deformation grid is not streamable, pay attention to this fact when setting the grid step.");
SetDocAuthors("OTB-Team");
AddDocTag(Tags::Geometry);
SetDocSeeAlso("otbGridBasedImageResampling");
AddParameter(ParameterType_Group,"io","Input and output data");
SetParameterDescription("io","This group of parameters allows to set the input and output images.");
AddParameter(ParameterType_InputImage,"io.inleft","Left input image");
SetParameterDescription("io.inleft","The left input image to resample");
AddParameter(ParameterType_InputImage,"io.inright","Right input image");
SetParameterDescription("io.inright","The right input image to resample");
AddParameter(ParameterType_OutputImage, "io.outleft", "Left output deformation grid");
SetParameterDescription("io.outleft","The output deformation grid to be used to resample the left input image");
AddParameter(ParameterType_OutputImage, "io.outright", "Right output deformation grid");
SetParameterDescription("io.outright","The output deformation grid to be used to resample the right input image");
AddParameter(ParameterType_Group,"epi","Epipolar geometry and grid parameters");
SetParameterDescription("epi","Parameters of the epipolar geometry and output grids");
ElevationParametersHandler::AddElevationParameters(this, "epi.elevation");
SetParameterDescription("epi.elevation","In the output rectified images, corresponding pixels whose elevation is equal to the mean elevation will have a null disparity");
MandatoryOn("epi.elevation");
AddParameter(ParameterType_Float,"epi.scale","Scale of epipolar images");
SetParameterDescription("epi.scale","The scale parameter allows to generated zoomed-in (scale < 1) or zoomed-out (scale > 1) epipolar images.");
SetDefaultParameterFloat("epi.scale",1.);
AddParameter(ParameterType_Int,"epi.step","Step of the deformation grid (in nb. of pixels)");
SetParameterDescription("epi.step","Stereo-rectification deformation grid only varies slowly. Therefore, it is recommanded to use a coarser grid (higher step value) in case of large images");
SetDefaultParameterInt("epi.step",1);
AddParameter(ParameterType_Int,"epi.rectsizex","Rectified image size X");
SetParameterDescription("epi.rectsizex","The application computes the optimal rectified image size so that the whole left input image fits into the rectified area. However, due to the scale and step parameter, this size may not match the size of the deformation field output. In this case, one can use these output values.");
SetParameterRole("epi.rectsizex", Role_Output);
AddParameter(ParameterType_Int,"epi.rectsizey","Rectified image size Y");
SetParameterDescription("epi.rectsizey","The application computes the optimal rectified image size so that the whole left input image fits into the rectified area. However, due to the scale and step parameter, this size may not match the size of the deformation field output. In this case, one can use these output values.");
SetParameterRole("epi.rectsizey", Role_Output);
AddParameter(ParameterType_Float,"epi.baseline","Mean baseline ratio");
SetParameterDescription("epi.baseline","This parameter is the mean value, in meters, of the baseline to sensor altitude ratio. It can be used to convert disparities to physical elevation, since a disparity of one pixel will corresspond to an elevation offset of this value with respect to the mean elevation.");
SetParameterRole("epi.baseline", Role_Output);
// Doc example
SetDocExampleParameterValue("io.inleft","wv2_xs_left.tif");
SetDocExampleParameterValue("io.inright","wv2_xs_left.tif");
SetDocExampleParameterValue("io.outleft","wv2_xs_left_epi_field.tif");
SetDocExampleParameterValue("io.outright","wv2_xs_right_epi_field.tif");
SetDocExampleParameterValue("epi.elevation.average","400");
}
void DoUpdateParameters()
{
// Nothing to do here
}
void DoExecute()
{
m_DeformationFieldSource->SetLeftImage(GetParameterImage("io.inleft"));
m_DeformationFieldSource->SetRightImage(GetParameterImage("io.inright"));
m_DeformationFieldSource->SetGridStep(GetParameterInt("epi.step"));
m_DeformationFieldSource->SetScale(GetParameterFloat("epi.scale"));
switch(ElevationParametersHandler::GetElevationType(this, "epi.elevation"))
{
case Elevation_DEM:
{
m_DeformationFieldSource->SetDEMDirectory(ElevationParametersHandler::GetDEMDirectory(this, "epi.elevation"));
m_DeformationFieldSource->SetGeoidFile(ElevationParametersHandler::GetGeoidFile(this, "epi.elevation"));
}
break;
case Elevation_Average:
{
m_DeformationFieldSource->SetAverageElevation(ElevationParametersHandler::GetAverageElevation(this, "epi.elevation"));
}
}
AddProcess(m_DeformationFieldSource, "Computing epipolar grids ...");
m_DeformationFieldSource->Update();
SetParameterInt("epi.rectsizex",m_DeformationFieldSource->GetRectifiedImageSize()[0]);
SetParameterInt("epi.rectsizey",m_DeformationFieldSource->GetRectifiedImageSize()[1]);
SetParameterFloat("epi.baseline",m_DeformationFieldSource->GetMeanBaselineRatio());
SetParameterOutputImage("io.outleft",m_DeformationFieldSource->GetLeftDeformationFieldOutput());
SetParameterOutputImage("io.outright",m_DeformationFieldSource->GetRightDeformationFieldOutput());
}
DeformationFieldSourceType::Pointer m_DeformationFieldSource;
};
} // End namespace Wrapper
} // End namespace otb
OTB_APPLICATION_EXPORT(otb::Wrapper::StereoRectificationGridGenerator)
<commit_msg>ENH: Computing inverse deformation field as well<commit_after>/*=========================================================================
Program: ORFEO Toolbox
Language: C++
Date: $Date$
Version: $Revision$
Copyright (c) Centre National d'Etudes Spatiales. All rights reserved.
See OTBCopyright.txt for details.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE. See the above copyright notices for more information.
=========================================================================*/
#include "otbWrapperApplication.h"
#include "otbWrapperApplicationFactory.h"
#include "otbStereorectificationDeformationFieldSource.h"
// Elevation handler
#include "otbWrapperElevationParametersHandler.h"
#include "itkInverseDeformationFieldImageFilter.h"
#include "itkVectorCastImageFilter.h"
#include "itkVectorIndexSelectionCastImageFilter.h"
#include "otbImageList.h"
#include "otbImageListToVectorImageFilter.h"
namespace otb
{
namespace Wrapper
{
class StereoRectificationGridGenerator : public Application
{
public:
/** Standard class typedefs. */
typedef StereoRectificationGridGenerator Self;
typedef Application Superclass;
typedef itk::SmartPointer<Self> Pointer;
typedef itk::SmartPointer<const Self> ConstPointer;
typedef otb::StereorectificationDeformationFieldSource
<FloatVectorImageType,FloatVectorImageType> DeformationFieldSourceType;
typedef itk::Vector<double,2> DeformationType;
typedef otb::Image<DeformationType> DeformationFieldType;
typedef itk::VectorCastImageFilter
<FloatVectorImageType,
DeformationFieldType> DeformationFieldCastFilterType;
typedef itk::InverseDeformationFieldImageFilter
<DeformationFieldType,DeformationFieldType> InverseDeformationFieldFilterType;
typedef itk::VectorIndexSelectionCastImageFilter<DeformationFieldType,
FloatImageType> IndexSelectionCastFilterType;
typedef otb::ImageList<FloatImageType> ImageListType;
typedef otb::ImageListToVectorImageFilter<ImageListType,FloatVectorImageType> ImageListFilterType;
/** Standard macro */
itkNewMacro(Self);
itkTypeMacro(StereoRectificationGridGenerator, otb::Application);
private:
StereoRectificationGridGenerator()
{
// Instanciate deformation field source
m_DeformationFieldSource = DeformationFieldSourceType::New();
m_LeftInvertDeformationFieldFilter = InverseDeformationFieldFilterType::New();
m_RightInvertDeformationFieldFilter = InverseDeformationFieldFilterType::New();
m_LeftDeformationFieldCaster = DeformationFieldCastFilterType::New();
m_LeftIndexSelectionFilter1 = IndexSelectionCastFilterType::New();
m_LeftIndexSelectionFilter2 = IndexSelectionCastFilterType::New();
m_LeftImageList = ImageListType::New();
m_LeftImageListFilter = ImageListFilterType::New();
m_RightDeformationFieldCaster = DeformationFieldCastFilterType::New();
m_RightIndexSelectionFilter1 = IndexSelectionCastFilterType::New();
m_RightIndexSelectionFilter2 = IndexSelectionCastFilterType::New();
m_RightImageList = ImageListType::New();
m_RightImageListFilter = ImageListFilterType::New();
}
void DoInit()
{
SetName("StereoRectificationGridGenerator");
SetDescription("Generates two deformation fields to stereo-rectify (i.e. resample in epipolar geometry) a pair of stereo images up to the sensor model precision");
SetDocName("Stereo-rectification deformation grid generator");
SetDocLongDescription("This application generates a pair of deformation grid to stereo-rectify a pair of stereo images according to sensor modelling and a mean elevation hypothesis. The deformation grids can be passed to the StereoRectificationGridGenerator application for actual resampling in epipolar geometry.");
SetDocLimitations("Generation of the deformation grid is not streamable, pay attention to this fact when setting the grid step.");
SetDocAuthors("OTB-Team");
AddDocTag(Tags::Geometry);
SetDocSeeAlso("otbGridBasedImageResampling");
AddParameter(ParameterType_Group,"io","Input and output data");
SetParameterDescription("io","This group of parameters allows to set the input and output images.");
AddParameter(ParameterType_InputImage,"io.inleft","Left input image");
SetParameterDescription("io.inleft","The left input image to resample");
AddParameter(ParameterType_InputImage,"io.inright","Right input image");
SetParameterDescription("io.inright","The right input image to resample");
AddParameter(ParameterType_OutputImage, "io.outleft", "Left output deformation grid");
SetParameterDescription("io.outleft","The output deformation grid to be used to resample the left input image");
AddParameter(ParameterType_OutputImage, "io.outright", "Right output deformation grid");
SetParameterDescription("io.outright","The output deformation grid to be used to resample the right input image");
AddParameter(ParameterType_Group,"epi","Epipolar geometry and grid parameters");
SetParameterDescription("epi","Parameters of the epipolar geometry and output grids");
ElevationParametersHandler::AddElevationParameters(this, "epi.elevation");
SetParameterDescription("epi.elevation","In the output rectified images, corresponding pixels whose elevation is equal to the mean elevation will have a null disparity");
MandatoryOn("epi.elevation");
AddParameter(ParameterType_Float,"epi.scale","Scale of epipolar images");
SetParameterDescription("epi.scale","The scale parameter allows to generated zoomed-in (scale < 1) or zoomed-out (scale > 1) epipolar images.");
SetDefaultParameterFloat("epi.scale",1.);
AddParameter(ParameterType_Int,"epi.step","Step of the deformation grid (in nb. of pixels)");
SetParameterDescription("epi.step","Stereo-rectification deformation grid only varies slowly. Therefore, it is recommanded to use a coarser grid (higher step value) in case of large images");
SetDefaultParameterInt("epi.step",1);
AddParameter(ParameterType_Int,"epi.rectsizex","Rectified image size X");
SetParameterDescription("epi.rectsizex","The application computes the optimal rectified image size so that the whole left input image fits into the rectified area. However, due to the scale and step parameter, this size may not match the size of the deformation field output. In this case, one can use these output values.");
SetParameterRole("epi.rectsizex", Role_Output);
AddParameter(ParameterType_Int,"epi.rectsizey","Rectified image size Y");
SetParameterDescription("epi.rectsizey","The application computes the optimal rectified image size so that the whole left input image fits into the rectified area. However, due to the scale and step parameter, this size may not match the size of the deformation field output. In this case, one can use these output values.");
SetParameterRole("epi.rectsizey", Role_Output);
AddParameter(ParameterType_Float,"epi.baseline","Mean baseline ratio");
SetParameterDescription("epi.baseline","This parameter is the mean value, in meters, of the baseline to sensor altitude ratio. It can be used to convert disparities to physical elevation, since a disparity of one pixel will corresspond to an elevation offset of this value with respect to the mean elevation.");
SetParameterRole("epi.baseline", Role_Output);
AddParameter(ParameterType_Group,"inverse","Write inverse fields");
SetParameterDescription("inverse","This group of parameter allows to generate the inverse fields as well");
AddParameter(ParameterType_OutputImage, "inverse.outleft", "Left inverse deformation grid");
SetParameterDescription("inverse.outleft","The output deformation grid to be used to resample the epipolar left image");
AddParameter(ParameterType_OutputImage, "inverse.outright", "Right inverse deformation grid");
SetParameterDescription("inverse.outright","The output deformation grid to be used to resample the epipolar right image");
AddParameter(ParameterType_Int, "inverse.ssrate", "Sub-sampling rate for inversion");
SetParameterDescription("inverse.ssrate","Grid inversion is an heavy process that implies spline regression on control points. To avoid eating to much memory, this parameter allows to first sub-sample the field to invert.");
SetDefaultParameterInt("inverse.ssrate",16);
SetMinimumParameterIntValue("inverse.ssrate",1);
// Doc example
SetDocExampleParameterValue("io.inleft","wv2_xs_left.tif");
SetDocExampleParameterValue("io.inright","wv2_xs_left.tif");
SetDocExampleParameterValue("io.outleft","wv2_xs_left_epi_field.tif");
SetDocExampleParameterValue("io.outright","wv2_xs_right_epi_field.tif");
SetDocExampleParameterValue("epi.elevation.average","400");
}
void DoUpdateParameters()
{
// Nothing to do here
}
void DoExecute()
{
m_DeformationFieldSource->SetLeftImage(GetParameterImage("io.inleft"));
m_DeformationFieldSource->SetRightImage(GetParameterImage("io.inright"));
m_DeformationFieldSource->SetGridStep(GetParameterInt("epi.step"));
m_DeformationFieldSource->SetScale(GetParameterFloat("epi.scale"));
switch(ElevationParametersHandler::GetElevationType(this, "epi.elevation"))
{
case Elevation_DEM:
{
m_DeformationFieldSource->SetDEMDirectory(ElevationParametersHandler::GetDEMDirectory(this, "epi.elevation"));
m_DeformationFieldSource->SetGeoidFile(ElevationParametersHandler::GetGeoidFile(this, "epi.elevation"));
}
break;
case Elevation_Average:
{
m_DeformationFieldSource->SetAverageElevation(ElevationParametersHandler::GetAverageElevation(this, "epi.elevation"));
}
}
AddProcess(m_DeformationFieldSource, "Computing epipolar grids ...");
m_DeformationFieldSource->Update();
SetParameterInt("epi.rectsizex",m_DeformationFieldSource->GetRectifiedImageSize()[0]);
SetParameterInt("epi.rectsizey",m_DeformationFieldSource->GetRectifiedImageSize()[1]);
SetParameterFloat("epi.baseline",m_DeformationFieldSource->GetMeanBaselineRatio());
SetParameterOutputImage("io.outleft",m_DeformationFieldSource->GetLeftDeformationFieldOutput());
SetParameterOutputImage("io.outright",m_DeformationFieldSource->GetRightDeformationFieldOutput());
// Inverse part
// lots of casting here ...
// Left field inversion
m_LeftDeformationFieldCaster->SetInput(m_DeformationFieldSource->GetLeftDeformationFieldOutput());
m_LeftInvertDeformationFieldFilter->SetInput(m_LeftDeformationFieldCaster->GetOutput());
FloatVectorImageType::PointType lorigin = GetParameterImage("io.inleft")->GetOrigin();
FloatVectorImageType::SpacingType lspacing = GetParameterImage("io.inleft")->GetSpacing();
FloatVectorImageType::SizeType lsize = GetParameterImage("io.inleft")->GetLargestPossibleRegion().GetSize();
lspacing[0]*=GetParameterInt("epi.step");
lspacing[1]*=GetParameterInt("epi.step");
lsize[0]/=GetParameterInt("epi.step")+1;
lsize[1]/=GetParameterInt("epi.step")+1;
m_LeftInvertDeformationFieldFilter->SetOutputOrigin(lorigin);
m_LeftInvertDeformationFieldFilter->SetOutputSpacing(lspacing);
m_LeftInvertDeformationFieldFilter->SetSize(lsize);
m_LeftInvertDeformationFieldFilter->SetSubsamplingFactor(GetParameterInt("inverse.ssrate"));
m_LeftIndexSelectionFilter1->SetInput(m_LeftInvertDeformationFieldFilter->GetOutput());
m_LeftIndexSelectionFilter1->SetIndex(0);
m_LeftIndexSelectionFilter2->SetInput(m_LeftInvertDeformationFieldFilter->GetOutput());
m_LeftIndexSelectionFilter2->SetIndex(1);
m_LeftImageList->Clear();
m_LeftImageList->PushBack(m_LeftIndexSelectionFilter1->GetOutput());
m_LeftImageList->PushBack(m_LeftIndexSelectionFilter2->GetOutput());
m_LeftImageListFilter->SetInput(m_LeftImageList);
SetParameterOutputImage("inverse.outleft",m_LeftImageListFilter->GetOutput());
// Right field inversion
m_RightDeformationFieldCaster->SetInput(m_DeformationFieldSource->GetRightDeformationFieldOutput());
m_RightInvertDeformationFieldFilter->SetInput(m_RightDeformationFieldCaster->GetOutput());
FloatVectorImageType::PointType rorigin = GetParameterImage("io.inright")->GetOrigin();
FloatVectorImageType::SpacingType rspacing = GetParameterImage("io.inright")->GetSpacing();
FloatVectorImageType::SizeType rsize = GetParameterImage("io.inright")->GetLargestPossibleRegion().GetSize();
m_RightInvertDeformationFieldFilter->SetOutputOrigin(rorigin);
m_RightInvertDeformationFieldFilter->SetOutputSpacing(rspacing);
m_RightInvertDeformationFieldFilter->SetSize(rsize);
m_RightInvertDeformationFieldFilter->SetSubsamplingFactor(GetParameterInt("inverse.ssrate"));
m_RightIndexSelectionFilter1->SetInput(m_RightInvertDeformationFieldFilter->GetOutput());
m_RightIndexSelectionFilter1->SetIndex(0);
m_RightIndexSelectionFilter2->SetInput(m_RightInvertDeformationFieldFilter->GetOutput());
m_RightIndexSelectionFilter2->SetIndex(1);
m_RightImageList->Clear();
m_RightImageList->PushBack(m_RightIndexSelectionFilter1->GetOutput());
m_RightImageList->PushBack(m_RightIndexSelectionFilter2->GetOutput());
m_RightImageListFilter->SetInput(m_RightImageList);
SetParameterOutputImage("inverse.outright",m_RightImageListFilter->GetOutput());
}
DeformationFieldSourceType::Pointer m_DeformationFieldSource;
InverseDeformationFieldFilterType::Pointer m_LeftInvertDeformationFieldFilter;
DeformationFieldCastFilterType::Pointer m_LeftDeformationFieldCaster;
IndexSelectionCastFilterType::Pointer m_LeftIndexSelectionFilter1;
IndexSelectionCastFilterType::Pointer m_LeftIndexSelectionFilter2;
ImageListType::Pointer m_LeftImageList;
ImageListFilterType::Pointer m_LeftImageListFilter;
InverseDeformationFieldFilterType::Pointer m_RightInvertDeformationFieldFilter;
DeformationFieldCastFilterType::Pointer m_RightDeformationFieldCaster;
IndexSelectionCastFilterType::Pointer m_RightIndexSelectionFilter1;
IndexSelectionCastFilterType::Pointer m_RightIndexSelectionFilter2;
ImageListType::Pointer m_RightImageList;
ImageListFilterType::Pointer m_RightImageListFilter;
};
} // End namespace Wrapper
} // End namespace otb
OTB_APPLICATION_EXPORT(otb::Wrapper::StereoRectificationGridGenerator)
<|endoftext|> |
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: IItemSetHelper.hxx,v $
*
* $Revision: 1.6 $
*
* last change: $Author: hr $ $Date: 2007-11-01 15:15:09 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
#ifndef DBAUI_ITEMSETHELPER_HXX
#define DBAUI_ITEMSETHELPER_HXX
#ifndef _SAL_TYPES_H_
#include <sal/types.h>
#endif
#ifndef _COMPHELPER_UNO3_HXX_
#include <comphelper/uno3.hxx>
#endif
#ifndef _DBAUI_DSNTYPES_HXX_
#include "dsntypes.hxx"
#endif
FORWARD_DECLARE_INTERFACE(beans,XPropertySet)
FORWARD_DECLARE_INTERFACE(sdbc,XConnection)
FORWARD_DECLARE_INTERFACE(sdbc,XDriver)
FORWARD_DECLARE_INTERFACE(lang,XMultiServiceFactory)
class SfxItemSet;
namespace dbaui
{
class SAL_NO_VTABLE IItemSetHelper
{
public:
virtual const SfxItemSet* getOutputSet() const = 0;
virtual SfxItemSet* getWriteOutputSet() = 0;
};
class SAL_NO_VTABLE IDatabaseSettingsDialog
{
public:
virtual ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory > getORB() const = 0;
virtual ::std::pair< ::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XConnection >,sal_Bool> createConnection() = 0;
virtual ::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XDriver > getDriver() = 0;
virtual DATASOURCE_TYPE getDatasourceType(const SfxItemSet& _rSet) const = 0;
virtual void clearPassword() = 0;
virtual sal_Bool saveDatasource() = 0;
virtual void setTitle(const ::rtl::OUString& _sTitle) = 0;
/** enables or disables the user's possibility to confirm the settings
In a wizard, disabling this will usually disable the "Finish" button.
In a normal tab dialog, this will usually disable the "OK" button.
*/
virtual void enableConfirmSettings( bool _bEnable ) = 0;
};
}
#endif // DBAUI_ITEMSETHELPER_HXX
<commit_msg>INTEGRATION: CWS changefileheader (1.6.96); FILE MERGED 2008/03/31 13:27:43 rt 1.6.96.1: #i87441# Change license header to LPGL v3.<commit_after>/*************************************************************************
*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* Copyright 2008 by Sun Microsystems, Inc.
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: IItemSetHelper.hxx,v $
* $Revision: 1.7 $
*
* This file is part of OpenOffice.org.
*
* OpenOffice.org is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License version 3
* only, as published by the Free Software Foundation.
*
* OpenOffice.org is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License version 3 for more details
* (a copy is included in the LICENSE file that accompanied this code).
*
* You should have received a copy of the GNU Lesser General Public License
* version 3 along with OpenOffice.org. If not, see
* <http://www.openoffice.org/license.html>
* for a copy of the LGPLv3 License.
*
************************************************************************/
#ifndef DBAUI_ITEMSETHELPER_HXX
#define DBAUI_ITEMSETHELPER_HXX
#ifndef _SAL_TYPES_H_
#include <sal/types.h>
#endif
#ifndef _COMPHELPER_UNO3_HXX_
#include <comphelper/uno3.hxx>
#endif
#ifndef _DBAUI_DSNTYPES_HXX_
#include "dsntypes.hxx"
#endif
FORWARD_DECLARE_INTERFACE(beans,XPropertySet)
FORWARD_DECLARE_INTERFACE(sdbc,XConnection)
FORWARD_DECLARE_INTERFACE(sdbc,XDriver)
FORWARD_DECLARE_INTERFACE(lang,XMultiServiceFactory)
class SfxItemSet;
namespace dbaui
{
class SAL_NO_VTABLE IItemSetHelper
{
public:
virtual const SfxItemSet* getOutputSet() const = 0;
virtual SfxItemSet* getWriteOutputSet() = 0;
};
class SAL_NO_VTABLE IDatabaseSettingsDialog
{
public:
virtual ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory > getORB() const = 0;
virtual ::std::pair< ::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XConnection >,sal_Bool> createConnection() = 0;
virtual ::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XDriver > getDriver() = 0;
virtual DATASOURCE_TYPE getDatasourceType(const SfxItemSet& _rSet) const = 0;
virtual void clearPassword() = 0;
virtual sal_Bool saveDatasource() = 0;
virtual void setTitle(const ::rtl::OUString& _sTitle) = 0;
/** enables or disables the user's possibility to confirm the settings
In a wizard, disabling this will usually disable the "Finish" button.
In a normal tab dialog, this will usually disable the "OK" button.
*/
virtual void enableConfirmSettings( bool _bEnable ) = 0;
};
}
#endif // DBAUI_ITEMSETHELPER_HXX
<|endoftext|> |
<commit_before>#include "Sandbox.h"
#include "glad/glad.h"
#include <GLFW/glfw3.h>
#include <fmt/format.h>
#include <stdexcept>
#include <map>
namespace Moonshine
{
auto APPLICATION_NAME = "Moonshine";
static std::map<GLFWwindow*, std::function<void(int, int)>> sWindowSizeCallbackMap;
static std::map<GLFWwindow*, std::function<void(int, int, int)>> sMouseButtonCallbackMap;
static std::map<GLFWwindow*, std::function<void(int, int, int, int)>> sKeyCallbackMap;
void InternalWindowSizeCallback(GLFWwindow* window, int width, int height);
void InternalKeyCallback(GLFWwindow* window, int key, int scancode, int action, int mods);
void InternalMouseButtonCallback(GLFWwindow* window, int button, int action, int mods);
Sandbox::Sandbox() :
Sandbox(Parameters())
{
}
Sandbox::Sandbox(Parameters p) :
_window(nullptr)
{
glfwSetErrorCallback([](auto error, auto description) { fmt::print("Error {0:#x}: {1}\n", error, description); } );
if (!glfwInit())
{
throw std::runtime_error("Failed to initialize GLFW");
}
try
{
if (p.IsDebugModeActive)
{
glfwWindowHint(GLFW_OPENGL_DEBUG_CONTEXT, GL_TRUE);
}
glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 4);
glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 0);
glfwWindowHint(GLFW_OPENGL_FORWARD_COMPAT, GL_TRUE);
glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);
if (p.IsFullScreen)
{
auto monitor = glfwGetPrimaryMonitor();
auto mode = glfwGetVideoMode(monitor);
glfwWindowHint(GLFW_RED_BITS, mode->redBits);
glfwWindowHint(GLFW_GREEN_BITS, mode->greenBits);
glfwWindowHint(GLFW_BLUE_BITS, mode->blueBits);
glfwWindowHint(GLFW_REFRESH_RATE, mode->refreshRate);
_window = glfwCreateWindow(mode->width, mode->height, APPLICATION_NAME, monitor, nullptr);
}
else
{
_window = glfwCreateWindow(p.Width, p.Height, APPLICATION_NAME, nullptr, nullptr);
}
if (_window == nullptr)
{
throw std::runtime_error("Failed to create a window with GLFW");
}
glfwMakeContextCurrent(_window);
glfwSwapInterval(1);
if (!gladLoadGL())
{
throw std::runtime_error("Could not load GL loader.");
}
if (!GLAD_GL_VERSION_4_5)
{
throw std::runtime_error("OpenGL 4.5 or later is required to use the sandbox.");
}
glfwSetWindowSizeCallback(_window, InternalWindowSizeCallback);
glfwSetMouseButtonCallback(_window, InternalMouseButtonCallback);
glfwSetKeyCallback(_window, InternalKeyCallback);
if (p.IsDebugModeActive)
{
auto glDebugCallback = [](GLenum source, GLenum type, GLuint id, GLenum severity, GLsizei length,
const GLchar* message, const GLvoid* userParam)
{
fmt::print("Error {0:#x}: {1}\n", id, message);
};
glDebugMessageCallback(glDebugCallback, nullptr);
glEnable(GL_DEBUG_OUTPUT);
glEnable(GL_DEBUG_OUTPUT_SYNCHRONOUS);
glDebugMessageControl(GL_DONT_CARE, GL_DONT_CARE, GL_DONT_CARE, 0, nullptr, GL_TRUE);
}
}
catch (...)
{
glfwTerminate();
throw;
}
}
void Sandbox::printRendererInformation() const
{
fmt::print("Vendor: {0}\n", glGetString(GL_VENDOR));
fmt::print("Renderer: {0}\n", glGetString(GL_RENDERER));
fmt::print("Version: {0}\n", glGetString(GL_VERSION));
}
Sandbox::~Sandbox()
{
glfwDestroyWindow(_window);
glfwTerminate();
}
void Sandbox::setWindowSizeCallback(std::function<void(int, int)> callback)
{
sWindowSizeCallbackMap[_window] = callback;
}
void Sandbox::setKeyCallback(std::function<void(int, int, int, int)> callback)
{
sKeyCallbackMap[_window] = callback;
}
void Sandbox::setMouseButtonCallback(std::function<void(int, int, int)> callback)
{
sMouseButtonCallbackMap[_window] = callback;
}
void Sandbox::stop() const
{
glfwSetWindowShouldClose(_window, GL_TRUE);
}
void Sandbox::swapBuffers() const
{
glfwSwapBuffers(_window);
}
void Sandbox::poolEvents() const
{
glfwPollEvents();
}
bool Sandbox::isStopping() const
{
return glfwWindowShouldClose(_window);
}
void InternalWindowSizeCallback(GLFWwindow* window, int width, int height)
{
if (auto itr = sWindowSizeCallbackMap.find(window); itr != sWindowSizeCallbackMap.end())
{
itr->second(width, height);
}
};
void InternalKeyCallback(GLFWwindow* window, int key, int scancode, int action, int mods)
{
if (auto itr = sKeyCallbackMap.find(window); itr != sKeyCallbackMap.end())
{
itr->second(key, scancode, action, mods);
}
}
void InternalMouseButtonCallback(GLFWwindow* window, int button, int action, int mods)
{
if (auto itr = sMouseButtonCallbackMap.find(window); itr != sMouseButtonCallbackMap.end())
{
itr->second(button, action, mods);
}
}
}
<commit_msg>Now requesting an OpenGL 4.5 context since that's what we want to use...<commit_after>#include "Sandbox.h"
#include "glad/glad.h"
#include <GLFW/glfw3.h>
#include <fmt/format.h>
#include <stdexcept>
#include <map>
namespace Moonshine
{
auto APPLICATION_NAME = "Moonshine";
static std::map<GLFWwindow*, std::function<void(int, int)>> sWindowSizeCallbackMap;
static std::map<GLFWwindow*, std::function<void(int, int, int)>> sMouseButtonCallbackMap;
static std::map<GLFWwindow*, std::function<void(int, int, int, int)>> sKeyCallbackMap;
void InternalWindowSizeCallback(GLFWwindow* window, int width, int height);
void InternalKeyCallback(GLFWwindow* window, int key, int scancode, int action, int mods);
void InternalMouseButtonCallback(GLFWwindow* window, int button, int action, int mods);
Sandbox::Sandbox() :
Sandbox(Parameters())
{
}
Sandbox::Sandbox(Parameters p) :
_window(nullptr)
{
glfwSetErrorCallback([](auto error, auto description) { fmt::print("Error {0:#x}: {1}\n", error, description); } );
if (!glfwInit())
{
throw std::runtime_error("Failed to initialize GLFW");
}
try
{
if (p.IsDebugModeActive)
{
glfwWindowHint(GLFW_OPENGL_DEBUG_CONTEXT, GL_TRUE);
}
glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 4);
glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 5);
glfwWindowHint(GLFW_OPENGL_FORWARD_COMPAT, GL_TRUE);
glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);
if (p.IsFullScreen)
{
auto monitor = glfwGetPrimaryMonitor();
auto mode = glfwGetVideoMode(monitor);
glfwWindowHint(GLFW_RED_BITS, mode->redBits);
glfwWindowHint(GLFW_GREEN_BITS, mode->greenBits);
glfwWindowHint(GLFW_BLUE_BITS, mode->blueBits);
glfwWindowHint(GLFW_REFRESH_RATE, mode->refreshRate);
_window = glfwCreateWindow(mode->width, mode->height, APPLICATION_NAME, monitor, nullptr);
}
else
{
_window = glfwCreateWindow(p.Width, p.Height, APPLICATION_NAME, nullptr, nullptr);
}
if (_window == nullptr)
{
throw std::runtime_error("Failed to create a window with GLFW");
}
glfwMakeContextCurrent(_window);
glfwSwapInterval(1);
if (!gladLoadGL())
{
throw std::runtime_error("Could not load GL loader.");
}
if (!GLAD_GL_VERSION_4_5)
{
throw std::runtime_error("OpenGL 4.5 or later is required to use the sandbox.");
}
glfwSetWindowSizeCallback(_window, InternalWindowSizeCallback);
glfwSetMouseButtonCallback(_window, InternalMouseButtonCallback);
glfwSetKeyCallback(_window, InternalKeyCallback);
if (p.IsDebugModeActive)
{
auto glDebugCallback = [](GLenum source, GLenum type, GLuint id, GLenum severity, GLsizei length,
const GLchar* message, const GLvoid* userParam)
{
fmt::print("Error {0:#x}: {1}\n", id, message);
};
glDebugMessageCallback(glDebugCallback, nullptr);
glEnable(GL_DEBUG_OUTPUT);
glEnable(GL_DEBUG_OUTPUT_SYNCHRONOUS);
glDebugMessageControl(GL_DONT_CARE, GL_DONT_CARE, GL_DONT_CARE, 0, nullptr, GL_TRUE);
}
}
catch (...)
{
glfwTerminate();
throw;
}
}
void Sandbox::printRendererInformation() const
{
fmt::print("Vendor: {0}\n", glGetString(GL_VENDOR));
fmt::print("Renderer: {0}\n", glGetString(GL_RENDERER));
fmt::print("Version: {0}\n", glGetString(GL_VERSION));
}
Sandbox::~Sandbox()
{
glfwDestroyWindow(_window);
glfwTerminate();
}
void Sandbox::setWindowSizeCallback(std::function<void(int, int)> callback)
{
sWindowSizeCallbackMap[_window] = callback;
}
void Sandbox::setKeyCallback(std::function<void(int, int, int, int)> callback)
{
sKeyCallbackMap[_window] = callback;
}
void Sandbox::setMouseButtonCallback(std::function<void(int, int, int)> callback)
{
sMouseButtonCallbackMap[_window] = callback;
}
void Sandbox::stop() const
{
glfwSetWindowShouldClose(_window, GL_TRUE);
}
void Sandbox::swapBuffers() const
{
glfwSwapBuffers(_window);
}
void Sandbox::poolEvents() const
{
glfwPollEvents();
}
bool Sandbox::isStopping() const
{
return glfwWindowShouldClose(_window);
}
void InternalWindowSizeCallback(GLFWwindow* window, int width, int height)
{
if (auto itr = sWindowSizeCallbackMap.find(window); itr != sWindowSizeCallbackMap.end())
{
itr->second(width, height);
}
};
void InternalKeyCallback(GLFWwindow* window, int key, int scancode, int action, int mods)
{
if (auto itr = sKeyCallbackMap.find(window); itr != sKeyCallbackMap.end())
{
itr->second(key, scancode, action, mods);
}
}
void InternalMouseButtonCallback(GLFWwindow* window, int button, int action, int mods)
{
if (auto itr = sMouseButtonCallbackMap.find(window); itr != sMouseButtonCallbackMap.end())
{
itr->second(button, action, mods);
}
}
}
<|endoftext|> |
<commit_before>// This file should document by example usage of the GEOS library.
// It could actually be a live discuss-by-example board for
// architectural design choices.
// --strk;
//
// DEBUGGING TIPS:
// use -D__USE_MALLOC at compile time for gcc 2.91, 2.95, 3.0 and 3.1
// and GLIBCXX_FORCE_NEW or GLIBCPP_FORCE_NEW at run time with gcc 3.2.2+
// to force libstdc++ avoid caching memory. This should remove some
// obscure reports from memory checkers like valgrind.
//
#include <stdio.h>
#include <io.h>
#include <geom.h>
#include <unload.h>
using namespace geos;
// This object will be used to construct our geometries.
// It might be bypassed by directly call geometry constructors,
// but that would be boring because you'd need to specify
// a PrecisionModel and a SRID everytime: those infos are
// cached inside a GeometryFactory object.
GeometryFactory *global_factory;
// This function will print given geometries in WKT
// format to stdout.
void
wkt_print_geoms(int numgeoms, Geometry **geoms)
{
// WKT-print created geometries
WKTWriter *wkt = new WKTWriter();
for (int i=0; i<numgeoms; i++) {
cout<<wkt->write(geoms[i])<<endl;
}
delete wkt;
}
// This function will create a LinearRing
// geometry rapresenting a square with the given origin
// and side
LinearRing *
create_square_linearring(double xoffset, double yoffset, double side)
{
// We will use a coordinate list to build the linearring
CoordinateList *cl = new BasicCoordinateList(5);
// Each coordinate in the list must be created,
// passed to coordinate list setAt and then deleted.
// Pretty boring uh ?
Coordinate *c;
c = new Coordinate(xoffset, yoffset);
cl->setAt(*c ,0);
delete c;
c = new Coordinate(xoffset+side, yoffset);
cl->setAt(*c ,1);
delete c;
c = new Coordinate(xoffset+side, yoffset+side);
cl->setAt(*c ,2);
delete c;
c = new Coordinate(xoffset, yoffset+side);
cl->setAt(*c ,3);
delete c;
c = new Coordinate(xoffset, yoffset);
cl->setAt(*c ,4);
delete c;
// Now that we have a CoordinateList we can create
// the linearring.
LinearRing *lr = (LinearRing*) global_factory->createLinearRing(cl);
// We don't need our CoordinateList anymore, it has been
// copied inside the LinearRing object
delete cl;
return lr; // our LinearRing
}
// This function will create a Polygon
// geometry rapresenting a square with the given origin
// and side and with a central hole 1/3 sided.
Polygon *
create_square_polygon(double xoffset, double yoffset, double side)
{
// We need a LinearRing for the polygon shell
LinearRing *outer = create_square_linearring(xoffset,yoffset,side);
// And another for the hole
LinearRing *inner = create_square_linearring(xoffset+(side/3),
yoffset+(side/3),(side/3));
// If we need to specify any hole, we do it using
// a vector of Geometry pointers (I don't know why
// not LinearRings)
vector<Geometry *> *holes = new vector<Geometry *>;
// We add the newly created geometry to the vector
// of holes.
holes->push_back(inner);
// And finally we call the polygon constructor.
// Both the outer LinearRing and the vector of holes
// will be referenced by the resulting Polygon object,
// thus we CANNOT delete them, neither the holes, nor
// the vector containing their pointers, nor the outer
// LinearRing. Everything will be deleted at Polygon
// deletion time (this is inconsistent with LinearRing
// behaviour... what should we do?).
Polygon *poly = global_factory->createPolygon(outer, holes);
return poly;
}
// This function will create a GeoemtryCollection
// containing the two given Geometries.
// Note that given Geometries will be referenced
// by returned object, thus deleted at its destruction
// time.
//
GeometryCollection *
create_simple_collection(Geometry *g1, Geometry *g2)
{
// We need to construct a <Geometry *> vector
// to use as argument to the factory function
vector<Geometry *> *collection = new vector<Geometry *>;
// Now, we need to make copies of the given args
// we do it using copy constructor.
collection->push_back(g1);
collection->push_back(g2);
GeometryCollection *ret =
global_factory->createGeometryCollection(collection);
// We HAVE to delete the vectore used to store
// goemetry pointers, but created object will
// delete pointed geometries, weird uh?
delete collection;
return ret;
}
// Start reading here
void do_all()
{
int numgeoms = 3;
Geometry *geoms[numgeoms];
// Initialize global factory with default PrecisionModel
// and SRID.
global_factory = new GeometryFactory();
/////////////////////////////////////////////
// BASIC GEOMETRY CREATION
/////////////////////////////////////////////
// Read function bodies to see the magic behind them
geoms[0] = create_square_linearring(0,0,100);
geoms[1] = create_square_polygon(0,200,300);
// here we write this bad-looking code to copy
// geometries before putting them in a collection
// object, since it will take responsability about
// passed arguments life.
geoms[2] = create_simple_collection(
new LinearRing(*((LinearRing *)geoms[0])),
new Polygon(*((Polygon *)geoms[1])));
// Print all geoms.
wkt_print_geoms(numgeoms, geoms);
/////////////////////////////////////////////
// CONVEX HULL
/////////////////////////////////////////////
// Make convex hulls of geometries
Geometry *hulls[numgeoms];
for (int i=0; i<numgeoms; i++) {
hulls[i] = geoms[i]->convexHull();
}
// Print all convex hulls
wkt_print_geoms(numgeoms, geoms);
// Delete created geometries and hulls
for (int i=0; i<numgeoms; i++) {
delete geoms[i];
delete hulls[i];
}
delete global_factory;
}
main()
{
try
{
do_all();
}
// All exception thrown by GEOS are subclasses of this
// one, so this is a catch-all
catch (GEOSException *exc)
{
cerr <<"Generic exception: "<<exc->toString()<<"\n";
exit(1);
}
// and this is a catch-all non standard ;)
catch (...)
{
cerr <<"unknown exception trown!\n";
exit(1);
}
// This is not really needed but to make
// memory checker like valgrind quiet
// about static heap-allocated data.
Unload::Release();
}
<commit_msg>added convexHull and PrecisionModel<commit_after>// $Log$
// Revision 1.3 2003/10/09 11:19:20 strk
// added convexHull and PrecisionModel
//
//
// This file should document by example usage of the GEOS library.
// It could actually be a live discuss-by-example board for
// architectural design choices.
// --strk;
//
// DEBUGGING TIPS:
// use -D__USE_MALLOC at compile time for gcc 2.91, 2.95, 3.0 and 3.1
// and GLIBCXX_FORCE_NEW or GLIBCPP_FORCE_NEW at run time with gcc 3.2.2+
// to force libstdc++ avoid caching memory. This should remove some
// obscure reports from memory checkers like valgrind.
//
#include <stdio.h>
#include <io.h>
#include <geom.h>
#include <unload.h>
using namespace geos;
// This object will be used to construct our geometries.
// It might be bypassed by directly call geometry constructors,
// but that would be boring because you'd need to specify
// a PrecisionModel and a SRID everytime: those infos are
// cached inside a GeometryFactory object.
GeometryFactory *global_factory;
// This function will print given geometries in WKT
// format to stdout.
void
wkt_print_geoms(int numgeoms, Geometry **geoms)
{
// WKT-print created geometries
WKTWriter *wkt = new WKTWriter();
for (int i=0; i<numgeoms; i++) {
cout<<wkt->write(geoms[i])<<endl;
}
delete wkt;
}
// This function will create a LinearRing
// geometry rapresenting a square with the given origin
// and side
LinearRing *
create_square_linearring(double xoffset, double yoffset, double side)
{
// We will use a coordinate list to build the linearring
CoordinateList *cl = new BasicCoordinateList(5);
// Each coordinate in the list must be created,
// passed to coordinate list setAt and then deleted.
// Pretty boring uh ?
Coordinate *c;
c = new Coordinate(xoffset, yoffset);
cl->setAt(*c ,0);
delete c;
c = new Coordinate(xoffset+side, yoffset);
cl->setAt(*c ,1);
delete c;
c = new Coordinate(xoffset+side, yoffset+side);
cl->setAt(*c ,2);
delete c;
c = new Coordinate(xoffset, yoffset+side);
cl->setAt(*c ,3);
delete c;
c = new Coordinate(xoffset, yoffset);
cl->setAt(*c ,4);
delete c;
// Now that we have a CoordinateList we can create
// the linearring.
LinearRing *lr = (LinearRing*) global_factory->createLinearRing(cl);
// We don't need our CoordinateList anymore, it has been
// copied inside the LinearRing object
delete cl;
return lr; // our LinearRing
}
// This function will create a Polygon
// geometry rapresenting a square with the given origin
// and side and with a central hole 1/3 sided.
Polygon *
create_square_polygon(double xoffset, double yoffset, double side)
{
// We need a LinearRing for the polygon shell
LinearRing *outer = create_square_linearring(xoffset,yoffset,side);
// And another for the hole
LinearRing *inner = create_square_linearring(xoffset+(side/3),
yoffset+(side/3),(side/3));
// If we need to specify any hole, we do it using
// a vector of Geometry pointers (I don't know why
// not LinearRings)
vector<Geometry *> *holes = new vector<Geometry *>;
// We add the newly created geometry to the vector
// of holes.
holes->push_back(inner);
// And finally we call the polygon constructor.
// Both the outer LinearRing and the vector of holes
// will be referenced by the resulting Polygon object,
// thus we CANNOT delete them, neither the holes, nor
// the vector containing their pointers, nor the outer
// LinearRing. Everything will be deleted at Polygon
// deletion time (this is inconsistent with LinearRing
// behaviour... what should we do?).
Polygon *poly = global_factory->createPolygon(outer, holes);
return poly;
}
// This function will create a GeoemtryCollection
// containing the two given Geometries.
// Note that given Geometries will be referenced
// by returned object, thus deleted at its destruction
// time.
//
GeometryCollection *
create_simple_collection(Geometry *g1, Geometry *g2)
{
// We need to construct a <Geometry *> vector
// to use as argument to the factory function
vector<Geometry *> *collection = new vector<Geometry *>;
// Now, we need to make copies of the given args
// we do it using copy constructor.
collection->push_back(g1);
collection->push_back(g2);
GeometryCollection *ret =
global_factory->createGeometryCollection(collection);
// We HAVE to delete the vectore used to store
// goemetry pointers, but created object will
// delete pointed geometries, weird uh?
delete collection;
return ret;
}
// Start reading here
void do_all()
{
int numgeoms = 3;
Geometry *geoms[numgeoms];
// Define a precision model using 0,0 as the reference origin
// and 2.0 as coordinates scale.
// Using 1.0 as scale will segfault, dunno why --strk;
PrecisionModel *pm = new PrecisionModel(2.0, 0, 0);
// Initialize global factory with defined PrecisionModel
// and a SRID of -1 (undefined).
global_factory = new GeometryFactory(pm, -1);
// We do not need PrecisionMode object anymore, it has
// been copied to global_factory private storage
delete pm;
/////////////////////////////////////////////
// BASIC GEOMETRY CREATION
/////////////////////////////////////////////
// Read function bodies to see the magic behind them
geoms[0] = create_square_linearring(0,0,100);
geoms[1] = create_square_polygon(0,200,300);
// here we write this bad-looking code to copy
// geometries before putting them in a collection
// object, since it will take responsability about
// passed arguments life.
geoms[2] = create_simple_collection(
new LinearRing(*((LinearRing *)geoms[0])),
new Polygon(*((Polygon *)geoms[1])));
// Print all geoms.
cout<<"--------HERE ARE THE BASE GEOMS ----------"<<endl;
wkt_print_geoms(numgeoms, geoms);
/////////////////////////////////////////////
// CONVEX HULL
/////////////////////////////////////////////
// Make convex hulls of geometries
Geometry *hulls[numgeoms];
for (int i=0; i<numgeoms; i++) {
hulls[i] = geoms[i]->convexHull();
}
// Print all convex hulls
cout<<"--------HERE COMES THE HULLS----------"<<endl;
wkt_print_geoms(numgeoms, hulls);
// Delete created geometries and hulls
for (int i=0; i<numgeoms; i++) {
delete geoms[i];
delete hulls[i];
}
delete global_factory;
}
main()
{
try
{
do_all();
}
// All exception thrown by GEOS are subclasses of this
// one, so this is a catch-all
catch (GEOSException *exc)
{
cerr <<"Generic exception: "<<exc->toString()<<"\n";
exit(1);
}
// and this is a catch-all non standard ;)
catch (...)
{
cerr <<"unknown exception trown!\n";
exit(1);
}
// This is not really needed but to make
// memory checker like valgrind quiet
// about static heap-allocated data.
Unload::Release();
}
<|endoftext|> |
<commit_before>/**
* \file
* \brief FifoQueueBase class header
*
* \author Copyright (C) 2014-2015 Kamil Szczygiel http://www.distortec.com http://www.freddiechopin.info
*
* \par License
* This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0. If a copy of the MPL was not
* distributed with this file, You can obtain one at http://mozilla.org/MPL/2.0/.
*
* \date 2015-01-19
*/
#ifndef INCLUDE_DISTORTOS_SYNCHRONIZATION_FIFOQUEUEBASE_HPP_
#define INCLUDE_DISTORTOS_SYNCHRONIZATION_FIFOQUEUEBASE_HPP_
#include "distortos/Semaphore.hpp"
#include "distortos/synchronization/SemaphoreFunctor.hpp"
namespace distortos
{
namespace synchronization
{
/// FifoQueueBase class implements basic functionality of FifoQueue template class
class FifoQueueBase
{
public:
/**
* \brief Functor is a type-erased interface for functors which execute some action on queue's storage (like
* copy-constructing, swapping, destroying, emplacing, ...).
*
* The functor will be called by FifoQueueBase internals with one argument - \a storage - which is a reference to
* pointer to queue's storage - after executing functor's action, the pointer should be incremented to next position
* (using the actual size of element)
*/
using Functor = estd::TypeErasedFunctor<void(void*&)>;
/**
* \brief FifoQueueBase's constructor
*
* \param [in] storageBegin is the beginning of storage for queue elements
* \param [in] storageEnd is the pointer to past-the-last element of storage for queue elements
* \param [in] elementSize is the size of single queue element, bytes
* \param [in] maxElements is the number of elements in storage
*/
FifoQueueBase(void* storageBegin, const void* storageEnd, size_t elementSize, size_t maxElements);
/**
* \brief Implementation of pop() using type-erased functor
*
* \param [in] waitSemaphoreFunctor is a reference to SemaphoreFunctor which will be executed with \a popSemaphore_
* \param [in] functor is a reference to Functor which will execute actions related to popping - it will get a
* reference to readPosition_ as argument
*
* \return zero if element was popped successfully, error code otherwise:
* - error codes returned by \a waitSemaphoreFunctor's operator() call;
* - error codes returned by Semaphore::post();
*/
int pop(const SemaphoreFunctor& waitSemaphoreFunctor, const Functor& functor)
{
return popPush(waitSemaphoreFunctor, functor, popSemaphore_, pushSemaphore_, readPosition_);
}
/**
* \brief Implementation of push() using type-erased functor
*
* \param [in] waitSemaphoreFunctor is a reference to SemaphoreFunctor which will be executed with \a pushSemaphore_
* \param [in] functor is a reference to Functor which will execute actions related to pushing - it will get a
* reference to writePosition_ as argument
*
* \return zero if element was pushed successfully, error code otherwise:
* - error codes returned by \a waitSemaphoreFunctor's operator() call;
* - error codes returned by Semaphore::post();
*/
int push(const SemaphoreFunctor& waitSemaphoreFunctor, const Functor& functor)
{
return popPush(waitSemaphoreFunctor, functor, pushSemaphore_, popSemaphore_, writePosition_);
}
private:
/**
* \brief Implementation of pop() and push() using type-erased functor
*
* \param [in] waitSemaphoreFunctor is a reference to SemaphoreFunctor which will be executed with \a waitSemaphore
* \param [in] functor is a reference to Functor which will execute actions related to popping/pushing - it will get
* a reference to \a storage as argument
* \param [in] waitSemaphore is a reference to semaphore that will be waited for, \a popSemaphore_ for pop(), \a
* pushSemaphore_ for push()
* \param [in] postSemaphore is a reference to semaphore that will be posted after the operation, \a pushSemaphore_
* for pop(), \a popSemaphore_ for push()
* \param [in] storage is a reference to appropriate pointer to storage, which will be passed to \a functor, \a
* readPosition_ for pop(), \a writePosition_ for push()
*
* \return zero if operation was successful, error code otherwise:
* - error codes returned by \a waitSemaphoreFunctor's operator() call;
* - error codes returned by Semaphore::post();
*/
int popPush(const SemaphoreFunctor& waitSemaphoreFunctor, const Functor& functor, Semaphore& waitSemaphore,
Semaphore& postSemaphore, void*& storage);
/// semaphore guarding access to "pop" functions - its value is equal to the number of available elements
Semaphore popSemaphore_;
/// semaphore guarding access to "push" functions - its value is equal to the number of free slots
Semaphore pushSemaphore_;
/// beginning of storage for queue elements
void* const storageBegin_;
/// pointer to past-the-last element of storage for queue elements
const void* const storageEnd_;
/// pointer to first element available for reading
void* readPosition_;
/// pointer to first free slot available for writing
void* writePosition_;
/// size of single queue element, bytes
const size_t elementSize_;
};
} // namespace synchronization
} // namespace distortos
#endif // INCLUDE_DISTORTOS_SYNCHRONIZATION_FIFOQUEUEBASE_HPP_
<commit_msg>FifoQueueBase: add FifoQueueBase::getElementSize() accessor<commit_after>/**
* \file
* \brief FifoQueueBase class header
*
* \author Copyright (C) 2014-2015 Kamil Szczygiel http://www.distortec.com http://www.freddiechopin.info
*
* \par License
* This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0. If a copy of the MPL was not
* distributed with this file, You can obtain one at http://mozilla.org/MPL/2.0/.
*
* \date 2015-01-19
*/
#ifndef INCLUDE_DISTORTOS_SYNCHRONIZATION_FIFOQUEUEBASE_HPP_
#define INCLUDE_DISTORTOS_SYNCHRONIZATION_FIFOQUEUEBASE_HPP_
#include "distortos/Semaphore.hpp"
#include "distortos/synchronization/SemaphoreFunctor.hpp"
namespace distortos
{
namespace synchronization
{
/// FifoQueueBase class implements basic functionality of FifoQueue template class
class FifoQueueBase
{
public:
/**
* \brief Functor is a type-erased interface for functors which execute some action on queue's storage (like
* copy-constructing, swapping, destroying, emplacing, ...).
*
* The functor will be called by FifoQueueBase internals with one argument - \a storage - which is a reference to
* pointer to queue's storage - after executing functor's action, the pointer should be incremented to next position
* (using the actual size of element)
*/
using Functor = estd::TypeErasedFunctor<void(void*&)>;
/**
* \brief FifoQueueBase's constructor
*
* \param [in] storageBegin is the beginning of storage for queue elements
* \param [in] storageEnd is the pointer to past-the-last element of storage for queue elements
* \param [in] elementSize is the size of single queue element, bytes
* \param [in] maxElements is the number of elements in storage
*/
FifoQueueBase(void* storageBegin, const void* storageEnd, size_t elementSize, size_t maxElements);
/**
* \return size of single queue element, bytes
*/
size_t getElementSize() const
{
return elementSize_;
}
/**
* \brief Implementation of pop() using type-erased functor
*
* \param [in] waitSemaphoreFunctor is a reference to SemaphoreFunctor which will be executed with \a popSemaphore_
* \param [in] functor is a reference to Functor which will execute actions related to popping - it will get a
* reference to readPosition_ as argument
*
* \return zero if element was popped successfully, error code otherwise:
* - error codes returned by \a waitSemaphoreFunctor's operator() call;
* - error codes returned by Semaphore::post();
*/
int pop(const SemaphoreFunctor& waitSemaphoreFunctor, const Functor& functor)
{
return popPush(waitSemaphoreFunctor, functor, popSemaphore_, pushSemaphore_, readPosition_);
}
/**
* \brief Implementation of push() using type-erased functor
*
* \param [in] waitSemaphoreFunctor is a reference to SemaphoreFunctor which will be executed with \a pushSemaphore_
* \param [in] functor is a reference to Functor which will execute actions related to pushing - it will get a
* reference to writePosition_ as argument
*
* \return zero if element was pushed successfully, error code otherwise:
* - error codes returned by \a waitSemaphoreFunctor's operator() call;
* - error codes returned by Semaphore::post();
*/
int push(const SemaphoreFunctor& waitSemaphoreFunctor, const Functor& functor)
{
return popPush(waitSemaphoreFunctor, functor, pushSemaphore_, popSemaphore_, writePosition_);
}
private:
/**
* \brief Implementation of pop() and push() using type-erased functor
*
* \param [in] waitSemaphoreFunctor is a reference to SemaphoreFunctor which will be executed with \a waitSemaphore
* \param [in] functor is a reference to Functor which will execute actions related to popping/pushing - it will get
* a reference to \a storage as argument
* \param [in] waitSemaphore is a reference to semaphore that will be waited for, \a popSemaphore_ for pop(), \a
* pushSemaphore_ for push()
* \param [in] postSemaphore is a reference to semaphore that will be posted after the operation, \a pushSemaphore_
* for pop(), \a popSemaphore_ for push()
* \param [in] storage is a reference to appropriate pointer to storage, which will be passed to \a functor, \a
* readPosition_ for pop(), \a writePosition_ for push()
*
* \return zero if operation was successful, error code otherwise:
* - error codes returned by \a waitSemaphoreFunctor's operator() call;
* - error codes returned by Semaphore::post();
*/
int popPush(const SemaphoreFunctor& waitSemaphoreFunctor, const Functor& functor, Semaphore& waitSemaphore,
Semaphore& postSemaphore, void*& storage);
/// semaphore guarding access to "pop" functions - its value is equal to the number of available elements
Semaphore popSemaphore_;
/// semaphore guarding access to "push" functions - its value is equal to the number of free slots
Semaphore pushSemaphore_;
/// beginning of storage for queue elements
void* const storageBegin_;
/// pointer to past-the-last element of storage for queue elements
const void* const storageEnd_;
/// pointer to first element available for reading
void* readPosition_;
/// pointer to first free slot available for writing
void* writePosition_;
/// size of single queue element, bytes
const size_t elementSize_;
};
} // namespace synchronization
} // namespace distortos
#endif // INCLUDE_DISTORTOS_SYNCHRONIZATION_FIFOQUEUEBASE_HPP_
<|endoftext|> |
<commit_before>/*
* Copyright 2014-2020 Real Logic Limited.
*
* 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
*
* https://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 <iostream>
#include <thread>
using namespace std;
int main(int argc, char** argv)
{
cout << "system_clock resolution ";
cout << chrono::system_clock::period::num << "/";
cout << chrono::system_clock::period::den << "\n";
cout << "steady_clock resolution ";
cout << chrono::steady_clock::period::num << "/";
cout << chrono::steady_clock::period::den << "\n";
cout << "high_resolution_clock resolution ";
cout << chrono::high_resolution_clock::period::num << "/";
cout << chrono::high_resolution_clock::period::den << "\n";
auto start = chrono::steady_clock::now();
this_thread::sleep_for(chrono::nanoseconds(1));
auto end = chrono::steady_clock::now();
auto diff = end - start;
cout << "sleep_for min duration: ";
cout << std::chrono::duration<long, std::nano>(diff).count() << " ns\n";
start = chrono::steady_clock::now();
this_thread::yield();
end = chrono::steady_clock::now();
diff = end - start;
cout << "sample yield duration: ";
cout << std::chrono::duration<long, std::nano>(diff).count() << " ns\n";
start = chrono::steady_clock::now();
chrono::high_resolution_clock::now();
end = chrono::steady_clock::now();
diff = end - start;
cout << "high_resolution_clock::now duration: ";
cout << std::chrono::duration<long, std::nano>(diff).count() << " ns\n";
start = chrono::steady_clock::now();
chrono::steady_clock::now();
end = chrono::steady_clock::now();
diff = end - start;
cout << "steady_clock::now duration: ";
cout << std::chrono::duration<long, std::nano>(diff).count() << " ns\n";
start = chrono::steady_clock::now();
chrono::system_clock::now();
end = chrono::steady_clock::now();
diff = end - start;
cout << "system_clock::now duration: ";
cout << std::chrono::duration<long, std::nano>(diff).count() << " ns\n";
start = chrono::steady_clock::now();
end = chrono::steady_clock::now();
diff = end - start;
cout << "no op duration: ";
cout << std::chrono::duration<long, std::nano>(diff).count() << " ns\n";
start = chrono::steady_clock::now();
chrono::steady_clock::time_point now = chrono::steady_clock::now();
long count = chrono::duration<long, std::nano>(now.time_since_epoch()).count();
end = chrono::steady_clock::now();
diff = end - start;
cout << "nano_clock duration: ";
cout << std::chrono::duration<long, std::nano>(diff).count() << " ns\n";
cout << "nano_clock sample: " << count << "\n";
cout << "duration ratio: " << chrono::duration<double, std::ratio<1,1>>(diff).count() << "\n";
return 0;
}
<commit_msg>[C++] Fix nodiscard warning in TimeTests.<commit_after>/*
* Copyright 2014-2020 Real Logic Limited.
*
* 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
*
* https://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 <iostream>
#include <thread>
using namespace std;
int main(int argc, char** argv)
{
cout << "system_clock resolution ";
cout << chrono::system_clock::period::num << "/";
cout << chrono::system_clock::period::den << "\n";
cout << "steady_clock resolution ";
cout << chrono::steady_clock::period::num << "/";
cout << chrono::steady_clock::period::den << "\n";
cout << "high_resolution_clock resolution ";
cout << chrono::high_resolution_clock::period::num << "/";
cout << chrono::high_resolution_clock::period::den << "\n";
auto start = chrono::steady_clock::now();
this_thread::sleep_for(chrono::nanoseconds(1));
auto end = chrono::steady_clock::now();
auto diff = end - start;
cout << "sleep_for min duration: ";
cout << std::chrono::duration<long, std::nano>(diff).count() << " ns\n";
start = chrono::steady_clock::now();
this_thread::yield();
end = chrono::steady_clock::now();
diff = end - start;
cout << "sample yield duration: ";
cout << std::chrono::duration<long, std::nano>(diff).count() << " ns\n";
start = chrono::steady_clock::now();
static_cast<void>(chrono::high_resolution_clock::now());
end = chrono::steady_clock::now();
diff = end - start;
cout << "high_resolution_clock::now duration: ";
cout << std::chrono::duration<long, std::nano>(diff).count() << " ns\n";
start = chrono::steady_clock::now();
static_cast<void>(chrono::steady_clock::now());
end = chrono::steady_clock::now();
diff = end - start;
cout << "steady_clock::now duration: ";
cout << std::chrono::duration<long, std::nano>(diff).count() << " ns\n";
start = chrono::steady_clock::now();
static_cast<void>(chrono::system_clock::now());
end = chrono::steady_clock::now();
diff = end - start;
cout << "system_clock::now duration: ";
cout << std::chrono::duration<long, std::nano>(diff).count() << " ns\n";
start = chrono::steady_clock::now();
end = chrono::steady_clock::now();
diff = end - start;
cout << "no op duration: ";
cout << std::chrono::duration<long, std::nano>(diff).count() << " ns\n";
start = chrono::steady_clock::now();
chrono::steady_clock::time_point now = chrono::steady_clock::now();
long count = chrono::duration<long, std::nano>(now.time_since_epoch()).count();
end = chrono::steady_clock::now();
diff = end - start;
cout << "nano_clock duration: ";
cout << std::chrono::duration<long, std::nano>(diff).count() << " ns\n";
cout << "nano_clock sample: " << count << "\n";
cout << "duration ratio: " << chrono::duration<double, std::ratio<1,1>>(diff).count() << "\n";
return 0;
}
<|endoftext|> |
<commit_before><commit_msg>Add a syslog print to systrace due to backtrace sometimes missing the message<commit_after><|endoftext|> |
<commit_before>#include <iostream>
#include <sstream>
#include <string>
#include <unistd.h> // For option parsing.
#include <thread>
#include "data.h"
#include "stats.h"
#include "algo_recuit.h"
#define STEPS_RECUIT 100
template<typename T>
std::string to_string(const T& x) {
std::ostringstream oss;
oss << x;
return oss.str();
}
using std::cout;
using std::cerr;
using std::endl;
using std::string;
using std::thread;
// Calcul et affiche quelques statistiques sur toute les données.
void general_stats() {
}
void start_thread(ProblemData data, bool verbose_p);
int main(int argc, char *argv[])
{
// "Globals"
string filename;
bool verbose_p = false;
// Le nombre d'etape pour le recuit
int steps = 100;
// Parse command-line options
int opt;
while((opt = getopt(argc, argv, "pf:s:")) != -1) {
switch(opt) {
case 'p':
verbose_p = true;
break;
case 'f':
filename = optarg;
break;
case 's':
steps = std::stoi(optarg);
break;
//case '?':
//cerr << "Unrecognized option"
}
}
if( filename != "" )
{
ProblemData data = make_problem_data(filename);
int nb_thread = 4;
std::vector<std::thread> threads;
// TODO For each thread
for(int i = 0; i < nb_thread; ++i)
{
threads.push_back(thread( [data,verbose_p]()
{
AlgoRecuit algo(data, STEPS_RECUIT);
// Timeout pour reset la temperature quand ca fait longtemps qu'on a pas trouver de meilleur solution.
int timeout_temp = 0;
int timeout_temp_thresh = 20;
// Timeout quand ca fait plein de fois qu'on reset la temperature, on shuffle les employe de place.
int timeout_restart = 0;
int timeout_restart_thresh = 20;
algo.init_solution(true);
algo.print_solution(algo.best_sol, verbose_p);
while(true){
algo.run_one_loop();
// si on a trouver une meilleur solution
if(algo.new_solution) {
timeout_temp = 0;
algo.print_solution(algo.best_sol, verbose_p);
algo.new_solution = false;
}
else
{
timeout_temp++;
if(timeout_temp == timeout_temp_thresh)
{
timeout_restart++;
//cout << algo.temperature << endl;
algo.temperature = 20;
timeout_temp = 0;
if(timeout_restart == timeout_restart_thresh) {
cout << "Thread "<< std::this_thread::get_id() << " Restarting" << endl;
// Reinitialize l'algo.
algo.init_solution(false);
algo.print_solution(algo.best_sol, verbose_p);
timeout_restart = 0;
}
}
}
}
}));
std::for_each(threads.begin(), threads.end(), [](std::thread &t)
{
t.join();
});
}
}
else
{
cout << "File not found, enter valid filename" << endl;
}
// general_stats();
// Eval data
// Print solutions
// Loop!
return 0;
}
void start_thread(ProblemData data, bool verbose_p )
{
AlgoRecuit algo(data, STEPS_RECUIT);
// Timeout pour reset la temperature quand ca fait longtemps qu'on a pas trouver de meilleur solution.
int timeout_temp = 0;
int timeout_temp_thresh = 20;
// Timeout quand ca fait plein de fois qu'on reset la temperature, on shuffle les employe de place.
int timeout_restart = 0;
int timeout_restart_thresh = 20;
algo.init_solution(true);
algo.print_solution(algo.best_sol, verbose_p);
while(true){
algo.run_one_loop();
// si on a trouver une meilleur solution
if(algo.new_solution) {
timeout_temp = 0;
algo.print_solution(algo.best_sol, verbose_p);
algo.new_solution = false;
}
else
{
timeout_temp++;
if(timeout_temp == timeout_temp_thresh)
{
timeout_restart++;
cout << algo.temperature << endl;
algo.temperature = 20;
timeout_temp = 0;
if(timeout_restart == timeout_restart_thresh) {
cout << "Restarting" << endl;
// Reinitialize l'algo.
algo.init_solution(false);
algo.print_solution(algo.best_sol, verbose_p);
timeout_restart = 0;
}
}
}
}
}
<commit_msg>Random employee assignment + thread create<commit_after>#include <iostream>
#include <sstream>
#include <string>
#include <unistd.h> // For option parsing.
#include <thread>
#include "data.h"
#include "stats.h"
#include "algo_recuit.h"
#define STEPS_RECUIT 100
template<typename T>
std::string to_string(const T& x) {
std::ostringstream oss;
oss << x;
return oss.str();
}
using std::cout;
using std::cerr;
using std::endl;
using std::string;
using std::thread;
// Calcul et affiche quelques statistiques sur toute les données.
void general_stats() {
}
void start_thread(ProblemData data, bool verbose_p);
int main(int argc, char *argv[])
{
// "Globals"
string filename;
bool verbose_p = false;
// Le nombre d'etape pour le recuit
int steps = 100;
// Parse command-line options
int opt;
while((opt = getopt(argc, argv, "pf:s:")) != -1) {
switch(opt) {
case 'p':
verbose_p = true;
break;
case 'f':
filename = optarg;
break;
case 's':
steps = std::stoi(optarg);
break;
//case '?':
//cerr << "Unrecognized option"
}
}
if( filename != "" )
{
ProblemData data = make_problem_data(filename);
int nb_thread = 4;
std::vector<std::thread> threads;
// TODO For each thread
for(int i = 0; i < nb_thread; ++i)
{
threads.push_back(thread( [data,verbose_p]()
{
AlgoRecuit algo(data, STEPS_RECUIT);
// Timeout pour reset la temperature quand ca fait longtemps qu'on a pas trouver de meilleur solution.
int timeout_temp = 0;
int timeout_temp_thresh = 20;
// Timeout quand ca fait plein de fois qu'on reset la temperature, on shuffle les employe de place.
int timeout_restart = 0;
int timeout_restart_thresh = 20;
algo.init_solution(true);
algo.print_solution(algo.best_sol, verbose_p);
while(true){
algo.run_one_loop();
// si on a trouver une meilleur solution
if(algo.new_solution) {
timeout_temp = 0;
algo.print_solution(algo.best_sol, verbose_p);
algo.new_solution = false;
}
else
{
timeout_temp++;
if(timeout_temp == timeout_temp_thresh)
{
timeout_restart++;
//cout << algo.temperature << endl;
algo.temperature = 20;
timeout_temp = 0;
if(timeout_restart == timeout_restart_thresh) {
cout << "Thread "<< std::this_thread::get_id() << " Restarting" << endl;
// Reinitialize l'algo.
algo.init_solution(false);
algo.print_solution(algo.best_sol, verbose_p);
timeout_restart = 0;
}
}
}
}
}));
std::for_each(threads.begin(), threads.end(), [](std::thread &t)
{
t.join();
});
}
}
else
{
cout << "File not found, enter valid filename" << endl;
}
// general_stats();
// Eval data
// Print solutions
// Loop!
return 0;
}<|endoftext|> |
<commit_before>// Boggle.cpp
// Given a Boggle board and a dictionary of words, find all possible words on the board
//
#include <iostream>
#include <set>
#include <vector>
#include "Trie.h"
typedef std::vector<std::vector<char>> BBoard;
typedef std::vector<std::vector<bool>> Visited;
size_t counter = 0;
std::set<std::string> find( const BBoard& board,
Visited& visited,
const int rpos,
const int cpos,
Node* n,
std::string s = std::string())
{
const int maxRows = board.size(),
maxCols = board[0].size();
std::set<std::string> foundStrings;
visited[rpos][cpos] = true;
// Is this board cell in the dict?
const char c = board[rpos][cpos];
if (n->val == c)
{
std::cout << "found " << s << "+" << c << std::endl;
s += c;
if (n->marker) foundStrings.insert(s);
}
// Search neighbouring board cells
for (int r = rpos-1; r <= rpos+1 && r<maxRows; ++r)
{
for (int c = cpos-1; c <= cpos+1 && c<maxCols; ++c)
{
if(r>=0 && c>=0 && !visited[r][c])
{
counter++;
Node* next = n->get(board[r][c]);
if (next)
{
auto moreStr = find(board, visited, r, c, next, s);
foundStrings.insert(moreStr.begin(), moreStr.end());
}
}
}
}
return foundStrings;
}
std::set<std::string> findWords(const BBoard& board, const Trie& dict)
{
std::set<std::string> results;
for (size_t r = 0; r < board.size(); ++r)
{
for (size_t c = 0; c < board[0].size(); ++c)
{
Visited visited;
for (size_t i = 0; i < board.size(); ++i)
visited.push_back(std::vector<bool>(board[0].size(), false));
Node* start = dict.root->get(board[r][c]);
if (start)
{
auto strings = find(board, visited, r, c, start);
results.insert(strings.begin(), strings.end());
}
}
}
return results;
}
int main()
{
BBoard board{
{'G', 'I', 'P'},
{'O', 'T', 'E'},
{'O', 'G', 'L'},
{'P', 'X', 'T'}
};
// Dictionary
std::set<std::string> d{
"GIT",
"GOOGLE",
"GOO"
};
// Convert dictionary to Trie for better search performance
Trie t;
for (const auto& w : d) t.addString(w);
// Trie test
std::cout << "Search GOO: " << t.search("GOO") << std::endl;
std::cout << "Search GOT: " << t.search("GOT") << std::endl;
std::cout << "Search GOOGLE: " << t.search("GOOGLE") << std::endl;
std::cout << "Searching boggle board..." << std::endl;
for (const auto& r : findWords(board, t))
std::cout << r << std::endl;
std::cout << "Number of cells tested " << counter << std::endl;
return 0;
}
<commit_msg>Add docs<commit_after>// Boggle.cpp
// Given a Boggle board and a dictionary of words, find all possible words on the board
// This is an exercise in efficient search for known strings as we travel over a wordspace.
//
// Utilises a Trie data structure for tracking known word formation.
// Problem taken from geekforgeeks.com
//
#include <iostream>
#include <set>
#include <vector>
#include "Trie.h"
// A matrix containing our boggle board letters
typedef std::vector<std::vector<char>> BBoard;
// A mask so we know which cells in the board we have already visited
typedef std::vector<std::vector<bool>> Visited;
/*
* From the starting cell defined by rpos,cpos search the
* surrounding cells to find potential words in the dictionary.
*
* We avoid considering cells that have already been visited.
*
* The string s contains the letters we have gathered so far from
* previous calls to this function.
*
* The Node n represents the current position that we are at in
* the Trie structure which is representing our dictionary.
*/
std::set<std::string> find( const BBoard& board,
Visited& visited,
const int rpos,
const int cpos,
Node* n,
std::string s = std::string())
{
const int maxRows = board.size(),
maxCols = board[0].size();
std::set<std::string> foundStrings;
visited[rpos][cpos] = true;
// Is this board cell in the dict?
const char c = board[rpos][cpos];
if (n->val == c)
{
std::cout << "found " << s << "+" << c << std::endl;
s += c;
if (n->marker) foundStrings.insert(s);
}
// Search neighbouring board cells
for (int r = rpos-1; r <= rpos+1 && r<maxRows; ++r)
{
for (int c = cpos-1; c <= cpos+1 && c<maxCols; ++c)
{
if(r>=0 && c>=0 && !visited[r][c])
{
Node* next = n->get(board[r][c]);
if (next)
{
auto moreStr = find(board, visited, r, c, next, s);
foundStrings.insert(moreStr.begin(), moreStr.end());
}
}
}
}
return foundStrings;
}
/*
* Entry point for searching the board for words that appear in the dictionary.
*
* We try to find words starting at each cell in the board, and then combine
* all the found words together for return.
*/
std::set<std::string> findWords(const BBoard& board, const Trie& dict)
{
// A clear bool mask the same size of the board
Visited clear_mask;
for (size_t i = 0; i < board.size(); ++i)
clear_mask.push_back(std::vector<bool>(board[0].size(), false));
std::set<std::string> results;
for (size_t r = 0; r < board.size(); ++r)
{
for (size_t c = 0; c < board[0].size(); ++c)
{
// Start with a clear mask
Visited visited = clear_mask;
Node* start = dict.root->get(board[r][c]);
if (start)
{
auto strings = find(board, visited, r, c, start);
results.insert(strings.begin(), strings.end());
}
}
}
return results;
}
int main()
{
BBoard board{
{'G', 'I', 'P'},
{'O', 'T', 'E'},
{'O', 'G', 'L'},
{'P', 'X', 'T'}
};
// Dictionary
std::set<std::string> d{
"GIT",
"GOOGLE",
"GOO"
};
// Convert dictionary to Trie for better search performance
Trie t;
for (const auto& w : d) t.addString(w);
// Trie test
std::cout << "Search GOO: " << t.search("GOO") << std::endl;
std::cout << "Search GOT: " << t.search("GOT") << std::endl;
std::cout << "Search GOOGLE: " << t.search("GOOGLE") << std::endl;
std::cout << "Searching boggle board..." << std::endl;
for (const auto& r : findWords(board, t))
std::cout << r << std::endl;
return 0;
}
<|endoftext|> |
<commit_before>/* This file is part of Mapnik (c++ mapping toolkit)
*
* Copyright (C) 2011 Artem Pavlenko
*
* Mapnik is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or 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 General Public License for more details.
*
* You should have received a copy of the GNU 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.
*/
//$Id$
// stl
#include <iostream>
// qt
#include <QtGui>
#include <QSplitter>
#include <QTreeView>
#include <QListView>
#include <QTabWidget>
#include <QList>
#include <QItemDelegate>
#include <QSlider>
#include <QComboBox>
#include <QDoubleSpinBox>
// mapnik
#ifndef Q_MOC_RUN // QT moc chokes on BOOST_JOIN
#include <mapnik/config_error.hpp>
#include <mapnik/load_map.hpp>
#include <mapnik/save_map.hpp>
#endif
// qt
#include "mainwindow.hpp"
#include "layerlistmodel.hpp"
#include "styles_model.hpp"
#include "layerwidget.hpp"
#include "layerdelegate.hpp"
#include "about_dialog.hpp"
MainWindow::MainWindow()
: filename_(),
default_extent_(-20037508.3428,-20037508.3428,20037508.3428,20037508.3428)
{
mapWidget_ = new MapWidget(this);
QSplitter *splitter = new QSplitter(this);
QTabWidget *tabWidget=new QTabWidget;
layerTab_ = new LayerTab;
layerTab_->setFocusPolicy(Qt::NoFocus);
layerTab_->setIconSize(QSize(16,16));
//LayerDelegate *delegate = new LayerDelegate(this);
//layerTab_->setItemDelegate(delegate);
//layerTab_->setItemDelegate(new QItemDelegate(this));
//layerTab_->setViewMode(QListView::IconMode);
layerTab_->setFlow(QListView::TopToBottom);
tabWidget->addTab(layerTab_,tr("Layers"));
// Styles tab
styleTab_ = new StyleTab;
tabWidget->addTab(styleTab_,tr("Styles"));
splitter->addWidget(tabWidget);
splitter->addWidget(mapWidget_);
QList<int> list;
list.push_back(200);
list.push_back(600);
splitter->setSizes(list);
mapWidget_->setFocusPolicy(Qt::StrongFocus);
mapWidget_->setFocus();
//setCentralWidget(mapWidget_);
setCentralWidget(splitter);
createActions();
createMenus();
createToolBars();
createContextMenu();
setWindowTitle(tr("Mapnik Viewer"));
status=new QStatusBar(this);
status->showMessage(tr(""));
setStatusBar(status);
resize(800,600);
//connect mapview to layerlist
connect(mapWidget_, SIGNAL(mapViewChanged()),layerTab_, SLOT(update()));
// slider
connect(slider_,SIGNAL(valueChanged(int)),mapWidget_,SLOT(zoomToLevel(int)));
// renderer selector
connect(renderer_selector_,SIGNAL(currentIndexChanged(QString const&)),
mapWidget_, SLOT(updateRenderer(QString const&)));
// scale factor
connect(scale_factor_,SIGNAL(valueChanged(double)),
mapWidget_, SLOT(updateScaleFactor(double)));
//
connect(layerTab_,SIGNAL(update_mapwidget()),mapWidget_,SLOT(updateMap()));
connect(layerTab_,SIGNAL(layerSelected(int)),
mapWidget_,SLOT(layerSelected(int)));
}
MainWindow::~MainWindow()
{
delete mapWidget_;
}
void MainWindow::closeEvent(QCloseEvent* event)
{
event->accept();
}
void MainWindow::createContextMenu()
{
layerTab_->setContextMenuPolicy(Qt::ActionsContextMenu);
layerTab_->addAction(openAct);
layerTab_->addAction(layerInfo);
}
void MainWindow::open(QString const& path)
{
if (path.isNull())
{
filename_ = QFileDialog::getOpenFileName(this,tr("Open Mapnik file"),
currentPath,"*.xml");
}
else
{
filename_ = path;
}
if (!filename_.isEmpty())
{
load_map_file(filename_);
setWindowTitle(tr("%1 - Mapnik Viewer").arg(filename_));
}
}
void MainWindow::reload()
{
if (!filename_.isEmpty())
{
mapnik::box2d<double> bbox = mapWidget_->getMap()->get_current_extent();
load_map_file(filename_);
mapWidget_->zoomToBox(bbox);
setWindowTitle(tr("%1 - *Reloaded*").arg(filename_));
}
}
void MainWindow::save()
{
QString initialPath = QDir::currentPath() + "/untitled.xml";
QString filename = QFileDialog::getSaveFileName(this, tr("Save"),
initialPath,
tr("%1 Files (*.xml)")
.arg(QString("Mapnik definition")));
if (!filename.isEmpty())
{
std::cout<<"saving "<< filename.toStdString() << std::endl;
mapnik::save_map(*mapWidget_->getMap(),filename.toStdString());
}
}
void MainWindow::load_map_file(QString const& filename)
{
std::cout<<"loading "<< filename.toStdString() << std::endl;
unsigned width = mapWidget_->width();
unsigned height = mapWidget_->height();
boost::shared_ptr<mapnik::Map> map(new mapnik::Map(width,height));
mapWidget_->setMap(map);
try
{
mapnik::load_map(*map,filename.toStdString());
}
catch (mapnik::config_error & ex)
{
std::cout << ex.what() << "\n";
}
catch (...)
{
std::cerr << "Exception caught in load_map\n";
}
layerTab_->setModel(new LayerListModel(map,this));
styleTab_->setModel(new StyleModel(map,this));
zoom_all();
}
void MainWindow::zoom_to_box()
{
mapWidget_->setTool(MapWidget::ZoomToBox);
}
void MainWindow::pan()
{
mapWidget_->setTool(MapWidget::Pan);
}
void MainWindow::info()
{
mapWidget_->setTool(MapWidget::Info);
}
void MainWindow::pan_left()
{
mapWidget_->panLeft();
}
void MainWindow::pan_right()
{
mapWidget_->panRight();
}
void MainWindow::pan_up()
{
mapWidget_->panUp();
}
void MainWindow::pan_down()
{
mapWidget_->panDown();
}
void MainWindow::about()
{
about_dialog dlg;
dlg.exec();
}
void MainWindow::export_as()
{
QAction *action = qobject_cast<QAction *>(sender());
QByteArray fileFormat = action->data().toByteArray();
QString initialPath = QDir::currentPath() + "/map." + fileFormat;
QString fileName = QFileDialog::getSaveFileName(this, tr("Export As"),
initialPath,
tr("%1 Files (*.%2);;All Files (*)")
.arg(QString(fileFormat.toUpper()))
.arg(QString(fileFormat)));
if (!fileName.isEmpty())
{
QPixmap const& pix = mapWidget_->pixmap();
pix.save(fileName);
}
}
void MainWindow::print()
{
//Q_ASSERT(mapWidget_->pixmap());
//QPrintDialog dialog(&printer, this);
//if (dialog.exec()) {
// QPainter painter(&printer);
// QRect rect = painter.viewport();
// QSize size = mapWidget_->pixmap()->size();
// size.scale(rect.size(), Qt::KeepAspectRatio);
// painter.setViewport(rect.x(), rect.y(), size.width(), size.height());
// painter.setWindow(mapWidget_->pixmap()->rect());
// painter.drawPixmap(0, 0, *mapWidget_->pixmap());
//}
}
void MainWindow::createActions()
{
//exportAct = new QAction(tr("&Export as ..."),this);
//exportAct->setShortcut(tr("Ctrl+E"));
//connect(exportAct, SIGNAL(triggered()), this, SLOT(export_as()));
zoomAllAct = new QAction(QIcon(":/images/home.png"),tr("Zoom All"),this);
connect(zoomAllAct, SIGNAL(triggered()), this, SLOT(zoom_all()));
zoomBoxAct = new QAction(QIcon(":/images/zoombox.png"),tr("Zoom To Box"),this);
zoomBoxAct->setCheckable(true);
connect(zoomBoxAct, SIGNAL(triggered()), this, SLOT(zoom_to_box()));
panAct = new QAction(QIcon(":/images/pan.png"),tr("Pan"),this);
panAct->setCheckable(true);
connect(panAct, SIGNAL(triggered()), this, SLOT(pan()));
infoAct = new QAction(QIcon(":/images/info.png"),tr("Info"),this);
infoAct->setCheckable(true);
connect(infoAct, SIGNAL(triggered()), this, SLOT(info()));
toolsGroup=new QActionGroup(this);
toolsGroup->addAction(zoomBoxAct);
toolsGroup->addAction(panAct);
toolsGroup->addAction(infoAct);
zoomBoxAct->setChecked(true);
openAct=new QAction(tr("Open Map definition"),this);
connect(openAct,SIGNAL(triggered()),this,SLOT(open()));
saveAct=new QAction(tr("Save Map definition"),this);
connect(saveAct,SIGNAL(triggered()),this,SLOT(save()));
panLeftAct = new QAction(QIcon(":/images/left.png"),tr("&Pan Left"),this);
connect(panLeftAct, SIGNAL(triggered()), this, SLOT(pan_left()));
panRightAct = new QAction(QIcon(":/images/right.png"),tr("&Pan Right"),this);
connect(panRightAct, SIGNAL(triggered()), this, SLOT(pan_right()));
panUpAct = new QAction(QIcon(":/images/up.png"),tr("&Pan Up"),this);
connect(panUpAct, SIGNAL(triggered()), this, SLOT(pan_up()));
panDownAct = new QAction(QIcon(":/images/down.png"),tr("&Pan Down"),this);
connect(panDownAct, SIGNAL(triggered()), this, SLOT(pan_down()));
reloadAct = new QAction(QIcon(":/images/reload.png"),tr("Reload"),this);
connect(reloadAct, SIGNAL(triggered()), this, SLOT(reload()));
layerInfo = new QAction(QIcon(":/images/info.png"),tr("&Layer info"),layerTab_);
connect(layerInfo, SIGNAL(triggered()), layerTab_,SLOT(layerInfo()));
connect(layerTab_, SIGNAL(doubleClicked(QModelIndex const&)), layerTab_,SLOT(layerInfo2(QModelIndex const&)));
foreach (QByteArray format, QImageWriter::supportedImageFormats())
{
QString text = tr("%1...").arg(QString(format).toUpper());
QAction *action = new QAction(text, this);
action->setData(format);
connect(action, SIGNAL(triggered()), this, SLOT(export_as()));
exportAsActs.append(action);
}
printAct = new QAction(QIcon(":/images/print.png"),tr("&Print ..."),this);
printAct->setShortcut(tr("Ctrl+E"));
connect(printAct, SIGNAL(triggered()), this, SLOT(print()));
exitAct = new QAction(tr("E&xit"), this);
exitAct->setShortcut(tr("Ctrl+Q"));
connect(exitAct, SIGNAL(triggered()), this, SLOT(close()));
aboutAct = new QAction(QIcon(":/images/about.png"),tr("&About"), this);
connect(aboutAct, SIGNAL(triggered()), this, SLOT(about()));
}
void MainWindow::createMenus()
{
exportMenu = new QMenu(tr("&Export As"), this);
foreach (QAction *action, exportAsActs)
exportMenu->addAction(action);
fileMenu = new QMenu(tr("&File"),this);
fileMenu->addAction(openAct);
fileMenu->addAction(saveAct);
fileMenu->addMenu(exportMenu);
fileMenu->addAction(printAct);
fileMenu->addSeparator();
fileMenu->addAction(exitAct);
menuBar()->addMenu(fileMenu);
helpMenu = new QMenu(tr("&Help"), this);
helpMenu->addAction(aboutAct);
menuBar()->addMenu(helpMenu);
}
void MainWindow::createToolBars()
{
fileToolBar = addToolBar(tr("Actions"));
fileToolBar->addAction(zoomAllAct);
fileToolBar->addAction(zoomBoxAct);
fileToolBar->addAction(panAct);
fileToolBar->addAction(panLeftAct);
fileToolBar->addAction(panRightAct);
fileToolBar->addAction(panUpAct);
fileToolBar->addAction(panDownAct);
fileToolBar->addAction(infoAct);
fileToolBar->addAction(reloadAct);
fileToolBar->addAction(printAct);
renderer_selector_ = new QComboBox(fileToolBar);
renderer_selector_->setFocusPolicy(Qt::NoFocus);
renderer_selector_->addItem("AGG");
#ifdef HAVE_CAIRO
renderer_selector_->addItem("Cairo");
#endif
renderer_selector_->addItem("Grid");
fileToolBar->addWidget(renderer_selector_);
scale_factor_ = new QDoubleSpinBox(fileToolBar);
scale_factor_->setMinimum(0.1);
scale_factor_->setMaximum(5.0);
scale_factor_->setSingleStep(0.1);
scale_factor_->setValue(1.0);
fileToolBar->addWidget(scale_factor_);
slider_ = new QSlider(Qt::Horizontal,fileToolBar);
slider_->setRange(1,18);
slider_->setTickPosition(QSlider::TicksBelow);
slider_->setTickInterval(1);
slider_->setTracking(false);
fileToolBar->addWidget(slider_);
fileToolBar->addAction(aboutAct);
}
void MainWindow::set_default_extent(double x0,double y0, double x1, double y1)
{
try
{
boost::shared_ptr<mapnik::Map> map_ptr = mapWidget_->getMap();
if (map_ptr)
{
mapnik::projection prj(map_ptr->srs());
prj.forward(x0,y0);
prj.forward(x1,y1);
default_extent_=mapnik::box2d<double>(x0,y0,x1,y1);
mapWidget_->zoomToBox(default_extent_);
std::cout << "SET DEFAULT EXT\n";
}
}
catch (...) {}
}
void MainWindow::set_scaling_factor(double scaling_factor)
{
mapWidget_->set_scaling_factor(scaling_factor);
}
void MainWindow::zoom_all()
{
boost::shared_ptr<mapnik::Map> map_ptr = mapWidget_->getMap();
if (map_ptr)
{
map_ptr->zoom_all();
mapnik::box2d<double> const& ext = map_ptr->get_current_extent();
mapWidget_->zoomToBox(ext);
}
}
<commit_msg>+ add missing header<commit_after>/* This file is part of Mapnik (c++ mapping toolkit)
*
* Copyright (C) 2011 Artem Pavlenko
*
* Mapnik is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or 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 General Public License for more details.
*
* You should have received a copy of the GNU 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.
*/
//$Id$
// stl
#include <iostream>
// qt
#include <QtGui>
#include <QSplitter>
#include <QTreeView>
#include <QListView>
#include <QTabWidget>
#include <QList>
#include <QItemDelegate>
#include <QSlider>
#include <QComboBox>
#include <QDoubleSpinBox>
// mapnik
#ifndef Q_MOC_RUN // QT moc chokes on BOOST_JOIN
#include <mapnik/config_error.hpp>
#include <mapnik/load_map.hpp>
#include <mapnik/save_map.hpp>
#include <mapnik/projection.hpp>
#endif
// qt
#include "mainwindow.hpp"
#include "layerlistmodel.hpp"
#include "styles_model.hpp"
#include "layerwidget.hpp"
#include "layerdelegate.hpp"
#include "about_dialog.hpp"
MainWindow::MainWindow()
: filename_(),
default_extent_(-20037508.3428,-20037508.3428,20037508.3428,20037508.3428)
{
mapWidget_ = new MapWidget(this);
QSplitter *splitter = new QSplitter(this);
QTabWidget *tabWidget=new QTabWidget;
layerTab_ = new LayerTab;
layerTab_->setFocusPolicy(Qt::NoFocus);
layerTab_->setIconSize(QSize(16,16));
//LayerDelegate *delegate = new LayerDelegate(this);
//layerTab_->setItemDelegate(delegate);
//layerTab_->setItemDelegate(new QItemDelegate(this));
//layerTab_->setViewMode(QListView::IconMode);
layerTab_->setFlow(QListView::TopToBottom);
tabWidget->addTab(layerTab_,tr("Layers"));
// Styles tab
styleTab_ = new StyleTab;
tabWidget->addTab(styleTab_,tr("Styles"));
splitter->addWidget(tabWidget);
splitter->addWidget(mapWidget_);
QList<int> list;
list.push_back(200);
list.push_back(600);
splitter->setSizes(list);
mapWidget_->setFocusPolicy(Qt::StrongFocus);
mapWidget_->setFocus();
//setCentralWidget(mapWidget_);
setCentralWidget(splitter);
createActions();
createMenus();
createToolBars();
createContextMenu();
setWindowTitle(tr("Mapnik Viewer"));
status=new QStatusBar(this);
status->showMessage(tr(""));
setStatusBar(status);
resize(800,600);
//connect mapview to layerlist
connect(mapWidget_, SIGNAL(mapViewChanged()),layerTab_, SLOT(update()));
// slider
connect(slider_,SIGNAL(valueChanged(int)),mapWidget_,SLOT(zoomToLevel(int)));
// renderer selector
connect(renderer_selector_,SIGNAL(currentIndexChanged(QString const&)),
mapWidget_, SLOT(updateRenderer(QString const&)));
// scale factor
connect(scale_factor_,SIGNAL(valueChanged(double)),
mapWidget_, SLOT(updateScaleFactor(double)));
//
connect(layerTab_,SIGNAL(update_mapwidget()),mapWidget_,SLOT(updateMap()));
connect(layerTab_,SIGNAL(layerSelected(int)),
mapWidget_,SLOT(layerSelected(int)));
}
MainWindow::~MainWindow()
{
delete mapWidget_;
}
void MainWindow::closeEvent(QCloseEvent* event)
{
event->accept();
}
void MainWindow::createContextMenu()
{
layerTab_->setContextMenuPolicy(Qt::ActionsContextMenu);
layerTab_->addAction(openAct);
layerTab_->addAction(layerInfo);
}
void MainWindow::open(QString const& path)
{
if (path.isNull())
{
filename_ = QFileDialog::getOpenFileName(this,tr("Open Mapnik file"),
currentPath,"*.xml");
}
else
{
filename_ = path;
}
if (!filename_.isEmpty())
{
load_map_file(filename_);
setWindowTitle(tr("%1 - Mapnik Viewer").arg(filename_));
}
}
void MainWindow::reload()
{
if (!filename_.isEmpty())
{
mapnik::box2d<double> bbox = mapWidget_->getMap()->get_current_extent();
load_map_file(filename_);
mapWidget_->zoomToBox(bbox);
setWindowTitle(tr("%1 - *Reloaded*").arg(filename_));
}
}
void MainWindow::save()
{
QString initialPath = QDir::currentPath() + "/untitled.xml";
QString filename = QFileDialog::getSaveFileName(this, tr("Save"),
initialPath,
tr("%1 Files (*.xml)")
.arg(QString("Mapnik definition")));
if (!filename.isEmpty())
{
std::cout<<"saving "<< filename.toStdString() << std::endl;
mapnik::save_map(*mapWidget_->getMap(),filename.toStdString());
}
}
void MainWindow::load_map_file(QString const& filename)
{
std::cout<<"loading "<< filename.toStdString() << std::endl;
unsigned width = mapWidget_->width();
unsigned height = mapWidget_->height();
boost::shared_ptr<mapnik::Map> map(new mapnik::Map(width,height));
mapWidget_->setMap(map);
try
{
mapnik::load_map(*map,filename.toStdString());
}
catch (mapnik::config_error & ex)
{
std::cout << ex.what() << "\n";
}
catch (...)
{
std::cerr << "Exception caught in load_map\n";
}
layerTab_->setModel(new LayerListModel(map,this));
styleTab_->setModel(new StyleModel(map,this));
zoom_all();
}
void MainWindow::zoom_to_box()
{
mapWidget_->setTool(MapWidget::ZoomToBox);
}
void MainWindow::pan()
{
mapWidget_->setTool(MapWidget::Pan);
}
void MainWindow::info()
{
mapWidget_->setTool(MapWidget::Info);
}
void MainWindow::pan_left()
{
mapWidget_->panLeft();
}
void MainWindow::pan_right()
{
mapWidget_->panRight();
}
void MainWindow::pan_up()
{
mapWidget_->panUp();
}
void MainWindow::pan_down()
{
mapWidget_->panDown();
}
void MainWindow::about()
{
about_dialog dlg;
dlg.exec();
}
void MainWindow::export_as()
{
QAction *action = qobject_cast<QAction *>(sender());
QByteArray fileFormat = action->data().toByteArray();
QString initialPath = QDir::currentPath() + "/map." + fileFormat;
QString fileName = QFileDialog::getSaveFileName(this, tr("Export As"),
initialPath,
tr("%1 Files (*.%2);;All Files (*)")
.arg(QString(fileFormat.toUpper()))
.arg(QString(fileFormat)));
if (!fileName.isEmpty())
{
QPixmap const& pix = mapWidget_->pixmap();
pix.save(fileName);
}
}
void MainWindow::print()
{
//Q_ASSERT(mapWidget_->pixmap());
//QPrintDialog dialog(&printer, this);
//if (dialog.exec()) {
// QPainter painter(&printer);
// QRect rect = painter.viewport();
// QSize size = mapWidget_->pixmap()->size();
// size.scale(rect.size(), Qt::KeepAspectRatio);
// painter.setViewport(rect.x(), rect.y(), size.width(), size.height());
// painter.setWindow(mapWidget_->pixmap()->rect());
// painter.drawPixmap(0, 0, *mapWidget_->pixmap());
//}
}
void MainWindow::createActions()
{
//exportAct = new QAction(tr("&Export as ..."),this);
//exportAct->setShortcut(tr("Ctrl+E"));
//connect(exportAct, SIGNAL(triggered()), this, SLOT(export_as()));
zoomAllAct = new QAction(QIcon(":/images/home.png"),tr("Zoom All"),this);
connect(zoomAllAct, SIGNAL(triggered()), this, SLOT(zoom_all()));
zoomBoxAct = new QAction(QIcon(":/images/zoombox.png"),tr("Zoom To Box"),this);
zoomBoxAct->setCheckable(true);
connect(zoomBoxAct, SIGNAL(triggered()), this, SLOT(zoom_to_box()));
panAct = new QAction(QIcon(":/images/pan.png"),tr("Pan"),this);
panAct->setCheckable(true);
connect(panAct, SIGNAL(triggered()), this, SLOT(pan()));
infoAct = new QAction(QIcon(":/images/info.png"),tr("Info"),this);
infoAct->setCheckable(true);
connect(infoAct, SIGNAL(triggered()), this, SLOT(info()));
toolsGroup=new QActionGroup(this);
toolsGroup->addAction(zoomBoxAct);
toolsGroup->addAction(panAct);
toolsGroup->addAction(infoAct);
zoomBoxAct->setChecked(true);
openAct=new QAction(tr("Open Map definition"),this);
connect(openAct,SIGNAL(triggered()),this,SLOT(open()));
saveAct=new QAction(tr("Save Map definition"),this);
connect(saveAct,SIGNAL(triggered()),this,SLOT(save()));
panLeftAct = new QAction(QIcon(":/images/left.png"),tr("&Pan Left"),this);
connect(panLeftAct, SIGNAL(triggered()), this, SLOT(pan_left()));
panRightAct = new QAction(QIcon(":/images/right.png"),tr("&Pan Right"),this);
connect(panRightAct, SIGNAL(triggered()), this, SLOT(pan_right()));
panUpAct = new QAction(QIcon(":/images/up.png"),tr("&Pan Up"),this);
connect(panUpAct, SIGNAL(triggered()), this, SLOT(pan_up()));
panDownAct = new QAction(QIcon(":/images/down.png"),tr("&Pan Down"),this);
connect(panDownAct, SIGNAL(triggered()), this, SLOT(pan_down()));
reloadAct = new QAction(QIcon(":/images/reload.png"),tr("Reload"),this);
connect(reloadAct, SIGNAL(triggered()), this, SLOT(reload()));
layerInfo = new QAction(QIcon(":/images/info.png"),tr("&Layer info"),layerTab_);
connect(layerInfo, SIGNAL(triggered()), layerTab_,SLOT(layerInfo()));
connect(layerTab_, SIGNAL(doubleClicked(QModelIndex const&)), layerTab_,SLOT(layerInfo2(QModelIndex const&)));
foreach (QByteArray format, QImageWriter::supportedImageFormats())
{
QString text = tr("%1...").arg(QString(format).toUpper());
QAction *action = new QAction(text, this);
action->setData(format);
connect(action, SIGNAL(triggered()), this, SLOT(export_as()));
exportAsActs.append(action);
}
printAct = new QAction(QIcon(":/images/print.png"),tr("&Print ..."),this);
printAct->setShortcut(tr("Ctrl+E"));
connect(printAct, SIGNAL(triggered()), this, SLOT(print()));
exitAct = new QAction(tr("E&xit"), this);
exitAct->setShortcut(tr("Ctrl+Q"));
connect(exitAct, SIGNAL(triggered()), this, SLOT(close()));
aboutAct = new QAction(QIcon(":/images/about.png"),tr("&About"), this);
connect(aboutAct, SIGNAL(triggered()), this, SLOT(about()));
}
void MainWindow::createMenus()
{
exportMenu = new QMenu(tr("&Export As"), this);
foreach (QAction *action, exportAsActs)
exportMenu->addAction(action);
fileMenu = new QMenu(tr("&File"),this);
fileMenu->addAction(openAct);
fileMenu->addAction(saveAct);
fileMenu->addMenu(exportMenu);
fileMenu->addAction(printAct);
fileMenu->addSeparator();
fileMenu->addAction(exitAct);
menuBar()->addMenu(fileMenu);
helpMenu = new QMenu(tr("&Help"), this);
helpMenu->addAction(aboutAct);
menuBar()->addMenu(helpMenu);
}
void MainWindow::createToolBars()
{
fileToolBar = addToolBar(tr("Actions"));
fileToolBar->addAction(zoomAllAct);
fileToolBar->addAction(zoomBoxAct);
fileToolBar->addAction(panAct);
fileToolBar->addAction(panLeftAct);
fileToolBar->addAction(panRightAct);
fileToolBar->addAction(panUpAct);
fileToolBar->addAction(panDownAct);
fileToolBar->addAction(infoAct);
fileToolBar->addAction(reloadAct);
fileToolBar->addAction(printAct);
renderer_selector_ = new QComboBox(fileToolBar);
renderer_selector_->setFocusPolicy(Qt::NoFocus);
renderer_selector_->addItem("AGG");
#ifdef HAVE_CAIRO
renderer_selector_->addItem("Cairo");
#endif
renderer_selector_->addItem("Grid");
fileToolBar->addWidget(renderer_selector_);
scale_factor_ = new QDoubleSpinBox(fileToolBar);
scale_factor_->setMinimum(0.1);
scale_factor_->setMaximum(5.0);
scale_factor_->setSingleStep(0.1);
scale_factor_->setValue(1.0);
fileToolBar->addWidget(scale_factor_);
slider_ = new QSlider(Qt::Horizontal,fileToolBar);
slider_->setRange(1,18);
slider_->setTickPosition(QSlider::TicksBelow);
slider_->setTickInterval(1);
slider_->setTracking(false);
fileToolBar->addWidget(slider_);
fileToolBar->addAction(aboutAct);
}
void MainWindow::set_default_extent(double x0,double y0, double x1, double y1)
{
try
{
boost::shared_ptr<mapnik::Map> map_ptr = mapWidget_->getMap();
if (map_ptr)
{
mapnik::projection prj(map_ptr->srs());
prj.forward(x0,y0);
prj.forward(x1,y1);
default_extent_=mapnik::box2d<double>(x0,y0,x1,y1);
mapWidget_->zoomToBox(default_extent_);
std::cout << "SET DEFAULT EXT\n";
}
}
catch (...) {}
}
void MainWindow::set_scaling_factor(double scaling_factor)
{
mapWidget_->set_scaling_factor(scaling_factor);
}
void MainWindow::zoom_all()
{
boost::shared_ptr<mapnik::Map> map_ptr = mapWidget_->getMap();
if (map_ptr)
{
map_ptr->zoom_all();
mapnik::box2d<double> const& ext = map_ptr->get_current_extent();
mapWidget_->zoomToBox(ext);
}
}
<|endoftext|> |
<commit_before>#include "StorageMemoChunk.h"
#include "StorageChunkSerializer.h"
#include "StorageChunkWriter.h"
#include "StorageBulkCursor.h"
#include "StorageEnvironment.h"
#include "StorageAsyncGet.h"
static inline int KeyCmp(const ReadBuffer& a, const ReadBuffer& b)
{
return ReadBuffer::Cmp(a, b);
}
static inline const ReadBuffer Key(const StorageMemoKeyValue* kv)
{
return kv->GetKey();
}
static inline const ReadBuffer Key(const StorageFileKeyValue* kv)
{
return kv->GetKey();
}
uint32_t StorageMemoKeyValueAllocator::GetFreeSize()
{
return size - pos;
}
StorageMemoChunk::StorageMemoChunk(uint64_t chunkID_, bool useBloomFilter_)
{
chunkID = chunkID_;
useBloomFilter = useBloomFilter_;
serialized = false;
minLogSegmentID = 0;
maxLogSegmentID = 0;
maxLogCommandID = 0;
size = 0;
fileChunk = NULL;
deleted = false;
}
StorageMemoChunk::~StorageMemoChunk()
{
StorageMemoKeyValueAllocator* allocator;
keyValueBlocks.DeleteQueue();
FOREACH_FIRST (allocator, allocators)
{
allocators.Remove(allocator);
free((void*) allocator);
}
if (fileChunk != NULL)
delete fileChunk;
}
StorageChunk::ChunkState StorageMemoChunk::GetChunkState()
{
if (serialized)
return StorageChunk::Serialized;
else
return StorageChunk::Tree;
}
void StorageMemoChunk::NextBunch(StorageBulkCursor& cursor, StorageShard* shard)
{
bool first;
int cmpres;
ReadBuffer nextKey, key, value;
StorageMemoKeyValue* it;
uint32_t total;
if (keyValues.GetCount() == 0)
{
cursor.SetLast(true);
return;
}
nextKey = cursor.GetNextKey();
it = keyValues.Locate(nextKey, cmpres);
total = 0;
first = true;
while (it)
{
if (!shard->RangeContains(it->GetKey()))
{
it = keyValues.Next(it);
continue;
}
if (!first && total + it->GetKey().GetLength() + it->GetValue().GetLength() > STORAGE_MEMO_BUNCH_GRAN)
break;
total += it->GetKey().GetLength() + it->GetValue().GetLength();
cursor.AppendKeyValue(it);
it = keyValues.Next(it);
first = false;
}
cursor.FinalizeKeyValues();
if (!it)
{
cursor.SetLast(true);
}
else
{
cursor.SetNextKey(it->GetKey());
cursor.SetLast(false);
}
}
//void StorageMemoChunk::SetChunkID(uint64_t chunkID_)
//{
// chunkID = chunkID_;
//}
//
//void StorageMemoChunk::SetUseBloomFilter(bool useBloomFilter_)
//{
// useBloomFilter = useBloomFilter_;
//}
uint64_t StorageMemoChunk::GetChunkID()
{
return chunkID;
}
bool StorageMemoChunk::UseBloomFilter()
{
return useBloomFilter;
}
StorageKeyValue* StorageMemoChunk::Get(ReadBuffer& key)
{
int cmpres;
StorageMemoKeyValue* it;
if (keyValues.GetCount() == 0)
return NULL;
it = keyValues.Locate<const ReadBuffer&>(key, cmpres);
if (cmpres != 0)
return NULL;
return it;
}
void StorageMemoChunk::AsyncGet(StorageAsyncGet* asyncGet)
{
StorageKeyValue* kv;
Log_Debug("StorageMemoChunk::AsyncGet");
kv = Get(asyncGet->key);
if (kv == NULL || kv->GetType() == STORAGE_KEYVALUE_TYPE_DELETE)
{
asyncGet->ret = false;
asyncGet->completed = true;
return;
}
asyncGet->value = kv->GetValue();
asyncGet->ret = true;
asyncGet->completed = true;
}
bool StorageMemoChunk::Set(ReadBuffer key, ReadBuffer value)
{
int cmpres;
StorageMemoKeyValue* it;
if (keyValues.GetCount() != 0)
{
it = keyValues.Locate<const ReadBuffer&>(key, cmpres);
if (cmpres == 0)
{
it->Set(key, value, this);
return true;
}
}
it = NewStorageMemoKeyValue();
it->Set(key, value, this);
keyValues.Insert<const ReadBuffer>(it);
return true;
}
bool StorageMemoChunk::Delete(ReadBuffer key)
{
int cmpres;
StorageMemoKeyValue* it;
if (keyValues.GetCount() != 0)
{
it = keyValues.Locate<const ReadBuffer&>(key, cmpres);
if (cmpres == 0)
{
it->Delete(key, this);
return true;
}
}
it = NewStorageMemoKeyValue();
it->Delete(key, this);
keyValues.Insert<const ReadBuffer>(it);
return true;
}
void StorageMemoChunk::RegisterLogCommand(uint64_t logSegmentID_, uint32_t logCommandID_)
{
if (minLogSegmentID == 0)
minLogSegmentID = logSegmentID_;
if (logSegmentID_ > maxLogSegmentID)
{
maxLogSegmentID = logSegmentID_;
maxLogCommandID = logCommandID_;
}
else if (logSegmentID_ == maxLogSegmentID)
{
if (logCommandID_ > maxLogCommandID)
maxLogCommandID = logCommandID_;
}
}
uint64_t StorageMemoChunk::GetMinLogSegmentID()
{
return minLogSegmentID;
}
uint64_t StorageMemoChunk::GetMaxLogSegmentID()
{
return maxLogSegmentID;
}
uint32_t StorageMemoChunk::GetMaxLogCommandID()
{
return maxLogCommandID;
}
ReadBuffer StorageMemoChunk::GetFirstKey()
{
if (keyValues.First())
return keyValues.First()->GetKey();
else
return ReadBuffer();
}
ReadBuffer StorageMemoChunk::GetLastKey()
{
if (keyValues.Last())
return keyValues.Last()->GetKey();
else
return ReadBuffer();
}
uint64_t StorageMemoChunk::GetSize()
{
return size;
}
ReadBuffer StorageMemoChunk::GetMidpoint()
{
if (keyValues.Mid())
return keyValues.Mid()->GetKey();
else
return ReadBuffer();
}
bool StorageMemoChunk::IsEmpty()
{
return (size == 0);
}
StorageFileChunk* StorageMemoChunk::RemoveFileChunk()
{
StorageFileChunk* ret;
ret = fileChunk;
fileChunk = NULL;
return ret;
}
void StorageMemoChunk::RemoveFirst()
{
StorageMemoKeyValueBlock* block;
StorageMemoKeyValue* first;
first = keyValues.First();
keyValues.Remove(first);
first->Free(this);
block = keyValueBlocks.First();
ASSERT(first >= block->keyValues && first < (block->keyValues + STORAGE_BLOCK_NUM_KEY_VALUE));
block->last++;
if (block->last == STORAGE_BLOCK_NUM_KEY_VALUE)
{
keyValueBlocks.Dequeue();
delete block;
size -= sizeof(StorageMemoKeyValueBlock);
}
}
StorageMemoKeyValue* StorageMemoChunk::NewStorageMemoKeyValue()
{
StorageMemoKeyValueBlock* block;
StorageMemoKeyValue* keyValue;
bool isNewBlockNeeded;
isNewBlockNeeded = false;
if (keyValueBlocks.GetLength() == 0)
isNewBlockNeeded = true;
else
{
block = keyValueBlocks.Last();
if (block->first == STORAGE_BLOCK_NUM_KEY_VALUE)
isNewBlockNeeded = true;
}
if (isNewBlockNeeded)
{
block = new StorageMemoKeyValueBlock;
block->next = block;
block->first = 0;
block->last = 0;
keyValueBlocks.Enqueue(block);
size += sizeof(StorageMemoKeyValueBlock);
Log_Debug("MemoChunk %U, size: %s, keyValues: %u", chunkID, HUMAN_BYTES(size), keyValues.GetCount());
}
keyValue = &block->keyValues[block->first];
block->first++;
return keyValue;
}
char* StorageMemoChunk::Alloc(size_t size_)
{
StorageMemoKeyValueAllocator* allocator;
StorageMemoKeyValueAllocator* prevAllocator;
char* memory;
uint32_t allocatedSize;
size_t requiredSize;
// Each allocated piece of memory is prefixed with an uint32_t offset
// from the start of the buffer of the allocator. Therefore it is
// possible to find the allocator object of a given pointer.
requiredSize = size_ + sizeof(uint32_t);
// save the last allocator to avoid fragmentation
prevAllocator = allocator = allocators.Last();
if (allocator == NULL || allocator->GetFreeSize() < requiredSize)
{
allocatedSize = MAX(requiredSize, STORAGE_MEMO_ALLOCATOR_DEFAULT_SIZE);
// avoid calling malloc twice by allocating memory and setting the pointers
memory = (char*) malloc(sizeof(StorageMemoKeyValueAllocator) + allocatedSize);
allocator = (StorageMemoKeyValueAllocator*) memory;
allocator->buffer = memory + sizeof(StorageMemoKeyValueAllocator);
allocator->size = allocatedSize;
allocator->pos = 0;
allocator->num = 0;
allocator->next = allocator;
allocator->prev = allocator;
// TODO: better strategy to avoid fragmentation
if (prevAllocator != NULL &&
prevAllocator->GetFreeSize() > STORAGE_MEMO_ALLOCATOR_MIN_SIZE &&
prevAllocator->GetFreeSize() * 2 >= requiredSize)
{
allocators.Remove(prevAllocator);
allocators.Append(allocator);
allocators.Append(prevAllocator);
}
else
allocators.Append(allocator);
size += sizeof(StorageMemoKeyValueAllocator) + allocator->size;
Log_Debug("MemoChunk %U, size: %s, keyValues: %u", chunkID, HUMAN_BYTES(size), keyValues.GetCount());
}
// The memory layout is the following:
//
// +---------------------
// | pos (4 bytes)
// +---------------------
// | memory (size_ bytes)
// +---------------------
//
memory = allocator->buffer + allocator->pos;
allocator->pos += sizeof(uint32_t);
*(uint32_t*) memory = (uint32_t) allocator->pos;
memory += sizeof(uint32_t);
allocator->pos += size_;
allocator->num++;
return memory;
}
void StorageMemoChunk::Free(char* buffer)
{
ReadBuffer key;
uint32_t pos;
StorageMemoKeyValueAllocator* allocator;
pos = *(uint32_t*)(buffer - sizeof(uint32_t));
allocator = (StorageMemoKeyValueAllocator*)(buffer - pos - sizeof(StorageMemoKeyValueAllocator));
allocator->num--;
if (allocator->num == 0)
{
size -= sizeof(StorageMemoKeyValueAllocator) + allocator->size;
allocators.Remove(allocator);
free(allocator);
}
}
<commit_msg>Removed debug logs.<commit_after>#include "StorageMemoChunk.h"
#include "StorageChunkSerializer.h"
#include "StorageChunkWriter.h"
#include "StorageBulkCursor.h"
#include "StorageEnvironment.h"
#include "StorageAsyncGet.h"
static inline int KeyCmp(const ReadBuffer& a, const ReadBuffer& b)
{
return ReadBuffer::Cmp(a, b);
}
static inline const ReadBuffer Key(const StorageMemoKeyValue* kv)
{
return kv->GetKey();
}
static inline const ReadBuffer Key(const StorageFileKeyValue* kv)
{
return kv->GetKey();
}
uint32_t StorageMemoKeyValueAllocator::GetFreeSize()
{
return size - pos;
}
StorageMemoChunk::StorageMemoChunk(uint64_t chunkID_, bool useBloomFilter_)
{
chunkID = chunkID_;
useBloomFilter = useBloomFilter_;
serialized = false;
minLogSegmentID = 0;
maxLogSegmentID = 0;
maxLogCommandID = 0;
size = 0;
fileChunk = NULL;
deleted = false;
}
StorageMemoChunk::~StorageMemoChunk()
{
StorageMemoKeyValueAllocator* allocator;
keyValueBlocks.DeleteQueue();
FOREACH_FIRST (allocator, allocators)
{
allocators.Remove(allocator);
free((void*) allocator);
}
if (fileChunk != NULL)
delete fileChunk;
}
StorageChunk::ChunkState StorageMemoChunk::GetChunkState()
{
if (serialized)
return StorageChunk::Serialized;
else
return StorageChunk::Tree;
}
void StorageMemoChunk::NextBunch(StorageBulkCursor& cursor, StorageShard* shard)
{
bool first;
int cmpres;
ReadBuffer nextKey, key, value;
StorageMemoKeyValue* it;
uint32_t total;
if (keyValues.GetCount() == 0)
{
cursor.SetLast(true);
return;
}
nextKey = cursor.GetNextKey();
it = keyValues.Locate(nextKey, cmpres);
total = 0;
first = true;
while (it)
{
if (!shard->RangeContains(it->GetKey()))
{
it = keyValues.Next(it);
continue;
}
if (!first && total + it->GetKey().GetLength() + it->GetValue().GetLength() > STORAGE_MEMO_BUNCH_GRAN)
break;
total += it->GetKey().GetLength() + it->GetValue().GetLength();
cursor.AppendKeyValue(it);
it = keyValues.Next(it);
first = false;
}
cursor.FinalizeKeyValues();
if (!it)
{
cursor.SetLast(true);
}
else
{
cursor.SetNextKey(it->GetKey());
cursor.SetLast(false);
}
}
//void StorageMemoChunk::SetChunkID(uint64_t chunkID_)
//{
// chunkID = chunkID_;
//}
//
//void StorageMemoChunk::SetUseBloomFilter(bool useBloomFilter_)
//{
// useBloomFilter = useBloomFilter_;
//}
uint64_t StorageMemoChunk::GetChunkID()
{
return chunkID;
}
bool StorageMemoChunk::UseBloomFilter()
{
return useBloomFilter;
}
StorageKeyValue* StorageMemoChunk::Get(ReadBuffer& key)
{
int cmpres;
StorageMemoKeyValue* it;
if (keyValues.GetCount() == 0)
return NULL;
it = keyValues.Locate<const ReadBuffer&>(key, cmpres);
if (cmpres != 0)
return NULL;
return it;
}
void StorageMemoChunk::AsyncGet(StorageAsyncGet* asyncGet)
{
StorageKeyValue* kv;
Log_Debug("StorageMemoChunk::AsyncGet");
kv = Get(asyncGet->key);
if (kv == NULL || kv->GetType() == STORAGE_KEYVALUE_TYPE_DELETE)
{
asyncGet->ret = false;
asyncGet->completed = true;
return;
}
asyncGet->value = kv->GetValue();
asyncGet->ret = true;
asyncGet->completed = true;
}
bool StorageMemoChunk::Set(ReadBuffer key, ReadBuffer value)
{
int cmpres;
StorageMemoKeyValue* it;
if (keyValues.GetCount() != 0)
{
it = keyValues.Locate<const ReadBuffer&>(key, cmpres);
if (cmpres == 0)
{
it->Set(key, value, this);
return true;
}
}
it = NewStorageMemoKeyValue();
it->Set(key, value, this);
keyValues.Insert<const ReadBuffer>(it);
return true;
}
bool StorageMemoChunk::Delete(ReadBuffer key)
{
int cmpres;
StorageMemoKeyValue* it;
if (keyValues.GetCount() != 0)
{
it = keyValues.Locate<const ReadBuffer&>(key, cmpres);
if (cmpres == 0)
{
it->Delete(key, this);
return true;
}
}
it = NewStorageMemoKeyValue();
it->Delete(key, this);
keyValues.Insert<const ReadBuffer>(it);
return true;
}
void StorageMemoChunk::RegisterLogCommand(uint64_t logSegmentID_, uint32_t logCommandID_)
{
if (minLogSegmentID == 0)
minLogSegmentID = logSegmentID_;
if (logSegmentID_ > maxLogSegmentID)
{
maxLogSegmentID = logSegmentID_;
maxLogCommandID = logCommandID_;
}
else if (logSegmentID_ == maxLogSegmentID)
{
if (logCommandID_ > maxLogCommandID)
maxLogCommandID = logCommandID_;
}
}
uint64_t StorageMemoChunk::GetMinLogSegmentID()
{
return minLogSegmentID;
}
uint64_t StorageMemoChunk::GetMaxLogSegmentID()
{
return maxLogSegmentID;
}
uint32_t StorageMemoChunk::GetMaxLogCommandID()
{
return maxLogCommandID;
}
ReadBuffer StorageMemoChunk::GetFirstKey()
{
if (keyValues.First())
return keyValues.First()->GetKey();
else
return ReadBuffer();
}
ReadBuffer StorageMemoChunk::GetLastKey()
{
if (keyValues.Last())
return keyValues.Last()->GetKey();
else
return ReadBuffer();
}
uint64_t StorageMemoChunk::GetSize()
{
return size;
}
ReadBuffer StorageMemoChunk::GetMidpoint()
{
if (keyValues.Mid())
return keyValues.Mid()->GetKey();
else
return ReadBuffer();
}
bool StorageMemoChunk::IsEmpty()
{
return (size == 0);
}
StorageFileChunk* StorageMemoChunk::RemoveFileChunk()
{
StorageFileChunk* ret;
ret = fileChunk;
fileChunk = NULL;
return ret;
}
void StorageMemoChunk::RemoveFirst()
{
StorageMemoKeyValueBlock* block;
StorageMemoKeyValue* first;
first = keyValues.First();
keyValues.Remove(first);
first->Free(this);
block = keyValueBlocks.First();
ASSERT(first >= block->keyValues && first < (block->keyValues + STORAGE_BLOCK_NUM_KEY_VALUE));
block->last++;
if (block->last == STORAGE_BLOCK_NUM_KEY_VALUE)
{
keyValueBlocks.Dequeue();
delete block;
size -= sizeof(StorageMemoKeyValueBlock);
}
}
StorageMemoKeyValue* StorageMemoChunk::NewStorageMemoKeyValue()
{
StorageMemoKeyValueBlock* block;
StorageMemoKeyValue* keyValue;
bool isNewBlockNeeded;
isNewBlockNeeded = false;
if (keyValueBlocks.GetLength() == 0)
isNewBlockNeeded = true;
else
{
block = keyValueBlocks.Last();
if (block->first == STORAGE_BLOCK_NUM_KEY_VALUE)
isNewBlockNeeded = true;
}
if (isNewBlockNeeded)
{
block = new StorageMemoKeyValueBlock;
block->next = block;
block->first = 0;
block->last = 0;
keyValueBlocks.Enqueue(block);
size += sizeof(StorageMemoKeyValueBlock);
}
keyValue = &block->keyValues[block->first];
block->first++;
return keyValue;
}
char* StorageMemoChunk::Alloc(size_t size_)
{
StorageMemoKeyValueAllocator* allocator;
StorageMemoKeyValueAllocator* prevAllocator;
char* memory;
uint32_t allocatedSize;
size_t requiredSize;
// Each allocated piece of memory is prefixed with an uint32_t offset
// from the start of the buffer of the allocator. Therefore it is
// possible to find the allocator object of a given pointer.
requiredSize = size_ + sizeof(uint32_t);
// save the last allocator to avoid fragmentation
prevAllocator = allocator = allocators.Last();
if (allocator == NULL || allocator->GetFreeSize() < requiredSize)
{
allocatedSize = MAX(requiredSize, STORAGE_MEMO_ALLOCATOR_DEFAULT_SIZE);
// avoid calling malloc twice by allocating memory and setting the pointers
memory = (char*) malloc(sizeof(StorageMemoKeyValueAllocator) + allocatedSize);
allocator = (StorageMemoKeyValueAllocator*) memory;
allocator->buffer = memory + sizeof(StorageMemoKeyValueAllocator);
allocator->size = allocatedSize;
allocator->pos = 0;
allocator->num = 0;
allocator->next = allocator;
allocator->prev = allocator;
// TODO: better strategy to avoid fragmentation
if (prevAllocator != NULL &&
prevAllocator->GetFreeSize() > STORAGE_MEMO_ALLOCATOR_MIN_SIZE &&
prevAllocator->GetFreeSize() * 2 >= requiredSize)
{
allocators.Remove(prevAllocator);
allocators.Append(allocator);
allocators.Append(prevAllocator);
}
else
allocators.Append(allocator);
size += sizeof(StorageMemoKeyValueAllocator) + allocator->size;
}
// The memory layout is the following:
//
// +---------------------
// | pos (4 bytes)
// +---------------------
// | memory (size_ bytes)
// +---------------------
//
memory = allocator->buffer + allocator->pos;
allocator->pos += sizeof(uint32_t);
*(uint32_t*) memory = (uint32_t) allocator->pos;
memory += sizeof(uint32_t);
allocator->pos += size_;
allocator->num++;
return memory;
}
void StorageMemoChunk::Free(char* buffer)
{
ReadBuffer key;
uint32_t pos;
StorageMemoKeyValueAllocator* allocator;
pos = *(uint32_t*)(buffer - sizeof(uint32_t));
allocator = (StorageMemoKeyValueAllocator*)(buffer - pos - sizeof(StorageMemoKeyValueAllocator));
allocator->num--;
if (allocator->num == 0)
{
size -= sizeof(StorageMemoKeyValueAllocator) + allocator->size;
allocators.Remove(allocator);
free(allocator);
}
}
<|endoftext|> |
<commit_before><commit_msg>Fixed storage file parsing in Linux.<commit_after><|endoftext|> |
<commit_before>/*
* Copyright (C) 2017 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <errno.h>
#include <string.h>
#include <arpa/inet.h>
#include <netdb.h>
#include <sys/socket.h>
#include <glog/logging.h>
#include <fstream>
#include <sstream>
#include "common/libs/fs/shared_select.h"
#include "common/libs/fs/shared_fd.h"
#include "host/vadb/usbip/vhci_instrument.h"
namespace vadb {
namespace usbip {
namespace {
// Device ID is specified as a concatenated pair of BUS and DEVICE id.
// Since we only export one device and our server doesn't care much about
// its number, we use the default value of BUS=1 and DEVICE=1.
// This can be set to something else and should still work, as long as
// numbers are valid in USB sense.
constexpr uint32_t kDefaultDeviceID = (1 << 16) | 1;
constexpr uint32_t kDefaultDeviceSpeed = 2;
// Subsystem and device type where VHCI driver is located.
// These values can usually be found after loading vhci-hcd module here:
// /sys/devices/platform/vhci_hcd/modalias
constexpr char kVHCISubsystem[] = "platform";
constexpr char kVHCIDevType[] = "vhci_hcd";
// Control messages.
// Attach tells thread to attach remote device.
// Detach tells thread to detach remote device.
using ControlMsgType = uint8_t;
constexpr ControlMsgType kControlAttach = 'A';
constexpr ControlMsgType kControlDetach = 'D';
constexpr ControlMsgType kControlExit = 'E';
// Port status values deducted from /sys/devices/platform/vhci_hcd/status
enum {
// kVHCIPortFree indicates the port is not currently in use.
kVHCIStatusPortFree = 4
};
} // anonymous namespace
VHCIInstrument::VHCIInstrument(const std::string& name)
: udev_(nullptr, [](udev* u) { udev_unref(u); }),
vhci_device_(nullptr,
[](udev_device* device) { udev_device_unref(device); }),
name_(name) {}
VHCIInstrument::~VHCIInstrument() {
control_write_end_->Write(&kControlExit, sizeof(kControlExit));
attach_thread_->join();
if (sys_fd_ > 0) close(sys_fd_);
}
bool VHCIInstrument::Init() {
avd::SharedFD::Pipe(&control_read_end_, &control_write_end_);
udev_.reset(udev_new());
CHECK(udev_) << "Could not create libudev context.";
vhci_device_.reset(udev_device_new_from_subsystem_sysname(
udev_.get(), kVHCISubsystem, kVHCIDevType));
if (!vhci_device_) {
LOG(ERROR) << "VHCI not available. Is the driver loaded?";
LOG(ERROR) << "Try: sudo modprobe vhci_hcd";
LOG(ERROR) << "The driver is part of linux-image-extra-`uname -r` package";
return false;
}
syspath_ = udev_device_get_syspath(vhci_device_.get());
if (!FindFreePort()) {
LOG(ERROR) << "It appears all your VHCI ports are currently occupied.";
LOG(ERROR) << "New VHCI device cannot be registered unless one of the "
<< "ports is freed.";
return false;
}
attach_thread_.reset(new std::thread([this]() { AttachThread(); }));
return true;
}
bool VHCIInstrument::FindFreePort() {
std::ifstream stat(syspath_ + "/status");
int port;
int status;
std::string everything_else;
if (!stat.is_open()) {
LOG(ERROR) << "Could not open usb-ip status file.";
return false;
}
// Skip past the header line.
std::getline(stat, everything_else);
while (stat.rdstate() == std::ios_base::goodbit) {
stat >> port >> status;
std::getline(stat, everything_else);
if (status == kVHCIStatusPortFree) {
port_ = port;
LOG(INFO) << "Using VHCI port " << port_;
return true;
}
}
return false;
}
void VHCIInstrument::TriggerAttach() {
control_write_end_->Write(&kControlAttach, sizeof(kControlAttach));
}
void VHCIInstrument::TriggerDetach() {
control_write_end_->Write(&kControlDetach, sizeof(kControlDetach));
}
void VHCIInstrument::AttachThread() {
avd::SharedFDSet rset;
// If we're attempting connection, make sure to re-try every second until
// we're successful.
timeval period = {1, 0};
// Trigger attach upon start.
bool want_attach = true;
// Indicate running operation on start.
bool is_pending = true;
while (true) {
rset.Zero();
rset.Set(control_read_end_);
// Wait until poked.
if (0 != avd::Select(&rset, nullptr, nullptr,
(is_pending ? &period : nullptr))) {
ControlMsgType request_type;
control_read_end_->Read(&request_type, sizeof(request_type));
is_pending = true;
want_attach = request_type == kControlAttach;
LOG(INFO) << (want_attach ? "Attach" : "Detach") << " triggered.";
}
// Make an attempt to re-attach. If successful, clear pending attach flag.
if (is_pending) {
if (want_attach && Attach()) {
is_pending = false;
} else if (!want_attach && Detach()) {
is_pending = false;
} else {
LOG(INFO) << (want_attach ? "Attach" : "Detach") << " unsuccessful. "
<< "Will re-try.";
sleep(1);
}
}
}
}
bool VHCIInstrument::Detach() {
// sys_fd_ is the descriptor we supplied to the system to allow it to talk to
// (remote) USB device. By closing this descriptor we effectively force close
// connection to remote USB device.
if (sys_fd_ > 0) {
close(sys_fd_);
sys_fd_ = -1;
}
std::stringstream result;
result << port_;
std::ofstream detach(syspath_ + "/detach");
if (!detach.is_open()) {
LOG(WARNING) << "Could not open VHCI detach file.";
return false;
}
detach << result.str();
return detach.rdstate() == std::ios_base::goodbit;
}
bool VHCIInstrument::Attach() {
avd::SharedFD socket =
avd::SharedFD::SocketLocalClient(name_.c_str(), true, SOCK_STREAM);
if (!socket->IsOpen()) return false;
sys_fd_ = socket->UNMANAGED_Dup();
std::stringstream result;
result << port_ << ' ' << sys_fd_ << ' ' << kDefaultDeviceID << ' '
<< kDefaultDeviceSpeed;
std::string path = syspath_ + "/attach";
std::ofstream attach(path);
if (!attach.is_open()) {
LOG(WARNING) << "Could not open VHCI attach file " << path << " ("
<< strerror(errno) << ")";
close(sys_fd_);
sys_fd_ = -1;
return false;
}
attach << result.str();
// It is unclear whether duplicate FD should remain open or not. There are
// cases supporting both assumptions, likely related to kernel version.
// Kernel 4.10 is having problems communicating with USB/IP server if the
// socket is closed after it's passed to kernel. It is a clear indication that
// the kernel requires the socket to be kept open.
bool success = attach.rdstate() == std::ios_base::goodbit;
if (!success) {
close(sys_fd_);
sys_fd_ = -1;
}
return success;
}
} // namespace usbip
} // namespace vadb
<commit_msg>Attach(vhci) after receiving heart-beat from guest<commit_after>/*
* Copyright (C) 2017 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <errno.h>
#include <string.h>
#include <arpa/inet.h>
#include <netdb.h>
#include <sys/socket.h>
#include <glog/logging.h>
#include <fstream>
#include <sstream>
#include "common/libs/fs/shared_select.h"
#include "common/libs/fs/shared_fd.h"
#include "host/vadb/usbip/vhci_instrument.h"
namespace vadb {
namespace usbip {
namespace {
// Device ID is specified as a concatenated pair of BUS and DEVICE id.
// Since we only export one device and our server doesn't care much about
// its number, we use the default value of BUS=1 and DEVICE=1.
// This can be set to something else and should still work, as long as
// numbers are valid in USB sense.
constexpr uint32_t kDefaultDeviceID = (1 << 16) | 1;
// Request Highspeed configuration. Superspeed isn't supported by vhci.
// Supported configurations are:
// 4 -> wireless
// 3 -> highspeed
// 2 -> full speed
// 1 -> low speed
// Please refer to the Kernel source tree in the following locations:
// include/uapi/linux/usb/ch9.h
// drivers/usb/usbip/vhci_sysfs.c
constexpr uint32_t kDefaultDeviceSpeed = 3;
// Subsystem and device type where VHCI driver is located.
// These values can usually be found after loading vhci-hcd module here:
// /sys/devices/platform/vhci_hcd/modalias
constexpr char kVHCISubsystem[] = "platform";
constexpr char kVHCIDevType[] = "vhci_hcd";
// Control messages.
// Attach tells thread to attach remote device.
// Detach tells thread to detach remote device.
using ControlMsgType = uint8_t;
constexpr ControlMsgType kControlAttach = 'A';
constexpr ControlMsgType kControlDetach = 'D';
constexpr ControlMsgType kControlExit = 'E';
// Port status values deducted from /sys/devices/platform/vhci_hcd/status
enum {
// kVHCIPortFree indicates the port is not currently in use.
kVHCIStatusPortFree = 4
};
} // anonymous namespace
VHCIInstrument::VHCIInstrument(const std::string& name)
: udev_(nullptr, [](udev* u) { udev_unref(u); }),
vhci_device_(nullptr,
[](udev_device* device) { udev_device_unref(device); }),
name_(name) {}
VHCIInstrument::~VHCIInstrument() {
control_write_end_->Write(&kControlExit, sizeof(kControlExit));
attach_thread_->join();
if (sys_fd_ > 0) close(sys_fd_);
}
bool VHCIInstrument::Init() {
avd::SharedFD::Pipe(&control_read_end_, &control_write_end_);
udev_.reset(udev_new());
CHECK(udev_) << "Could not create libudev context.";
vhci_device_.reset(udev_device_new_from_subsystem_sysname(
udev_.get(), kVHCISubsystem, kVHCIDevType));
if (!vhci_device_) {
LOG(ERROR) << "VHCI not available. Is the driver loaded?";
LOG(ERROR) << "Try: sudo modprobe vhci_hcd";
LOG(ERROR) << "The driver is part of linux-image-extra-`uname -r` package";
return false;
}
syspath_ = udev_device_get_syspath(vhci_device_.get());
if (!FindFreePort()) {
LOG(ERROR) << "It appears all your VHCI ports are currently occupied.";
LOG(ERROR) << "New VHCI device cannot be registered unless one of the "
<< "ports is freed.";
return false;
}
attach_thread_.reset(new std::thread([this]() { AttachThread(); }));
return true;
}
bool VHCIInstrument::FindFreePort() {
std::ifstream stat(syspath_ + "/status");
int port;
int status;
std::string everything_else;
if (!stat.is_open()) {
LOG(ERROR) << "Could not open usb-ip status file.";
return false;
}
// Skip past the header line.
std::getline(stat, everything_else);
while (stat.rdstate() == std::ios_base::goodbit) {
stat >> port >> status;
std::getline(stat, everything_else);
if (status == kVHCIStatusPortFree) {
port_ = port;
LOG(INFO) << "Using VHCI port " << port_;
return true;
}
}
return false;
}
void VHCIInstrument::TriggerAttach() {
control_write_end_->Write(&kControlAttach, sizeof(kControlAttach));
}
void VHCIInstrument::TriggerDetach() {
control_write_end_->Write(&kControlDetach, sizeof(kControlDetach));
}
void VHCIInstrument::AttachThread() {
avd::SharedFDSet rset;
// If we're attempting connection, make sure to re-try every second until
// we're successful.
timeval period = {1, 0};
// Trigger attach upon start.
bool want_attach = true;
// Operation is pending on read.
bool is_pending = false;
while (true) {
rset.Zero();
rset.Set(control_read_end_);
// Wait until poked.
if (0 != avd::Select(&rset, nullptr, nullptr,
(is_pending ? &period : nullptr))) {
ControlMsgType request_type;
control_read_end_->Read(&request_type, sizeof(request_type));
is_pending = true;
want_attach = request_type == kControlAttach;
LOG(INFO) << (want_attach ? "Attach" : "Detach") << " triggered.";
}
// Make an attempt to re-attach. If successful, clear pending attach flag.
if (is_pending) {
if (want_attach && Attach()) {
is_pending = false;
} else if (!want_attach && Detach()) {
is_pending = false;
} else {
LOG(INFO) << (want_attach ? "Attach" : "Detach") << " unsuccessful. "
<< "Will re-try.";
sleep(1);
}
}
}
}
bool VHCIInstrument::Detach() {
// sys_fd_ is the descriptor we supplied to the system to allow it to talk to
// (remote) USB device. By closing this descriptor we effectively force close
// connection to remote USB device.
if (sys_fd_ > 0) {
close(sys_fd_);
sys_fd_ = -1;
}
std::stringstream result;
result << port_;
std::ofstream detach(syspath_ + "/detach");
if (!detach.is_open()) {
LOG(WARNING) << "Could not open VHCI detach file.";
return false;
}
detach << result.str();
return detach.rdstate() == std::ios_base::goodbit;
}
bool VHCIInstrument::Attach() {
avd::SharedFD socket =
avd::SharedFD::SocketLocalClient(name_.c_str(), true, SOCK_STREAM);
if (!socket->IsOpen()) return false;
sys_fd_ = socket->UNMANAGED_Dup();
std::stringstream result;
result << port_ << ' ' << sys_fd_ << ' ' << kDefaultDeviceID << ' '
<< kDefaultDeviceSpeed;
std::string path = syspath_ + "/attach";
std::ofstream attach(path);
if (!attach.is_open()) {
LOG(WARNING) << "Could not open VHCI attach file " << path << " ("
<< strerror(errno) << ")";
close(sys_fd_);
sys_fd_ = -1;
return false;
}
attach << result.str();
// It is unclear whether duplicate FD should remain open or not. There are
// cases supporting both assumptions, likely related to kernel version.
// Kernel 4.10 is having problems communicating with USB/IP server if the
// socket is closed after it's passed to kernel. It is a clear indication that
// the kernel requires the socket to be kept open.
bool success = attach.rdstate() == std::ios_base::goodbit;
if (!success) {
close(sys_fd_);
sys_fd_ = -1;
}
return success;
}
} // namespace usbip
} // namespace vadb
<|endoftext|> |
<commit_before>// Time: O(1), per operation.
// Space: O(k), k is the capacity of cache.
#include <list>
class LRUCache {
public:
LRUCache(int capacity) : capa_(capacity) {
}
int get(int key) {
if (map_.find(key) != map_.end()) {
// It key exists, update it.
const auto value = map_[key]->second;
update(key, value);
return value;
} else {
return -1;
}
}
void set(int key, int value) {
// If cache is full while inserting, remove the last one.
if (map_.find(key) == map_.end() && list_.size() == capa_) {
auto del = list_.back(); list_.pop_back();
map_.erase(del.first);
}
update(key, value);
}
private:
list<pair<int, int>> list_; // key, value
unordered_map<int, list<pair<int, int>>::iterator> map_; // key, list iterator
int capa_;
// Update (key, iterator of (key, value)) pair
void update(int key, int value) {
auto it = map_.find(key);
if (it != map_.end()) {
list_.erase(it->second);
}
list_.emplace_front(key, value);
map_[key] = list_.begin();
}
};
<commit_msg>Update lru-cache.cpp<commit_after>// Time: O(1), per operation.
// Space: O(k), k is the capacity of cache.
#include <list>
class LRUCache {
public:
LRUCache(int capacity) : capa_(capacity) {
}
int get(int key) {
if (map_.find(key) != map_.end()) {
// It key exists, update it.
const auto value = map_[key]->second;
update(key, value);
return value;
} else {
return -1;
}
}
void put(int key, int value) {
// If cache is full while inserting, remove the last one.
if (map_.find(key) == map_.end() && list_.size() == capa_) {
auto del = list_.back(); list_.pop_back();
map_.erase(del.first);
}
update(key, value);
}
private:
list<pair<int, int>> list_; // key, value
unordered_map<int, list<pair<int, int>>::iterator> map_; // key, list iterator
int capa_;
// Update (key, iterator of (key, value)) pair
void update(int key, int value) {
auto it = map_.find(key);
if (it != map_.end()) {
list_.erase(it->second);
}
list_.emplace_front(key, value);
map_[key] = list_.begin();
}
};
<|endoftext|> |
<commit_before>/*
Copyright (c) 2013 Microsoft Corporation. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Author: Leonardo de Moura
*/
#include "util/test.h"
#include "kernel/abstract.h"
#include "kernel/kernel.h"
#include "library/expr_lt.h"
#include "library/arith/nat.h"
#include "library/arith/int.h"
#include "library/arith/real.h"
using namespace lean;
static void lt(expr const & e1, expr const & e2, bool expected) {
lean_assert(is_lt(e1, e2, false) == expected);
lean_assert(is_lt(e1, e2, false) == !(e1 == e2 || (is_lt(e2, e1, false))));
lean_assert(!(e1.hash() < e2.hash()) || (e1 < e2))
}
static void tst1() {
lt(iVal(1), iVal(1), false);
lt(iVal(1), iVal(2), true);
lt(rVal(1), rVal(1), false);
lt(rVal(1), rVal(2), true);
lt(nVal(1), nVal(1), false);
lt(nVal(1), nVal(2), true);
lt(Var(0), Var(0), false);
lt(Var(0), Var(1), true);
lt(False, True, true);
lt(False, False, false);
lt(Bool, Int, true);
lt(Const("a"), Const("b"), true);
lt(Const("a"), Const("a"), false);
lt(Var(1), Const("a"), true);
lt(Const("f")(Var(0)), Const("f")(Var(0), Const("a")), true);
lt(Const("f")(Var(0), Const("a"), Const("b")), Const("f")(Var(0), Const("a")), false);
lt(Const("f")(Var(0), Const("a")), Const("g")(Var(0), Const("a")), true);
lt(Const("f")(Var(0), Const("a")), Const("f")(Var(1), Const("a")), true);
lt(Const("f")(Var(0), Const("a")), Const("f")(Var(0), Const("b")), true);
lt(Const("f")(Var(0), Const("a")), Const("f")(Var(0), Const("a")), false);
lt(Const("g")(Var(0), Const("a")), Const("f")(Var(0), Const("a")), false);
lt(Const("f")(Var(1), Const("a")), Const("f")(Var(0), Const("a")), false);
lt(Const("f")(Var(0), Const("b")), Const("f")(Var(0), Const("a")), false);
lt(Type(level()), Type(level()+1), true);
lt(Type(level("u")), Type(level("z")), true);
lt(Type(level("u") + 1), Type(level("u") + 2), true);
lt(Type(level("u") + 1), Type(level("u") + 1), false);
lt(Type(max({level("u"), level("v")})), Type(max({level("u"), level("z")})), true);
lt(Type(max({level("u"), level("v")})), Type(max({level("u"), level("v")})), false);
lt(mk_lambda("x", Int, Var(0)), mk_lambda("y", Real, Var(0)), true);
lt(mk_lambda("x", Int, Var(0)), mk_lambda("y", Real, Var(10)), true);
lt(mk_lambda("x", Bool, Var(100)), mk_lambda("y", Real, Var(10)), true);
lt(mk_lambda("x", Int, Var(0)), mk_lambda("y", Int, Var(0)), false);
lt(mk_let("x", Int, iVal(10), Var(0)), mk_let("y", Real, rVal(10), Var(0)), true);
lt(mk_let("x", Int, iVal(10), Var(0)), mk_let("y", Int, iVal(20), Var(0)), true);
lt(mk_let("x", Int, iVal(10), Var(0)), mk_let("y", Int, iVal(10), Var(1)), true);
lt(mk_let("x", Int, iVal(10), Var(0)), mk_let("y", Int, iVal(10), Var(0)), false);
lt(mk_pi("x", Int, Int), mk_pi("y", Real, Bool), true);
lt(mk_pi("x", Int, Int), mk_pi("y", Int, Real), true);
lt(mk_pi("x", Int, Int), mk_pi("y", Int, Int), false);
local_context lctx1{mk_lift(0, 1), mk_inst(0, Const("a"))};
local_context lctx2{mk_lift(0, 1), mk_inst(0, Const("b"))};
local_context lctx3{mk_lift(3, 1), mk_inst(0, Const("a"))};
local_context lctx4{mk_lift(0, 1), mk_inst(0, Const("a")), mk_inst(0, Const("b"))};
local_context lctx5{mk_inst(0, Const("a")), mk_inst(0, Const("a"))};
lt(mk_metavar("a", lctx1), mk_metavar("b", lctx1), true);
lt(mk_metavar("a", lctx1), mk_metavar("a", lctx2), true);
lt(mk_metavar("a", lctx1), mk_metavar("a", lctx3), true);
lt(mk_metavar("a", lctx1), mk_metavar("a", lctx4), true);
lt(mk_metavar("a", lctx1), mk_metavar("a", lctx5), true);
lt(mk_metavar("a", lctx1), mk_metavar("a", lctx1), false);
}
int main() {
save_stack_info();
tst1();
return has_violations() ? 1 : 0;
}
<commit_msg>fix(tests/library/expr_lt): adjust is_lt unit tests to reflect recent modifications<commit_after>/*
Copyright (c) 2013 Microsoft Corporation. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Author: Leonardo de Moura
*/
#include "util/test.h"
#include "kernel/abstract.h"
#include "kernel/kernel.h"
#include "library/expr_lt.h"
#include "library/arith/nat.h"
#include "library/arith/int.h"
#include "library/arith/real.h"
using namespace lean;
static void lt(expr const & e1, expr const & e2, bool expected) {
lean_assert(is_lt(e1, e2, false) == expected);
lean_assert(is_lt(e1, e2, false) == !(e1 == e2 || (is_lt(e2, e1, false))));
}
static void tst1() {
lt(iVal(1), iVal(1), false);
lt(iVal(1), iVal(2), true);
lt(rVal(1), rVal(1), false);
lt(rVal(1), rVal(2), true);
lt(nVal(1), nVal(1), false);
lt(nVal(1), nVal(2), true);
lt(Var(0), Var(0), false);
lt(Var(0), Var(1), true);
lt(False, True, true);
lt(False, False, false);
lt(Bool, Int, true);
lt(Const("a"), Const("b"), true);
lt(Const("a"), Const("a"), false);
lt(Var(1), Const("a"), true);
lt(Const("f")(Var(0)), Const("f")(Var(0), Const("a")), true);
lt(Const("f")(Var(0), Const("a"), Const("b")), Const("f")(Var(0), Const("a")), false);
lt(Const("f")(Var(0), Const("a")), Const("g")(Var(0), Const("a")), true);
lt(Const("f")(Var(0), Const("a")), Const("f")(Var(1), Const("a")), true);
lt(Const("f")(Var(0), Const("a")), Const("f")(Var(0), Const("b")), true);
lt(Const("f")(Var(0), Const("a")), Const("f")(Var(0), Const("a")), false);
lt(Const("g")(Var(0), Const("a")), Const("f")(Var(0), Const("a")), false);
lt(Const("f")(Var(1), Const("a")), Const("f")(Var(0), Const("a")), false);
lt(Const("f")(Var(0), Const("b")), Const("f")(Var(0), Const("a")), false);
lt(Type(level()), Type(level()+1), true);
lt(Type(level("u")), Type(level("z")), true);
lt(Type(level("u") + 1), Type(level("u") + 2), true);
lt(Type(level("u") + 1), Type(level("u") + 1), false);
lt(Type(max({level("u"), level("v")})), Type(max({level("u"), level("z")})), true);
lt(Type(max({level("u"), level("v")})), Type(max({level("u"), level("v")})), false);
lt(mk_lambda("x", Int, Var(0)), mk_lambda("y", Real, Var(0)), true);
lt(mk_lambda("x", Int, Var(0)), mk_lambda("y", Real, Var(10)), true);
lt(mk_lambda("x", Bool, Var(100)), mk_lambda("y", Real, Var(10)), true);
lt(mk_lambda("x", Int, Var(0)), mk_lambda("y", Int, Var(0)), false);
lt(mk_let("x", Int, iVal(10), Var(0)), mk_let("y", Real, rVal(10), Var(0)), true);
lt(mk_let("x", Int, iVal(10), Var(0)), mk_let("y", Int, iVal(20), Var(0)), true);
lt(mk_let("x", Int, iVal(10), Var(0)), mk_let("y", Int, iVal(10), Var(1)), true);
lt(mk_let("x", Int, iVal(10), Var(0)), mk_let("y", Int, iVal(10), Var(0)), false);
lt(mk_pi("x", Int, Int), mk_pi("y", Real, Bool), true);
lt(mk_pi("x", Int, Int), mk_pi("y", Int, Real), true);
lt(mk_pi("x", Int, Int), mk_pi("y", Int, Int), false);
local_context lctx1{mk_lift(0, 1), mk_inst(0, Const("a"))};
local_context lctx2{mk_lift(0, 1), mk_inst(0, Const("b"))};
local_context lctx3{mk_lift(3, 1), mk_inst(0, Const("a"))};
local_context lctx4{mk_lift(0, 1), mk_inst(0, Const("a")), mk_inst(0, Const("b"))};
local_context lctx5{mk_inst(0, Const("a")), mk_inst(0, Const("a"))};
lt(mk_metavar("a", lctx1), mk_metavar("b", lctx1), true);
lt(mk_metavar("a", lctx1), mk_metavar("a", lctx2), true);
lt(mk_metavar("a", lctx1), mk_metavar("a", lctx3), true);
lt(mk_metavar("a", lctx1), mk_metavar("a", lctx4), true);
lt(mk_metavar("a", lctx1), mk_metavar("a", lctx5), true);
lt(mk_metavar("a", lctx1), mk_metavar("a", lctx1), false);
}
int main() {
save_stack_info();
tst1();
return has_violations() ? 1 : 0;
}
<|endoftext|> |
<commit_before>/* This file is part of Mapnik (c++ mapping toolkit)
*
* Copyright (C) 2015 Artem Pavlenko
*
* Mapnik is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or 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 General Public License for more details.
*
* You should have received a copy of the GNU 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.
*/
// stl
#include <iostream>
// qt
#include <QtGui>
#include <QSplitter>
#include <QTreeView>
#include <QListView>
#include <QTabWidget>
#include <QList>
#include <QItemDelegate>
#include <QSlider>
#include <QComboBox>
#include <QDoubleSpinBox>
#include <QFileDialog>
#include <QMenu>
#include <QMenuBar>
#include <QToolBar>
// mapnik
#ifndef Q_MOC_RUN // QT moc chokes on BOOST_JOIN
//#include <mapnik/config_error.hpp>
#include <mapnik/load_map.hpp>
#include <mapnik/save_map.hpp>
#include <mapnik/projection.hpp>
#include <mapnik/util/timer.hpp>
#endif
// qt
#include "mainwindow.hpp"
#include "layerlistmodel.hpp"
#include "styles_model.hpp"
#include "layerwidget.hpp"
#include "layerdelegate.hpp"
#include "about_dialog.hpp"
// boost
#include <boost/algorithm/string.hpp>
MainWindow::MainWindow()
: filename_(),
default_extent_(-20037508.3428,-20037508.3428,20037508.3428,20037508.3428)
{
mapWidget_ = new MapWidget(this);
QSplitter *splitter = new QSplitter(this);
QTabWidget *tabWidget=new QTabWidget;
layerTab_ = new LayerTab;
layerTab_->setFocusPolicy(Qt::NoFocus);
layerTab_->setIconSize(QSize(16,16));
//LayerDelegate *delegate = new LayerDelegate(this);
//layerTab_->setItemDelegate(delegate);
//layerTab_->setItemDelegate(new QItemDelegate(this));
//layerTab_->setViewMode(QListView::IconMode);
layerTab_->setFlow(QListView::TopToBottom);
tabWidget->addTab(layerTab_,tr("Layers"));
// Styles tab
styleTab_ = new StyleTab;
tabWidget->addTab(styleTab_,tr("Styles"));
splitter->addWidget(tabWidget);
splitter->addWidget(mapWidget_);
QList<int> list;
list.push_back(200);
list.push_back(600);
splitter->setSizes(list);
mapWidget_->setFocusPolicy(Qt::StrongFocus);
mapWidget_->setFocus();
//setCentralWidget(mapWidget_);
setCentralWidget(splitter);
createActions();
createMenus();
createToolBars();
createContextMenu();
setWindowTitle(tr("Mapnik Viewer"));
status=new QStatusBar(this);
status->showMessage(tr(""));
setStatusBar(status);
resize(800,600);
//connect mapview to layerlist
connect(mapWidget_, SIGNAL(mapViewChanged()),layerTab_, SLOT(update()));
// slider
connect(slider_,SIGNAL(valueChanged(int)),mapWidget_,SLOT(zoomToLevel(int)));
// renderer selector
connect(renderer_selector_,SIGNAL(currentIndexChanged(QString const&)),
mapWidget_, SLOT(updateRenderer(QString const&)));
// scale factor
connect(scale_factor_,SIGNAL(valueChanged(double)),
mapWidget_, SLOT(updateScaleFactor(double)));
//
connect(layerTab_,SIGNAL(update_mapwidget()),mapWidget_,SLOT(updateMap()));
connect(layerTab_,SIGNAL(layerSelected(int)),
mapWidget_,SLOT(layerSelected(int)));
}
MainWindow::~MainWindow()
{
delete mapWidget_;
}
void MainWindow::closeEvent(QCloseEvent* event)
{
event->accept();
}
void MainWindow::createContextMenu()
{
layerTab_->setContextMenuPolicy(Qt::ActionsContextMenu);
layerTab_->addAction(openAct);
layerTab_->addAction(layerInfo);
}
void MainWindow::open(QString const& path)
{
if (path.isNull())
{
filename_ = QFileDialog::getOpenFileName(this,tr("Open Mapnik file"),
currentPath,"*.xml");
}
else
{
filename_ = path;
}
if (!filename_.isEmpty())
{
load_map_file(filename_);
setWindowTitle(tr("%1 - Mapnik Viewer").arg(filename_));
}
}
void MainWindow::reload()
{
if (!filename_.isEmpty())
{
mapnik::box2d<double> bbox = mapWidget_->getMap()->get_current_extent();
load_map_file(filename_);
mapWidget_->zoomToBox(bbox);
setWindowTitle(tr("%1 - *Reloaded*").arg(filename_));
}
}
void MainWindow::save()
{
QString initialPath = QDir::currentPath() + "/untitled.xml";
QString filename = QFileDialog::getSaveFileName(this, tr("Save"),
initialPath,
tr("%1 Files (*.xml)")
.arg(QString("Mapnik definition")));
if (!filename.isEmpty())
{
std::cout<<"saving "<< filename.toStdString() << std::endl;
mapnik::save_map(*mapWidget_->getMap(),filename.toStdString());
}
}
void MainWindow::load_map_file(QString const& filename)
{
std::cout << "loading "<< filename.toStdString() << std::endl;
unsigned width = mapWidget_->width();
unsigned height = mapWidget_->height();
std::shared_ptr<mapnik::Map> map(new mapnik::Map(width,height));
mapWidget_->setMap(map);
try
{
mapnik::auto_cpu_timer t(std::clog, "loading map took: ");
mapnik::load_map(*map,filename.toStdString());
}
//catch (mapnik::config_error & ex)
//{
// std::cout << ex.what() << "\n";
//}
catch (...)
{
std::cerr << "Exception caught in load_map\n";
}
layerTab_->setModel(new LayerListModel(map,this));
styleTab_->setModel(new StyleModel(map,this));
zoom_all();
}
void MainWindow::zoom_to_box()
{
mapWidget_->setTool(MapWidget::ZoomToBox);
}
void MainWindow::pan()
{
mapWidget_->setTool(MapWidget::Pan);
}
void MainWindow::info()
{
mapWidget_->setTool(MapWidget::Info);
}
void MainWindow::pan_left()
{
mapWidget_->panLeft();
}
void MainWindow::pan_right()
{
mapWidget_->panRight();
}
void MainWindow::pan_up()
{
mapWidget_->panUp();
}
void MainWindow::pan_down()
{
mapWidget_->panDown();
}
void MainWindow::about()
{
about_dialog dlg;
dlg.exec();
}
void MainWindow::export_as()
{
QAction *action = qobject_cast<QAction *>(sender());
QByteArray fileFormat = action->data().toByteArray();
QString initialPath = QDir::currentPath() + "/map." + fileFormat;
QString fileName = QFileDialog::getSaveFileName(this, tr("Export As"),
initialPath,
tr("%1 Files (*.%2);;All Files (*)")
.arg(QString(fileFormat.toUpper()))
.arg(QString(fileFormat)));
if (!fileName.isEmpty())
{
QPixmap const& pix = mapWidget_->pixmap();
pix.save(fileName);
}
}
void MainWindow::print()
{
//Q_ASSERT(mapWidget_->pixmap());
//QPrintDialog dialog(&printer, this);
//if (dialog.exec()) {
// QPainter painter(&printer);
// QRect rect = painter.viewport();
// QSize size = mapWidget_->pixmap()->size();
// size.scale(rect.size(), Qt::KeepAspectRatio);
// painter.setViewport(rect.x(), rect.y(), size.width(), size.height());
// painter.setWindow(mapWidget_->pixmap()->rect());
// painter.drawPixmap(0, 0, *mapWidget_->pixmap());
//}
}
void MainWindow::createActions()
{
//exportAct = new QAction(tr("&Export as ..."),this);
//exportAct->setShortcut(tr("Ctrl+E"));
//connect(exportAct, SIGNAL(triggered()), this, SLOT(export_as()));
zoomAllAct = new QAction(QIcon(":/images/home.png"),tr("Zoom All"),this);
connect(zoomAllAct, SIGNAL(triggered()), this, SLOT(zoom_all()));
zoomBoxAct = new QAction(QIcon(":/images/zoombox.png"),tr("Zoom To Box"),this);
zoomBoxAct->setCheckable(true);
connect(zoomBoxAct, SIGNAL(triggered()), this, SLOT(zoom_to_box()));
panAct = new QAction(QIcon(":/images/pan.png"),tr("Pan"),this);
panAct->setCheckable(true);
connect(panAct, SIGNAL(triggered()), this, SLOT(pan()));
infoAct = new QAction(QIcon(":/images/info.png"),tr("Info"),this);
infoAct->setCheckable(true);
connect(infoAct, SIGNAL(triggered()), this, SLOT(info()));
toolsGroup=new QActionGroup(this);
toolsGroup->addAction(zoomBoxAct);
toolsGroup->addAction(panAct);
toolsGroup->addAction(infoAct);
zoomBoxAct->setChecked(true);
openAct=new QAction(tr("Open Map definition"),this);
connect(openAct,SIGNAL(triggered()),this,SLOT(open()));
saveAct=new QAction(tr("Save Map definition"),this);
connect(saveAct,SIGNAL(triggered()),this,SLOT(save()));
panLeftAct = new QAction(QIcon(":/images/left.png"),tr("&Pan Left"),this);
connect(panLeftAct, SIGNAL(triggered()), this, SLOT(pan_left()));
panRightAct = new QAction(QIcon(":/images/right.png"),tr("&Pan Right"),this);
connect(panRightAct, SIGNAL(triggered()), this, SLOT(pan_right()));
panUpAct = new QAction(QIcon(":/images/up.png"),tr("&Pan Up"),this);
connect(panUpAct, SIGNAL(triggered()), this, SLOT(pan_up()));
panDownAct = new QAction(QIcon(":/images/down.png"),tr("&Pan Down"),this);
connect(panDownAct, SIGNAL(triggered()), this, SLOT(pan_down()));
reloadAct = new QAction(QIcon(":/images/reload.png"),tr("Reload"),this);
connect(reloadAct, SIGNAL(triggered()), this, SLOT(reload()));
layerInfo = new QAction(QIcon(":/images/info.png"),tr("&Layer info"),layerTab_);
connect(layerInfo, SIGNAL(triggered()), layerTab_,SLOT(layerInfo()));
connect(layerTab_, SIGNAL(doubleClicked(QModelIndex const&)), layerTab_,SLOT(layerInfo2(QModelIndex const&)));
foreach (QByteArray format, QImageWriter::supportedImageFormats())
{
QString text = tr("%1...").arg(QString(format).toUpper());
QAction *action = new QAction(text, this);
action->setData(format);
connect(action, SIGNAL(triggered()), this, SLOT(export_as()));
exportAsActs.append(action);
}
printAct = new QAction(QIcon(":/images/print.png"),tr("&Print ..."),this);
printAct->setShortcut(tr("Ctrl+E"));
connect(printAct, SIGNAL(triggered()), this, SLOT(print()));
exitAct = new QAction(tr("E&xit"), this);
exitAct->setShortcut(tr("Ctrl+Q"));
connect(exitAct, SIGNAL(triggered()), this, SLOT(close()));
aboutAct = new QAction(QIcon(":/images/about.png"),tr("&About"), this);
connect(aboutAct, SIGNAL(triggered()), this, SLOT(about()));
}
void MainWindow::createMenus()
{
exportMenu = new QMenu(tr("&Export As"), this);
foreach (QAction *action, exportAsActs)
exportMenu->addAction(action);
fileMenu = new QMenu(tr("&File"),this);
fileMenu->addAction(openAct);
fileMenu->addAction(saveAct);
fileMenu->addMenu(exportMenu);
fileMenu->addAction(printAct);
fileMenu->addSeparator();
fileMenu->addAction(exitAct);
menuBar()->addMenu(fileMenu);
helpMenu = new QMenu(tr("&Help"), this);
helpMenu->addAction(aboutAct);
menuBar()->addMenu(helpMenu);
}
void MainWindow::createToolBars()
{
fileToolBar = addToolBar(tr("Actions"));
fileToolBar->addAction(zoomAllAct);
fileToolBar->addAction(zoomBoxAct);
fileToolBar->addAction(panAct);
fileToolBar->addAction(panLeftAct);
fileToolBar->addAction(panRightAct);
fileToolBar->addAction(panUpAct);
fileToolBar->addAction(panDownAct);
fileToolBar->addAction(infoAct);
fileToolBar->addAction(reloadAct);
fileToolBar->addAction(printAct);
renderer_selector_ = new QComboBox(fileToolBar);
renderer_selector_->setFocusPolicy(Qt::NoFocus);
renderer_selector_->addItem("AGG");
#ifdef HAVE_CAIRO
renderer_selector_->addItem("Cairo");
#endif
renderer_selector_->addItem("Grid");
fileToolBar->addWidget(renderer_selector_);
scale_factor_ = new QDoubleSpinBox(fileToolBar);
scale_factor_->setMinimum(0.1);
scale_factor_->setMaximum(5.0);
scale_factor_->setSingleStep(0.1);
scale_factor_->setValue(1.0);
fileToolBar->addWidget(scale_factor_);
slider_ = new QSlider(Qt::Horizontal,fileToolBar);
slider_->setRange(1,18);
slider_->setTickPosition(QSlider::TicksBelow);
slider_->setTickInterval(1);
slider_->setTracking(false);
fileToolBar->addWidget(slider_);
fileToolBar->addAction(aboutAct);
}
void MainWindow::set_default_extent(double x0,double y0, double x1, double y1)
{
try
{
std::shared_ptr<mapnik::Map> map_ptr = mapWidget_->getMap();
if (map_ptr)
{
mapnik::projection prj(map_ptr->srs());
prj.forward(x0,y0);
prj.forward(x1,y1);
default_extent_=mapnik::box2d<double>(x0,y0,x1,y1);
mapWidget_->zoomToBox(default_extent_);
std::cout << "SET DEFAULT EXT\n";
}
}
catch (...) {}
}
void MainWindow::set_scaling_factor(double scaling_factor)
{
mapWidget_->set_scaling_factor(scaling_factor);
}
void MainWindow::zoom_all()
{
std::shared_ptr<mapnik::Map> map_ptr = mapWidget_->getMap();
if (map_ptr)
{
map_ptr->zoom_all();
mapnik::box2d<double> const& ext = map_ptr->get_current_extent();
mapWidget_->zoomToBox(ext);
}
}
std::shared_ptr<mapnik::Map> MainWindow::get_map()
{
return mapWidget_->getMap();
}
<commit_msg>catch std::exception<commit_after>/* This file is part of Mapnik (c++ mapping toolkit)
*
* Copyright (C) 2015 Artem Pavlenko
*
* Mapnik is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or 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 General Public License for more details.
*
* You should have received a copy of the GNU 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.
*/
// stl
#include <iostream>
// qt
#include <QtGui>
#include <QSplitter>
#include <QTreeView>
#include <QListView>
#include <QTabWidget>
#include <QList>
#include <QItemDelegate>
#include <QSlider>
#include <QComboBox>
#include <QDoubleSpinBox>
#include <QFileDialog>
#include <QMenu>
#include <QMenuBar>
#include <QToolBar>
// mapnik
#ifndef Q_MOC_RUN // QT moc chokes on BOOST_JOIN
//#include <mapnik/config_error.hpp>
#include <mapnik/load_map.hpp>
#include <mapnik/save_map.hpp>
#include <mapnik/projection.hpp>
#include <mapnik/util/timer.hpp>
#endif
// qt
#include "mainwindow.hpp"
#include "layerlistmodel.hpp"
#include "styles_model.hpp"
#include "layerwidget.hpp"
#include "layerdelegate.hpp"
#include "about_dialog.hpp"
// boost
#include <boost/algorithm/string.hpp>
MainWindow::MainWindow()
: filename_(),
default_extent_(-20037508.3428,-20037508.3428,20037508.3428,20037508.3428)
{
mapWidget_ = new MapWidget(this);
QSplitter *splitter = new QSplitter(this);
QTabWidget *tabWidget=new QTabWidget;
layerTab_ = new LayerTab;
layerTab_->setFocusPolicy(Qt::NoFocus);
layerTab_->setIconSize(QSize(16,16));
//LayerDelegate *delegate = new LayerDelegate(this);
//layerTab_->setItemDelegate(delegate);
//layerTab_->setItemDelegate(new QItemDelegate(this));
//layerTab_->setViewMode(QListView::IconMode);
layerTab_->setFlow(QListView::TopToBottom);
tabWidget->addTab(layerTab_,tr("Layers"));
// Styles tab
styleTab_ = new StyleTab;
tabWidget->addTab(styleTab_,tr("Styles"));
splitter->addWidget(tabWidget);
splitter->addWidget(mapWidget_);
QList<int> list;
list.push_back(200);
list.push_back(600);
splitter->setSizes(list);
mapWidget_->setFocusPolicy(Qt::StrongFocus);
mapWidget_->setFocus();
//setCentralWidget(mapWidget_);
setCentralWidget(splitter);
createActions();
createMenus();
createToolBars();
createContextMenu();
setWindowTitle(tr("Mapnik Viewer"));
status=new QStatusBar(this);
status->showMessage(tr(""));
setStatusBar(status);
resize(800,600);
//connect mapview to layerlist
connect(mapWidget_, SIGNAL(mapViewChanged()),layerTab_, SLOT(update()));
// slider
connect(slider_,SIGNAL(valueChanged(int)),mapWidget_,SLOT(zoomToLevel(int)));
// renderer selector
connect(renderer_selector_,SIGNAL(currentIndexChanged(QString const&)),
mapWidget_, SLOT(updateRenderer(QString const&)));
// scale factor
connect(scale_factor_,SIGNAL(valueChanged(double)),
mapWidget_, SLOT(updateScaleFactor(double)));
//
connect(layerTab_,SIGNAL(update_mapwidget()),mapWidget_,SLOT(updateMap()));
connect(layerTab_,SIGNAL(layerSelected(int)),
mapWidget_,SLOT(layerSelected(int)));
}
MainWindow::~MainWindow()
{
delete mapWidget_;
}
void MainWindow::closeEvent(QCloseEvent* event)
{
event->accept();
}
void MainWindow::createContextMenu()
{
layerTab_->setContextMenuPolicy(Qt::ActionsContextMenu);
layerTab_->addAction(openAct);
layerTab_->addAction(layerInfo);
}
void MainWindow::open(QString const& path)
{
if (path.isNull())
{
filename_ = QFileDialog::getOpenFileName(this,tr("Open Mapnik file"),
currentPath,"*.xml");
}
else
{
filename_ = path;
}
if (!filename_.isEmpty())
{
load_map_file(filename_);
setWindowTitle(tr("%1 - Mapnik Viewer").arg(filename_));
}
}
void MainWindow::reload()
{
if (!filename_.isEmpty())
{
mapnik::box2d<double> bbox = mapWidget_->getMap()->get_current_extent();
load_map_file(filename_);
mapWidget_->zoomToBox(bbox);
setWindowTitle(tr("%1 - *Reloaded*").arg(filename_));
}
}
void MainWindow::save()
{
QString initialPath = QDir::currentPath() + "/untitled.xml";
QString filename = QFileDialog::getSaveFileName(this, tr("Save"),
initialPath,
tr("%1 Files (*.xml)")
.arg(QString("Mapnik definition")));
if (!filename.isEmpty())
{
std::cout<<"saving "<< filename.toStdString() << std::endl;
mapnik::save_map(*mapWidget_->getMap(),filename.toStdString());
}
}
void MainWindow::load_map_file(QString const& filename)
{
std::cout << "loading "<< filename.toStdString() << std::endl;
unsigned width = mapWidget_->width();
unsigned height = mapWidget_->height();
std::shared_ptr<mapnik::Map> map(new mapnik::Map(width,height));
mapWidget_->setMap(map);
try
{
mapnik::auto_cpu_timer t(std::clog, "loading map took: ");
mapnik::load_map(*map,filename.toStdString());
}
catch (std::exception & ex)
{
std::cout << ex.what() << "\n";
}
catch (...)
{
std::cerr << "Exception caught in load_map\n";
}
layerTab_->setModel(new LayerListModel(map,this));
styleTab_->setModel(new StyleModel(map,this));
zoom_all();
}
void MainWindow::zoom_to_box()
{
mapWidget_->setTool(MapWidget::ZoomToBox);
}
void MainWindow::pan()
{
mapWidget_->setTool(MapWidget::Pan);
}
void MainWindow::info()
{
mapWidget_->setTool(MapWidget::Info);
}
void MainWindow::pan_left()
{
mapWidget_->panLeft();
}
void MainWindow::pan_right()
{
mapWidget_->panRight();
}
void MainWindow::pan_up()
{
mapWidget_->panUp();
}
void MainWindow::pan_down()
{
mapWidget_->panDown();
}
void MainWindow::about()
{
about_dialog dlg;
dlg.exec();
}
void MainWindow::export_as()
{
QAction *action = qobject_cast<QAction *>(sender());
QByteArray fileFormat = action->data().toByteArray();
QString initialPath = QDir::currentPath() + "/map." + fileFormat;
QString fileName = QFileDialog::getSaveFileName(this, tr("Export As"),
initialPath,
tr("%1 Files (*.%2);;All Files (*)")
.arg(QString(fileFormat.toUpper()))
.arg(QString(fileFormat)));
if (!fileName.isEmpty())
{
QPixmap const& pix = mapWidget_->pixmap();
pix.save(fileName);
}
}
void MainWindow::print()
{
//Q_ASSERT(mapWidget_->pixmap());
//QPrintDialog dialog(&printer, this);
//if (dialog.exec()) {
// QPainter painter(&printer);
// QRect rect = painter.viewport();
// QSize size = mapWidget_->pixmap()->size();
// size.scale(rect.size(), Qt::KeepAspectRatio);
// painter.setViewport(rect.x(), rect.y(), size.width(), size.height());
// painter.setWindow(mapWidget_->pixmap()->rect());
// painter.drawPixmap(0, 0, *mapWidget_->pixmap());
//}
}
void MainWindow::createActions()
{
//exportAct = new QAction(tr("&Export as ..."),this);
//exportAct->setShortcut(tr("Ctrl+E"));
//connect(exportAct, SIGNAL(triggered()), this, SLOT(export_as()));
zoomAllAct = new QAction(QIcon(":/images/home.png"),tr("Zoom All"),this);
connect(zoomAllAct, SIGNAL(triggered()), this, SLOT(zoom_all()));
zoomBoxAct = new QAction(QIcon(":/images/zoombox.png"),tr("Zoom To Box"),this);
zoomBoxAct->setCheckable(true);
connect(zoomBoxAct, SIGNAL(triggered()), this, SLOT(zoom_to_box()));
panAct = new QAction(QIcon(":/images/pan.png"),tr("Pan"),this);
panAct->setCheckable(true);
connect(panAct, SIGNAL(triggered()), this, SLOT(pan()));
infoAct = new QAction(QIcon(":/images/info.png"),tr("Info"),this);
infoAct->setCheckable(true);
connect(infoAct, SIGNAL(triggered()), this, SLOT(info()));
toolsGroup=new QActionGroup(this);
toolsGroup->addAction(zoomBoxAct);
toolsGroup->addAction(panAct);
toolsGroup->addAction(infoAct);
zoomBoxAct->setChecked(true);
openAct=new QAction(tr("Open Map definition"),this);
connect(openAct,SIGNAL(triggered()),this,SLOT(open()));
saveAct=new QAction(tr("Save Map definition"),this);
connect(saveAct,SIGNAL(triggered()),this,SLOT(save()));
panLeftAct = new QAction(QIcon(":/images/left.png"),tr("&Pan Left"),this);
connect(panLeftAct, SIGNAL(triggered()), this, SLOT(pan_left()));
panRightAct = new QAction(QIcon(":/images/right.png"),tr("&Pan Right"),this);
connect(panRightAct, SIGNAL(triggered()), this, SLOT(pan_right()));
panUpAct = new QAction(QIcon(":/images/up.png"),tr("&Pan Up"),this);
connect(panUpAct, SIGNAL(triggered()), this, SLOT(pan_up()));
panDownAct = new QAction(QIcon(":/images/down.png"),tr("&Pan Down"),this);
connect(panDownAct, SIGNAL(triggered()), this, SLOT(pan_down()));
reloadAct = new QAction(QIcon(":/images/reload.png"),tr("Reload"),this);
connect(reloadAct, SIGNAL(triggered()), this, SLOT(reload()));
layerInfo = new QAction(QIcon(":/images/info.png"),tr("&Layer info"),layerTab_);
connect(layerInfo, SIGNAL(triggered()), layerTab_,SLOT(layerInfo()));
connect(layerTab_, SIGNAL(doubleClicked(QModelIndex const&)), layerTab_,SLOT(layerInfo2(QModelIndex const&)));
foreach (QByteArray format, QImageWriter::supportedImageFormats())
{
QString text = tr("%1...").arg(QString(format).toUpper());
QAction *action = new QAction(text, this);
action->setData(format);
connect(action, SIGNAL(triggered()), this, SLOT(export_as()));
exportAsActs.append(action);
}
printAct = new QAction(QIcon(":/images/print.png"),tr("&Print ..."),this);
printAct->setShortcut(tr("Ctrl+E"));
connect(printAct, SIGNAL(triggered()), this, SLOT(print()));
exitAct = new QAction(tr("E&xit"), this);
exitAct->setShortcut(tr("Ctrl+Q"));
connect(exitAct, SIGNAL(triggered()), this, SLOT(close()));
aboutAct = new QAction(QIcon(":/images/about.png"),tr("&About"), this);
connect(aboutAct, SIGNAL(triggered()), this, SLOT(about()));
}
void MainWindow::createMenus()
{
exportMenu = new QMenu(tr("&Export As"), this);
foreach (QAction *action, exportAsActs)
exportMenu->addAction(action);
fileMenu = new QMenu(tr("&File"),this);
fileMenu->addAction(openAct);
fileMenu->addAction(saveAct);
fileMenu->addMenu(exportMenu);
fileMenu->addAction(printAct);
fileMenu->addSeparator();
fileMenu->addAction(exitAct);
menuBar()->addMenu(fileMenu);
helpMenu = new QMenu(tr("&Help"), this);
helpMenu->addAction(aboutAct);
menuBar()->addMenu(helpMenu);
}
void MainWindow::createToolBars()
{
fileToolBar = addToolBar(tr("Actions"));
fileToolBar->addAction(zoomAllAct);
fileToolBar->addAction(zoomBoxAct);
fileToolBar->addAction(panAct);
fileToolBar->addAction(panLeftAct);
fileToolBar->addAction(panRightAct);
fileToolBar->addAction(panUpAct);
fileToolBar->addAction(panDownAct);
fileToolBar->addAction(infoAct);
fileToolBar->addAction(reloadAct);
fileToolBar->addAction(printAct);
renderer_selector_ = new QComboBox(fileToolBar);
renderer_selector_->setFocusPolicy(Qt::NoFocus);
renderer_selector_->addItem("AGG");
#ifdef HAVE_CAIRO
renderer_selector_->addItem("Cairo");
#endif
renderer_selector_->addItem("Grid");
fileToolBar->addWidget(renderer_selector_);
scale_factor_ = new QDoubleSpinBox(fileToolBar);
scale_factor_->setMinimum(0.1);
scale_factor_->setMaximum(5.0);
scale_factor_->setSingleStep(0.1);
scale_factor_->setValue(1.0);
fileToolBar->addWidget(scale_factor_);
slider_ = new QSlider(Qt::Horizontal,fileToolBar);
slider_->setRange(1,18);
slider_->setTickPosition(QSlider::TicksBelow);
slider_->setTickInterval(1);
slider_->setTracking(false);
fileToolBar->addWidget(slider_);
fileToolBar->addAction(aboutAct);
}
void MainWindow::set_default_extent(double x0,double y0, double x1, double y1)
{
try
{
std::shared_ptr<mapnik::Map> map_ptr = mapWidget_->getMap();
if (map_ptr)
{
mapnik::projection prj(map_ptr->srs());
prj.forward(x0,y0);
prj.forward(x1,y1);
default_extent_=mapnik::box2d<double>(x0,y0,x1,y1);
mapWidget_->zoomToBox(default_extent_);
std::cout << "SET DEFAULT EXT\n";
}
}
catch (...) {}
}
void MainWindow::set_scaling_factor(double scaling_factor)
{
mapWidget_->set_scaling_factor(scaling_factor);
}
void MainWindow::zoom_all()
{
std::shared_ptr<mapnik::Map> map_ptr = mapWidget_->getMap();
if (map_ptr)
{
map_ptr->zoom_all();
mapnik::box2d<double> const& ext = map_ptr->get_current_extent();
mapWidget_->zoomToBox(ext);
}
}
std::shared_ptr<mapnik::Map> MainWindow::get_map()
{
return mapWidget_->getMap();
}
<|endoftext|> |
<commit_before>/*
* Copyright (c) 2015, Cryptonomex, Inc.
* All rights reserved.
*
* This source code is provided for evaluation in private test networks only, until September 8, 2015. After this date, this license expires and
* the code may not be used, modified or distributed for any purpose. Redistribution and use in source and binary forms, with or without modification,
* are permitted until September 8, 2015, provided that the following conditions are met:
*
* 1. The code and/or derivative works are used only for private test networks consisting of no more than 10 P2P nodes.
*
* 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.
*/
#pragma once
#include <graphene/chain/types.hpp>
#include <graphene/chain/operations.hpp>
#include <numeric>
namespace graphene { namespace chain {
/**
* @defgroup transactions Transactions
*
* All transactions are sets of operations that must be applied atomically. Transactions must refer to a recent
* block that defines the context of the operation so that they assert a known binding to the object id's referenced
* in the transaction.
*
* Rather than specify a full block number, we only specify the lower 16 bits of the block number which means you
* can reference any block within the last 65,536 blocks which is 3.5 days with a 5 second block interval or 18
* hours with a 1 second interval.
*
* All transactions must expire so that the network does not have to maintain a permanent record of all transactions
* ever published. There are two accepted ways to specify the transaction's expiration time. The first is to choose
* a reference block, which is generally the most recent block the wallet is aware of when it signs the transaction,
* and specify a number of block intervals after the reference block until the transaction expires. The second
* expiration mechanism is to explicitly specify a timestamp of expiration.
*
* Note: The number of block intervals is different than the number of blocks. In effect the maximum period that a
* transaction is theoretically valid is 18 hours (1 sec interval) to 3.5 days (5 sec interval) if the reference
* block was the most recent block.
*
* If a transaction is to expire after a number of block intervals from a reference block, the reference block
* should be identified in the transaction header using the @ref ref_block_num, @ref ref_block_prefix, and @ref
* relative_expiration fields. If the transaction is instead to expire at an absolute timestamp, @ref
* ref_block_prefix should be treated as a 32-bit timestamp of the expiration time, and @ref ref_block_num and @ref
* relative_expiration must both be set to zero.
*
* The block prefix is the first 4 bytes of the block hash of the reference block number, which is the second 4
* bytes of the @ref block_id_type (the first 4 bytes of the block ID are the block number)
*
* Note: A transaction which selects a reference block cannot be migrated between forks outside the period of
* ref_block_num.time to (ref_block_num.time + rel_exp * interval). This fact can be used to protect market orders
* which should specify a relatively short re-org window of perhaps less than 1 minute. Normal payments should
* probably have a longer re-org window to ensure their transaction can still go through in the event of a momentary
* disruption in service.
*
* @note It is not recommended to set the @ref ref_block_num, @ref ref_block_prefix, and @ref relative_expiration
* fields manually. Call the appropriate overload of @ref set_expiration instead.
*
* @{
*/
/**
* @brief groups operations that should be applied atomically
*/
struct transaction
{
/**
* Least significant 16 bits from the reference block number. If @ref relative_expiration is zero, this field
* must be zero as well.
*/
uint16_t ref_block_num = 0;
/**
* The first non-block-number 32-bits of the reference block ID. Recall that block IDs have 32 bits of block
* number followed by the actual block hash, so this field should be set using the second 32 bits in the
* @ref block_id_type
*/
uint32_t ref_block_prefix = 0;
/**
* This field specifies the number of block intervals after the reference block until this transaction becomes
* invalid. If this field is set to zero, the @ref ref_block_prefix is interpreted as an absolute timestamp of
* the time the transaction becomes invalid.
*/
uint16_t relative_expiration = 1;
vector<operation> operations;
/// Calculate the digest for a transaction with a reference block
/// @param ref_block_id Full block ID of the reference block
digest_type digest(const block_id_type& ref_block_id)const;
/// Calculate the digest for a transaction with an absolute expiration time
digest_type digest()const;
transaction_id_type id()const;
void validate() const;
void set_expiration( fc::time_point_sec expiration_time )
{
ref_block_num = 0;
relative_expiration = 0;
ref_block_prefix = expiration_time.sec_since_epoch();
block_id_cache.reset();
}
void set_expiration( const block_id_type& reference_block, unsigned_int lifetime_intervals = 3 )
{
ref_block_num = ntohl(reference_block._hash[0]);
ref_block_prefix = reference_block._hash[1];
relative_expiration = lifetime_intervals;
block_id_cache = reference_block;
}
/// visit all operations
template<typename Visitor>
void visit( Visitor&& visitor )
{
for( auto& op : operations )
op.visit( std::forward<Visitor>( visitor ) );
}
template<typename Visitor>
void visit( Visitor&& visitor )const
{
for( auto& op : operations )
op.visit( std::forward<Visitor>( visitor ) );
}
protected:
// Intentionally unreflected: does not go on wire
optional<block_id_type> block_id_cache;
};
/**
* @brief adds a signature to a transaction
*/
struct signed_transaction : public transaction
{
signed_transaction( const transaction& trx = transaction() )
: transaction(trx){}
void sign( const private_key_type& key );
vector<signature_type> signatures;
/// Removes all operations and signatures
void clear() { operations.clear(); signatures.clear(); }
};
/**
* @brief captures the result of evaluating the operations contained in the transaction
*
* When processing a transaction some operations generate
* new object IDs and these IDs cannot be known until the
* transaction is actually included into a block. When a
* block is produced these new ids are captured and included
* with every transaction. The index in operation_results should
* correspond to the same index in operations.
*
* If an operation did not create any new object IDs then 0
* should be returned.
*/
struct processed_transaction : public signed_transaction
{
processed_transaction( const signed_transaction& trx = signed_transaction() )
: signed_transaction(trx){}
vector<operation_result> operation_results;
digest_type merkle_digest()const;
};
/// @} transactions group
} }
FC_REFLECT( graphene::chain::transaction, (ref_block_num)(ref_block_prefix)(relative_expiration)(operations) )
FC_REFLECT_DERIVED( graphene::chain::signed_transaction, (graphene::chain::transaction), (signatures) )
FC_REFLECT_DERIVED( graphene::chain::processed_transaction, (graphene::chain::signed_transaction), (operation_results) )
<commit_msg>Add missing include for htonl on linux, #125<commit_after>/*
* Copyright (c) 2015, Cryptonomex, Inc.
* All rights reserved.
*
* This source code is provided for evaluation in private test networks only, until September 8, 2015. After this date, this license expires and
* the code may not be used, modified or distributed for any purpose. Redistribution and use in source and binary forms, with or without modification,
* are permitted until September 8, 2015, provided that the following conditions are met:
*
* 1. The code and/or derivative works are used only for private test networks consisting of no more than 10 P2P nodes.
*
* 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.
*/
#pragma once
#include <graphene/chain/types.hpp>
#include <graphene/chain/operations.hpp>
#include <numeric>
#include <arpa/inet.h> // for htonl
namespace graphene { namespace chain {
/**
* @defgroup transactions Transactions
*
* All transactions are sets of operations that must be applied atomically. Transactions must refer to a recent
* block that defines the context of the operation so that they assert a known binding to the object id's referenced
* in the transaction.
*
* Rather than specify a full block number, we only specify the lower 16 bits of the block number which means you
* can reference any block within the last 65,536 blocks which is 3.5 days with a 5 second block interval or 18
* hours with a 1 second interval.
*
* All transactions must expire so that the network does not have to maintain a permanent record of all transactions
* ever published. There are two accepted ways to specify the transaction's expiration time. The first is to choose
* a reference block, which is generally the most recent block the wallet is aware of when it signs the transaction,
* and specify a number of block intervals after the reference block until the transaction expires. The second
* expiration mechanism is to explicitly specify a timestamp of expiration.
*
* Note: The number of block intervals is different than the number of blocks. In effect the maximum period that a
* transaction is theoretically valid is 18 hours (1 sec interval) to 3.5 days (5 sec interval) if the reference
* block was the most recent block.
*
* If a transaction is to expire after a number of block intervals from a reference block, the reference block
* should be identified in the transaction header using the @ref ref_block_num, @ref ref_block_prefix, and @ref
* relative_expiration fields. If the transaction is instead to expire at an absolute timestamp, @ref
* ref_block_prefix should be treated as a 32-bit timestamp of the expiration time, and @ref ref_block_num and @ref
* relative_expiration must both be set to zero.
*
* The block prefix is the first 4 bytes of the block hash of the reference block number, which is the second 4
* bytes of the @ref block_id_type (the first 4 bytes of the block ID are the block number)
*
* Note: A transaction which selects a reference block cannot be migrated between forks outside the period of
* ref_block_num.time to (ref_block_num.time + rel_exp * interval). This fact can be used to protect market orders
* which should specify a relatively short re-org window of perhaps less than 1 minute. Normal payments should
* probably have a longer re-org window to ensure their transaction can still go through in the event of a momentary
* disruption in service.
*
* @note It is not recommended to set the @ref ref_block_num, @ref ref_block_prefix, and @ref relative_expiration
* fields manually. Call the appropriate overload of @ref set_expiration instead.
*
* @{
*/
/**
* @brief groups operations that should be applied atomically
*/
struct transaction
{
/**
* Least significant 16 bits from the reference block number. If @ref relative_expiration is zero, this field
* must be zero as well.
*/
uint16_t ref_block_num = 0;
/**
* The first non-block-number 32-bits of the reference block ID. Recall that block IDs have 32 bits of block
* number followed by the actual block hash, so this field should be set using the second 32 bits in the
* @ref block_id_type
*/
uint32_t ref_block_prefix = 0;
/**
* This field specifies the number of block intervals after the reference block until this transaction becomes
* invalid. If this field is set to zero, the @ref ref_block_prefix is interpreted as an absolute timestamp of
* the time the transaction becomes invalid.
*/
uint16_t relative_expiration = 1;
vector<operation> operations;
/// Calculate the digest for a transaction with a reference block
/// @param ref_block_id Full block ID of the reference block
digest_type digest(const block_id_type& ref_block_id)const;
/// Calculate the digest for a transaction with an absolute expiration time
digest_type digest()const;
transaction_id_type id()const;
void validate() const;
void set_expiration( fc::time_point_sec expiration_time )
{
ref_block_num = 0;
relative_expiration = 0;
ref_block_prefix = expiration_time.sec_since_epoch();
block_id_cache.reset();
}
void set_expiration( const block_id_type& reference_block, unsigned_int lifetime_intervals = 3 )
{
ref_block_num = ntohl(reference_block._hash[0]);
ref_block_prefix = reference_block._hash[1];
relative_expiration = lifetime_intervals;
block_id_cache = reference_block;
}
/// visit all operations
template<typename Visitor>
void visit( Visitor&& visitor )
{
for( auto& op : operations )
op.visit( std::forward<Visitor>( visitor ) );
}
template<typename Visitor>
void visit( Visitor&& visitor )const
{
for( auto& op : operations )
op.visit( std::forward<Visitor>( visitor ) );
}
protected:
// Intentionally unreflected: does not go on wire
optional<block_id_type> block_id_cache;
};
/**
* @brief adds a signature to a transaction
*/
struct signed_transaction : public transaction
{
signed_transaction( const transaction& trx = transaction() )
: transaction(trx){}
void sign( const private_key_type& key );
vector<signature_type> signatures;
/// Removes all operations and signatures
void clear() { operations.clear(); signatures.clear(); }
};
/**
* @brief captures the result of evaluating the operations contained in the transaction
*
* When processing a transaction some operations generate
* new object IDs and these IDs cannot be known until the
* transaction is actually included into a block. When a
* block is produced these new ids are captured and included
* with every transaction. The index in operation_results should
* correspond to the same index in operations.
*
* If an operation did not create any new object IDs then 0
* should be returned.
*/
struct processed_transaction : public signed_transaction
{
processed_transaction( const signed_transaction& trx = signed_transaction() )
: signed_transaction(trx){}
vector<operation_result> operation_results;
digest_type merkle_digest()const;
};
/// @} transactions group
} }
FC_REFLECT( graphene::chain::transaction, (ref_block_num)(ref_block_prefix)(relative_expiration)(operations) )
FC_REFLECT_DERIVED( graphene::chain::signed_transaction, (graphene::chain::transaction), (signatures) )
FC_REFLECT_DERIVED( graphene::chain::processed_transaction, (graphene::chain::signed_transaction), (operation_results) )
<|endoftext|> |
<commit_before> ///////////////////////////////////////////////////////////////////////////
///\file AddTaskEMCALPhotonIsolation.C
///\brief Configuration of AliAnalysisTaskEMCALPhotonIsolation
///
/// Version to be used in lego train for testing on pp@7TeV
///
/// \author Lucile Ronflette <lucile.ronflette@cern.ch>, SUBATECH, Nantes
/// \author Davide Francesco Lodato <davide.francesco.lodato@cern.ch>, Utrecht University
/// \author Marco Marquard <marco.marquard@cern.ch>, University Frankfurt am Main
///////////////////////////////////////////////////////////////////////////
AliAnalysisTaskEMCALPhotonIsolation* AddTaskEMCALPhotonIsolation(
const char* periodstr = "LHC11c",
const char* ntracks = "EmcalTracks",
const char* nclusters = "EmcCaloClusters",
const UInt_t pSel = AliVEvent::kEMC7,
const TString dType = "ESD",
const Bool_t bHisto = kTRUE,
const Int_t iOutput = 0,
const Bool_t bIsMC = kFALSE,
const Bool_t bMCNormalization = kFALSE,
const Bool_t bNLMCut = kFALSE,
const Int_t NLMCut = 0,
const Double_t minPtCutCluster = 0.3,
const Double_t EtIso = 2.,
const Int_t iIsoMethod = 1,
const Int_t iEtIsoMethod = 0,
const Int_t iUEMethod = 1,
const Bool_t bUseofTPC = kFALSE,
const Double_t TMdeta = 0.02,
const Double_t TMdphi = 0.03,
const Bool_t bTMClusterRejection = kTRUE,
const Bool_t bTMClusterRejectionInCone = kTRUE,
const Float_t iIsoConeRadius = 0.4,
const Bool_t iSmearingSS = kFALSE,
const Float_t iWidthSSsmear = 0.,
const Float_t iMean_SSsmear = 0.,
const Bool_t iExtraIsoCuts = kFALSE,
const Bool_t i_pPb = kFALSE,
const Bool_t isQA = kFALSE,
TString configBasePath = "",
const Int_t bWhichToSmear = 0,
const Int_t minNLM = 1,
const Double_t TMdetaIso = 0.02,
const Double_t TMdphiIso = 0.03,
const Bool_t bmcTruth = kTRUE,
const Bool_t isLCAnalysis = kFALSE,
TString L1triggerName = ""
)
{
Printf("Preparing neutral cluster analysis\n");
// #### Define manager and data container names
AliAnalysisManager *manager = AliAnalysisManager::GetAnalysisManager();
if(!manager){
::Error("AddTaskEMCALPhotonIsolation", "No analysis manager to connect to.");
return NULL;
}
printf("Creating container name for cluster analysis\n");
TString myContName("");
if(bIsMC){
myContName = Form("Analysis_Neutrals_MC");
}
else{
myContName = Form("Analysis_Neutrals");
}
if(L1triggerName.Contains("EG1") || L1triggerName.Contains("EGA1")){
L1triggerName = "EG1";
}
else if(L1triggerName.Contains("EG2") || L1triggerName.Contains("EGA2")){
L1triggerName = "EG2";
}
else{
L1triggerName = "";
}
if(L1triggerName != ""){
myContName.Append(Form("%s_TM_%s_CPVe%.2lf_CPVp%.2lf_IsoMet%d_EtIsoMet%d_UEMet%d_TPCbound_%s_IsoConeR%.1f_NLMCut_%s_minNLM%d_maxNLM%d_SSsmear_%s_Width%.3f_Mean_%.3f_PureIso_%s_WhichSmear_%d_Trigger_%s",isLCAnalysis?"_LC_Yes":"",bTMClusterRejection? "On" :"Off", TMdeta , TMdphi ,iIsoMethod,iEtIsoMethod,iUEMethod,bUseofTPC ? "Yes" : "No",iIsoConeRadius,bNLMCut ? "On": "Off",minNLM, NLMCut, iSmearingSS ? "On":"Off",iWidthSSsmear,iMean_SSsmear,iExtraIsoCuts?"On":"Off",bWhichToSmear,L1triggerName.Data()));
}
else{
myContName.Append(Form("%s_TM_%s_CPVe%.2lf_CPVp%.2lf_IsoMet%d_EtIsoMet%d_UEMet%d_TPCbound_%s_IsoConeR%.1f_NLMCut_%s_minNLM%d_maxNLM%d_SSsmear_%s_Width%.3f_Mean_%.3f_PureIso_%s_WhichSmear_%d",isLCAnalysis?"_LC_Yes":"",bTMClusterRejection? "On" :"Off", TMdeta , TMdphi ,iIsoMethod,iEtIsoMethod,iUEMethod,bUseofTPC ? "Yes" : "No",iIsoConeRadius,bNLMCut ? "On": "Off",minNLM, NLMCut, iSmearingSS ? "On":"Off",iWidthSSsmear,iMean_SSsmear,iExtraIsoCuts?"On":"Off",bWhichToSmear));
}
// #### Define analysis task
AliAnalysisTaskEMCALPhotonIsolation* task = new AliAnalysisTaskEMCALPhotonIsolation("Analysis",bHisto);
TString configFile("config_PhotonIsolation.C"); // Name of config file
// if(gSystem->AccessPathName(configFile.Data())){ // Check for exsisting file and delete it
// gSystem->Exec(Form("rm %s",configFile.Data()));
// }
if(configBasePath.IsNull()){ // Check if a specific config should be used and copy appropriate file
configBasePath="$ALICE_PHYSICS/PWGGA/EMCALTasks/macros";
gSystem->Exec(Form("cp %s/%s .",configBasePath.Data(),configFile.Data()));
}
else if(configBasePath.Contains("alien:///")){
gSystem->Exec(Form("alien_cp %s/%s .",configBasePath.Data(),configFile.Data()));
}
else{
gSystem->Exec(Form("cp %s/%s .",configBasePath.Data(),configFile.Data()));
}
configBasePath=Form("%s/",gSystem->pwd());
ifstream configIn; // Open config file for hash calculation
configIn.open(configFile);
TString configStr;
configStr.ReadFile(configIn);
TString configMD5 = configStr.MD5();
configMD5.Resize(5); // Short hash value for usable extension
TString configFileMD5 = configFile;
TDatime time; // Get timestamp
Int_t timeStamp = time.GetTime();
configFileMD5.ReplaceAll(".C",Form("\_%s_%i.C",configMD5.Data(),timeStamp));
if(gSystem->AccessPathName(configFileMD5.Data())){ // Add additional identifier if file exists
gSystem->Exec(Form("mv %s %s",configFile.Data(),configFileMD5.Data()));
}
else{
while(!gSystem->AccessPathName(configFileMD5.Data())){
configFileMD5.ReplaceAll(".C","_1.C");
}
gSystem->Exec(Form("mv %s %s",configFile.Data(),configFileMD5.Data()));
}
TString configFilePath(configBasePath+"/"+configFileMD5);
gROOT->LoadMacro(configFilePath.Data());
printf("Path of config file: %s\n",configFilePath.Data());
// #### Task preferences
task->SetOutputFormat(iOutput);
task->SetLCAnalysis(isLCAnalysis);
task->SetIsoConeRadius(iIsoConeRadius);
task->SetEtIsoThreshold(EtIso);
task->SetCTMdeltaEta(TMdeta);
task->SetCTMdeltaPhi(TMdphi);
task->SetCTMdeltaEtaIso(TMdetaIso);
task->SetCTMdeltaPhiIso(TMdphiIso);
task->SetQA(isQA);
task->SetIsoMethod(iIsoMethod);
task->SetEtIsoMethod(iEtIsoMethod);
task->SetUEMethod(iUEMethod);
task->SetUSEofTPC(bUseofTPC);
task->SetMC(bIsMC);
task->SetM02Smearing(iSmearingSS);
task->SetWidth4Smear(iWidthSSsmear);
task->SetMean4Smear(iMean_SSsmear);
task->SetExtraIsoCuts(iExtraIsoCuts);
task->SetAnalysispPb(i_pPb);
task->SetNLMCut(bNLMCut,NLMCut,minNLM);
task->SetPtBinning(ptBin);
task->SetM02Binning(M02Bin);
task->SetEtisoBinning(EtisoBin);
task->SetEtueBinning(EtueBin);
task->SetEtaBinning(EtaBin);
task->SetPhiBinning(PhiBin);
task->SetLabelBinning(LabelBin);
task->SetPDGBinning(PDGBin);
task->SetMomPDGBinning(MomPDGBin);
task->SetClustPDGBinning(ClustPDGBin);
task->SetDxBinning(DxBin);
task->SetDzBinning(DzBin);
task->SetDecayBinning(DecayBin);
task->SetSmearForClusters(bWhichToSmear);
task->SetNeedEmcalGeom(kTRUE);
task->SetMCtruth(bmcTruth);
if(bIsMC && bMCNormalization) task->SetIsPythia(kTRUE);
TString name(Form("PhotonIsolation_%s_%s", ntracks, nclusters));
cout<<"Name of the container "<<name.Data()<<endl;
// Tracks to be used for the track matching (already used in TM task, TPC only tracks)
AliTrackContainer *trackCont = task->AddTrackContainer("tracks");
if(!trackCont) Printf("Error with TPCOnly!!");
trackCont->SetName("tpconlyMatch");
trackCont->SetTrackFilterType(AliEmcalTrackSelection::kTPCOnlyTracks);
// Clusters to be used in the analysis already filtered
AliClusterContainer *clusterCont = task->AddClusterContainer(nclusters);
// Tracks to be used in the analysis (Hybrid tracks)
AliTrackContainer * tracksForAnalysis = task->AddTrackContainer("tracks");
if(!tracksForAnalysis) Printf("Error with Hybrids!!");
tracksForAnalysis->SetName("filterTracksAna");
tracksForAnalysis->SetFilterHybridTracks(kTRUE);
if(!bIsMC){
tracksForAnalysis->SetTrackCutsPeriod(periodstr);
tracksForAnalysis->SetDefTrackCutsPeriod(periodstr);
}
Printf("Name of tracks for matching: %s \nName of tracks for isolation: %s",trackCont->GetName(),tracksForAnalysis->GetName());
printf("Task for neutral cluster analysis created and configured, pass it to AnalysisManager\n");
// #### Add analysis task
manager->AddTask(task);
AliAnalysisDataContainer *contHistos = manager->CreateContainer(myContName.Data(), TList::Class(), AliAnalysisManager::kOutputContainer,Form("%s:NeutralClusters",AliAnalysisManager::GetCommonFileName()));
AliAnalysisDataContainer *cinput = manager->GetCommonInputContainer();
manager->ConnectInput(task, 0, cinput);
manager->ConnectOutput(task, 1, contHistos);
return task;
}
<commit_msg>Adaptation to 'usedefault' container naming convention<commit_after> ///////////////////////////////////////////////////////////////////////////
///\file AddTaskEMCALPhotonIsolation.C
///\brief Configuration of AliAnalysisTaskEMCALPhotonIsolation
///
/// Version to be used in lego train for testing on pp@7TeV
///
/// \author Lucile Ronflette <lucile.ronflette@cern.ch>, SUBATECH, Nantes
/// \author Davide Francesco Lodato <davide.francesco.lodato@cern.ch>, Utrecht University
/// \author Marco Marquard <marco.marquard@cern.ch>, University Frankfurt am Main
///////////////////////////////////////////////////////////////////////////
AliAnalysisTaskEMCALPhotonIsolation* AddTaskEMCALPhotonIsolation(
const char* periodstr = "LHC11c",
const char* ntracks = "EmcalTracks",
const char* nclusters = "EmcCaloClusters",
const UInt_t pSel = AliVEvent::kEMC7,
const TString dType = "ESD",
const Bool_t bHisto = kTRUE,
const Int_t iOutput = 0,
const Bool_t bIsMC = kFALSE,
const Bool_t bMCNormalization = kFALSE,
const Bool_t bNLMCut = kFALSE,
const Int_t NLMCut = 0,
const Double_t minPtCutCluster = 0.3,
const Double_t EtIso = 2.,
const Int_t iIsoMethod = 1,
const Int_t iEtIsoMethod = 0,
const Int_t iUEMethod = 1,
const Bool_t bUseofTPC = kFALSE,
const Double_t TMdeta = 0.02,
const Double_t TMdphi = 0.03,
const Bool_t bTMClusterRejection = kTRUE,
const Bool_t bTMClusterRejectionInCone = kTRUE,
const Float_t iIsoConeRadius = 0.4,
const Bool_t iSmearingSS = kFALSE,
const Float_t iWidthSSsmear = 0.,
const Float_t iMean_SSsmear = 0.,
const Bool_t iExtraIsoCuts = kFALSE,
const Bool_t i_pPb = kFALSE,
const Bool_t isQA = kFALSE,
TString configBasePath = "",
const Int_t bWhichToSmear = 0,
const Int_t minNLM = 1,
const Double_t TMdetaIso = 0.02,
const Double_t TMdphiIso = 0.03,
const Bool_t bmcTruth = kTRUE,
const Bool_t isLCAnalysis = kFALSE,
TString L1triggerName = ""
)
{
Printf("Preparing neutral cluster analysis\n"); // Should be modified into Printf("Preparing photon isolation analysis\n"), don't you think?
// #### Define manager and data container names
AliAnalysisManager *manager = AliAnalysisManager::GetAnalysisManager();
if(!manager){
::Error("AddTaskEMCALPhotonIsolation", "No analysis manager to connect to.");
return NULL;
}
// Use the input containers naming convention with "usedefault" (already used in several EMCal tasks and new correction framework)
TString trackName(ntracks);
TString clusName(nclusters);
if(trackName == "usedefault"){
if(dType == "ESD"){
trackName = "Tracks";
}
else if(dType == "AOD"){
trackName = "tracks";
}
else{
trackName = "";
}
}
if(clusName == "usedefault"){
if(dType == "ESD"){
clusName = "CaloClusters";
}
else if(dType == "AOD"){
clusName = "caloClusters";
}
else{
clusName = "";
}
}
// Set the task output container name
Printf("Creating container name for cluster analysis\n");
TString myContName("");
if(bIsMC){
myContName = Form("Analysis_Neutrals_MC");
}
else{
myContName = Form("Analysis_Neutrals");
}
if(L1triggerName.Contains("EG1") || L1triggerName.Contains("EGA1")){
L1triggerName = "EG1";
}
else if(L1triggerName.Contains("EG2") || L1triggerName.Contains("EGA2")){
L1triggerName = "EG2";
}
else{
L1triggerName = "";
}
if(L1triggerName != ""){
myContName.Append(Form("%s_TM_%s_CPVe%.2lf_CPVp%.2lf_IsoMet%d_EtIsoMet%d_UEMet%d_TPCbound_%s_IsoConeR%.1f_NLMCut_%s_minNLM%d_maxNLM%d_SSsmear_%s_Width%.3f_Mean_%.3f_PureIso_%s_WhichSmear_%d_Trigger_%s",isLCAnalysis?"_LC_Yes":"",bTMClusterRejection? "On" :"Off", TMdeta , TMdphi ,iIsoMethod,iEtIsoMethod,iUEMethod,bUseofTPC ? "Yes" : "No",iIsoConeRadius,bNLMCut ? "On": "Off",minNLM, NLMCut, iSmearingSS ? "On":"Off",iWidthSSsmear,iMean_SSsmear,iExtraIsoCuts?"On":"Off",bWhichToSmear,L1triggerName.Data()));
}
else{
myContName.Append(Form("%s_TM_%s_CPVe%.2lf_CPVp%.2lf_IsoMet%d_EtIsoMet%d_UEMet%d_TPCbound_%s_IsoConeR%.1f_NLMCut_%s_minNLM%d_maxNLM%d_SSsmear_%s_Width%.3f_Mean_%.3f_PureIso_%s_WhichSmear_%d",isLCAnalysis?"_LC_Yes":"",bTMClusterRejection? "On" :"Off", TMdeta , TMdphi ,iIsoMethod,iEtIsoMethod,iUEMethod,bUseofTPC ? "Yes" : "No",iIsoConeRadius,bNLMCut ? "On": "Off",minNLM, NLMCut, iSmearingSS ? "On":"Off",iWidthSSsmear,iMean_SSsmear,iExtraIsoCuts?"On":"Off",bWhichToSmear));
}
// #### Define analysis task
AliAnalysisTaskEMCALPhotonIsolation* task = new AliAnalysisTaskEMCALPhotonIsolation("Analysis",bHisto);
TString configFile("config_PhotonIsolation.C"); // Name of config file
// if(gSystem->AccessPathName(configFile.Data())){ // Check for exsisting file and delete it
// gSystem->Exec(Form("rm %s",configFile.Data()));
// }
if(configBasePath.IsNull()){ // Check if a specific config should be used and copy appropriate file
configBasePath="$ALICE_PHYSICS/PWGGA/EMCALTasks/macros";
gSystem->Exec(Form("cp %s/%s .",configBasePath.Data(),configFile.Data()));
}
else if(configBasePath.Contains("alien:///")){
gSystem->Exec(Form("alien_cp %s/%s .",configBasePath.Data(),configFile.Data()));
}
else{
gSystem->Exec(Form("cp %s/%s .",configBasePath.Data(),configFile.Data()));
}
configBasePath=Form("%s/",gSystem->pwd());
ifstream configIn; // Open config file for hash calculation
configIn.open(configFile);
TString configStr;
configStr.ReadFile(configIn);
TString configMD5 = configStr.MD5();
configMD5.Resize(5); // Short hash value for usable extension
TString configFileMD5 = configFile;
TDatime time; // Get timestamp
Int_t timeStamp = time.GetTime();
configFileMD5.ReplaceAll(".C",Form("\_%s_%i.C",configMD5.Data(),timeStamp));
if(gSystem->AccessPathName(configFileMD5.Data())){ // Add additional identifier if file exists
gSystem->Exec(Form("mv %s %s",configFile.Data(),configFileMD5.Data()));
}
else{
while(!gSystem->AccessPathName(configFileMD5.Data())){
configFileMD5.ReplaceAll(".C","_1.C");
}
gSystem->Exec(Form("mv %s %s",configFile.Data(),configFileMD5.Data()));
}
TString configFilePath(configBasePath+"/"+configFileMD5);
gROOT->LoadMacro(configFilePath.Data());
Printf("Path of config file: %s\n",configFilePath.Data());
// #### Task preferences
task->SetOutputFormat(iOutput);
task->SetLCAnalysis(isLCAnalysis);
task->SetIsoConeRadius(iIsoConeRadius);
task->SetEtIsoThreshold(EtIso);
task->SetCTMdeltaEta(TMdeta);
task->SetCTMdeltaPhi(TMdphi);
task->SetCTMdeltaEtaIso(TMdetaIso);
task->SetCTMdeltaPhiIso(TMdphiIso);
task->SetQA(isQA);
task->SetIsoMethod(iIsoMethod);
task->SetEtIsoMethod(iEtIsoMethod);
task->SetUEMethod(iUEMethod);
task->SetUSEofTPC(bUseofTPC);
task->SetMC(bIsMC);
task->SetM02Smearing(iSmearingSS);
task->SetWidth4Smear(iWidthSSsmear);
task->SetMean4Smear(iMean_SSsmear);
task->SetExtraIsoCuts(iExtraIsoCuts);
task->SetAnalysispPb(i_pPb);
task->SetNLMCut(bNLMCut,NLMCut,minNLM);
task->SetPtBinning(ptBin);
task->SetM02Binning(M02Bin);
task->SetEtisoBinning(EtisoBin);
task->SetEtueBinning(EtueBin);
task->SetEtaBinning(EtaBin);
task->SetPhiBinning(PhiBin);
task->SetLabelBinning(LabelBin);
task->SetPDGBinning(PDGBin);
task->SetMomPDGBinning(MomPDGBin);
task->SetClustPDGBinning(ClustPDGBin);
task->SetDxBinning(DxBin);
task->SetDzBinning(DzBin);
task->SetDecayBinning(DecayBin);
task->SetSmearForClusters(bWhichToSmear);
task->SetNeedEmcalGeom(kTRUE);
task->SetMCtruth(bmcTruth);
if(bIsMC && bMCNormalization) task->SetIsPythia(kTRUE);
TString name(Form("PhotonIsolation_%s_%s", trackName.Data(), clusName.Data())); // Is this variable still useful?
cout<<"Name of the container "<<name.Data()<<endl;
// Tracks to be used for the track matching (already used in TM task, TPC only tracks)
AliTrackContainer *trackCont = task->AddTrackContainer(trackName);
if(!trackCont) Printf("Error with TPC-Only Tracks!!");
trackCont->SetName("tpconlyMatch");
trackCont->SetTrackFilterType(AliEmcalTrackSelection::kTPCOnlyTracks);
// Tracks to be used in the analysis (Hybrid Tracks)
AliTrackContainer * tracksForAnalysis = task->AddTrackContainer(trackName);
if(!tracksForAnalysis) Printf("Error with Hybrids Tracks!!");
tracksForAnalysis->SetName("filterTracksAna");
tracksForAnalysis->SetFilterHybridTracks(kTRUE);
if(!bIsMC){
tracksForAnalysis->SetTrackCutsPeriod(periodstr);
tracksForAnalysis->SetDefTrackCutsPeriod(periodstr);
}
// Clusters to be used in the analysis (already filtered)
AliClusterContainer *clusterCont = task->AddClusterContainer(clusName);
Printf("Name of track container for matching: %s \nName of track container for isolation: %s \nName of cluster container: %s",trackCont->GetName(),tracksForAnalysis->GetName(),clusterCont->GetName());
// #### Add analysis task
Printf("Task for neutral cluster analysis created and configured, pass it to AnalysisManager\n");
manager->AddTask(task);
AliAnalysisDataContainer *contHistos = manager->CreateContainer(myContName.Data(), TList::Class(), AliAnalysisManager::kOutputContainer,Form("%s:NeutralClusters",AliAnalysisManager::GetCommonFileName()));
AliAnalysisDataContainer *cinput = manager->GetCommonInputContainer();
manager->ConnectInput(task, 0, cinput);
manager->ConnectOutput(task, 1, contHistos);
return task;
}
<|endoftext|> |
<commit_before>/*
* Copyright 2009-2019 The VOTCA Development Team (http://www.votca.org)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
#include "csg_imc_solve.h"
#include <fstream>
#include <votca/tools/table.h>
int main(int argc, char** argv) {
CG_IMC_solve app;
return app.Exec(argc, argv);
}
void CG_IMC_solve::Initialize(void) {
namespace propt = boost::program_options;
AddProgramOptions()("regularization,r",
propt::value<double>()->default_value(0.0),
"regularization factor");
AddProgramOptions()("imcfile,i", boost::program_options::value<std::string>(),
"imc statefile");
AddProgramOptions()("gmcfile,g", boost::program_options::value<std::string>(),
"gmc statefile");
AddProgramOptions()("outputfile,o",
boost::program_options::value<std::string>(),
"outputfile");
}
bool CG_IMC_solve::EvaluateOptions() {
CheckRequired("imcfile", "Missing imcfile");
CheckRequired("gmcfile", "Missing gmcfile");
CheckRequired("outputfile", "Missing outputfile");
return true;
}
Eigen::MatrixXd CG_IMC_solve::LoadMatrix(const std::string& filename) const {
std::ifstream intt;
intt.open(filename);
if (!intt)
throw std::runtime_error(std::string("error, cannot open file ") +
filename);
std::string line;
std::vector<double> result;
int numrows = 0;
unsigned numcols = 0;
while (getline(intt, line)) {
if (line[0] == '#') {
continue;
}
votca::tools::Tokenizer tok(line, " \t");
std::vector<std::string> tokens = tok.ToVector();
if (numrows == 0) {
numcols = tokens.size();
} else if (numcols != tokens.size()) {
throw std::runtime_error(
"Matrix has not the same number of entries in each row.");
}
for (const std::string& s : tokens) {
result.push_back(std::stod(s));
}
numrows++;
}
intt.close();
return Eigen::Map<Eigen::MatrixXd>(result.data(), numrows, numcols);
}
void CG_IMC_solve::Run() {
std::string imcfile = _op_vm["imcfile"].as<std::string>();
std::string gmcfile = _op_vm["gmcfile"].as<std::string>();
std::string outputfile = _op_vm["outputfile"].as<std::string>();
double reg = _op_vm["regularization"].as<double>();
Eigen::MatrixXd A = LoadMatrix(gmcfile);
votca::tools::Table B;
B.Load(imcfile);
votca::tools::Table x;
x.resize(B.size());
x.x() = B.x();
// Calculating https://en.wikipedia.org/wiki/Tikhonov_regularization
Eigen::MatrixXd ATA = A.transpose() * A;
// We could add and invert but for stability reasons we will diagonalize the
// matrix which is symmetric by construction
Eigen::SelfAdjointEigenSolver<Eigen::MatrixXd> es(ATA);
Eigen::VectorXd inv_diag = Eigen::VectorXd::Zero(es.eigenvalues().size());
double etol = 1e-12;
int numerics_unstable = 0;
// Constructing pseudoinverse if not stable
// https://en.wikipedia.org/wiki/Moore%E2%80%93Penrose_inverse
for (int i = 0; i < es.eigenvalues().size(); i++) {
if (std::abs(es.eigenvalues()[i] + reg) < etol) {
numerics_unstable++;
} else {
inv_diag[i] = 1 / (es.eigenvalues()[i] + reg);
}
}
if (numerics_unstable > 0) {
std::cout
<< "Regularisation parameter was to small, a pseudo inverse was "
"constructed instead.\n Use a larger regularisation parameter R."
" Smallest (eigenvalue+R)="
<< (es.eigenvalues().array() + reg).abs().minCoeff() << " Found "
<< numerics_unstable << " eigenvalues of " << es.eigenvalues().size()
<< " below " << etol << std::endl;
}
Eigen::MatrixXd inverse =
es.eigenvectors() * inv_diag.asDiagonal() * es.eigenvectors().transpose();
x.y() = inverse * A.transpose() * B.y();
x.Save(outputfile);
}
<commit_msg>minus missing<commit_after>/*
* Copyright 2009-2019 The VOTCA Development Team (http://www.votca.org)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
#include "csg_imc_solve.h"
#include <fstream>
#include <votca/tools/table.h>
int main(int argc, char** argv) {
CG_IMC_solve app;
return app.Exec(argc, argv);
}
void CG_IMC_solve::Initialize(void) {
namespace propt = boost::program_options;
AddProgramOptions()("regularization,r",
propt::value<double>()->default_value(0.0),
"regularization factor");
AddProgramOptions()("imcfile,i", boost::program_options::value<std::string>(),
"imc statefile");
AddProgramOptions()("gmcfile,g", boost::program_options::value<std::string>(),
"gmc statefile");
AddProgramOptions()("outputfile,o",
boost::program_options::value<std::string>(),
"outputfile");
}
bool CG_IMC_solve::EvaluateOptions() {
CheckRequired("imcfile", "Missing imcfile");
CheckRequired("gmcfile", "Missing gmcfile");
CheckRequired("outputfile", "Missing outputfile");
return true;
}
Eigen::MatrixXd CG_IMC_solve::LoadMatrix(const std::string& filename) const {
std::ifstream intt;
intt.open(filename);
if (!intt)
throw std::runtime_error(std::string("error, cannot open file ") +
filename);
std::string line;
std::vector<double> result;
int numrows = 0;
unsigned numcols = 0;
while (getline(intt, line)) {
if (line[0] == '#') {
continue;
}
votca::tools::Tokenizer tok(line, " \t");
std::vector<std::string> tokens = tok.ToVector();
if (numrows == 0) {
numcols = tokens.size();
} else if (numcols != tokens.size()) {
throw std::runtime_error(
"Matrix has not the same number of entries in each row.");
}
for (const std::string& s : tokens) {
result.push_back(std::stod(s));
}
numrows++;
}
intt.close();
return Eigen::Map<Eigen::MatrixXd>(result.data(), numrows, numcols);
}
void CG_IMC_solve::Run() {
std::string imcfile = _op_vm["imcfile"].as<std::string>();
std::string gmcfile = _op_vm["gmcfile"].as<std::string>();
std::string outputfile = _op_vm["outputfile"].as<std::string>();
double reg = _op_vm["regularization"].as<double>();
Eigen::MatrixXd A = LoadMatrix(gmcfile);
votca::tools::Table B;
B.Load(imcfile);
votca::tools::Table x;
x.resize(B.size());
x.x() = B.x();
// Calculating https://en.wikipedia.org/wiki/Tikhonov_regularization
Eigen::MatrixXd ATA = A.transpose() * A;
// We could add and invert but for stability reasons we will diagonalize the
// matrix which is symmetric by construction
Eigen::SelfAdjointEigenSolver<Eigen::MatrixXd> es(ATA);
Eigen::VectorXd inv_diag = Eigen::VectorXd::Zero(es.eigenvalues().size());
double etol = 1e-12;
int numerics_unstable = 0;
// Constructing pseudoinverse if not stable
// https://en.wikipedia.org/wiki/Moore%E2%80%93Penrose_inverse
for (int i = 0; i < es.eigenvalues().size(); i++) {
if (std::abs(es.eigenvalues()[i] + reg) < etol) {
numerics_unstable++;
} else {
inv_diag[i] = 1 / (es.eigenvalues()[i] + reg);
}
}
if (numerics_unstable > 0) {
std::cout
<< "Regularisation parameter was to small, a pseudo inverse was "
"constructed instead.\n Use a larger regularisation parameter R."
" Smallest (eigenvalue+R)="
<< (es.eigenvalues().array() + reg).abs().minCoeff() << " Found "
<< numerics_unstable << " eigenvalues of " << es.eigenvalues().size()
<< " below " << etol << std::endl;
}
Eigen::MatrixXd inverse =
es.eigenvectors() * inv_diag.asDiagonal() * es.eigenvectors().transpose();
x.y() = -inverse * A.transpose() * B.y();
x.Save(outputfile);
}
<|endoftext|> |
<commit_before>/*
Copyright (c) 2017 InversePalindrome
Memento Mori - Subject.cpp
InversePalindrome.com
*/
#include "Subject.hpp"
#include <algorithm>
void Subject::addObserver(Observer& observer)
{
if (std::find(std::begin(this->observers), std::end(this->observers), &observer) == std::end(this->observers))
{
this->observers.push_back(&observer);
}
}
void Subject::removeObserver(Observer& observer)
{
this->observers.erase(std::remove(std::begin(this->observers), std::end(this->observers), &observer), std::end(this->observers));
}
void Subject::notifyObservers(const Message& message)
{
for (auto& observer : this->observers)
{
observer->notify(message);
}
}<commit_msg>Delete Subject.cpp<commit_after><|endoftext|> |
<commit_before>/* This file is part of the KDE project
Copyright (C) 2005 Kopete Developers <kopete-devel@kde.org>
Copyright (C) 2008-2009 Pali Rohár <pali.rohar@gmail.com>
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Library General Public
License version 2 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
Library General Public License for more details.
You should have received a copy of the GNU Library General Public License
along with this library; see the file COPYING.LIB. If not, write to
the Free Software Foundation, Inc., 59 Temple Place - Suite 330,
Boston, MA 02111-1307, USA.
*/
#include "skypeconnection.h"
#include "clientadaptor.h"
#include <QtDBus>
#include <QVariant>
#include <qstringlist.h>
#include <qtimer.h>
#include <kdebug.h>
#include <klocale.h>
#include <unistd.h>
#define BUS d->bus == 1 ? QDBusConnection::systemBus() : QDBusConnection::sessionBus() //0 - session bus, 1 - system bus, default:0
typedef enum {
cfConnected,
cfNotConnected,
cfNameSent,
cfProtocolSent,
cfWaitingStart
} connFase;
class SkypeConnectionPrivate {
public:
///Are we connected/connecting?
connFase fase;
///How will we be known to skype?
QString appName;
///What is the protocol version used (wanted if not connected yet)
int protocolVer;
///Bus type 0 - session, 1 - system
int bus;
///This timer will keep trying until Skype starts
QTimer *startTimer;
///How much time rest? (until I say starting skype did not work)
int timeRemaining;
///Wait a while before we conect to just-started skype?
int waitBeforeConnect;
///Skype process
QProcess skypeProcess;
};
SkypeConnection::SkypeConnection() {
kDebug() << k_funcinfo << endl;//some debug info
d = new SkypeConnectionPrivate;//create the d pointer
d->fase = cfNotConnected;//not connected yet
d->startTimer = 0L;
connect(this, SIGNAL(received(const QString&)), this, SLOT(parseMessage(const QString&)));//look into all messages
}
SkypeConnection::~SkypeConnection() {
kDebug() << k_funcinfo << endl;//some debug info
disconnectSkype();//disconnect before you leave
if ( d->skypeProcess.state() != QProcess::NotRunning )//if we started skype process kill it
d->skypeProcess.kill();
QProcess::execute("bash -c \"pkill -6 -U $USER -x skype.*\"");//try find skype process (skype, skype.real, ...) and kill it if we dont start skype or use skype.real wrapper
delete d;//Remove the D pointer
}
void SkypeConnection::startLogOn() {
kDebug() << k_funcinfo << endl;//some debug info
if (d->startTimer) {
d->startTimer->deleteLater();
d->startTimer = 0L;
}
QDBusReply <QString> reply = QDBusInterface("com.Skype.API", "/com/Skype", "com.Skype.API", BUS).call("Invoke", "PING");
if ( reply.value() != "PONG" ){
emit error(i18n("Could not ping Skype"));
disconnectSkype(crLost);
emit connectionDone(seNoSkype, 0);
return;
}
d->fase = cfNameSent;
send(QString("NAME %1").arg(d->appName));
}
void SkypeConnection::parseMessage(const QString &message) {
kDebug() << k_funcinfo << endl;//some debug info
switch (d->fase) {
case cfNameSent: {
if (message == "OK") {//Accepted by skype
d->fase = cfProtocolSent;//Sending the protocol
send(QString("PROTOCOL %1").arg(d->protocolVer));//send the protocol version
} else {//Not accepted by skype
emit error(i18n("Skype did not accept this application"));//say there is an error
emit connectionDone(seAuthorization, 0);//Problem with authorization
disconnectSkype(crLost);//Lost the connection
}
break;
}
case cfProtocolSent: {
if (message.contains(QString("PROTOCOL"), Qt::CaseSensitivity(false))) {//This one inform us what protocol do we use
bool ok;
int version = message.section(' ', 1, 1).trimmed().toInt(&ok, 0);//take out the protocol version and make it int
if (!ok) {
emit error(i18n("Skype API syntax error"));
emit connectionDone(seUnknown, 0);
disconnectSkype(crLost);//lost the connection
return;//I have enough
}
d->protocolVer = version;//this will be the used version of protocol
d->fase = cfConnected;
emit connectionDone(seSuccess, version);//tell him that we are connected at last
} else {//the API is not ready yet, try later
emit error(i18n("Skype API not ready yet, wait a bit longer"));
emit connectionDone(seUnknown, 0);
disconnectSkype(crLost);
return;
}
break;//Other messages are ignored, waiting for the protocol response
}
}
}
void SkypeConnection::Notify(const QString &message){
kDebug() << k_funcinfo << "Got message:" << message << endl;//show what we have got
emit received(message);
}
void SkypeConnection::connectSkype(const QString &start, const QString &appName, int protocolVer, int bus, int launchTimeout, int waitBeforeConnect, const QString &name, const QString &pass) {
kDebug() << k_funcinfo << endl;//some debug info
if (d->fase != cfNotConnected)
return;
d->appName = appName;
d->protocolVer = protocolVer;
d->bus = bus;
new ClientAdaptor(this);
QDBusConnection busConn = BUS;
busConn.registerObject("/com/Skype/Client", this); //Register skype client to dbus for receiving messages to slot Notify
{
QDBusInterface interface("com.Skype.API", "/com/Skype", "com.Skype.API", BUS);
QDBusReply <QString> reply = interface.call("Invoke", "PING");
bool started = interface.isValid();
bool loggedin = reply.value() == "PONG";
if ( ! started || ! loggedin ){
if ( ! started && ! start.isEmpty() ) {//try starting Skype by the given command
QStringList args = start.split(' ');
QString skypeBin = args.takeFirst();
if ( !name.isEmpty() && !pass.isEmpty() ){
args << "--pipelogin";
}
kDebug() << k_funcinfo << "Starting skype process" << skypeBin << "with parms" << args << endl;
d->skypeProcess.start(skypeBin, args);
if ( !name.isEmpty() && !pass.isEmpty() ){
kDebug() << k_funcinfo << "Sending login name:" << name << endl;
d->skypeProcess.write(name.trimmed().toLocal8Bit());
d->skypeProcess.write(" ");
kDebug() << k_funcinfo << "Sending password" << endl;
d->skypeProcess.write(pass.trimmed().toLocal8Bit());
d->skypeProcess.closeWriteChannel();
}
d->skypeProcess.waitForStarted();
kDebug() << k_funcinfo << "Skype process state:" << d->skypeProcess.state() << "Skype process error:" << d->skypeProcess.error() << endl;
if ( d->skypeProcess.state() != QProcess::Running || d->skypeProcess.error() == QProcess::FailedToStart ) {
emit error(i18n("Could not launch Skype.\nYou need to install the original dynamic linked Skype version 2.0 binary from http://www.skype.com"));
disconnectSkype(crLost);
emit connectionDone(seNoSkype, 0);
return;
}
} else {
if ( start.isEmpty() ){
emit error(i18n("Could not find Skype.\nYou need to install the original dynamic linked Skype version 2.0 binary from http://www.skype.com"));
disconnectSkype(crLost);
emit connectionDone(seNoSkype, 0);
return;
}
}
d->fase = cfWaitingStart;
d->startTimer = new QTimer();
connect(d->startTimer, SIGNAL(timeout()), this, SLOT(tryConnect()));
d->startTimer->start(1000);
d->timeRemaining = launchTimeout;
d->waitBeforeConnect = waitBeforeConnect;
return;
}
}
startLogOn();
}
void SkypeConnection::disconnectSkype(skypeCloseReason reason) {
kDebug() << k_funcinfo << endl;//some debug info
if (d->startTimer) {
d->startTimer->stop();
d->startTimer->deleteLater();
d->startTimer = 0L;
}
d->fase = cfNotConnected;//No longer connected
emit connectionDone(seCanceled, 0);
emit connectionClosed(reason);//we disconnect
}
QString SkypeConnection::operator %(const QString &message) {
kDebug() << k_funcinfo << "Send message:" << message << endl;//some debug info
if (d->fase == cfNotConnected)
return "";//not connected, posibly because of earlier error, do not show it again
QDBusInterface interface("com.Skype.API", "/com/Skype", "com.Skype.API", BUS);
QDBusReply <QString> reply = interface.call("Invoke", message);
if ( interface.lastError().type() != QDBusError::NoError && interface.lastError().type() != QDBusError::Other ){//There was some error
if ( message == "PING" )
emit error(i18n("Could not ping Skype.\nMaybe Skype not running.\nError while sending a message to Skype (%1).", QDBusError::errorString(interface.lastError().type())));//say there was the error
else
emit error(i18n("Error while sending a message to Skype (%1).", QDBusError::errorString(interface.lastError().type())));//say there was the error
if (d->fase != cfConnected)
emit connectionDone(seUnknown, 0);//Connection attempt finished with error
disconnectSkype(crLost);//lost the connection
return "";//this is enough, no more errors please..
}
if ( message == "PING" && reply.value() != "PONG" ){
emit error(i18n("Could not ping Skype.\nYou are logged out from Skype, please log in."));
emit connectionDone(seNoSkype, 0);
disconnectSkype(crLost);//lost the connection
return "";//this is enough, no more errors please..
}
kDebug() << "Reply message:" << reply.value() << endl;//show what we have received
return reply.value();//ok, just return it
}
void SkypeConnection::send(const QString &message) {
kDebug() << k_funcinfo << endl;//some debug info
QString reply = *this % message;
if ( ! reply.isEmpty() )
emit received(reply);
}
SkypeConnection &SkypeConnection::operator <<(const QString &message) {
send(message);//just send it
return *this;//and return yourself
}
bool SkypeConnection::connected() const {
kDebug() << k_funcinfo << endl;//some debug info
return d->fase == cfConnected;
}
int SkypeConnection::protocolVer() const {
kDebug() << k_funcinfo << endl;//some debug info
return d->protocolVer;//just give him the protocol version
}
void SkypeConnection::tryConnect() {
kDebug() << k_funcinfo << endl;//some debug info
{
QDBusInterface interface("com.Skype.API", "/com/Skype", "com.Skype.API", BUS);
QDBusReply <QString> reply = interface.call("Invoke", "PING");
bool started = interface.isValid();
bool loggedin = reply.value() == "PONG";
if ( ! started || ! loggedin ){
if (--d->timeRemaining == 0) {
d->startTimer->stop();
d->startTimer->deleteLater();
d->startTimer = 0L;
if ( !started )
emit error(i18n("Could not find Skype\nYou need to install the original dynamic linked Skype version 2.0 binary from http://www.skype.com"));
else
emit error(i18n("Please login to Skype first"));
disconnectSkype(crLost);
emit connectionDone(seNoSkype, 0);
return;
}
return;//Maybe next time
}
}
d->startTimer->stop();
d->startTimer->deleteLater();
d->startTimer = 0L;
if (d->waitBeforeConnect) {
QTimer::singleShot(1000 * d->waitBeforeConnect, this, SLOT(startLogOn()));
//Skype does not like being bothered right after it's start, give it a while to breathe
} else
startLogOn();//OK, it's your choise
}
#include "skypeconnection.moc"
<commit_msg>fix a typo in an i18n message (adding a period at the end of phrase) this makes the message exactly like another message in this source file<commit_after>/* This file is part of the KDE project
Copyright (C) 2005 Kopete Developers <kopete-devel@kde.org>
Copyright (C) 2008-2009 Pali Rohár <pali.rohar@gmail.com>
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Library General Public
License version 2 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
Library General Public License for more details.
You should have received a copy of the GNU Library General Public License
along with this library; see the file COPYING.LIB. If not, write to
the Free Software Foundation, Inc., 59 Temple Place - Suite 330,
Boston, MA 02111-1307, USA.
*/
#include "skypeconnection.h"
#include "clientadaptor.h"
#include <QtDBus>
#include <QVariant>
#include <qstringlist.h>
#include <qtimer.h>
#include <kdebug.h>
#include <klocale.h>
#include <unistd.h>
#define BUS d->bus == 1 ? QDBusConnection::systemBus() : QDBusConnection::sessionBus() //0 - session bus, 1 - system bus, default:0
typedef enum {
cfConnected,
cfNotConnected,
cfNameSent,
cfProtocolSent,
cfWaitingStart
} connFase;
class SkypeConnectionPrivate {
public:
///Are we connected/connecting?
connFase fase;
///How will we be known to skype?
QString appName;
///What is the protocol version used (wanted if not connected yet)
int protocolVer;
///Bus type 0 - session, 1 - system
int bus;
///This timer will keep trying until Skype starts
QTimer *startTimer;
///How much time rest? (until I say starting skype did not work)
int timeRemaining;
///Wait a while before we conect to just-started skype?
int waitBeforeConnect;
///Skype process
QProcess skypeProcess;
};
SkypeConnection::SkypeConnection() {
kDebug() << k_funcinfo << endl;//some debug info
d = new SkypeConnectionPrivate;//create the d pointer
d->fase = cfNotConnected;//not connected yet
d->startTimer = 0L;
connect(this, SIGNAL(received(const QString&)), this, SLOT(parseMessage(const QString&)));//look into all messages
}
SkypeConnection::~SkypeConnection() {
kDebug() << k_funcinfo << endl;//some debug info
disconnectSkype();//disconnect before you leave
if ( d->skypeProcess.state() != QProcess::NotRunning )//if we started skype process kill it
d->skypeProcess.kill();
QProcess::execute("bash -c \"pkill -6 -U $USER -x skype.*\"");//try find skype process (skype, skype.real, ...) and kill it if we dont start skype or use skype.real wrapper
delete d;//Remove the D pointer
}
void SkypeConnection::startLogOn() {
kDebug() << k_funcinfo << endl;//some debug info
if (d->startTimer) {
d->startTimer->deleteLater();
d->startTimer = 0L;
}
QDBusReply <QString> reply = QDBusInterface("com.Skype.API", "/com/Skype", "com.Skype.API", BUS).call("Invoke", "PING");
if ( reply.value() != "PONG" ){
emit error(i18n("Could not ping Skype"));
disconnectSkype(crLost);
emit connectionDone(seNoSkype, 0);
return;
}
d->fase = cfNameSent;
send(QString("NAME %1").arg(d->appName));
}
void SkypeConnection::parseMessage(const QString &message) {
kDebug() << k_funcinfo << endl;//some debug info
switch (d->fase) {
case cfNameSent: {
if (message == "OK") {//Accepted by skype
d->fase = cfProtocolSent;//Sending the protocol
send(QString("PROTOCOL %1").arg(d->protocolVer));//send the protocol version
} else {//Not accepted by skype
emit error(i18n("Skype did not accept this application"));//say there is an error
emit connectionDone(seAuthorization, 0);//Problem with authorization
disconnectSkype(crLost);//Lost the connection
}
break;
}
case cfProtocolSent: {
if (message.contains(QString("PROTOCOL"), Qt::CaseSensitivity(false))) {//This one inform us what protocol do we use
bool ok;
int version = message.section(' ', 1, 1).trimmed().toInt(&ok, 0);//take out the protocol version and make it int
if (!ok) {
emit error(i18n("Skype API syntax error"));
emit connectionDone(seUnknown, 0);
disconnectSkype(crLost);//lost the connection
return;//I have enough
}
d->protocolVer = version;//this will be the used version of protocol
d->fase = cfConnected;
emit connectionDone(seSuccess, version);//tell him that we are connected at last
} else {//the API is not ready yet, try later
emit error(i18n("Skype API not ready yet, wait a bit longer"));
emit connectionDone(seUnknown, 0);
disconnectSkype(crLost);
return;
}
break;//Other messages are ignored, waiting for the protocol response
}
}
}
void SkypeConnection::Notify(const QString &message){
kDebug() << k_funcinfo << "Got message:" << message << endl;//show what we have got
emit received(message);
}
void SkypeConnection::connectSkype(const QString &start, const QString &appName, int protocolVer, int bus, int launchTimeout, int waitBeforeConnect, const QString &name, const QString &pass) {
kDebug() << k_funcinfo << endl;//some debug info
if (d->fase != cfNotConnected)
return;
d->appName = appName;
d->protocolVer = protocolVer;
d->bus = bus;
new ClientAdaptor(this);
QDBusConnection busConn = BUS;
busConn.registerObject("/com/Skype/Client", this); //Register skype client to dbus for receiving messages to slot Notify
{
QDBusInterface interface("com.Skype.API", "/com/Skype", "com.Skype.API", BUS);
QDBusReply <QString> reply = interface.call("Invoke", "PING");
bool started = interface.isValid();
bool loggedin = reply.value() == "PONG";
if ( ! started || ! loggedin ){
if ( ! started && ! start.isEmpty() ) {//try starting Skype by the given command
QStringList args = start.split(' ');
QString skypeBin = args.takeFirst();
if ( !name.isEmpty() && !pass.isEmpty() ){
args << "--pipelogin";
}
kDebug() << k_funcinfo << "Starting skype process" << skypeBin << "with parms" << args << endl;
d->skypeProcess.start(skypeBin, args);
if ( !name.isEmpty() && !pass.isEmpty() ){
kDebug() << k_funcinfo << "Sending login name:" << name << endl;
d->skypeProcess.write(name.trimmed().toLocal8Bit());
d->skypeProcess.write(" ");
kDebug() << k_funcinfo << "Sending password" << endl;
d->skypeProcess.write(pass.trimmed().toLocal8Bit());
d->skypeProcess.closeWriteChannel();
}
d->skypeProcess.waitForStarted();
kDebug() << k_funcinfo << "Skype process state:" << d->skypeProcess.state() << "Skype process error:" << d->skypeProcess.error() << endl;
if ( d->skypeProcess.state() != QProcess::Running || d->skypeProcess.error() == QProcess::FailedToStart ) {
emit error(i18n("Could not launch Skype.\nYou need to install the original dynamic linked Skype version 2.0 binary from http://www.skype.com"));
disconnectSkype(crLost);
emit connectionDone(seNoSkype, 0);
return;
}
} else {
if ( start.isEmpty() ){
emit error(i18n("Could not find Skype.\nYou need to install the original dynamic linked Skype version 2.0 binary from http://www.skype.com"));
disconnectSkype(crLost);
emit connectionDone(seNoSkype, 0);
return;
}
}
d->fase = cfWaitingStart;
d->startTimer = new QTimer();
connect(d->startTimer, SIGNAL(timeout()), this, SLOT(tryConnect()));
d->startTimer->start(1000);
d->timeRemaining = launchTimeout;
d->waitBeforeConnect = waitBeforeConnect;
return;
}
}
startLogOn();
}
void SkypeConnection::disconnectSkype(skypeCloseReason reason) {
kDebug() << k_funcinfo << endl;//some debug info
if (d->startTimer) {
d->startTimer->stop();
d->startTimer->deleteLater();
d->startTimer = 0L;
}
d->fase = cfNotConnected;//No longer connected
emit connectionDone(seCanceled, 0);
emit connectionClosed(reason);//we disconnect
}
QString SkypeConnection::operator %(const QString &message) {
kDebug() << k_funcinfo << "Send message:" << message << endl;//some debug info
if (d->fase == cfNotConnected)
return "";//not connected, posibly because of earlier error, do not show it again
QDBusInterface interface("com.Skype.API", "/com/Skype", "com.Skype.API", BUS);
QDBusReply <QString> reply = interface.call("Invoke", message);
if ( interface.lastError().type() != QDBusError::NoError && interface.lastError().type() != QDBusError::Other ){//There was some error
if ( message == "PING" )
emit error(i18n("Could not ping Skype.\nMaybe Skype not running.\nError while sending a message to Skype (%1).", QDBusError::errorString(interface.lastError().type())));//say there was the error
else
emit error(i18n("Error while sending a message to Skype (%1).", QDBusError::errorString(interface.lastError().type())));//say there was the error
if (d->fase != cfConnected)
emit connectionDone(seUnknown, 0);//Connection attempt finished with error
disconnectSkype(crLost);//lost the connection
return "";//this is enough, no more errors please..
}
if ( message == "PING" && reply.value() != "PONG" ){
emit error(i18n("Could not ping Skype.\nYou are logged out from Skype, please log in."));
emit connectionDone(seNoSkype, 0);
disconnectSkype(crLost);//lost the connection
return "";//this is enough, no more errors please..
}
kDebug() << "Reply message:" << reply.value() << endl;//show what we have received
return reply.value();//ok, just return it
}
void SkypeConnection::send(const QString &message) {
kDebug() << k_funcinfo << endl;//some debug info
QString reply = *this % message;
if ( ! reply.isEmpty() )
emit received(reply);
}
SkypeConnection &SkypeConnection::operator <<(const QString &message) {
send(message);//just send it
return *this;//and return yourself
}
bool SkypeConnection::connected() const {
kDebug() << k_funcinfo << endl;//some debug info
return d->fase == cfConnected;
}
int SkypeConnection::protocolVer() const {
kDebug() << k_funcinfo << endl;//some debug info
return d->protocolVer;//just give him the protocol version
}
void SkypeConnection::tryConnect() {
kDebug() << k_funcinfo << endl;//some debug info
{
QDBusInterface interface("com.Skype.API", "/com/Skype", "com.Skype.API", BUS);
QDBusReply <QString> reply = interface.call("Invoke", "PING");
bool started = interface.isValid();
bool loggedin = reply.value() == "PONG";
if ( ! started || ! loggedin ){
if (--d->timeRemaining == 0) {
d->startTimer->stop();
d->startTimer->deleteLater();
d->startTimer = 0L;
if ( !started )
emit error(i18n("Could not find Skype.\nYou need to install the original dynamic linked Skype version 2.0 binary from http://www.skype.com"));
else
emit error(i18n("Please login to Skype first"));
disconnectSkype(crLost);
emit connectionDone(seNoSkype, 0);
return;
}
return;//Maybe next time
}
}
d->startTimer->stop();
d->startTimer->deleteLater();
d->startTimer = 0L;
if (d->waitBeforeConnect) {
QTimer::singleShot(1000 * d->waitBeforeConnect, this, SLOT(startLogOn()));
//Skype does not like being bothered right after it's start, give it a while to breathe
} else
startLogOn();//OK, it's your choise
}
#include "skypeconnection.moc"
<|endoftext|> |
<commit_before><commit_msg>removed unused var<commit_after><|endoftext|> |
<commit_before>/****************************************************************************
*
* (c) 2009-2016 QGROUNDCONTROL PROJECT <http://www.qgroundcontrol.org>
*
* QGroundControl is licensed according to the terms in the file
* COPYING.md in the root of the source code directory.
*
****************************************************************************/
/// @file
/// @author Don Gagne <don@thegagnes.com>
#include "QGroundControlQmlGlobal.h"
#include <QSettings>
#include <QLineF>
#include <QPointF>
static const char* kQmlGlobalKeyName = "QGCQml";
const char* QGroundControlQmlGlobal::_flightMapPositionSettingsGroup = "FlightMapPosition";
const char* QGroundControlQmlGlobal::_flightMapPositionLatitudeSettingsKey = "Latitude";
const char* QGroundControlQmlGlobal::_flightMapPositionLongitudeSettingsKey = "Longitude";
const char* QGroundControlQmlGlobal::_flightMapZoomSettingsKey = "FlightMapZoom";
QGeoCoordinate QGroundControlQmlGlobal::_coord = QGeoCoordinate(0.0,0.0);
double QGroundControlQmlGlobal::_zoom = 2;
QGroundControlQmlGlobal::QGroundControlQmlGlobal(QGCApplication* app, QGCToolbox* toolbox)
: QGCTool (app, toolbox)
{
// We clear the parent on this object since we run into shutdown problems caused by hybrid qml app. Instead we let it leak on shutdown.
setParent(nullptr);
// Load last coordinates and zoom from config file
QSettings settings;
settings.beginGroup(_flightMapPositionSettingsGroup);
_coord.setLatitude(settings.value(_flightMapPositionLatitudeSettingsKey, _coord.latitude()).toDouble());
_coord.setLongitude(settings.value(_flightMapPositionLongitudeSettingsKey, _coord.longitude()).toDouble());
_zoom = settings.value(_flightMapZoomSettingsKey, _zoom).toDouble();
}
QGroundControlQmlGlobal::~QGroundControlQmlGlobal()
{
// Save last coordinates and zoom to config file
QSettings settings;
settings.beginGroup(_flightMapPositionSettingsGroup);
settings.setValue(_flightMapPositionLatitudeSettingsKey, _coord.latitude());
settings.setValue(_flightMapPositionLongitudeSettingsKey, _coord.longitude());
settings.setValue(_flightMapZoomSettingsKey, _zoom);
}
void QGroundControlQmlGlobal::setToolbox(QGCToolbox* toolbox)
{
QGCTool::setToolbox(toolbox);
_linkManager = toolbox->linkManager();
_multiVehicleManager = toolbox->multiVehicleManager();
_mapEngineManager = toolbox->mapEngineManager();
_qgcPositionManager = toolbox->qgcPositionManager();
_missionCommandTree = toolbox->missionCommandTree();
_videoManager = toolbox->videoManager();
_mavlinkLogManager = toolbox->mavlinkLogManager();
_corePlugin = toolbox->corePlugin();
_firmwarePluginManager = toolbox->firmwarePluginManager();
_settingsManager = toolbox->settingsManager();
_gpsRtkFactGroup = qgcApp()->gpsRtkFactGroup();
_airspaceManager = toolbox->airspaceManager();
#if defined(QGC_GST_TAISYNC_ENABLED)
_taisyncManager = toolbox->taisyncManager();
#endif
#if defined(QGC_GST_MICROHARD_ENABLED)
_microhardManager = toolbox->microhardManager();
#endif
}
void QGroundControlQmlGlobal::saveGlobalSetting (const QString& key, const QString& value)
{
QSettings settings;
settings.beginGroup(kQmlGlobalKeyName);
settings.setValue(key, value);
}
QString QGroundControlQmlGlobal::loadGlobalSetting (const QString& key, const QString& defaultValue)
{
QSettings settings;
settings.beginGroup(kQmlGlobalKeyName);
return settings.value(key, defaultValue).toString();
}
void QGroundControlQmlGlobal::saveBoolGlobalSetting (const QString& key, bool value)
{
QSettings settings;
settings.beginGroup(kQmlGlobalKeyName);
settings.setValue(key, value);
}
bool QGroundControlQmlGlobal::loadBoolGlobalSetting (const QString& key, bool defaultValue)
{
QSettings settings;
settings.beginGroup(kQmlGlobalKeyName);
return settings.value(key, defaultValue).toBool();
}
void QGroundControlQmlGlobal::startPX4MockLink(bool sendStatusText)
{
#ifdef QT_DEBUG
MockLink::startPX4MockLink(sendStatusText);
#else
Q_UNUSED(sendStatusText);
#endif
}
void QGroundControlQmlGlobal::startGenericMockLink(bool sendStatusText)
{
#ifdef QT_DEBUG
MockLink::startGenericMockLink(sendStatusText);
#else
Q_UNUSED(sendStatusText);
#endif
}
void QGroundControlQmlGlobal::startAPMArduCopterMockLink(bool sendStatusText)
{
#ifdef QT_DEBUG
MockLink::startAPMArduCopterMockLink(sendStatusText);
#else
Q_UNUSED(sendStatusText);
#endif
}
void QGroundControlQmlGlobal::startAPMArduPlaneMockLink(bool sendStatusText)
{
#ifdef QT_DEBUG
MockLink::startAPMArduPlaneMockLink(sendStatusText);
#else
Q_UNUSED(sendStatusText);
#endif
}
void QGroundControlQmlGlobal::startAPMArduSubMockLink(bool sendStatusText)
{
#ifdef QT_DEBUG
MockLink::startAPMArduSubMockLink(sendStatusText);
#else
Q_UNUSED(sendStatusText);
#endif
}
void QGroundControlQmlGlobal::startAPMArduRoverMockLink(bool sendStatusText)
{
#ifdef QT_DEBUG
MockLink::startAPMArduRoverMockLink(sendStatusText);
#else
Q_UNUSED(sendStatusText);
#endif
}
void QGroundControlQmlGlobal::stopOneMockLink(void)
{
#ifdef QT_DEBUG
LinkManager* linkManager = qgcApp()->toolbox()->linkManager();
for (int i=0; i<linkManager->links().count(); i++) {
LinkInterface* link = linkManager->links()[i];
MockLink* mockLink = qobject_cast<MockLink*>(link);
if (mockLink) {
linkManager->disconnectLink(mockLink);
return;
}
}
#endif
}
void QGroundControlQmlGlobal::setIsVersionCheckEnabled(bool enable)
{
qgcApp()->toolbox()->mavlinkProtocol()->enableVersionCheck(enable);
emit isVersionCheckEnabledChanged(enable);
}
void QGroundControlQmlGlobal::setMavlinkSystemID(int id)
{
qgcApp()->toolbox()->mavlinkProtocol()->setSystemId(id);
emit mavlinkSystemIDChanged(id);
}
int QGroundControlQmlGlobal::supportedFirmwareCount()
{
return _firmwarePluginManager->supportedFirmwareTypes().count();
}
int QGroundControlQmlGlobal::supportedVehicleCount()
{
int count = 0;
QList<MAV_AUTOPILOT> list = _firmwarePluginManager->supportedFirmwareTypes();
qDebug() << "Supported Firmwares" << list.count();
foreach(auto firmware, list) {
if(firmware != MAV_AUTOPILOT_GENERIC) {
count += _firmwarePluginManager->supportedVehicleTypes(firmware).count();
qDebug() << "Firmware" << firmware << "Vehicles" << _firmwarePluginManager->supportedVehicleTypes(firmware).count();
}
}
return count;
}
bool QGroundControlQmlGlobal::px4ProFirmwareSupported()
{
return _firmwarePluginManager->supportedFirmwareTypes().contains(MAV_AUTOPILOT_PX4);
}
bool QGroundControlQmlGlobal::apmFirmwareSupported()
{
return _firmwarePluginManager->supportedFirmwareTypes().contains(MAV_AUTOPILOT_ARDUPILOTMEGA);
}
bool QGroundControlQmlGlobal::linesIntersect(QPointF line1A, QPointF line1B, QPointF line2A, QPointF line2B)
{
QPointF intersectPoint;
return QLineF(line1A, line1B).intersect(QLineF(line2A, line2B), &intersectPoint) == QLineF::BoundedIntersection &&
intersectPoint != line1A && intersectPoint != line1B;
}
void QGroundControlQmlGlobal::setSkipSetupPage(bool skip)
{
if(_skipSetupPage != skip) {
_skipSetupPage = skip;
emit skipSetupPageChanged();
}
}
void QGroundControlQmlGlobal::setFlightMapPosition(QGeoCoordinate& coordinate)
{
if (coordinate != flightMapPosition()) {
_coord.setLatitude(coordinate.latitude());
_coord.setLongitude(coordinate.longitude());
emit flightMapPositionChanged(coordinate);
}
}
void QGroundControlQmlGlobal::setFlightMapZoom(double zoom)
{
if (zoom != flightMapZoom()) {
_zoom = zoom;
emit flightMapZoomChanged(zoom);
}
}
<commit_msg>Remove debug output<commit_after>/****************************************************************************
*
* (c) 2009-2016 QGROUNDCONTROL PROJECT <http://www.qgroundcontrol.org>
*
* QGroundControl is licensed according to the terms in the file
* COPYING.md in the root of the source code directory.
*
****************************************************************************/
/// @file
/// @author Don Gagne <don@thegagnes.com>
#include "QGroundControlQmlGlobal.h"
#include <QSettings>
#include <QLineF>
#include <QPointF>
static const char* kQmlGlobalKeyName = "QGCQml";
const char* QGroundControlQmlGlobal::_flightMapPositionSettingsGroup = "FlightMapPosition";
const char* QGroundControlQmlGlobal::_flightMapPositionLatitudeSettingsKey = "Latitude";
const char* QGroundControlQmlGlobal::_flightMapPositionLongitudeSettingsKey = "Longitude";
const char* QGroundControlQmlGlobal::_flightMapZoomSettingsKey = "FlightMapZoom";
QGeoCoordinate QGroundControlQmlGlobal::_coord = QGeoCoordinate(0.0,0.0);
double QGroundControlQmlGlobal::_zoom = 2;
QGroundControlQmlGlobal::QGroundControlQmlGlobal(QGCApplication* app, QGCToolbox* toolbox)
: QGCTool (app, toolbox)
{
// We clear the parent on this object since we run into shutdown problems caused by hybrid qml app. Instead we let it leak on shutdown.
setParent(nullptr);
// Load last coordinates and zoom from config file
QSettings settings;
settings.beginGroup(_flightMapPositionSettingsGroup);
_coord.setLatitude(settings.value(_flightMapPositionLatitudeSettingsKey, _coord.latitude()).toDouble());
_coord.setLongitude(settings.value(_flightMapPositionLongitudeSettingsKey, _coord.longitude()).toDouble());
_zoom = settings.value(_flightMapZoomSettingsKey, _zoom).toDouble();
}
QGroundControlQmlGlobal::~QGroundControlQmlGlobal()
{
// Save last coordinates and zoom to config file
QSettings settings;
settings.beginGroup(_flightMapPositionSettingsGroup);
settings.setValue(_flightMapPositionLatitudeSettingsKey, _coord.latitude());
settings.setValue(_flightMapPositionLongitudeSettingsKey, _coord.longitude());
settings.setValue(_flightMapZoomSettingsKey, _zoom);
}
void QGroundControlQmlGlobal::setToolbox(QGCToolbox* toolbox)
{
QGCTool::setToolbox(toolbox);
_linkManager = toolbox->linkManager();
_multiVehicleManager = toolbox->multiVehicleManager();
_mapEngineManager = toolbox->mapEngineManager();
_qgcPositionManager = toolbox->qgcPositionManager();
_missionCommandTree = toolbox->missionCommandTree();
_videoManager = toolbox->videoManager();
_mavlinkLogManager = toolbox->mavlinkLogManager();
_corePlugin = toolbox->corePlugin();
_firmwarePluginManager = toolbox->firmwarePluginManager();
_settingsManager = toolbox->settingsManager();
_gpsRtkFactGroup = qgcApp()->gpsRtkFactGroup();
_airspaceManager = toolbox->airspaceManager();
#if defined(QGC_GST_TAISYNC_ENABLED)
_taisyncManager = toolbox->taisyncManager();
#endif
#if defined(QGC_GST_MICROHARD_ENABLED)
_microhardManager = toolbox->microhardManager();
#endif
}
void QGroundControlQmlGlobal::saveGlobalSetting (const QString& key, const QString& value)
{
QSettings settings;
settings.beginGroup(kQmlGlobalKeyName);
settings.setValue(key, value);
}
QString QGroundControlQmlGlobal::loadGlobalSetting (const QString& key, const QString& defaultValue)
{
QSettings settings;
settings.beginGroup(kQmlGlobalKeyName);
return settings.value(key, defaultValue).toString();
}
void QGroundControlQmlGlobal::saveBoolGlobalSetting (const QString& key, bool value)
{
QSettings settings;
settings.beginGroup(kQmlGlobalKeyName);
settings.setValue(key, value);
}
bool QGroundControlQmlGlobal::loadBoolGlobalSetting (const QString& key, bool defaultValue)
{
QSettings settings;
settings.beginGroup(kQmlGlobalKeyName);
return settings.value(key, defaultValue).toBool();
}
void QGroundControlQmlGlobal::startPX4MockLink(bool sendStatusText)
{
#ifdef QT_DEBUG
MockLink::startPX4MockLink(sendStatusText);
#else
Q_UNUSED(sendStatusText);
#endif
}
void QGroundControlQmlGlobal::startGenericMockLink(bool sendStatusText)
{
#ifdef QT_DEBUG
MockLink::startGenericMockLink(sendStatusText);
#else
Q_UNUSED(sendStatusText);
#endif
}
void QGroundControlQmlGlobal::startAPMArduCopterMockLink(bool sendStatusText)
{
#ifdef QT_DEBUG
MockLink::startAPMArduCopterMockLink(sendStatusText);
#else
Q_UNUSED(sendStatusText);
#endif
}
void QGroundControlQmlGlobal::startAPMArduPlaneMockLink(bool sendStatusText)
{
#ifdef QT_DEBUG
MockLink::startAPMArduPlaneMockLink(sendStatusText);
#else
Q_UNUSED(sendStatusText);
#endif
}
void QGroundControlQmlGlobal::startAPMArduSubMockLink(bool sendStatusText)
{
#ifdef QT_DEBUG
MockLink::startAPMArduSubMockLink(sendStatusText);
#else
Q_UNUSED(sendStatusText);
#endif
}
void QGroundControlQmlGlobal::startAPMArduRoverMockLink(bool sendStatusText)
{
#ifdef QT_DEBUG
MockLink::startAPMArduRoverMockLink(sendStatusText);
#else
Q_UNUSED(sendStatusText);
#endif
}
void QGroundControlQmlGlobal::stopOneMockLink(void)
{
#ifdef QT_DEBUG
LinkManager* linkManager = qgcApp()->toolbox()->linkManager();
for (int i=0; i<linkManager->links().count(); i++) {
LinkInterface* link = linkManager->links()[i];
MockLink* mockLink = qobject_cast<MockLink*>(link);
if (mockLink) {
linkManager->disconnectLink(mockLink);
return;
}
}
#endif
}
void QGroundControlQmlGlobal::setIsVersionCheckEnabled(bool enable)
{
qgcApp()->toolbox()->mavlinkProtocol()->enableVersionCheck(enable);
emit isVersionCheckEnabledChanged(enable);
}
void QGroundControlQmlGlobal::setMavlinkSystemID(int id)
{
qgcApp()->toolbox()->mavlinkProtocol()->setSystemId(id);
emit mavlinkSystemIDChanged(id);
}
int QGroundControlQmlGlobal::supportedFirmwareCount()
{
return _firmwarePluginManager->supportedFirmwareTypes().count();
}
int QGroundControlQmlGlobal::supportedVehicleCount()
{
int count = 0;
QList<MAV_AUTOPILOT> list = _firmwarePluginManager->supportedFirmwareTypes();
foreach(auto firmware, list) {
if(firmware != MAV_AUTOPILOT_GENERIC) {
count += _firmwarePluginManager->supportedVehicleTypes(firmware).count();
}
}
return count;
}
bool QGroundControlQmlGlobal::px4ProFirmwareSupported()
{
return _firmwarePluginManager->supportedFirmwareTypes().contains(MAV_AUTOPILOT_PX4);
}
bool QGroundControlQmlGlobal::apmFirmwareSupported()
{
return _firmwarePluginManager->supportedFirmwareTypes().contains(MAV_AUTOPILOT_ARDUPILOTMEGA);
}
bool QGroundControlQmlGlobal::linesIntersect(QPointF line1A, QPointF line1B, QPointF line2A, QPointF line2B)
{
QPointF intersectPoint;
return QLineF(line1A, line1B).intersect(QLineF(line2A, line2B), &intersectPoint) == QLineF::BoundedIntersection &&
intersectPoint != line1A && intersectPoint != line1B;
}
void QGroundControlQmlGlobal::setSkipSetupPage(bool skip)
{
if(_skipSetupPage != skip) {
_skipSetupPage = skip;
emit skipSetupPageChanged();
}
}
void QGroundControlQmlGlobal::setFlightMapPosition(QGeoCoordinate& coordinate)
{
if (coordinate != flightMapPosition()) {
_coord.setLatitude(coordinate.latitude());
_coord.setLongitude(coordinate.longitude());
emit flightMapPositionChanged(coordinate);
}
}
void QGroundControlQmlGlobal::setFlightMapZoom(double zoom)
{
if (zoom != flightMapZoom()) {
_zoom = zoom;
emit flightMapZoomChanged(zoom);
}
}
<|endoftext|> |
<commit_before>/*-----------------------------------------------------------------------------
This source file is a part of Hopsan
Copyright (c) 2009 to present year, Hopsan Group
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
For license details and information about the Hopsan Group see the files
GPLv3 and HOPSANGROUP in the Hopsan source code root directory
For author and contributor information see the AUTHORS file
-----------------------------------------------------------------------------*/
//!
//! @file AuxiliarySimulationFunctions.cc
//! @author Robert Braun <robert.braun@liu.se>
//! @date 2010-06-30
//!
//! @brief Contains a second order integrator utility with provision for some damping
//!
//$Id$
#include "ComponentUtilities/AuxiliarySimulationFunctions.h"
#include <cmath>
#include <limits>
using namespace hopsan;
//! @defgroup ComponentUtilities ComponentUtilities
//! @defgroup AuxiliarySimulationFunctions AuxiliarySimulationFunctions
//! @ingroup ComponentUtilities
//! @defgroup ComponentUtilityClasses ComponentUtilityClasses
//! @ingroup ComponentUtilities
//! @brief Limits a value so it is between min and max
//! @ingroup AuxiliarySimulationFunctions
//! @param &rValue Reference pointer to the value
//! @param min Lower limit of the value
//! @param max Upper limit of the value
void hopsan::limitValue(double &rValue, double min, double max)
{
if(min>max)
{
double temp;
temp = max;
max = min;
min = temp;
}
if(rValue > max)
{
rValue = max;
}
else if(rValue < min)
{
rValue = min;
}
}
//! @brief checks if two double variables are equal with a tolerance
//! @ingroup AuxiliarySimulationFunctions
//! @param [in] x First value
//! @param [in] y Second value
//! @param [in] epsilon Allowed relative error
//! @note Based on http://floating-point-gui.de/errors/comparison (20130429)
bool hopsan::fuzzyEqual(const double x, const double y, const double epsilon)
{
const double absX = fabs(x);
const double absY = fabs(y);
const double diff = fabs(x-y);
// shortcut, handles infinities
if (x == y)
{
return true;
}
// a or b is zero or both are extremely close to it
// relative error is less meaningful here
else if (x == 0 || y == 0 || diff < epsilon * std::numeric_limits<double>::epsilon() ) //! @todo Added multiplication with epsilon here, otherwise it may return false without ever reaching the second comparison
{
return diff < (epsilon * std::numeric_limits<double>::epsilon() );
}
// use relative error
else
{
return diff / (absX + absY) < epsilon;
}
}
//! @ingroup AuxiliarySimulationFunctions
double hopsan::signedSquareL(const double x, const double x0)
{
// return (-sqrt(x0) + sqrt(x0 + fabs(x))) * sign(x);
return fabs(x)*pow(1/(pow(x0,2) + pow(fabs(x),2)),0.25)*sign(x);
}
//! @ingroup AuxiliarySimulationFunctions
double hopsan::dxSignedSquareL(const double x, const double x0)
{
// return (1.0 / (sqrt(x0 + fabs(x)) * 2.0));
return (pow(1/(pow(x0,2) + pow(fabs(x),2)),1.25)*(2*pow(x0,2) + pow(fabs(x),2))*
dxAbs(x)*sign(x))/2.;
}
//! @ingroup AuxiliarySimulationFunctions
double hopsan::squareAbsL(const double x, const double x0)
{
return (-sqrt(x0) + sqrt(x0 + fabs(x)));
}
//! @ingroup AuxiliarySimulationFunctions
double hopsan::dxSquareAbsL(const double x, const double x0)
{
return 1.0 / (sqrt(x0 + fabs(x)) * 2.0) * sign(x);
}
//! @brief Safe variant of atan2
//! @ingroup AuxiliarySimulationFunctions
double hopsan::Atan2L(const double y, const double x)
{
if (x!=0 || y!=0)
{
return atan2(y,x);
}
else
{
return 0;
}
}
//! @brief Returns 1.0 if input variables have same sign, else returns 0.0
//! @ingroup AuxiliarySimulationFunctions
double hopsan::equalSigns(const double x, const double y)
{
// //! @warning This will NOT work (double != double)
// if (hopsan::sign(x) != hopsan::sign(y)) {
// return 0.0;
// }
// return 1.0;
if ( ((x < 0.0) && ( y < 0.0)) || ((x >= 0.0) && (y >= 0.0)) )
{
return 1.0;
}
else
{
return 0.0;
}
}
//! @brief Safe variant of asin
//! @ingroup AuxiliarySimulationFunctions
double hopsan::ArcSinL(const double x)
{
return asin(limit(x,-0.9999999999,0.9999999999));
}
//! @brief derivative of AsinL
//! @ingroup AuxiliarySimulationFunctions
double hopsan::dxArcSinL(const double x)
{
return 1.0/sqrt(1 - pow(limit(x,-0.9999999999,0.9999999999),2));
}
//! @brief difference between two angles, fi1-fi2
//! @ingroup AuxiliarySimulationFunctions
double hopsan::diffAngle(const double fi1, const double fi2)
{ double output;
double output0 = fi1-fi2;
double output1 = fi1-fi2 + 2.0*pi;
double output2 = fi1-fi2 - 2.0*pi;
output = output0;
if (fabs(output0)>= fabs(output1)){output = output1;}
if (fabs(output0)>= fabs(output2)){output = output2;}
return output;
}
//! @brief Lift coefficient for aircraft model
//! @ingroup AuxiliarySimulationFunctions
double hopsan::CLift(const double alpha, const double CLalpha, const double ap, const double an, const double awp, const double awn)
{
return (1 - 1/(1 + pow(2.71828,(-2*(-alpha - an))/awn)) - 1/(1 + pow(2.71828,(-2*(alpha - ap))/awp)))*alpha*
CLalpha + 0.707107*(1/(1 + pow(2.71828,(-2*(-alpha - an))/awn)) +
1/(1 + pow(2.71828,(-2*(alpha - ap))/awp)))*sin(2*alpha);
}
//! @brief Induced drag coefficient for aircraft model
//! @ingroup AuxiliarySimulationFunctions
double hopsan::CDragInd(const double alpha, const double AR, const double e, const double CLalpha, const double ap, const double an, const double awp, const double awn)
{
return (0.31831*(1 - 1/(1 + pow(2.71828,(-2*(-alpha - an))/awn)) - 1/(1 + pow(2.71828,(-2*(alpha - ap))/awp)))*
pow(alpha,2)*pow(CLalpha,2))/(AR*e) +
(1/(1 + pow(2.71828,(-2*(-alpha - an))/awn)) + 1/(1 + pow(2.71828,(-2*(alpha - ap))/awp)))*
pow(sin(alpha),2);
}
//! @brief Moment coefficient for aircraft model
//! @ingroup AuxiliarySimulationFunctions
double hopsan::CMoment(const double alpha, const double Cm0, const double Cmfs, const double ap, const double an, const double awp, const double awn)
{
return (1 - 1/(1 + pow(2.71828,(-2*(-alpha - an))/awn)) - 1/(1 + pow(2.71828,(-2*(alpha - ap))/awp)))*Cm0 +
(1/(1 + pow(2.71828,(-2*(-alpha - an))/awn)) + 1/(1 + pow(2.71828,(-2*(alpha - ap))/awp)))*Cmfs*sign(alpha);
}
//! @brief Segment area, used to calculate valve openings with circular holes
//! @ingroup AuxiliarySimulationFunctions
double hopsan::segare(const double x, const double d)
{
double x1;
x1=x;
if(x < 0)
{
x1=0;
}
else
{
if(x > d)
{
x1=d;
}
else
{
x1=x;
}
}
return -(d*(2*(d - 2*x1)*sqrt(((d - x1)*x1)/pow(d,2)) - d*acos(1 - (2*x1)/d)))/4.;
}
//! @brief Segment area, used to calculate valve openings with circular holes
//! @ingroup AuxiliarySimulationFunctions
double hopsan::dxSegare(const double x, const double d)
{
double x1;
x1=x;
if(x < 0)
{
x1=0;
}
else
{
if(x > d)
{
x1=d;
}
else
{
x1=x;
}
}
return 2*sqrt((d - x)*x);
}
//! @brief Overloads void hopsan::limitValue() with a return value.
//! @ingroup AuxiliarySimulationFunctions
//! @see void hopsan::limitValue(&value, min, max)
//! @param x Value to be limited
//! @param xmin Minimum value of x
//! @param xmax Maximum value of x
double hopsan::limit(const double x, const double xmin, const double xmax)
{
double output = x;
limitValue(output, xmin, xmax);
return output;
}
//! @brief Limits a value to a lower limit
//! @ingroup AuxiliarySimulationFunctions
//! @param x Value to be limited
//! @param xmin Minimum value of x
double hopsan::lowLimit(const double x, const double xmin)
{
if(x < xmin)
{
return xmin;
}
else
{
return x;
}
}
//! @brief Sets the derivative of x to zero if x is outside of limits.
//! @ingroup AuxiliarySimulationFunctions
//! @details Returns 1.0 if x is within limits, else 0.0. Used to make the derivative of x zero if limit is reached.
//! @param x Value whose derivative is to be limited
//! @param xmin Minimum value of x
//! @param xmax Maximum value of x
//! @returns Limited derivative of x
double hopsan::dxLimit(const double x, const double xmin, const double xmax)
{
if (x >= xmax) { return 0.000000001; }
if (x <= xmin) { return 0.000000001; }
return 1.0;
}
//! @brief Sets the derivative of x to zero if x is outside of limits.
//! @ingroup AuxiliarySimulationFunctions
//! @details Returns 1.0 if x is within limits, else 0.0. Used to make the derivative of x zero if limit is reached.
//! @param x Value whose derivative is to be limited
//! @param xmin Minimum value of x
//! @returns Limited derivative of x
double hopsan::dxLowLimit(const double x,const double xmin)
{
if (x <= xmin) { return 0.000000001; }
return 1.0;
}
//! @brief Sets the derivative of x to zero if x is outside of limits.
//! @ingroup AuxiliarySimulationFunctions
//! @details Returns 1.0 if x is within limits, else 0.0. Used to make the derivative of x zero if limit is reached.
//! @param x Value whose derivative is to be limited
//! @param xmin Minimum value of x
//! @returns Limited derivative of x
double hopsan::dxLowLimit2(const double x, const double sx, const double xmin)
{
if (x <= xmin && sx <= 0.0) { return 0.000000001; }
return 1.0;
}
//! @brief Limits the derivative of x when x is outside of its limits.
//! @ingroup AuxiliarySimulationFunctions
//! Returns 1.0 if x is within borders, or if x is outside borders but derivative has opposite sign (so that x can only move back to the limited range).
//! @param x Value whose derivative is to be limited
//! @param xmin Minimum value of x
//! @param xmax Maximum value of x
//! @returns Limited derivative of x
double hopsan::dxLimit2(const double x, const double sx, const double xmin, const double xmax)
{
if (x >= xmax && sx >= 0.0) { return 0.000000001; }
if (x <= xmin && sx <= 0.0) { return 0.000000001; }
return 1.0;
}
//! @brief Returns the algebraic quotient x/y with any fractional parts discarded
//! @ingroup AuxiliarySimlationFunctions
//! @ingroup ModelicaWrapperFunctions
//! @param x Numerator
//! @param y Denominator
//! @returns Algebraic quotient with any fractional parts discarded
double hopsan::div(const double x, const double y)
{
if(x/y > 0)
{
return floor(x/y);
}
else
{
return ceil(x/y);
}
}
<commit_msg>Fixed compiler warning, and code cleanup<commit_after>/*-----------------------------------------------------------------------------
This source file is a part of Hopsan
Copyright (c) 2009 to present year, Hopsan Group
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
For license details and information about the Hopsan Group see the files
GPLv3 and HOPSANGROUP in the Hopsan source code root directory
For author and contributor information see the AUTHORS file
-----------------------------------------------------------------------------*/
//!
//! @file AuxiliarySimulationFunctions.cc
//! @author Robert Braun <robert.braun@liu.se>
//! @date 2010-06-30
//!
//! @brief Contains a second order integrator utility with provision for some damping
//!
//$Id$
#include "ComponentUtilities/AuxiliarySimulationFunctions.h"
#include <cmath>
#include <limits>
using namespace hopsan;
//! @defgroup ComponentUtilities ComponentUtilities
//! @defgroup AuxiliarySimulationFunctions AuxiliarySimulationFunctions
//! @ingroup ComponentUtilities
//! @defgroup ComponentUtilityClasses ComponentUtilityClasses
//! @ingroup ComponentUtilities
//! @brief Limits a value so it is between min and max
//! @ingroup AuxiliarySimulationFunctions
//! @param &rValue Reference pointer to the value
//! @param min Lower limit of the value
//! @param max Upper limit of the value
void hopsan::limitValue(double &rValue, double min, double max)
{
if(min>max)
{
double temp;
temp = max;
max = min;
min = temp;
}
if(rValue > max)
{
rValue = max;
}
else if(rValue < min)
{
rValue = min;
}
}
//! @brief checks if two double variables are equal with a tolerance
//! @ingroup AuxiliarySimulationFunctions
//! @param [in] x First value
//! @param [in] y Second value
//! @param [in] epsilon Allowed relative error
//! @note Based on http://floating-point-gui.de/errors/comparison (20130429)
bool hopsan::fuzzyEqual(const double x, const double y, const double epsilon)
{
const double absX = fabs(x);
const double absY = fabs(y);
const double diff = fabs(x-y);
// shortcut, handles infinities
if (x == y)
{
return true;
}
// a or b is zero or both are extremely close to it
// relative error is less meaningful here
else if (x == 0 || y == 0 || diff < epsilon * std::numeric_limits<double>::epsilon() ) //! @todo Added multiplication with epsilon here, otherwise it may return false without ever reaching the second comparison
{
return diff < (epsilon * std::numeric_limits<double>::epsilon() );
}
// use relative error
else
{
return diff / (absX + absY) < epsilon;
}
}
//! @ingroup AuxiliarySimulationFunctions
double hopsan::signedSquareL(const double x, const double x0)
{
// return (-sqrt(x0) + sqrt(x0 + fabs(x))) * sign(x);
return fabs(x)*pow(1/(pow(x0,2) + pow(fabs(x),2)),0.25)*sign(x);
}
//! @ingroup AuxiliarySimulationFunctions
double hopsan::dxSignedSquareL(const double x, const double x0)
{
// return (1.0 / (sqrt(x0 + fabs(x)) * 2.0));
return (pow(1/(pow(x0,2) + pow(fabs(x),2)),1.25)*(2*pow(x0,2) + pow(fabs(x),2))*
dxAbs(x)*sign(x))/2.;
}
//! @ingroup AuxiliarySimulationFunctions
double hopsan::squareAbsL(const double x, const double x0)
{
return (-sqrt(x0) + sqrt(x0 + fabs(x)));
}
//! @ingroup AuxiliarySimulationFunctions
double hopsan::dxSquareAbsL(const double x, const double x0)
{
return 1.0 / (sqrt(x0 + fabs(x)) * 2.0) * sign(x);
}
//! @brief Safe variant of atan2
//! @ingroup AuxiliarySimulationFunctions
double hopsan::Atan2L(const double y, const double x)
{
if (x!=0 || y!=0)
{
return atan2(y,x);
}
else
{
return 0;
}
}
//! @brief Returns 1.0 if input variables have same sign, else returns 0.0
//! @ingroup AuxiliarySimulationFunctions
double hopsan::equalSigns(const double x, const double y)
{
// //! @warning This will NOT work (double != double)
// if (hopsan::sign(x) != hopsan::sign(y)) {
// return 0.0;
// }
// return 1.0;
if ( ((x < 0.0) && ( y < 0.0)) || ((x >= 0.0) && (y >= 0.0)) )
{
return 1.0;
}
else
{
return 0.0;
}
}
//! @brief Safe variant of asin
//! @ingroup AuxiliarySimulationFunctions
double hopsan::ArcSinL(const double x)
{
return asin(limit(x,-0.9999999999,0.9999999999));
}
//! @brief derivative of AsinL
//! @ingroup AuxiliarySimulationFunctions
double hopsan::dxArcSinL(const double x)
{
return 1.0/sqrt(1 - pow(limit(x,-0.9999999999,0.9999999999),2));
}
//! @brief difference between two angles, fi1-fi2
//! @ingroup AuxiliarySimulationFunctions
double hopsan::diffAngle(const double fi1, const double fi2)
{ double output;
double output0 = fi1-fi2;
double output1 = fi1-fi2 + 2.0*pi;
double output2 = fi1-fi2 - 2.0*pi;
output = output0;
if (fabs(output0)>= fabs(output1)){output = output1;}
if (fabs(output0)>= fabs(output2)){output = output2;}
return output;
}
//! @brief Lift coefficient for aircraft model
//! @ingroup AuxiliarySimulationFunctions
double hopsan::CLift(const double alpha, const double CLalpha, const double ap, const double an, const double awp, const double awn)
{
return (1 - 1/(1 + pow(2.71828,(-2*(-alpha - an))/awn)) - 1/(1 + pow(2.71828,(-2*(alpha - ap))/awp)))*alpha*
CLalpha + 0.707107*(1/(1 + pow(2.71828,(-2*(-alpha - an))/awn)) +
1/(1 + pow(2.71828,(-2*(alpha - ap))/awp)))*sin(2*alpha);
}
//! @brief Induced drag coefficient for aircraft model
//! @ingroup AuxiliarySimulationFunctions
double hopsan::CDragInd(const double alpha, const double AR, const double e, const double CLalpha, const double ap, const double an, const double awp, const double awn)
{
return (0.31831*(1 - 1/(1 + pow(2.71828,(-2*(-alpha - an))/awn)) - 1/(1 + pow(2.71828,(-2*(alpha - ap))/awp)))*
pow(alpha,2)*pow(CLalpha,2))/(AR*e) +
(1/(1 + pow(2.71828,(-2*(-alpha - an))/awn)) + 1/(1 + pow(2.71828,(-2*(alpha - ap))/awp)))*
pow(sin(alpha),2);
}
//! @brief Moment coefficient for aircraft model
//! @ingroup AuxiliarySimulationFunctions
double hopsan::CMoment(const double alpha, const double Cm0, const double Cmfs, const double ap, const double an, const double awp, const double awn)
{
return (1 - 1/(1 + pow(2.71828,(-2*(-alpha - an))/awn)) - 1/(1 + pow(2.71828,(-2*(alpha - ap))/awp)))*Cm0 +
(1/(1 + pow(2.71828,(-2*(-alpha - an))/awn)) + 1/(1 + pow(2.71828,(-2*(alpha - ap))/awp)))*Cmfs*sign(alpha);
}
//! @brief Segment area, used to calculate valve openings with circular holes
//! @param[in] x How far into the circle
//! @param[in] d Circle diameter
//! @ingroup AuxiliarySimulationFunctions
double hopsan::segare(const double x, const double d)
{
double x1;
if(x < 0)
{
x1=0;
}
else if(x > d)
{
x1=d;
}
else
{
x1=x;
}
return -(d*(2.*(d - 2.*x1)*sqrt(((d - x1)*x1)/pow(d,2.)) - d*acos(1. - (2.*x1)/d)))/4.;
}
//! @brief Segment area, used to calculate valve openings with circular holes
//! @param[in] x How far into the circle
//! @param[in] d Circle diameter
//! @ingroup AuxiliarySimulationFunctions
double hopsan::dxSegare(const double x, const double d)
{
double x1;
if(x < 0)
{
x1=0;
}
else if(x > d)
{
x1=d;
}
else
{
x1=x;
}
return 2.*sqrt((d - x1)*x1);
}
//! @brief Overloads void hopsan::limitValue() with a return value.
//! @ingroup AuxiliarySimulationFunctions
//! @see void hopsan::limitValue(&value, min, max)
//! @param x Value to be limited
//! @param xmin Minimum value of x
//! @param xmax Maximum value of x
double hopsan::limit(const double x, const double xmin, const double xmax)
{
double output = x;
limitValue(output, xmin, xmax);
return output;
}
//! @brief Limits a value to a lower limit
//! @ingroup AuxiliarySimulationFunctions
//! @param x Value to be limited
//! @param xmin Minimum value of x
double hopsan::lowLimit(const double x, const double xmin)
{
if(x < xmin)
{
return xmin;
}
else
{
return x;
}
}
//! @brief Sets the derivative of x to zero if x is outside of limits.
//! @ingroup AuxiliarySimulationFunctions
//! @details Returns 1.0 if x is within limits, else 0.0. Used to make the derivative of x zero if limit is reached.
//! @param x Value whose derivative is to be limited
//! @param xmin Minimum value of x
//! @param xmax Maximum value of x
//! @returns Limited derivative of x
double hopsan::dxLimit(const double x, const double xmin, const double xmax)
{
if (x >= xmax) { return 0.000000001; }
if (x <= xmin) { return 0.000000001; }
return 1.0;
}
//! @brief Sets the derivative of x to zero if x is outside of limits.
//! @ingroup AuxiliarySimulationFunctions
//! @details Returns 1.0 if x is within limits, else 0.0. Used to make the derivative of x zero if limit is reached.
//! @param x Value whose derivative is to be limited
//! @param xmin Minimum value of x
//! @returns Limited derivative of x
double hopsan::dxLowLimit(const double x,const double xmin)
{
if (x <= xmin) { return 0.000000001; }
return 1.0;
}
//! @brief Sets the derivative of x to zero if x is outside of limits.
//! @ingroup AuxiliarySimulationFunctions
//! @details Returns 1.0 if x is within limits, else 0.0. Used to make the derivative of x zero if limit is reached.
//! @param x Value whose derivative is to be limited
//! @param xmin Minimum value of x
//! @returns Limited derivative of x
double hopsan::dxLowLimit2(const double x, const double sx, const double xmin)
{
if (x <= xmin && sx <= 0.0) { return 0.000000001; }
return 1.0;
}
//! @brief Limits the derivative of x when x is outside of its limits.
//! @ingroup AuxiliarySimulationFunctions
//! Returns 1.0 if x is within borders, or if x is outside borders but derivative has opposite sign (so that x can only move back to the limited range).
//! @param x Value whose derivative is to be limited
//! @param xmin Minimum value of x
//! @param xmax Maximum value of x
//! @returns Limited derivative of x
double hopsan::dxLimit2(const double x, const double sx, const double xmin, const double xmax)
{
if (x >= xmax && sx >= 0.0) { return 0.000000001; }
if (x <= xmin && sx <= 0.0) { return 0.000000001; }
return 1.0;
}
//! @brief Returns the algebraic quotient x/y with any fractional parts discarded
//! @ingroup AuxiliarySimlationFunctions
//! @ingroup ModelicaWrapperFunctions
//! @param x Numerator
//! @param y Denominator
//! @returns Algebraic quotient with any fractional parts discarded
double hopsan::div(const double x, const double y)
{
if(x/y > 0)
{
return floor(x/y);
}
else
{
return ceil(x/y);
}
}
<|endoftext|> |
<commit_before>#ifndef GNR_COROUTINE_HPP
# define GNR_COROUTINE_HPP
# pragma once
#include <cassert>
#include <cstdint>
#include <functional>
#include <memory>
#include "savestate.hpp"
namespace gnr
{
template <template <typename> class Function = std::function>
class coroutine
{
public:
enum : std::size_t { default_stack_size = 512 * 1024 };
enum status : std::uint8_t
{
INITIALIZED,
RUNNING,
TERMINATED
};
private:
statebuf env_in_;
statebuf env_out_;
enum status status_{TERMINATED};
std::size_t const N_;
std::unique_ptr<char[]> stack_;
Function<void()> f_;
public:
explicit coroutine(std::size_t const N = default_stack_size) :
N_(N),
stack_(new char[N])
{
}
template <typename F,
typename = std::enable_if_t<!std::is_integral<F>{}>
>
explicit coroutine(F&& f, std::size_t const N = default_stack_size) :
coroutine(N)
{
assign(std::forward<F>(f));
}
coroutine(coroutine&&) = default;
coroutine& operator=(coroutine&&) = default;
auto status() const noexcept
{
return status_;
}
auto is_terminated() const noexcept
{
return TERMINATED == status_;
}
template <typename F>
void assign(F&& f)
{
f_ = [this, f = std::forward<F>(f)]()
{
status_ = RUNNING;
f(*this);
status_ = TERMINATED;
yield();
};
status_ = INITIALIZED;
}
#if defined(__GNUC__)
void yield() noexcept __attribute__ ((noinline))
#elif defined(_MSC_VER)
__declspec(noinline) void yield() noexcept
#endif
{
#if defined(__GNUC__)
#if defined(i386) || defined(__i386) || defined(__i386__)
asm volatile ("":::"eax", "ebx", "ecx", "edx", "esi", "edi");
#elif defined(__amd64__) || defined(__amd64) || defined(__x86_64__) || defined(__x86_64)
asm volatile ("":::"rax", "rbx", "rcx", "rdx", "rsi", "rdi", "r8", "r9", "r10", "r11", "r12", "r13", "r14", "r15");
#endif
#endif
if (!savestate(env_out_))
{
restorestate(env_in_);
}
}
#if defined(__GNUC__)
void resume() noexcept __attribute__ ((noinline))
#elif defined(_MSC_VER)
__declspec(noinline) void resume() noexcept
#endif
{
#if defined(__GNUC__)
#if defined(i386) || defined(__i386) || defined(__i386__)
asm volatile ("":::"eax", "ebx", "ecx", "edx", "esi", "edi");
#elif defined(__amd64__) || defined(__amd64) || defined(__x86_64__) || defined(__x86_64)
asm volatile ("":::"rax", "rbx", "rcx", "rdx", "rsi", "rdi", "r8", "r9", "r10", "r11", "r12", "r13", "r14", "r15");
#endif
#endif
assert(TERMINATED != status());
if (savestate(env_in_))
{
return;
}
else if (RUNNING == status())
{
restorestate(env_out_);
}
else
{
#if defined(__GNUC__)
// stack switch
#if defined(i386) || defined(__i386) || defined(__i386__)
asm volatile(
"movl %0, %%esp"
:
: "r" (stack_.get() + N_)
);
#elif defined(__amd64__) || defined(__amd64) || defined(__x86_64__) || defined(__x86_64)
asm volatile(
"movq %0, %%rsp"
:
: "r" (stack_.get() + N_)
);
#else
#error "can't switch stack frame"
#endif
#elif defined(_MSC_VER)
auto const p(stack_.get() + N_);
_asm mov esp, p
#else
#error "can't switch stack frame"
#endif
f_();
}
}
};
}
#endif // GNR_COROUTINE_HPP
<commit_msg>some fixes<commit_after>#ifndef GNR_COROUTINE_HPP
# define GNR_COROUTINE_HPP
# pragma once
#include <cassert>
#include <cstdint>
#include <functional>
#include <memory>
#include "savestate.hpp"
namespace gnr
{
template <template <typename> class Function = std::function>
class coroutine
{
public:
enum : std::size_t { default_stack_size = 512 * 1024 };
enum status : std::uint8_t
{
INITIALIZED,
RUNNING,
TERMINATED
};
private:
statebuf env_in_;
statebuf env_out_;
enum status status_{TERMINATED};
std::size_t const N_;
std::unique_ptr<char[]> stack_;
Function<void()> f_;
public:
explicit coroutine(std::size_t const N = default_stack_size) :
N_(N),
stack_(new char[N])
{
}
template <typename F,
typename = std::enable_if_t<!std::is_integral<F>{}>
>
explicit coroutine(F&& f, std::size_t const N = default_stack_size) :
coroutine(N)
{
assign(std::forward<F>(f));
}
coroutine(coroutine&&) = default;
coroutine& operator=(coroutine&&) = default;
auto status() const noexcept
{
return status_;
}
auto is_terminated() const noexcept
{
return TERMINATED == status_;
}
template <typename F>
void assign(F&& f)
{
f_ = [this, f = std::forward<F>(f)]()
{
status_ = RUNNING;
f(*this);
status_ = TERMINATED;
yield();
};
status_ = INITIALIZED;
}
#if defined(__GNUC__)
void yield() noexcept __attribute__ ((noinline))
#elif defined(_MSC_VER)
__declspec(noinline) void yield() noexcept
#else
# error "unsupported compiler"
#endif
{
#if defined(__GNUC__)
#if defined(i386) || defined(__i386) || defined(__i386__)
asm volatile ("":::"eax", "ebx", "ecx", "edx", "esi", "edi");
#elif defined(__amd64__) || defined(__amd64) || defined(__x86_64__) || defined(__x86_64)
asm volatile ("":::"rax", "rbx", "rcx", "rdx", "rsi", "rdi", "r8", "r9", "r10", "r11", "r12", "r13", "r14", "r15");
#endif
#endif
if (!savestate(env_out_))
{
restorestate(env_in_);
}
}
#if defined(__GNUC__)
void resume() noexcept __attribute__ ((noinline))
#elif defined(_MSC_VER)
__declspec(noinline) void resume() noexcept
#endif
{
#if defined(__GNUC__)
#if defined(i386) || defined(__i386) || defined(__i386__)
asm volatile ("":::"eax", "ebx", "ecx", "edx", "esi", "edi");
#elif defined(__amd64__) || defined(__amd64) || defined(__x86_64__) || defined(__x86_64)
asm volatile ("":::"rax", "rbx", "rcx", "rdx", "rsi", "rdi", "r8", "r9", "r10", "r11", "r12", "r13", "r14", "r15");
#endif
#endif
assert(TERMINATED != status());
if (savestate(env_in_))
{
return;
}
else if (RUNNING == status())
{
restorestate(env_out_);
}
else
{
#if defined(__GNUC__)
// stack switch
#if defined(i386) || defined(__i386) || defined(__i386__)
asm volatile(
"movl %0, %%esp"
:
: "r" (stack_.get() + N_)
);
#elif defined(__amd64__) || defined(__amd64) || defined(__x86_64__) || defined(__x86_64)
asm volatile(
"movq %0, %%rsp"
:
: "r" (stack_.get() + N_)
);
#else
#error "can't switch stack frame"
#endif
#elif defined(_MSC_VER)
auto const p(stack_.get() + N_);
_asm mov esp, p
#else
#error "can't switch stack frame"
#endif
f_();
}
}
};
}
#endif // GNR_COROUTINE_HPP
<|endoftext|> |
<commit_before>/*
* Software License Agreement (Apache License)
*
* Copyright (c) 2014, Dan Solomon
*
* 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.
*/
/*
* cart_trajectory_pt.cpp
*
* Created on: Oct 3, 2014
* Author: Dan Solomon
*/
#include <tuple>
#include <map>
#include <algorithm>
#include <console_bridge/console.h>
#include <ros/console.h>
#include "descartes_core/cart_trajectory_pt.h"
#define NOT_IMPLEMENTED_ERR(ret) logError("%s not implemented", __PRETTY_FUNCTION__); return ret;
const double EQUALITY_TOLERANCE = 0.0001f;
namespace descartes_core
{
EigenSTL::vector_Affine3d uniform(const TolerancedFrame & frame, const double orient_increment,
const double pos_increment)
{
EigenSTL::vector_Affine3d rtn;
if(pos_increment < 0.0 || orient_increment < 0.0)
{
ROS_WARN_STREAM("Negative position/orientation intcrement: " << pos_increment
<< "/" << orient_increment);
rtn.clear();
return rtn;
}
Eigen::Affine3d sampled_frame;
// Calculating the number of samples for each tolerance (position and orientation)
size_t ntx, nty, ntz, nrx, nry, nrz;
if(orient_increment > 0)
{
nrx = ((frame.orientation_tolerance.x_upper - frame.orientation_tolerance.x_lower)/orient_increment) + 1;
nry = ((frame.orientation_tolerance.y_upper - frame.orientation_tolerance.y_lower)/orient_increment) + 1;
nrz = ((frame.orientation_tolerance.z_upper - frame.orientation_tolerance.z_lower)/orient_increment) + 1;
}
else
{
nrx = nry = nrz = 1;
}
if(pos_increment > 0)
{
ntx = ((frame.position_tolerance.x_upper - frame.position_tolerance.x_lower)/pos_increment) + 1;
nty = ((frame.position_tolerance.y_upper - frame.position_tolerance.y_lower)/pos_increment) + 1;
ntz = ((frame.position_tolerance.z_upper - frame.position_tolerance.z_lower)/pos_increment) + 1;
}
else
{
ntx = nty = ntz = 1;
}
// Estimating the number of samples base on tolerance zones and sampling increment.
size_t est_num_samples = ntx * nty * ntz * nrx * nry * nrz;
ROS_DEBUG_STREAM("Estimated number of samples: " << est_num_samples << ", reserving space");
rtn.reserve(est_num_samples);
//TODO: The following for loops do not ensure that the rull range is sample (lower to upper)
//since there could be round off error in the incrementing of samples. As a result, the
//exact upper bound may not be sampled. Since this isn't a final implementation, this will
//be ignored.
double rx, ry, rz, tx, ty, tz;
for(size_t ii = 0; ii < nrx; ++ii)
{
rx = frame.orientation_tolerance.x_lower + orient_increment * ii;
for(size_t jj = 0; jj < nry; ++jj)
{
ry = frame.orientation_tolerance.y_lower + orient_increment * jj;
for(size_t kk = 0; kk < nrz; ++kk)
{
rz = frame.orientation_tolerance.z_lower + orient_increment * kk;
for(size_t ll = 0; ll < ntx; ++ll)
{
tx = frame.position_tolerance.x_lower + pos_increment * ll;
for(size_t mm = 0; mm < nty; ++mm)
{
ty = frame.position_tolerance.y_lower + pos_increment * mm;
for(size_t nn = 0; nn < ntz; ++nn)
{
tz = frame.position_tolerance.z_lower + pos_increment * nn;
sampled_frame = Eigen::Translation3d(tx,ty,tz) *
Eigen::AngleAxisd(rz, Eigen::Vector3d::UnitZ()) *
Eigen::AngleAxisd(ry, Eigen::Vector3d::UnitY()) *
Eigen::AngleAxisd(rx, Eigen::Vector3d::UnitX());
rtn.push_back(sampled_frame);
}
}
}
}
}
}
ROS_DEBUG_STREAM("Uniform sampling of frame, utilizing orientation increment: " << orient_increment
<< ", and position increment: " << pos_increment
<< " resulted in " << rtn.size() << " samples");
return rtn;
}
CartTrajectoryPt::CartTrajectoryPt():
tool_base_(Eigen::Affine3d::Identity()),
tool_pt_(Eigen::Affine3d::Identity()),
wobj_base_(Eigen::Affine3d::Identity()),
wobj_pt_(Eigen::Affine3d::Identity()),
pos_increment_(0.0),
orient_increment_(0.0)
{}
CartTrajectoryPt::CartTrajectoryPt(const Frame &wobj_base, const TolerancedFrame &wobj_pt, const Frame &tool,
const TolerancedFrame &tool_pt, double pos_increment, double orient_increment):
tool_base_(tool),
tool_pt_(tool_pt),
wobj_base_(wobj_base),
wobj_pt_(wobj_pt),
pos_increment_(pos_increment),
orient_increment_(orient_increment)
{}
CartTrajectoryPt::CartTrajectoryPt(const TolerancedFrame &wobj_pt, double pos_increment,
double orient_increment):
tool_base_(Eigen::Affine3d::Identity()),
tool_pt_(Eigen::Affine3d::Identity()),
wobj_base_(Eigen::Affine3d::Identity()),
wobj_pt_(wobj_pt),
pos_increment_(pos_increment),
orient_increment_(orient_increment)
{}
CartTrajectoryPt::CartTrajectoryPt(const Frame &wobj_pt):
tool_base_(Eigen::Affine3d::Identity()),
tool_pt_(Eigen::Affine3d::Identity()),
wobj_base_(Eigen::Affine3d::Identity()),
wobj_pt_(wobj_pt),
pos_increment_(0),
orient_increment_(0)
{}
bool CartTrajectoryPt::getClosestCartPose(const std::vector<double> &seed_state,
const RobotModel &model, Eigen::Affine3d &pose) const
{
NOT_IMPLEMENTED_ERR(false);
}
bool CartTrajectoryPt::getNominalCartPose(const std::vector<double> &seed_state,
const RobotModel &model, Eigen::Affine3d &pose) const
{
/* Simply return wobj_pt expressed in world */
pose = wobj_base_.frame * wobj_pt_.frame;
return true; //TODO can this ever return false?
}
void CartTrajectoryPt::getCartesianPoses(const RobotModel &model, EigenSTL::vector_Affine3d &poses) const
{
poses.clear();
EigenSTL::vector_Affine3d sampled_wobj_pts = uniform(wobj_pt_, orient_increment_,
pos_increment_);
poses.reserve(sampled_wobj_pts.size());
for(size_t wobj_pt = 0; wobj_pt < sampled_wobj_pts.size(); ++wobj_pt)
{
Eigen::Affine3d pose = wobj_base_.frame * sampled_wobj_pts[wobj_pt];
if(model.isValid(pose))
{
poses.push_back(pose);
}
}
if( poses.empty())
{
ROS_WARN("Failed for find ANY cartesian poses, returning");
}
else
{
ROS_DEBUG_STREAM("Get cartesian poses, sampled: " << sampled_wobj_pts.size()
<< ", with " << poses.size() << " valid(returned) poses");
}
}
bool CartTrajectoryPt::getClosestJointPose(const std::vector<double> &seed_state,
const RobotModel &model,
std::vector<double> &joint_pose) const
{
Eigen::Affine3d nominal_pose,candidate_pose;
getNominalCartPose(seed_state,model,nominal_pose);
model.getFK(seed_state,candidate_pose);
// getting pose values
Eigen::Vector3d t = candidate_pose.translation();
Eigen::Vector3d rpy = candidate_pose.rotation().eulerAngles(2,1,0);
std::vector< std::tuple<double,double,double> > vals =
{
std::make_tuple(t(0),wobj_pt_.position_tolerance.x_lower,wobj_pt_.position_tolerance.x_upper),
std::make_tuple(t(1),wobj_pt_.position_tolerance.y_lower,wobj_pt_.position_tolerance.y_upper),
std::make_tuple(t(2),wobj_pt_.position_tolerance.z_lower,wobj_pt_.position_tolerance.z_upper),
std::make_tuple(rpy(0),wobj_pt_.orientation_tolerance.x_lower,wobj_pt_.orientation_tolerance.x_upper),
std::make_tuple(rpy(1),wobj_pt_.orientation_tolerance.y_lower,wobj_pt_.orientation_tolerance.y_upper),
std::make_tuple(rpy(2),wobj_pt_.orientation_tolerance.z_lower,wobj_pt_.orientation_tolerance.z_upper)
};
std::vector<double> closest_pose_vals = {t(0),t(1),t(2),rpy(0),rpy(1),rpy(2)};
bool solve_ik = false;
for(int i = 0; i < vals.size();i++)
{
auto &lower = std::get<1>(vals[i]);
auto &upper = std::get<2>(vals[i]);
auto &v = std::get<0>(vals[i]);
if( std::abs(upper -lower) > EQUALITY_TOLERANCE)
{
auto bounds = std::make_pair(lower,upper);
if(std::minmax({lower,v,upper}) != bounds)
{
solve_ik = true;
closest_pose_vals[i] = v < lower ? lower : upper;
}
}
else
{
if(std::abs(v-lower) > EQUALITY_TOLERANCE)
{
solve_ik = true;
}
}
}
if(solve_ik)
{
Eigen::Affine3d closest_pose = descartes_core::utils::toFrame(closest_pose_vals[0],
closest_pose_vals[1],
closest_pose_vals[2],
closest_pose_vals[3],
closest_pose_vals[4],
closest_pose_vals[5]);
if(!model.getIK(closest_pose,seed_state,joint_pose))
{
return false;
}
}
else
{
joint_pose.assign(seed_state.begin(),seed_state.end());
}
return true;
}
bool CartTrajectoryPt::getNominalJointPose(const std::vector<double> &seed_state,
const RobotModel &model,
std::vector<double> &joint_pose) const
{
Eigen::Affine3d robot_pose = wobj_base_.frame * wobj_pt_.frame *
tool_pt_.frame_inv * tool_base_.frame_inv;
return model.getIK(robot_pose, seed_state, joint_pose);
}
void CartTrajectoryPt::getJointPoses(const RobotModel &model,
std::vector<std::vector<double> > &joint_poses) const
{
joint_poses.clear();
EigenSTL::vector_Affine3d sampled_wobj_pts = uniform(wobj_pt_, orient_increment_,
pos_increment_);
EigenSTL::vector_Affine3d sampled_tool_pts = uniform(tool_pt_, orient_increment_,
pos_increment_);
size_t sample_size = sampled_wobj_pts.size() * sampled_tool_pts.size();
joint_poses.reserve(sample_size);
for(size_t wobj_pt = 0; wobj_pt < sampled_wobj_pts.size(); ++wobj_pt)
{
for(size_t tool_pt = 0; tool_pt < sampled_tool_pts.size(); ++tool_pt)
{
Eigen::Affine3d pose = wobj_base_.frame * sampled_wobj_pts[wobj_pt] *
sampled_tool_pts[tool_pt].inverse() * tool_base_.frame_inv;
std::vector<std::vector<double> > local_joint_poses;
if(model.getAllIK(pose, local_joint_poses))
{
joint_poses.insert(joint_poses.end(), local_joint_poses.begin(), local_joint_poses.end());
}
}
}
if( joint_poses.empty())
{
ROS_WARN("Failed for find ANY joint poses, returning");
}
else
{
ROS_DEBUG_STREAM("Get joint poses, sampled: " << sample_size
<< ", with " << joint_poses.size() << " valid(returned) poses");
}
}
bool CartTrajectoryPt::isValid(const RobotModel &model) const
{
Eigen::Affine3d robot_pose = wobj_base_.frame * wobj_pt_.frame *
tool_pt_.frame_inv * tool_base_.frame_inv;
return model.isValid(robot_pose);
}
bool CartTrajectoryPt::setDiscretization(const std::vector<double> &discretization)
{
NOT_IMPLEMENTED_ERR(false);
}
} /* namespace descartes_core */
<commit_msg>uses the elements of the rpy array in the right order<commit_after>/*
* Software License Agreement (Apache License)
*
* Copyright (c) 2014, Dan Solomon
*
* 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.
*/
/*
* cart_trajectory_pt.cpp
*
* Created on: Oct 3, 2014
* Author: Dan Solomon
*/
#include <tuple>
#include <map>
#include <algorithm>
#include <console_bridge/console.h>
#include <ros/console.h>
#include "descartes_core/cart_trajectory_pt.h"
#define NOT_IMPLEMENTED_ERR(ret) logError("%s not implemented", __PRETTY_FUNCTION__); return ret;
const double EQUALITY_TOLERANCE = 0.0001f;
namespace descartes_core
{
EigenSTL::vector_Affine3d uniform(const TolerancedFrame & frame, const double orient_increment,
const double pos_increment)
{
EigenSTL::vector_Affine3d rtn;
if(pos_increment < 0.0 || orient_increment < 0.0)
{
ROS_WARN_STREAM("Negative position/orientation intcrement: " << pos_increment
<< "/" << orient_increment);
rtn.clear();
return rtn;
}
Eigen::Affine3d sampled_frame;
// Calculating the number of samples for each tolerance (position and orientation)
size_t ntx, nty, ntz, nrx, nry, nrz;
if(orient_increment > 0)
{
nrx = ((frame.orientation_tolerance.x_upper - frame.orientation_tolerance.x_lower)/orient_increment) + 1;
nry = ((frame.orientation_tolerance.y_upper - frame.orientation_tolerance.y_lower)/orient_increment) + 1;
nrz = ((frame.orientation_tolerance.z_upper - frame.orientation_tolerance.z_lower)/orient_increment) + 1;
}
else
{
nrx = nry = nrz = 1;
}
if(pos_increment > 0)
{
ntx = ((frame.position_tolerance.x_upper - frame.position_tolerance.x_lower)/pos_increment) + 1;
nty = ((frame.position_tolerance.y_upper - frame.position_tolerance.y_lower)/pos_increment) + 1;
ntz = ((frame.position_tolerance.z_upper - frame.position_tolerance.z_lower)/pos_increment) + 1;
}
else
{
ntx = nty = ntz = 1;
}
// Estimating the number of samples base on tolerance zones and sampling increment.
size_t est_num_samples = ntx * nty * ntz * nrx * nry * nrz;
ROS_DEBUG_STREAM("Estimated number of samples: " << est_num_samples << ", reserving space");
rtn.reserve(est_num_samples);
//TODO: The following for loops do not ensure that the rull range is sample (lower to upper)
//since there could be round off error in the incrementing of samples. As a result, the
//exact upper bound may not be sampled. Since this isn't a final implementation, this will
//be ignored.
double rx, ry, rz, tx, ty, tz;
for(size_t ii = 0; ii < nrx; ++ii)
{
rx = frame.orientation_tolerance.x_lower + orient_increment * ii;
for(size_t jj = 0; jj < nry; ++jj)
{
ry = frame.orientation_tolerance.y_lower + orient_increment * jj;
for(size_t kk = 0; kk < nrz; ++kk)
{
rz = frame.orientation_tolerance.z_lower + orient_increment * kk;
for(size_t ll = 0; ll < ntx; ++ll)
{
tx = frame.position_tolerance.x_lower + pos_increment * ll;
for(size_t mm = 0; mm < nty; ++mm)
{
ty = frame.position_tolerance.y_lower + pos_increment * mm;
for(size_t nn = 0; nn < ntz; ++nn)
{
tz = frame.position_tolerance.z_lower + pos_increment * nn;
sampled_frame = Eigen::Translation3d(tx,ty,tz) *
Eigen::AngleAxisd(rz, Eigen::Vector3d::UnitZ()) *
Eigen::AngleAxisd(ry, Eigen::Vector3d::UnitY()) *
Eigen::AngleAxisd(rx, Eigen::Vector3d::UnitX());
rtn.push_back(sampled_frame);
}
}
}
}
}
}
ROS_DEBUG_STREAM("Uniform sampling of frame, utilizing orientation increment: " << orient_increment
<< ", and position increment: " << pos_increment
<< " resulted in " << rtn.size() << " samples");
return rtn;
}
CartTrajectoryPt::CartTrajectoryPt():
tool_base_(Eigen::Affine3d::Identity()),
tool_pt_(Eigen::Affine3d::Identity()),
wobj_base_(Eigen::Affine3d::Identity()),
wobj_pt_(Eigen::Affine3d::Identity()),
pos_increment_(0.0),
orient_increment_(0.0)
{}
CartTrajectoryPt::CartTrajectoryPt(const Frame &wobj_base, const TolerancedFrame &wobj_pt, const Frame &tool,
const TolerancedFrame &tool_pt, double pos_increment, double orient_increment):
tool_base_(tool),
tool_pt_(tool_pt),
wobj_base_(wobj_base),
wobj_pt_(wobj_pt),
pos_increment_(pos_increment),
orient_increment_(orient_increment)
{}
CartTrajectoryPt::CartTrajectoryPt(const TolerancedFrame &wobj_pt, double pos_increment,
double orient_increment):
tool_base_(Eigen::Affine3d::Identity()),
tool_pt_(Eigen::Affine3d::Identity()),
wobj_base_(Eigen::Affine3d::Identity()),
wobj_pt_(wobj_pt),
pos_increment_(pos_increment),
orient_increment_(orient_increment)
{}
CartTrajectoryPt::CartTrajectoryPt(const Frame &wobj_pt):
tool_base_(Eigen::Affine3d::Identity()),
tool_pt_(Eigen::Affine3d::Identity()),
wobj_base_(Eigen::Affine3d::Identity()),
wobj_pt_(wobj_pt),
pos_increment_(0),
orient_increment_(0)
{}
bool CartTrajectoryPt::getClosestCartPose(const std::vector<double> &seed_state,
const RobotModel &model, Eigen::Affine3d &pose) const
{
NOT_IMPLEMENTED_ERR(false);
}
bool CartTrajectoryPt::getNominalCartPose(const std::vector<double> &seed_state,
const RobotModel &model, Eigen::Affine3d &pose) const
{
/* Simply return wobj_pt expressed in world */
pose = wobj_base_.frame * wobj_pt_.frame;
return true; //TODO can this ever return false?
}
void CartTrajectoryPt::getCartesianPoses(const RobotModel &model, EigenSTL::vector_Affine3d &poses) const
{
poses.clear();
EigenSTL::vector_Affine3d sampled_wobj_pts = uniform(wobj_pt_, orient_increment_,
pos_increment_);
poses.reserve(sampled_wobj_pts.size());
for(size_t wobj_pt = 0; wobj_pt < sampled_wobj_pts.size(); ++wobj_pt)
{
Eigen::Affine3d pose = wobj_base_.frame * sampled_wobj_pts[wobj_pt];
if(model.isValid(pose))
{
poses.push_back(pose);
}
}
if( poses.empty())
{
ROS_WARN("Failed for find ANY cartesian poses, returning");
}
else
{
ROS_DEBUG_STREAM("Get cartesian poses, sampled: " << sampled_wobj_pts.size()
<< ", with " << poses.size() << " valid(returned) poses");
}
}
bool CartTrajectoryPt::getClosestJointPose(const std::vector<double> &seed_state,
const RobotModel &model,
std::vector<double> &joint_pose) const
{
Eigen::Affine3d nominal_pose,candidate_pose;
if(!model.getFK(seed_state,candidate_pose))
{
return false;
}
// getting pose values
Eigen::Vector3d t = candidate_pose.translation();
Eigen::Vector3d rpy = candidate_pose.rotation().eulerAngles(2,1,0);
std::vector< std::tuple<double,double,double> > vals =
{
std::make_tuple(t(0),wobj_pt_.position_tolerance.x_lower,wobj_pt_.position_tolerance.x_upper),
std::make_tuple(t(1),wobj_pt_.position_tolerance.y_lower,wobj_pt_.position_tolerance.y_upper),
std::make_tuple(t(2),wobj_pt_.position_tolerance.z_lower,wobj_pt_.position_tolerance.z_upper),
std::make_tuple(rpy(2),wobj_pt_.orientation_tolerance.x_lower,wobj_pt_.orientation_tolerance.x_upper),
std::make_tuple(rpy(1),wobj_pt_.orientation_tolerance.y_lower,wobj_pt_.orientation_tolerance.y_upper),
std::make_tuple(rpy(0),wobj_pt_.orientation_tolerance.z_lower,wobj_pt_.orientation_tolerance.z_upper)
};
std::vector<double> closest_pose_vals = {t(0),t(1),t(2),rpy(2),rpy(1),rpy(0)};
bool solve_ik = false;
for(int i = 0; i < vals.size();i++)
{
auto &lower = std::get<1>(vals[i]);
auto &upper = std::get<2>(vals[i]);
auto &v = std::get<0>(vals[i]);
if( std::abs(upper -lower) > EQUALITY_TOLERANCE)
{
auto bounds = std::make_pair(lower,upper);
if(std::minmax({lower,v,upper}) != bounds)
{
solve_ik = true;
closest_pose_vals[i] = v < lower ? lower : upper;
}
}
else
{
if(std::abs(v-lower) > EQUALITY_TOLERANCE)
{
solve_ik = true;
}
}
}
if(solve_ik)
{
Eigen::Affine3d closest_pose = descartes_core::utils::toFrame(closest_pose_vals[0],
closest_pose_vals[1],
closest_pose_vals[2],
closest_pose_vals[3],
closest_pose_vals[4],
closest_pose_vals[5]);
if(!model.getIK(closest_pose,seed_state,joint_pose))
{
return false;
}
}
else
{
joint_pose.assign(seed_state.begin(),seed_state.end());
}
return true;
}
bool CartTrajectoryPt::getNominalJointPose(const std::vector<double> &seed_state,
const RobotModel &model,
std::vector<double> &joint_pose) const
{
Eigen::Affine3d robot_pose = wobj_base_.frame * wobj_pt_.frame *
tool_pt_.frame_inv * tool_base_.frame_inv;
return model.getIK(robot_pose, seed_state, joint_pose);
}
void CartTrajectoryPt::getJointPoses(const RobotModel &model,
std::vector<std::vector<double> > &joint_poses) const
{
joint_poses.clear();
EigenSTL::vector_Affine3d sampled_wobj_pts = uniform(wobj_pt_, orient_increment_,
pos_increment_);
EigenSTL::vector_Affine3d sampled_tool_pts = uniform(tool_pt_, orient_increment_,
pos_increment_);
size_t sample_size = sampled_wobj_pts.size() * sampled_tool_pts.size();
joint_poses.reserve(sample_size);
for(size_t wobj_pt = 0; wobj_pt < sampled_wobj_pts.size(); ++wobj_pt)
{
for(size_t tool_pt = 0; tool_pt < sampled_tool_pts.size(); ++tool_pt)
{
Eigen::Affine3d pose = wobj_base_.frame * sampled_wobj_pts[wobj_pt] *
sampled_tool_pts[tool_pt].inverse() * tool_base_.frame_inv;
std::vector<std::vector<double> > local_joint_poses;
if(model.getAllIK(pose, local_joint_poses))
{
joint_poses.insert(joint_poses.end(), local_joint_poses.begin(), local_joint_poses.end());
}
}
}
if( joint_poses.empty())
{
ROS_WARN("Failed for find ANY joint poses, returning");
}
else
{
ROS_DEBUG_STREAM("Get joint poses, sampled: " << sample_size
<< ", with " << joint_poses.size() << " valid(returned) poses");
}
}
bool CartTrajectoryPt::isValid(const RobotModel &model) const
{
Eigen::Affine3d robot_pose = wobj_base_.frame * wobj_pt_.frame *
tool_pt_.frame_inv * tool_base_.frame_inv;
return model.isValid(robot_pose);
}
bool CartTrajectoryPt::setDiscretization(const std::vector<double> &discretization)
{
NOT_IMPLEMENTED_ERR(false);
}
} /* namespace descartes_core */
<|endoftext|> |
<commit_before>/*
* Copyright (C) 2014 Pavel Kirienko <pavel.kirienko@gmail.com>
*/
#pragma once
#include <cassert>
#include <ctime>
#include <sys/time.h>
#include <cstdint>
#include <uavcan/driver/system_clock.hpp>
#include <uavcan_linux/exception.hpp>
namespace uavcan_linux
{
enum class ClockAdjustmentMode
{
SystemWide,
PerDriverPrivate
};
class SystemClockDriver : public uavcan::ISystemClock
{
uavcan::UtcDuration private_adj_;
uavcan::UtcDuration gradual_adj_limit_;
const ClockAdjustmentMode adj_mode_;
std::uint64_t step_adj_cnt_;
std::uint64_t gradual_adj_cnt_;
static constexpr int64_t Int1e6 = 1000000;
bool performStepAdjustment(uavcan::UtcDuration adjustment) const
{
step_adj_cnt_++;
const int64_t usec = adjustment.toUSec();
timeval tv;
if (gettimeofday(&tv, NULL) != 0)
{
return false;
}
tv.tv_sec += usec / Int1e6;
tv.tv_usec += usec % Int1e6;
return settimeofday(&tv, nullptr) == 0;
}
bool performGradualAdjustment(uavcan::UtcDuration adjustment) const
{
gradual_adj_cnt_++;
const int64_t usec = adjustment.toUSec();
timeval tv;
tv.tv_sec = usec / Int1e6;
tv.tv_usec = usec % Int1e6;
return adjtime(&tv, nullptr) == 0;
}
public:
SystemClockDriver(ClockAdjustmentMode adj_mode = ClockAdjustmentMode::SystemWide)
: gradual_adj_limit_(uavcan::UtcDuration::fromMSec(4000))
, adj_mode_(adj_mode)
, step_adj_cnt_(0)
, gradual_adj_cnt_(0)
{ }
uavcan::MonotonicTime getMonotonic() const
{
struct timespec ts;
if (clock_gettime(CLOCK_MONOTONIC, &ts) != 0)
{
throw Exception("Failed to get monotonic time");
}
return uavcan::MonotonicTime::fromUSec(uint64_t(ts.tv_sec) * 1000000UL + ts.tv_nsec / 1000UL);
}
uavcan::UtcTime getUtc() const
{
timeval tv;
if (gettimeofday(&tv, NULL) != 0)
{
throw Exception("Failed to get UTC time");
}
uavcan::UtcTime utc = uavcan::UtcTime::fromUSec(uint64_t(tv.tv_sec) * 1000000UL + tv.tv_usec);
if (adj_mode_ == ClockAdjustmentMode::PerDriverPrivate)
{
utc += private_adj_;
}
return utc;
}
void adjustUtc(uavcan::UtcDuration adjustment)
{
if (adj_mode_ == ClockAdjustmentMode::PerDriverPrivate)
{
private_adj_ += adjustment;
}
else
{
assert(private_adj_.isZero());
assert(!gradual_adj_limit_.isNegative());
bool success = false;
if (adjustment.getAbs() < gradual_adj_limit_)
{
success = performGradualAdjustment(adjustment);
}
else
{
success = performStepAdjustment(adjustment);
}
if (!success)
{
throw Exception("Clock adjustment failed");
}
}
}
void setGradualAdjustmentLimit(uavcan::UtcDuration limit)
{
if (limit.isNegative())
{
limit = uavcan::UtcDuration();
}
gradual_adj_limit_ = limit;
}
uavcan::UtcDuration getGradualAdjustmentLimit() const { return gradual_adj_limit_; }
ClockAdjustmentMode getAdjustmentMode() const { return adj_mode_; }
uavcan::UtcDuration getPrivateAdjustment() const { return private_adj_; }
std::uint64_t getStepAdjustmentCount() const { return step_adj_cnt_; }
std::uint64_t getGradualAdjustmentCount() const { return gradual_adj_cnt_; }
std::uint64_t getAdjustmentCount() const
{
return getStepAdjustmentCount() + getGradualAdjustmentCount();
}
};
}
<commit_msg>Explicit 'virtual' for implemented methods<commit_after>/*
* Copyright (C) 2014 Pavel Kirienko <pavel.kirienko@gmail.com>
*/
#pragma once
#include <cassert>
#include <ctime>
#include <sys/time.h>
#include <cstdint>
#include <uavcan/driver/system_clock.hpp>
#include <uavcan_linux/exception.hpp>
namespace uavcan_linux
{
enum class ClockAdjustmentMode
{
SystemWide,
PerDriverPrivate
};
class SystemClockDriver : public uavcan::ISystemClock
{
uavcan::UtcDuration private_adj_;
uavcan::UtcDuration gradual_adj_limit_;
const ClockAdjustmentMode adj_mode_;
std::uint64_t step_adj_cnt_;
std::uint64_t gradual_adj_cnt_;
static constexpr int64_t Int1e6 = 1000000;
bool performStepAdjustment(uavcan::UtcDuration adjustment) const
{
step_adj_cnt_++;
const int64_t usec = adjustment.toUSec();
timeval tv;
if (gettimeofday(&tv, NULL) != 0)
{
return false;
}
tv.tv_sec += usec / Int1e6;
tv.tv_usec += usec % Int1e6;
return settimeofday(&tv, nullptr) == 0;
}
bool performGradualAdjustment(uavcan::UtcDuration adjustment) const
{
gradual_adj_cnt_++;
const int64_t usec = adjustment.toUSec();
timeval tv;
tv.tv_sec = usec / Int1e6;
tv.tv_usec = usec % Int1e6;
return adjtime(&tv, nullptr) == 0;
}
public:
SystemClockDriver(ClockAdjustmentMode adj_mode = ClockAdjustmentMode::SystemWide)
: gradual_adj_limit_(uavcan::UtcDuration::fromMSec(4000))
, adj_mode_(adj_mode)
, step_adj_cnt_(0)
, gradual_adj_cnt_(0)
{ }
virtual uavcan::MonotonicTime getMonotonic() const
{
struct timespec ts;
if (clock_gettime(CLOCK_MONOTONIC, &ts) != 0)
{
throw Exception("Failed to get monotonic time");
}
return uavcan::MonotonicTime::fromUSec(uint64_t(ts.tv_sec) * 1000000UL + ts.tv_nsec / 1000UL);
}
virtual uavcan::UtcTime getUtc() const
{
timeval tv;
if (gettimeofday(&tv, NULL) != 0)
{
throw Exception("Failed to get UTC time");
}
uavcan::UtcTime utc = uavcan::UtcTime::fromUSec(uint64_t(tv.tv_sec) * 1000000UL + tv.tv_usec);
if (adj_mode_ == ClockAdjustmentMode::PerDriverPrivate)
{
utc += private_adj_;
}
return utc;
}
virtual void adjustUtc(uavcan::UtcDuration adjustment)
{
if (adj_mode_ == ClockAdjustmentMode::PerDriverPrivate)
{
private_adj_ += adjustment;
}
else
{
assert(private_adj_.isZero());
assert(!gradual_adj_limit_.isNegative());
bool success = false;
if (adjustment.getAbs() < gradual_adj_limit_)
{
success = performGradualAdjustment(adjustment);
}
else
{
success = performStepAdjustment(adjustment);
}
if (!success)
{
throw Exception("Clock adjustment failed");
}
}
}
void setGradualAdjustmentLimit(uavcan::UtcDuration limit)
{
if (limit.isNegative())
{
limit = uavcan::UtcDuration();
}
gradual_adj_limit_ = limit;
}
uavcan::UtcDuration getGradualAdjustmentLimit() const { return gradual_adj_limit_; }
ClockAdjustmentMode getAdjustmentMode() const { return adj_mode_; }
uavcan::UtcDuration getPrivateAdjustment() const { return private_adj_; }
std::uint64_t getStepAdjustmentCount() const { return step_adj_cnt_; }
std::uint64_t getGradualAdjustmentCount() const { return gradual_adj_cnt_; }
std::uint64_t getAdjustmentCount() const
{
return getStepAdjustmentCount() + getGradualAdjustmentCount();
}
};
}
<|endoftext|> |
<commit_before>/*
* Qumulus UML editor
* Author: Frank Erens
*
*/
#include "GraphConnector.h"
QUML_BEGIN_NAMESPACE_UD
QUML_END_NAMESPACE_UD
<commit_msg>GraphConnector constructor.<commit_after>/*
* Qumulus UML editor
* Author: Frank Erens
*
*/
#include "GraphConnector.h"
QUML_BEGIN_NAMESPACE_UD
GraphConnector(GraphElement* e) :
mGraphElement(e),
mFirstEdge(nullptr),
mSecondEdge(nullptr) {
}
QUML_END_NAMESPACE_UD
<|endoftext|> |
<commit_before>#include "resources/ResourcesManager.hpp"
#include "graphics/GLUtilities.hpp"
#include "system/Window.hpp"
#include "Common.hpp"
#include <iostream>
#include <map>
#include <sstream>
#include "system/TextUtilities.hpp"
/**
\defgroup ShaderValidator Shader Validation
\brief Validate shaders compilation on the GPU and output IDE-compliant error messages.
\ingroup Tools
*/
/** Convert a shader compilation log into a IDE-compatible error reporting format and output it to stderr.
\param compilationLog the compilation log to process.
\param filePaths the paths to the shader file and all include files, absolute or relative to the directory containing the IDE project.
\return a boolean denoting if at least one error was reported by the log.
\warning If filePath is not expressed absolute or relative to the directory containing the IDE project, error links (for instance "src/foo/bar.frag:18") won't be functional.
\ingroup ShaderValidator
*/
bool processLog(const std::string & compilationLog, const std::vector<std::string> & filePaths) {
if(!compilationLog.empty()) {
std::stringstream str(compilationLog);
std::string line;
// Iterate over the lines of the log.
while(std::getline(str, line)) {
// Parse the log and output it as a compiler readable error.
// Find the global file ID limits.
const std::string::size_type firstIDDigitPos = line.find_first_of("0123456789");
const std::string::size_type lastIDDigitPos = line.find_first_not_of("0123456789", firstIDDigitPos);
if(firstIDDigitPos == std::string::npos || lastIDDigitPos == std::string::npos) {
continue;
}
// Find the line number limits.
const std::string::size_type firstLineDigitPos = line.find_first_of("0123456789", lastIDDigitPos + 1);
const std::string::size_type lastLineDigitPos = line.find_first_not_of("0123456789", firstLineDigitPos);
if(firstLineDigitPos == std::string::npos || lastLineDigitPos == std::string::npos) {
continue;
}
// Find the file containing the error based on the ID.
const std::string fileNumberRaw = line.substr(firstIDDigitPos, lastIDDigitPos - 1 - firstIDDigitPos + 1);
const unsigned int fileId = std::stoi(fileNumberRaw);
// Update the file path.
std::string finalFilePath = "unknown_file";
if(fileId < filePaths.size()) {
finalFilePath = filePaths[fileId];
}
// Generate the corresponding int.
const std::string lineNumberRaw = line.substr(firstLineDigitPos, lastLineDigitPos - 1 - firstLineDigitPos + 1);
const unsigned int lineId = std::stoi(lineNumberRaw);
// Find the error message.
const std::string::size_type firstMessagePos = line.find_first_not_of(" :)]", lastLineDigitPos + 1);
std::string errorMessage = "Unknown error.";
if(firstMessagePos != std::string::npos) {
errorMessage = line.substr(firstMessagePos);
}
// The path should be relative to the root build directory.
// Output in an IDE compatible format, to display warning and errors properly.
#ifdef _WIN32
std::cerr << finalFilePath << "(" << lineId << "): error: " << errorMessage << std::endl;
#else
std::cerr << finalFilePath << ":" << lineId << ": error: " << errorMessage << std::endl;
#endif
}
// At least one issue was encountered.
return true;
}
// No log, no problem.
return false;
}
/**
Perform shader validation: load all shaders in the resources directory, compile them on the GPU and output error logs.
\param argc the number of input arguments.
\param argv a pointer to the raw input arguments.
\return a boolean denoting if at least one shader failed to compile.
\ingroup ShaderValidator
*/
int main(int argc, char ** argv) {
Log::setDefaultVerbose(false);
if(argc < 2) {
Log::Error() << "Missing resource path." << std::endl;
return 1;
}
Resources::manager().addResources(std::string(argv[1]));
RenderingConfig config({ "ShaderValidator", "wxh", "100", "100"});
Window window("Validation", config, false, true);
// Query the renderer identifier, and the supported OpenGL version.
std::string vendor, renderer, version, shaderVersion;
GLUtilities::deviceInfos(vendor, renderer, version, shaderVersion);
Log::Info() << Log::OpenGL << "Vendor: " << vendor << "." << std::endl;
Log::Info() << Log::OpenGL << "Internal renderer: " << renderer << "." << std::endl;
Log::Info() << Log::OpenGL << "Versions: Driver: " << version << ", GLSL: " << shaderVersion << "." << std::endl;
// We will need all glsl files for include support.
std::map<std::string, std::string> includeFiles;
Resources::manager().getFiles("glsl", includeFiles);
// Test all shaders.
const std::map<ShaderType, std::string> types = {
{ShaderType::VERTEX, "vert" },
{ShaderType::GEOMETRY, "geom" },
{ShaderType::FRAGMENT, "frag" }
};
bool encounteredIssues = false;
for(const auto & type : types) {
// Load shaders from disk.
std::map<std::string, std::string> files;
Resources::manager().getFiles(type.second, files);
for (auto& file : files) {
GLUtilities::Bindings bindings;
std::string compilationLog;
// Keep track of the include files used.
// File with ID 0 is the base file, already set its name.
std::vector<std::string> names = { file.second };
// Load the shader.
const std::string fullName = file.first + "." + type.second;
const std::string shader = Resources::manager().getStringWithIncludes(fullName, names);
// Compile the shader.
GLUtilities::loadShader(shader, type.first, bindings, compilationLog);
// Replace the include names by the full paths.
for(size_t nid = 1; nid < names.size(); ++nid) {
auto& name = names[nid];
TextUtilities::splitExtension(name);
if(includeFiles.count(name) > 0) {
name = includeFiles[name];
}
}
// Process the log.
const bool newIssues = processLog(compilationLog, names);
encounteredIssues = encounteredIssues || newIssues;
}
}
window.clean();
// Has any of the shaders encountered a compilation issue?
return encounteredIssues ? 1 : 0;
}
<commit_msg>ShaderValidator: compile tessellation control and evaluation shaders.<commit_after>#include "resources/ResourcesManager.hpp"
#include "graphics/GLUtilities.hpp"
#include "system/Window.hpp"
#include "Common.hpp"
#include <iostream>
#include <map>
#include <sstream>
#include "system/TextUtilities.hpp"
/**
\defgroup ShaderValidator Shader Validation
\brief Validate shaders compilation on the GPU and output IDE-compliant error messages.
\ingroup Tools
*/
/** Convert a shader compilation log into a IDE-compatible error reporting format and output it to stderr.
\param compilationLog the compilation log to process.
\param filePaths the paths to the shader file and all include files, absolute or relative to the directory containing the IDE project.
\return a boolean denoting if at least one error was reported by the log.
\warning If filePath is not expressed absolute or relative to the directory containing the IDE project, error links (for instance "src/foo/bar.frag:18") won't be functional.
\ingroup ShaderValidator
*/
bool processLog(const std::string & compilationLog, const std::vector<std::string> & filePaths) {
if(!compilationLog.empty()) {
std::stringstream str(compilationLog);
std::string line;
// Iterate over the lines of the log.
while(std::getline(str, line)) {
// Parse the log and output it as a compiler readable error.
// Find the global file ID limits.
const std::string::size_type firstIDDigitPos = line.find_first_of("0123456789");
const std::string::size_type lastIDDigitPos = line.find_first_not_of("0123456789", firstIDDigitPos);
if(firstIDDigitPos == std::string::npos || lastIDDigitPos == std::string::npos) {
continue;
}
// Find the line number limits.
const std::string::size_type firstLineDigitPos = line.find_first_of("0123456789", lastIDDigitPos + 1);
const std::string::size_type lastLineDigitPos = line.find_first_not_of("0123456789", firstLineDigitPos);
if(firstLineDigitPos == std::string::npos || lastLineDigitPos == std::string::npos) {
continue;
}
// Find the file containing the error based on the ID.
const std::string fileNumberRaw = line.substr(firstIDDigitPos, lastIDDigitPos - 1 - firstIDDigitPos + 1);
const unsigned int fileId = std::stoi(fileNumberRaw);
// Update the file path.
std::string finalFilePath = "unknown_file";
if(fileId < filePaths.size()) {
finalFilePath = filePaths[fileId];
}
// Generate the corresponding int.
const std::string lineNumberRaw = line.substr(firstLineDigitPos, lastLineDigitPos - 1 - firstLineDigitPos + 1);
const unsigned int lineId = std::stoi(lineNumberRaw);
// Find the error message.
const std::string::size_type firstMessagePos = line.find_first_not_of(" :)]", lastLineDigitPos + 1);
std::string errorMessage = "Unknown error.";
if(firstMessagePos != std::string::npos) {
errorMessage = line.substr(firstMessagePos);
}
// The path should be relative to the root build directory.
// Output in an IDE compatible format, to display warning and errors properly.
#ifdef _WIN32
std::cerr << finalFilePath << "(" << lineId << "): error: " << errorMessage << std::endl;
#else
std::cerr << finalFilePath << ":" << lineId << ": error: " << errorMessage << std::endl;
#endif
}
// At least one issue was encountered.
return true;
}
// No log, no problem.
return false;
}
/**
Perform shader validation: load all shaders in the resources directory, compile them on the GPU and output error logs.
\param argc the number of input arguments.
\param argv a pointer to the raw input arguments.
\return a boolean denoting if at least one shader failed to compile.
\ingroup ShaderValidator
*/
int main(int argc, char ** argv) {
Log::setDefaultVerbose(false);
if(argc < 2) {
Log::Error() << "Missing resource path." << std::endl;
return 1;
}
Resources::manager().addResources(std::string(argv[1]));
RenderingConfig config({ "ShaderValidator", "wxh", "100", "100"});
Window window("Validation", config, false, true);
// Query the renderer identifier, and the supported OpenGL version.
std::string vendor, renderer, version, shaderVersion;
GLUtilities::deviceInfos(vendor, renderer, version, shaderVersion);
Log::Info() << Log::OpenGL << "Vendor: " << vendor << "." << std::endl;
Log::Info() << Log::OpenGL << "Internal renderer: " << renderer << "." << std::endl;
Log::Info() << Log::OpenGL << "Versions: Driver: " << version << ", GLSL: " << shaderVersion << "." << std::endl;
// We will need all glsl files for include support.
std::map<std::string, std::string> includeFiles;
Resources::manager().getFiles("glsl", includeFiles);
// Test all shaders.
const std::map<ShaderType, std::string> types = {
{ShaderType::VERTEX, "vert" },
{ShaderType::GEOMETRY, "geom" },
{ShaderType::FRAGMENT, "frag" },
{ShaderType::TESSCONTROL, "tessc" },
{ShaderType::TESSEVAL, "tesse" }
};
bool encounteredIssues = false;
for(const auto & type : types) {
// Load shaders from disk.
std::map<std::string, std::string> files;
Resources::manager().getFiles(type.second, files);
for (auto& file : files) {
GLUtilities::Bindings bindings;
std::string compilationLog;
// Keep track of the include files used.
// File with ID 0 is the base file, already set its name.
std::vector<std::string> names = { file.second };
// Load the shader.
const std::string fullName = file.first + "." + type.second;
const std::string shader = Resources::manager().getStringWithIncludes(fullName, names);
// Compile the shader.
GLUtilities::loadShader(shader, type.first, bindings, compilationLog);
// Replace the include names by the full paths.
for(size_t nid = 1; nid < names.size(); ++nid) {
auto& name = names[nid];
TextUtilities::splitExtension(name);
if(includeFiles.count(name) > 0) {
name = includeFiles[name];
}
}
// Process the log.
const bool newIssues = processLog(compilationLog, names);
encounteredIssues = encounteredIssues || newIssues;
}
}
window.clean();
// Has any of the shaders encountered a compilation issue?
return encounteredIssues ? 1 : 0;
}
<|endoftext|> |
<commit_before>#ifndef GENERIC_COROUTINE_HPP
# define GENERIC_COROUTINE_HPP
# pragma once
#include <cassert>
#include <csetjmp>
#include <cstdint>
#include <functional>
#include <memory>
#include "savestate.hpp"
namespace generic
{
class coroutine
{
public:
enum status : ::std::uint8_t
{
UNINITIALIZED,
INITIALIZED,
RUNNING,
TERMINATED
};
private:
statebuf env_in_;
statebuf env_out_;
::std::function<void()> f_;
enum status status_{UNINITIALIZED};
::std::size_t N_;
::std::unique_ptr<char[]> stack_;
enum : ::std::size_t { default_stack_size = 512 * 1024 };
public:
explicit coroutine(::std::size_t const N = default_stack_size) :
N_(N)
{
}
template <typename F>
explicit coroutine(F&& f, ::std::size_t const N) :
coroutine(N)
{
assign(::std::forward<F>(f));
}
auto status() const noexcept
{
return status_;
}
auto is_terminated() const noexcept
{
return TERMINATED == status_;
}
template <typename F>
void assign(F&& f)
{
f_ = [this, f = ::std::forward<F>(f)]()
{
status_ = RUNNING;
f(*this);
status_ = TERMINATED;
yield();
};
status_ = INITIALIZED;
}
void yield() noexcept __attribute__ ((noinline))
{
#if defined(i386) || defined(__i386) || defined(__i386__)
asm volatile ("":::"eax", "ebx", "ecx", "edx", "esi", "edi");
#elif defined(__amd64__) || defined(__amd64) || defined(__x86_64__) || defined(__x86_64)
asm volatile ("":::"rax", "rbx", "rcx", "rdx", "rsi", "rdi", "r8", "r9", "r10", "r11", "r12", "r13", "r14", "r15");
#endif
if (savestate(env_out_))
{
if (is_terminated())
{
stack_.reset();
}
// else do nothing
}
else
{
restorestate(env_in_);
}
// else do nothing
}
void resume() noexcept __attribute__ ((noinline))
{
#if defined(i386) || defined(__i386) || defined(__i386__)
asm volatile ("":::"eax", "ebx", "ecx", "edx", "esi", "edi");
#elif defined(__amd64__) || defined(__amd64) || defined(__x86_64__) || defined(__x86_64)
asm volatile ("":::"rax", "rbx", "rcx", "rdx", "rsi", "rdi", "r8", "r9", "r10", "r11", "r12", "r13", "r14", "r15");
#endif
if (savestate(env_in_))
{
return;
}
else if (RUNNING == status_)
{
restorestate(env_out_);
}
else
{
stack_.reset(new char[N_]);
// stack switch
#if defined(i386) || defined(__i386) || defined(__i386__)
asm volatile(
"movl %0, %%esp"
:
: "r" (stack_.get() + N_)
);
#elif defined(__amd64__) || defined(__amd64) || defined(__x86_64__) || defined(__x86_64)
asm volatile(
"movq %0, %%rsp"
:
: "r" (stack_.get() + N_)
);
#else
#error "can't switch stack frame"
#endif
f_();
}
}
};
}
#endif // GENERIC_COROUTINE_HPP
<commit_msg>some fixes<commit_after>#ifndef GENERIC_COROUTINE_HPP
# define GENERIC_COROUTINE_HPP
# pragma once
#include <cassert>
#include <csetjmp>
#include <cstdint>
#include <functional>
#include <memory>
#include "savestate.hpp"
namespace generic
{
class coroutine
{
public:
enum status : ::std::uint8_t
{
UNINITIALIZED,
INITIALIZED,
RUNNING,
TERMINATED
};
private:
statebuf env_in_;
statebuf env_out_;
::std::function<void()> f_;
enum status status_{UNINITIALIZED};
::std::size_t const N_;
::std::unique_ptr<char[]> stack_;
enum : ::std::size_t { default_stack_size = 512 * 1024 };
public:
explicit coroutine(::std::size_t const N = default_stack_size) :
N_(N)
{
}
template <typename F>
explicit coroutine(F&& f, ::std::size_t const N) :
coroutine(N)
{
assign(::std::forward<F>(f));
}
auto status() const noexcept
{
return status_;
}
auto is_terminated() const noexcept
{
return TERMINATED == status_;
}
template <typename F>
void assign(F&& f)
{
f_ = [this, f = ::std::forward<F>(f)]()
{
status_ = RUNNING;
f(*this);
status_ = TERMINATED;
yield();
};
status_ = INITIALIZED;
}
void yield() noexcept __attribute__ ((noinline))
{
#if defined(i386) || defined(__i386) || defined(__i386__)
asm volatile ("":::"eax", "ebx", "ecx", "edx", "esi", "edi");
#elif defined(__amd64__) || defined(__amd64) || defined(__x86_64__) || defined(__x86_64)
asm volatile ("":::"rax", "rbx", "rcx", "rdx", "rsi", "rdi", "r8", "r9", "r10", "r11", "r12", "r13", "r14", "r15");
#endif
if (savestate(env_out_))
{
if (is_terminated())
{
stack_.reset();
}
// else do nothing
}
else
{
restorestate(env_in_);
}
// else do nothing
}
void resume() noexcept __attribute__ ((noinline))
{
#if defined(i386) || defined(__i386) || defined(__i386__)
asm volatile ("":::"eax", "ebx", "ecx", "edx", "esi", "edi");
#elif defined(__amd64__) || defined(__amd64) || defined(__x86_64__) || defined(__x86_64)
asm volatile ("":::"rax", "rbx", "rcx", "rdx", "rsi", "rdi", "r8", "r9", "r10", "r11", "r12", "r13", "r14", "r15");
#endif
if (savestate(env_in_))
{
return;
}
else if (RUNNING == status_)
{
restorestate(env_out_);
}
else
{
stack_.reset(new char[N_]);
// stack switch
#if defined(i386) || defined(__i386) || defined(__i386__)
asm volatile(
"movl %0, %%esp"
:
: "r" (stack_.get() + N_)
);
#elif defined(__amd64__) || defined(__amd64) || defined(__x86_64__) || defined(__x86_64)
asm volatile(
"movq %0, %%rsp"
:
: "r" (stack_.get() + N_)
);
#else
#error "can't switch stack frame"
#endif
f_();
}
}
};
}
#endif // GENERIC_COROUTINE_HPP
<|endoftext|> |
<commit_before>//------------------------------------------------------------------------------
// CLING - the C++ LLVM-based InterpreterG :)
// version: $Id$
// author: Vassil Vassilev <vasil.georgiev.vasilev@cern.ch>
//------------------------------------------------------------------------------
#include "DeclCollector.h"
#include "cling/Interpreter/Transaction.h"
#include "clang/AST/Decl.h"
#include "clang/AST/DeclGroup.h"
using namespace clang;
namespace cling {
// pin the vtable here.
DeclCollector::~DeclCollector() {
}
bool DeclCollector::HandleTopLevelDecl(DeclGroupRef DGR) {
m_CurTransaction->appendUnique(DGR);
return true;
}
void DeclCollector::HandleInterestingDecl(DeclGroupRef DGR) {
assert("Not implemented yet!");
}
// Does more than we want:
// if there is class A {enum E {kEnum = 1};};
// we get two different tag decls one for A and one for E. This is not that
// bad because esentially it has no effect on codegen but it differs from what
// one'd expect. For now rely on the HandleTopLevelDecl to provide all the
// declarations in the transaction.
void DeclCollector::HandleTagDeclDefinition(TagDecl* TD) {
// Intentional no-op.
}
void DeclCollector::HandleVTable(CXXRecordDecl* RD,
bool DefinitionRequired) {
assert("Not implemented yet!");
}
void DeclCollector::CompleteTentativeDefinition(VarDecl* VD) {
assert("Not implemented yet!");
}
void DeclCollector::HandleTranslationUnit(ASTContext& Ctx) {
assert("Not implemented yet!");
}
} // namespace cling
<commit_msg>Assert actually on use of one of those routines in Sema.<commit_after>//------------------------------------------------------------------------------
// CLING - the C++ LLVM-based InterpreterG :)
// version: $Id$
// author: Vassil Vassilev <vasil.georgiev.vasilev@cern.ch>
//------------------------------------------------------------------------------
#include "DeclCollector.h"
#include "cling/Interpreter/Transaction.h"
#include "clang/AST/Decl.h"
#include "clang/AST/DeclGroup.h"
using namespace clang;
namespace cling {
// pin the vtable here.
DeclCollector::~DeclCollector() {
}
bool DeclCollector::HandleTopLevelDecl(DeclGroupRef DGR) {
m_CurTransaction->appendUnique(DGR);
return true;
}
void DeclCollector::HandleInterestingDecl(DeclGroupRef DGR) {
assert("Not implemented yet!");
}
// Does more than we want:
// if there is class A {enum E {kEnum = 1};};
// we get two different tag decls one for A and one for E. This is not that
// bad because esentially it has no effect on codegen but it differs from what
// one'd expect. For now rely on the HandleTopLevelDecl to provide all the
// declarations in the transaction.
void DeclCollector::HandleTagDeclDefinition(TagDecl* TD) {
// Intentional no-op.
}
void DeclCollector::HandleVTable(CXXRecordDecl* RD, bool DefinitionRequired) {
assert(0 && "Not implemented yet!");
}
void DeclCollector::CompleteTentativeDefinition(VarDecl* VD) {
assert(0 && "Not implemented yet!");
}
void DeclCollector::HandleTranslationUnit(ASTContext& Ctx) {
}
} // namespace cling
<|endoftext|> |
<commit_before><commit_msg>reverse map fixes<commit_after><|endoftext|> |
<commit_before>// 未完成品。当然ACしない。RubyのほうはAC済み。
#include <iostream>
#include <vector>
#include <set>
using namespace std;
typedef vector< vector<int> > tab;
int b[2][3];
int c[3][2];
int fukasa(tab ary, int dep) {
if (dep == 9) {
int ans = 0;
for (auto i=0; i<2; i++) {
for (auto j=0; j<3; j++) {
ans += b[i][j] * ary[i][j] * ary[i+1][j];
}
}
for (auto i=0; i<3; i++) {
for (auto j=0; j<2; j++) {
ans += c[i][j] * ary[i][j] * ary[i][j+1];
}
}
return ans;
} else {
vector<int> shu;
for (auto i=0; i<3; i++) {
for (auto j=0; j<3; j++) {
if (ary[i][j] == 0) {
tab temp = tab(3, vector<int>(3));
for (auto k=0; k<3; k++) {
for (auto l=0; l<3; l++) {
temp[k][l] = ary[k][l];
}
}
temp[i][j] = ((dep%2 == 0) ? 1 : -1);
shu.push_back(fukasa(temp, dep+1));
}
}
}
int ans = 0;
if (dep == 0) {
for (unsigned i=0; i<shu.size(); i++) {
cout << shu[i] << endl;
}
}
if (dep%2 == 0) {
for (unsigned i=0; i<shu.size(); i++) {
ans = -1000000;
ans = max(ans, shu[i]);
}
} else {
for (unsigned i=0; i<shu.size(); i++) {
ans = 1000000;
ans = min(ans, shu[i]);
}
}
return ans;
}
}
int main() {
int wa = 0;
for (auto i=0; i<2; i++) {
for (auto j=0; j<3; j++) {
cin >> b[i][j];
wa += b[i][j];
}
}
for (auto i=0; i<3; i++) {
for (auto j=0; j<2; j++) {
cin >> c[i][j];
wa += c[i][j];
}
}
// tab table = tab(3, vector<int>(3, 0));
tab table = {{0, 0, 0}, {0, 0, 0}, {0, 0, 0}};
int sa = fukasa(table, 0);
cout << (wa+sa)/2 << endl;
cout << (wa-sa)/2 << endl;
}
<commit_msg>mapを使ってACしました。<commit_after>#include <iostream>
#include <vector>
#include <algorithm>
#include <map>
using namespace std;
typedef vector< vector<int> > tab;
int b[2][3];
int c[3][2];
map<tab, int> scores;
int eval(tab ary) {
int ans = 0;
for (auto i=0; i<2; i++) {
for (auto j=0; j<3; j++) {
ans += b[i][j] * ary[i][j] * ary[i+1][j];
}
}
for (auto i=0; i<3; i++) {
for (auto j=0; j<2; j++) {
ans += c[i][j] * ary[i][j] * ary[i][j+1];
}
}
return ans;
}
int fukasa(tab ary, int dep) {
if (dep == 9) {
if (scores.find(ary) != scores.end()) {
return scores[ary];
}
return eval(ary);
} else {
vector<int> scoreset;
for (auto i=0; i<3; i++) {
for (auto j=0; j<3; j++) {
if (ary[i][j] == 0) {
ary[i][j] = ((dep%2 == 0) ? 1 : -1);
scoreset.push_back(fukasa(ary, dep+1));
ary[i][j] = 0;
}
}
}
int ans = 0;
ans = ((dep%2 == 0) ?
*max_element(scoreset.begin(), scoreset.end())
: *min_element(scoreset.begin(), scoreset.end()));
scores[ary] = ans;
return ans;
}
}
int main() {
int wa = 0;
for (auto i=0; i<2; i++) {
for (auto j=0; j<3; j++) {
cin >> b[i][j];
wa += b[i][j];
}
}
for (auto i=0; i<3; i++) {
for (auto j=0; j<2; j++) {
cin >> c[i][j];
wa += c[i][j];
}
}
tab table = tab(3, vector<int>(3, 0));
int sa = fukasa(table, 0);
cout << (wa+sa)/2 << endl;
cout << (wa-sa)/2 << endl;
}
<|endoftext|> |
<commit_before>/*=============================================================================
Library: CTK
Copyright (c) German Cancer Research Center,
Division of Medical and Biological Informatics
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
=============================================================================*/
#include "ctkPluginFrameworkTestRunner.h"
#include "ctkTestSuiteInterface.h"
#include <ctkPluginFrameworkFactory.h>
#include <ctkPluginFramework.h>
#include <ctkPluginContext.h>
#include <ctkPluginException.h>
#include <QStringList>
#include <QPair>
#include <QCoreApplication>
#include <QDirIterator>
#include <QTest>
#include <QThread>
#include <QDebug>
#ifdef _WIN32
#include <windows.h>
#include <stdlib.h>
#endif // _WIN32
class TestRunner : public QThread
{
public:
typedef QPair<long, ctkPlugin::StartOptions> StartPluginPair;
TestRunner(ctkPluginContext* context, const QSet<StartPluginPair>& startPlugins, int argc, char** argv)
: context(context), startPluginInfos(startPlugins),
argc(argc), argv(argv)
{
}
void run()
{
// start the specified plugins which may register the test suites (QObject classes)
foreach(StartPluginPair pluginInfo, startPluginInfos)
{
QSharedPointer<ctkPlugin> plugin = context->getPlugin(pluginInfo.first);
plugin->start(pluginInfo.second);
}
QList<ctkServiceReference> refs = context->getServiceReferences<ctkTestSuiteInterface>();
int result = 0;
foreach(ctkServiceReference ref, refs)
{
result += QTest::qExec(context->getService(ref), argc, argv);
if (result > 0) break;
}
if (result > 0) QCoreApplication::exit(result);
}
private:
ctkPluginContext* context;
QSet<StartPluginPair> startPluginInfos;
int argc;
char** argv;
};
class ctkPluginFrameworkTestRunnerPrivate
{
public:
typedef QPair<QString, bool> PluginPathPair;
QList<PluginPathPair> pluginPaths;
typedef QPair<QString, QString> InstallCandPair;
QList<InstallCandPair> installCandidates;
typedef QPair<QString, ctkPlugin::StartOptions> ActivatePair;
QList<ActivatePair> activatePlugins;
typedef QPair<long, ctkPlugin::StartOptions> StartPluginPair;
QSet<StartPluginPair> startPlugins;
ctkPluginContext* context;
ctkPluginFrameworkFactory* fwFactory;
ctkPluginFrameworkTestRunnerPrivate()
: context(0), fwFactory(0)
{
pluginLibFilter << "*.dll" << "*.so" << "*.dylib";
}
void installPlugins(const QString& path)
{
QDirIterator dirIter(path, pluginLibFilter, QDir::Files);
while(dirIter.hasNext())
{
dirIter.next();
try
{
QSharedPointer<ctkPlugin> plugin = context->installPlugin(QUrl::fromLocalFile(dirIter.filePath()));
long pluginId = plugin->getPluginId();
QString symbolicName = plugin->getSymbolicName();
foreach(ActivatePair activatePlugin, activatePlugins)
{
if (activatePlugin.first == symbolicName)
{
startPlugins.insert(qMakePair(pluginId, activatePlugin.second));
activatePlugins.removeAll(activatePlugin);
break;
}
}
}
catch (const ctkPluginException& e)
{
qCritical() << e.what();
}
}
}
void installPlugin(const QString& path, const QString& name)
{
QDirIterator dirIter(path, pluginLibFilter, QDir::Files);
while(dirIter.hasNext())
{
dirIter.next();
if (dirIter.fileName().contains(name))
{
try
{
QSharedPointer<ctkPlugin> plugin = context->installPlugin(QUrl::fromLocalFile(dirIter.filePath()));
QString symbolicName = plugin->getSymbolicName();
long pluginId = plugin->getPluginId();
foreach(ActivatePair activatePlugin, activatePlugins)
{
if (activatePlugin.first == symbolicName)
{
startPlugins.insert(qMakePair(pluginId, activatePlugin.second));
activatePlugins.removeAll(activatePlugin);
break;
}
}
break;
}
catch (const ctkPluginException& e)
{
qCritical() << e.what();
}
}
}
}
private:
QStringList pluginLibFilter;
};
ctkPluginFrameworkTestRunner::ctkPluginFrameworkTestRunner()
: d_ptr(new ctkPluginFrameworkTestRunnerPrivate())
{
}
ctkPluginFrameworkTestRunner::~ctkPluginFrameworkTestRunner()
{
Q_D(ctkPluginFrameworkTestRunner);
delete d->fwFactory;
}
void ctkPluginFrameworkTestRunner::addPluginPath(const QString& path, bool install)
{
Q_D(ctkPluginFrameworkTestRunner);
d->pluginPaths.push_back(qMakePair(path, install));
#ifdef _WIN32
if(_putenv_s("PATH", path.toLatin1().data()))
{
LPVOID lpMsgBuf;
DWORD dw = GetLastError();
FormatMessage(
FORMAT_MESSAGE_ALLOCATE_BUFFER |
FORMAT_MESSAGE_FROM_SYSTEM |
FORMAT_MESSAGE_IGNORE_INSERTS,
NULL,
dw,
MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
(LPTSTR) &lpMsgBuf,
0, NULL );
QString msg = QString("Adding '%1' to the PATH environment variable failed: %2")
.arg(path).arg(QString((LPCTSTR)lpMsgBuf));
qWarning() << msg;
LocalFree(lpMsgBuf);
}
#endif
}
void ctkPluginFrameworkTestRunner::addPlugin(const QString &path, const QString &name)
{
Q_D(ctkPluginFrameworkTestRunner);
d->installCandidates.push_back(qMakePair(path, name));
}
void ctkPluginFrameworkTestRunner::startPluginOnRun(const QString& pluginId, ctkPlugin::StartOptions opts)
{
Q_D(ctkPluginFrameworkTestRunner);
d->activatePlugins.push_back(qMakePair(pluginId, opts));
}
void ctkPluginFrameworkTestRunner::init(const ctkProperties& fwProps)
{
Q_D(ctkPluginFrameworkTestRunner);
d->fwFactory = new ctkPluginFrameworkFactory(fwProps);
QSharedPointer<ctkPluginFramework> framework = d->fwFactory->getFramework();
framework->start();
d->context = framework->getPluginContext();
foreach(ctkPluginFrameworkTestRunnerPrivate::PluginPathPair path,
d->pluginPaths)
{
QCoreApplication::addLibraryPath(path.first);
if (path.second) d->installPlugins(path.first);
}
foreach(ctkPluginFrameworkTestRunnerPrivate::InstallCandPair candidate,
d->installCandidates)
{
d->installPlugin(candidate.first, candidate.second);
}
}
int ctkPluginFrameworkTestRunner::run(int argc, char** argv)
{
Q_D(ctkPluginFrameworkTestRunner);
if (!d->activatePlugins.isEmpty())
{
qCritical() << "The following plugins will not be started, because"
<< "they could not be installed:";
foreach(ctkPluginFrameworkTestRunnerPrivate::ActivatePair p,
d->activatePlugins)
{
qCritical() << " -" << p.first;
}
}
TestRunner runner(d->context, d->startPlugins, argc, argv);
runner.connect(&runner, SIGNAL(finished()), qApp, SLOT(quit()));
runner.start();
return qApp->exec();
}
<commit_msg>Fail plugin tests if the desired plugins could not be started.<commit_after>/*=============================================================================
Library: CTK
Copyright (c) German Cancer Research Center,
Division of Medical and Biological Informatics
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
=============================================================================*/
#include "ctkPluginFrameworkTestRunner.h"
#include "ctkTestSuiteInterface.h"
#include <ctkPluginFrameworkFactory.h>
#include <ctkPluginFramework.h>
#include <ctkPluginContext.h>
#include <ctkPluginException.h>
#include <QStringList>
#include <QPair>
#include <QCoreApplication>
#include <QDirIterator>
#include <QTest>
#include <QThread>
#include <QDebug>
#ifdef _WIN32
#include <windows.h>
#include <stdlib.h>
#endif // _WIN32
class TestRunner : public QThread
{
public:
typedef QPair<long, ctkPlugin::StartOptions> StartPluginPair;
TestRunner(ctkPluginContext* context, const QSet<StartPluginPair>& startPlugins, int argc, char** argv)
: context(context), startPluginInfos(startPlugins),
argc(argc), argv(argv)
{
}
void run()
{
// start the specified plugins which may register the test suites (QObject classes)
foreach(StartPluginPair pluginInfo, startPluginInfos)
{
QSharedPointer<ctkPlugin> plugin = context->getPlugin(pluginInfo.first);
plugin->start(pluginInfo.second);
}
QList<ctkServiceReference> refs = context->getServiceReferences<ctkTestSuiteInterface>();
int result = 0;
foreach(ctkServiceReference ref, refs)
{
result += QTest::qExec(context->getService(ref), argc, argv);
if (result > 0) break;
}
if (result > 0) QCoreApplication::exit(result);
}
private:
ctkPluginContext* context;
QSet<StartPluginPair> startPluginInfos;
int argc;
char** argv;
};
class ctkPluginFrameworkTestRunnerPrivate
{
public:
typedef QPair<QString, bool> PluginPathPair;
QList<PluginPathPair> pluginPaths;
typedef QPair<QString, QString> InstallCandPair;
QList<InstallCandPair> installCandidates;
typedef QPair<QString, ctkPlugin::StartOptions> ActivatePair;
QList<ActivatePair> activatePlugins;
typedef QPair<long, ctkPlugin::StartOptions> StartPluginPair;
QSet<StartPluginPair> startPlugins;
ctkPluginContext* context;
ctkPluginFrameworkFactory* fwFactory;
ctkPluginFrameworkTestRunnerPrivate()
: context(0), fwFactory(0)
{
pluginLibFilter << "*.dll" << "*.so" << "*.dylib";
}
void installPlugins(const QString& path)
{
QDirIterator dirIter(path, pluginLibFilter, QDir::Files);
while(dirIter.hasNext())
{
dirIter.next();
try
{
QSharedPointer<ctkPlugin> plugin = context->installPlugin(QUrl::fromLocalFile(dirIter.filePath()));
long pluginId = plugin->getPluginId();
QString symbolicName = plugin->getSymbolicName();
foreach(ActivatePair activatePlugin, activatePlugins)
{
if (activatePlugin.first == symbolicName)
{
startPlugins.insert(qMakePair(pluginId, activatePlugin.second));
activatePlugins.removeAll(activatePlugin);
break;
}
}
}
catch (const ctkPluginException& e)
{
qCritical() << e.what();
}
}
}
void installPlugin(const QString& path, const QString& name)
{
QDirIterator dirIter(path, pluginLibFilter, QDir::Files);
while(dirIter.hasNext())
{
dirIter.next();
if (dirIter.fileName().contains(name))
{
try
{
QSharedPointer<ctkPlugin> plugin = context->installPlugin(QUrl::fromLocalFile(dirIter.filePath()));
QString symbolicName = plugin->getSymbolicName();
long pluginId = plugin->getPluginId();
foreach(ActivatePair activatePlugin, activatePlugins)
{
if (activatePlugin.first == symbolicName)
{
startPlugins.insert(qMakePair(pluginId, activatePlugin.second));
activatePlugins.removeAll(activatePlugin);
break;
}
}
break;
}
catch (const ctkPluginException& e)
{
qCritical() << e.what();
}
}
}
}
private:
QStringList pluginLibFilter;
};
ctkPluginFrameworkTestRunner::ctkPluginFrameworkTestRunner()
: d_ptr(new ctkPluginFrameworkTestRunnerPrivate())
{
}
ctkPluginFrameworkTestRunner::~ctkPluginFrameworkTestRunner()
{
Q_D(ctkPluginFrameworkTestRunner);
delete d->fwFactory;
}
void ctkPluginFrameworkTestRunner::addPluginPath(const QString& path, bool install)
{
Q_D(ctkPluginFrameworkTestRunner);
d->pluginPaths.push_back(qMakePair(path, install));
#ifdef _WIN32
if(_putenv_s("PATH", path.toLatin1().data()))
{
LPVOID lpMsgBuf;
DWORD dw = GetLastError();
FormatMessage(
FORMAT_MESSAGE_ALLOCATE_BUFFER |
FORMAT_MESSAGE_FROM_SYSTEM |
FORMAT_MESSAGE_IGNORE_INSERTS,
NULL,
dw,
MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
(LPTSTR) &lpMsgBuf,
0, NULL );
QString msg = QString("Adding '%1' to the PATH environment variable failed: %2")
.arg(path).arg(QString((LPCTSTR)lpMsgBuf));
qWarning() << msg;
LocalFree(lpMsgBuf);
}
#endif
}
void ctkPluginFrameworkTestRunner::addPlugin(const QString &path, const QString &name)
{
Q_D(ctkPluginFrameworkTestRunner);
d->installCandidates.push_back(qMakePair(path, name));
}
void ctkPluginFrameworkTestRunner::startPluginOnRun(const QString& pluginId, ctkPlugin::StartOptions opts)
{
Q_D(ctkPluginFrameworkTestRunner);
d->activatePlugins.push_back(qMakePair(pluginId, opts));
}
void ctkPluginFrameworkTestRunner::init(const ctkProperties& fwProps)
{
Q_D(ctkPluginFrameworkTestRunner);
d->fwFactory = new ctkPluginFrameworkFactory(fwProps);
QSharedPointer<ctkPluginFramework> framework = d->fwFactory->getFramework();
framework->start();
d->context = framework->getPluginContext();
foreach(ctkPluginFrameworkTestRunnerPrivate::PluginPathPair path,
d->pluginPaths)
{
QCoreApplication::addLibraryPath(path.first);
if (path.second) d->installPlugins(path.first);
}
foreach(ctkPluginFrameworkTestRunnerPrivate::InstallCandPair candidate,
d->installCandidates)
{
d->installPlugin(candidate.first, candidate.second);
}
}
int ctkPluginFrameworkTestRunner::run(int argc, char** argv)
{
Q_D(ctkPluginFrameworkTestRunner);
if (!d->activatePlugins.isEmpty())
{
qCritical() << "The following plugins will not be started, because"
<< "they could not be installed:";
foreach(ctkPluginFrameworkTestRunnerPrivate::ActivatePair p,
d->activatePlugins)
{
qCritical() << " -" << p.first;
}
return EXIT_FAILURE;
}
TestRunner runner(d->context, d->startPlugins, argc, argv);
runner.connect(&runner, SIGNAL(finished()), qApp, SLOT(quit()));
runner.start();
return qApp->exec();
}
<|endoftext|> |
<commit_before>/**
* @file LogAttribute.cpp
* LogAttribute class implementation
*
* 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 "LogAttribute.h"
#include <time.h>
#include <string.h>
#include <memory>
#include <string>
#include <vector>
#include <queue>
#include <map>
#include <set>
#include <sstream>
#include <iostream>
#include "utils/TimeUtil.h"
#include "utils/StringUtils.h"
#include "core/ProcessContext.h"
#include "core/ProcessSession.h"
namespace org {
namespace apache {
namespace nifi {
namespace minifi {
namespace processors {
core::Property LogAttribute::LogLevel(core::PropertyBuilder::createProperty("Log Level")->withDescription("The Log Level to use when logging the Attributes")->withAllowableValues<std::string>(
{"info", "trace", "error", "warn", "debug" })->build());
core::Property LogAttribute::AttributesToLog(
core::PropertyBuilder::createProperty("Attributes to Log")->withDescription("A comma-separated list of Attributes to Log. If not specified, all attributes will be logged.")->build());
core::Property LogAttribute::FlowFilesToLog(
core::PropertyBuilder::createProperty("FlowFiles To Log")->withDescription(
"Number of flow files to log. If set to zero all flow files will be logged. Please note that this may block other threads from running if not used judiciously.")->withDefaultValue<uint64_t>(1)
->build());
core::Property LogAttribute::AttributesToIgnore(
core::PropertyBuilder::createProperty("Attributes to Ignore")->withDescription("A comma-separated list of Attributes to ignore. If not specified, no attributes will be ignored.")->build());
core::Property LogAttribute::LogPayload(core::PropertyBuilder::createProperty("Log Payload")->withDescription("If true, the FlowFile's payload will be logged, in addition to its attributes."
"otherwise, just the Attributes will be logged")->withDefaultValue<bool>(false)->build());
core::Property LogAttribute::HexencodePayload(core::PropertyBuilder::createProperty("Hexencode Payload")->withDescription("If true, the FlowFile's payload will be logged in a hexencoded format")->withDefaultValue<bool>(false)->build());
core::Property LogAttribute::MaxPayloadLineLength(core::PropertyBuilder::createProperty("Maximum Payload Line Length")->withDescription("The logged payload will be broken into lines this long. 0 means no newlines will be added.")->withDefaultValue<uint32_t>(80U)->build());
core::Property LogAttribute::LogPrefix(
core::PropertyBuilder::createProperty("Log Prefix")->withDescription("Log prefix appended to the log lines. It helps to distinguish the output of multiple LogAttribute processors.")->build());
core::Relationship LogAttribute::Success("success", "success operational on the flow record");
void LogAttribute::initialize() {
// Set the supported properties
std::set<core::Property> properties;
properties.insert(LogLevel);
properties.insert(AttributesToLog);
properties.insert(AttributesToIgnore);
properties.insert(LogPayload);
properties.insert(HexencodePayload);
properties.insert(MaxPayloadLineLength);
properties.insert(FlowFilesToLog);
properties.insert(LogPrefix);
setSupportedProperties(properties);
// Set the supported relationships
std::set<core::Relationship> relationships;
relationships.insert(Success);
setSupportedRelationships(relationships);
}
void LogAttribute::onSchedule(const std::shared_ptr<core::ProcessContext> &context, const std::shared_ptr<core::ProcessSessionFactory> &factory) {
core::Property flowsToLog = FlowFilesToLog;
if (getProperty(FlowFilesToLog.getName(), flowsToLog)) {
// we are going this route since to avoid breaking backwards compatibility the get property function doesn't perform validation ( That's done
// in configuration. In future releases we can add that exception handling there.
if (!flowsToLog.getValue().validate("Validating FlowFilesToLog").valid())
throw Exception(PROCESS_SCHEDULE_EXCEPTION, "Invalid value for flowfiles to log: " + flowsToLog.getValue().to_string());
flowfiles_to_log_ = flowsToLog.getValue();
}
std::string value;
if (context->getProperty(HexencodePayload.getName(), value)) {
utils::StringUtils::StringToBool(value, hexencode_);
}
if (context->getProperty(MaxPayloadLineLength.getName(), value)) {
core::Property::StringToInt(value, max_line_length_);
}
}
// OnTrigger method, implemented by NiFi LogAttribute
void LogAttribute::onTrigger(const std::shared_ptr<core::ProcessContext> &context, const std::shared_ptr<core::ProcessSession> &session) {
logger_->log_trace("enter log attribute, attempting to retrieve %u flow files", flowfiles_to_log_);
std::string dashLine = "--------------------------------------------------";
LogAttrLevel level = LogAttrLevelInfo;
bool logPayload = false;
uint64_t i = 0;
const auto max = flowfiles_to_log_ == 0 ? UINT64_MAX : flowfiles_to_log_;
for (; i < max; ++i) {
std::shared_ptr<core::FlowFile> flow = session->get();
if (!flow) {
break;
}
std::string value;
if (context->getProperty(LogLevel.getName(), value)) {
logLevelStringToEnum(value, level);
}
if (context->getProperty(LogPrefix.getName(), value)) {
dashLine = "-----" + value + "-----";
}
context->getProperty(LogPayload.getName(), logPayload);
std::ostringstream message;
message << "Logging for flow file " << "\n";
message << dashLine;
message << "\nStandard FlowFile Attributes";
message << "\n" << "UUID:" << flow->getUUIDStr();
message << "\n" << "EntryDate:" << getTimeStr(flow->getEntryDate());
message << "\n" << "lineageStartDate:" << getTimeStr(flow->getlineageStartDate());
message << "\n" << "Size:" << flow->getSize() << " Offset:" << flow->getOffset();
message << "\nFlowFile Attributes Map Content";
std::map<std::string, std::string> attrs = flow->getAttributes();
std::map<std::string, std::string>::iterator it;
for (it = attrs.begin(); it != attrs.end(); it++) {
message << "\n" << "key:" << it->first << " value:" << it->second;
}
message << "\nFlowFile Resource Claim Content";
std::shared_ptr<ResourceClaim> claim = flow->getResourceClaim();
if (claim) {
message << "\n" << "Content Claim:" << claim->getContentFullPath();
}
if (logPayload && flow->getSize() <= 1024 * 1024) {
message << "\n" << "Payload:" << "\n";
ReadCallback callback(logger_, flow->getSize());
session->read(flow, &callback);
std::string printable_payload;
if (hexencode_) {
printable_payload = utils::StringUtils::to_hex(callback.buffer_.data(), callback.buffer_.size());
} else {
printable_payload = std::string(reinterpret_cast<char*>(callback.buffer_.data()), callback.buffer_.size());
}
if (max_line_length_ == 0U) {
message << printable_payload << "\n";
} else {
for (size_t i = 0; i < printable_payload.size(); i += max_line_length_) {
message << printable_payload.substr(i, max_line_length_) << '\n';
}
}
} else {
message << "\n";
}
message << dashLine;
std::string output = message.str();
switch (level) {
case LogAttrLevelInfo:
logging::LOG_INFO(logger_) << output;
break;
case LogAttrLevelDebug:
logging::LOG_DEBUG(logger_) << output;
break;
case LogAttrLevelError:
logging::LOG_ERROR(logger_) << output;
break;
case LogAttrLevelTrace:
logging::LOG_TRACE(logger_) << output;
break;
case LogAttrLevelWarn:
logging::LOG_WARN(logger_) << output;
break;
default:
break;
}
session->transfer(flow, Success);
}
logger_->log_debug("Logged %d flow files", i);
}
} /* namespace processors */
} /* namespace minifi */
} /* namespace nifi */
} /* namespace apache */
} /* namespace org */
<commit_msg>MINIFICPP-984 - Fix linter errors<commit_after>/**
* @file LogAttribute.cpp
* LogAttribute class implementation
*
* 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 "LogAttribute.h"
#include <time.h>
#include <string.h>
#include <memory>
#include <string>
#include <vector>
#include <queue>
#include <map>
#include <set>
#include <sstream>
#include <iostream>
#include "utils/TimeUtil.h"
#include "utils/StringUtils.h"
#include "core/ProcessContext.h"
#include "core/ProcessSession.h"
namespace org {
namespace apache {
namespace nifi {
namespace minifi {
namespace processors {
core::Property LogAttribute::LogLevel(core::PropertyBuilder::createProperty("Log Level")->withDescription("The Log Level to use when logging the Attributes")->withAllowableValues<std::string>(
{"info", "trace", "error", "warn", "debug" })->build());
core::Property LogAttribute::AttributesToLog(
core::PropertyBuilder::createProperty("Attributes to Log")->withDescription("A comma-separated list of Attributes to Log. If not specified, all attributes will be logged.")->build());
core::Property LogAttribute::FlowFilesToLog(
core::PropertyBuilder::createProperty("FlowFiles To Log")->withDescription(
"Number of flow files to log. If set to zero all flow files will be logged. Please note that this may block other threads from running if not used judiciously.")->withDefaultValue<uint64_t>(1)
->build());
core::Property LogAttribute::AttributesToIgnore(
core::PropertyBuilder::createProperty("Attributes to Ignore")->withDescription("A comma-separated list of Attributes to ignore. If not specified, no attributes will be ignored.")->build());
core::Property LogAttribute::LogPayload(core::PropertyBuilder::createProperty("Log Payload")->withDescription("If true, the FlowFile's payload will be logged, in addition to its attributes."
"otherwise, just the Attributes will be logged")->withDefaultValue<bool>(false)->build());
core::Property LogAttribute::HexencodePayload(
core::PropertyBuilder::createProperty("Hexencode Payload")->withDescription(
"If true, the FlowFile's payload will be logged in a hexencoded format")->withDefaultValue<bool>(false)->build());
core::Property LogAttribute::MaxPayloadLineLength(
core::PropertyBuilder::createProperty("Maximum Payload Line Length")->withDescription(
"The logged payload will be broken into lines this long. 0 means no newlines will be added.")->withDefaultValue<uint32_t>(80U)->build());
core::Property LogAttribute::LogPrefix(
core::PropertyBuilder::createProperty("Log Prefix")->withDescription("Log prefix appended to the log lines. It helps to distinguish the output of multiple LogAttribute processors.")->build());
core::Relationship LogAttribute::Success("success", "success operational on the flow record");
void LogAttribute::initialize() {
// Set the supported properties
std::set<core::Property> properties;
properties.insert(LogLevel);
properties.insert(AttributesToLog);
properties.insert(AttributesToIgnore);
properties.insert(LogPayload);
properties.insert(HexencodePayload);
properties.insert(MaxPayloadLineLength);
properties.insert(FlowFilesToLog);
properties.insert(LogPrefix);
setSupportedProperties(properties);
// Set the supported relationships
std::set<core::Relationship> relationships;
relationships.insert(Success);
setSupportedRelationships(relationships);
}
void LogAttribute::onSchedule(const std::shared_ptr<core::ProcessContext> &context, const std::shared_ptr<core::ProcessSessionFactory> &factory) {
core::Property flowsToLog = FlowFilesToLog;
if (getProperty(FlowFilesToLog.getName(), flowsToLog)) {
// we are going this route since to avoid breaking backwards compatibility the get property function doesn't perform validation ( That's done
// in configuration. In future releases we can add that exception handling there.
if (!flowsToLog.getValue().validate("Validating FlowFilesToLog").valid())
throw Exception(PROCESS_SCHEDULE_EXCEPTION, "Invalid value for flowfiles to log: " + flowsToLog.getValue().to_string());
flowfiles_to_log_ = flowsToLog.getValue();
}
std::string value;
if (context->getProperty(HexencodePayload.getName(), value)) {
utils::StringUtils::StringToBool(value, hexencode_);
}
if (context->getProperty(MaxPayloadLineLength.getName(), value)) {
core::Property::StringToInt(value, max_line_length_);
}
}
// OnTrigger method, implemented by NiFi LogAttribute
void LogAttribute::onTrigger(const std::shared_ptr<core::ProcessContext> &context, const std::shared_ptr<core::ProcessSession> &session) {
logger_->log_trace("enter log attribute, attempting to retrieve %u flow files", flowfiles_to_log_);
std::string dashLine = "--------------------------------------------------";
LogAttrLevel level = LogAttrLevelInfo;
bool logPayload = false;
uint64_t i = 0;
const auto max = flowfiles_to_log_ == 0 ? UINT64_MAX : flowfiles_to_log_;
for (; i < max; ++i) {
std::shared_ptr<core::FlowFile> flow = session->get();
if (!flow) {
break;
}
std::string value;
if (context->getProperty(LogLevel.getName(), value)) {
logLevelStringToEnum(value, level);
}
if (context->getProperty(LogPrefix.getName(), value)) {
dashLine = "-----" + value + "-----";
}
context->getProperty(LogPayload.getName(), logPayload);
std::ostringstream message;
message << "Logging for flow file " << "\n";
message << dashLine;
message << "\nStandard FlowFile Attributes";
message << "\n" << "UUID:" << flow->getUUIDStr();
message << "\n" << "EntryDate:" << getTimeStr(flow->getEntryDate());
message << "\n" << "lineageStartDate:" << getTimeStr(flow->getlineageStartDate());
message << "\n" << "Size:" << flow->getSize() << " Offset:" << flow->getOffset();
message << "\nFlowFile Attributes Map Content";
std::map<std::string, std::string> attrs = flow->getAttributes();
std::map<std::string, std::string>::iterator it;
for (it = attrs.begin(); it != attrs.end(); it++) {
message << "\n" << "key:" << it->first << " value:" << it->second;
}
message << "\nFlowFile Resource Claim Content";
std::shared_ptr<ResourceClaim> claim = flow->getResourceClaim();
if (claim) {
message << "\n" << "Content Claim:" << claim->getContentFullPath();
}
if (logPayload && flow->getSize() <= 1024 * 1024) {
message << "\n" << "Payload:" << "\n";
ReadCallback callback(logger_, flow->getSize());
session->read(flow, &callback);
std::string printable_payload;
if (hexencode_) {
printable_payload = utils::StringUtils::to_hex(callback.buffer_.data(), callback.buffer_.size());
} else {
printable_payload = std::string(reinterpret_cast<char*>(callback.buffer_.data()), callback.buffer_.size());
}
if (max_line_length_ == 0U) {
message << printable_payload << "\n";
} else {
for (size_t i = 0; i < printable_payload.size(); i += max_line_length_) {
message << printable_payload.substr(i, max_line_length_) << '\n';
}
}
} else {
message << "\n";
}
message << dashLine;
std::string output = message.str();
switch (level) {
case LogAttrLevelInfo:
logging::LOG_INFO(logger_) << output;
break;
case LogAttrLevelDebug:
logging::LOG_DEBUG(logger_) << output;
break;
case LogAttrLevelError:
logging::LOG_ERROR(logger_) << output;
break;
case LogAttrLevelTrace:
logging::LOG_TRACE(logger_) << output;
break;
case LogAttrLevelWarn:
logging::LOG_WARN(logger_) << output;
break;
default:
break;
}
session->transfer(flow, Success);
}
logger_->log_debug("Logged %d flow files", i);
}
} /* namespace processors */
} /* namespace minifi */
} /* namespace nifi */
} /* namespace apache */
} /* namespace org */
<|endoftext|> |
<commit_before><commit_msg>Added extra options to rotate around X,Y,Z axes.<commit_after><|endoftext|> |
<commit_before>/*
* Copyright 2013-2014 gtalent2@gmail.com
*
* 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 WOMBAT_CORE_THREADS_HPP
#define WOMBAT_CORE_THREADS_HPP
#include <functional>
#include <queue>
#ifdef WITH_SDL
#include <SDL.h>
#endif
#include "types.hpp"
namespace wombat {
namespace core {
class Semaphore;
class TaskProcessor;
class Task {
public:
virtual int64 run() = 0;
};
class Mutex {
public:
#ifdef WITH_SDL
SDL_mutex *m_mutex;
#endif
/**
* Constructor
*/
Mutex();
/**
* Destructor
*/
~Mutex();
/**
* Locks this Mutex.
* @return 0 on success
*/
int lock();
/**
* Unlocks this Mutex.
* @return 0 on success
*/
int unlock();
private:
Mutex(const Mutex&);
Mutex &operator=(const Mutex&);
};
class SemaphorePost {
friend Semaphore;
friend TaskProcessor;
public:
enum Reason {
GenericPost,
Timeout,
ReceivedMessage
};
protected:
/**
* Used to specify the Task that received a message.
*/
Task *m_task;
Reason m_reason;
public:
/**
* Constructor
* @param reason optional reason parameter, defaults to GenericPost
*/
SemaphorePost(Reason reason = GenericPost);
/**
* Gets the reason for the wake up.
* @return the reason for the post
*/
Reason reason();
};
class Semaphore {
private:
#ifdef WITH_SDL
SDL_sem *m_semaphore;
SDL_mutex *m_mutex;
#endif
std::queue<SemaphorePost> m_posts;
public:
/**
* Constructor
*/
Semaphore();
/**
* Destructor
*/
~Semaphore();
/**
* Waits until there is a post to process.
* @return a SemaphorePost with the reason for the wake up
*/
SemaphorePost wait();
/**
* Waits until there is a post to process or the given timeout has expired.
* @param timeout the desired timeout period in milliseconds
* @return a SemaphorePost with the reason for the wake up
*/
SemaphorePost wait(uint64 timeout);
/**
* Posts the the Semaphore to wake up.
* @param wakeup optional parameter used to specify the reason for the wake up
*/
void post(SemaphorePost wakeup = SemaphorePost());
/**
* Gets the oldest post available.
* @return the oldest post available
*/
SemaphorePost popPost();
/**
* Indicates whether or not there are any pending posts.
* @return indicator of whether or not there are any pending posts
*/
bool hasPosts();
// disallow copying
private:
Semaphore(const Semaphore&);
Semaphore &operator=(const Semaphore&);
};
class TaskProcessor {
private:
bool m_running;
public:
/**
* Starts the thread for this TaskProcessor.
*/
void start();
};
void startThread(std::function<void()> f);
void sleep(uint64 ms);
template <typename T>
class Channel {
private:
Semaphore *m_sem;
Mutex m_mutex;
std::queue<T> m_msgs;
public:
/**
* Constructor
* @param sem the Semaphore for this Channel to listen on
*/
Channel(Semaphore *sem = new Semaphore()) {
m_sem = sem;
}
/**
* Destructor
*/
~Channel() {
delete m_sem();
}
/**
* Read will wait until a message is received, then write it to the given
* destination.
* @param msg reference to the message to write to
* @return reason for the wake up
*/
SemaphorePost::Reason read(T &msg) {
auto reason = m_sem->wait().reason();
if (reason == SemaphorePost::ReceivedMessage) {
m_mutex.lock();
msg = m_msgs.front();
m_msgs.pop();
m_mutex.unlock();
}
return reason;
}
/**
* Read will wait until a message is received, then write it to the given
* destination.
* @param msg reference to the message to write to
* @param timeout timeout duration to give up on
* @return reason for the wake up
*/
SemaphorePost::Reason read(T &msg, uint64 timeout) {
auto reason = m_sem->wait(timeout).reason();
if (reason == SemaphorePost::ReceivedMessage) {
m_mutex.lock();
msg = m_msgs.front();
m_msgs.pop();
m_mutex.unlock();
}
return reason;
}
/**
* Writes the given message to the message queue and wakes up any thread
* waiting for a message.
* @param msg the message to write
*/
void write(T msg) {
m_mutex.lock();
m_msgs.push(msg);
m_mutex.unlock();
m_sem->post(SemaphorePost::ReceivedMessage);
}
// disallow copying
private:
Channel(const Channel&);
Channel &operator=(const Channel&);
};
}
}
#endif
<commit_msg>Added null check to Channel's destrutor, as its API would actually the semaphore to be null.<commit_after>/*
* Copyright 2013-2014 gtalent2@gmail.com
*
* 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 WOMBAT_CORE_THREADS_HPP
#define WOMBAT_CORE_THREADS_HPP
#include <functional>
#include <queue>
#ifdef WITH_SDL
#include <SDL.h>
#endif
#include "types.hpp"
namespace wombat {
namespace core {
class Semaphore;
class TaskProcessor;
class Task {
public:
virtual int64 run() = 0;
};
class Mutex {
public:
#ifdef WITH_SDL
SDL_mutex *m_mutex;
#endif
/**
* Constructor
*/
Mutex();
/**
* Destructor
*/
~Mutex();
/**
* Locks this Mutex.
* @return 0 on success
*/
int lock();
/**
* Unlocks this Mutex.
* @return 0 on success
*/
int unlock();
private:
Mutex(const Mutex&);
Mutex &operator=(const Mutex&);
};
class SemaphorePost {
friend Semaphore;
friend TaskProcessor;
public:
enum Reason {
GenericPost,
Timeout,
ReceivedMessage
};
protected:
/**
* Used to specify the Task that received a message.
*/
Task *m_task;
Reason m_reason;
public:
/**
* Constructor
* @param reason optional reason parameter, defaults to GenericPost
*/
SemaphorePost(Reason reason = GenericPost);
/**
* Gets the reason for the wake up.
* @return the reason for the post
*/
Reason reason();
};
class Semaphore {
private:
#ifdef WITH_SDL
SDL_sem *m_semaphore;
SDL_mutex *m_mutex;
#endif
std::queue<SemaphorePost> m_posts;
public:
/**
* Constructor
*/
Semaphore();
/**
* Destructor
*/
~Semaphore();
/**
* Waits until there is a post to process.
* @return a SemaphorePost with the reason for the wake up
*/
SemaphorePost wait();
/**
* Waits until there is a post to process or the given timeout has expired.
* @param timeout the desired timeout period in milliseconds
* @return a SemaphorePost with the reason for the wake up
*/
SemaphorePost wait(uint64 timeout);
/**
* Posts the the Semaphore to wake up.
* @param wakeup optional parameter used to specify the reason for the wake up
*/
void post(SemaphorePost wakeup = SemaphorePost());
/**
* Gets the oldest post available.
* @return the oldest post available
*/
SemaphorePost popPost();
/**
* Indicates whether or not there are any pending posts.
* @return indicator of whether or not there are any pending posts
*/
bool hasPosts();
// disallow copying
private:
Semaphore(const Semaphore&);
Semaphore &operator=(const Semaphore&);
};
class TaskProcessor {
private:
bool m_running;
public:
/**
* Starts the thread for this TaskProcessor.
*/
void start();
};
void startThread(std::function<void()> f);
void sleep(uint64 ms);
template <typename T>
class Channel {
private:
Semaphore *m_sem;
Mutex m_mutex;
std::queue<T> m_msgs;
public:
/**
* Constructor
* @param sem the Semaphore for this Channel to listen on
*/
Channel(Semaphore *sem = new Semaphore()) {
m_sem = sem;
}
/**
* Destructor
*/
~Channel() {
if (m_sem) {
delete m_sem;
}
}
/**
* Read will wait until a message is received, then write it to the given
* destination.
* @param msg reference to the message to write to
* @return reason for the wake up
*/
SemaphorePost::Reason read(T &msg) {
auto reason = m_sem->wait().reason();
if (reason == SemaphorePost::ReceivedMessage) {
m_mutex.lock();
msg = m_msgs.front();
m_msgs.pop();
m_mutex.unlock();
}
return reason;
}
/**
* Read will wait until a message is received, then write it to the given
* destination.
* @param msg reference to the message to write to
* @param timeout timeout duration to give up on
* @return reason for the wake up
*/
SemaphorePost::Reason read(T &msg, uint64 timeout) {
auto reason = m_sem->wait(timeout).reason();
if (reason == SemaphorePost::ReceivedMessage) {
m_mutex.lock();
msg = m_msgs.front();
m_msgs.pop();
m_mutex.unlock();
}
return reason;
}
/**
* Writes the given message to the message queue and wakes up any thread
* waiting for a message.
* @param msg the message to write
*/
void write(T msg) {
m_mutex.lock();
m_msgs.push(msg);
m_mutex.unlock();
m_sem->post(SemaphorePost::ReceivedMessage);
}
// disallow copying
private:
Channel(const Channel&);
Channel &operator=(const Channel&);
};
}
}
#endif
<|endoftext|> |
<commit_before>#include "ros/ros.h"
#include "boost/asio.hpp"
#include "jaws_msgs/Thrusters.h"
class Arbotix
{
private:
ros::NodeHandle prm;
ros::NodeHandle nh;
ros::Subscriber sub;
boost::asio::io_service i_o;
boost::asio::serial_port s_p;
std::string port_name;
public:
Arbotix() : prm("~"), nh(), i_o(), s_p(i_o)
{
prm.param<std::string>("port", port_name, "/dev/ttyUSB0");
s_p.open(port_name);
s_p.set_option(boost::asio::serial_port_base::baud_rate(38400));
sub = nh.subscribe<jaws_msgs::Thrusters>("thrusters", 1, &Arbotix::callback, this);
}
void callback(const jaws_msgs::Thrusters::ConstPtr& thrusters)
{
const int SIZE = 11;
unsigned char packet[SIZE];
packet[0] = '-';
packet[1] = (thrusters->port_angle >> 8) & 0xFF;
packet[2] = thrusters->port_angle & 0xFF;
packet[3] = (thrusters->stbd_angle >> 8) & 0xFF;
packet[4] = thrusters->stbd_angle & 0xFF;
packet[5] = (thrusters->aft_power >> 8) & 0xFF;
packet[6] = thrusters->aft_power & 0xFF;
packet[7] = (thrusters->port_power >> 8) & 0xFF;
packet[8] = thrusters->port_power & 0xFF;
packet[9] = (thrusters->stbd_power >> 8) & 0xFF;
packet[10] = thrusters->stbd_power & 0xFF;
s_p.write_some(boost::asio::buffer(&packet, SIZE));
}
void loop()
{
ros::spin();
}
};
int main(int argc, char **argv)
{
ros::init(argc, argv, "arbotix_node");
Arbotix arbotix;
arbotix.loop();
}
<commit_msg>Added parameters<commit_after>#include "ros/ros.h"
#include "boost/asio.hpp"
#include "jaws_msgs/Thrusters.h"
class Arbotix
{
private:
ros::NodeHandle nh;
ros::Subscriber sub;
boost::asio::io_service i_o;
boost::asio::serial_port s_p;
std::string port_name;
int br;
public:
Arbotix() : nh(), i_o(), s_p(i_o)
{
nh.getParam("/arbotix_node/port_name",port_name);
nh.getParam("/arbotix_node/baud_rate",br);
s_p.open(port_name);
s_p.set_option(boost::asio::serial_port_base::baud_rate(br));
sub = nh.subscribe<jaws_msgs::Thrusters>("thrusters", 1, &Arbotix::callback, this);
}
void callback(const jaws_msgs::Thrusters::ConstPtr& thrusters)
{
const int SIZE = 11;
unsigned char packet[SIZE];
packet[0] = '-';
packet[1] = (thrusters->port_angle >> 8) & 0xFF;
packet[2] = thrusters->port_angle & 0xFF;
packet[3] = (thrusters->stbd_angle >> 8) & 0xFF;
packet[4] = thrusters->stbd_angle & 0xFF;
packet[5] = (thrusters->aft_power >> 8) & 0xFF;
packet[6] = thrusters->aft_power & 0xFF;
packet[7] = (thrusters->port_power >> 8) & 0xFF;
packet[8] = thrusters->port_power & 0xFF;
packet[9] = (thrusters->stbd_power >> 8) & 0xFF;
packet[10] = thrusters->stbd_power & 0xFF;
s_p.write_some(boost::asio::buffer(&packet, SIZE));
}
void loop()
{
ros::spin();
}
};
int main(int argc, char **argv)
{
ros::init(argc, argv, "arbotix_node");
Arbotix arbotix;
arbotix.loop();
}
<|endoftext|> |
<commit_before>/*
* Copyright (C) 2017 National Research Institute of Science and
* Technology for Environment and Agriculture (IRSTEA)
*
* This file is part of Orfeo Toolbox
*
* https://www.orfeo-toolbox.org/
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "itkFixedArray.h"
#include "itkObjectFactory.h"
// Elevation handler
#include "otbWrapperElevationParametersHandler.h"
#include "otbWrapperApplicationFactory.h"
// Application engine
#include "otbStandardFilterWatcher.h"
// Process objects
#include "otbVectorDataToLabelImageFilter.h"
#include "otbVectorDataIntoImageProjectionFilter.h"
#include "otbStreamingStatisticsMapFromLabelImageFilter.h"
#include "otbStatisticsXMLFileWriter.h"
namespace otb
{
namespace Wrapper
{
class ZonalStatistics : public Application
{
public:
/** Standard class typedefs. */
typedef ZonalStatistics Self;
typedef Application Superclass;
typedef itk::SmartPointer<Self> Pointer;
typedef itk::SmartPointer<const Self> ConstPointer;
/* Typedefs */
typedef UInt32ImageType LabelImageType;
typedef LabelImageType::ValueType LabelValueType;
typedef otb::VectorData<double, 2> VectorDataType;
typedef otb::VectorDataIntoImageProjectionFilter<VectorDataType,
FloatVectorImageType> VectorDataReprojFilterType;
typedef otb::VectorDataToLabelImageFilter<VectorDataType,
LabelImageType> RasterizeFilterType;
typedef VectorDataType::DataTreeType DataTreeType;
typedef itk::PreOrderTreeIterator<DataTreeType>
TreeIteratorType;
typedef VectorDataType::DataNodeType DataNodeType;
typedef DataNodeType::PolygonListPointerType
PolygonListPointerType;
typedef otb::StreamingStatisticsMapFromLabelImageFilter<FloatVectorImageType,
LabelImageType> StatsFilterType;
typedef otb::StatisticsXMLFileWriter<FloatVectorImageType::PixelType>
StatsWriterType;
/** Standard macro */
itkNewMacro(Self);
itkTypeMacro(ZonalStatistics, Application);
void DoInit()
{
SetName("ZonalStatistics");
SetDescription("This application computes zonal statistics");
// Documentation
SetDocName("ZonalStatistics");
SetDocLongDescription("This application computes zonal statistics from label image, or vector data. "
"The application inputs one input multiband image, and a label input. "
"If the label input is a raster, the output statistics are exported in a XML file. If the label "
"input is a vector data, the output statistics are exported in a new vector data with statistics "
"in the attribute table. The computed statistics are mean, min, max, and standard deviation.");
SetDocLimitations("The shapefile must fit in memory");
SetDocAuthors("Remi Cresson");
AddDocTag(Tags::Manip);
AddDocTag(Tags::Analysis);
// Input image
AddParameter(ParameterType_InputImage, "in", "Input Image");
// Processing mode
AddParameter(ParameterType_Choice, "mode", "Processing mode");
AddChoice("mode.vector", "Input objects from vector data");
AddChoice("mode.labelimage", "Input objects from label image");
// Input for vector mode
AddParameter(ParameterType_InputVectorData, "mode.vector.in", "Input vector data");
AddParameter(ParameterType_Bool, "mode.vector.reproject", "Reproject the input vector");
AddParameter(ParameterType_OutputVectorData, "mode.vector.out", "Output vector data");
// Input for label image mode
AddParameter(ParameterType_InputImage, "mode.labelimage.in", "Input label image");
AddParameter(ParameterType_InputImage, "mode.labelimage.outxml", "Output XML file");
// No data value
AddParameter(ParameterType_Float, "nodata", "No-data value");
MandatoryOff("nodata");
AddRAMParameter();
// Doc example parameter settings
SetDocExampleParameterValue("in", "input.tif");
SetDocExampleParameterValue("mode.vector.in", "myvector.shp");
SetDocExampleParameterValue("mode.vector.out", "myvector_with_stats.shp");
}
void DoUpdateParameters()
{
// Nothing to do here : all parameters are independent
}
// Returns a string of the kind "prefix_i"
const std::string CreateFieldName(const std::string & prefix, const unsigned int i)
{
std::stringstream ss;
ss << prefix << "_" << i;
return ss.str();
}
// Returns a null pixel which has the same number of components per pixels as img
FloatVectorImageType::PixelType NullPixel(FloatVectorImageType::Pointer & img)
{
const unsigned int nBands = img->GetNumberOfComponentsPerPixel();
FloatVectorImageType::PixelType pix;
pix.SetSize(nBands);
pix.Fill(0);
return pix;
}
void DoExecute()
{
// Get input image
FloatVectorImageType::Pointer img = GetParameterImage("in");
// Instantiate objects that are used by both processing modes
// No-data
FloatVectorImageType::InternalPixelType m_InputNoData = 0;
const bool has_nodata = HasValue("nodata");
if (has_nodata)
{
m_InputNoData = GetParameterFloat("nodata");
otbAppLogINFO("Using no-data value: " << m_InputNoData);
}
// Internal no-data value
const LabelValueType intNoData = itk::NumericTraits<LabelValueType>::max();
// Statistics filter
m_StatsFilter = StatsFilterType::New();
m_StatsFilter->SetInput(img);
m_StatsFilter->GetStreamer()->SetAutomaticAdaptativeStreaming(GetParameterInt("ram"));
AddProcess(m_StatsFilter->GetStreamer(), "Computing statistics");
// Select mode
if (GetParameterAsString("mode") == "vector")
{
otbAppLogINFO("Processing mode: vector");
otbAppLogINFO("Loading vector data...");
VectorDataType* shp = GetParameterVectorData("mode.vector.in");
// Reproject vector data
if (GetParameterInt("mode.vector.reproject") != 0)
{
otbAppLogINFO("Vector data reprojection enabled");
m_VectorDataReprojectionFilter = VectorDataReprojFilterType::New();
m_VectorDataReprojectionFilter->SetInputVectorData(shp);
m_VectorDataReprojectionFilter->SetInputImage(img);
AddProcess(m_VectorDataReprojectionFilter, "Reproject vector data");
m_VectorDataReprojectionFilter->Update();
m_VectorDataSrc = m_VectorDataReprojectionFilter->GetOutput();
}
else
{
m_VectorDataSrc = shp;
}
// Rasterize vector data
m_RasterizeFilter = RasterizeFilterType::New();
m_RasterizeFilter->AddVectorData(m_VectorDataSrc);
m_RasterizeFilter->SetOutputOrigin(img->GetOrigin());
m_RasterizeFilter->SetOutputSpacing(img->GetSignedSpacing());
m_RasterizeFilter->SetOutputSize(img->GetLargestPossibleRegion().GetSize());
m_RasterizeFilter->SetOutputProjectionRef(img->GetProjectionRef());
m_RasterizeFilter->SetBurnAttribute("________");
m_RasterizeFilter->SetDefaultBurnValue(0);
m_RasterizeFilter->SetGlobalWarningDisplay(false);
m_RasterizeFilter->SetBackgroundValue(intNoData);
// Computing stats
m_StatsFilter->SetInputLabelImage(m_RasterizeFilter->GetOutput());
m_StatsFilter->Update();
// Remove the no-data entry
StatsFilterType::LabelPopulationMapType countMap = m_StatsFilter->GetLabelPopulationMap();
StatsFilterType::PixelValueMapType meanMap = m_StatsFilter->GetMeanValueMap();
StatsFilterType::PixelValueMapType stdMap = m_StatsFilter->GetStandardDeviationValueMap();
StatsFilterType::PixelValueMapType minMap = m_StatsFilter->GetMinValueMap();
StatsFilterType::PixelValueMapType maxMap = m_StatsFilter->GetMaxValueMap();
countMap.erase(intNoData);
meanMap.erase(intNoData);
stdMap.erase(intNoData);
minMap.erase(intNoData);
maxMap.erase(intNoData);
// Add a statistics fields
otbAppLogINFO("Writing output vector data");
LabelValueType internalFID = 0;
m_NewVectorData = VectorDataType::New();
DataNodeType::Pointer root = m_NewVectorData->GetDataTree()->GetRoot()->Get();
DataNodeType::Pointer document = DataNodeType::New();
document->SetNodeType(otb::DOCUMENT);
m_NewVectorData->GetDataTree()->Add(document, root);
DataNodeType::Pointer folder = DataNodeType::New();
folder->SetNodeType(otb::FOLDER);
m_NewVectorData->GetDataTree()->Add(folder, document);
m_NewVectorData->SetProjectionRef(m_VectorDataSrc->GetProjectionRef());
TreeIteratorType itVector(m_VectorDataSrc->GetDataTree());
itVector.GoToBegin();
while (!itVector.IsAtEnd())
{
if (!itVector.Get()->IsRoot() && !itVector.Get()->IsDocument() && !itVector.Get()->IsFolder())
{
DataNodeType::Pointer currentGeometry = itVector.Get();
// Add the geometry with the new fields
if (countMap.count(internalFID) > 0)
{
currentGeometry->SetFieldAsDouble("count", countMap[internalFID] );
for (unsigned int band = 0 ; band < img->GetNumberOfComponentsPerPixel() ; band++)
{
currentGeometry->SetFieldAsDouble(CreateFieldName("mean", band), meanMap[internalFID][band] );
currentGeometry->SetFieldAsDouble(CreateFieldName("stdev", band), stdMap [internalFID][band] );
currentGeometry->SetFieldAsDouble(CreateFieldName("min", band), minMap [internalFID][band] );
currentGeometry->SetFieldAsDouble(CreateFieldName("max", band), maxMap [internalFID][band] );
}
m_NewVectorData->GetDataTree()->Add(currentGeometry, folder);
}
internalFID++;
}
++itVector;
} // next feature
SetParameterOutputVectorData("mode.vector.out", m_NewVectorData);
}
else if (GetParameterAsString("mode") == "labelimage")
{
otbAppLogINFO("Processing mode: label image");
// Computing stats
m_StatsFilter->SetInputLabelImage(GetParameterUInt32Image("mode.labelimage.in"));
m_StatsFilter->Update();
// Remove the no-data entry
StatsFilterType::LabelPopulationMapType countMap = m_StatsFilter->GetLabelPopulationMap();
StatsFilterType::PixelValueMapType meanMap = m_StatsFilter->GetMeanValueMap();
StatsFilterType::PixelValueMapType stdMap = m_StatsFilter->GetStandardDeviationValueMap();
StatsFilterType::PixelValueMapType minMap = m_StatsFilter->GetMinValueMap();
StatsFilterType::PixelValueMapType maxMap = m_StatsFilter->GetMaxValueMap();
countMap.erase(intNoData);
meanMap.erase(intNoData);
stdMap.erase(intNoData);
minMap.erase(intNoData);
maxMap.erase(intNoData);
// Write stats
const std::string outXMLFile = this->GetParameterString("mode.labelimage.outxml");
otbAppLogINFO("Writing " + outXMLFile)
StatsWriterType::Pointer statWriter = StatsWriterType::New();
statWriter->SetFileName(outXMLFile);
statWriter->AddInputMap<StatsFilterType::LabelPopulationMapType>("count",countMap);
statWriter->AddInputMap<StatsFilterType::PixelValueMapType>("mean",meanMap);
statWriter->AddInputMap<StatsFilterType::PixelValueMapType>("std",stdMap);
statWriter->AddInputMap<StatsFilterType::PixelValueMapType>("min",minMap);
statWriter->AddInputMap<StatsFilterType::PixelValueMapType>("max",maxMap);
statWriter->Update();
}
else
{
otbAppLogFATAL("Unknow processing mode");
}
}
VectorDataType::Pointer m_VectorDataSrc;
VectorDataType::Pointer m_NewVectorData;
VectorDataReprojFilterType::Pointer m_VectorDataReprojectionFilter;
RasterizeFilterType::Pointer m_RasterizeFilter;
StatsFilterType::Pointer m_StatsFilter;
};
}
}
OTB_APPLICATION_EXPORT( otb::Wrapper::ZonalStatistics )
<commit_msg>FIX: nodata now only in labelimage mode<commit_after>/*
* Copyright (C) 2017 National Research Institute of Science and
* Technology for Environment and Agriculture (IRSTEA)
*
* This file is part of Orfeo Toolbox
*
* https://www.orfeo-toolbox.org/
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "itkFixedArray.h"
#include "itkObjectFactory.h"
// Elevation handler
#include "otbWrapperElevationParametersHandler.h"
#include "otbWrapperApplicationFactory.h"
// Application engine
#include "otbStandardFilterWatcher.h"
// Process objects
#include "otbVectorDataToLabelImageFilter.h"
#include "otbVectorDataIntoImageProjectionFilter.h"
#include "otbStreamingStatisticsMapFromLabelImageFilter.h"
#include "otbStatisticsXMLFileWriter.h"
namespace otb
{
namespace Wrapper
{
class ZonalStatistics : public Application
{
public:
/** Standard class typedefs. */
typedef ZonalStatistics Self;
typedef Application Superclass;
typedef itk::SmartPointer<Self> Pointer;
typedef itk::SmartPointer<const Self> ConstPointer;
/* Typedefs */
typedef Int32ImageType LabelImageType;
typedef LabelImageType::ValueType LabelValueType;
typedef otb::VectorData<double, 2> VectorDataType;
typedef otb::VectorDataIntoImageProjectionFilter<VectorDataType,
FloatVectorImageType> VectorDataReprojFilterType;
typedef otb::VectorDataToLabelImageFilter<VectorDataType,
LabelImageType> RasterizeFilterType;
typedef VectorDataType::DataTreeType DataTreeType;
typedef itk::PreOrderTreeIterator<DataTreeType>
TreeIteratorType;
typedef VectorDataType::DataNodeType DataNodeType;
typedef DataNodeType::PolygonListPointerType
PolygonListPointerType;
typedef otb::StreamingStatisticsMapFromLabelImageFilter<FloatVectorImageType,
LabelImageType> StatsFilterType;
typedef otb::StatisticsXMLFileWriter<FloatVectorImageType::PixelType>
StatsWriterType;
/** Standard macro */
itkNewMacro(Self);
itkTypeMacro(ZonalStatistics, Application);
void DoInit()
{
SetName("ZonalStatistics");
SetDescription("This application computes zonal statistics");
// Documentation
SetDocName("ZonalStatistics");
SetDocLongDescription("This application computes zonal statistics from label image, or vector data. "
"The application inputs one input multiband image, and a label input. "
"If the label input is a raster, the output statistics are exported in a XML file. If the label "
"input is a vector data, the output statistics are exported in a new vector data with statistics "
"in the attribute table. The computed statistics are mean, min, max, and standard deviation.");
SetDocLimitations("The shapefile must fit in memory");
SetDocAuthors("Remi Cresson");
AddDocTag(Tags::Manip);
AddDocTag(Tags::Analysis);
// Input image
AddParameter(ParameterType_InputImage, "in", "Input Image");
// Processing mode
AddParameter(ParameterType_Choice, "mode", "Processing mode");
AddChoice("mode.vector", "Input objects from vector data");
AddChoice("mode.labelimage", "Input objects from label image");
// Input for vector mode
AddParameter(ParameterType_InputVectorData, "mode.vector.in", "Input vector data");
AddParameter(ParameterType_Bool, "mode.vector.reproject", "Reproject the input vector");
AddParameter(ParameterType_OutputVectorData, "mode.vector.out", "Output vector data");
// Input for label image mode
AddParameter(ParameterType_InputImage, "mode.labelimage.in", "Input label image");
AddParameter(ParameterType_Int, "mode.labelimage.nodata", "No-data value for the input label image");
SetDefaultParameterInt ("mode.labelimage.nodata", 0);
MandatoryOff ("mode.labelimage.nodata");
AddParameter(ParameterType_InputImage, "mode.labelimage.outxml", "Output XML file");
AddRAMParameter();
// Doc example parameter settings
SetDocExampleParameterValue("in", "input.tif");
SetDocExampleParameterValue("mode.vector.in", "myvector.shp");
SetDocExampleParameterValue("mode.vector.out", "myvector_with_stats.shp");
}
void DoUpdateParameters()
{
// Nothing to do here : all parameters are independent
}
// Returns a string of the kind "prefix_i"
const std::string CreateFieldName(const std::string & prefix, const unsigned int i)
{
std::stringstream ss;
ss << prefix << "_" << i;
return ss.str();
}
// Returns a null pixel which has the same number of components per pixels as img
FloatVectorImageType::PixelType NullPixel(FloatVectorImageType::Pointer & img)
{
const unsigned int nBands = img->GetNumberOfComponentsPerPixel();
FloatVectorImageType::PixelType pix;
pix.SetSize(nBands);
pix.Fill(0);
return pix;
}
void DoExecute()
{
// Get input image
FloatVectorImageType::Pointer img = GetParameterImage("in");
// Statistics filter
m_StatsFilter = StatsFilterType::New();
m_StatsFilter->SetInput(img);
m_StatsFilter->GetStreamer()->SetAutomaticAdaptativeStreaming(GetParameterInt("ram"));
AddProcess(m_StatsFilter->GetStreamer(), "Computing statistics");
// Select mode
if (GetParameterAsString("mode") == "vector")
{
otbAppLogINFO("Processing mode: vector");
otbAppLogINFO("Loading vector data...");
VectorDataType* shp = GetParameterVectorData("mode.vector.in");
// Reproject vector data
if (GetParameterInt("mode.vector.reproject") != 0)
{
otbAppLogINFO("Vector data reprojection enabled");
m_VectorDataReprojectionFilter = VectorDataReprojFilterType::New();
m_VectorDataReprojectionFilter->SetInputVectorData(shp);
m_VectorDataReprojectionFilter->SetInputImage(img);
AddProcess(m_VectorDataReprojectionFilter, "Reproject vector data");
m_VectorDataReprojectionFilter->Update();
m_VectorDataSrc = m_VectorDataReprojectionFilter->GetOutput();
}
else
{
m_VectorDataSrc = shp;
}
// Internal no-data value
const LabelValueType intNoData = itk::NumericTraits<LabelValueType>::max();
// Rasterize vector data
m_RasterizeFilter = RasterizeFilterType::New();
m_RasterizeFilter->AddVectorData(m_VectorDataSrc);
m_RasterizeFilter->SetOutputOrigin(img->GetOrigin());
m_RasterizeFilter->SetOutputSpacing(img->GetSignedSpacing());
m_RasterizeFilter->SetOutputSize(img->GetLargestPossibleRegion().GetSize());
m_RasterizeFilter->SetOutputProjectionRef(img->GetProjectionRef());
m_RasterizeFilter->SetBurnAttribute("________");
m_RasterizeFilter->SetDefaultBurnValue(intNoData);
m_RasterizeFilter->SetGlobalWarningDisplay(false);
m_RasterizeFilter->SetBackgroundValue(intNoData);
// Computing stats
m_StatsFilter->SetInputLabelImage(m_RasterizeFilter->GetOutput());
m_StatsFilter->Update();
// Remove the no-data entry
StatsFilterType::LabelPopulationMapType countMap = m_StatsFilter->GetLabelPopulationMap();
StatsFilterType::PixelValueMapType meanMap = m_StatsFilter->GetMeanValueMap();
StatsFilterType::PixelValueMapType stdMap = m_StatsFilter->GetStandardDeviationValueMap();
StatsFilterType::PixelValueMapType minMap = m_StatsFilter->GetMinValueMap();
StatsFilterType::PixelValueMapType maxMap = m_StatsFilter->GetMaxValueMap();
countMap.erase(intNoData);
meanMap.erase(intNoData);
stdMap.erase(intNoData);
minMap.erase(intNoData);
maxMap.erase(intNoData);
// Add a statistics fields
otbAppLogINFO("Writing output vector data");
LabelValueType internalFID = 0;
m_NewVectorData = VectorDataType::New();
DataNodeType::Pointer root = m_NewVectorData->GetDataTree()->GetRoot()->Get();
DataNodeType::Pointer document = DataNodeType::New();
document->SetNodeType(otb::DOCUMENT);
m_NewVectorData->GetDataTree()->Add(document, root);
DataNodeType::Pointer folder = DataNodeType::New();
folder->SetNodeType(otb::FOLDER);
m_NewVectorData->GetDataTree()->Add(folder, document);
m_NewVectorData->SetProjectionRef(m_VectorDataSrc->GetProjectionRef());
TreeIteratorType itVector(m_VectorDataSrc->GetDataTree());
itVector.GoToBegin();
while (!itVector.IsAtEnd())
{
if (!itVector.Get()->IsRoot() && !itVector.Get()->IsDocument() && !itVector.Get()->IsFolder())
{
DataNodeType::Pointer currentGeometry = itVector.Get();
// Add the geometry with the new fields
if (countMap.count(internalFID) > 0)
{
currentGeometry->SetFieldAsDouble("count", countMap[internalFID] );
for (unsigned int band = 0 ; band < img->GetNumberOfComponentsPerPixel() ; band++)
{
currentGeometry->SetFieldAsDouble(CreateFieldName("mean", band), meanMap[internalFID][band] );
currentGeometry->SetFieldAsDouble(CreateFieldName("stdev", band), stdMap [internalFID][band] );
currentGeometry->SetFieldAsDouble(CreateFieldName("min", band), minMap [internalFID][band] );
currentGeometry->SetFieldAsDouble(CreateFieldName("max", band), maxMap [internalFID][band] );
}
m_NewVectorData->GetDataTree()->Add(currentGeometry, folder);
}
internalFID++;
}
++itVector;
} // next feature
SetParameterOutputVectorData("mode.vector.out", m_NewVectorData);
}
else if (GetParameterAsString("mode") == "labelimage")
{
otbAppLogINFO("Processing mode: label image");
// Computing stats
m_StatsFilter->SetInputLabelImage(GetParameterInt32Image("mode.labelimage.in"));
m_StatsFilter->Update();
// Remove the no-data entry
StatsFilterType::LabelPopulationMapType countMap = m_StatsFilter->GetLabelPopulationMap();
StatsFilterType::PixelValueMapType meanMap = m_StatsFilter->GetMeanValueMap();
StatsFilterType::PixelValueMapType stdMap = m_StatsFilter->GetStandardDeviationValueMap();
StatsFilterType::PixelValueMapType minMap = m_StatsFilter->GetMinValueMap();
StatsFilterType::PixelValueMapType maxMap = m_StatsFilter->GetMaxValueMap();
if (HasUserValue("mode.labelimage.nodata"))
{
// Internal no-data value
const LabelValueType intNoData = GetParameterInt("mode.labelimage.nodata");
otbAppLogINFO("Using no-data value: " << intNoData);
countMap.erase(intNoData);
meanMap.erase(intNoData);
stdMap.erase(intNoData);
minMap.erase(intNoData);
maxMap.erase(intNoData);
}
// Write stats
const std::string outXMLFile = this->GetParameterString("mode.labelimage.outxml");
otbAppLogINFO("Writing " + outXMLFile)
StatsWriterType::Pointer statWriter = StatsWriterType::New();
statWriter->SetFileName(outXMLFile);
statWriter->AddInputMap<StatsFilterType::LabelPopulationMapType>("count",countMap);
statWriter->AddInputMap<StatsFilterType::PixelValueMapType>("mean",meanMap);
statWriter->AddInputMap<StatsFilterType::PixelValueMapType>("std",stdMap);
statWriter->AddInputMap<StatsFilterType::PixelValueMapType>("min",minMap);
statWriter->AddInputMap<StatsFilterType::PixelValueMapType>("max",maxMap);
statWriter->Update();
}
else
{
otbAppLogFATAL("Unknow processing mode");
}
}
VectorDataType::Pointer m_VectorDataSrc;
VectorDataType::Pointer m_NewVectorData;
VectorDataReprojFilterType::Pointer m_VectorDataReprojectionFilter;
RasterizeFilterType::Pointer m_RasterizeFilter;
StatsFilterType::Pointer m_StatsFilter;
};
}
}
OTB_APPLICATION_EXPORT( otb::Wrapper::ZonalStatistics )
<|endoftext|> |
<commit_before>/*
Copyright (c) 2019-2020 Carsten Burstedde, Donna Calhoun, Scott Aiton, Grady Wright
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.
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.
*/
#include "phasefield_operator.h"
#include "phasefield_patch_operator.h"
#include "phasefield_options.h"
#include "fc2d_thunderegg.h"
#include "fc2d_thunderegg_vector.hpp"
#include <fclaw2d_elliptic_solver.h>
#include <fclaw2d_clawpatch.h>
#include <fclaw2d_clawpatch_options.h>
#include <fclaw2d_clawpatch_output_ascii.h>
#include <fclaw2d_clawpatch_output_vtk.h>
#include <fclaw2d_global.h>
#include <fclaw2d_map.h>
#include <fclaw2d_map_brick.h>
#include <fclaw2d_options.h>
#include <fclaw2d_patch.h>
#include <fclaw2d_vtable.h>
#include <p4est_bits.h>
#include <p4est_wrap.h>
#include <ThunderEgg/BiCGStab.h>
#include <ThunderEgg/BiCGStabPatchSolver.h>
#include <ThunderEgg/VarPoisson/StarPatchOperator.h>
#include <ThunderEgg/Poisson/FFTWPatchSolver.h>
#include <ThunderEgg/GMG/LinearRestrictor.h>
#include <ThunderEgg/GMG/DirectInterpolator.h>
#include <ThunderEgg/P4estDomGen.h>
#include <ThunderEgg/GMG/CycleBuilder.h>
#include <ThunderEgg/BiLinearGhostFiller.h>
#include <ThunderEgg/ValVectorGenerator.h>
#include <stdlib.h>
using namespace std;
using namespace ThunderEgg;
using namespace ThunderEgg::VarPoisson;
void phasefield_set_lambda(double lambda)
{
phasefield::setLambda(lambda);
}
double phasefield_get_lambda()
{
return phasefield::getLambda();
}
shared_ptr<Vector<2>> restrict_phi_n_vec(shared_ptr<Vector<2>> prev_beta_vec,
shared_ptr<Domain<2>> prev_domain,
shared_ptr<Domain<2>> curr_domain)
{
GMG::LinearRestrictor<2> restrictor(prev_domain,curr_domain, prev_beta_vec->getNumComponents(), true);
auto new_beta_vec = ValVector<2>::GetNewVector(curr_domain, prev_beta_vec->getNumComponents());
restrictor.restrict(prev_beta_vec, new_beta_vec);
return new_beta_vec;
}
void phasefield_solve(fclaw2d_global_t *glob)
{
// get needed options
const fclaw_options_t *fclaw_opt = fclaw2d_get_options(glob);
const fc2d_thunderegg_options_t *mg_opt = fc2d_thunderegg_get_options(glob);
const fclaw2d_clawpatch_options_t *clawpatch_opt = fclaw2d_clawpatch_get_options(glob);
#if 0
fc2d_thunderegg_vtable_t *mg_vt = fc2d_thunderegg_vt();
#endif
// create thunderegg vector for eqn 0
shared_ptr<Vector<2>> f = make_shared<fc2d_thunderegg_vector>(glob,RHS);
// get patch size
array<int, 2> ns = {clawpatch_opt->mx, clawpatch_opt->my};
// get p4est structure
fclaw2d_domain_t *domain = glob->domain;
p4est_wrap_t *wrap = (p4est_wrap_t *)domain->pp;
// create map function
P4estDomGen::BlockMapFunc bmf = [&](int block_no, double unit_x,
double unit_y, double &x, double &y)
{
double x1,y1,z1;
FCLAW2D_MAP_BRICK2C(&glob->cont,&block_no,&unit_x, &unit_y, &x1, &y1, &z1);
x = fclaw_opt->ax + (fclaw_opt->bx - fclaw_opt->ax) * x1;
y = fclaw_opt->ay + (fclaw_opt->by - fclaw_opt->ay) * y1;
};
// create neumann function
IsNeumannFunc<2> inf = [&](Side<2> s, const array<double, 2> &lower,
const array<double, 2> &upper)
{
return mg_opt->boundary_conditions[s.getIndex()] == 2;
};
// generates levels of patches for GMG; 2 layers of ghost cells
P4estDomGen domain_gen(wrap->p4est, ns, clawpatch_opt->mbc, inf, bmf);
// get finest level
shared_ptr<Domain<2>> te_domain = domain_gen.getFinestDomain();
/* Store phi at time level n */
shared_ptr<Vector<2>> beta_vec = make_shared<fc2d_thunderegg_vector>(glob,STORE_STATE);
// ghost filler
auto ghost_filler = make_shared<BiLinearGhostFiller>(te_domain);
// patch operator
auto op = make_shared<phasefield>(glob,beta_vec,te_domain,ghost_filler);
// set the patch solver
shared_ptr<PatchSolver<2>> solver;
solver = make_shared<BiCGStabPatchSolver<2>>(op,
mg_opt->patch_bcgs_tol,
mg_opt->patch_bcgs_max_it);
// create matrix
shared_ptr<Operator<2>> A = op;
// create gmg preconditioner
shared_ptr<Operator<2>> M;
if (mg_opt->mg_prec && domain_gen.hasCoarserDomain())
{
// options
GMG::CycleOpts copts;
copts.max_levels = mg_opt->max_levels;
copts.patches_per_proc = mg_opt->patches_per_proc;
copts.pre_sweeps = mg_opt->pre_sweeps;
copts.post_sweeps = mg_opt->post_sweeps;
copts.mid_sweeps = mg_opt->mid_sweeps;
copts.coarse_sweeps = mg_opt->coarse_sweeps;
copts.cycle_type = mg_opt->cycle_type;
//GMG cycle builder
GMG::CycleBuilder<2> builder(copts);
//add finest level
//next domain
auto curr_domain = te_domain;
auto next_domain = domain_gen.getCoarserDomain();
//operator
auto patch_operator = op;
//smoother
shared_ptr<GMG::Smoother<2>> smoother = solver;
//restrictor
auto restrictor = make_shared<GMG::LinearRestrictor<2>>(curr_domain,
next_domain,
clawpatch_opt->rhs_fields);
//vector generator
auto vg = make_shared<ValVectorGenerator<2>>(curr_domain,
clawpatch_opt->rhs_fields);
builder.addFinestLevel(patch_operator, smoother, restrictor, vg);
//add intermediate levels
auto prev_phi_n_vec = beta_vec;
auto prev_domain = curr_domain;
curr_domain = next_domain;
while(domain_gen.hasCoarserDomain())
{
next_domain = domain_gen.getCoarserDomain();
//operator
auto ghost_filler = make_shared<BiLinearGhostFiller>(curr_domain);
auto restricted_phi_n_vec = restrict_phi_n_vec(prev_phi_n_vec,
prev_domain, curr_domain);
patch_operator = make_shared<phasefield>(glob,restricted_phi_n_vec,curr_domain, ghost_filler);
prev_phi_n_vec = restricted_phi_n_vec;
//smoother
shared_ptr<GMG::Smoother<2>> smoother;
smoother = make_shared<BiCGStabPatchSolver<2>>(patch_operator,
mg_opt->patch_bcgs_tol,
mg_opt->patch_bcgs_max_it);
//restrictor
auto restrictor = make_shared<GMG::LinearRestrictor<2>>(curr_domain,
next_domain,
clawpatch_opt->rhs_fields);
//interpolator
auto interpolator = make_shared<GMG::DirectInterpolator<2>>(curr_domain,
prev_domain,
clawpatch_opt->rhs_fields);
//vector generator
vg = make_shared<ValVectorGenerator<2>>(curr_domain, clawpatch_opt->rhs_fields);
builder.addIntermediateLevel(patch_operator, smoother, restrictor,
interpolator, vg);
prev_domain = curr_domain;
curr_domain = next_domain;
}
//add coarsest level
//operator
auto ghost_filler = make_shared<BiLinearGhostFiller>(curr_domain);
auto restricted_phi_n_vec = restrict_phi_n_vec(prev_phi_n_vec, prev_domain, curr_domain);
patch_operator = make_shared<phasefield>(glob,restricted_phi_n_vec, curr_domain, ghost_filler);
//smoother
smoother = make_shared<BiCGStabPatchSolver<2>>(patch_operator,
mg_opt->patch_bcgs_tol,
mg_opt->patch_bcgs_max_it);
//interpolator
auto interpolator = make_shared<GMG::DirectInterpolator<2>>(curr_domain, prev_domain, clawpatch_opt->rhs_fields);
//vector generator
vg = make_shared<ValVectorGenerator<2>>(curr_domain, clawpatch_opt->rhs_fields);
builder.addCoarsestLevel(patch_operator, smoother, interpolator, vg);
M = builder.getCycle();
}
// solve
auto vg = make_shared<ValVectorGenerator<2>>(te_domain, clawpatch_opt->rhs_fields);
#if 1
// Set starting conditions
shared_ptr<Vector<2>> u = make_shared<fc2d_thunderegg_vector>(glob,SOLN);
#else
shared_ptr<Vector<2>> u = vg->getNewVector();
#endif
int its = BiCGStab<2>::solve(vg, A, u, f, M, mg_opt->max_it, mg_opt->tol);
fclaw_global_productionf("Iterations: %i\n", its);
/* Solution is copied to right hand side */
f->copy(u);
#if 0
fclaw_global_productionf("f-2norm: %24.16f\n", f->twoNorm());
fclaw_global_productionf("f-infnorm: %24.16f\n", f->infNorm());
fclaw_global_productionf("u-2norm: %24.16f\n", u->twoNorm());
fclaw_global_productionf("u-infnorm: %24.16f\n\n", u->infNorm());
// copy solution into rhs
fclaw_global_productionf("Checking if copy function works:\n");
fclaw_global_productionf("fcopy-2norm: %24.16f\n", f->twoNorm());
fclaw_global_productionf("fcopy-infnorm: %24.16f\n\n", f->infNorm());
#endif
}
<commit_msg>(multigrid) updated for new thunderegg interface<commit_after>/*
Copyright (c) 2019-2020 Carsten Burstedde, Donna Calhoun, Scott Aiton, Grady Wright
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.
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.
*/
#include "phasefield_operator.h"
#include "phasefield_patch_operator.h"
#include "phasefield_options.h"
#include "fc2d_thunderegg.h"
#include "fc2d_thunderegg_vector.hpp"
#include <fclaw2d_elliptic_solver.h>
#include <fclaw2d_clawpatch.h>
#include <fclaw2d_clawpatch_options.h>
#include <fclaw2d_clawpatch_output_ascii.h>
#include <fclaw2d_clawpatch_output_vtk.h>
#include <fclaw2d_global.h>
#include <fclaw2d_map.h>
#include <fclaw2d_map_brick.h>
#include <fclaw2d_options.h>
#include <fclaw2d_patch.h>
#include <fclaw2d_vtable.h>
#include <p4est_bits.h>
#include <p4est_wrap.h>
#include <ThunderEgg/BiCGStab.h>
#include <ThunderEgg/BiCGStabPatchSolver.h>
#include <ThunderEgg/VarPoisson/StarPatchOperator.h>
#include <ThunderEgg/Poisson/FFTWPatchSolver.h>
#include <ThunderEgg/GMG/LinearRestrictor.h>
#include <ThunderEgg/GMG/DirectInterpolator.h>
#include <ThunderEgg/P4estDomGen.h>
#include <ThunderEgg/GMG/CycleBuilder.h>
#include <ThunderEgg/BiLinearGhostFiller.h>
#include <ThunderEgg/ValVectorGenerator.h>
#include <stdlib.h>
using namespace std;
using namespace ThunderEgg;
using namespace ThunderEgg::VarPoisson;
void phasefield_set_lambda(double lambda)
{
phasefield::setLambda(lambda);
}
double phasefield_get_lambda()
{
return phasefield::getLambda();
}
shared_ptr<Vector<2>> restrict_phi_n_vec(shared_ptr<Vector<2>> prev_beta_vec,
shared_ptr<Domain<2>> prev_domain,
shared_ptr<Domain<2>> curr_domain)
{
GMG::LinearRestrictor<2> restrictor(prev_domain,curr_domain, prev_beta_vec->getNumComponents(), true);
auto new_beta_vec = ValVector<2>::GetNewVector(curr_domain, prev_beta_vec->getNumComponents());
restrictor.restrict(prev_beta_vec, new_beta_vec);
return new_beta_vec;
}
void phasefield_solve(fclaw2d_global_t *glob)
{
// get needed options
const fclaw_options_t *fclaw_opt = fclaw2d_get_options(glob);
const fc2d_thunderegg_options_t *mg_opt = fc2d_thunderegg_get_options(glob);
const fclaw2d_clawpatch_options_t *clawpatch_opt = fclaw2d_clawpatch_get_options(glob);
#if 0
fc2d_thunderegg_vtable_t *mg_vt = fc2d_thunderegg_vt();
#endif
// create thunderegg vector for eqn 0
shared_ptr<Vector<2>> f = make_shared<fc2d_thunderegg_vector>(glob,RHS);
// get patch size
array<int, 2> ns = {clawpatch_opt->mx, clawpatch_opt->my};
// get p4est structure
fclaw2d_domain_t *domain = glob->domain;
p4est_wrap_t *wrap = (p4est_wrap_t *)domain->pp;
// create map function
P4estDomGen::BlockMapFunc bmf = [&](int block_no, double unit_x,
double unit_y, double &x, double &y)
{
double x1,y1,z1;
FCLAW2D_MAP_BRICK2C(&glob->cont,&block_no,&unit_x, &unit_y, &x1, &y1, &z1);
x = fclaw_opt->ax + (fclaw_opt->bx - fclaw_opt->ax) * x1;
y = fclaw_opt->ay + (fclaw_opt->by - fclaw_opt->ay) * y1;
};
// create neumann function
IsNeumannFunc<2> inf = [&](Side<2> s, const array<double, 2> &lower,
const array<double, 2> &upper)
{
return mg_opt->boundary_conditions[s.getIndex()] == 2;
};
// generates levels of patches for GMG; 2 layers of ghost cells
P4estDomGen domain_gen(wrap->p4est, ns, clawpatch_opt->mbc, inf, bmf);
// get finest level
shared_ptr<Domain<2>> te_domain = domain_gen.getFinestDomain();
/* Store phi at time level n */
shared_ptr<Vector<2>> beta_vec = make_shared<fc2d_thunderegg_vector>(glob,STORE_STATE);
// ghost filler
auto ghost_filler = make_shared<BiLinearGhostFiller>(te_domain);
// patch operator
auto op = make_shared<phasefield>(glob,beta_vec,te_domain,ghost_filler);
// set the patch solver
shared_ptr<PatchSolver<2>> solver;
solver = make_shared<BiCGStabPatchSolver<2>>(op,
mg_opt->patch_bcgs_tol,
mg_opt->patch_bcgs_max_it,
true);
// create matrix
shared_ptr<Operator<2>> A = op;
// create gmg preconditioner
shared_ptr<Operator<2>> M;
if (mg_opt->mg_prec && domain_gen.hasCoarserDomain())
{
// options
GMG::CycleOpts copts;
copts.max_levels = mg_opt->max_levels;
copts.patches_per_proc = mg_opt->patches_per_proc;
copts.pre_sweeps = mg_opt->pre_sweeps;
copts.post_sweeps = mg_opt->post_sweeps;
copts.mid_sweeps = mg_opt->mid_sweeps;
copts.coarse_sweeps = mg_opt->coarse_sweeps;
copts.cycle_type = mg_opt->cycle_type;
//GMG cycle builder
GMG::CycleBuilder<2> builder(copts);
//add finest level
//next domain
auto curr_domain = te_domain;
auto next_domain = domain_gen.getCoarserDomain();
//operator
auto patch_operator = op;
//smoother
shared_ptr<GMG::Smoother<2>> smoother = solver;
//restrictor
auto restrictor = make_shared<GMG::LinearRestrictor<2>>(curr_domain,
next_domain,
clawpatch_opt->rhs_fields);
//vector generator
auto vg = make_shared<ValVectorGenerator<2>>(curr_domain,
clawpatch_opt->rhs_fields);
builder.addFinestLevel(patch_operator, smoother, restrictor, vg);
//add intermediate levels
auto prev_phi_n_vec = beta_vec;
auto prev_domain = curr_domain;
curr_domain = next_domain;
while(domain_gen.hasCoarserDomain())
{
next_domain = domain_gen.getCoarserDomain();
//operator
auto ghost_filler = make_shared<BiLinearGhostFiller>(curr_domain);
auto restricted_phi_n_vec = restrict_phi_n_vec(prev_phi_n_vec,
prev_domain, curr_domain);
patch_operator = make_shared<phasefield>(glob,restricted_phi_n_vec,curr_domain, ghost_filler);
prev_phi_n_vec = restricted_phi_n_vec;
//smoother
shared_ptr<GMG::Smoother<2>> smoother;
smoother = make_shared<BiCGStabPatchSolver<2>>(patch_operator,
mg_opt->patch_bcgs_tol,
mg_opt->patch_bcgs_max_it,
true);
//restrictor
auto restrictor = make_shared<GMG::LinearRestrictor<2>>(curr_domain,
next_domain,
clawpatch_opt->rhs_fields);
//interpolator
auto interpolator = make_shared<GMG::DirectInterpolator<2>>(curr_domain,
prev_domain,
clawpatch_opt->rhs_fields);
//vector generator
vg = make_shared<ValVectorGenerator<2>>(curr_domain, clawpatch_opt->rhs_fields);
builder.addIntermediateLevel(patch_operator, smoother, restrictor,
interpolator, vg);
prev_domain = curr_domain;
curr_domain = next_domain;
}
//add coarsest level
//operator
auto ghost_filler = make_shared<BiLinearGhostFiller>(curr_domain);
auto restricted_phi_n_vec = restrict_phi_n_vec(prev_phi_n_vec, prev_domain, curr_domain);
patch_operator = make_shared<phasefield>(glob,restricted_phi_n_vec, curr_domain, ghost_filler);
//smoother
smoother = make_shared<BiCGStabPatchSolver<2>>(patch_operator,
mg_opt->patch_bcgs_tol,
mg_opt->patch_bcgs_max_it,
true);
//interpolator
auto interpolator = make_shared<GMG::DirectInterpolator<2>>(curr_domain, prev_domain, clawpatch_opt->rhs_fields);
//vector generator
vg = make_shared<ValVectorGenerator<2>>(curr_domain, clawpatch_opt->rhs_fields);
builder.addCoarsestLevel(patch_operator, smoother, interpolator, vg);
M = builder.getCycle();
}
// solve
auto vg = make_shared<ValVectorGenerator<2>>(te_domain, clawpatch_opt->rhs_fields);
#if 1
// Set starting conditions
shared_ptr<Vector<2>> u = make_shared<fc2d_thunderegg_vector>(glob,SOLN);
#else
shared_ptr<Vector<2>> u = vg->getNewVector();
#endif
int its = BiCGStab<2>::solve(vg, A, u, f, M, mg_opt->max_it, mg_opt->tol,
nullptr, //no timer
true); //output iteration information to cout
fclaw_global_productionf("Iterations: %i\n", its);
/* Solution is copied to right hand side */
f->copy(u);
#if 0
fclaw_global_productionf("f-2norm: %24.16f\n", f->twoNorm());
fclaw_global_productionf("f-infnorm: %24.16f\n", f->infNorm());
fclaw_global_productionf("u-2norm: %24.16f\n", u->twoNorm());
fclaw_global_productionf("u-infnorm: %24.16f\n\n", u->infNorm());
// copy solution into rhs
fclaw_global_productionf("Checking if copy function works:\n");
fclaw_global_productionf("fcopy-2norm: %24.16f\n", f->twoNorm());
fclaw_global_productionf("fcopy-infnorm: %24.16f\n\n", f->infNorm());
#endif
}
<|endoftext|> |
<commit_before>/*******************************************************************************
* ALMA - Atacama Large Millimiter Array
* (c) European Southern Observatory, 2002
* Copyright by ESO (in the framework of the ALMA collaboration),
* All rights reserved
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
* "@(#) $Id: acscomponentTestServer.cpp,v 1.19 2008/07/25 09:40:47 cparedes Exp $"
*
* who when what
* -------- -------- ----------------------------------------------
* rcirami 2002-09-24 created
*/
static char *rcsId="@(#) $Id: acscomponentTestServer.cpp,v 1.19 2008/07/25 09:40:47 cparedes Exp $";
static void *use_rcsId = ((void)&use_rcsId,(void *) &rcsId);
#include <vltPort.h>
#include <acsutil.h>
#include "acscomponentTestImpl.h"
#include "acscomponentTestC.h"
#include <maciC.h>
#define ACS_TEST_INIT_CORBA \
{ \
try \
{ \
ACS_DEBUG("ACS_TEST_INIT_CORBA", "Initialising ORB ... "); \
orb = CORBA::ORB_init (argc, argv, 0); \
ACS_DEBUG ("ACS_TEST_INIT_CORBA", "ORB initialised !"); \
} \
catch( CORBA::Exception &ex ) \
{ \
ACE_PRINT_EXCEPTION (ex, "Failed to initalise ORB"); \
return -1; \
} \
}
// We need an implementation of the ContainerServices here because
// 1. the component fails if the pointer to the ContainerServices it receives
// in the constructor is NULL
// 2. the smart pointer used to store the ContainerServices deletes all
// the not-NULL instances of the Container Services
// This clla implements all the methods of the interface but does nothing
class TestContainerServices : public maci::ContainerServices {
public:
TestContainerServices(ACE_CString& compName, PortableServer::POA_ptr poa):
maci::ContainerServices(compName,poa) {}
virtual ~TestContainerServices() {}
CORBA::Object* getCORBAComponent(const char* name)
throw (maciErrType::CannotGetComponentExImpl)
{
return (CORBA::Object*)NULL;
}
CORBA::Object* getCORBADynamicComponent(maci::ComponentSpec compSpec, bool markAsDefault)
throw (maciErrType::IncompleteComponentSpecExImpl,
maciErrType::InvalidComponentSpecExImpl,
maciErrType::ComponentSpecIncompatibleWithActiveComponentExImpl,
maciErrType::CannotGetComponentExImpl)
{
return (CORBA::Object*)NULL;
}
CORBA::Object* getCORBADefaultComponent(const char* idlType)
throw (maciErrType::NoDefaultComponentExImpl,
maciErrType::CannotGetComponentExImpl)
{
return (CORBA::Object*)NULL;
}
CORBA::Object* getCORBACollocatedComponent(maci::ComponentSpec, bool, const char*)
throw(maciErrType::IncompleteComponentSpecExImpl,
maciErrType::InvalidComponentSpecExImpl,
maciErrType::ComponentSpecIncompatibleWithActiveComponentExImpl,
maciErrType::CannotGetComponentExImpl)
{
return (CORBA::Object*)NULL;
}
CORBA::Object* getCORBAComponentNonSticky(const char*)
throw (maciErrType::CannotGetComponentExImpl)
{
return (CORBA::Object*)NULL;
}
public:
maci::ComponentInfo getComponentDescriptor(const char* componentName)
throw (acsErrTypeContainerServices::GettingCompInfoExImpl)
{
maci::ComponentInfo temp;
return temp;
}
ACE_CString_Vector findComponents(const char *nameWilcard, const char *typeWildcard)
{
return ACE_CString_Vector();
}
void releaseComponent(const char *name)
throw (maciErrType::CannotReleaseComponentExImpl)
{}
void releaseAllComponents(){}
CDB::DAL_ptr getCDB()
throw (acsErrTypeContainerServices::CanNotGetCDBExImpl)
{
return NULL;
}
PortableServer::POA_var getOffShootPOA()
{
return NULL;
}
ACS::OffShoot_ptr activateOffShoot(PortableServer::Servant cbServant)
{
return NULL;
}
void deactivateOffShoot(PortableServer::Servant cbServant)
throw (
acsErrTypeContainerServices::OffShootDeactivationExImpl,
acsErrTypeContainerServices::OffShootPOAExImpl){}
PortableServer::POA_var createOffShootPOA()
{
return NULL;
}
maci::ComponentStateManager* getComponentStateManager()
{
return NULL;
}
};
CORBA::ORB_var orb;
void TerminationSignalHandler(int)
{
try
{
// false - avoid deadlock; true would try to wait for all requests
// to complete before returning, but because we are calling it from within
// a request, we would be blocking it from
orb->shutdown(false);
}
catch( CORBA::Exception &ex )
{
ACE_PRINT_EXCEPTION( ex, "TerminationSignalHandler");
}
}
#ifdef MAKE_VXWORKS
# include "rebootLib.h"
# include "acsutilArgUnpack.h"
int acscomponentTestServer (char *szCmdLn)
{
int argc;
char *argv[100];
argc = argUnpack(szCmdLn, argv);
argv[0] = "acscomponentTestServer";
#else
int main(int argc, char* argv[])
{
#endif // defined( MAKE_VXWORKS )
// creating ORB
ACS_TEST_INIT_CORBA;
try
{
ACE_OS::signal(SIGINT, TerminationSignalHandler); // Ctrl+C
ACE_OS::signal(SIGTERM, TerminationSignalHandler); // termination request
//Get a reference to the RootPOA
CORBA::Object_var obj = orb->resolve_initial_references("RootPOA");
PortableServer::POA_var root_poa = PortableServer::POA::_narrow(obj.in());
PortableServer::POAManager_var poa_manager = root_poa->the_POAManager();
// The component will throw an exception if receives a NULL ContainerServices
// in the constructor.
// We pass a value only to avoid that i throws the exception. On the other
// hand the test doe not use the ContainerServices (remember: ContainerServices
// does not yet exist at this point!!!!)
ACE_CString compName("TEST");
ACSComponentTestClassImpl mytestImpl(compName.c_str(), new TestContainerServices(compName,NULL));
ACSCOMPONENT_TEST::ACSComponentTestClass_var mytest = mytestImpl._this ();;
poa_manager->activate ();
ACS_DEBUG ("acscomponentTestServer","POA Manager -> activate");
ACS_DEBUG ("acscomponentTestServer", "Writing ior to the file: ACSCOMPONENTTEST1");
char* ior = orb->object_to_string (mytest.in());
char fileName[64];
sprintf(fileName, "%s.ior", "ACSCOMPONENTTEST1");
FILE *output_file = ACE_OS::fopen (fileName, "w");
if (output_file == 0) {
ACS_SHORT_LOG((LM_ERROR, "Cannot open output files for writing IOR: ior.ior"));
return -1;
}
int result = ACE_OS::fprintf (output_file, "%s", ior);
if (result < 0) {
ACE_ERROR_RETURN ((LM_ERROR, "ACE_OS::fprintf failed while writing %s to ior.ior", ior), -1);
}
ACE_OS::fclose (output_file);
ACS_DEBUG ("acscomponentTestServer", "Waiting for requests ...");
orb->run ();
}
catch( CORBA::Exception &_ex )
{
ACE_PRINT_EXCEPTION (_ex, "EXCEPTION CAUGHT");
return -1;
}
// orb->shutdown(true); //wait until all requests have completed
return 0;
}
<commit_msg>Added dummy implementation of TestContainerServices::getAlarmSource(). It always returns NULL.<commit_after>/*******************************************************************************
* ALMA - Atacama Large Millimiter Array
* (c) European Southern Observatory, 2002
* Copyright by ESO (in the framework of the ALMA collaboration),
* All rights reserved
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
* "@(#) $Id: acscomponentTestServer.cpp,v 1.20 2011/10/16 08:53:49 hsommer Exp $"
*
* who when what
* -------- -------- ----------------------------------------------
* rcirami 2002-09-24 created
*/
static char *rcsId="@(#) $Id: acscomponentTestServer.cpp,v 1.20 2011/10/16 08:53:49 hsommer Exp $";
static void *use_rcsId = ((void)&use_rcsId,(void *) &rcsId);
#include <vltPort.h>
#include <acsutil.h>
#include "acscomponentTestImpl.h"
#include "acscomponentTestC.h"
#include <maciC.h>
#define ACS_TEST_INIT_CORBA \
{ \
try \
{ \
ACS_DEBUG("ACS_TEST_INIT_CORBA", "Initialising ORB ... "); \
orb = CORBA::ORB_init (argc, argv, 0); \
ACS_DEBUG ("ACS_TEST_INIT_CORBA", "ORB initialised !"); \
} \
catch( CORBA::Exception &ex ) \
{ \
ACE_PRINT_EXCEPTION (ex, "Failed to initalise ORB"); \
return -1; \
} \
}
// We need an implementation of the ContainerServices here because
// 1. the component fails if the pointer to the ContainerServices it receives
// in the constructor is NULL
// 2. the smart pointer used to store the ContainerServices deletes all
// the not-NULL instances of the Container Services
// This clla implements all the methods of the interface but does nothing
class TestContainerServices : public maci::ContainerServices {
public:
TestContainerServices(ACE_CString& compName, PortableServer::POA_ptr poa):
maci::ContainerServices(compName,poa) {}
virtual ~TestContainerServices() {}
CORBA::Object* getCORBAComponent(const char* name)
throw (maciErrType::CannotGetComponentExImpl)
{
return (CORBA::Object*)NULL;
}
CORBA::Object* getCORBADynamicComponent(maci::ComponentSpec compSpec, bool markAsDefault)
throw (maciErrType::IncompleteComponentSpecExImpl,
maciErrType::InvalidComponentSpecExImpl,
maciErrType::ComponentSpecIncompatibleWithActiveComponentExImpl,
maciErrType::CannotGetComponentExImpl)
{
return (CORBA::Object*)NULL;
}
CORBA::Object* getCORBADefaultComponent(const char* idlType)
throw (maciErrType::NoDefaultComponentExImpl,
maciErrType::CannotGetComponentExImpl)
{
return (CORBA::Object*)NULL;
}
CORBA::Object* getCORBACollocatedComponent(maci::ComponentSpec, bool, const char*)
throw(maciErrType::IncompleteComponentSpecExImpl,
maciErrType::InvalidComponentSpecExImpl,
maciErrType::ComponentSpecIncompatibleWithActiveComponentExImpl,
maciErrType::CannotGetComponentExImpl)
{
return (CORBA::Object*)NULL;
}
CORBA::Object* getCORBAComponentNonSticky(const char*)
throw (maciErrType::CannotGetComponentExImpl)
{
return (CORBA::Object*)NULL;
}
public:
maci::ComponentInfo getComponentDescriptor(const char* componentName)
throw (acsErrTypeContainerServices::GettingCompInfoExImpl)
{
maci::ComponentInfo temp;
return temp;
}
ACE_CString_Vector findComponents(const char *nameWilcard, const char *typeWildcard)
{
return ACE_CString_Vector();
}
void releaseComponent(const char *name)
throw (maciErrType::CannotReleaseComponentExImpl)
{}
void releaseAllComponents(){}
CDB::DAL_ptr getCDB()
throw (acsErrTypeContainerServices::CanNotGetCDBExImpl)
{
return NULL;
}
PortableServer::POA_var getOffShootPOA()
{
return NULL;
}
ACS::OffShoot_ptr activateOffShoot(PortableServer::Servant cbServant)
{
return NULL;
}
void deactivateOffShoot(PortableServer::Servant cbServant)
throw (
acsErrTypeContainerServices::OffShootDeactivationExImpl,
acsErrTypeContainerServices::OffShootPOAExImpl){}
PortableServer::POA_var createOffShootPOA()
{
return NULL;
}
maci::ComponentStateManager* getComponentStateManager()
{
return NULL;
}
acsalarm::AlarmSource* getAlarmSource()
{
return NULL;
}
};
CORBA::ORB_var orb;
void TerminationSignalHandler(int)
{
try
{
// false - avoid deadlock; true would try to wait for all requests
// to complete before returning, but because we are calling it from within
// a request, we would be blocking it from
orb->shutdown(false);
}
catch( CORBA::Exception &ex )
{
ACE_PRINT_EXCEPTION( ex, "TerminationSignalHandler");
}
}
#ifdef MAKE_VXWORKS
# include "rebootLib.h"
# include "acsutilArgUnpack.h"
int acscomponentTestServer (char *szCmdLn)
{
int argc;
char *argv[100];
argc = argUnpack(szCmdLn, argv);
argv[0] = "acscomponentTestServer";
#else
int main(int argc, char* argv[])
{
#endif // defined( MAKE_VXWORKS )
// creating ORB
ACS_TEST_INIT_CORBA;
try
{
ACE_OS::signal(SIGINT, TerminationSignalHandler); // Ctrl+C
ACE_OS::signal(SIGTERM, TerminationSignalHandler); // termination request
//Get a reference to the RootPOA
CORBA::Object_var obj = orb->resolve_initial_references("RootPOA");
PortableServer::POA_var root_poa = PortableServer::POA::_narrow(obj.in());
PortableServer::POAManager_var poa_manager = root_poa->the_POAManager();
// The component will throw an exception if receives a NULL ContainerServices
// in the constructor.
// We pass a value only to avoid that i throws the exception. On the other
// hand the test doe not use the ContainerServices (remember: ContainerServices
// does not yet exist at this point!!!!)
ACE_CString compName("TEST");
ACSComponentTestClassImpl mytestImpl(compName.c_str(), new TestContainerServices(compName,NULL));
ACSCOMPONENT_TEST::ACSComponentTestClass_var mytest = mytestImpl._this ();;
poa_manager->activate ();
ACS_DEBUG ("acscomponentTestServer","POA Manager -> activate");
ACS_DEBUG ("acscomponentTestServer", "Writing ior to the file: ACSCOMPONENTTEST1");
char* ior = orb->object_to_string (mytest.in());
char fileName[64];
sprintf(fileName, "%s.ior", "ACSCOMPONENTTEST1");
FILE *output_file = ACE_OS::fopen (fileName, "w");
if (output_file == 0) {
ACS_SHORT_LOG((LM_ERROR, "Cannot open output files for writing IOR: ior.ior"));
return -1;
}
int result = ACE_OS::fprintf (output_file, "%s", ior);
if (result < 0) {
ACE_ERROR_RETURN ((LM_ERROR, "ACE_OS::fprintf failed while writing %s to ior.ior", ior), -1);
}
ACE_OS::fclose (output_file);
ACS_DEBUG ("acscomponentTestServer", "Waiting for requests ...");
orb->run ();
}
catch( CORBA::Exception &_ex )
{
ACE_PRINT_EXCEPTION (_ex, "EXCEPTION CAUGHT");
return -1;
}
// orb->shutdown(true); //wait until all requests have completed
return 0;
}
<|endoftext|> |
<commit_before>/*
* Copyright (c) 2003 The Regents of The University of Michigan
* 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 holders 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.
*/
/* @file
* Device module for modelling a fixed bandwidth full duplex ethernet link
*/
#include <cmath>
#include <deque>
#include <string>
#include <vector>
#include "base/trace.hh"
#include "dev/etherdump.hh"
#include "dev/etherint.hh"
#include "dev/etherlink.hh"
#include "dev/etherpkt.hh"
#include "sim/builder.hh"
#include "sim/universe.hh"
#include "sim/system.hh"
using namespace std;
EtherLink::EtherLink(const std::string &name, EtherInt *i1, EtherInt *i2,
Tick speed, EtherDump *dump)
: SimObject(name)
{
double rate = ((double)ticksPerSecond * 8.0) / (double)speed;
link1 = new Link(name + ".link1", rate, dump);
link2 = new Link(name + ".link2", rate, dump);
int1 = new Interface(name + ".int1", link1, link2);
int2 = new Interface(name + ".int2", link2, link1);
int1->setPeer(i1);
i1->setPeer(int1);
int2->setPeer(i2);
i2->setPeer(int2);
}
EtherLink::~EtherLink()
{
delete link1;
delete link2;
delete int1;
delete int2;
}
EtherLink::Interface::Interface(const std::string &name, Link *tx, Link *rx)
: EtherInt(name), txlink(tx)
{
tx->setTxInt(this);
rx->setRxInt(this);
}
EtherLink::Link::Link(const std::string &name, double rate, EtherDump *d)
: objName(name), txint(NULL), rxint(NULL), ticks_per_byte(rate),
dump(d), event(&mainEventQueue, this)
{}
void
EtherLink::serialize(ostream &os)
{
link1->serialize(os);
link2->serialize(os);
}
void
EtherLink::unserialize(Checkpoint *cp, const string §ion)
{
link1->unserialize(cp, section);
link2->unserialize(cp, section);
}
void
EtherLink::Link::txDone()
{
if (dump)
dump->dump(packet);
DPRINTF(Ethernet, "EtherLink packet received: len=%d\n", packet->length);
DDUMP(EthernetData, packet->data, packet->length);
rxint->sendPacket(packet);
packet = 0;
assert(!busy());
txint->sendDone();
}
bool
EtherLink::Link::transmit(PacketPtr &pkt)
{
if (busy()) {
DPRINTF(Ethernet, "EtherLink packet not sent, link busy\n");
return false;
}
DPRINTF(Ethernet, "EtherLink packet sent: len=%d\n", pkt->length);
DDUMP(EthernetData, pkt->data, pkt->length);
packet = pkt;
int delay = (int)ceil(((double)pkt->length * ticks_per_byte) + 1.0);
DPRINTF(Ethernet, "EtherLink scheduling packet: delay=%d, (rate=%f)\n",
delay, ticks_per_byte);
event.schedule(curTick + delay);
return true;
}
void
EtherLink::Link::serialize(ostream &os)
{
bool packetExists = false;
if (packet) packetExists = true;
SERIALIZE_SCALAR(packetExists);
if (packetExists) {
nameOut(os, csprintf("%s.linkPacket", name()));
packet->serialize(os);
}
bool event_scheduled = event.scheduled();
SERIALIZE_SCALAR(event_scheduled);
if (event_scheduled) {
SERIALIZE_SCALAR(event.when());
}
}
void
EtherLink::Link::unserialize(Checkpoint *cp, const string §ion)
{
bool event_scheduled, packetExists;
Tick eventTime;
UNSERIALIZE_SCALAR(packetExists);
if (packetExists) {
packet = new EtherPacket;
packet->unserialize(cp, csprintf("%s.linkPacket", section));
}
UNSERIALIZE_SCALAR(event_scheduled);
if (event_scheduled) {
UNSERIALIZE_SCALAR(eventTime);
event.schedule(eventTime);
}
}
BEGIN_DECLARE_SIM_OBJECT_PARAMS(EtherLink)
SimObjectParam<EtherInt *> interface1;
SimObjectParam<EtherInt *> interface2;
Param<Tick> link_speed;
SimObjectParam<EtherDump *> packet_dump;
END_DECLARE_SIM_OBJECT_PARAMS(EtherLink)
BEGIN_INIT_SIM_OBJECT_PARAMS(EtherLink)
INIT_PARAM(interface1, "interface 1"),
INIT_PARAM(interface2, "interface 2"),
INIT_PARAM_DFLT(link_speed, "link speed in bits per second", 100000000),
INIT_PARAM_DFLT(packet_dump, "object to dump network packets to", NULL)
END_INIT_SIM_OBJECT_PARAMS(EtherLink)
CREATE_SIM_OBJECT(EtherLink)
{
return new EtherLink(getInstanceName(), interface1, interface2, link_speed,
packet_dump);
}
REGISTER_SIM_OBJECT("EtherLink", EtherLink)
<commit_msg>configurable latency for programmed IO fix serialization<commit_after>/*
* Copyright (c) 2003 The Regents of The University of Michigan
* 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 holders 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.
*/
/* @file
* Device module for modelling a fixed bandwidth full duplex ethernet link
*/
#include <cmath>
#include <deque>
#include <string>
#include <vector>
#include "base/trace.hh"
#include "dev/etherdump.hh"
#include "dev/etherint.hh"
#include "dev/etherlink.hh"
#include "dev/etherpkt.hh"
#include "sim/builder.hh"
#include "sim/universe.hh"
#include "sim/system.hh"
using namespace std;
EtherLink::EtherLink(const std::string &name, EtherInt *i1, EtherInt *i2,
Tick speed, EtherDump *dump)
: SimObject(name)
{
double rate = ((double)ticksPerSecond * 8.0) / (double)speed;
link1 = new Link(name + ".link1", rate, dump);
link2 = new Link(name + ".link2", rate, dump);
int1 = new Interface(name + ".int1", link1, link2);
int2 = new Interface(name + ".int2", link2, link1);
int1->setPeer(i1);
i1->setPeer(int1);
int2->setPeer(i2);
i2->setPeer(int2);
}
EtherLink::~EtherLink()
{
delete link1;
delete link2;
delete int1;
delete int2;
}
EtherLink::Interface::Interface(const std::string &name, Link *tx, Link *rx)
: EtherInt(name), txlink(tx)
{
tx->setTxInt(this);
rx->setRxInt(this);
}
EtherLink::Link::Link(const std::string &name, double rate, EtherDump *d)
: objName(name), txint(NULL), rxint(NULL), ticks_per_byte(rate),
dump(d), event(&mainEventQueue, this)
{}
void
EtherLink::serialize(ostream &os)
{
nameOut(os, name() + ".link1");
link1->serialize(os);
nameOut(os, name() + ".link2");
link2->serialize(os);
}
void
EtherLink::unserialize(Checkpoint *cp, const string §ion)
{
link1->unserialize(cp, section + ".link1");
link2->unserialize(cp, section + ".link2");
}
void
EtherLink::Link::txDone()
{
if (dump)
dump->dump(packet);
DPRINTF(Ethernet, "EtherLink packet received: len=%d\n", packet->length);
DDUMP(EthernetData, packet->data, packet->length);
rxint->sendPacket(packet);
packet = 0;
assert(!busy());
txint->sendDone();
}
bool
EtherLink::Link::transmit(PacketPtr &pkt)
{
if (busy()) {
DPRINTF(Ethernet, "EtherLink packet not sent, link busy\n");
return false;
}
DPRINTF(Ethernet, "EtherLink packet sent: len=%d\n", pkt->length);
DDUMP(EthernetData, pkt->data, pkt->length);
packet = pkt;
int delay = (int)ceil(((double)pkt->length * ticks_per_byte) + 1.0);
DPRINTF(Ethernet, "EtherLink scheduling packet: delay=%d, (rate=%f)\n",
delay, ticks_per_byte);
event.schedule(curTick + delay);
return true;
}
void
EtherLink::Link::serialize(ostream &os)
{
bool packet_exists = packet;
SERIALIZE_SCALAR(packet_exists);
bool event_scheduled = event.scheduled();
SERIALIZE_SCALAR(event_scheduled);
if (event_scheduled) {
Tick event_time = event.when();
SERIALIZE_SCALAR(event_time);
}
if (packet_exists) {
nameOut(os, csprintf("%s.packet", name()));
packet->serialize(os);
}
}
void
EtherLink::Link::unserialize(Checkpoint *cp, const string §ion)
{
bool packet_exists;
UNSERIALIZE_SCALAR(packet_exists);
if (packet_exists) {
packet = new EtherPacket;
packet->unserialize(cp, csprintf("%s.packet", section));
}
bool event_scheduled;
UNSERIALIZE_SCALAR(event_scheduled);
if (event_scheduled) {
Tick event_time;
UNSERIALIZE_SCALAR(event_time);
event.schedule(event_time);
}
}
BEGIN_DECLARE_SIM_OBJECT_PARAMS(EtherLink)
SimObjectParam<EtherInt *> interface1;
SimObjectParam<EtherInt *> interface2;
Param<Tick> link_speed;
SimObjectParam<EtherDump *> packet_dump;
END_DECLARE_SIM_OBJECT_PARAMS(EtherLink)
BEGIN_INIT_SIM_OBJECT_PARAMS(EtherLink)
INIT_PARAM(interface1, "interface 1"),
INIT_PARAM(interface2, "interface 2"),
INIT_PARAM_DFLT(link_speed, "link speed in bits per second", 100000000),
INIT_PARAM_DFLT(packet_dump, "object to dump network packets to", NULL)
END_INIT_SIM_OBJECT_PARAMS(EtherLink)
CREATE_SIM_OBJECT(EtherLink)
{
return new EtherLink(getInstanceName(), interface1, interface2, link_speed,
packet_dump);
}
REGISTER_SIM_OBJECT("EtherLink", EtherLink)
<|endoftext|> |
<commit_before><commit_msg>Replace Equals expression with IsTrue from snowhouse library.<commit_after><|endoftext|> |
<commit_before><commit_msg>more voice sensor work<commit_after><|endoftext|> |
<commit_before>/*
* This file is open source software, licensed to you under the terms
* of the Apache License, Version 2.0 (the "License"). See the NOTICE file
* distributed with this work for additional information regarding copyright
* ownership. 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.
*/
/*
* Copyright (C) 2015 Cloudius Systems, Ltd.
*/
//
// Buffered input and output streams
//
// Two abstract classes (data_source and data_sink) provide means
// to acquire bulk data from, or push bulk data to, some provider.
// These could be tied to a TCP connection, a disk file, or a memory
// buffer.
//
// Two concrete classes (input_stream and output_stream) buffer data
// from data_source and data_sink and provide easier means to process
// it.
//
#pragma once
#include "future.hh"
#include "temporary_buffer.hh"
#include "scattered_message.hh"
namespace net { class packet; }
class data_source_impl {
public:
virtual ~data_source_impl() {}
virtual future<temporary_buffer<char>> get() = 0;
};
class data_source {
std::unique_ptr<data_source_impl> _dsi;
protected:
data_source_impl* impl() const { return _dsi.get(); }
public:
data_source() = default;
explicit data_source(std::unique_ptr<data_source_impl> dsi) : _dsi(std::move(dsi)) {}
data_source(data_source&& x) = default;
data_source& operator=(data_source&& x) = default;
future<temporary_buffer<char>> get() { return _dsi->get(); }
};
class data_sink_impl {
public:
virtual ~data_sink_impl() {}
virtual temporary_buffer<char> allocate_buffer(size_t size) {
return temporary_buffer<char>(size);
}
virtual future<> put(net::packet data) = 0;
virtual future<> put(std::vector<temporary_buffer<char>> data) {
net::packet p;
p.reserve(data.size());
for (auto& buf : data) {
p = net::packet(std::move(p), net::fragment{buf.get_write(), buf.size()}, buf.release());
}
return put(std::move(p));
}
virtual future<> put(temporary_buffer<char> buf) {
return put(net::packet(net::fragment{buf.get_write(), buf.size()}, buf.release()));
}
virtual future<> flush() {
return make_ready_future<>();
}
virtual future<> close() = 0;
};
class data_sink {
std::unique_ptr<data_sink_impl> _dsi;
public:
data_sink() = default;
explicit data_sink(std::unique_ptr<data_sink_impl> dsi) : _dsi(std::move(dsi)) {}
data_sink(data_sink&& x) = default;
data_sink& operator=(data_sink&& x) = default;
temporary_buffer<char> allocate_buffer(size_t size) {
return _dsi->allocate_buffer(size);
}
future<> put(std::vector<temporary_buffer<char>> data) {
return _dsi->put(std::move(data));
}
future<> put(temporary_buffer<char> data) {
return _dsi->put(std::move(data));
}
future<> put(net::packet p) {
return _dsi->put(std::move(p));
}
future<> flush() {
return _dsi->flush();
}
future<> close() { return _dsi->close(); }
};
template <typename CharType>
class input_stream final {
static_assert(sizeof(CharType) == 1, "must buffer stream of bytes");
data_source _fd;
temporary_buffer<CharType> _buf;
bool _eof = false;
private:
using tmp_buf = temporary_buffer<CharType>;
size_t available() const { return _buf.size(); }
protected:
void reset() { _buf = {}; }
data_source* fd() { return &_fd; }
public:
// Consumer concept, for consume() method:
using unconsumed_remainder = std::experimental::optional<tmp_buf>;
struct ConsumerConcept {
// The consumer should operate on the data given to it, and
// return a future "unconsumed remainder", which can be undefined
// if the consumer consumed all the input given to it and is ready
// for more, or defined when the consumer is done (and in that case
// the value is the unconsumed part of the last data buffer - this
// can also happen to be empty).
future<unconsumed_remainder> operator()(tmp_buf data);
};
using char_type = CharType;
input_stream() = default;
explicit input_stream(data_source fd) : _fd(std::move(fd)), _buf(0) {}
input_stream(input_stream&&) = default;
input_stream& operator=(input_stream&&) = default;
future<temporary_buffer<CharType>> read_exactly(size_t n);
template <typename Consumer>
future<> consume(Consumer& c);
bool eof() { return _eof; }
private:
future<temporary_buffer<CharType>> read_exactly_part(size_t n, tmp_buf buf, size_t completed);
};
// Facilitates data buffering before it's handed over to data_sink.
//
// When trim_to_size is true it's guaranteed that data sink will not receive
// chunks larger than the configured size, which could be the case when a
// single write call is made with data larger than the configured size.
//
// The data sink will not receive empty chunks.
//
template <typename CharType>
class output_stream final {
static_assert(sizeof(CharType) == 1, "must buffer stream of bytes");
data_sink _fd;
temporary_buffer<CharType> _buf;
size_t _size = 0;
size_t _begin = 0;
size_t _end = 0;
bool _trim_to_size = false;
private:
size_t available() const { return _end - _begin; }
size_t possibly_available() const { return _size - _begin; }
future<> split_and_put(temporary_buffer<CharType> buf);
public:
using char_type = CharType;
output_stream() = default;
output_stream(data_sink fd, size_t size, bool trim_to_size = false)
: _fd(std::move(fd)), _size(size), _trim_to_size(trim_to_size) {}
output_stream(output_stream&&) = default;
output_stream& operator=(output_stream&&) = default;
future<> write(const char_type* buf, size_t n);
future<> write(const char_type* buf);
template <typename StringChar, typename SizeType, SizeType MaxSize>
future<> write(const basic_sstring<StringChar, SizeType, MaxSize>& s);
future<> write(const std::basic_string<char_type>& s);
future<> write(net::packet p);
future<> write(scattered_message<char_type> msg);
future<> flush();
future<> close() { return flush().then([this] { return _fd.close(); }); }
private:
};
#include "iostream-impl.hh"
<commit_msg>iostream: support background operations for data_source<commit_after>/*
* This file is open source software, licensed to you under the terms
* of the Apache License, Version 2.0 (the "License"). See the NOTICE file
* distributed with this work for additional information regarding copyright
* ownership. 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.
*/
/*
* Copyright (C) 2015 Cloudius Systems, Ltd.
*/
//
// Buffered input and output streams
//
// Two abstract classes (data_source and data_sink) provide means
// to acquire bulk data from, or push bulk data to, some provider.
// These could be tied to a TCP connection, a disk file, or a memory
// buffer.
//
// Two concrete classes (input_stream and output_stream) buffer data
// from data_source and data_sink and provide easier means to process
// it.
//
#pragma once
#include "future.hh"
#include "temporary_buffer.hh"
#include "scattered_message.hh"
namespace net { class packet; }
class data_source_impl {
public:
virtual ~data_source_impl() {}
virtual future<temporary_buffer<char>> get() = 0;
virtual future<> close() { return make_ready_future<>(); }
};
class data_source {
std::unique_ptr<data_source_impl> _dsi;
protected:
data_source_impl* impl() const { return _dsi.get(); }
public:
data_source() = default;
explicit data_source(std::unique_ptr<data_source_impl> dsi) : _dsi(std::move(dsi)) {}
data_source(data_source&& x) = default;
data_source& operator=(data_source&& x) = default;
~data_source() {
if (!_dsi) {
return;
}
// await any background operations
auto closed = _dsi->close();
closed.finally([dsi = std::move(_dsi)] {});
}
future<temporary_buffer<char>> get() { return _dsi->get(); }
};
class data_sink_impl {
public:
virtual ~data_sink_impl() {}
virtual temporary_buffer<char> allocate_buffer(size_t size) {
return temporary_buffer<char>(size);
}
virtual future<> put(net::packet data) = 0;
virtual future<> put(std::vector<temporary_buffer<char>> data) {
net::packet p;
p.reserve(data.size());
for (auto& buf : data) {
p = net::packet(std::move(p), net::fragment{buf.get_write(), buf.size()}, buf.release());
}
return put(std::move(p));
}
virtual future<> put(temporary_buffer<char> buf) {
return put(net::packet(net::fragment{buf.get_write(), buf.size()}, buf.release()));
}
virtual future<> flush() {
return make_ready_future<>();
}
virtual future<> close() = 0;
};
class data_sink {
std::unique_ptr<data_sink_impl> _dsi;
public:
data_sink() = default;
explicit data_sink(std::unique_ptr<data_sink_impl> dsi) : _dsi(std::move(dsi)) {}
data_sink(data_sink&& x) = default;
data_sink& operator=(data_sink&& x) = default;
temporary_buffer<char> allocate_buffer(size_t size) {
return _dsi->allocate_buffer(size);
}
future<> put(std::vector<temporary_buffer<char>> data) {
return _dsi->put(std::move(data));
}
future<> put(temporary_buffer<char> data) {
return _dsi->put(std::move(data));
}
future<> put(net::packet p) {
return _dsi->put(std::move(p));
}
future<> flush() {
return _dsi->flush();
}
future<> close() { return _dsi->close(); }
};
template <typename CharType>
class input_stream final {
static_assert(sizeof(CharType) == 1, "must buffer stream of bytes");
data_source _fd;
temporary_buffer<CharType> _buf;
bool _eof = false;
private:
using tmp_buf = temporary_buffer<CharType>;
size_t available() const { return _buf.size(); }
protected:
void reset() { _buf = {}; }
data_source* fd() { return &_fd; }
public:
// Consumer concept, for consume() method:
using unconsumed_remainder = std::experimental::optional<tmp_buf>;
struct ConsumerConcept {
// The consumer should operate on the data given to it, and
// return a future "unconsumed remainder", which can be undefined
// if the consumer consumed all the input given to it and is ready
// for more, or defined when the consumer is done (and in that case
// the value is the unconsumed part of the last data buffer - this
// can also happen to be empty).
future<unconsumed_remainder> operator()(tmp_buf data);
};
using char_type = CharType;
input_stream() = default;
explicit input_stream(data_source fd) : _fd(std::move(fd)), _buf(0) {}
input_stream(input_stream&&) = default;
input_stream& operator=(input_stream&&) = default;
future<temporary_buffer<CharType>> read_exactly(size_t n);
template <typename Consumer>
future<> consume(Consumer& c);
bool eof() { return _eof; }
private:
future<temporary_buffer<CharType>> read_exactly_part(size_t n, tmp_buf buf, size_t completed);
};
// Facilitates data buffering before it's handed over to data_sink.
//
// When trim_to_size is true it's guaranteed that data sink will not receive
// chunks larger than the configured size, which could be the case when a
// single write call is made with data larger than the configured size.
//
// The data sink will not receive empty chunks.
//
template <typename CharType>
class output_stream final {
static_assert(sizeof(CharType) == 1, "must buffer stream of bytes");
data_sink _fd;
temporary_buffer<CharType> _buf;
size_t _size = 0;
size_t _begin = 0;
size_t _end = 0;
bool _trim_to_size = false;
private:
size_t available() const { return _end - _begin; }
size_t possibly_available() const { return _size - _begin; }
future<> split_and_put(temporary_buffer<CharType> buf);
public:
using char_type = CharType;
output_stream() = default;
output_stream(data_sink fd, size_t size, bool trim_to_size = false)
: _fd(std::move(fd)), _size(size), _trim_to_size(trim_to_size) {}
output_stream(output_stream&&) = default;
output_stream& operator=(output_stream&&) = default;
future<> write(const char_type* buf, size_t n);
future<> write(const char_type* buf);
template <typename StringChar, typename SizeType, SizeType MaxSize>
future<> write(const basic_sstring<StringChar, SizeType, MaxSize>& s);
future<> write(const std::basic_string<char_type>& s);
future<> write(net::packet p);
future<> write(scattered_message<char_type> msg);
future<> flush();
future<> close() { return flush().then([this] { return _fd.close(); }); }
private:
};
#include "iostream-impl.hh"
<|endoftext|> |
<commit_before>/*===================================================================
The Medical Imaging Interaction Toolkit (MITK)
Copyright (c) German Cancer Research Center,
Division of Medical and Biological Informatics.
All rights reserved.
This software is distributed WITHOUT ANY WARRANTY; without
even the implied warranty of MERCHANTABILITY or FITNESS FOR
A PARTICULAR PURPOSE.
See LICENSE.txt or http://www.mitk.org for details.
===================================================================*/
// mitk includes
#include "mitkImageToOpenCVImageFilter.h"
#include "mitkOpenCVToMitkImageFilter.h"
#include <mitkTestingMacros.h>
#include <mitkITKImageImport.h>
#include <mitkImageAccessByItk.h>
#include <mitkIOUtil.h>
#include "mitkImageReadAccessor.h"
#include "mitkImageSliceSelector.h"
// itk includes
#include <itkRGBPixel.h>
#include <iostream>
#include <highgui.h>
// define test pixel indexes and intensities and other values
typedef itk::RGBPixel< unsigned char > TestUCRGBPixelType;
cv::Size testImageSize;
cv::Point pos1;
cv::Point pos2;
cv::Point pos3;
cv::Vec3b color1;
cv::Vec3b color2;
cv::Vec3b color3;
uchar greyValue1;
uchar greyValue2;
uchar greyValue3;
/*! Documentation
* Test for image conversion of OpenCV images and mitk::Images. It tests the classes
* OpenCVToMitkImageFilter and ImageToOpenCVImageFilter
*/
// Some declarations
template<typename TPixel, unsigned int VImageDimension>
void ComparePixels( itk::Image<itk::RGBPixel<TPixel>,VImageDimension>* image );
void ReadImageDataAndConvertForthAndBack(std::string imageFileName);
void ConvertIplImageForthAndBack(mitk::Image::Pointer inputForCVMat, std::string imageFileName);
void ConvertCVMatForthAndBack(mitk::Image::Pointer inputForCVMat, std::string imageFileName);
// Begin the test for mitkImage to OpenCV image conversion and back.
int mitkOpenCVMitkConversionTest(int argc, char* argv[])
{
MITK_TEST_BEGIN("ImageToOpenCVImageFilter")
// the first part of this test checks the conversion of a cv::Mat style OpenCV image.
// we build an cv::Mat image
MITK_INFO << "setting test values";
testImageSize = cv::Size(11,11);
pos1 = cv::Point(0,0);
pos2 = cv::Point(5,5);
pos3 = cv::Point(10,10);
color1 = cv::Vec3b(50,0,0);
color2 = cv::Vec3b(0,128,0);
color3 = cv::Vec3b(0,0,255);
greyValue1 = 0;
greyValue2 = 128;
greyValue3 = 255;
MITK_INFO << "generating test OpenCV image (RGB)";
cv::Mat testRGBImage = cv::Mat::zeros( testImageSize, CV_8UC3 );
// generate some test intensity values
testRGBImage.at<cv::Vec3b>(pos1)= color1;
testRGBImage.at<cv::Vec3b>(pos2)= color2;
testRGBImage.at<cv::Vec3b>(pos3)= color3;
//cv::namedWindow("debug", CV_WINDOW_FREERATIO );
//cv::imshow("debug", testRGBImage.clone());
//cv::waitKey(0);
// convert it to a mitk::Image
MITK_INFO << "converting OpenCV test image to mitk image and comparing scalar rgb values";
mitk::OpenCVToMitkImageFilter::Pointer openCvToMitkFilter =
mitk::OpenCVToMitkImageFilter::New();
openCvToMitkFilter->SetOpenCVMat( testRGBImage );
openCvToMitkFilter->Update();
mitk::Image::Pointer mitkImage = openCvToMitkFilter->GetOutput();
AccessFixedTypeByItk(mitkImage.GetPointer(), ComparePixels,
(itk::RGBPixel<unsigned char>), // rgb image
(2) );
// convert it back to OpenCV image
MITK_INFO << "converting mitk image to OpenCV image and comparing scalar rgb values";
mitk::ImageToOpenCVImageFilter::Pointer mitkToOpenCv = mitk::ImageToOpenCVImageFilter::New();
mitkToOpenCv->SetImage( mitkImage );
cv::Mat openCvImage = mitkToOpenCv->GetOpenCVMat();
// and test equality of the sentinel pixel
cv::Vec3b convertedColor1 = openCvImage.at<cv::Vec3b>(pos1);
cv::Vec3b convertedColor2 = openCvImage.at<cv::Vec3b>(pos2);
cv::Vec3b convertedColor3 = openCvImage.at<cv::Vec3b>(pos3);
MITK_TEST_CONDITION( color1 == convertedColor1, "Testing if initially created color values " << static_cast<int>( color1[0] ) << ", " << static_cast<int>( color1[1] ) << ", " << static_cast<int>( color1[2] ) << " matches the color values " << static_cast<int>( convertedColor1[0] ) << ", " << static_cast<int>( convertedColor1[1] ) << ", " << static_cast<int>( convertedColor1[2] ) << " at the same position " << pos1.x << ", " << pos1.y << " in the back converted OpenCV image" )
MITK_TEST_CONDITION( color2 == convertedColor2, "Testing if initially created color values " << static_cast<int>( color2[0] ) << ", " << static_cast<int>( color2[1] ) << ", " << static_cast<int>( color2[2] ) << " matches the color values " << static_cast<int>( convertedColor2[0] ) << ", " << static_cast<int>( convertedColor2[1] ) << ", " << static_cast<int>( convertedColor2[2] ) << " at the same position " << pos2.x << ", " << pos2.y << " in the back converted OpenCV image" )
MITK_TEST_CONDITION( color3 == convertedColor3, "Testing if initially created color values " << static_cast<int>( color3[0] ) << ", " << static_cast<int>( color3[1] ) << ", " << static_cast<int>( color3[2] ) << " matches the color values " << static_cast<int>( convertedColor3[0] ) << ", " << static_cast<int>( convertedColor3[1] ) << ", " << static_cast<int>( convertedColor3[2] ) << " at the same position " << pos3.x << ", " << pos3.y << " in the back converted OpenCV image" )
// the second part of this test checks the conversion of mitk::Images to Ipl images and cv::Mat and back.
for (int i = 1; i < argc; ++i)
{
ReadImageDataAndConvertForthAndBack(argv[i]);
}
MITK_TEST_END();
}
template<typename TPixel, unsigned int VImageDimension>
void ComparePixels( itk::Image<itk::RGBPixel<TPixel>,VImageDimension>* image )
{
typedef itk::RGBPixel<TPixel> PixelType;
typedef itk::Image<PixelType, VImageDimension> ImageType;
typename ImageType::IndexType pixelIndex;
pixelIndex[0] = pos1.x;
pixelIndex[1] = pos1.y;
PixelType onePixel = image->GetPixel( pixelIndex );
MITK_TEST_CONDITION( color1[0] == onePixel.GetBlue(), "Testing if blue value (= " << static_cast<int>(color1[0]) << ") at postion "
<< pos1.x << ", " << pos1.y << " in OpenCV image is "
<< "equals the blue value (= " << static_cast<int>(onePixel.GetBlue()) << ")"
<< " in the generated mitk image");
pixelIndex[0] = pos2.x;
pixelIndex[1] = pos2.y;
onePixel = image->GetPixel( pixelIndex );
MITK_TEST_CONDITION( color2[1] == onePixel.GetGreen(), "Testing if green value (= " << static_cast<int>(color2[1]) << ") at postion "
<< pos2.x << ", " << pos2.y << " in OpenCV image is "
<< "equals the green value (= " << static_cast<int>(onePixel.GetGreen()) << ")"
<< " in the generated mitk image");
pixelIndex[0] = pos3.x;
pixelIndex[1] = pos3.y;
onePixel = image->GetPixel( pixelIndex );
MITK_TEST_CONDITION( color3[2] == onePixel.GetRed(), "Testing if red value (= " << static_cast<int>(color3[2]) << ") at postion "
<< pos3.x << ", " << pos3.y << " in OpenCV image is "
<< "equals the red value (= " << static_cast<int>(onePixel.GetRed()) << ")"
<< " in the generated mitk image");
}
void ReadImageDataAndConvertForthAndBack(std::string imageFileName)
{
// first we load an mitk::Image from the data repository
mitk::Image::Pointer mitkTestImage = dynamic_cast<mitk::Image*>(mitk::IOUtil::Load(imageFileName)[0].GetPointer());
// some format checking
mitk::Image::Pointer resultImg = nullptr;
if( mitkTestImage->GetDimension() <= 3 )
{
if( mitkTestImage->GetDimension() > 2 && mitkTestImage->GetDimension(2) == 1 )
{
mitk::ImageSliceSelector::Pointer sliceSelector = mitk::ImageSliceSelector::New();
sliceSelector->SetInput(mitkTestImage);
sliceSelector->SetSliceNr(0);
sliceSelector->Update();
resultImg = sliceSelector->GetOutput()->Clone();
}
else if(mitkTestImage->GetDimension() < 3)
{
resultImg = mitkTestImage;
}
else
{
return; // 3D images are not supported, except with just one slice.
}
}
else
{
return; // 4D images are not supported!
}
ConvertIplImageForthAndBack(resultImg, imageFileName);
ConvertCVMatForthAndBack(resultImg, imageFileName);
}
void ConvertCVMatForthAndBack(mitk::Image::Pointer inputForCVMat, std::string imageFileName)
{
// now we convert it to OpenCV IplImage
mitk::ImageToOpenCVImageFilter::Pointer toOCvConverter = mitk::ImageToOpenCVImageFilter::New();
toOCvConverter->SetImage(inputForCVMat);
cv::Mat cvmatTestImage = toOCvConverter->GetOpenCVMat();
MITK_TEST_CONDITION_REQUIRED( !cvmatTestImage.empty(), "Conversion to cv::Mat successful!");
mitk::OpenCVToMitkImageFilter::Pointer toMitkConverter = mitk::OpenCVToMitkImageFilter::New();
toMitkConverter->SetOpenCVMat(cvmatTestImage);
toMitkConverter->Update();
// initialize the image with the input image, since we want to test equality and OpenCV does not feature geometries and spacing
mitk::Image::Pointer result = inputForCVMat->Clone();
mitk::ImageReadAccessor resultAcc(toMitkConverter->GetOutput(), toMitkConverter->GetOutput()->GetSliceData());
result->SetImportSlice(const_cast<void*>(resultAcc.GetData()));
if( result->GetPixelType().GetNumberOfComponents() == 1 )
{
MITK_ASSERT_EQUAL( result, inputForCVMat, "Testing equality of input and output image of cv::Mat conversion" );
}
else if( result->GetPixelType().GetNumberOfComponents() == 3 )
{
MITK_ASSERT_EQUAL( result, inputForCVMat, "Testing equality of input and output image of cv::Mat conversion" );
}
else
{
MITK_WARN << "Unhandled number of components used to test equality, please enhance test!";
}
// change OpenCV image to test if the filter gets updated
cv::Mat changedcvmatTestImage = cvmatTestImage.clone();
if (result->GetPixelType().GetBitsPerComponent() == sizeof(char)*8)
{
changedcvmatTestImage.at<char>(0,0) = cvmatTestImage.at<char>(0,0) != 0 ? 0 : 1;
}
else if (result->GetPixelType().GetBitsPerComponent() == sizeof(float)*8)
{
changedcvmatTestImage.at<float>(0,0) = cvmatTestImage.at<float>(0,0) != 0 ? 0 : 1;
}
toMitkConverter->SetOpenCVMat(changedcvmatTestImage);
toMitkConverter->Update();
MITK_TEST_NOT_EQUAL(toMitkConverter->GetOutput(), inputForCVMat, "Converted image must not be the same as before.");
}
void ConvertIplImageForthAndBack(mitk::Image::Pointer inputForIpl, std::string imageFileName)
{
// now we convert it to OpenCV IplImage
mitk::ImageToOpenCVImageFilter::Pointer toOCvConverter = mitk::ImageToOpenCVImageFilter::New();
toOCvConverter->SetImage(inputForIpl);
IplImage* iplTestImage = toOCvConverter->GetOpenCVImage();
MITK_TEST_CONDITION_REQUIRED( iplTestImage != nullptr, "Conversion to OpenCv IplImage successful!");
mitk::OpenCVToMitkImageFilter::Pointer toMitkConverter = mitk::OpenCVToMitkImageFilter::New();
toMitkConverter->SetOpenCVImage(iplTestImage);
toMitkConverter->Update();
// initialize the image with the input image, since we want to test equality and OpenCV does not feature geometries and spacing
mitk::Image::Pointer result = inputForIpl->Clone();
mitk::ImageReadAccessor resultAcc(toMitkConverter->GetOutput(), toMitkConverter->GetOutput()->GetSliceData());
result->SetImportSlice(const_cast<void*>(resultAcc.GetData()));
if( result->GetPixelType().GetNumberOfComponents() == 1 )
{
MITK_ASSERT_EQUAL( result, inputForIpl, "Testing equality of input and output image of IplImage conversion" );
}
else if( result->GetPixelType().GetNumberOfComponents() == 3 )
{
MITK_ASSERT_EQUAL( result, inputForIpl, "Testing equality of input and output image of cv::Mat conversion" );
}
else
{
MITK_WARN << "Unhandled number of components used to test equality, please enhance test!";
}
}
<commit_msg>Fix warnings in OpenCVVideoSupport tests<commit_after>/*===================================================================
The Medical Imaging Interaction Toolkit (MITK)
Copyright (c) German Cancer Research Center,
Division of Medical and Biological Informatics.
All rights reserved.
This software is distributed WITHOUT ANY WARRANTY; without
even the implied warranty of MERCHANTABILITY or FITNESS FOR
A PARTICULAR PURPOSE.
See LICENSE.txt or http://www.mitk.org for details.
===================================================================*/
// mitk includes
#include "mitkImageToOpenCVImageFilter.h"
#include "mitkOpenCVToMitkImageFilter.h"
#include <mitkTestingMacros.h>
#include <mitkITKImageImport.h>
#include <mitkImageAccessByItk.h>
#include <mitkIOUtil.h>
#include "mitkImageReadAccessor.h"
#include "mitkImageSliceSelector.h"
// itk includes
#include <itkRGBPixel.h>
#include <iostream>
#include <highgui.h>
// define test pixel indexes and intensities and other values
typedef itk::RGBPixel< unsigned char > TestUCRGBPixelType;
cv::Size testImageSize;
cv::Point pos1;
cv::Point pos2;
cv::Point pos3;
cv::Vec3b color1;
cv::Vec3b color2;
cv::Vec3b color3;
uchar greyValue1;
uchar greyValue2;
uchar greyValue3;
/*! Documentation
* Test for image conversion of OpenCV images and mitk::Images. It tests the classes
* OpenCVToMitkImageFilter and ImageToOpenCVImageFilter
*/
// Some declarations
template<typename TPixel, unsigned int VImageDimension>
void ComparePixels( itk::Image<itk::RGBPixel<TPixel>,VImageDimension>* image );
void ReadImageDataAndConvertForthAndBack(std::string imageFileName);
void ConvertIplImageForthAndBack(mitk::Image::Pointer inputForCVMat, std::string imageFileName);
void ConvertCVMatForthAndBack(mitk::Image::Pointer inputForCVMat, std::string imageFileName);
// Begin the test for mitkImage to OpenCV image conversion and back.
int mitkOpenCVMitkConversionTest(int argc, char* argv[])
{
MITK_TEST_BEGIN("ImageToOpenCVImageFilter")
// the first part of this test checks the conversion of a cv::Mat style OpenCV image.
// we build an cv::Mat image
MITK_INFO << "setting test values";
testImageSize = cv::Size(11,11);
pos1 = cv::Point(0,0);
pos2 = cv::Point(5,5);
pos3 = cv::Point(10,10);
color1 = cv::Vec3b(50,0,0);
color2 = cv::Vec3b(0,128,0);
color3 = cv::Vec3b(0,0,255);
greyValue1 = 0;
greyValue2 = 128;
greyValue3 = 255;
MITK_INFO << "generating test OpenCV image (RGB)";
cv::Mat testRGBImage = cv::Mat::zeros( testImageSize, CV_8UC3 );
// generate some test intensity values
testRGBImage.at<cv::Vec3b>(pos1)= color1;
testRGBImage.at<cv::Vec3b>(pos2)= color2;
testRGBImage.at<cv::Vec3b>(pos3)= color3;
//cv::namedWindow("debug", CV_WINDOW_FREERATIO );
//cv::imshow("debug", testRGBImage.clone());
//cv::waitKey(0);
// convert it to a mitk::Image
MITK_INFO << "converting OpenCV test image to mitk image and comparing scalar rgb values";
mitk::OpenCVToMitkImageFilter::Pointer openCvToMitkFilter =
mitk::OpenCVToMitkImageFilter::New();
openCvToMitkFilter->SetOpenCVMat( testRGBImage );
openCvToMitkFilter->Update();
mitk::Image::Pointer mitkImage = openCvToMitkFilter->GetOutput();
AccessFixedTypeByItk(mitkImage.GetPointer(), ComparePixels,
(itk::RGBPixel<unsigned char>), // rgb image
(2) );
// convert it back to OpenCV image
MITK_INFO << "converting mitk image to OpenCV image and comparing scalar rgb values";
mitk::ImageToOpenCVImageFilter::Pointer mitkToOpenCv = mitk::ImageToOpenCVImageFilter::New();
mitkToOpenCv->SetImage( mitkImage );
cv::Mat openCvImage = mitkToOpenCv->GetOpenCVMat();
// and test equality of the sentinel pixel
cv::Vec3b convertedColor1 = openCvImage.at<cv::Vec3b>(pos1);
cv::Vec3b convertedColor2 = openCvImage.at<cv::Vec3b>(pos2);
cv::Vec3b convertedColor3 = openCvImage.at<cv::Vec3b>(pos3);
MITK_TEST_CONDITION( color1 == convertedColor1, "Testing if initially created color values " << static_cast<int>( color1[0] ) << ", " << static_cast<int>( color1[1] ) << ", " << static_cast<int>( color1[2] ) << " matches the color values " << static_cast<int>( convertedColor1[0] ) << ", " << static_cast<int>( convertedColor1[1] ) << ", " << static_cast<int>( convertedColor1[2] ) << " at the same position " << pos1.x << ", " << pos1.y << " in the back converted OpenCV image" )
MITK_TEST_CONDITION( color2 == convertedColor2, "Testing if initially created color values " << static_cast<int>( color2[0] ) << ", " << static_cast<int>( color2[1] ) << ", " << static_cast<int>( color2[2] ) << " matches the color values " << static_cast<int>( convertedColor2[0] ) << ", " << static_cast<int>( convertedColor2[1] ) << ", " << static_cast<int>( convertedColor2[2] ) << " at the same position " << pos2.x << ", " << pos2.y << " in the back converted OpenCV image" )
MITK_TEST_CONDITION( color3 == convertedColor3, "Testing if initially created color values " << static_cast<int>( color3[0] ) << ", " << static_cast<int>( color3[1] ) << ", " << static_cast<int>( color3[2] ) << " matches the color values " << static_cast<int>( convertedColor3[0] ) << ", " << static_cast<int>( convertedColor3[1] ) << ", " << static_cast<int>( convertedColor3[2] ) << " at the same position " << pos3.x << ", " << pos3.y << " in the back converted OpenCV image" )
// the second part of this test checks the conversion of mitk::Images to Ipl images and cv::Mat and back.
for (int i = 1; i < argc; ++i)
{
ReadImageDataAndConvertForthAndBack(argv[i]);
}
MITK_TEST_END();
}
template<typename TPixel, unsigned int VImageDimension>
void ComparePixels( itk::Image<itk::RGBPixel<TPixel>,VImageDimension>* image )
{
typedef itk::RGBPixel<TPixel> PixelType;
typedef itk::Image<PixelType, VImageDimension> ImageType;
typename ImageType::IndexType pixelIndex;
pixelIndex[0] = pos1.x;
pixelIndex[1] = pos1.y;
PixelType onePixel = image->GetPixel( pixelIndex );
MITK_TEST_CONDITION( color1[0] == onePixel.GetBlue(), "Testing if blue value (= " << static_cast<int>(color1[0]) << ") at postion "
<< pos1.x << ", " << pos1.y << " in OpenCV image is "
<< "equals the blue value (= " << static_cast<int>(onePixel.GetBlue()) << ")"
<< " in the generated mitk image");
pixelIndex[0] = pos2.x;
pixelIndex[1] = pos2.y;
onePixel = image->GetPixel( pixelIndex );
MITK_TEST_CONDITION( color2[1] == onePixel.GetGreen(), "Testing if green value (= " << static_cast<int>(color2[1]) << ") at postion "
<< pos2.x << ", " << pos2.y << " in OpenCV image is "
<< "equals the green value (= " << static_cast<int>(onePixel.GetGreen()) << ")"
<< " in the generated mitk image");
pixelIndex[0] = pos3.x;
pixelIndex[1] = pos3.y;
onePixel = image->GetPixel( pixelIndex );
MITK_TEST_CONDITION( color3[2] == onePixel.GetRed(), "Testing if red value (= " << static_cast<int>(color3[2]) << ") at postion "
<< pos3.x << ", " << pos3.y << " in OpenCV image is "
<< "equals the red value (= " << static_cast<int>(onePixel.GetRed()) << ")"
<< " in the generated mitk image");
}
void ReadImageDataAndConvertForthAndBack(std::string imageFileName)
{
// first we load an mitk::Image from the data repository
mitk::Image::Pointer mitkTestImage = dynamic_cast<mitk::Image*>(mitk::IOUtil::Load(imageFileName)[0].GetPointer());
// some format checking
mitk::Image::Pointer resultImg = nullptr;
if( mitkTestImage->GetDimension() <= 3 )
{
if( mitkTestImage->GetDimension() > 2 && mitkTestImage->GetDimension(2) == 1 )
{
mitk::ImageSliceSelector::Pointer sliceSelector = mitk::ImageSliceSelector::New();
sliceSelector->SetInput(mitkTestImage);
sliceSelector->SetSliceNr(0);
sliceSelector->Update();
resultImg = sliceSelector->GetOutput()->Clone();
}
else if(mitkTestImage->GetDimension() < 3)
{
resultImg = mitkTestImage;
}
else
{
return; // 3D images are not supported, except with just one slice.
}
}
else
{
return; // 4D images are not supported!
}
ConvertIplImageForthAndBack(resultImg, imageFileName);
ConvertCVMatForthAndBack(resultImg, imageFileName);
}
void ConvertCVMatForthAndBack(mitk::Image::Pointer inputForCVMat, std::string)
{
// now we convert it to OpenCV IplImage
mitk::ImageToOpenCVImageFilter::Pointer toOCvConverter = mitk::ImageToOpenCVImageFilter::New();
toOCvConverter->SetImage(inputForCVMat);
cv::Mat cvmatTestImage = toOCvConverter->GetOpenCVMat();
MITK_TEST_CONDITION_REQUIRED( !cvmatTestImage.empty(), "Conversion to cv::Mat successful!");
mitk::OpenCVToMitkImageFilter::Pointer toMitkConverter = mitk::OpenCVToMitkImageFilter::New();
toMitkConverter->SetOpenCVMat(cvmatTestImage);
toMitkConverter->Update();
// initialize the image with the input image, since we want to test equality and OpenCV does not feature geometries and spacing
mitk::Image::Pointer result = inputForCVMat->Clone();
mitk::ImageReadAccessor resultAcc(toMitkConverter->GetOutput(), toMitkConverter->GetOutput()->GetSliceData());
result->SetImportSlice(const_cast<void*>(resultAcc.GetData()));
if( result->GetPixelType().GetNumberOfComponents() == 1 )
{
MITK_ASSERT_EQUAL( result, inputForCVMat, "Testing equality of input and output image of cv::Mat conversion" );
}
else if( result->GetPixelType().GetNumberOfComponents() == 3 )
{
MITK_ASSERT_EQUAL( result, inputForCVMat, "Testing equality of input and output image of cv::Mat conversion" );
}
else
{
MITK_WARN << "Unhandled number of components used to test equality, please enhance test!";
}
// change OpenCV image to test if the filter gets updated
cv::Mat changedcvmatTestImage = cvmatTestImage.clone();
if (result->GetPixelType().GetBitsPerComponent() == sizeof(char)*8)
{
changedcvmatTestImage.at<char>(0,0) = cvmatTestImage.at<char>(0,0) != 0 ? 0 : 1;
}
else if (result->GetPixelType().GetBitsPerComponent() == sizeof(float)*8)
{
changedcvmatTestImage.at<float>(0,0) = cvmatTestImage.at<float>(0,0) != 0 ? 0 : 1;
}
toMitkConverter->SetOpenCVMat(changedcvmatTestImage);
toMitkConverter->Update();
MITK_TEST_NOT_EQUAL(toMitkConverter->GetOutput(), inputForCVMat, "Converted image must not be the same as before.");
}
void ConvertIplImageForthAndBack(mitk::Image::Pointer inputForIpl, std::string)
{
// now we convert it to OpenCV IplImage
mitk::ImageToOpenCVImageFilter::Pointer toOCvConverter = mitk::ImageToOpenCVImageFilter::New();
toOCvConverter->SetImage(inputForIpl);
IplImage* iplTestImage = toOCvConverter->GetOpenCVImage();
MITK_TEST_CONDITION_REQUIRED( iplTestImage != nullptr, "Conversion to OpenCv IplImage successful!");
mitk::OpenCVToMitkImageFilter::Pointer toMitkConverter = mitk::OpenCVToMitkImageFilter::New();
toMitkConverter->SetOpenCVImage(iplTestImage);
toMitkConverter->Update();
// initialize the image with the input image, since we want to test equality and OpenCV does not feature geometries and spacing
mitk::Image::Pointer result = inputForIpl->Clone();
mitk::ImageReadAccessor resultAcc(toMitkConverter->GetOutput(), toMitkConverter->GetOutput()->GetSliceData());
result->SetImportSlice(const_cast<void*>(resultAcc.GetData()));
if( result->GetPixelType().GetNumberOfComponents() == 1 )
{
MITK_ASSERT_EQUAL( result, inputForIpl, "Testing equality of input and output image of IplImage conversion" );
}
else if( result->GetPixelType().GetNumberOfComponents() == 3 )
{
MITK_ASSERT_EQUAL( result, inputForIpl, "Testing equality of input and output image of cv::Mat conversion" );
}
else
{
MITK_WARN << "Unhandled number of components used to test equality, please enhance test!";
}
}
<|endoftext|> |
<commit_before>// Copyright (c) 2010 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "remoting/client/plugin/chromoting_scriptable_object.h"
#include "base/logging.h"
#include "ppapi/cpp/var.h"
#include "remoting/client/client_config.h"
#include "remoting/client/plugin/chromoting_instance.h"
using pp::Var;
namespace remoting {
const char kConnectionInfoUpdate[] = "connectionInfoUpdate";
const char kDebugInfoUpdate[] = "debugInfoUpdate";
const char kDebugInfoAttribute[] = "debugInfo";
const char kDesktopHeight[] = "desktopHeight";
const char kDesktopWidth[] = "desktopWidth";
const char kLoginChallenge[] = "loginChallenge";
const char kQualityAttribute[] = "quality";
const char kStatusAttribute[] = "status";
ChromotingScriptableObject::ChromotingScriptableObject(
ChromotingInstance* instance)
: instance_(instance) {
}
ChromotingScriptableObject::~ChromotingScriptableObject() {
}
void ChromotingScriptableObject::Init() {
// Property addition order should match the interface description at the
// top of chromoting_scriptable_object.h.
// Connection status.
AddAttribute(kStatusAttribute, Var(STATUS_UNKNOWN));
// Connection status values.
AddAttribute("STATUS_UNKNOWN", Var(STATUS_UNKNOWN));
AddAttribute("STATUS_CONNECTING", Var(STATUS_CONNECTING));
AddAttribute("STATUS_INITIALIZING", Var(STATUS_INITIALIZING));
AddAttribute("STATUS_CONNECTED", Var(STATUS_CONNECTED));
AddAttribute("STATUS_CLOSED", Var(STATUS_CLOSED));
AddAttribute("STATUS_FAILED", Var(STATUS_FAILED));
// Connection quality.
AddAttribute(kQualityAttribute, Var(QUALITY_UNKNOWN));
// Connection quality values.
AddAttribute("QUALITY_UNKNOWN", Var(QUALITY_UNKNOWN));
AddAttribute("QUALITY_GOOD", Var(QUALITY_GOOD));
AddAttribute("QUALITY_BAD", Var(QUALITY_BAD));
// Debug info to display.
AddAttribute(kDebugInfoAttribute, Var());
AddAttribute(kConnectionInfoUpdate, Var());
AddAttribute(kDebugInfoUpdate, Var());
AddAttribute(kLoginChallenge, Var());
AddAttribute(kDesktopWidth, Var(0));
AddAttribute(kDesktopHeight, Var(0));
AddMethod("connect", &ChromotingScriptableObject::DoConnect);
AddMethod("disconnect", &ChromotingScriptableObject::DoDisconnect);
AddMethod("submitLoginInfo", &ChromotingScriptableObject::DoSubmitLogin);
}
bool ChromotingScriptableObject::HasProperty(const Var& name, Var* exception) {
// TODO(ajwong): Check if all these name.is_string() sentinels are required.
if (!name.is_string()) {
*exception = Var("HasProperty expects a string for the name.");
return false;
}
PropertyNameMap::const_iterator iter = property_names_.find(name.AsString());
if (iter == property_names_.end()) {
return false;
}
// TODO(ajwong): Investigate why ARM build breaks if you do:
// properties_[iter->second].method == NULL;
// Somehow the ARM compiler is thinking that the above is using NULL as an
// arithmetic expression.
return properties_[iter->second].method == 0;
}
bool ChromotingScriptableObject::HasMethod(const Var& name, Var* exception) {
// TODO(ajwong): Check if all these name.is_string() sentinels are required.
if (!name.is_string()) {
*exception = Var("HasMethod expects a string for the name.");
return false;
}
PropertyNameMap::const_iterator iter = property_names_.find(name.AsString());
if (iter == property_names_.end()) {
return false;
}
// See comment from HasProperty about why to use 0 instead of NULL here.
return properties_[iter->second].method != 0;
}
Var ChromotingScriptableObject::GetProperty(const Var& name, Var* exception) {
// TODO(ajwong): Check if all these name.is_string() sentinels are required.
if (!name.is_string()) {
*exception = Var("GetProperty expects a string for the name.");
return Var();
}
PropertyNameMap::const_iterator iter = property_names_.find(name.AsString());
// No property found.
if (iter == property_names_.end()) {
return ScriptableObject::GetProperty(name, exception);
}
// TODO(ajwong): This incorrectly return a null object if a function
// property is requested.
return properties_[iter->second].attribute;
}
void ChromotingScriptableObject::GetAllPropertyNames(
std::vector<Var>* properties,
Var* exception) {
for (size_t i = 0; i < properties_.size(); i++) {
properties->push_back(Var(properties_[i].name));
}
}
void ChromotingScriptableObject::SetProperty(const Var& name,
const Var& value,
Var* exception) {
// TODO(ajwong): Check if all these name.is_string() sentinels are required.
if (!name.is_string()) {
*exception = Var("SetProperty expects a string for the name.");
return;
}
// Allow writing to connectionInfoUpdate or loginChallenge. See top of
// chromoting_scriptable_object.h for the object interface definition.
std::string property_name = name.AsString();
if (property_name != kConnectionInfoUpdate &&
property_name != kDebugInfoUpdate &&
property_name != kLoginChallenge &&
property_name != kDesktopWidth &&
property_name != kDesktopHeight) {
*exception =
Var("Cannot set property " + property_name + " on this object.");
return;
}
// Since we're whitelisting the propertie that are settable above, we can
// assume that the property exists in the map.
properties_[property_names_[property_name]].attribute = value;
}
Var ChromotingScriptableObject::Call(const Var& method_name,
const std::vector<Var>& args,
Var* exception) {
PropertyNameMap::const_iterator iter =
property_names_.find(method_name.AsString());
if (iter == property_names_.end()) {
return pp::deprecated::ScriptableObject::Call(method_name, args, exception);
}
return (this->*(properties_[iter->second].method))(args, exception);
}
void ChromotingScriptableObject::SetConnectionInfo(ConnectionStatus status,
ConnectionQuality quality) {
int status_index = property_names_[kStatusAttribute];
int quality_index = property_names_[kQualityAttribute];
if (properties_[status_index].attribute.AsInt() != status ||
properties_[quality_index].attribute.AsInt() != quality) {
// Update the connection state properties..
properties_[status_index].attribute = Var(status);
properties_[quality_index].attribute = Var(quality);
// Signal the Chromoting Tab UI to get the update connection state values.
SignalConnectionInfoChange();
}
}
void ChromotingScriptableObject::LogDebugInfo(const std::string& info) {
int debug_info_index = property_names_[kDebugInfoAttribute];
// Update the debug info string.
// Note that this only stores the most recent debug string.
properties_[debug_info_index].attribute = Var(info);
// Signal the client UI to get the updated debug info.
SignalDebugInfoChange();
}
void ChromotingScriptableObject::SetDesktopSize(int width, int height) {
int width_index = property_names_[kDesktopWidth];
int height_index = property_names_[kDesktopHeight];
if (properties_[width_index].attribute.AsInt() != width ||
properties_[height_index].attribute.AsInt() != height) {
properties_[width_index].attribute = Var(width);
properties_[height_index].attribute = Var(height);
}
}
void ChromotingScriptableObject::AddAttribute(const std::string& name,
Var attribute) {
property_names_[name] = properties_.size();
properties_.push_back(PropertyDescriptor(name, attribute));
}
void ChromotingScriptableObject::AddMethod(const std::string& name,
MethodHandler handler) {
property_names_[name] = properties_.size();
properties_.push_back(PropertyDescriptor(name, handler));
}
void ChromotingScriptableObject::SignalConnectionInfoChange() {
Var exception;
// The JavaScript callback function is the 'callback' property on the
// 'connectionInfoUpdate' object.
Var cb = GetProperty(Var(kConnectionInfoUpdate), &exception);
// Var() means call the object directly as a function rather than calling
// a method in the object.
cb.Call(Var(), 0, NULL, &exception);
if (!exception.is_undefined()) {
LOG(WARNING) << "Exception when invoking connectionInfoUpdate JS callback"
<< exception.AsString();
}
}
void ChromotingScriptableObject::SignalDebugInfoChange() {
Var exception;
// The JavaScript callback function is the 'callback' property on the
// 'debugInfoUpdate' object.
Var cb = GetProperty(Var(kDebugInfoUpdate), &exception);
// Var() means call the object directly as a function rather than calling
// a method in the object.
cb.Call(Var(), 0, NULL, &exception);
if (!exception.is_undefined()) {
LOG(WARNING) << "Exception when invoking debugInfoUpdate JS callback"
<< exception.AsString();
}
}
void ChromotingScriptableObject::SignalLoginChallenge() {
Var exception;
// The JavaScript callback function is the 'callback' property on the
// 'loginChallenge' object.
Var cb = GetProperty(Var(kLoginChallenge), &exception);
// Var() means call the object directly as a function rather than calling
// a method in the object.
cb.Call(Var(), 0, NULL, &exception);
if (!exception.is_undefined()) {
LOG(WARNING) << "Exception when invoking loginChallenge JS callback"
<< exception.AsString();
}
}
Var ChromotingScriptableObject::DoConnect(const std::vector<Var>& args,
Var* exception) {
if (args.size() != 3) {
*exception = Var("Usage: connect(username, host_jid, auth_token)");
return Var();
}
ClientConfig config;
if (!args[0].is_string()) {
*exception = Var("The username must be a string.");
return Var();
}
config.username = args[0].AsString();
if (!args[1].is_string()) {
*exception = Var("The host_jid must be a string.");
return Var();
}
config.host_jid = args[1].AsString();
if (!args[2].is_string()) {
*exception = Var("The auth_token must be a string.");
return Var();
}
config.auth_token = args[2].AsString();
instance_->Connect(config);
return Var();
}
Var ChromotingScriptableObject::DoDisconnect(const std::vector<Var>& args,
Var* exception) {
instance_->Disconnect();
return Var();
}
Var ChromotingScriptableObject::DoSubmitLogin(const std::vector<Var>& args,
Var* exception) {
if (args.size() != 2) {
*exception = Var("Usage: login(username, password)");
return Var();
}
if (!args[0].is_string()) {
*exception = Var("Username must be a string.");
return Var();
}
std::string username = args[0].AsString();
if (!args[1].is_string()) {
*exception = Var("Password must be a string.");
return Var();
}
std::string password = args[1].AsString();
instance_->SubmitLoginInfo(username, password);
return Var();
}
} // namespace remoting
<commit_msg>Chromoting client plugin use DebugString() instead of AsString()<commit_after>// Copyright (c) 2010 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "remoting/client/plugin/chromoting_scriptable_object.h"
#include "base/logging.h"
#include "ppapi/cpp/var.h"
#include "remoting/client/client_config.h"
#include "remoting/client/plugin/chromoting_instance.h"
using pp::Var;
namespace remoting {
const char kConnectionInfoUpdate[] = "connectionInfoUpdate";
const char kDebugInfoUpdate[] = "debugInfoUpdate";
const char kDebugInfoAttribute[] = "debugInfo";
const char kDesktopHeight[] = "desktopHeight";
const char kDesktopWidth[] = "desktopWidth";
const char kLoginChallenge[] = "loginChallenge";
const char kQualityAttribute[] = "quality";
const char kStatusAttribute[] = "status";
ChromotingScriptableObject::ChromotingScriptableObject(
ChromotingInstance* instance)
: instance_(instance) {
}
ChromotingScriptableObject::~ChromotingScriptableObject() {
}
void ChromotingScriptableObject::Init() {
// Property addition order should match the interface description at the
// top of chromoting_scriptable_object.h.
// Connection status.
AddAttribute(kStatusAttribute, Var(STATUS_UNKNOWN));
// Connection status values.
AddAttribute("STATUS_UNKNOWN", Var(STATUS_UNKNOWN));
AddAttribute("STATUS_CONNECTING", Var(STATUS_CONNECTING));
AddAttribute("STATUS_INITIALIZING", Var(STATUS_INITIALIZING));
AddAttribute("STATUS_CONNECTED", Var(STATUS_CONNECTED));
AddAttribute("STATUS_CLOSED", Var(STATUS_CLOSED));
AddAttribute("STATUS_FAILED", Var(STATUS_FAILED));
// Connection quality.
AddAttribute(kQualityAttribute, Var(QUALITY_UNKNOWN));
// Connection quality values.
AddAttribute("QUALITY_UNKNOWN", Var(QUALITY_UNKNOWN));
AddAttribute("QUALITY_GOOD", Var(QUALITY_GOOD));
AddAttribute("QUALITY_BAD", Var(QUALITY_BAD));
// Debug info to display.
AddAttribute(kDebugInfoAttribute, Var());
AddAttribute(kConnectionInfoUpdate, Var());
AddAttribute(kDebugInfoUpdate, Var());
AddAttribute(kLoginChallenge, Var());
AddAttribute(kDesktopWidth, Var(0));
AddAttribute(kDesktopHeight, Var(0));
AddMethod("connect", &ChromotingScriptableObject::DoConnect);
AddMethod("disconnect", &ChromotingScriptableObject::DoDisconnect);
AddMethod("submitLoginInfo", &ChromotingScriptableObject::DoSubmitLogin);
}
bool ChromotingScriptableObject::HasProperty(const Var& name, Var* exception) {
// TODO(ajwong): Check if all these name.is_string() sentinels are required.
if (!name.is_string()) {
*exception = Var("HasProperty expects a string for the name.");
return false;
}
PropertyNameMap::const_iterator iter = property_names_.find(name.AsString());
if (iter == property_names_.end()) {
return false;
}
// TODO(ajwong): Investigate why ARM build breaks if you do:
// properties_[iter->second].method == NULL;
// Somehow the ARM compiler is thinking that the above is using NULL as an
// arithmetic expression.
return properties_[iter->second].method == 0;
}
bool ChromotingScriptableObject::HasMethod(const Var& name, Var* exception) {
// TODO(ajwong): Check if all these name.is_string() sentinels are required.
if (!name.is_string()) {
*exception = Var("HasMethod expects a string for the name.");
return false;
}
PropertyNameMap::const_iterator iter = property_names_.find(name.AsString());
if (iter == property_names_.end()) {
return false;
}
// See comment from HasProperty about why to use 0 instead of NULL here.
return properties_[iter->second].method != 0;
}
Var ChromotingScriptableObject::GetProperty(const Var& name, Var* exception) {
// TODO(ajwong): Check if all these name.is_string() sentinels are required.
if (!name.is_string()) {
*exception = Var("GetProperty expects a string for the name.");
return Var();
}
PropertyNameMap::const_iterator iter = property_names_.find(name.AsString());
// No property found.
if (iter == property_names_.end()) {
return ScriptableObject::GetProperty(name, exception);
}
// TODO(ajwong): This incorrectly return a null object if a function
// property is requested.
return properties_[iter->second].attribute;
}
void ChromotingScriptableObject::GetAllPropertyNames(
std::vector<Var>* properties,
Var* exception) {
for (size_t i = 0; i < properties_.size(); i++) {
properties->push_back(Var(properties_[i].name));
}
}
void ChromotingScriptableObject::SetProperty(const Var& name,
const Var& value,
Var* exception) {
// TODO(ajwong): Check if all these name.is_string() sentinels are required.
if (!name.is_string()) {
*exception = Var("SetProperty expects a string for the name.");
return;
}
// Allow writing to connectionInfoUpdate or loginChallenge. See top of
// chromoting_scriptable_object.h for the object interface definition.
std::string property_name = name.AsString();
if (property_name != kConnectionInfoUpdate &&
property_name != kDebugInfoUpdate &&
property_name != kLoginChallenge &&
property_name != kDesktopWidth &&
property_name != kDesktopHeight) {
*exception =
Var("Cannot set property " + property_name + " on this object.");
return;
}
// Since we're whitelisting the propertie that are settable above, we can
// assume that the property exists in the map.
properties_[property_names_[property_name]].attribute = value;
}
Var ChromotingScriptableObject::Call(const Var& method_name,
const std::vector<Var>& args,
Var* exception) {
PropertyNameMap::const_iterator iter =
property_names_.find(method_name.AsString());
if (iter == property_names_.end()) {
return pp::deprecated::ScriptableObject::Call(method_name, args, exception);
}
return (this->*(properties_[iter->second].method))(args, exception);
}
void ChromotingScriptableObject::SetConnectionInfo(ConnectionStatus status,
ConnectionQuality quality) {
int status_index = property_names_[kStatusAttribute];
int quality_index = property_names_[kQualityAttribute];
if (properties_[status_index].attribute.AsInt() != status ||
properties_[quality_index].attribute.AsInt() != quality) {
// Update the connection state properties..
properties_[status_index].attribute = Var(status);
properties_[quality_index].attribute = Var(quality);
// Signal the Chromoting Tab UI to get the update connection state values.
SignalConnectionInfoChange();
}
}
void ChromotingScriptableObject::LogDebugInfo(const std::string& info) {
int debug_info_index = property_names_[kDebugInfoAttribute];
// Update the debug info string.
// Note that this only stores the most recent debug string.
properties_[debug_info_index].attribute = Var(info);
// Signal the client UI to get the updated debug info.
SignalDebugInfoChange();
}
void ChromotingScriptableObject::SetDesktopSize(int width, int height) {
int width_index = property_names_[kDesktopWidth];
int height_index = property_names_[kDesktopHeight];
if (properties_[width_index].attribute.AsInt() != width ||
properties_[height_index].attribute.AsInt() != height) {
properties_[width_index].attribute = Var(width);
properties_[height_index].attribute = Var(height);
}
}
void ChromotingScriptableObject::AddAttribute(const std::string& name,
Var attribute) {
property_names_[name] = properties_.size();
properties_.push_back(PropertyDescriptor(name, attribute));
}
void ChromotingScriptableObject::AddMethod(const std::string& name,
MethodHandler handler) {
property_names_[name] = properties_.size();
properties_.push_back(PropertyDescriptor(name, handler));
}
void ChromotingScriptableObject::SignalConnectionInfoChange() {
Var exception;
// The JavaScript callback function is the 'callback' property on the
// 'connectionInfoUpdate' object.
Var cb = GetProperty(Var(kConnectionInfoUpdate), &exception);
// Var() means call the object directly as a function rather than calling
// a method in the object.
cb.Call(Var(), 0, NULL, &exception);
if (!exception.is_undefined()) {
LOG(WARNING) << "Exception when invoking connectionInfoUpdate JS callback: "
<< exception.DebugString();
}
}
void ChromotingScriptableObject::SignalDebugInfoChange() {
Var exception;
// The JavaScript callback function is the 'callback' property on the
// 'debugInfoUpdate' object.
Var cb = GetProperty(Var(kDebugInfoUpdate), &exception);
// Var() means call the object directly as a function rather than calling
// a method in the object.
cb.Call(Var(), 0, NULL, &exception);
if (!exception.is_undefined()) {
LOG(WARNING) << "Exception when invoking debugInfoUpdate JS callback: "
<< exception.DebugString();
}
}
void ChromotingScriptableObject::SignalLoginChallenge() {
Var exception;
// The JavaScript callback function is the 'callback' property on the
// 'loginChallenge' object.
Var cb = GetProperty(Var(kLoginChallenge), &exception);
// Var() means call the object directly as a function rather than calling
// a method in the object.
cb.Call(Var(), 0, NULL, &exception);
if (!exception.is_undefined()) {
LOG(WARNING) << "Exception when invoking loginChallenge JS callback: "
<< exception.DebugString();
}
}
Var ChromotingScriptableObject::DoConnect(const std::vector<Var>& args,
Var* exception) {
if (args.size() != 3) {
*exception = Var("Usage: connect(username, host_jid, auth_token)");
return Var();
}
ClientConfig config;
if (!args[0].is_string()) {
*exception = Var("The username must be a string.");
return Var();
}
config.username = args[0].DebugString();
if (!args[1].is_string()) {
*exception = Var("The host_jid must be a string.");
return Var();
}
config.host_jid = args[1].AsString();
if (!args[2].is_string()) {
*exception = Var("The auth_token must be a string.");
return Var();
}
config.auth_token = args[2].AsString();
instance_->Connect(config);
return Var();
}
Var ChromotingScriptableObject::DoDisconnect(const std::vector<Var>& args,
Var* exception) {
instance_->Disconnect();
return Var();
}
Var ChromotingScriptableObject::DoSubmitLogin(const std::vector<Var>& args,
Var* exception) {
if (args.size() != 2) {
*exception = Var("Usage: login(username, password)");
return Var();
}
if (!args[0].is_string()) {
*exception = Var("Username must be a string.");
return Var();
}
std::string username = args[0].AsString();
if (!args[1].is_string()) {
*exception = Var("Password must be a string.");
return Var();
}
std::string password = args[1].AsString();
instance_->SubmitLoginInfo(username, password);
return Var();
}
} // namespace remoting
<|endoftext|> |
<commit_before>#include "viewerbase.h"
#include "ui_viewerbase.h"
#include <QCloseEvent>
#include <QToolBar>
#include <QComboBox>
#include <QLabel>
#include <QDebug>
#include <QScrollArea>
#include "applesoftfileviewer.h"
#include "hexdumpviewer.h"
#include "texthexdumpviewer.h"
#include "charsetviewer.h"
#include "hiresviewwidget.h"
#include "disassemblerviewer.h"
#include "textfile.h"
#include "mazeviewer.h"
ViewerBase::ViewerBase(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::ViewerBase)
{
// setMinimumWidth(1024);
m_stack = new QStackedWidget(this);
ui->setupUi(this);
// QScrollArea *scroller = new QScrollArea(this);
// scroller->setWidgetResizable(true);
// setCentralWidget(scroller);
// scroller->setWidget(m_stack);
setCentralWidget(m_stack);
m_toolbar = new QToolBar(this);
addToolBar(m_toolbar);
QLabel *label = new QLabel("View With: ");
m_toolbar->addWidget(label);
m_viewercombo = new QComboBox(m_toolbar);
m_toolbar->addWidget(m_viewercombo);
m_optionMenu = new QMenu("&Viewer");
menuBar()->addMenu(m_optionMenu);
m_optionMenu->setEnabled(false);
}
ViewerBase::~ViewerBase()
{
delete ui;
}
void ViewerBase::setFile(GenericFile *file)
{
m_file = file;
QString descriptor;
HexDumpViewer *hdv = new HexDumpViewer(0);
hdv->setFile(file);
descriptor = ("Hex Dump Viewer");
addViewer(descriptor,hdv);
if (dynamic_cast<ApplesoftFile*>(file))
{
ApplesoftFileViewer *afv = new ApplesoftFileViewer(0);
afv->setFile(file);
descriptor="Applesoft File Viewer";
addViewer(descriptor,afv);
showViewer(descriptor);
}
else if (dynamic_cast<BinaryFile*>(file))
{
BinaryFile *bf = dynamic_cast<BinaryFile*>(file);
CharSetViewer *csv = new CharSetViewer();
csv->setFile(bf);
descriptor ="HRCG Character Set Viewer";
addViewer(descriptor,csv);
HiresViewWidget *hrvw = new HiresViewWidget();
hrvw->setFile(bf);
descriptor = "HiRes Image Viewer";
addViewer(descriptor,hrvw);
MazeViewer *mv = new MazeViewer();
mv->setFile(file);
descriptor = "MissingRing Maze Viewer";
addViewer(descriptor,mv);
DisassemblerViewer *dv = new DisassemblerViewer();
dv->setFile(bf);
descriptor = "Disassembler Viewer";
addViewer(descriptor,dv);
showViewer(descriptor);
}
else if (dynamic_cast<TextFile*>(file))
{
BinaryFile *bf = dynamic_cast<BinaryFile*>(file);
TextHexDumpViewer *thdv = new TextHexDumpViewer();
thdv->setFile(bf);
descriptor = QString("Text/Hex Dump Viewer");
addViewer(descriptor,thdv);
showViewer(descriptor);
}
else if (dynamic_cast<RelocatableFile*>(file))
{
DisassemblerViewer *dv = new DisassemblerViewer();
dv->setFile(file);
descriptor = "Relocatable Disassembler Viewer";
addViewer(descriptor,dv);
showViewer(descriptor);
}
else
{
showViewer(descriptor);
}
connect(m_viewercombo, SIGNAL(currentIndexChanged(QString)), SLOT(showViewer(QString)));
}
void ViewerBase::closeEvent(QCloseEvent *event)
{
event->accept();
}
void ViewerBase::addViewer(QString descriptor, FileViewerInterface *viewer)
{
if (!m_viewers.contains(descriptor))
{
m_stack->addWidget(viewer);
m_viewers[descriptor] = viewer;
m_viewercombo->addItem(descriptor);
}
}
void ViewerBase::showViewer(QString descriptor)
{
FileViewerInterface *fvi = m_viewers[descriptor];
if (fvi)
{
m_optionMenu->clear();
m_viewercombo->setCurrentText(descriptor);
m_stack->setCurrentWidget(fvi);
setWindowTitle(fvi->windowTitle());
if (m_optionMenu)
{
if (!fvi->optionsMenuItems(m_optionMenu))
{
m_optionMenu->setEnabled(false);
}
else
{
m_optionMenu->setEnabled(true);
}
}
}
else
{
qDebug() << "Could not find widget for descriptor " << descriptor;
}
}
<commit_msg>Added some default file type handling for viewer.<commit_after>#include "viewerbase.h"
#include "ui_viewerbase.h"
#include <QCloseEvent>
#include <QToolBar>
#include <QComboBox>
#include <QLabel>
#include <QDebug>
#include <QScrollArea>
#include "applesoftfileviewer.h"
#include "hexdumpviewer.h"
#include "texthexdumpviewer.h"
#include "charsetviewer.h"
#include "hiresviewwidget.h"
#include "disassemblerviewer.h"
#include "textfile.h"
#include "mazeviewer.h"
ViewerBase::ViewerBase(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::ViewerBase)
{
// setMinimumWidth(1024);
m_stack = new QStackedWidget(this);
ui->setupUi(this);
// QScrollArea *scroller = new QScrollArea(this);
// scroller->setWidgetResizable(true);
// setCentralWidget(scroller);
// scroller->setWidget(m_stack);
setCentralWidget(m_stack);
m_toolbar = new QToolBar(this);
addToolBar(m_toolbar);
QLabel *label = new QLabel("View With: ");
m_toolbar->addWidget(label);
m_viewercombo = new QComboBox(m_toolbar);
m_toolbar->addWidget(m_viewercombo);
m_optionMenu = new QMenu("&Viewer");
menuBar()->addMenu(m_optionMenu);
m_optionMenu->setEnabled(false);
}
ViewerBase::~ViewerBase()
{
delete ui;
}
void ViewerBase::setFile(GenericFile *file)
{
m_file = file;
QString descriptor;
QString defaultDescriptor;
HexDumpViewer *hdv = new HexDumpViewer(0);
hdv->setFile(file);
descriptor = ("Hex Dump Viewer");
addViewer(descriptor,hdv);
defaultDescriptor = descriptor;
if (dynamic_cast<ApplesoftFile*>(file))
{
ApplesoftFileViewer *afv = new ApplesoftFileViewer(0);
afv->setFile(file);
descriptor="Applesoft File Viewer";
addViewer(descriptor,afv);
defaultDescriptor = descriptor;
showViewer(descriptor);
}
else if (dynamic_cast<BinaryFile*>(file))
{
BinaryFile *bf = dynamic_cast<BinaryFile*>(file);
CharSetViewer *csv = new CharSetViewer();
csv->setFile(bf);
descriptor ="HRCG Character Set Viewer";
addViewer(descriptor,csv);
HiresViewWidget *hrvw = new HiresViewWidget();
hrvw->setFile(bf);
descriptor = "HiRes Image Viewer";
addViewer(descriptor,hrvw);
MazeViewer *mv = new MazeViewer();
mv->setFile(file);
descriptor = "MissingRing Maze Viewer";
addViewer(descriptor,mv);
DisassemblerViewer *dv = new DisassemblerViewer();
dv->setFile(bf);
descriptor = "Disassembler Viewer";
addViewer(descriptor,dv);
defaultDescriptor = descriptor;
if (bf->filename().toUpper().endsWith(".SET"))
{
defaultDescriptor ="HRCG Character Set Viewer";
}
if (bf->filename().toUpper().startsWith("MAZE"))
{
defaultDescriptor = "MissingRing Maze Viewer";
}
if ((bf->address() == 0x2000 || bf->address() == 0x4000)
&& bf->length() == 0x2000)
{
defaultDescriptor = "HiRes Image Viewer";
}
}
else if (dynamic_cast<TextFile*>(file))
{
BinaryFile *bf = dynamic_cast<BinaryFile*>(file);
TextHexDumpViewer *thdv = new TextHexDumpViewer();
thdv->setFile(bf);
descriptor = QString("Text/Hex Dump Viewer");
addViewer(descriptor,thdv);
defaultDescriptor = descriptor;
}
else if (dynamic_cast<RelocatableFile*>(file))
{
DisassemblerViewer *dv = new DisassemblerViewer();
dv->setFile(file);
descriptor = "Relocatable Disassembler Viewer";
addViewer(descriptor,dv);
defaultDescriptor = descriptor;
}
connect(m_viewercombo, SIGNAL(currentIndexChanged(QString)), SLOT(showViewer(QString)));
showViewer(defaultDescriptor);
}
void ViewerBase::closeEvent(QCloseEvent *event)
{
event->accept();
}
void ViewerBase::addViewer(QString descriptor, FileViewerInterface *viewer)
{
if (!m_viewers.contains(descriptor))
{
m_stack->addWidget(viewer);
m_viewers[descriptor] = viewer;
m_viewercombo->addItem(descriptor);
}
}
void ViewerBase::showViewer(QString descriptor)
{
FileViewerInterface *fvi = m_viewers[descriptor];
if (fvi)
{
m_optionMenu->clear();
m_viewercombo->setCurrentText(descriptor);
m_stack->setCurrentWidget(fvi);
setWindowTitle(fvi->windowTitle());
if (m_optionMenu)
{
if (!fvi->optionsMenuItems(m_optionMenu))
{
m_optionMenu->setEnabled(false);
}
else
{
m_optionMenu->setEnabled(true);
}
}
}
else
{
qDebug() << "Could not find widget for descriptor " << descriptor;
}
}
<|endoftext|> |
<commit_before>// Macro for testing the new C++ reconstruction code
// Arguments:
// FirstEvent (default 0)
// LastEvent (default 0)
// RecGeantHits (1 to reconstruct GEANT hits) (default 0)
// FileName (for signal) (default "galice.root")
// BkgGeantFileName (for background),
// needed only if RecGeantHits = 1 and background to be added
void MUONreco (Int_t FirstEvent = 0, Int_t LastEvent = 0, Int_t RecGeantHits = 0, Text_t *FileName = "galice.root", Text_t *BkgGeantFileName = "")
{
//
cout << "MUONtest_reco" << endl;
cout << "FirstEvent " << FirstEvent << endl;
cout << "LastEvent " << LastEvent << endl;
cout << "RecGeantHits " << RecGeantHits << endl;
cout << "FileName ``" << FileName << "''" << endl;
cout << "BkgGeantFileName ``" << BkgGeantFileName << "''" << endl;
// Dynamically link some shared libs
if (gClassTable->GetID("AliRun") < 0) {
gROOT->LoadMacro("loadlibs.C");
loadlibs();
}
// Connect the Root Galice file containing Geometry, Kine and Hits
TFile *file = (TFile*) gROOT->GetListOfFiles()->FindObject(FileName);
if (!file) {
printf("\n Creating file %s\n", FileName);
file = new TFile(FileName);
}
else printf("\n File %s found in file list\n", FileName);
// Get AliRun object from file or create it if not on file
if (!gAlice) {
gAlice = (AliRun*) file->Get("gAlice");
if (gAlice) printf("AliRun object found on file\n");
if (!gAlice) {
printf("\n Create new gAlice object");
gAlice = new AliRun("gAlice","Alice test program");
}
}
// Initializations
// AliMUON *MUON = (AliMUON*) gAlice->GetModule("MUON"); // necessary ????
AliMUONEventReconstructor *Reco = new AliMUONEventReconstructor();
Reco->SetRecGeantHits(RecGeantHits);
// The right place for changing AliMUONEventReconstructor parameters
// with respect to the default ones
// Reco->SetMaxSigma2Distance(100.0);
Reco->SetPrintLevel(10);
cout << "AliMUONEventReconstructor: actual parameters" << endl;
Reco->Dump();
// Loop over events
for (Int_t event = FirstEvent; event <= LastEvent; event++) {
cout << "Event: " << event << endl;
AliMUON *MUON = (AliMUON*) gAlice->GetModule("MUON"); // necessary ????
Int_t nparticles = gAlice->GetEvent(event);
cout << "nparticles: " << nparticles << endl;
// prepare background file and/or event if necessary
if (RecGeantHits == 1) {
if (event == FirstEvent) Reco->SetBkgGeantFile(BkgGeantFileName);
if (Reco->GetBkgGeantFile())Reco->NextBkgGeantEvent();
}
Reco->EventReconstruct();
// Dump current event
Reco->EventDump();
} // Event loop
}
<commit_msg>Updated comments<commit_after>// Macro MUONreco.C for testing the C++ reconstruction code
// Arguments:
// FirstEvent (default 0)
// LastEvent (default 0)
// RecGeantHits (1 to reconstruct GEANT hits) (default 0)
// FileName (for signal) (default "galice.root")
// BkgGeantFileName (for background),
// needed only if RecGeantHits = 1 and background to be added
void MUONreco (Int_t FirstEvent = 0, Int_t LastEvent = 0, Int_t RecGeantHits = 0, Text_t *FileName = "galice.root", Text_t *BkgGeantFileName = "")
{
//
cout << "MUONreco" << endl;
cout << "FirstEvent " << FirstEvent << endl;
cout << "LastEvent " << LastEvent << endl;
cout << "RecGeantHits " << RecGeantHits << endl;
cout << "FileName ``" << FileName << "''" << endl;
cout << "BkgGeantFileName ``" << BkgGeantFileName << "''" << endl;
// Dynamically link some shared libs
if (gClassTable->GetID("AliRun") < 0) {
gROOT->LoadMacro("loadlibs.C");
loadlibs();
}
// Connect the Root Galice file containing Geometry, Kine, Hits
// and eventually RawClusters
TFile *file = (TFile*) gROOT->GetListOfFiles()->FindObject(FileName);
if (!file) {
printf("\n Creating file %s\n", FileName);
file = new TFile(FileName);
}
else printf("\n File %s found in file list\n", FileName);
// Get AliRun object from file or create it if not on file
if (!gAlice) {
gAlice = (AliRun*) file->Get("gAlice");
if (gAlice) printf("AliRun object found on file\n");
if (!gAlice) {
printf("\n Create new gAlice object");
gAlice = new AliRun("gAlice","Alice test program");
}
}
// Initializations
// AliMUON *MUON = (AliMUON*) gAlice->GetModule("MUON"); // necessary ????
AliMUONEventReconstructor *Reco = new AliMUONEventReconstructor();
Reco->SetRecGeantHits(RecGeantHits);
// The right place for changing AliMUONEventReconstructor parameters
// with respect to the default ones
// Reco->SetMaxSigma2Distance(100.0);
Reco->SetPrintLevel(10);
cout << "AliMUONEventReconstructor: actual parameters" << endl;
Reco->Dump();
// Loop over events
for (Int_t event = FirstEvent; event <= LastEvent; event++) {
cout << "Event: " << event << endl;
AliMUON *MUON = (AliMUON*) gAlice->GetModule("MUON"); // necessary ????
Int_t nparticles = gAlice->GetEvent(event);
cout << "nparticles: " << nparticles << endl;
// prepare background file and/or event if necessary
if (RecGeantHits == 1) {
if (event == FirstEvent) Reco->SetBkgGeantFile(BkgGeantFileName);
if (Reco->GetBkgGeantFile())Reco->NextBkgGeantEvent();
}
Reco->EventReconstruct();
// Dump current event
Reco->EventDump();
} // Event loop
}
<|endoftext|> |
<commit_before>// two_sum.cpp: TwoSum evaluation of posit number systems
//
// Copyright (C) 2017-2019 Stillwater Supercomputing, Inc.
//
// This file is part of the UNIVERSAL project, which is released under an MIT Open Source license.
#define ALIASING_ALLOWED
#include "common.hpp"
#include "../tests/test_helpers.hpp"
#include "../tests/posit_test_helpers.hpp"
/*
floating point arithmetic:
- integers are represented exactly
- float(x - y) = x - y when x/2 <= y <= 2x: difference is represented exactly when two numbers are less than 2x of each other
- float(2x) = 2x barring overflow
- float(x/2) = x/2 barring underflow
TwoSum denotes an algorithm introduced by Knuth in "The Art of Computer Programming", vol 2, Seminumerical Algorithms.
Given two floating point values a and b, generate a rounded sum s and a remainder r, such that
s = RoundToNearest(a + b), and
a + b = s + r
*/
namespace sw {
namespace unum {
template<typename Scalar>
std::pair<Scalar, Scalar> twoSum2(const Scalar& a, const Scalar& b) {
Scalar s = a + b;
Scalar aApprox = s - b;
Scalar bApprox = s - aApprox;
Scalar aDiff = a - aApprox;
Scalar bDiff = b - bApprox;
Scalar r = aDiff + bDiff;
return std::pair<Scalar, Scalar>(s, r);
}
template<size_t nbits, size_t es>
std::pair< posit<nbits, es>, posit<nbits, es> > twoSum(const posit<nbits, es>& a, const posit<nbits, es>& b) {
if ((minpos<nbits, es>() == a && minpos<nbits, es>() == b) || (maxpos<nbits, es>() == a && maxpos<nbits, es>() == b)) {
return std::pair< posit<nbits, es>, posit<nbits, es> >(a, b);
}
using Scalar = posit<nbits, es>;
Scalar s = a + b;
Scalar aApprox = s - b;
Scalar bApprox = s - aApprox;
Scalar aDiff = a - aApprox;
Scalar bDiff = b - bApprox;
Scalar r = aDiff + bDiff;
return std::pair<Scalar, Scalar>(s, r);
}
}
}
template<size_t nbits, size_t es>
void ReportTwoSumError(std::string test_case, std::string op, const sw::unum::posit<nbits, es>& a, const sw::unum::posit<nbits, es>& b, const sw::unum::posit<nbits, es>& s, const sw::unum::posit<nbits, es>& r) {
std::cerr << test_case << " "
<< std::setw(nbits) << a.get()
<< " " << op << " "
<< std::setw(nbits) << b.get()
<< " != "
<< std::setw(nbits) << s.get()
<< " " << op << " "
<< std::setw(nbits) << r.get()
<< " instead it yielded "
<< std::setw(nbits) << (a + b).get()
<< " vs "
<< std::setw(nbits) << (s + r).get()
<< " : " << sw::unum::pretty_print(s + r)
<< std::endl;
}
template<typename Scalar>
bool GenerateTwoSumTestCase(const Scalar& a, const Scalar& b) {
constexpr size_t nbits = a.nbits;
Scalar s = a + b;
Scalar aApprox = s - b;
Scalar bApprox = s - aApprox;
Scalar aDiff = a - aApprox;
Scalar bDiff = b - bApprox;
Scalar r = aDiff + bDiff;
std::cout << "a : " << std::setw(nbits) << a.get() << " : " << a << std::endl;
std::cout << "b : " << std::setw(nbits) << b.get() << " : " << b << std::endl;
std::cout << "s : " << std::setw(nbits) << s.get() << " : " << s << std::endl;
std::cout << "aApprox = s - a : " << std::setw(nbits) << aApprox.get() << " : " << aApprox << std::endl;
std::cout << "bApprox = s - aApprox : " << std::setw(nbits) << bApprox.get() << " : " << bApprox << std::endl;
std::cout << "aDiff = a - aApprox : " << std::setw(nbits) << aDiff.get() << " : " << aDiff << std::endl;
std::cout << "bDiff = b - bApprox : " << std::setw(nbits) << bDiff.get() << " : " << bDiff << std::endl;
std::cout << "r = aDiff + bDiff : " << std::setw(nbits) << r.get() << " : " << r << std::endl;
std::cout << "s + r : " << std::setw(nbits) << (s + r).get() << " : " << (s + r) << std::endl;
std::cout << "a + b : " << std::setw(nbits) << (a + b).get() << " : " << (a + b) << std::endl;
Scalar a_and_b = a + b;
Scalar s_and_r = s + r;
return a_and_b == s_and_r;
}
// enumerate all addition cases for a posit configuration: is within 10sec till about nbits = 14
template<size_t nbits, size_t es>
int ValidateTwoSum(std::string tag, bool bReportIndividualTestCases) {
using namespace std;
const size_t NR_POSITS = (size_t(1) << nbits);
int nrOfFailedTests = 0;
using Posit = sw::unum::posit<nbits, es>;
Posit pa, pb, ps, pr, psum, pref;
pair<Posit, Posit> s_and_r;
double da, db;
for (size_t i = 0; i < NR_POSITS; i++) {
pa.set_raw_bits(i);
da = double(pa);
for (size_t j = 0; j < NR_POSITS; j++) {
pb.set_raw_bits(j);
db = double(pb);
s_and_r = sw::unum::twoSum(pa, pb);
ps = s_and_r.first;
pr = s_and_r.second;
pref = ps + pr;
psum = pa + pb;
if (psum != pref) {
nrOfFailedTests++;
if (bReportIndividualTestCases) ReportTwoSumError("FAIL", "+", pa, pb, ps, pr);
}
else {
//if (bReportIndividualTestCases) ReportBinaryArithmeticSuccess("PASS", "+", pa, pb, pref, psum);
}
}
}
return nrOfFailedTests;
}
#define MANUAL_TEST 1
int main(int argc, char** argv)
try {
using namespace std;
using namespace sw::unum;
// print detailed bit-level computational intermediate results
bool verbose = false;
int nrOfFailedTestCases = 0;
bool bReportIndividualTestCases = true;
std::string tag = "TwoSum failed: ";
// preserve the existing ostream precision
auto precision = cout.precision();
cout << setprecision(12);
cout << "Posit TwoSum validation" << endl;
#if MANUAL_TEST
/*
constexpr size_t nbits = 8;
constexpr size_t es = 1;
using Posit = posit<nbits, es>;
Posit a, b;
a = b = minpos<nbits, es>();
cout << "geometric rounding region\n";
cout << (GenerateTwoSumTestCase(a, b) ? "PASS\n" : "FAIL\n");
cout << (GenerateTwoSumTestCase(a, ++b) ? "PASS\n" : "FAIL\n");
cout << (GenerateTwoSumTestCase(++a, b) ? "PASS\n" : "FAIL\n");
cout << endl << "arithmetic rounding region\n";
a = 1.0;
b = 1.0;
++b;
cout << (GenerateTwoSumTestCase(a, b) ? "PASS\n" : "FAIL\n");
*/
nrOfFailedTestCases += ReportTestResult(ValidateTwoSum<8, 0>(tag, bReportIndividualTestCases), "posit<8,0>", "twoSum");
nrOfFailedTestCases += ReportTestResult(ValidateTwoSum<8, 1>(tag, bReportIndividualTestCases), "posit<8,1>", "twoSum");
nrOfFailedTestCases += ReportTestResult(ValidateTwoSum<8, 2>(tag, bReportIndividualTestCases), "posit<8,2>", "twoSum");
// nrOfFailedTestCases += ReportTestResult(ValidateTwoSum<8, 3>(tag, bReportIndividualTestCases), "posit<8,3>", "twoSum");
// nrOfFailedTestCases += ReportTestResult(ValidateTwoSum<8, 4>(tag, bReportIndividualTestCases), "posit<8,4>", "twoSum");
// nrOfFailedTestCases += ReportTestResult(ValidateTwoSum<8, 5>(tag, bReportIndividualTestCases), "posit<8,5>", "twoSum");
#else
nrOfFailedTestCases += ReportTestResult(ValidateTwoSum<2, 0>(tag, bReportIndividualTestCases), "posit<2,0>", "twoSum");
nrOfFailedTestCases += ReportTestResult(ValidateTwoSum<3, 0>(tag, bReportIndividualTestCases), "posit<3,0>", "twoSum");
nrOfFailedTestCases += ReportTestResult(ValidateTwoSum<3, 1>(tag, bReportIndividualTestCases), "posit<3,1>", "twoSum");
nrOfFailedTestCases += ReportTestResult(ValidateTwoSum<4, 0>(tag, bReportIndividualTestCases), "posit<4,0>", "twoSum");
nrOfFailedTestCases += ReportTestResult(ValidateTwoSum<4, 1>(tag, bReportIndividualTestCases), "posit<4,1>", "twoSum");
nrOfFailedTestCases += ReportTestResult(ValidateTwoSum<4, 2>(tag, bReportIndividualTestCases), "posit<4,2>", "twoSum");
nrOfFailedTestCases += ReportTestResult(ValidateTwoSum<5, 0>(tag, bReportIndividualTestCases), "posit<5,0>", "twoSum");
nrOfFailedTestCases += ReportTestResult(ValidateTwoSum<5, 1>(tag, bReportIndividualTestCases), "posit<5,1>", "twoSum");
nrOfFailedTestCases += ReportTestResult(ValidateTwoSum<5, 2>(tag, bReportIndividualTestCases), "posit<5,2>", "twoSum");
nrOfFailedTestCases += ReportTestResult(ValidateTwoSum<5, 3>(tag, bReportIndividualTestCases), "posit<5,3>", "twoSum");
nrOfFailedTestCases += ReportTestResult(ValidateTwoSum<6, 0>(tag, bReportIndividualTestCases), "posit<6,0>", "twoSum");
nrOfFailedTestCases += ReportTestResult(ValidateTwoSum<6, 1>(tag, bReportIndividualTestCases), "posit<6,1>", "twoSum");
nrOfFailedTestCases += ReportTestResult(ValidateTwoSum<6, 2>(tag, bReportIndividualTestCases), "posit<6,2>", "twoSum");
nrOfFailedTestCases += ReportTestResult(ValidateTwoSum<6, 3>(tag, bReportIndividualTestCases), "posit<6,3>", "twoSum");
nrOfFailedTestCases += ReportTestResult(ValidateTwoSum<6, 4>(tag, bReportIndividualTestCases), "posit<6,4>", "twoSum");
#endif MANUAL_TEST
// restore the previous ostream precision
cout << setprecision(precision);
return EXIT_SUCCESS;
}
catch (char const* msg) {
std::cerr << msg << std::endl;
return EXIT_FAILURE;
}
catch (const posit_arithmetic_exception& err) {
std::cerr << "Uncaught posit arithmetic exception: " << err.what() << std::endl;
return EXIT_FAILURE;
}
catch (const quire_exception& err) {
std::cerr << "Uncaught quire exception: " << err.what() << std::endl;
return EXIT_FAILURE;
}
catch (const posit_internal_exception& err) {
std::cerr << "Uncaught posit internal exception: " << err.what() << std::endl;
return EXIT_FAILURE;
}
catch (std::runtime_error& err) {
std::cerr << err.what() << std::endl;
return EXIT_FAILURE;
}
catch (...) {
std::cerr << "Caught unknown exception" << std::endl;
return EXIT_FAILURE;
}
<commit_msg>setting up test case generator to study geometric rounding region twoSum behavior<commit_after>// two_sum.cpp: TwoSum evaluation of posit number systems
//
// Copyright (C) 2017-2019 Stillwater Supercomputing, Inc.
//
// This file is part of the UNIVERSAL project, which is released under an MIT Open Source license.
#define ALIASING_ALLOWED
#include "common.hpp"
#include "../tests/test_helpers.hpp"
#include "../tests/posit_test_helpers.hpp"
/*
floating point arithmetic:
- integers are represented exactly
- float(x - y) = x - y when x/2 <= y <= 2x: difference is represented exactly when two numbers are less than 2x of each other
- float(2x) = 2x barring overflow
- float(x/2) = x/2 barring underflow
TwoSum denotes an algorithm introduced by Knuth in "The Art of Computer Programming", vol 2, Seminumerical Algorithms.
Given two floating point values a and b, generate a rounded sum s and a remainder r, such that
s = RoundToNearest(a + b), and
a + b = s + r
*/
namespace sw {
namespace unum {
template<typename Scalar>
std::pair<Scalar, Scalar> twoSum2(const Scalar& a, const Scalar& b) {
Scalar s = a + b;
Scalar aApprox = s - b;
Scalar bApprox = s - aApprox;
Scalar aDiff = a - aApprox;
Scalar bDiff = b - bApprox;
Scalar r = aDiff + bDiff;
return std::pair<Scalar, Scalar>(s, r);
}
template<size_t nbits, size_t es>
std::pair< posit<nbits, es>, posit<nbits, es> > twoSum(const posit<nbits, es>& a, const posit<nbits, es>& b) {
if ((minpos<nbits, es>() == a && minpos<nbits, es>() == b) || (maxpos<nbits, es>() == a && maxpos<nbits, es>() == b)) {
return std::pair< posit<nbits, es>, posit<nbits, es> >(a, b);
}
using Scalar = posit<nbits, es>;
Scalar s = a + b;
Scalar aApprox = s - b;
Scalar bApprox = s - aApprox;
Scalar aDiff = a - aApprox;
Scalar bDiff = b - bApprox;
Scalar r = aDiff + bDiff;
return std::pair<Scalar, Scalar>(s, r);
}
}
}
template<size_t nbits, size_t es>
void ReportTwoSumError(std::string test_case, std::string op, const sw::unum::posit<nbits, es>& a, const sw::unum::posit<nbits, es>& b, const sw::unum::posit<nbits, es>& s, const sw::unum::posit<nbits, es>& r) {
std::cerr << test_case << " "
<< std::setw(nbits) << a.get()
<< " " << op << " "
<< std::setw(nbits) << b.get()
<< " != "
<< std::setw(nbits) << s.get()
<< " " << op << " "
<< std::setw(nbits) << r.get()
<< " instead it yielded "
<< std::setw(nbits) << (a + b).get()
<< " vs "
<< std::setw(nbits) << (s + r).get()
<< " : " << sw::unum::pretty_print(s + r)
<< std::endl;
}
template<typename Scalar>
bool GenerateTwoSumTestCase(const Scalar& a, const Scalar& b) {
constexpr size_t nbits = a.nbits;
Scalar s = a + b;
Scalar aApprox = s - b;
Scalar bApprox = s - aApprox;
Scalar aDiff = a - aApprox;
Scalar bDiff = b - bApprox;
Scalar r = aDiff + bDiff;
std::cout << "a : " << std::setw(nbits) << a.get() << " : " << a << std::endl;
std::cout << "b : " << std::setw(nbits) << b.get() << " : " << b << std::endl;
std::cout << "s : " << std::setw(nbits) << s.get() << " : " << s << std::endl;
std::cout << "aApprox = s - a : " << std::setw(nbits) << aApprox.get() << " : " << aApprox << std::endl;
std::cout << "bApprox = s - aApprox : " << std::setw(nbits) << bApprox.get() << " : " << bApprox << std::endl;
std::cout << "aDiff = a - aApprox : " << std::setw(nbits) << aDiff.get() << " : " << aDiff << std::endl;
std::cout << "bDiff = b - bApprox : " << std::setw(nbits) << bDiff.get() << " : " << bDiff << std::endl;
std::cout << "r = aDiff + bDiff : " << std::setw(nbits) << r.get() << " : " << r << std::endl;
std::cout << "s + r : " << std::setw(nbits) << (s + r).get() << " : " << (s + r) << std::endl;
std::cout << "a + b : " << std::setw(nbits) << (a + b).get() << " : " << (a + b) << std::endl;
Scalar a_and_b = a + b;
Scalar s_and_r = s + r;
bool equal = (a_and_b == s_and_r);
std::cout << (equal ? " PASS\n" : " FAIL\n");
return equal;
}
// enumerate all addition cases for a posit configuration: is within 10sec till about nbits = 14
template<size_t nbits, size_t es>
int ValidateTwoSum(std::string tag, bool bReportIndividualTestCases) {
using namespace std;
const size_t NR_POSITS = (size_t(1) << nbits);
int nrOfFailedTests = 0;
using Posit = sw::unum::posit<nbits, es>;
Posit pa, pb, ps, pr, psum, pref;
pair<Posit, Posit> s_and_r;
double da, db;
for (size_t i = 0; i < NR_POSITS; i++) {
pa.set_raw_bits(i);
da = double(pa);
for (size_t j = 0; j < NR_POSITS; j++) {
pb.set_raw_bits(j);
db = double(pb);
s_and_r = sw::unum::twoSum(pa, pb);
ps = s_and_r.first;
pr = s_and_r.second;
pref = ps + pr;
psum = pa + pb;
if (psum != pref) {
nrOfFailedTests++;
if (bReportIndividualTestCases) ReportTwoSumError("FAIL", "+", pa, pb, ps, pr);
}
else {
//if (bReportIndividualTestCases) ReportBinaryArithmeticSuccess("PASS", "+", pa, pb, pref, psum);
}
}
}
return nrOfFailedTests;
}
#define MANUAL_TEST 1
int main(int argc, char** argv)
try {
using namespace std;
using namespace sw::unum;
// print detailed bit-level computational intermediate results
bool verbose = false;
int nrOfFailedTestCases = 0;
bool bReportIndividualTestCases = true;
std::string tag = "TwoSum failed: ";
// preserve the existing ostream precision
auto precision = cout.precision();
cout << setprecision(12);
cout << "Posit TwoSum validation" << endl;
#if MANUAL_TEST
constexpr size_t nbits = 8;
constexpr size_t es = 1;
using Posit = posit<nbits, es>;
Posit a, b;
a = b = minpos<nbits, es>();
cout << "geometric rounding region\n";
GenerateTwoSumTestCase(a, b);
GenerateTwoSumTestCase(-a, b);
GenerateTwoSumTestCase(a, -b);
GenerateTwoSumTestCase(-a, -b);
cout << endl << "arithmetic rounding region\n";
a = 1.0;
GenerateTwoSumTestCase(a, b);
GenerateTwoSumTestCase(-a, b);
b = 1.0;
GenerateTwoSumTestCase(a, b);
return 0;
nrOfFailedTestCases += ReportTestResult(ValidateTwoSum<8, 0>(tag, bReportIndividualTestCases), "posit<8,0>", "twoSum");
nrOfFailedTestCases += ReportTestResult(ValidateTwoSum<8, 1>(tag, bReportIndividualTestCases), "posit<8,1>", "twoSum");
nrOfFailedTestCases += ReportTestResult(ValidateTwoSum<8, 2>(tag, bReportIndividualTestCases), "posit<8,2>", "twoSum");
nrOfFailedTestCases += ReportTestResult(ValidateTwoSum<8, 3>(tag, bReportIndividualTestCases), "posit<8,3>", "twoSum");
nrOfFailedTestCases += ReportTestResult(ValidateTwoSum<8, 4>(tag, bReportIndividualTestCases), "posit<8,4>", "twoSum");
nrOfFailedTestCases += ReportTestResult(ValidateTwoSum<8, 5>(tag, bReportIndividualTestCases), "posit<8,5>", "twoSum");
#else
nrOfFailedTestCases += ReportTestResult(ValidateTwoSum<2, 0>(tag, bReportIndividualTestCases), "posit<2,0>", "twoSum");
nrOfFailedTestCases += ReportTestResult(ValidateTwoSum<3, 0>(tag, bReportIndividualTestCases), "posit<3,0>", "twoSum");
nrOfFailedTestCases += ReportTestResult(ValidateTwoSum<3, 1>(tag, bReportIndividualTestCases), "posit<3,1>", "twoSum");
nrOfFailedTestCases += ReportTestResult(ValidateTwoSum<4, 0>(tag, bReportIndividualTestCases), "posit<4,0>", "twoSum");
nrOfFailedTestCases += ReportTestResult(ValidateTwoSum<4, 1>(tag, bReportIndividualTestCases), "posit<4,1>", "twoSum");
nrOfFailedTestCases += ReportTestResult(ValidateTwoSum<4, 2>(tag, bReportIndividualTestCases), "posit<4,2>", "twoSum");
nrOfFailedTestCases += ReportTestResult(ValidateTwoSum<5, 0>(tag, bReportIndividualTestCases), "posit<5,0>", "twoSum");
nrOfFailedTestCases += ReportTestResult(ValidateTwoSum<5, 1>(tag, bReportIndividualTestCases), "posit<5,1>", "twoSum");
nrOfFailedTestCases += ReportTestResult(ValidateTwoSum<5, 2>(tag, bReportIndividualTestCases), "posit<5,2>", "twoSum");
nrOfFailedTestCases += ReportTestResult(ValidateTwoSum<5, 3>(tag, bReportIndividualTestCases), "posit<5,3>", "twoSum");
nrOfFailedTestCases += ReportTestResult(ValidateTwoSum<6, 0>(tag, bReportIndividualTestCases), "posit<6,0>", "twoSum");
nrOfFailedTestCases += ReportTestResult(ValidateTwoSum<6, 1>(tag, bReportIndividualTestCases), "posit<6,1>", "twoSum");
nrOfFailedTestCases += ReportTestResult(ValidateTwoSum<6, 2>(tag, bReportIndividualTestCases), "posit<6,2>", "twoSum");
nrOfFailedTestCases += ReportTestResult(ValidateTwoSum<6, 3>(tag, bReportIndividualTestCases), "posit<6,3>", "twoSum");
nrOfFailedTestCases += ReportTestResult(ValidateTwoSum<6, 4>(tag, bReportIndividualTestCases), "posit<6,4>", "twoSum");
#endif MANUAL_TEST
// restore the previous ostream precision
cout << setprecision(precision);
return EXIT_SUCCESS;
}
catch (char const* msg) {
std::cerr << msg << std::endl;
return EXIT_FAILURE;
}
catch (const posit_arithmetic_exception& err) {
std::cerr << "Uncaught posit arithmetic exception: " << err.what() << std::endl;
return EXIT_FAILURE;
}
catch (const quire_exception& err) {
std::cerr << "Uncaught quire exception: " << err.what() << std::endl;
return EXIT_FAILURE;
}
catch (const posit_internal_exception& err) {
std::cerr << "Uncaught posit internal exception: " << err.what() << std::endl;
return EXIT_FAILURE;
}
catch (std::runtime_error& err) {
std::cerr << err.what() << std::endl;
return EXIT_FAILURE;
}
catch (...) {
std::cerr << "Caught unknown exception" << std::endl;
return EXIT_FAILURE;
}
<|endoftext|> |
<commit_before>#include "ros/ros.h"
#include "std_msgs/Float32.h"
#include "std_msgs/Float64MultiArray.h"
#include "Robosub/HighLevelControl.h"
#include "SubMotorController/MotorMessage.h"
#include <string>
using namespace std;
#define LEFT_DRIVE_BIT 0x01
#define RIGHT_DRIVE_BIT 0x02
#define FRONT_DEPTH_BIT 0x04
#define REAR_DEPTH_BIT 0x08
#define FRONT_TURN_BIT 0x10
#define REAR_TURN_BIT 0x20
const double FORWARD_SPEED_CONST = .0000006;
const double FORWARD_DRAG_CONST = .99;
const double STRAF_SPEED_CONST = .0000004;
const double STRAF_DRAG_CONST = .98;
enum Mode {
MANUAL,
AUTOMATIC
};
const double Epsilon = .4;
Mode ForwardMode = MANUAL;
Mode StrafMode = MANUAL;
Mode TurnMode = MANUAL;
Mode DepthMode = MANUAL;
Mode YawMode = MANUAL;
Mode PitchMode = MANUAL;
double ForwardSpeed = 0;
double StrafSpeed = 0;
double TurnSpeed = 0;
double DepthSpeed = 0;
double YawSpeed = 0;
double PitchSpeed = 0;
double ForwardOffset = 0;
double StrafOffset = 0;
double TurnOffset = 0;
double DepthOffset = 0;
double YawOffset = 0;
double PitchOffset = 0;
double CurrentDepth = 0;
double CurrentYaw = 0;
double CurrentTurn = 0;
double CurrentPitch = 0;
double ForwardVelocity = 0;
double StrafVelocity = 0;
bool DepthInMotion = false;
ros::Publisher* motorPub;
void commandCallback(Robosub::HighLevelControl::ConstPtr msg) {
if(msg->Direction == "Forward" && msg->MotionType == "Offset") {
ForwardMode = AUTOMATIC;
ForwardOffset = msg->Value;
} else if (msg->Direction == "Forward" && msg->MotionType == "Manual") {
ForwardMode = MANUAL;
ForwardSpeed = msg->Value;
} else if(msg->Direction == "Turn" && msg->MotionType == "Offset") {
TurnMode = AUTOMATIC;
TurnOffset = msg->Value;
} else if (msg->Direction == "Turn" && msg->MotionType == "Manual") {
TurnMode = MANUAL;
TurnSpeed = msg->Value;
} else if(msg->Direction == "Straf" && msg->MotionType == "Offset") {
StrafMode = AUTOMATIC;
StrafOffset = msg->Value;
} else if (msg->Direction == "Straf" && msg->MotionType == "Manual") {
StrafMode = MANUAL;
StrafSpeed = msg->Value;
} else if(msg->Direction == "Depth" && msg->MotionType == "Offset") {
DepthMode = AUTOMATIC;
DepthOffset = msg->Value;
} else if (msg->Direction == "Depth" && msg->MotionType == "Manual") {
DepthMode = MANUAL;
DepthSpeed = msg->Value;
} else if(msg->Direction == "Yaw" && msg->MotionType == "Offset") {
YawMode = AUTOMATIC;
YawOffset = msg->Value;
} else if (msg->Direction == "Yaw" && msg->MotionType == "Manual") {
YawMode = MANUAL;
YawSpeed = msg->Value;
} else if(msg->Direction == "Pitch" && msg->MotionType == "Offset") {
PitchMode = AUTOMATIC;
PitchOffset = msg->Value;
} else if (msg->Direction == "Pitch" && msg->MotionType == "Manual") {
PitchMode = MANUAL;
PitchSpeed = msg->Value;
} else {
printf("Unknown Direction: %s and Mode: %s\n", msg->Direction.c_str(), msg->MotionType.c_str());
}
}
void sendMotorMessage(unsigned int mask, int FR, int FL, int TR, int TF, int DR, int DF) {
SubMotorController::MotorMessage msg;
msg.mask = mask;
msg.Left = FL;
msg.Right = FR;
msg.FrontDepth = DF;
msg.RearDepth = DR;
msg.FrontTurn = TF;
msg.RearTurn = TR;
motorPub->publish(msg);
}
void updateDepth(std_msgs::Float32::ConstPtr msg) {
DepthOffset = DepthOffset + CurrentDepth - msg->data;
CurrentDepth = msg->data;
// printf("DepthOffset = %f\n", DepthOffset);
}
void updateAttitude(const std_msgs::Float64MultiArray::ConstPtr msg) {
YawOffset = YawOffset + CurrentYaw - msg->data[0];
TurnOffset = TurnOffset + CurrentYaw - msg->data[0];
CurrentYaw = msg->data[0];
PitchOffset = PitchOffset + CurrentPitch - msg->data[1];
CurrentPitch = msg->data[1];
// printf("Turn Message = %lf\n", msg->data[0]);
}
void UpdateForwardVelocity() {
ForwardVelocity += ForwardSpeed * FORWARD_SPEED_CONST;
ForwardVelocity *= FORWARD_DRAG_CONST;
}
void UpdateStrafVelocity() {
StrafVelocity += StrafSpeed * STRAF_SPEED_CONST;
StrafVelocity *= STRAF_DRAG_CONST;
}
int sanatize(int speed) {
while(abs(speed) < 60)
speed *= 1.2;
if(speed > 255)
return 255;
if(speed < -255)
return -255;
return speed;
}
int CalcDepth() {
if(DepthMode == AUTOMATIC) {
double speed = DepthOffset / 1.5;
return sanatize(speed * 255.0);
} else {
return DepthSpeed;
}
}
int CalcTurn() {
if(TurnMode == AUTOMATIC) {
TurnSpeed = sanatize(TurnOffset / 8.0 * 255)/4;
}
return TurnSpeed;
}
int CalcStraf() {
if(StrafMode == AUTOMATIC) {
StrafOffset -= StrafVelocity;
StrafSpeed = sanatize(StrafOffset / .5 * 255.0);
}
return StrafSpeed;
}
int CalcPitch() {
if(PitchMode == AUTOMATIC) {
double speed = PitchOffset / 10;
return sanatize(speed * 255.0);
} else {
return PitchSpeed;
}
}
void ManageForwardThrusters() {
static int currentValueRight;
static int currentValueLeft;
UpdateForwardVelocity();
if(ForwardMode == AUTOMATIC) {
ForwardOffset -= ForwardVelocity;
// printf("forward offset = %f\n", ForwardOffset);
// printf("forward velocity = %f\n", ForwardVelocity);
double speed = ForwardOffset / 1.5;
ForwardSpeed = sanatize(speed * 255.0);
}
if(currentValueLeft != ForwardSpeed ||
currentValueRight != ForwardSpeed) {
sendMotorMessage(LEFT_DRIVE_BIT | RIGHT_DRIVE_BIT,
ForwardSpeed, ForwardSpeed, 0, 0, 0, 0);
currentValueRight = ForwardSpeed;
currentValueLeft = ForwardSpeed;
}
}
void ManageTurnThrusters() {
static int currentValueRear;
static int currentValueFront;
int TurnThrust = CalcTurn();
int StrafThrust = CalcStraf();
int RearThrust = TurnThrust + StrafThrust;
int FrontThrust = TurnThrust - StrafThrust;
UpdateStrafVelocity();
RearThrust = sanatize(RearThrust);
FrontThrust = sanatize(FrontThrust);
if(RearThrust != currentValueRear ||
FrontThrust != currentValueFront) {
printf("%d %d\n", RearThrust, FrontThrust);
sendMotorMessage(REAR_TURN_BIT | FRONT_TURN_BIT,
0, 0, RearThrust, FrontThrust, 0, 0);
currentValueRear = RearThrust;
currentValueFront = FrontThrust;
}
}
void ManageDepthThrusters() {
static int currentValueRear;
static int currentValueFront;
int DepthThrust = CalcDepth();
int PitchThrust = CalcPitch();
int FrontThrust = DepthThrust + PitchThrust;
int RearThrust = DepthThrust - PitchThrust;
if(RearThrust != currentValueRear ||
FrontThrust != currentValueFront) {
sendMotorMessage(REAR_DEPTH_BIT | FRONT_DEPTH_BIT,
0, 0, 0, 0, RearThrust, FrontThrust);
currentValueRear = RearThrust;
currentValueFront = FrontThrust;
}
}
int main(int argc, char** argv) {
ros::init(argc, argv, "HighLevelControl");
ros::NodeHandle nh;
ros::Publisher motorPublisher = nh.advertise<SubMotorController::MotorMessage>("Motor_Control", 1);
motorPub = &motorPublisher;
ros::Subscriber DepthSub = nh.subscribe("Sub_Depth", 1, updateDepth);
ros::Subscriber AttitudeSub = nh.subscribe("IMU_Attitude", 1, updateAttitude);
ros::Subscriber CommandSub = nh.subscribe("High_Level_Motion", 1000, commandCallback);
while(ros::ok()) {
ManageForwardThrusters();
ManageTurnThrusters();
ManageDepthThrusters();
ros::spinOnce();
usleep(10000);
}
}
<commit_msg>Fixed reversed diving for center on point<commit_after>#include "ros/ros.h"
#include "std_msgs/Float32.h"
#include "std_msgs/Float64MultiArray.h"
#include "Robosub/HighLevelControl.h"
#include "Robosub/Point.h"
#include "SubMotorController/MotorMessage.h"
#include <string>
using namespace std;
#define LEFT_DRIVE_BIT 0x01
#define RIGHT_DRIVE_BIT 0x02
#define FRONT_DEPTH_BIT 0x04
#define REAR_DEPTH_BIT 0x08
#define FRONT_TURN_BIT 0x10
#define REAR_TURN_BIT 0x20
const double FORWARD_SPEED_CONST = .0000006;
const double FORWARD_DRAG_CONST = .99;
const double STRAF_SPEED_CONST = .0000004;
const double STRAF_DRAG_CONST = .98;
enum Mode {
MANUAL,
AUTOMATIC
};
const double Epsilon = .4;
Mode ForwardMode = MANUAL;
Mode StrafMode = MANUAL;
Mode TurnMode = MANUAL;
Mode DepthMode = MANUAL;
Mode YawMode = MANUAL;
Mode PitchMode = MANUAL;
double ForwardSpeed = 0;
double StrafSpeed = 0;
double TurnSpeed = 0;
double DepthSpeed = 0;
double YawSpeed = 0;
double PitchSpeed = 0;
double ForwardOffset = 0;
double StrafOffset = 0;
double TurnOffset = 0;
double DepthOffset = 0;
double YawOffset = 0;
double PitchOffset = 0;
double CurrentDepth = 0;
double CurrentYaw = 0;
double CurrentTurn = 0;
double CurrentPitch = 0;
double ForwardVelocity = 0;
double StrafVelocity = 0;
bool DepthInMotion = false;
ros::Publisher* motorPub;
void CenterOnPointCallback(Robosub::Point::ConstPtr msg) {
TurnMode = AUTOMATIC;
TurnOffset = msg->x * 60 / 1640;
DepthMode = AUTOMATIC;
DepthOffset = -msg->y / 80.0;
}
void commandCallback(Robosub::HighLevelControl::ConstPtr msg) {
if(msg->Direction == "Forward" && msg->MotionType == "Offset") {
ForwardMode = AUTOMATIC;
ForwardOffset = msg->Value;
} else if (msg->Direction == "Forward" && msg->MotionType == "Manual") {
ForwardMode = MANUAL;
ForwardSpeed = msg->Value;
} else if(msg->Direction == "Turn" && msg->MotionType == "Offset") {
TurnMode = AUTOMATIC;
TurnOffset = msg->Value;
} else if (msg->Direction == "Turn" && msg->MotionType == "Manual") {
TurnMode = MANUAL;
TurnSpeed = msg->Value;
} else if(msg->Direction == "Straf" && msg->MotionType == "Offset") {
StrafMode = AUTOMATIC;
StrafOffset = msg->Value;
} else if (msg->Direction == "Straf" && msg->MotionType == "Manual") {
StrafMode = MANUAL;
StrafSpeed = msg->Value;
} else if(msg->Direction == "Depth" && msg->MotionType == "Offset") {
DepthMode = AUTOMATIC;
DepthOffset = msg->Value;
} else if (msg->Direction == "Depth" && msg->MotionType == "Manual") {
DepthMode = MANUAL;
DepthSpeed = msg->Value;
} else if(msg->Direction == "Yaw" && msg->MotionType == "Offset") {
YawMode = AUTOMATIC;
YawOffset = msg->Value;
} else if (msg->Direction == "Yaw" && msg->MotionType == "Manual") {
YawMode = MANUAL;
YawSpeed = msg->Value;
} else if(msg->Direction == "Pitch" && msg->MotionType == "Offset") {
PitchMode = AUTOMATIC;
PitchOffset = msg->Value;
} else if (msg->Direction == "Pitch" && msg->MotionType == "Manual") {
PitchMode = MANUAL;
PitchSpeed = msg->Value;
} else {
printf("Unknown Direction: %s and Mode: %s\n", msg->Direction.c_str(), msg->MotionType.c_str());
}
}
void sendMotorMessage(unsigned int mask, int FR, int FL, int TR, int TF, int DR, int DF) {
SubMotorController::MotorMessage msg;
msg.mask = mask;
msg.Left = FL;
msg.Right = FR;
msg.FrontDepth = DF;
msg.RearDepth = DR;
msg.FrontTurn = TF;
msg.RearTurn = TR;
motorPub->publish(msg);
}
void updateDepth(std_msgs::Float32::ConstPtr msg) {
DepthOffset = DepthOffset + CurrentDepth - msg->data;
CurrentDepth = msg->data;
// printf("DepthOffset = %f\n", DepthOffset);
}
void updateAttitude(const std_msgs::Float64MultiArray::ConstPtr msg) {
YawOffset = YawOffset + CurrentYaw - msg->data[0];
TurnOffset = TurnOffset + CurrentYaw - msg->data[0];
CurrentYaw = msg->data[0];
PitchOffset = PitchOffset + CurrentPitch - msg->data[1];
CurrentPitch = msg->data[1];
// printf("Turn Message = %lf\n", msg->data[0]);
}
void UpdateForwardVelocity() {
ForwardVelocity += ForwardSpeed * FORWARD_SPEED_CONST;
ForwardVelocity *= FORWARD_DRAG_CONST;
}
void UpdateStrafVelocity() {
StrafVelocity += StrafSpeed * STRAF_SPEED_CONST;
StrafVelocity *= STRAF_DRAG_CONST;
}
int sanatize(int speed) {
if(speed > 0 && speed < 60)
speed = 40;
else if (speed < 0 && speed > -60)
speed = -40;
if(speed > 255)
return 255;
if(speed < -255)
return -255;
return speed;
}
int CalcDepth() {
if(DepthMode == AUTOMATIC) {
double speed = DepthOffset / 1.5;
return sanatize(speed * 255.0);
} else {
return DepthSpeed;
}
}
int CalcTurn() {
if(TurnMode == AUTOMATIC) {
TurnSpeed = sanatize(TurnOffset / 8.0 * 255)/2;
printf("Offset = %f Speed = %f\n", TurnOffset, TurnSpeed);
}
return TurnSpeed;
}
int CalcStraf() {
if(StrafMode == AUTOMATIC) {
StrafOffset -= StrafVelocity;
StrafSpeed = sanatize(StrafOffset / .5 * 255.0);
}
return StrafSpeed;
}
int CalcPitch() {
if(PitchMode == AUTOMATIC) {
double speed = PitchOffset / 10;
return sanatize(speed * 255.0);
} else {
return PitchSpeed;
}
}
void ManageForwardThrusters() {
static int currentValueRight;
static int currentValueLeft;
UpdateForwardVelocity();
if(ForwardMode == AUTOMATIC) {
ForwardOffset -= ForwardVelocity;
// printf("forward offset = %f\n", ForwardOffset);
// printf("forward velocity = %f\n", ForwardVelocity);
double speed = ForwardOffset / 1.5;
ForwardSpeed = sanatize(speed * 255.0);
}
if(currentValueLeft != ForwardSpeed ||
currentValueRight != ForwardSpeed) {
sendMotorMessage(LEFT_DRIVE_BIT | RIGHT_DRIVE_BIT,
ForwardSpeed, ForwardSpeed, 0, 0, 0, 0);
currentValueRight = ForwardSpeed;
currentValueLeft = ForwardSpeed;
}
}
void ManageTurnThrusters() {
static int currentValueRear;
static int currentValueFront;
int TurnThrust = CalcTurn();
int StrafThrust = CalcStraf();
int RearThrust = TurnThrust + StrafThrust;
int FrontThrust = TurnThrust - StrafThrust;
UpdateStrafVelocity();
RearThrust = sanatize(RearThrust);
FrontThrust = sanatize(FrontThrust);
if(RearThrust != currentValueRear ||
FrontThrust != currentValueFront) {
sendMotorMessage(REAR_TURN_BIT | FRONT_TURN_BIT,
0, 0, RearThrust, FrontThrust, 0, 0);
currentValueRear = RearThrust;
currentValueFront = FrontThrust;
}
}
void ManageDepthThrusters() {
static int currentValueRear;
static int currentValueFront;
int DepthThrust = CalcDepth();
int PitchThrust = CalcPitch();
int FrontThrust = DepthThrust + PitchThrust;
int RearThrust = DepthThrust - PitchThrust;
if(true || RearThrust != currentValueRear ||
FrontThrust != currentValueFront) {
printf("Depth %d %d\n", RearThrust, FrontThrust);
sendMotorMessage(REAR_DEPTH_BIT | FRONT_DEPTH_BIT,
0, 0, 0, 0, RearThrust, FrontThrust);
currentValueRear = RearThrust;
currentValueFront = FrontThrust;
}
}
int main(int argc, char** argv) {
ros::init(argc, argv, "HighLevelControl");
ros::NodeHandle nh;
ros::Publisher motorPublisher = nh.advertise<SubMotorController::MotorMessage>("Motor_Control", 1);
motorPub = &motorPublisher;
ros::Subscriber DepthSub = nh.subscribe("Sub_Depth", 1, updateDepth);
ros::Subscriber AttitudeSub = nh.subscribe("IMU_Attitude", 1, updateAttitude);
ros::Subscriber CommandSub = nh.subscribe("High_Level_Motion", 10, commandCallback);
ros::Subscriber PointSub = nh.subscribe("Center_On_Point", 10, CenterOnPointCallback);
while(ros::ok()) {
ManageForwardThrusters();
ManageTurnThrusters();
ManageDepthThrusters();
ros::spinOnce();
usleep(10000);
}
}
<|endoftext|> |
<commit_before>#include "ros/ros.h"
#include "std_msgs/Float32.h"
#include "std_msgs/Float32MultiArray.h"
#include "Robosub/HighLevelControl.h"
#include "Robosub/Point.h"
#include "SubMotorController/MotorMessage.h"
#include <string>
using namespace std;
#define LEFT_DRIVE_BIT 0x01
#define RIGHT_DRIVE_BIT 0x02
#define FRONT_DEPTH_BIT 0x04
#define REAR_DEPTH_BIT 0x08
#define FRONT_TURN_BIT 0x10
#define REAR_TURN_BIT 0x20
#define TARGET_ZERO -500
const double FORWARD_SPEED_CONST = .0000006;
const double FORWARD_DRAG_CONST = .99;
const double STRAF_SPEED_CONST = .0000004;
const double STRAF_DRAG_CONST = .98;
const double LEFT_FWD_MULT = 0.78;
const double REAR_TURN_MULT = .8928; //right
const double FRONT_TURN_MULT = .83; //left
double RIGHT_PIVOT_MULT = 1.0; //Multiplier to change the pivot point to be under the camera
double LEFT_PIVOT_MULT = 1.0;
enum Mode {
MANUAL,
AUTOMATIC
};
const double Epsilon = .4;
Mode ForwardMode = MANUAL;
Mode StrafeMode = MANUAL;
Mode TurnMode = MANUAL;
Mode DepthMode = MANUAL;
Mode YawMode = MANUAL;
Mode PitchMode = MANUAL;
Mode PivotMode = MANUAL;
//Speeds come from the controllers
int ForwardSpeed = 0;
int StrafeSpeed = 0;
int TurnSpeed = 0;
int DepthSpeed = 0;
int YawSpeed = 0;
int PitchSpeed = 0;
int PivotSpeed = 0;
//Commands come from the tasks
double ForwardCommand = 0;
double StrafeCommand = 0;
double TurnCommand = 0;
double DepthCommand = 0;
double YawCommand = 0;
double PitchCommand = 0;
double CurrentDepth = 0;
double CurrentYaw = 0;
double CurrentTurn = 0;
double CurrentPitch = 0;
double ForwardVelocity = 0;
double StrafeVelocity = 0;
//These store the last speeds sent to the motors
int currentFwdRight = 0;
int currentFwdLeft = 0;
int currentTurnRear = 0;
int currentTurnFront = 0;
int currentDepthRear = 0;
int currentDepthFront = 0;
int currentPivotRear = 0;
int currentPivotFront = 0;
bool DepthInMotion = false;
ros::Publisher motorPublisher;
ros::Publisher depthPublisher;
ros::Publisher headingPublisher;
void CenterOnPointCallback(Robosub::Point::ConstPtr msg) {
TurnMode = AUTOMATIC;
TurnCommand = msg->x * 60 / 940;
DepthMode = AUTOMATIC;
DepthCommand = (40 - msg->y) / 150.0;
}
int makeSpeed(float percent)
{
//The smallest output is 60
//The largets output is 255
//map from 100 to 255 and from 60 to 1 percent
if (fabs(percent)<0.01)
return 0;
int p = (percent) * (255-60);
return p>0?p+60:p-60;
//return (x - in_min) * (out_max - out_min) / (in_max - in_min) + out_min;
}
//Changed the previous word of Offset to Command
//Changed the name Straf to Strafe EVERYWHERE
//All the MANUAL inputs are [0,1]
/*
AUTOMATIC ("Command") inputs differ:
Forward: percentage [0,1];
Turn: angle [-180,180];
Strafe: percentage [0,1];
Depth: distance [0,14]ft;
Pitch: angle [-10,10];
*/
void commandCallback(Robosub::HighLevelControl::ConstPtr msg) {
if(msg->Direction == "Forward" && msg->MotionType == "Command") {
ForwardMode = AUTOMATIC;
ForwardCommand = msg->Value;
} else if (msg->Direction == "Forward" && msg->MotionType == "Manual") {
ForwardMode = MANUAL;
ForwardSpeed = makeSpeed(msg->Value);
} else if(msg->Direction == "Turn" && msg->MotionType == "Command") {
TurnMode = AUTOMATIC;
TurnCommand = msg->Value;
} else if (msg->Direction == "Turn" && msg->MotionType == "Manual") {
TurnMode = MANUAL;
TurnSpeed = makeSpeed(msg->Value);
} else if(msg->Direction == "Strafe" && msg->MotionType == "Command") {
StrafeMode = AUTOMATIC;
StrafeCommand = msg->Value;
} else if (msg->Direction == "Strafe" && msg->MotionType == "Manual") {
StrafeMode = MANUAL;
StrafeSpeed = makeSpeed(msg->Value);
} else if(msg->Direction == "Depth" && msg->MotionType == "Command") {
DepthMode = AUTOMATIC;
DepthCommand = msg->Value;
} else if (msg->Direction == "Depth" && msg->MotionType == "Manual") {
DepthMode = MANUAL;
DepthSpeed = makeSpeed(msg->Value);
} else if(msg->Direction == "Yaw" && msg->MotionType == "Command") {
YawMode = AUTOMATIC;
YawCommand = msg->Value;
} else if (msg->Direction == "Yaw" && msg->MotionType == "Manual") {
YawMode = MANUAL;
YawSpeed = makeSpeed(msg->Value);
} else if(msg->Direction == "Pitch" && msg->MotionType == "Command") {
PitchMode = AUTOMATIC;
PitchCommand = msg->Value;
} else if (msg->Direction == "Pitch" && msg->MotionType == "Manual") {
PitchMode = MANUAL;
PitchSpeed = makeSpeed(msg->Value);
/*} else if(msg->Direction == "Pivot" && msg->MotionType == "Command") {
PitchMode = AUTOMATIC;
PitchCommand = msg->Value;*/
} else if (msg->Direction == "Pivot" && msg->MotionType == "Manual") {
PivotMode = MANUAL;
PivotSpeed = makeSpeed(msg->Value);
} else {
printf("Unknown Direction: %s and Mode: %s\n", msg->Direction.c_str(), msg->MotionType.c_str());
}
}
void sendMotorMessage(unsigned int mask, int FR, int FL, int TR, int TF, int DR, int DF) {
SubMotorController::MotorMessage msg;
msg.mask = mask;
msg.Left = FL;
msg.Right = FR;
msg.FrontDepth = DF;
msg.RearDepth = DR;
msg.FrontTurn = TF;
msg.RearTurn = TR;
motorPublisher.publish(msg);
}
/*
void updateDepth(std_msgs::Float32::ConstPtr msg) {
DepthCommand = DepthCommand + CurrentDepth - msg->data;
CurrentDepth = msg->data;
// printf("DepthCommand = %f\n", DepthCommand);
}
void updateAttitude(const std_msgs::Float32MultiArray::ConstPtr msg) {
//This function is where controllers should go.
//It is called at 100MHz
//YAW
//Updates the yaw offset with the old value and the new value
// INPUT + ( ERROR )
YawCommand = YawCommand + CurrentYaw - msg->data[2]; //Yaw is now in [2]
TurnCommand = msg->data[2];
CurrentYaw = msg->data[2];
//PITCH
//Updates the yaw offset with the old value and the new value
// INPUT + ( ERROR )
PitchCommand = PitchCommand + CurrentPitch - msg->data[1];
CurrentPitch = msg->data[1];
// printf("Turn Message = %lf\n", msg->data[0]);
}
void UpdateForwardVelocity() {
//Seems to update a velocity memory by increasing based ont the speed constant
//and limiting using the drag constant
ForwardVelocity += ForwardSpeed * FORWARD_SPEED_CONST;
ForwardVelocity *= FORWARD_DRAG_CONST;
}
void UpdateStrafeVelocity() {
//Seems to update a velocity memory by increasing based ont the speed constant
//and limiting using the drag constant
StrafeVelocity += StrafeSpeed * STRAF_SPEED_CONST;
StrafeVelocity *= STRAF_DRAG_CONST;
}
*/
int sanitize(int speed) {
if(speed >=0 && speed < 60)
speed = 0;
else if (speed <0 && speed > -60)
speed = 0;
if(speed > 255)
return 255;
if(speed < -255)
return -255;
return speed;
}
void setDepth(float input){
std_msgs::Float32 msg;
msg.data = input;
depthPublisher.publish(msg);
}
void setHeading(float input){
std_msgs::Float32 msg;
msg.data = input;
headingPublisher.publish(msg);
}
void CalcTurn() {
//The input on AUTOMATIC is a heading in degrees
//The heading needs be converted to yaw degrees.
//Zero yaw starts when the IMU is powered, and
//with drift, it means heading of zero may change
//If AUTOMATIC, it sends the command to the Heading Controller
if(TurnMode == AUTOMATIC && TurnCommand != TARGET_ZERO) {
//Prepare and set Target_Heading and let the
//controller take care of it
setHeading(TurnCommand); //This sets TurnSpeed
TurnCommand = TARGET_ZERO;
//printf("Command = %f Speed = %i\n", TurnCommand, TurnSpeed);
}
}
void CalcStrafe() {
//Convert the percentage on AUTOMATIC to a speed
if(StrafeMode == AUTOMATIC) {
//Convert from percentage to speed
StrafeSpeed = makeSpeed(StrafeCommand);
}
}
void CalcDepth() {
if(DepthMode == AUTOMATIC && DepthCommand != TARGET_ZERO) {
//Prepare and set Target_Depth and let the
//controller take care of it
setDepth(DepthCommand);
DepthCommand = TARGET_ZERO;
}
}
void CalcPitch() {
if(PitchMode == AUTOMATIC) {
PitchSpeed = 0;
}
}
//Changed the AUTOMATIC behavior to accept a percentage
//Included a bias of 75% for the left thruster to minimize drift
void ManageForwardThrusters() {
//If AUTOMATIC, it converts from a percentage to a speed
//otherwise it uses the value sent from Manual
if(ForwardMode == AUTOMATIC) {
ForwardSpeed = makeSpeed(ForwardCommand);
}
ForwardSpeed = sanitize(ForwardSpeed);
if(currentFwdLeft != ForwardSpeed ||
currentFwdRight != ForwardSpeed) {
currentFwdLeft = LEFT_FWD_MULT*ForwardSpeed;
currentFwdRight = ForwardSpeed;
sendMotorMessage( RIGHT_DRIVE_BIT | LEFT_DRIVE_BIT,
currentFwdRight, currentFwdLeft, 0, 0, 0, 0);
}
}
void ManageTurnThrusters() {
//This two take the commmands (AUTOMATIC mode) and convert them to speed values
//Turning command
CalcTurn();
//Strafing command
CalcStrafe();
int RearThrust = TurnSpeed - StrafeSpeed;
int FrontThrust = TurnSpeed + StrafeSpeed;
RearThrust = sanitize(RearThrust);
FrontThrust = sanitize(FrontThrust);
if(RearThrust != currentTurnRear ||
FrontThrust != currentTurnFront) {
//Include multipliers to compensate for differences in the motor
//Strafe left: rear is faster than front
//When rear is <0 multiply front
//when front is <0 multiply rear
if (RearThrust<0){ //LEFT
currentTurnRear = RearThrust;
currentTurnFront = FrontThrust*FRONT_TURN_MULT;
}else if (FrontThrust<0){ //RIGHT
currentTurnRear = RearThrust*REAR_TURN_MULT;
currentTurnFront = FrontThrust;
}else{
currentTurnRear = RearThrust;
currentTurnFront = FrontThrust;
}
sendMotorMessage(REAR_TURN_BIT | FRONT_TURN_BIT,
0, 0, currentTurnRear, currentTurnFront, 0, 0);
//left rear <0
//right front <0
}
}
void ManageDepthThrusters() {
CalcDepth();
CalcPitch(); //Should be zero until the controller is written
int FrontThrust = DepthSpeed + PitchSpeed;
int RearThrust = DepthSpeed - PitchSpeed;
if(RearThrust != currentDepthRear ||
FrontThrust != currentDepthFront) {
//Include multipliers to compensate for differences in the motors
currentDepthRear = RearThrust;
currentDepthFront = FrontThrust;
sendMotorMessage(REAR_DEPTH_BIT | FRONT_DEPTH_BIT,
0, 0, 0, 0, RearThrust, FrontThrust);
}
}
void ManagePivotThrusters(){
int FrontThrust = PivotSpeed; //Choose which stays.
int RearThrust = PivotSpeed;
if(RearThrust != currentPivotRear ||
FrontThrust != currentPivotFront) {
//Include multipliers to compensate for differences in the motors
//currentPivotRear = RearThrust;
//currentPivotFront = FrontThrust;
if (RearThrust<0){ //LEFT
currentPivotRear = RearThrust;
currentPivotFront = FrontThrust*RIGHT_PIVOT_MULT;
}else if (FrontThrust<0){ //RIGHT
currentPivotRear = RearThrust;
currentPivotFront = FrontThrust*LEFT_PIVOT_MULT;
}
sendMotorMessage(REAR_TURN_BIT | FRONT_TURN_BIT,
0, 0, currentPivotRear, currentPivotFront, 0, 0);
}
}
int main(int argc, char** argv) {
ros::init(argc, argv, "HighLevelControl");
ros::NodeHandle nh;
if (argc>1){
RIGHT_PIVOT_MULT = strtod(argv[1], NULL);
}
if (argc>2){
LEFT_PIVOT_MULT = strtod(argv[2], NULL);
}
motorPublisher = nh.advertise<SubMotorController::MotorMessage>("Motor_Control", 100);//Should this be 10?
depthPublisher = nh.advertise<std_msgs::Float32>("Target_Depth", 10);
headingPublisher = nh.advertise<std_msgs::Float32>("Target_Heading", 10);
//ros::Subscriber DepthSub = nh.subscribe("Sub_Depth", 1, updateDepth);
//ros::Subscriber AttitudeSub = nh.subscribe("IMU_Attitude", 1, updateAttitude);
ros::Subscriber CommandSub = nh.subscribe("High_Level_Motion", 100, commandCallback);
ros::Subscriber PointSub = nh.subscribe("Center_On_Point", 10, CenterOnPointCallback);
while(ros::ok()) {
ManageForwardThrusters();
ManageTurnThrusters();
ManageDepthThrusters();
// ManagePivotThrusters();
//Could just prepare the currents on the Manage* and
//send one motor message.
ros::spinOnce();
usleep(10000);
}
}
<commit_msg>Forgot to actually include the change to this file in my last commit. Whoops.<commit_after>#include "ros/ros.h"
#include "std_msgs/Float32.h"
#include "std_msgs/Float32MultiArray.h"
#include "Robosub/HighLevelControl.h"
#include "Robosub/Point.h"
#include "SubMotorController/MotorMessage.h"
#include <string>
using namespace std;
#define LEFT_DRIVE_BIT 0x01
#define RIGHT_DRIVE_BIT 0x02
#define FRONT_DEPTH_BIT 0x04
#define REAR_DEPTH_BIT 0x08
#define FRONT_TURN_BIT 0x10
#define REAR_TURN_BIT 0x20
#define TARGET_ZERO -500
const double FORWARD_SPEED_CONST = .0000006;
const double FORWARD_DRAG_CONST = .99;
const double STRAF_SPEED_CONST = .0000004;
const double STRAF_DRAG_CONST = .98;
const double LEFT_FWD_MULT = 1;//was 0.78
const double REAR_TURN_MULT = .8928; //right
const double FRONT_TURN_MULT = .83; //left
double RIGHT_PIVOT_MULT = 1.0; //Multiplier to change the pivot point to be under the camera
double LEFT_PIVOT_MULT = 1.0;
enum Mode {
MANUAL,
AUTOMATIC
};
const double Epsilon = .4;
Mode ForwardMode = MANUAL;
Mode StrafeMode = MANUAL;
Mode TurnMode = MANUAL;
Mode DepthMode = MANUAL;
Mode YawMode = MANUAL;
Mode PitchMode = MANUAL;
Mode PivotMode = MANUAL;
//Speeds come from the controllers
int ForwardSpeed = 0;
int StrafeSpeed = 0;
int TurnSpeed = 0;
int DepthSpeed = 0;
int YawSpeed = 0;
int PitchSpeed = 0;
int PivotSpeed = 0;
//Commands come from the tasks
double ForwardCommand = 0;
double StrafeCommand = 0;
double TurnCommand = 0;
double DepthCommand = 0;
double YawCommand = 0;
double PitchCommand = 0;
double CurrentDepth = 0;
double CurrentYaw = 0;
double CurrentTurn = 0;
double CurrentPitch = 0;
double ForwardVelocity = 0;
double StrafeVelocity = 0;
//These store the last speeds sent to the motors
int currentFwdRight = 0;
int currentFwdLeft = 0;
int currentTurnRear = 0;
int currentTurnFront = 0;
int currentDepthRear = 0;
int currentDepthFront = 0;
int currentPivotRear = 0;
int currentPivotFront = 0;
bool DepthInMotion = false;
ros::Publisher motorPublisher;
ros::Publisher depthPublisher;
ros::Publisher headingPublisher;
void CenterOnPointCallback(Robosub::Point::ConstPtr msg) {
TurnMode = AUTOMATIC;
TurnCommand = msg->x * 60 / 940;
DepthMode = AUTOMATIC;
DepthCommand = (40 - msg->y) / 150.0;
}
int makeSpeed(float percent)
{
//The smallest output is 60
//The largets output is 255
//map from 100 to 255 and from 60 to 1 percent
if (fabs(percent)<0.01)
return 0;
int p = (percent) * (255-60);
return p>0?p+60:p-60;
//return (x - in_min) * (out_max - out_min) / (in_max - in_min) + out_min;
}
//Changed the previous word of Offset to Command
//Changed the name Straf to Strafe EVERYWHERE
//All the MANUAL inputs are [0,1]
/*
AUTOMATIC ("Command") inputs differ:
Forward: percentage [0,1];
Turn: angle [-180,180];
Strafe: percentage [0,1];
Depth: distance [0,14]ft;
Pitch: angle [-10,10];
*/
void commandCallback(Robosub::HighLevelControl::ConstPtr msg) {
if(msg->Direction == "Forward" && msg->MotionType == "Command") {
ForwardMode = AUTOMATIC;
ForwardCommand = msg->Value;
} else if (msg->Direction == "Forward" && msg->MotionType == "Manual") {
ForwardMode = MANUAL;
ForwardSpeed = makeSpeed(msg->Value);
} else if(msg->Direction == "Turn" && msg->MotionType == "Command") {
TurnMode = AUTOMATIC;
TurnCommand = msg->Value;
} else if (msg->Direction == "Turn" && msg->MotionType == "Manual") {
TurnMode = MANUAL;
TurnSpeed = makeSpeed(msg->Value);
} else if(msg->Direction == "Strafe" && msg->MotionType == "Command") {
StrafeMode = AUTOMATIC;
StrafeCommand = msg->Value;
} else if (msg->Direction == "Strafe" && msg->MotionType == "Manual") {
StrafeMode = MANUAL;
StrafeSpeed = makeSpeed(msg->Value);
} else if(msg->Direction == "Depth" && msg->MotionType == "Command") {
DepthMode = AUTOMATIC;
DepthCommand = msg->Value;
} else if (msg->Direction == "Depth" && msg->MotionType == "Manual") {
DepthMode = MANUAL;
DepthSpeed = makeSpeed(msg->Value);
} else if(msg->Direction == "Yaw" && msg->MotionType == "Command") {
YawMode = AUTOMATIC;
YawCommand = msg->Value;
} else if (msg->Direction == "Yaw" && msg->MotionType == "Manual") {
YawMode = MANUAL;
YawSpeed = makeSpeed(msg->Value);
} else if(msg->Direction == "Pitch" && msg->MotionType == "Command") {
PitchMode = AUTOMATIC;
PitchCommand = msg->Value;
} else if (msg->Direction == "Pitch" && msg->MotionType == "Manual") {
PitchMode = MANUAL;
PitchSpeed = makeSpeed(msg->Value);
/*} else if(msg->Direction == "Pivot" && msg->MotionType == "Command") {
PitchMode = AUTOMATIC;
PitchCommand = msg->Value;*/
} else if (msg->Direction == "Pivot" && msg->MotionType == "Manual") {
PivotMode = MANUAL;
PivotSpeed = makeSpeed(msg->Value);
} else {
printf("Unknown Direction: %s and Mode: %s\n", msg->Direction.c_str(), msg->MotionType.c_str());
}
}
void sendMotorMessage(unsigned int mask, int FR, int FL, int TR, int TF, int DR, int DF) {
SubMotorController::MotorMessage msg;
msg.mask = mask;
msg.Left = FL;
msg.Right = FR;
msg.FrontDepth = DF;
msg.RearDepth = DR;
msg.FrontTurn = TF;
msg.RearTurn = TR;
motorPublisher.publish(msg);
}
/*
void updateDepth(std_msgs::Float32::ConstPtr msg) {
DepthCommand = DepthCommand + CurrentDepth - msg->data;
CurrentDepth = msg->data;
// printf("DepthCommand = %f\n", DepthCommand);
}
void updateAttitude(const std_msgs::Float32MultiArray::ConstPtr msg) {
//This function is where controllers should go.
//It is called at 100MHz
//YAW
//Updates the yaw offset with the old value and the new value
// INPUT + ( ERROR )
YawCommand = YawCommand + CurrentYaw - msg->data[2]; //Yaw is now in [2]
TurnCommand = msg->data[2];
CurrentYaw = msg->data[2];
//PITCH
//Updates the yaw offset with the old value and the new value
// INPUT + ( ERROR )
PitchCommand = PitchCommand + CurrentPitch - msg->data[1];
CurrentPitch = msg->data[1];
// printf("Turn Message = %lf\n", msg->data[0]);
}
void UpdateForwardVelocity() {
//Seems to update a velocity memory by increasing based ont the speed constant
//and limiting using the drag constant
ForwardVelocity += ForwardSpeed * FORWARD_SPEED_CONST;
ForwardVelocity *= FORWARD_DRAG_CONST;
}
void UpdateStrafeVelocity() {
//Seems to update a velocity memory by increasing based ont the speed constant
//and limiting using the drag constant
StrafeVelocity += StrafeSpeed * STRAF_SPEED_CONST;
StrafeVelocity *= STRAF_DRAG_CONST;
}
*/
int sanitize(int speed) {
if(speed >=0 && speed < 60)
speed = 0;
else if (speed <0 && speed > -60)
speed = 0;
if(speed > 255)
return 255;
if(speed < -255)
return -255;
return speed;
}
void setDepth(float input){
std_msgs::Float32 msg;
msg.data = input;
depthPublisher.publish(msg);
}
void setHeading(float input){
std_msgs::Float32 msg;
msg.data = input;
headingPublisher.publish(msg);
}
void CalcTurn() {
//The input on AUTOMATIC is a heading in degrees
//The heading needs be converted to yaw degrees.
//Zero yaw starts when the IMU is powered, and
//with drift, it means heading of zero may change
//If AUTOMATIC, it sends the command to the Heading Controller
if(TurnMode == AUTOMATIC && TurnCommand != TARGET_ZERO) {
//Prepare and set Target_Heading and let the
//controller take care of it
setHeading(TurnCommand); //This sets TurnSpeed
TurnCommand = TARGET_ZERO;
//printf("Command = %f Speed = %i\n", TurnCommand, TurnSpeed);
}
}
void CalcStrafe() {
//Convert the percentage on AUTOMATIC to a speed
if(StrafeMode == AUTOMATIC) {
//Convert from percentage to speed
StrafeSpeed = makeSpeed(StrafeCommand);
}
}
void CalcDepth() {
if(DepthMode == AUTOMATIC && DepthCommand != TARGET_ZERO) {
//Prepare and set Target_Depth and let the
//controller take care of it
setDepth(DepthCommand);
DepthCommand = TARGET_ZERO;
}
}
void CalcPitch() {
if(PitchMode == AUTOMATIC) {
PitchSpeed = 0;
}
}
//Changed the AUTOMATIC behavior to accept a percentage
//Included a bias of 75% for the left thruster to minimize drift
void ManageForwardThrusters() {
//If AUTOMATIC, it converts from a percentage to a speed
//otherwise it uses the value sent from Manual
if(ForwardMode == AUTOMATIC) {
ForwardSpeed = makeSpeed(ForwardCommand);
}
ForwardSpeed = sanitize(ForwardSpeed);
if(currentFwdLeft != ForwardSpeed ||
currentFwdRight != ForwardSpeed) {
currentFwdLeft = LEFT_FWD_MULT*ForwardSpeed;
currentFwdRight = ForwardSpeed;
sendMotorMessage( RIGHT_DRIVE_BIT | LEFT_DRIVE_BIT,
currentFwdRight, currentFwdLeft, 0, 0, 0, 0);
}
}
void ManageTurnThrusters() {
//This two take the commmands (AUTOMATIC mode) and convert them to speed values
//Turning command
CalcTurn();
//Strafing command
CalcStrafe();
int RearThrust = TurnSpeed - StrafeSpeed;
int FrontThrust = TurnSpeed + StrafeSpeed;
RearThrust = sanitize(RearThrust);
FrontThrust = sanitize(FrontThrust);
if(RearThrust != currentTurnRear ||
FrontThrust != currentTurnFront) {
//Include multipliers to compensate for differences in the motor
//Strafe left: rear is faster than front
//When rear is <0 multiply front
//when front is <0 multiply rear
if (RearThrust<0){ //LEFT
currentTurnRear = RearThrust;
currentTurnFront = FrontThrust*FRONT_TURN_MULT;
}else if (FrontThrust<0){ //RIGHT
currentTurnRear = RearThrust*REAR_TURN_MULT;
currentTurnFront = FrontThrust;
}else{
currentTurnRear = RearThrust;
currentTurnFront = FrontThrust;
}
sendMotorMessage(REAR_TURN_BIT | FRONT_TURN_BIT,
0, 0, currentTurnRear, currentTurnFront, 0, 0);
//left rear <0
//right front <0
}
}
void ManageDepthThrusters() {
CalcDepth();
CalcPitch(); //Should be zero until the controller is written
int FrontThrust = DepthSpeed + PitchSpeed;
int RearThrust = DepthSpeed - PitchSpeed;
if(RearThrust != currentDepthRear ||
FrontThrust != currentDepthFront) {
//Include multipliers to compensate for differences in the motors
currentDepthRear = RearThrust;
currentDepthFront = FrontThrust;
sendMotorMessage(REAR_DEPTH_BIT | FRONT_DEPTH_BIT,
0, 0, 0, 0, RearThrust, FrontThrust);
}
}
void ManagePivotThrusters(){
int FrontThrust = PivotSpeed; //Choose which stays.
int RearThrust = PivotSpeed;
if(RearThrust != currentPivotRear ||
FrontThrust != currentPivotFront) {
//Include multipliers to compensate for differences in the motors
//currentPivotRear = RearThrust;
//currentPivotFront = FrontThrust;
if (RearThrust<0){ //LEFT
currentPivotRear = RearThrust;
currentPivotFront = FrontThrust*RIGHT_PIVOT_MULT;
}else if (FrontThrust<0){ //RIGHT
currentPivotRear = RearThrust;
currentPivotFront = FrontThrust*LEFT_PIVOT_MULT;
}
sendMotorMessage(REAR_TURN_BIT | FRONT_TURN_BIT,
0, 0, currentPivotRear, currentPivotFront, 0, 0);
}
}
int main(int argc, char** argv) {
ros::init(argc, argv, "HighLevelControl");
ros::NodeHandle nh;
if (argc>1){
RIGHT_PIVOT_MULT = strtod(argv[1], NULL);
}
if (argc>2){
LEFT_PIVOT_MULT = strtod(argv[2], NULL);
}
motorPublisher = nh.advertise<SubMotorController::MotorMessage>("Motor_Control", 100);//Should this be 10?
depthPublisher = nh.advertise<std_msgs::Float32>("Target_Depth", 10);
headingPublisher = nh.advertise<std_msgs::Float32>("Target_Heading", 10);
//ros::Subscriber DepthSub = nh.subscribe("Sub_Depth", 1, updateDepth);
//ros::Subscriber AttitudeSub = nh.subscribe("IMU_Attitude", 1, updateAttitude);
ros::Subscriber CommandSub = nh.subscribe("High_Level_Motion", 100, commandCallback);
ros::Subscriber PointSub = nh.subscribe("Center_On_Point", 10, CenterOnPointCallback);
while(ros::ok()) {
ManageForwardThrusters();
ManageTurnThrusters();
ManageDepthThrusters();
// ManagePivotThrusters();
//Could just prepare the currents on the Manage* and
//send one motor message.
ros::spinOnce();
usleep(10000);
}
}
<|endoftext|> |
<commit_before>#ifndef GUARD_import_from_nap_hpp
#define GUARD_import_from_nap_hpp
/** \file import_from_nap.hpp
*
* \brief Header containing code to enable import of data
* into a Phatbooks database, from csv files exported from
* the N. A. P. application.
*
* The code here is solely for the purpose of migrating the developer's
* (Matthew Harvey's) personal accounting data from his previous, prototype
* Python application, N. A. P., to Phatbooks. This should be removed from
* any released version of Phatbooks.
*/
#include "phatbooks_database_connection.hpp"
#include <boost/shared_ptr.hpp>
#include <boost/filesystem.hpp>
namespace phatbooks
{
/**
* Import data from a N. A. P. csv set.
*
* @todo Implement this method.
*
* @todo Adjust existing implementation to use new DraftJournal and
* OrdinaryJournal derived classes as appropriate.
*
* @throws std::logic_error if \c directory is not directory
*
* @throws std::runtime_error if \c directory does not contain the
* following csv files (exported from nap):\n
* "accountshelf.csv";\n
* "draftentryshelf.csv";\n
* "draftjournalshelf.csv";\n
* "entryshelf";\n
* "journalshelf";\n
*
* May throw various other exceptions, or crash wildly. This is not
* a polished function but intended as a quick hack only! See
* file documentation for import_from_nap.hpp.
*
* @todo The implementation of this function is hideously messy, slow,
* bulky, inefficient and repetitive. It doesn't need to be perfect as
* it's only a hack for my own use... but really...
*/
void import_from_nap
( boost::shared_ptr<PhatbooksDatabaseConnection> p_database_connection,
boost::filesystem::path const& directory
);
} // namespace phatbooks
#endif // GUARD_phatbooks_database_connection_hpp
<commit_msg>Minor edit to todos.<commit_after>#ifndef GUARD_import_from_nap_hpp
#define GUARD_import_from_nap_hpp
/** \file import_from_nap.hpp
*
* \brief Header containing code to enable import of data
* into a Phatbooks database, from csv files exported from
* the N. A. P. application.
*
* The code here is solely for the purpose of migrating the developer's
* (Matthew Harvey's) personal accounting data from his previous, prototype
* Python application, N. A. P., to Phatbooks. This should be removed from
* any released version of Phatbooks.
*/
#include "phatbooks_database_connection.hpp"
#include <boost/shared_ptr.hpp>
#include <boost/filesystem.hpp>
namespace phatbooks
{
/**
* Import data from a N. A. P. csv set.
*
* @todo Implement this method.
*
* @todo Adjust existing implementation to use new DraftJournal and
* OrdinaryJournal derived classes as appropriate.
*
* @throws std::logic_error if \c directory is not directory
*
* @throws std::runtime_error if \c directory does not contain the
* following csv files (exported from nap):\n
* "accountshelf.csv";\n
* "draftentryshelf.csv";\n
* "draftjournalshelf.csv";\n
* "entryshelf";\n
* "journalshelf";\n
*
* May throw various other exceptions, or crash wildly. This is not
* a polished function but intended as a quick hack only! See
* file documentation for import_from_nap.hpp.
*
* @todo The implementation of this function is hideously messy, slow,
* bulky, inefficient and repetitive. It doesn't need to be perfect as
* it's only a hack for my own use... but really...
*
* @todo I don't think the function currently reacts properly to
* entries where a SINGLE ENTRY has both actual and budget impacts.
*/
void import_from_nap
( boost::shared_ptr<PhatbooksDatabaseConnection> p_database_connection,
boost::filesystem::path const& directory
);
} // namespace phatbooks
#endif // GUARD_phatbooks_database_connection_hpp
<|endoftext|> |
<commit_before>// Copyright (c) 2010 The WebM project authors. All Rights Reserved.
//
// Use of this source code is governed by a BSD-style license
// that can be found in the LICENSE file in the root of the source
// tree. An additional intellectual property rights grant can be found
// in the file PATENTS. All contributing project authors may
// be found in the AUTHORS file in the root of the source tree.
#ifndef __WEBMDSHOW_COMMON_MEMUTIL_HPP__
#define __WEBMDSHOW_COMMON_MEMUTIL_HPP__
#include "debugutil.hpp"
namespace WebmUtil
{
template <typename BufferType>
class auto_array
{
public:
auto_array(BufferType* ptr_buf, size_t count) :
buffer_(ptr_buf),
num_elements_(count)
{
};
~auto_array()
{
if (buffer_)
{
delete[] buffer_;
buffer_ = NULL;
}
num_elements_ = 0;
};
BufferType* get() const
{
return buffer_;
};
BufferType* operator->() const
{
return get();
};
BufferType& operator*() const
{
return *get();
};
operator bool() const
{
return buffer_ != NULL;
};
operator BufferType*() const
{
return get();
};
size_t size() const
{
return num_elements_;
};
void reset(BufferType* ptr_buf, size_t count)
{
if (buffer_)
{
delete[] buffer_;
buffer_ = (BufferType)0;
}
num_elements_ = count;
buffer_ = ptr_buf;
};
private:
BufferType* buffer_;
size_t num_elements_;
DISALLOW_COPY_AND_ASSIGN(auto_array);
};
// |auto_ref_counted_obj_ptr|, an auto_ptr like class for managing ref counted
// object pointers.
template <typename RefCountedObject>
class auto_ref_counted_obj_ptr // this name seems a crime against humanity...
{
public:
auto_ref_counted_obj_ptr(RefCountedObject* ptr_obj) :
ptr_obj_(ptr_obj)
{
};
~auto_ref_counted_obj_ptr()
{
safe_rel(ptr_obj_);
};
// allow user to take ownership of encapsulated pointer
RefCountedObject* detach()
{
RefCountedObject* ptr_obj = ptr_obj_;
ptr_obj_ = NULL;
return ptr_obj;
};
RefCountedObject* get() const
{
return ptr_obj_;
};
// allow user to check pointer via 'if (ptr) ...'
operator bool() const
{
return ptr_obj_ != NULL;
};
// allow pass by value of encapsulated pointer
operator RefCountedObject* const()
{
return get();
};
// allow manipulation of object
RefCountedObject* operator->() const
{
return get();
};
RefCountedObject& operator*() const
{
return *get();
};
// allow user to pass us directly to ref counted object creation functions
RefCountedObject** operator&()
{
safe_rel(ptr_obj_);
return &ptr_obj_;
};
// release old and assign new obj ptr
void reset(RefCountedObject* ptr_obj)
{
safe_rel(ptr_obj_);
ptr_obj_ = ptr_obj;
};
private:
RefCountedObject* ptr_obj_;
DISALLOW_COPY_AND_ASSIGN(auto_ref_counted_obj_ptr);
};
template <typename COMOBJ>
ULONG safe_rel(COMOBJ*& comobj)
{
ULONG refcnt = 0;
if (comobj)
{
refcnt = comobj->Release();
comobj = NULL;
}
return refcnt;
}
} // WebmUtil namespace
#endif // __WEBMDSHOW_COMMON_MEMUTIL_HPP__<commit_msg>memutil: include basictypes instead of debugutil<commit_after>// Copyright (c) 2010 The WebM project authors. All Rights Reserved.
//
// Use of this source code is governed by a BSD-style license
// that can be found in the LICENSE file in the root of the source
// tree. An additional intellectual property rights grant can be found
// in the file PATENTS. All contributing project authors may
// be found in the AUTHORS file in the root of the source tree.
#ifndef __WEBMDSHOW_COMMON_MEMUTIL_HPP__
#define __WEBMDSHOW_COMMON_MEMUTIL_HPP__
#pragma once
#include "chromium/base/basictypes.h"
namespace WebmUtil
{
template <typename BufferType>
class auto_array
{
public:
auto_array(BufferType* ptr_buf, size_t count) :
buffer_(ptr_buf),
num_elements_(count)
{
};
~auto_array()
{
if (buffer_)
{
delete[] buffer_;
buffer_ = NULL;
}
num_elements_ = 0;
};
BufferType* get() const
{
return buffer_;
};
BufferType* operator->() const
{
return get();
};
BufferType& operator*() const
{
return *get();
};
operator bool() const
{
return buffer_ != NULL;
};
operator BufferType*() const
{
return get();
};
size_t size() const
{
return num_elements_;
};
void reset(BufferType* ptr_buf, size_t count)
{
if (buffer_)
{
delete[] buffer_;
buffer_ = (BufferType)0;
}
num_elements_ = count;
buffer_ = ptr_buf;
};
private:
BufferType* buffer_;
size_t num_elements_;
DISALLOW_COPY_AND_ASSIGN(auto_array);
};
// |auto_ref_counted_obj_ptr|, an auto_ptr like class for managing ref counted
// object pointers.
template <typename RefCountedObject>
class auto_ref_counted_obj_ptr // this name seems a crime against humanity...
{
public:
auto_ref_counted_obj_ptr(RefCountedObject* ptr_obj) :
ptr_obj_(ptr_obj)
{
};
~auto_ref_counted_obj_ptr()
{
safe_rel(ptr_obj_);
};
// allow user to take ownership of encapsulated pointer
RefCountedObject* detach()
{
RefCountedObject* ptr_obj = ptr_obj_;
ptr_obj_ = NULL;
return ptr_obj;
};
RefCountedObject* get() const
{
return ptr_obj_;
};
// allow user to check pointer via 'if (ptr) ...'
operator bool() const
{
return ptr_obj_ != NULL;
};
// allow pass by value of encapsulated pointer
operator RefCountedObject* const()
{
return get();
};
// allow manipulation of object
RefCountedObject* operator->() const
{
return get();
};
RefCountedObject& operator*() const
{
return *get();
};
// allow user to pass us directly to ref counted object creation functions
RefCountedObject** operator&()
{
safe_rel(ptr_obj_);
return &ptr_obj_;
};
// release old and assign new obj ptr
void reset(RefCountedObject* ptr_obj)
{
safe_rel(ptr_obj_);
ptr_obj_ = ptr_obj;
};
private:
RefCountedObject* ptr_obj_;
DISALLOW_COPY_AND_ASSIGN(auto_ref_counted_obj_ptr);
};
template <typename COMOBJ>
ULONG safe_rel(COMOBJ*& comobj)
{
ULONG refcnt = 0;
if (comobj)
{
refcnt = comobj->Release();
comobj = NULL;
}
return refcnt;
}
} // WebmUtil namespace
#endif // __WEBMDSHOW_COMMON_MEMUTIL_HPP__<|endoftext|> |
<commit_before>/* Copyright 2017 R. Thomas
* Copyright 2017 Quarkslab
*
* 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 LIEF_MACHO_BUILD_VERSION_COMMAND_H_
#define LIEF_MACHO_BUILD_VERSION_COMMAND_H_
#include <string>
#include <vector>
#include <iostream>
#include <array>
#include "LIEF/visibility.h"
#include "LIEF/types.hpp"
#include "LIEF/MachO/LoadCommand.hpp"
namespace LIEF {
namespace MachO {
class BuildToolVersion : public LIEF::Object {
public:
//! @brief Version is an array of **3** integers
using version_t = std::array<uint32_t, 3>;
public:
enum class TOOLS {
UNKNOWN = 0,
CLANG = 1,
SWIFT = 2,
LD = 3,
};
public:
BuildToolVersion(void);
BuildToolVersion(const build_tool_version& tool);
//! TOOL used
TOOLS tool(void) const;
//! Version associated with the tool
version_t version(void) const;
virtual ~BuildToolVersion(void);
bool operator==(const BuildToolVersion& rhs) const;
bool operator!=(const BuildToolVersion& rhs) const;
virtual void accept(Visitor& visitor) const override;
LIEF_API friend std::ostream& operator<<(std::ostream& os, const BuildToolVersion& tool);
private:
TOOLS tool_{TOOLS::UNKNOWN};
version_t version_;
};
class LIEF_API BuildVersion : public LoadCommand {
friend class BinaryParser;
public:
//! @brief Version is an array of **3** integers
using version_t = std::array<uint32_t, 3>;
using tools_list_t = std::vector<BuildToolVersion>;
public:
enum class PLATFORMS {
UNKNOWN = 0,
MACOS = 1,
IOS = 2,
TVOS = 3,
WATCHOS = 4,
};
public:
BuildVersion(void);
BuildVersion(const build_version_command *version_cmd);
BuildVersion& operator=(const BuildVersion& copy);
BuildVersion(const BuildVersion& copy);
virtual BuildVersion* clone(void) const override;
version_t minos(void) const;
void minos(version_t version);
version_t sdk(void) const;
void sdk(version_t version);
PLATFORMS platform(void) const;
void platform(PLATFORMS plat);
tools_list_t tools(void) const;
virtual ~BuildVersion(void);
bool operator==(const BuildVersion& rhs) const;
bool operator!=(const BuildVersion& rhs) const;
virtual void accept(Visitor& visitor) const override;
virtual std::ostream& print(std::ostream& os) const override;
private:
PLATFORMS platform_{PLATFORMS::UNKNOWN};
version_t minos_;
version_t sdk_;
tools_list_t tools_;
};
}
}
#endif
<commit_msg>Export BuildToolVersion<commit_after>/* Copyright 2017 R. Thomas
* Copyright 2017 Quarkslab
*
* 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 LIEF_MACHO_BUILD_VERSION_COMMAND_H_
#define LIEF_MACHO_BUILD_VERSION_COMMAND_H_
#include <string>
#include <vector>
#include <iostream>
#include <array>
#include "LIEF/visibility.h"
#include "LIEF/types.hpp"
#include "LIEF/MachO/LoadCommand.hpp"
namespace LIEF {
namespace MachO {
class LIEF_API BuildToolVersion : public LIEF::Object {
public:
//! @brief Version is an array of **3** integers
using version_t = std::array<uint32_t, 3>;
public:
enum class TOOLS {
UNKNOWN = 0,
CLANG = 1,
SWIFT = 2,
LD = 3,
};
public:
BuildToolVersion(void);
BuildToolVersion(const build_tool_version& tool);
//! TOOL used
TOOLS tool(void) const;
//! Version associated with the tool
version_t version(void) const;
virtual ~BuildToolVersion(void);
bool operator==(const BuildToolVersion& rhs) const;
bool operator!=(const BuildToolVersion& rhs) const;
virtual void accept(Visitor& visitor) const override;
LIEF_API friend std::ostream& operator<<(std::ostream& os, const BuildToolVersion& tool);
private:
TOOLS tool_{TOOLS::UNKNOWN};
version_t version_;
};
class LIEF_API BuildVersion : public LoadCommand {
friend class BinaryParser;
public:
//! @brief Version is an array of **3** integers
using version_t = std::array<uint32_t, 3>;
using tools_list_t = std::vector<BuildToolVersion>;
public:
enum class PLATFORMS {
UNKNOWN = 0,
MACOS = 1,
IOS = 2,
TVOS = 3,
WATCHOS = 4,
};
public:
BuildVersion(void);
BuildVersion(const build_version_command *version_cmd);
BuildVersion& operator=(const BuildVersion& copy);
BuildVersion(const BuildVersion& copy);
virtual BuildVersion* clone(void) const override;
version_t minos(void) const;
void minos(version_t version);
version_t sdk(void) const;
void sdk(version_t version);
PLATFORMS platform(void) const;
void platform(PLATFORMS plat);
tools_list_t tools(void) const;
virtual ~BuildVersion(void);
bool operator==(const BuildVersion& rhs) const;
bool operator!=(const BuildVersion& rhs) const;
virtual void accept(Visitor& visitor) const override;
virtual std::ostream& print(std::ostream& os) const override;
private:
PLATFORMS platform_{PLATFORMS::UNKNOWN};
version_t minos_;
version_t sdk_;
tools_list_t tools_;
};
}
}
#endif
<|endoftext|> |
<commit_before>/**********************************************************************
* File: tessedit.cpp (Formerly tessedit.c)
* Description: Main program for merge of tess and editor.
* Author: Ray Smith
* Created: Tue Jan 07 15:21:46 GMT 1992
*
* (C) Copyright 1992, Hewlett-Packard Ltd.
** Licensed under the Apache License, Version 2.0 (the "License");
** you may not use this file except in compliance with the License.
** You may obtain a copy of the License at
** http://www.apache.org/licenses/LICENSE-2.0
** Unless required by applicable law or agreed to in writing, software
** distributed under the License is distributed on an "AS IS" BASIS,
** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
** See the License for the specific language governing permissions and
** limitations under the License.
*
**********************************************************************/
// Include automatically generated configuration file if running autoconf
#ifdef HAVE_CONFIG_H
#include "config_auto.h"
#endif
#ifdef _WIN32
#include <fcntl.h>
#include <io.h>
#endif // _WIN32
#include <iostream>
#include "allheaders.h"
#include "baseapi.h"
#include "basedir.h"
#include "renderer.h"
#include "strngs.h"
#include "tprintf.h"
#include "openclwrapper.h"
/**********************************************************************
* main()
*
**********************************************************************/
int main(int argc, char **argv) {
if ((argc == 2 && strcmp(argv[1], "-v") == 0) ||
(argc == 2 && strcmp(argv[1], "--version") == 0)) {
char *versionStrP;
fprintf(stderr, "tesseract %s\n", tesseract::TessBaseAPI::Version());
versionStrP = getLeptonicaVersion();
fprintf(stderr, " %s\n", versionStrP);
lept_free(versionStrP);
versionStrP = getImagelibVersions();
fprintf(stderr, " %s\n", versionStrP);
lept_free(versionStrP);
#ifdef USE_OPENCL
cl_platform_id platform;
cl_uint num_platforms;
cl_device_id devices[2];
cl_uint num_devices;
char info[256];
int i;
fprintf(stderr, " OpenCL info:\n");
clGetPlatformIDs(1, &platform, &num_platforms);
fprintf(stderr, " Found %d platforms.\n", num_platforms);
clGetPlatformInfo(platform, CL_PLATFORM_NAME, 256, info, 0);
fprintf(stderr, " Platform name: %s.\n", info);
clGetPlatformInfo(platform, CL_PLATFORM_VERSION, 256, info, 0);
fprintf(stderr, " Version: %s.\n", info);
clGetDeviceIDs(platform, CL_DEVICE_TYPE_ALL, 2, devices, &num_devices);
fprintf(stderr, " Found %d devices.\n", num_devices);
for (i = 0; i < num_devices; ++i) {
clGetDeviceInfo(devices[i], CL_DEVICE_NAME, 256, info, 0);
fprintf(stderr, " Device %d name: %s.\n", i+1, info);
}
#endif
exit(0);
}
// Make the order of args a bit more forgiving than it used to be.
const char* lang = "eng";
const char* image = NULL;
const char* output = NULL;
const char* datapath = NULL;
bool noocr = false;
bool list_langs = false;
bool print_parameters = false;
tesseract::PageSegMode pagesegmode = tesseract::PSM_AUTO;
int arg = 1;
while (arg < argc && (output == NULL || argv[arg][0] == '-')) {
if (strcmp(argv[arg], "-l") == 0 && arg + 1 < argc) {
lang = argv[arg + 1];
++arg;
} else if (strcmp(argv[arg], "--tessdata-dir") == 0 && arg + 1 < argc) {
datapath = argv[arg + 1];
++arg;
} else if (strcmp(argv[arg], "--list-langs") == 0) {
noocr = true;
list_langs = true;
} else if (strcmp(argv[arg], "-psm") == 0 && arg + 1 < argc) {
pagesegmode = static_cast<tesseract::PageSegMode>(atoi(argv[arg + 1]));
++arg;
} else if (strcmp(argv[arg], "--print-parameters") == 0) {
noocr = true;
print_parameters = true;
} else if (strcmp(argv[arg], "-c") == 0 && arg + 1 < argc) {
// handled properly after api init
++arg;
} else if (image == NULL) {
image = argv[arg];
} else if (output == NULL) {
output = argv[arg];
}
++arg;
}
if (argc == 2 && strcmp(argv[1], "--list-langs") == 0) {
list_langs = true;
noocr = true;
}
if (output == NULL && noocr == false) {
fprintf(stderr, "Usage:\n %s imagename|stdin outputbase|stdout "
"[options...] [configfile...]\n\n", argv[0]);
fprintf(stderr, "OCR options:\n");
fprintf(stderr, " --tessdata-dir /path\tspecify location of tessdata"
" path\n");
fprintf(stderr, " -l lang[+lang]\tspecify language(s) used for OCR\n");
fprintf(stderr, " -c configvar=value\tset value for control parameter.\n"
"\t\t\tMultiple -c arguments are allowed.\n");
fprintf(stderr, " -psm pagesegmode\tspecify page segmentation mode.\n");
fprintf(stderr, "These options must occur before any configfile.\n\n");
fprintf(stderr,
"pagesegmode values are:\n"
" 0 = Orientation and script detection (OSD) only.\n"
" 1 = Automatic page segmentation with OSD.\n"
" 2 = Automatic page segmentation, but no OSD, or OCR\n"
" 3 = Fully automatic page segmentation, but no OSD. (Default)\n"
" 4 = Assume a single column of text of variable sizes.\n"
" 5 = Assume a single uniform block of vertically aligned text.\n"
" 6 = Assume a single uniform block of text.\n"
" 7 = Treat the image as a single text line.\n"
" 8 = Treat the image as a single word.\n"
" 9 = Treat the image as a single word in a circle.\n"
" 10 = Treat the image as a single character.\n\n");
fprintf(stderr, "Single options:\n");
fprintf(stderr, " -v --version: version info\n");
fprintf(stderr, " --list-langs: list available languages for tesseract "
"engine. Can be used with --tessdata-dir.\n");
fprintf(stderr, " --print-parameters: print tesseract parameters to the "
"stdout.\n");
exit(1);
}
if (output != NULL && strcmp(output, "-") && strcmp(output, "stdout")) {
tprintf("Tesseract Open Source OCR Engine v%s with Leptonica\n",
tesseract::TessBaseAPI::Version());
}
PERF_COUNT_START("Tesseract:main")
tesseract::TessBaseAPI api;
api.SetOutputName(output);
int rc = api.Init(datapath, lang, tesseract::OEM_DEFAULT,
&(argv[arg]), argc - arg, NULL, NULL, false);
if (rc) {
fprintf(stderr, "Could not initialize tesseract.\n");
exit(1);
}
char opt1[255], opt2[255];
for (arg = 0; arg < argc; arg++) {
if (strcmp(argv[arg], "-c") == 0 && arg + 1 < argc) {
strncpy(opt1, argv[arg + 1], 255);
*(strchr(opt1, '=')) = 0;
strncpy(opt2, strchr(argv[arg + 1], '=') + 1, 255);
opt2[254] = 0;
++arg;
if (!api.SetVariable(opt1, opt2)) {
fprintf(stderr, "Could not set option: %s=%s\n", opt1, opt2);
}
}
}
if (list_langs) {
GenericVector<STRING> languages;
api.GetAvailableLanguagesAsVector(&languages);
fprintf(stderr, "List of available languages (%d):\n",
languages.size());
for (int index = 0; index < languages.size(); ++index) {
STRING& string = languages[index];
fprintf(stderr, "%s\n", string.string());
}
api.End();
exit(0);
}
if (print_parameters) {
FILE* fout = stdout;
fprintf(stdout, "Tesseract parameters:\n");
api.PrintVariables(fout);
api.End();
exit(0);
}
// We have 2 possible sources of pagesegmode: a config file and
// the command line. For backwards compatability reasons, the
// default in tesseract is tesseract::PSM_SINGLE_BLOCK, but the
// default for this program is tesseract::PSM_AUTO. We will let
// the config file take priority, so the command-line default
// can take priority over the tesseract default, so we use the
// value from the command line only if the retrieved mode
// is still tesseract::PSM_SINGLE_BLOCK, indicating no change
// in any config file. Therefore the only way to force
// tesseract::PSM_SINGLE_BLOCK is from the command line.
// It would be simpler if we could set the value before Init,
// but that doesn't work.
if (api.GetPageSegMode() == tesseract::PSM_SINGLE_BLOCK)
api.SetPageSegMode(pagesegmode);
bool stdInput = !strcmp(image, "stdin") || !strcmp(image, "-");
Pix* pixs = NULL;
if (stdInput) {
char byt;
GenericVector<l_uint8> ch_data;
std::istream file(std::cin.rdbuf());
#ifdef WIN32
if (_setmode(_fileno(stdin), _O_BINARY) == -1)
tprintf("ERROR: cin to binary: %s", strerror(errno));
#endif // WIN32
while (file.get(byt)) {
ch_data.push_back(byt);
}
std::cin.ignore(std::cin.rdbuf()->in_avail() + 1);
pixs = pixReadMem(&ch_data[0], ch_data.size());
}
if (pagesegmode == tesseract::PSM_AUTO_ONLY ||
pagesegmode == tesseract::PSM_OSD_ONLY) {
tesseract::Orientation orientation;
tesseract::WritingDirection direction;
tesseract::TextlineOrder order;
float deskew_angle;
int ret_val = 0;
if (!pixs)
pixs = pixRead(image);
api.SetImage(pixs);
tesseract::PageIterator* it = api.AnalyseLayout();
if (it) {
it->Orientation(&orientation, &direction, &order, &deskew_angle);
tprintf("Orientation: %d\nWritingDirection: %d\nTextlineOrder: %d\n" \
"Deskew angle: %.4f\n",
orientation, direction, order, deskew_angle);
} else {
ret_val = 1;
}
pixDestroy(&pixs);
delete it;
exit(ret_val);
}
tesseract::TessResultRenderer* renderer = NULL;
bool b;
api.GetBoolVariable("tessedit_create_hocr", &b);
if (b && renderer == NULL) renderer = new tesseract::TessHOcrRenderer();
api.GetBoolVariable("tessedit_create_pdf", &b);
if (b && renderer == NULL)
renderer = new tesseract::TessPDFRenderer(api.GetDatapath());
api.GetBoolVariable("tessedit_create_boxfile", &b);
if (b && renderer == NULL) renderer = new tesseract::TessBoxTextRenderer();
if (renderer == NULL) renderer = new tesseract::TessTextRenderer();
if (pixs) {
api.ProcessPage(pixs, 0, NULL, NULL, 0, renderer);
pixDestroy(&pixs);
} else {
FILE* fin = fopen(image, "rb");
if (fin == NULL) {
fprintf(stderr, "Cannot open input file: %s\n", image);
exit(2);
}
fclose(fin);
if (!api.ProcessPages(image, NULL, 0, renderer)) {
fprintf(stderr, "Error during processing.\n");
exit(1);
}
}
FILE* fout = stdout;
if (strcmp(output, "-") && strcmp(output, "stdout")) {
STRING outfile = STRING(output)
+ STRING(".")
+ STRING(renderer->file_extension());
fout = fopen(outfile.string(), "wb");
if (fout == NULL) {
fprintf(stderr, "Cannot create output file %s\n", outfile.string());
exit(1);
}
}
const char* data;
inT32 data_len;
if (renderer->GetOutput(&data, &data_len)) {
fwrite(data, 1, data_len, fout);
if (fout != stdout)
fclose(fout);
else
clearerr(fout);
}
PERF_COUNT_END
return 0; // Normal exit
}
<commit_msg>provide output for -psm 0<commit_after>/**********************************************************************
* File: tessedit.cpp (Formerly tessedit.c)
* Description: Main program for merge of tess and editor.
* Author: Ray Smith
* Created: Tue Jan 07 15:21:46 GMT 1992
*
* (C) Copyright 1992, Hewlett-Packard Ltd.
** Licensed under the Apache License, Version 2.0 (the "License");
** you may not use this file except in compliance with the License.
** You may obtain a copy of the License at
** http://www.apache.org/licenses/LICENSE-2.0
** Unless required by applicable law or agreed to in writing, software
** distributed under the License is distributed on an "AS IS" BASIS,
** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
** See the License for the specific language governing permissions and
** limitations under the License.
*
**********************************************************************/
// Include automatically generated configuration file if running autoconf
#ifdef HAVE_CONFIG_H
#include "config_auto.h"
#endif
#ifdef _WIN32
#include <fcntl.h>
#include <io.h>
#endif // _WIN32
#include <iostream>
#include "allheaders.h"
#include "baseapi.h"
#include "basedir.h"
#include "renderer.h"
#include "strngs.h"
#include "tprintf.h"
#include "openclwrapper.h"
#include "osdetect.h"
/**********************************************************************
* main()
*
**********************************************************************/
int main(int argc, char **argv) {
if ((argc == 2 && strcmp(argv[1], "-v") == 0) ||
(argc == 2 && strcmp(argv[1], "--version") == 0)) {
char *versionStrP;
fprintf(stderr, "tesseract %s\n", tesseract::TessBaseAPI::Version());
versionStrP = getLeptonicaVersion();
fprintf(stderr, " %s\n", versionStrP);
lept_free(versionStrP);
versionStrP = getImagelibVersions();
fprintf(stderr, " %s\n", versionStrP);
lept_free(versionStrP);
#ifdef USE_OPENCL
cl_platform_id platform;
cl_uint num_platforms;
cl_device_id devices[2];
cl_uint num_devices;
char info[256];
int i;
fprintf(stderr, " OpenCL info:\n");
clGetPlatformIDs(1, &platform, &num_platforms);
fprintf(stderr, " Found %d platforms.\n", num_platforms);
clGetPlatformInfo(platform, CL_PLATFORM_NAME, 256, info, 0);
fprintf(stderr, " Platform name: %s.\n", info);
clGetPlatformInfo(platform, CL_PLATFORM_VERSION, 256, info, 0);
fprintf(stderr, " Version: %s.\n", info);
clGetDeviceIDs(platform, CL_DEVICE_TYPE_ALL, 2, devices, &num_devices);
fprintf(stderr, " Found %d devices.\n", num_devices);
for (i = 0; i < num_devices; ++i) {
clGetDeviceInfo(devices[i], CL_DEVICE_NAME, 256, info, 0);
fprintf(stderr, " Device %d name: %s.\n", i+1, info);
}
#endif
exit(0);
}
// Make the order of args a bit more forgiving than it used to be.
const char* lang = "eng";
const char* image = NULL;
const char* output = NULL;
const char* datapath = NULL;
bool noocr = false;
bool list_langs = false;
bool print_parameters = false;
tesseract::PageSegMode pagesegmode = tesseract::PSM_AUTO;
int arg = 1;
while (arg < argc && (output == NULL || argv[arg][0] == '-')) {
if (strcmp(argv[arg], "-l") == 0 && arg + 1 < argc) {
lang = argv[arg + 1];
++arg;
} else if (strcmp(argv[arg], "--tessdata-dir") == 0 && arg + 1 < argc) {
datapath = argv[arg + 1];
++arg;
} else if (strcmp(argv[arg], "--list-langs") == 0) {
noocr = true;
list_langs = true;
} else if (strcmp(argv[arg], "-psm") == 0 && arg + 1 < argc) {
pagesegmode = static_cast<tesseract::PageSegMode>(atoi(argv[arg + 1]));
++arg;
} else if (strcmp(argv[arg], "--print-parameters") == 0) {
noocr = true;
print_parameters = true;
} else if (strcmp(argv[arg], "-c") == 0 && arg + 1 < argc) {
// handled properly after api init
++arg;
} else if (image == NULL) {
image = argv[arg];
} else if (output == NULL) {
output = argv[arg];
}
++arg;
}
if (argc == 2 && strcmp(argv[1], "--list-langs") == 0) {
list_langs = true;
noocr = true;
}
if (output == NULL && noocr == false) {
fprintf(stderr, "Usage:\n %s imagename|stdin outputbase|stdout "
"[options...] [configfile...]\n\n", argv[0]);
fprintf(stderr, "OCR options:\n");
fprintf(stderr, " --tessdata-dir /path\tspecify location of tessdata"
" path\n");
fprintf(stderr, " -l lang[+lang]\tspecify language(s) used for OCR\n");
fprintf(stderr, " -c configvar=value\tset value for control parameter.\n"
"\t\t\tMultiple -c arguments are allowed.\n");
fprintf(stderr, " -psm pagesegmode\tspecify page segmentation mode.\n");
fprintf(stderr, "These options must occur before any configfile.\n\n");
fprintf(stderr,
"pagesegmode values are:\n"
" 0 = Orientation and script detection (OSD) only.\n"
" 1 = Automatic page segmentation with OSD.\n"
" 2 = Automatic page segmentation, but no OSD, or OCR\n"
" 3 = Fully automatic page segmentation, but no OSD. (Default)\n"
" 4 = Assume a single column of text of variable sizes.\n"
" 5 = Assume a single uniform block of vertically aligned text.\n"
" 6 = Assume a single uniform block of text.\n"
" 7 = Treat the image as a single text line.\n"
" 8 = Treat the image as a single word.\n"
" 9 = Treat the image as a single word in a circle.\n"
" 10 = Treat the image as a single character.\n\n");
fprintf(stderr, "Single options:\n");
fprintf(stderr, " -v --version: version info\n");
fprintf(stderr, " --list-langs: list available languages for tesseract "
"engine. Can be used with --tessdata-dir.\n");
fprintf(stderr, " --print-parameters: print tesseract parameters to the "
"stdout.\n");
exit(1);
}
if (output != NULL && strcmp(output, "-") && strcmp(output, "stdout")) {
tprintf("Tesseract Open Source OCR Engine v%s with Leptonica\n",
tesseract::TessBaseAPI::Version());
}
PERF_COUNT_START("Tesseract:main")
tesseract::TessBaseAPI api;
api.SetOutputName(output);
int rc = api.Init(datapath, lang, tesseract::OEM_DEFAULT,
&(argv[arg]), argc - arg, NULL, NULL, false);
if (rc) {
fprintf(stderr, "Could not initialize tesseract.\n");
exit(1);
}
char opt1[255], opt2[255];
for (arg = 0; arg < argc; arg++) {
if (strcmp(argv[arg], "-c") == 0 && arg + 1 < argc) {
strncpy(opt1, argv[arg + 1], 255);
*(strchr(opt1, '=')) = 0;
strncpy(opt2, strchr(argv[arg + 1], '=') + 1, 255);
opt2[254] = 0;
++arg;
if (!api.SetVariable(opt1, opt2)) {
fprintf(stderr, "Could not set option: %s=%s\n", opt1, opt2);
}
}
}
if (list_langs) {
GenericVector<STRING> languages;
api.GetAvailableLanguagesAsVector(&languages);
fprintf(stderr, "List of available languages (%d):\n",
languages.size());
for (int index = 0; index < languages.size(); ++index) {
STRING& string = languages[index];
fprintf(stderr, "%s\n", string.string());
}
api.End();
exit(0);
}
if (print_parameters) {
FILE* fout = stdout;
fprintf(stdout, "Tesseract parameters:\n");
api.PrintVariables(fout);
api.End();
exit(0);
}
// We have 2 possible sources of pagesegmode: a config file and
// the command line. For backwards compatability reasons, the
// default in tesseract is tesseract::PSM_SINGLE_BLOCK, but the
// default for this program is tesseract::PSM_AUTO. We will let
// the config file take priority, so the command-line default
// can take priority over the tesseract default, so we use the
// value from the command line only if the retrieved mode
// is still tesseract::PSM_SINGLE_BLOCK, indicating no change
// in any config file. Therefore the only way to force
// tesseract::PSM_SINGLE_BLOCK is from the command line.
// It would be simpler if we could set the value before Init,
// but that doesn't work.
if (api.GetPageSegMode() == tesseract::PSM_SINGLE_BLOCK)
api.SetPageSegMode(pagesegmode);
bool stdInput = !strcmp(image, "stdin") || !strcmp(image, "-");
Pix* pixs = NULL;
if (stdInput) {
char byt;
GenericVector<l_uint8> ch_data;
std::istream file(std::cin.rdbuf());
#ifdef WIN32
if (_setmode(_fileno(stdin), _O_BINARY) == -1)
tprintf("ERROR: cin to binary: %s", strerror(errno));
#endif // WIN32
while (file.get(byt)) {
ch_data.push_back(byt);
}
std::cin.ignore(std::cin.rdbuf()->in_avail() + 1);
pixs = pixReadMem(&ch_data[0], ch_data.size());
}
if (pagesegmode == tesseract::PSM_AUTO_ONLY ||
pagesegmode == tesseract::PSM_OSD_ONLY) {
int ret_val = 0;
if (!pixs)
pixs = pixRead(image);
if (!pixs) {
fprintf(stderr, "Cannot open input file: %s\n", image);
exit(2);
}
api.SetImage(pixs);
if (pagesegmode == tesseract::PSM_OSD_ONLY) {
OSResults osr;
if (api.DetectOS(&osr)) {
int orient = osr.best_result.orientation_id;
int script_id = osr.get_best_script(orient);
float orient_oco = osr.best_result.oconfidence;
float orient_sco = osr.best_result.sconfidence;
tprintf("Orientation: %d\nOrientation in degrees: %d\n" \
"Orientation confidence: %.2f\n" \
"Script: %d\nScript confidence: %.2f\n",
orient, OrientationIdToValue(orient), orient_oco,
script_id, orient_sco);
} else {
ret_val = 1;
}
} else {
tesseract::Orientation orientation;
tesseract::WritingDirection direction;
tesseract::TextlineOrder order;
float deskew_angle;
tesseract::PageIterator* it = api.AnalyseLayout();
if (it) {
it->Orientation(&orientation, &direction, &order, &deskew_angle);
tprintf("Orientation: %d\nWritingDirection: %d\nTextlineOrder: %d\n" \
"Deskew angle: %.4f\n",
orientation, direction, order, deskew_angle);
} else {
ret_val = 1;
}
delete it;
}
pixDestroy(&pixs);
exit(ret_val);
}
tesseract::TessResultRenderer* renderer = NULL;
bool b;
api.GetBoolVariable("tessedit_create_hocr", &b);
if (b && renderer == NULL) renderer = new tesseract::TessHOcrRenderer();
api.GetBoolVariable("tessedit_create_pdf", &b);
if (b && renderer == NULL)
renderer = new tesseract::TessPDFRenderer(api.GetDatapath());
api.GetBoolVariable("tessedit_create_boxfile", &b);
if (b && renderer == NULL) renderer = new tesseract::TessBoxTextRenderer();
if (renderer == NULL) renderer = new tesseract::TessTextRenderer();
if (pixs) {
api.ProcessPage(pixs, 0, NULL, NULL, 0, renderer);
pixDestroy(&pixs);
} else {
FILE* fin = fopen(image, "rb");
if (fin == NULL) {
fprintf(stderr, "Cannot open input file: %s\n", image);
exit(2);
}
fclose(fin);
if (!api.ProcessPages(image, NULL, 0, renderer)) {
fprintf(stderr, "Error during processing.\n");
exit(1);
}
}
FILE* fout = stdout;
if (strcmp(output, "-") && strcmp(output, "stdout")) {
STRING outfile = STRING(output)
+ STRING(".")
+ STRING(renderer->file_extension());
fout = fopen(outfile.string(), "wb");
if (fout == NULL) {
fprintf(stderr, "Cannot create output file %s\n", outfile.string());
exit(1);
}
}
const char* data;
inT32 data_len;
if (renderer->GetOutput(&data, &data_len)) {
fwrite(data, 1, data_len, fout);
if (fout != stdout)
fclose(fout);
else
clearerr(fout);
}
PERF_COUNT_END
return 0; // Normal exit
}
<|endoftext|> |
<commit_before>#pragma once
#include <QString>
#include <pajlada/settings/serialize.hpp>
namespace pajlada {
namespace Settings {
template <>
struct Serialize<QString> {
static rapidjson::Value get(const QString &value, rapidjson::Document::AllocatorType &a)
{
rapidjson::Value ret(qPrintable(value), a);
return ret;
}
};
template <>
struct Deserialize<QString> {
static QString get(const rapidjson::Value &value)
{
if (!value.IsString()) {
throw std::runtime_error("Deserialized rapidjson::Value is not a string");
}
try {
const char *str = value.GetString();
auto strLen = value.GetStringLength();
return QString::fromUtf8(str, strLen);
} catch (const std::exception &) {
// int x = 5;
} catch (...) {
// int y = 5;
}
return QString();
}
};
} // namespace Settings
} // namespace pajlada
<commit_msg>Settings now saves unicode QString settings properly<commit_after>#pragma once
#include <QString>
#include <pajlada/settings/serialize.hpp>
namespace pajlada {
namespace Settings {
template <>
struct Serialize<QString> {
static rapidjson::Value get(const QString &value, rapidjson::Document::AllocatorType &a)
{
rapidjson::Value ret(value.toUtf8(), a);
return ret;
}
};
template <>
struct Deserialize<QString> {
static QString get(const rapidjson::Value &value)
{
if (!value.IsString()) {
throw std::runtime_error("Deserialized rapidjson::Value is not a string");
}
try {
const char *str = value.GetString();
auto strLen = value.GetStringLength();
return QString::fromUtf8(str, strLen);
} catch (const std::exception &) {
// int x = 5;
} catch (...) {
// int y = 5;
}
return QString();
}
};
} // namespace Settings
} // namespace pajlada
<|endoftext|> |
<commit_before>/*=========================================================================
Program: Insight Segmentation & Registration Toolkit
Module: itkGaussianDensityFunctionTest.cxx
Language: C++
Date: $Date$
Version: $Revision$
Copyright (c) Insight Software Consortium. All rights reserved.
See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE. See the above copyright notices for more information.
=========================================================================*/
#if defined(_MSC_VER)
#pragma warning ( disable : 4786 )
#endif
#include "itkGaussianDensityFunction.h"
#include "itkVector.h"
int itkGaussianDensityFunctionTest(int, char* [] )
{
std::cout << "itkGaussianDensityFunctionTest Test \n \n";
typedef itk::Vector< double, 1 > MeasurementVectorType;
typedef itk::Statistics::GaussianDensityFunction<
MeasurementVectorType
> DensityFunctionType;
typedef DensityFunctionType::MeasurementVectorType MeasurementVectorType;
typedef DensityFunctionType::CovarianceType CovarianceType;
typedef DensityFunctionType::MeanType MeanType;
MeanType mean;
CovarianceType covariance;
covariance.SetSize( 1, 1 ); // because this is a scalar image
mean[0] = 19.0;
covariance[0][0] = 1.0;
DensityFunctionType::Pointer densityFunction = DensityFunctionType::New();
densityFunction->SetMean( &mean );
densityFunction->SetCovariance( &covariance );
MeasurementVectorType inputValue;
inputValue[0] = mean[0];
const double value1 = densityFunction->Evaluate( inputValue );
std::cout << "Evaluate at the mean = " << value1 << std::endl;
std::cout << "Test passed." << std::endl;
return EXIT_SUCCESS;
}
<commit_msg>BUG: Both the Covariance and the Mean should allocate their respective sizes before being used. This is the price to pay for having the flexibility of changing the measurement vector size at run-time.<commit_after>/*=========================================================================
Program: Insight Segmentation & Registration Toolkit
Module: itkGaussianDensityFunctionTest.cxx
Language: C++
Date: $Date$
Version: $Revision$
Copyright (c) Insight Software Consortium. All rights reserved.
See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE. See the above copyright notices for more information.
=========================================================================*/
#if defined(_MSC_VER)
#pragma warning ( disable : 4786 )
#endif
#include "itkGaussianDensityFunction.h"
#include "itkVector.h"
int itkGaussianDensityFunctionTest(int, char* [] )
{
std::cout << "itkGaussianDensityFunctionTest Test \n \n";
typedef itk::Vector< double, 1 > MeasurementVectorType;
typedef itk::Statistics::GaussianDensityFunction<
MeasurementVectorType
> DensityFunctionType;
typedef DensityFunctionType::MeasurementVectorType MeasurementVectorType;
typedef DensityFunctionType::CovarianceType CovarianceType;
typedef DensityFunctionType::MeanType MeanType;
MeanType mean(1); // size = 1 because this is a scalar case.
CovarianceType covariance;
covariance.SetSize( 1, 1 ); // because this is a scalar case
mean[0] = 19.0;
covariance[0][0] = 1.0;
DensityFunctionType::Pointer densityFunction = DensityFunctionType::New();
densityFunction->SetMean( &mean );
densityFunction->SetCovariance( &covariance );
MeasurementVectorType inputValue;
inputValue[0] = mean[0];
const double value1 = densityFunction->Evaluate( inputValue );
std::cout << "Evaluate at the mean = " << value1 << std::endl;
std::cout << "Test passed." << std::endl;
return EXIT_SUCCESS;
}
<|endoftext|> |
<commit_before>// Copyright 2008 Paul Hodge
#include "ast.h"
#include "parser.h"
#include "tokenizer.h"
#include "token_stream.h"
namespace circa {
namespace parse_expression_function {
void evaluate(Term* caller)
{
/*
token_stream::TokenStream &tokens = as<token_stream::TokenStream>(caller->inputs[0]);
ast::Expression &result = as<ast::Expression>(caller);
*/
}
void setup(Branch& kernel)
{
/*
quick_create_cpp_type<ast::Expression>(kernel, "ExpresionAST");
Term* main_func = import_c_function(kernel, evaluate,
"function parse-expression(TokenStream) -> ExpressionAST");
as_function(main_func).pureFunction = false;
*/
}
}
} // namespace circa
<commit_msg>Fix typo<commit_after>// Copyright 2008 Paul Hodge
#include "ast.h"
#include "parser.h"
#include "tokenizer.h"
#include "token_stream.h"
namespace circa {
namespace parse_expression_function {
void evaluate(Term* caller)
{
/*
token_stream::TokenStream &tokens = as<token_stream::TokenStream>(caller->inputs[0]);
ast::Expression &result = as<ast::Expression>(caller);
*/
}
void setup(Branch& kernel)
{
/*
quick_create_cpp_type<ast::Expression>(kernel, "ExpressionAST");
Term* main_func = import_c_function(kernel, evaluate,
"function parse-expression(TokenStream) -> ExpressionAST");
as_function(main_func).pureFunction = false;
*/
}
}
} // namespace circa
<|endoftext|> |
<commit_before>/*
Q Light Controller
audioeditor.cpp
Copyright (c) Massimo Callegari
This program is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License
Version 2 as published by the Free Software Foundation.
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 General Public License for more details. The license is
in the file "COPYING".
You should have received a copy of the GNU 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.
*/
#include <QLineEdit>
#include <QLabel>
#include <QDebug>
#include "audiodecoder.h"
#include "audioeditor.h"
#include "audio.h"
#include "doc.h"
AudioEditor::AudioEditor(QWidget* parent, Audio *audio, Doc* doc)
: QWidget(parent)
, m_doc(doc)
, m_audio(audio)
{
Q_ASSERT(doc != NULL);
Q_ASSERT(audio != NULL);
setupUi(this);
connect(m_nameEdit, SIGNAL(textEdited(const QString&)),
this, SLOT(slotNameEdited(const QString&)));
m_nameEdit->setText(m_audio->name());
m_nameEdit->setSelection(0, m_nameEdit->text().length());
AudioDecoder *adec = m_audio->getAudioDecoder();
AudioParameters ap = adec->audioParameters();
m_filenameLabel->setText(m_audio->getSourceFileName());
m_durationLabel->setText(Function::speedToString(m_audio->getDuration()));
m_srateLabel->setText(QString("%1 Hz").arg(ap.sampleRate()));
m_channelsLabel->setText(QString("%1").arg(ap.channels()));
m_bitrateLabel->setText(QString("%1 kb/s").arg(adec->bitrate()));
// Set focus to the editor
m_nameEdit->setFocus();
}
AudioEditor::~AudioEditor()
{
}
void AudioEditor::slotNameEdited(const QString& text)
{
m_audio->setName(text);
}
<commit_msg>Fixed crash when trying to display the audio editor on a non existant file<commit_after>/*
Q Light Controller
audioeditor.cpp
Copyright (c) Massimo Callegari
This program is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License
Version 2 as published by the Free Software Foundation.
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 General Public License for more details. The license is
in the file "COPYING".
You should have received a copy of the GNU 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.
*/
#include <QLineEdit>
#include <QLabel>
#include <QDebug>
#include "audiodecoder.h"
#include "audioeditor.h"
#include "audio.h"
#include "doc.h"
AudioEditor::AudioEditor(QWidget* parent, Audio *audio, Doc* doc)
: QWidget(parent)
, m_doc(doc)
, m_audio(audio)
{
Q_ASSERT(doc != NULL);
Q_ASSERT(audio != NULL);
setupUi(this);
connect(m_nameEdit, SIGNAL(textEdited(const QString&)),
this, SLOT(slotNameEdited(const QString&)));
m_nameEdit->setText(m_audio->name());
m_nameEdit->setSelection(0, m_nameEdit->text().length());
AudioDecoder *adec = m_audio->getAudioDecoder();
m_filenameLabel->setText(m_audio->getSourceFileName());
if (adec != NULL)
{
AudioParameters ap = adec->audioParameters();
m_durationLabel->setText(Function::speedToString(m_audio->getDuration()));
m_srateLabel->setText(QString("%1 Hz").arg(ap.sampleRate()));
m_channelsLabel->setText(QString("%1").arg(ap.channels()));
m_bitrateLabel->setText(QString("%1 kb/s").arg(adec->bitrate()));
}
// Set focus to the editor
m_nameEdit->setFocus();
}
AudioEditor::~AudioEditor()
{
}
void AudioEditor::slotNameEdited(const QString& text)
{
m_audio->setName(text);
}
<|endoftext|> |
<commit_before>//============================================================================
// vSMC/example/rng/include/rng_test.hpp
//----------------------------------------------------------------------------
// vSMC: Scalable Monte Carlo
//----------------------------------------------------------------------------
// Copyright (c) 2013-2015, Yan Zhou
// 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.
//
// 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.
//============================================================================
#ifndef VSMC_EXAMPLE_RNG_TEST_HPP
#define VSMC_EXAMPLE_RNG_TEST_HPP
#ifndef VSMC_RNG_TEST_C_API
#define VSMC_RNG_TEST_C_API 0
#endif
#ifndef VSMC_RNG_TEST_MKL
#define VSMC_RNG_TEST_MKL 0
#endif
#include <vsmc/rng/rng.hpp>
#include <vsmc/utility/stop_watch.hpp>
#if VSMC_RNG_TEST_C_API
#include <vsmc/vsmc.h>
#if VSMC_HAS_MKL
#include <vsmc/rng/mkl_brng.hpp>
#endif
#endif
#define VSMC_RNG_TEST_PRE(prog) \
std::size_t N = 1000000; \
std::string prog_name(#prog); \
if (argc > 1) \
N = static_cast<std::size_t>(std::atoi(argv[1])); \
vsmc::Vector<std::string> names; \
vsmc::Vector<std::size_t> size; \
vsmc::Vector<vsmc::StopWatch> sw;
#define VSMC_RNG_TEST(RNGType) rng_test<RNGType>(N, #RNGType, names, size, sw);
#define VSMC_RNG_TEST_POST rng_output_sw(prog_name, names, size, sw);
template <typename RNGType>
inline double rng_test(std::size_t N, vsmc::Vector<vsmc::StopWatch> &sw,
RNGType &rng, vsmc::StopWatch &watch, std::true_type)
{
double result = 0;
vsmc::UniformRealDistribution<double, vsmc::Closed, vsmc::Open> runif(
0, 1);
watch.reset();
watch.start();
for (std::size_t i = 0; i != N; ++i)
result += runif(rng);
watch.stop();
sw.push_back(watch);
return result;
}
template <typename RNGType>
inline double rng_test(std::size_t, vsmc::Vector<vsmc::StopWatch> &sw,
RNGType &, vsmc::StopWatch &watch, std::false_type)
{
watch.reset();
sw.push_back(watch);
return 0;
}
template <typename RNGType>
inline void rng_test(std::size_t N, const std::string &name,
vsmc::Vector<std::string> &names, vsmc::Vector<std::size_t> &size,
vsmc::Vector<vsmc::StopWatch> &sw)
{
names.push_back(name);
size.push_back(sizeof(RNGType));
RNGType rng;
vsmc::StopWatch watch;
double result = 0;
vsmc::Vector<double> r(N);
#if VSMC_RNG_TEST_C_API && VSMC_RNG_TEST_MKL
MKL_INT brng = rng.stream().brng();
VSLStreamStatePtr stream = nullptr;
vslNewStream(&stream, rng.stream().brng(), 1);
#elif VSMC_RNG_TEST_C_API && VSMC_HAS_MKL
MKL_INT brng = vsmc::mkl_brng<RNGType>();
VSLStreamStatePtr stream = nullptr;
vslNewStream(&stream, brng, 1);
#endif
typename RNGType::result_type uresult = 0;
for (std::size_t i = 0; i != N; ++i)
uresult += rng();
watch.reset();
watch.start();
for (std::size_t i = 0; i != N; ++i)
uresult += rng();
watch.stop();
sw.push_back(watch);
result += static_cast<double>(uresult);
#if VSMC_RNG_TEST_C_API && VSMC_HAS_MKL
VSLBRngProperties properties;
vslGetBrngProperties(brng, &properties);
std::size_t B = N * sizeof(typename RNGType::result_type);
std::size_t M = B / static_cast<std::size_t>(properties.WordSize);
vsmc::Vector<unsigned> ur(B / sizeof(unsigned));
viRngUniformBits(VSL_RNG_METHOD_UNIFORMBITS_STD, stream,
static_cast<MKL_INT>(M), ur.data());
result += static_cast<double>(std::accumulate(ur.begin(), ur.end(), 0u));
watch.reset();
watch.start();
viRngUniformBits(VSL_RNG_METHOD_UNIFORMBITS_STD, stream,
static_cast<MKL_INT>(M), ur.data());
watch.stop();
sw.push_back(watch);
result += static_cast<double>(std::accumulate(ur.begin(), ur.end(), 0u));
#endif
std::uniform_real_distribution<double> runif_std(0, 1);
for (std::size_t i = 0; i != N; ++i)
result += runif_std(rng);
watch.reset();
watch.start();
for (std::size_t i = 0; i != N; ++i)
result += runif_std(rng);
watch.stop();
sw.push_back(watch);
vsmc::UniformRealDistributionType<RNGType, double> runif_vsmc(0, 1);
for (std::size_t i = 0; i != N; ++i)
result += runif_vsmc(rng);
watch.reset();
watch.start();
for (std::size_t i = 0; i != N; ++i)
result += runif_vsmc(rng);
watch.stop();
sw.push_back(watch);
#if VSMC_RNG_TEST_C_API && VSMC_HAS_MKL
vdRngUniform(VSL_RNG_METHOD_UNIFORM_STD, stream, static_cast<MKL_INT>(N),
r.data(), 0, 1);
result += std::accumulate(r.begin(), r.end(), result);
watch.reset();
watch.start();
vdRngUniform(VSL_RNG_METHOD_UNIFORM_STD, stream, static_cast<MKL_INT>(N),
r.data(), 0, 1);
watch.stop();
sw.push_back(watch);
result += std::accumulate(r.begin(), r.end(), result);
#endif
std::normal_distribution<double> rnorm_std(0, 1);
for (std::size_t i = 0; i != N; ++i)
result += rnorm_std(rng);
watch.reset();
watch.start();
for (std::size_t i = 0; i != N; ++i)
result += rnorm_std(rng);
watch.stop();
sw.push_back(watch);
vsmc::NormalDistribution<double> rnorm_vsmc(0, 1);
for (std::size_t i = 0; i != N; ++i)
result += rnorm_vsmc(rng);
watch.reset();
watch.start();
for (std::size_t i = 0; i != N; ++i)
result += rnorm_vsmc(rng);
watch.stop();
sw.push_back(watch);
vsmc::normal_distribution(rng, N, r.data(), 0.0, 1.0);
result += std::accumulate(r.begin(), r.end(), result);
watch.reset();
watch.start();
vsmc::normal_distribution(rng, N, r.data(), 0.0, 1.0);
watch.stop();
sw.push_back(watch);
result += std::accumulate(r.begin(), r.end(), result);
#if VSMC_RNG_TEST_C_API && VSMC_HAS_MKL
vdRngGaussian(VSL_RNG_METHOD_GAUSSIAN_BOXMULLER2, stream,
static_cast<MKL_INT>(N), r.data(), 0, 1);
result += std::accumulate(r.begin(), r.end(), result);
watch.reset();
watch.start();
vdRngGaussian(VSL_RNG_METHOD_GAUSSIAN_BOXMULLER2, stream,
static_cast<MKL_INT>(N), r.data(), 0, 1);
watch.stop();
sw.push_back(watch);
result += std::accumulate(r.begin(), r.end(), result);
#endif
#if VSMC_RNG_TEST_C_API && VSMC_HAS_MKL
vslDeleteStream(&stream);
#endif
std::ofstream rnd("rnd");
rnd << result << std::endl;
rnd.close();
}
inline void rng_output_sw(const std::string &prog_name,
const vsmc::Vector<std::string> &names,
const vsmc::Vector<std::size_t> &size,
const vsmc::Vector<vsmc::StopWatch> &sw)
{
std::size_t N = names.size();
std::size_t R = sw.size() / N;
std::size_t lwid = 165;
int twid = 15;
int swid = 5;
int Twid = twid * static_cast<int>(R);
int nwid = static_cast<int>(lwid) - swid - Twid;
std::cout << std::string(lwid, '=') << std::endl;
std::cout << std::left << std::setw(nwid) << prog_name;
std::cout << std::right << std::setw(swid) << "Size";
switch (R) {
case 1: // Only time
std::cout << std::right << std::setw(twid) << "Time (ms)";
break;
case 2: // rng_dist
std::cout << std::right << std::setw(twid) << "C++";
std::cout << std::right << std::setw(twid) << "C";
break;
case 6: // rng_test without c api or mkl
std::cout << std::right << std::setw(twid) << "Bits";
std::cout << std::right << std::setw(twid) << "U01 (STD)";
std::cout << std::right << std::setw(twid) << "U01 (vSMC)";
std::cout << std::right << std::setw(twid) << "Normal (STD)";
std::cout << std::right << std::setw(twid) << "Normal (vSMC)";
std::cout << std::right << std::setw(twid) << "Normal (Batch)";
break;
case 9: // rng_test with c api and mkl
std::cout << std::right << std::setw(twid) << "Bits";
std::cout << std::right << std::setw(twid) << "Bits (MKL)";
std::cout << std::right << std::setw(twid) << "U01 (STD)";
std::cout << std::right << std::setw(twid) << "U01 (vSMC)";
std::cout << std::right << std::setw(twid) << "U01 (MKL)";
std::cout << std::right << std::setw(twid) << "Normal (STD)";
std::cout << std::right << std::setw(twid) << "Normal (vSMC)";
std::cout << std::right << std::setw(twid) << "Normal (Batch)";
std::cout << std::right << std::setw(twid) << "Normal (MKL)";
break;
}
std::cout << std::endl;
std::cout << std::string(lwid, '-') << std::endl;
for (std::size_t i = 0; i != N; ++i) {
std::cout << std::left << std::setw(nwid) << names[i];
std::cout << std::right << std::setw(swid) << size[i];
for (std::size_t r = 0; r != R; ++r) {
double time = sw[i * R + r].milliseconds();
std::cout << std::right << std::setw(twid) << std::fixed << time;
}
std::cout << std::endl;
}
std::cout << std::string(lwid, '=') << std::endl;
}
#endif // VSMC_EXAMPLE_RNG_TEST_HPP
<commit_msg>include summation time in rng_test<commit_after>//============================================================================
// vSMC/example/rng/include/rng_test.hpp
//----------------------------------------------------------------------------
// vSMC: Scalable Monte Carlo
//----------------------------------------------------------------------------
// Copyright (c) 2013-2015, Yan Zhou
// 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.
//
// 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.
//============================================================================
#ifndef VSMC_EXAMPLE_RNG_TEST_HPP
#define VSMC_EXAMPLE_RNG_TEST_HPP
#ifndef VSMC_RNG_TEST_C_API
#define VSMC_RNG_TEST_C_API 0
#endif
#ifndef VSMC_RNG_TEST_MKL
#define VSMC_RNG_TEST_MKL 0
#endif
#include <vsmc/rng/rng.hpp>
#include <vsmc/utility/stop_watch.hpp>
#if VSMC_RNG_TEST_C_API
#include <vsmc/vsmc.h>
#if VSMC_HAS_MKL
#include <vsmc/rng/mkl_brng.hpp>
#endif
#endif
#define VSMC_RNG_TEST_PRE(prog) \
std::size_t N = 1000000; \
std::string prog_name(#prog); \
if (argc > 1) \
N = static_cast<std::size_t>(std::atoi(argv[1])); \
vsmc::Vector<std::string> names; \
vsmc::Vector<std::size_t> size; \
vsmc::Vector<vsmc::StopWatch> sw;
#define VSMC_RNG_TEST(RNGType) rng_test<RNGType>(N, #RNGType, names, size, sw);
#define VSMC_RNG_TEST_POST rng_output_sw(prog_name, names, size, sw);
template <typename RNGType>
inline void rng_test(std::size_t N, const std::string &name,
vsmc::Vector<std::string> &names, vsmc::Vector<std::size_t> &size,
vsmc::Vector<vsmc::StopWatch> &sw)
{
names.push_back(name);
size.push_back(sizeof(RNGType));
RNGType rng;
vsmc::StopWatch watch;
double result = 0;
vsmc::Vector<double> r(N);
#if VSMC_RNG_TEST_C_API && VSMC_RNG_TEST_MKL
MKL_INT brng = rng.stream().brng();
VSLStreamStatePtr stream = nullptr;
vslNewStream(&stream, rng.stream().brng(), 1);
#elif VSMC_RNG_TEST_C_API && VSMC_HAS_MKL
MKL_INT brng = vsmc::mkl_brng<RNGType>();
VSLStreamStatePtr stream = nullptr;
vslNewStream(&stream, brng, 1);
#endif
typename RNGType::result_type uresult = 0;
for (std::size_t i = 0; i != N; ++i)
uresult += rng();
watch.reset();
watch.start();
for (std::size_t i = 0; i != N; ++i)
uresult += rng();
watch.stop();
sw.push_back(watch);
result += static_cast<double>(uresult);
#if VSMC_RNG_TEST_C_API && VSMC_HAS_MKL
VSLBRngProperties properties;
vslGetBrngProperties(brng, &properties);
std::size_t B = N * sizeof(typename RNGType::result_type);
std::size_t M = B / static_cast<std::size_t>(properties.WordSize);
vsmc::Vector<unsigned> ur(B / sizeof(unsigned));
viRngUniformBits(VSL_RNG_METHOD_UNIFORMBITS_STD, stream,
static_cast<MKL_INT>(M), ur.data());
result += static_cast<double>(std::accumulate(ur.begin(), ur.end(), 0u));
watch.reset();
watch.start();
viRngUniformBits(VSL_RNG_METHOD_UNIFORMBITS_STD, stream,
static_cast<MKL_INT>(M), ur.data());
result += static_cast<double>(std::accumulate(ur.begin(), ur.end(), 0u));
watch.stop();
sw.push_back(watch);
#endif
std::uniform_real_distribution<double> runif_std(0, 1);
for (std::size_t i = 0; i != N; ++i)
result += runif_std(rng);
watch.reset();
watch.start();
for (std::size_t i = 0; i != N; ++i)
result += runif_std(rng);
watch.stop();
sw.push_back(watch);
vsmc::UniformRealDistributionType<RNGType, double> runif_vsmc(0, 1);
for (std::size_t i = 0; i != N; ++i)
result += runif_vsmc(rng);
watch.reset();
watch.start();
for (std::size_t i = 0; i != N; ++i)
result += runif_vsmc(rng);
watch.stop();
sw.push_back(watch);
#if VSMC_RNG_TEST_C_API && VSMC_HAS_MKL
vdRngUniform(VSL_RNG_METHOD_UNIFORM_STD, stream, static_cast<MKL_INT>(N),
r.data(), 0, 1);
result += std::accumulate(r.begin(), r.end(), result);
watch.reset();
watch.start();
vdRngUniform(VSL_RNG_METHOD_UNIFORM_STD, stream, static_cast<MKL_INT>(N),
r.data(), 0, 1);
result += std::accumulate(r.begin(), r.end(), result);
watch.stop();
sw.push_back(watch);
#endif
std::normal_distribution<double> rnorm_std(0, 1);
for (std::size_t i = 0; i != N; ++i)
result += rnorm_std(rng);
watch.reset();
watch.start();
for (std::size_t i = 0; i != N; ++i)
result += rnorm_std(rng);
watch.stop();
sw.push_back(watch);
vsmc::NormalDistribution<double> rnorm_vsmc(0, 1);
for (std::size_t i = 0; i != N; ++i)
result += rnorm_vsmc(rng);
watch.reset();
watch.start();
for (std::size_t i = 0; i != N; ++i)
result += rnorm_vsmc(rng);
watch.stop();
sw.push_back(watch);
vsmc::normal_distribution(rng, N, r.data(), 0.0, 1.0);
result += std::accumulate(r.begin(), r.end(), result);
watch.reset();
watch.start();
vsmc::normal_distribution(rng, N, r.data(), 0.0, 1.0);
result += std::accumulate(r.begin(), r.end(), result);
watch.stop();
sw.push_back(watch);
#if VSMC_RNG_TEST_C_API && VSMC_HAS_MKL
vdRngGaussian(VSL_RNG_METHOD_GAUSSIAN_BOXMULLER2, stream,
static_cast<MKL_INT>(N), r.data(), 0, 1);
result += std::accumulate(r.begin(), r.end(), result);
watch.reset();
watch.start();
vdRngGaussian(VSL_RNG_METHOD_GAUSSIAN_BOXMULLER2, stream,
static_cast<MKL_INT>(N), r.data(), 0, 1);
result += std::accumulate(r.begin(), r.end(), result);
watch.stop();
sw.push_back(watch);
#endif
#if VSMC_RNG_TEST_C_API && VSMC_HAS_MKL
vslDeleteStream(&stream);
#endif
std::ofstream rnd("rnd");
rnd << result << std::endl;
rnd.close();
}
inline void rng_output_sw(const std::string &prog_name,
const vsmc::Vector<std::string> &names,
const vsmc::Vector<std::size_t> &size,
const vsmc::Vector<vsmc::StopWatch> &sw)
{
std::size_t N = names.size();
std::size_t R = sw.size() / N;
std::size_t lwid = 165;
int twid = 15;
int swid = 5;
int Twid = twid * static_cast<int>(R);
int nwid = static_cast<int>(lwid) - swid - Twid;
std::cout << std::string(lwid, '=') << std::endl;
std::cout << std::left << std::setw(nwid) << prog_name;
std::cout << std::right << std::setw(swid) << "Size";
switch (R) {
case 1: // Only time
std::cout << std::right << std::setw(twid) << "Time (ms)";
break;
case 2: // rng_dist
std::cout << std::right << std::setw(twid) << "C++";
std::cout << std::right << std::setw(twid) << "C";
break;
case 6: // rng_test without c api or mkl
std::cout << std::right << std::setw(twid) << "Bits";
std::cout << std::right << std::setw(twid) << "U01 (STD)";
std::cout << std::right << std::setw(twid) << "U01 (vSMC)";
std::cout << std::right << std::setw(twid) << "Normal (STD)";
std::cout << std::right << std::setw(twid) << "Normal (vSMC)";
std::cout << std::right << std::setw(twid) << "Normal (Batch)";
break;
case 9: // rng_test with c api and mkl
std::cout << std::right << std::setw(twid) << "Bits";
std::cout << std::right << std::setw(twid) << "Bits (MKL)";
std::cout << std::right << std::setw(twid) << "U01 (STD)";
std::cout << std::right << std::setw(twid) << "U01 (vSMC)";
std::cout << std::right << std::setw(twid) << "U01 (MKL)";
std::cout << std::right << std::setw(twid) << "Normal (STD)";
std::cout << std::right << std::setw(twid) << "Normal (vSMC)";
std::cout << std::right << std::setw(twid) << "Normal (Batch)";
std::cout << std::right << std::setw(twid) << "Normal (MKL)";
break;
}
std::cout << std::endl;
std::cout << std::string(lwid, '-') << std::endl;
for (std::size_t i = 0; i != N; ++i) {
std::cout << std::left << std::setw(nwid) << names[i];
std::cout << std::right << std::setw(swid) << size[i];
for (std::size_t r = 0; r != R; ++r) {
double time = sw[i * R + r].milliseconds();
std::cout << std::right << std::setw(twid) << std::fixed << time;
}
std::cout << std::endl;
}
std::cout << std::string(lwid, '=') << std::endl;
}
#endif // VSMC_EXAMPLE_RNG_TEST_HPP
<|endoftext|> |
<commit_before>/**********************************************************************
* File: tessedit.cpp (Formerly tessedit.c)
* Description: Main program for merge of tess and editor.
* Author: Ray Smith
* Created: Tue Jan 07 15:21:46 GMT 1992
*
* (C) Copyright 1992, Hewlett-Packard Ltd.
** Licensed under the Apache License, Version 2.0 (the "License");
** you may not use this file except in compliance with the License.
** You may obtain a copy of the License at
** http://www.apache.org/licenses/LICENSE-2.0
** Unless required by applicable law or agreed to in writing, software
** distributed under the License is distributed on an "AS IS" BASIS,
** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
** See the License for the specific language governing permissions and
** limitations under the License.
*
**********************************************************************/
#include "mfcpch.h"
// #define USE_VLD //Uncomment for Visual Leak Detector.
#if (defined _MSC_VER && defined USE_VLD)
#include <vld.h>
#endif
// Include automatically generated configuration file if running autoconf
#ifdef HAVE_CONFIG_H
#include "config_auto.h"
#endif
#ifdef USING_GETTEXT
#include <libintl.h>
#include <locale.h>
#define _(x) gettext(x)
#else
#define _(x) (x)
#endif
#include "allheaders.h"
#include "baseapi.h"
#include "strngs.h"
#include "tesseractmain.h"
/**********************************************************************
* main()
*
**********************************************************************/
int main(int argc, char **argv) {
#ifdef USE_NLS
setlocale (LC_ALL, "");
bindtextdomain (PACKAGE, LOCALEDIR);
textdomain (PACKAGE);
#endif
if ((argc == 2 && strcmp(argv[1], "-v") == 0) ||
(argc == 2 && strcmp(argv[1], "--version") == 0)) {
fprintf(stderr, "tesseract %s\n", tesseract::TessBaseAPI::Version());
exit(0);
}
// Make the order of args a bit more forgiving than it used to be.
const char* lang = "eng";
const char* image = NULL;
const char* output = NULL;
tesseract::PageSegMode pagesegmode = tesseract::PSM_AUTO;
int arg = 1;
while (arg < argc && (output == NULL || argv[arg][0] == '-')) {
if (strcmp(argv[arg], "-l") == 0 && arg + 1 < argc) {
lang = argv[arg + 1];
++arg;
} else if (strcmp(argv[arg], "-psm") == 0 && arg + 1 < argc) {
pagesegmode = static_cast<tesseract::PageSegMode>(atoi(argv[arg + 1]));
++arg;
} else if (image == NULL) {
image = argv[arg];
} else if (output == NULL) {
output = argv[arg];
}
++arg;
}
if (output == NULL) {
fprintf(stderr, _("Usage:%s imagename outputbase [-l lang] "
"[-psm pagesegmode] [configfile...]\n"), argv[0]);
fprintf(stderr,
_("pagesegmode values are:\n"
"0 = Orientation and script detection (OSD) only.\n"
"1 = Automatic page segmentation with OSD.\n"
"2 = Automatic page segmentation, but no OSD, or OCR\n"
"3 = Fully automatic page segmentation, but no OSD. (Default)\n"
"4 = Assume a single column of text of variable sizes.\n"
"5 = Assume a single uniform block of vertically aligned text.\n"
"6 = Assume a single uniform block of text.\n"
"7 = Treat the image as a single text line.\n"
"8 = Treat the image as a single word.\n"
"9 = Treat the image as a single word in a circle.\n"
"10 = Treat the image as a single character.\n"));
fprintf(stderr, _("-l lang and/or -psm pagesegmode must occur before any"
"configfile.\n"));
exit(1);
}
tesseract::TessBaseAPI api;
api.SetOutputName(output);
api.Init(argv[0], lang, tesseract::OEM_DEFAULT,
&(argv[arg]), argc - arg, NULL, NULL, false);
// We have 2 possible sources of pagesegmode: a config file and
// the command line. For backwards compatability reasons, the
// default in tesseract is tesseract::PSM_SINGLE_BLOCK, but the
// default for this program is tesseract::PSM_AUTO. We will let
// the config file take priority, so the command-line default
// can take priority over the tesseract default, so we use the
// value from the command line only if the retrieved mode
// is still tesseract::PSM_SINGLE_BLOCK, indicating no change
// in any config file. Therefore the only way to force
// tesseract::PSM_SINGLE_BLOCK is from the command line.
// It would be simpler if we could set the value before Init,
// but that doesn't work.
if (api.GetPageSegMode() == tesseract::PSM_SINGLE_BLOCK)
api.SetPageSegMode(pagesegmode);
printf("Tesseract Open Source OCR Engine v%s with Leptonica\n",
tesseract::TessBaseAPI::Version());
FILE* fin = fopen(image, "rb");
if (fin == NULL) {
printf("Cannot open input file: %s\n", image);
exit(2);
}
fclose(fin);
PIX *pixs;
if ((pixs = pixRead(image)) == NULL) {
printf("Unsupported image type.\n");
exit(3);
}
pixDestroy(&pixs);
STRING text_out;
if (!api.ProcessPages(image, NULL, 0, &text_out)) {
printf("Error during processing.\n");
}
bool output_hocr = false;
api.GetBoolVariable("tessedit_create_hocr", &output_hocr);
bool output_box = false;
api.GetBoolVariable("tessedit_create_boxfile", &output_box);
STRING outfile = output;
outfile += output_hocr ? ".html" : output_box ? ".box" : ".txt";
FILE* fout = fopen(outfile.string(), "wb");
if (fout == NULL) {
printf("Cannot create output file %s\n", outfile.string());
exit(1);
}
fwrite(text_out.string(), 1, text_out.length(), fout);
fclose(fout);
return 0; // Normal exit
}
#ifdef _WIN32
char szAppName[] = "Tesseract"; //app name
int initialized = 0;
/**********************************************************************
* WinMain
*
* Main function for a windows program.
**********************************************************************/
int WINAPI WinMain( //main for windows //command line
HINSTANCE hInstance,
HINSTANCE hPrevInstance,
LPSTR lpszCmdLine,
int nCmdShow) {
WNDCLASS wc;
HWND hwnd;
MSG msg;
char **argv;
char *argsin[2];
int argc;
int exit_code;
wc.style = CS_NOCLOSE | CS_OWNDC;
wc.lpfnWndProc = (WNDPROC) WndProc;
wc.cbClsExtra = 0;
wc.cbWndExtra = 0;
wc.hInstance = hInstance;
wc.hIcon = NULL; //LoadIcon (NULL, IDI_APPLICATION);
wc.hCursor = NULL; //LoadCursor (NULL, IDC_ARROW);
wc.hbrBackground = (HBRUSH) (COLOR_WINDOW + 1);
wc.lpszMenuName = NULL;
wc.lpszClassName = szAppName;
RegisterClass(&wc);
hwnd = CreateWindow (szAppName, szAppName,
WS_OVERLAPPEDWINDOW | WS_DISABLED,
CW_USEDEFAULT, CW_USEDEFAULT, CW_USEDEFAULT,
CW_USEDEFAULT, HWND_DESKTOP, NULL, hInstance, NULL);
argsin[0] = strdup (szAppName);
argsin[1] = strdup (lpszCmdLine);
/*allocate memory for the args. There can never be more than half*/
/*the total number of characters in the arguments.*/
argv = (char **)malloc(((strlen(argsin[0]) + strlen(argsin[1])) / 2 + 1) *
sizeof(char *));
/*now construct argv as it should be for C.*/
argc = parse_args (2, argsin, argv);
// ShowWindow (hwnd, nCmdShow);
// UpdateWindow (hwnd);
if (initialized) {
exit_code = main (argc, argv);
free (argsin[0]);
free (argsin[1]);
free(argv);
return exit_code;
}
while (GetMessage (&msg, NULL, 0, 0)) {
TranslateMessage(&msg);
DispatchMessage(&msg);
if (initialized) {
exit_code = main (argc, argv);
break;
}
else
exit_code = msg.wParam;
}
free (argsin[0]);
free (argsin[1]);
free(argv);
return exit_code;
}
/**********************************************************************
* WndProc
*
* Function to respond to messages.
**********************************************************************/
LONG WINAPI WndProc( //message handler
HWND hwnd, //window with message
UINT msg, //message typ
WPARAM wParam,
LPARAM lParam) {
HDC hdc;
if (msg == WM_CREATE) {
//
// Create a rendering context.
//
hdc = GetDC (hwnd);
ReleaseDC(hwnd, hdc);
initialized = 1;
return 0;
}
return DefWindowProc (hwnd, msg, wParam, lParam);
}
/**********************************************************************
* parse_args
*
* Turn a list of args into a new list of args with each separate
* whitespace spaced string being an arg.
**********************************************************************/
int
parse_args ( /*refine arg list */
int argc, /*no of input args */
char *argv[], /*input args */
char *arglist[] /*output args */
) {
int argcount; /*converted argc */
char *testchar; /*char in option string */
int arg; /*current argument */
argcount = 0; /*no of options */
for (arg = 0; arg < argc; arg++) {
testchar = argv[arg]; /*start of arg */
do {
while (*testchar
&& (*testchar == ' ' || *testchar == '\n'
|| *testchar == '\t'))
testchar++; /*skip white space */
if (*testchar) {
/*new arg */
arglist[argcount++] = testchar;
/*skip to white space */
for (testchar++; *testchar && *testchar != ' ' && *testchar != '\n' && *testchar != '\t'; testchar++) ;
if (*testchar)
*testchar++ = '\0'; /*turn to separate args */
}
}
while (*testchar);
}
return argcount; /*new number of args */
}
#endif
<commit_msg>check return code of API init (issue 593)<commit_after>/**********************************************************************
* File: tessedit.cpp (Formerly tessedit.c)
* Description: Main program for merge of tess and editor.
* Author: Ray Smith
* Created: Tue Jan 07 15:21:46 GMT 1992
*
* (C) Copyright 1992, Hewlett-Packard Ltd.
** Licensed under the Apache License, Version 2.0 (the "License");
** you may not use this file except in compliance with the License.
** You may obtain a copy of the License at
** http://www.apache.org/licenses/LICENSE-2.0
** Unless required by applicable law or agreed to in writing, software
** distributed under the License is distributed on an "AS IS" BASIS,
** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
** See the License for the specific language governing permissions and
** limitations under the License.
*
**********************************************************************/
#include "mfcpch.h"
// #define USE_VLD //Uncomment for Visual Leak Detector.
#if (defined _MSC_VER && defined USE_VLD)
#include <vld.h>
#endif
// Include automatically generated configuration file if running autoconf
#ifdef HAVE_CONFIG_H
#include "config_auto.h"
#endif
#ifdef USING_GETTEXT
#include <libintl.h>
#include <locale.h>
#define _(x) gettext(x)
#else
#define _(x) (x)
#endif
#include "allheaders.h"
#include "baseapi.h"
#include "strngs.h"
#include "tesseractmain.h"
/**********************************************************************
* main()
*
**********************************************************************/
int main(int argc, char **argv) {
#ifdef USE_NLS
setlocale (LC_ALL, "");
bindtextdomain (PACKAGE, LOCALEDIR);
textdomain (PACKAGE);
#endif
if ((argc == 2 && strcmp(argv[1], "-v") == 0) ||
(argc == 2 && strcmp(argv[1], "--version") == 0)) {
fprintf(stderr, "tesseract %s\n", tesseract::TessBaseAPI::Version());
exit(0);
}
// Make the order of args a bit more forgiving than it used to be.
const char* lang = "eng";
const char* image = NULL;
const char* output = NULL;
tesseract::PageSegMode pagesegmode = tesseract::PSM_AUTO;
int arg = 1;
while (arg < argc && (output == NULL || argv[arg][0] == '-')) {
if (strcmp(argv[arg], "-l") == 0 && arg + 1 < argc) {
lang = argv[arg + 1];
++arg;
} else if (strcmp(argv[arg], "-psm") == 0 && arg + 1 < argc) {
pagesegmode = static_cast<tesseract::PageSegMode>(atoi(argv[arg + 1]));
++arg;
} else if (image == NULL) {
image = argv[arg];
} else if (output == NULL) {
output = argv[arg];
}
++arg;
}
if (output == NULL) {
fprintf(stderr, _("Usage:%s imagename outputbase [-l lang] "
"[-psm pagesegmode] [configfile...]\n"), argv[0]);
fprintf(stderr,
_("pagesegmode values are:\n"
"0 = Orientation and script detection (OSD) only.\n"
"1 = Automatic page segmentation with OSD.\n"
"2 = Automatic page segmentation, but no OSD, or OCR\n"
"3 = Fully automatic page segmentation, but no OSD. (Default)\n"
"4 = Assume a single column of text of variable sizes.\n"
"5 = Assume a single uniform block of vertically aligned text.\n"
"6 = Assume a single uniform block of text.\n"
"7 = Treat the image as a single text line.\n"
"8 = Treat the image as a single word.\n"
"9 = Treat the image as a single word in a circle.\n"
"10 = Treat the image as a single character.\n"));
fprintf(stderr, _("-l lang and/or -psm pagesegmode must occur before any"
"configfile.\n"));
exit(1);
}
tesseract::TessBaseAPI api;
api.SetOutputName(output);
int rc = api.Init(argv[0], lang, tesseract::OEM_DEFAULT,
&(argv[arg]), argc - arg, NULL, NULL, false);
if (rc) {
fprintf(stderr, "Could not initialize tesseract.\n");
exit(1);
}
// We have 2 possible sources of pagesegmode: a config file and
// the command line. For backwards compatability reasons, the
// default in tesseract is tesseract::PSM_SINGLE_BLOCK, but the
// default for this program is tesseract::PSM_AUTO. We will let
// the config file take priority, so the command-line default
// can take priority over the tesseract default, so we use the
// value from the command line only if the retrieved mode
// is still tesseract::PSM_SINGLE_BLOCK, indicating no change
// in any config file. Therefore the only way to force
// tesseract::PSM_SINGLE_BLOCK is from the command line.
// It would be simpler if we could set the value before Init,
// but that doesn't work.
if (api.GetPageSegMode() == tesseract::PSM_SINGLE_BLOCK)
api.SetPageSegMode(pagesegmode);
printf("Tesseract Open Source OCR Engine v%s with Leptonica\n",
tesseract::TessBaseAPI::Version());
FILE* fin = fopen(image, "rb");
if (fin == NULL) {
printf("Cannot open input file: %s\n", image);
exit(2);
}
fclose(fin);
PIX *pixs;
if ((pixs = pixRead(image)) == NULL) {
printf("Unsupported image type.\n");
exit(3);
}
pixDestroy(&pixs);
STRING text_out;
if (!api.ProcessPages(image, NULL, 0, &text_out)) {
printf("Error during processing.\n");
}
bool output_hocr = false;
api.GetBoolVariable("tessedit_create_hocr", &output_hocr);
bool output_box = false;
api.GetBoolVariable("tessedit_create_boxfile", &output_box);
STRING outfile = output;
outfile += output_hocr ? ".html" : output_box ? ".box" : ".txt";
FILE* fout = fopen(outfile.string(), "wb");
if (fout == NULL) {
printf("Cannot create output file %s\n", outfile.string());
exit(1);
}
fwrite(text_out.string(), 1, text_out.length(), fout);
fclose(fout);
return 0; // Normal exit
}
#ifdef _WIN32
char szAppName[] = "Tesseract"; //app name
int initialized = 0;
/**********************************************************************
* WinMain
*
* Main function for a windows program.
**********************************************************************/
int WINAPI WinMain( //main for windows //command line
HINSTANCE hInstance,
HINSTANCE hPrevInstance,
LPSTR lpszCmdLine,
int nCmdShow) {
WNDCLASS wc;
HWND hwnd;
MSG msg;
char **argv;
char *argsin[2];
int argc;
int exit_code;
wc.style = CS_NOCLOSE | CS_OWNDC;
wc.lpfnWndProc = (WNDPROC) WndProc;
wc.cbClsExtra = 0;
wc.cbWndExtra = 0;
wc.hInstance = hInstance;
wc.hIcon = NULL; //LoadIcon (NULL, IDI_APPLICATION);
wc.hCursor = NULL; //LoadCursor (NULL, IDC_ARROW);
wc.hbrBackground = (HBRUSH) (COLOR_WINDOW + 1);
wc.lpszMenuName = NULL;
wc.lpszClassName = szAppName;
RegisterClass(&wc);
hwnd = CreateWindow (szAppName, szAppName,
WS_OVERLAPPEDWINDOW | WS_DISABLED,
CW_USEDEFAULT, CW_USEDEFAULT, CW_USEDEFAULT,
CW_USEDEFAULT, HWND_DESKTOP, NULL, hInstance, NULL);
argsin[0] = strdup (szAppName);
argsin[1] = strdup (lpszCmdLine);
/*allocate memory for the args. There can never be more than half*/
/*the total number of characters in the arguments.*/
argv = (char **)malloc(((strlen(argsin[0]) + strlen(argsin[1])) / 2 + 1) *
sizeof(char *));
/*now construct argv as it should be for C.*/
argc = parse_args (2, argsin, argv);
// ShowWindow (hwnd, nCmdShow);
// UpdateWindow (hwnd);
if (initialized) {
exit_code = main (argc, argv);
free (argsin[0]);
free (argsin[1]);
free(argv);
return exit_code;
}
while (GetMessage (&msg, NULL, 0, 0)) {
TranslateMessage(&msg);
DispatchMessage(&msg);
if (initialized) {
exit_code = main (argc, argv);
break;
}
else
exit_code = msg.wParam;
}
free (argsin[0]);
free (argsin[1]);
free(argv);
return exit_code;
}
/**********************************************************************
* WndProc
*
* Function to respond to messages.
**********************************************************************/
LONG WINAPI WndProc( //message handler
HWND hwnd, //window with message
UINT msg, //message typ
WPARAM wParam,
LPARAM lParam) {
HDC hdc;
if (msg == WM_CREATE) {
//
// Create a rendering context.
//
hdc = GetDC (hwnd);
ReleaseDC(hwnd, hdc);
initialized = 1;
return 0;
}
return DefWindowProc (hwnd, msg, wParam, lParam);
}
/**********************************************************************
* parse_args
*
* Turn a list of args into a new list of args with each separate
* whitespace spaced string being an arg.
**********************************************************************/
int
parse_args ( /*refine arg list */
int argc, /*no of input args */
char *argv[], /*input args */
char *arglist[] /*output args */
) {
int argcount; /*converted argc */
char *testchar; /*char in option string */
int arg; /*current argument */
argcount = 0; /*no of options */
for (arg = 0; arg < argc; arg++) {
testchar = argv[arg]; /*start of arg */
do {
while (*testchar
&& (*testchar == ' ' || *testchar == '\n'
|| *testchar == '\t'))
testchar++; /*skip white space */
if (*testchar) {
/*new arg */
arglist[argcount++] = testchar;
/*skip to white space */
for (testchar++; *testchar && *testchar != ' ' && *testchar != '\n' && *testchar != '\t'; testchar++) ;
if (*testchar)
*testchar++ = '\0'; /*turn to separate args */
}
}
while (*testchar);
}
return argcount; /*new number of args */
}
#endif
<|endoftext|> |
<commit_before>/*
MobaTools.h - a library for model railroaders
Author: fpm, fpm@mnet-mail.de
Copyright (c) 2020 All right reserved.
Functions for the stepper part of MobaTools
*/
#ifdef ARDUINO_ARCH_AVR //this is only for 8Bit AVR controllers
#define COMPILING_MOTOSOFTLED_CPP
#include <MobaTools.h>
//#define debugPrint
//#define debugTP
#include <utilities/MoToDbg.h>
// Global Data for all instances and classes --------------------------------
// variables for softLeds
static ledData_t* ledRootP = NULL; //start of _ledData-chain
static uint8_t ledNextCyc = TIMERPERIODE / CYCLETIME; // next Cycle that is relevant for leds
static uint8_t ledCycleCnt = 0; // count IRQ cycles within PWM cycle
static ledData_t* ledDataP; // pointer to active Led in ISR
void softledISR(uintx8_t cyclesLastIRQ) { // uint8 for AVR, uint32 for 32-Bit processors
// ---------------------- softleds -----------------------------------------------
SET_TP2;
ledCycleCnt += cyclesLastIRQ;
if ( ledCycleCnt >= ledNextCyc ) {
// this IRQ is relevant for softleds
ledNextCyc = LED_CYCLE_MAX; // there must be atleast one IRQ per PWM Cycle
if ( ledCycleCnt >= LED_CYCLE_MAX ) {
// start of a new PWM Cycle - switch all leds with rising/falling state to on
// When rising, check if full on is reached
ledCycleCnt = 0;
for ( ledDataP=ledRootP; ledDataP!=NULL; ledDataP = ledDataP->nextLedDataP ) {
//SET_TP1;
// loop over led-objects
switch ( ledDataP->state ) {
case INCBULB:
case INCLIN:
// led with rising brightness
noInterrupts();
if (ledDataP->invFlg ) {
#ifdef FAST_PORTWRT
*ledDataP->portPin.Adr &= ~ledDataP->portPin.Mask;
#else
digitalWrite( ledDataP->pin, LOW );
#endif
} else {
#ifdef FAST_PORTWRT
*ledDataP->portPin.Adr |= ledDataP->portPin.Mask;
#else
digitalWrite( ledDataP->pin, HIGH );
#endif
}
interrupts();
// check if led on is reached
if ( ledDataP->aCycle >= LED_CYCLE_MAX ) { // led is full on, remove from active-chain
SET_TP4;
ledDataP->state = STATE_ON;
*ledDataP->backLedDataPP = ledDataP->nextLedDataP;
if ( ledDataP->nextLedDataP ) ledDataP->nextLedDataP->backLedDataPP = ledDataP->backLedDataPP;
ledDataP->aCycle = 0;
CLR_TP4;
} else { // set off-time
if ( ledNextCyc > ledDataP->aCycle ) ledNextCyc = ledDataP->aCycle;
ledDataP->actPulse = true;
}
break;
case DECBULB:
case DECLIN:
// led with falling brightness
if (ledDataP->invFlg ) {
#ifdef FAST_PORTWRT
*ledDataP->portPin.Adr &= ~ledDataP->portPin.Mask;
#else
digitalWrite( ledDataP->pin, LOW );
#endif
} else {
#ifdef FAST_PORTWRT
*ledDataP->portPin.Adr |= ledDataP->portPin.Mask;
#else
digitalWrite( ledDataP->pin, HIGH );
#endif
}
// set off-time
if ( ledNextCyc > ledDataP->aCycle ) ledNextCyc = ledDataP->aCycle;
ledDataP->actPulse = true;
break;
default: ;
} // end of 'switch'
//CLR_TP1;
} // end of led loop
} else { // is switchofftime within PWM cycle
SET_TP3;
for ( ledDataP=ledRootP; ledDataP!=NULL; ledDataP = ledDataP->nextLedDataP ) {
//SET_TP4;
if ( ledDataP->actPulse ) {
// led is within PWM cycle with output high
if ( ledDataP->aCycle <= ledCycleCnt ) {
uint8_t tmpIx;
// End of ON-time is reached
SET_TP4;
if (ledDataP->invFlg ) {
#ifdef FAST_PORTWRT
*ledDataP->portPin.Adr |= ledDataP->portPin.Mask;
#else
digitalWrite( ledDataP->pin, HIGH );
#endif
} else {
#ifdef FAST_PORTWRT
*ledDataP->portPin.Adr &= ~ledDataP->portPin.Mask;
#else
digitalWrite( ledDataP->pin, LOW );
#endif
}
CLR_TP4;
ledDataP->actPulse = false; // Led pulse is LOW now
// determine length of next PWM Cyle
//SET_TP1;
SET_TP4;
ledDataP->aStep += ledDataP->speed;
tmpIx = (ledDataP->aStep/DELTASTEPS);
if ( tmpIx > LED_IX_MAX ) {
// the end is reached
CLR_TP4;
switch ( ledDataP->state ) {
case DECBULB:
case DECLIN:
// led is off -> remove from chain
ledDataP->state = STATE_OFF;
*ledDataP->backLedDataPP = ledDataP->nextLedDataP;
if ( ledDataP->nextLedDataP ) ledDataP->nextLedDataP->backLedDataPP = ledDataP->backLedDataPP;
break;
case INCBULB:
case INCLIN:
// switch permanetly on wirh next cycle
ledDataP->aCycle = LED_CYCLE_MAX;
break;
default:
;
}
SET_TP4;
} else {
// we are still in up/down
CLR_TP4;
switch ( ledDataP->state ) {
case INCBULB:
ledDataP->aCycle = pgm_read_byte(&(iSteps[tmpIx]));
break;
case DECBULB:
//CLR_TP1;
ledDataP->aCycle = LED_CYCLE_MAX-pgm_read_byte(&(iSteps[tmpIx]));
//SET_TP1;
break;
case INCLIN:
ledDataP->aCycle = tmpIx;
break;
case DECLIN:
ledDataP->aCycle = LED_CYCLE_MAX - tmpIx;
break;
default:
// no action if state is one of NOTATTACHED, STATE_ON, STATE_OFF
break;
}
SET_TP4;
}
CLR_TP4;
} else {
// End of ON-time not yet reached, compute next necessary step
CLR_TP3;
ledNextCyc = min( ledDataP->aCycle, ledNextCyc);
SET_TP3;
}
}
//CLR_TP4;
}
CLR_TP3;
}
//CLR_TP3;
} // end of softleds
//CLR_TP3;
nextCycle = min( nextCycle, ( ledNextCyc-ledCycleCnt ) );
//SET_TP3;
CLR_TP2;
} //=============================== End of softledISR ========================================
/////////////////////////////////////////////////////////////////////////////
//Class MoToMoToSoftLed - for Led with soft on / soft off ---------------------------
// Version with Software PWM
MoToSoftLed::MoToSoftLed() {
_ledData.speed = 0; // defines rising/falling timer
_ledData.aStep = DELTASTEPS ; // actual PWM step
_ledData.aCycle = 0; // actual cycle ( =length of PWM pule )
_ledData.actPulse = false; // PWM pulse is active
_ledData.state = NOTATTACHED; // initialize
_setpoint = OFF ; // initialize to off
_ledType = LINEAR;
_ledData.nextLedDataP = NULL; // don't put in ISR chain
_ledData.invFlg = false;
}
void MoToSoftLed::mount( LedStats_t stateVal ) {
// mount softLed to ISR chain ( if not already in )
// new active Softleds are always inserted at the beginning of the chain
// only leds in the ISR chain are processed in ISR
noInterrupts();
//SET_TP2;
// check if it's not already active (mounted)
// Leds must not be mounted twice!
if ( _ledData.state < ACTIVE ) {
// write backward reference into the existing first entry
// only if the chain is not empty
if ( ledRootP ) ledRootP->backLedDataPP = &_ledData.nextLedDataP;
//CLR_TP2;
_ledData.nextLedDataP = ledRootP;
ledRootP = &_ledData;
_ledData.backLedDataPP = &ledRootP;
//SET_TP2;
}
_ledData.state = stateVal;
//CLR_TP2;
interrupts();
}
uint8_t MoToSoftLed::attach(uint8_t pinArg, uint8_t invArg ){
// Led-Ausgang mit Softstart.
_ledData.invFlg = invArg;
pinMode( pinArg, OUTPUT );
//DB_PRINT( "Led attached, ledIx = 0x%x, Count = %d", ledIx, ledCount );
_ledData.state = STATE_OFF ; // initialize
riseTime( LED_DEFAULT_RISETIME );
if ( _ledData.invFlg ) {
digitalWrite( pinArg, HIGH );
} else {
digitalWrite( pinArg, LOW );
}
#ifdef FAST_PORTWRT
_ledData.portPin.Adr = (byte *) pgm_read_word_near(&port_to_output_PGM[pgm_read_byte_near(&digital_pin_to_port_PGM[pinArg])]);
_ledData.portPin.Mask = pgm_read_byte_near(&digital_pin_to_bit_mask_PGM[pinArg]);
#else
_ledData.pin=pinArg ; // Pin-Nbr
#endif
seizeTimerAS();
// enable compareB- interrupt
#if defined(__AVR_ATmega8__)|| defined(__AVR_ATmega128__)
TIMSK |= ( _BV(OCIExB) ); // enable compare interrupts
#else
TIMSKx |= _BV(OCIExB) ;
#endif
DB_PRINT("IX_MAX=%d, CYCLE_MAX=%d, PWMTIME=%d", LED_IX_MAX, LED_CYCLE_MAX, LED_PWMTIME );
return true;
}
void MoToSoftLed::on(uint8_t value){
on();
}
void MoToSoftLed::on(){
if ( _ledData.state == NOTATTACHED ) return; // this is not a valid instance
LedStats_t stateT;
// Don't do anything if its already ON
if ( _setpoint != ON ) {
_setpoint = ON ;
/*if ( _ledData.state < ACTIVE ) {
// is full off*/
_ledData.aStep = DELTASTEPS;
/*} else {
// is counting up
_ledData.aStep = LED_STEP_MAX - _ledData.aStep;
}*/
_ledData.speed = _ledSpeed;
if ( _ledType == LINEAR ) {
stateT = INCLIN;
_ledData.aCycle = 1;
} else { // is bulb simulation
stateT = INCBULB;
_ledData.aCycle = iSteps[1];
}
mount(stateT);
}
DB_PRINT( "Led %04X On, state=%d, ledRoot=%04X", (uint32_t)this, _ledData.state, (uintxx_t)ledRootP);
}
void MoToSoftLed::off(uint8_t value){
off();
}
void MoToSoftLed::off(){
if ( _ledData.state == NOTATTACHED ) return; // this is not a valid instance
LedStats_t stateT;
// Dont do anything if its already OFF
if ( _setpoint != OFF ) {
//SET_TP3;
_setpoint = OFF;
/*if ( _ledData.state < ACTIVE ) {
// is full on*/
_ledData.aStep = DELTASTEPS;
/*} else {
// is counting up
_ledData.aStep = LED_STEP_MAX -_ledData.aStep;
}*/
_ledData.speed = _ledSpeed;
if ( _ledType == LINEAR ) {
stateT = DECLIN;
_ledData.aCycle = LED_IX_MAX;
} else { // is bulb simulation
//CLR_TP3;
stateT = DECBULB;
_ledData.aCycle = LED_CYCLE_MAX - iSteps[1];
}
//CLR_TP3;
mount(stateT);
}
DB_PRINT( "Led %04X Off, state=%d", (uint32_t)this, _ledData.state);
}
void MoToSoftLed::toggle( void ) {
if ( _ledData.state == NOTATTACHED ) return; // this is not a valid instance
if ( _setpoint == ON ) off();
else on();
}
void MoToSoftLed::write( uint8_t setpntVal, uint8_t ledPar ){
if ( _ledData.state == NOTATTACHED ) return; // this is not a valid instance
_ledType = ledPar;
write( setpntVal ) ;
}
void MoToSoftLed::write( uint8_t setpntVal ){
//DB_PRINT( "LedWrite ix= %d, valid= 0x%x, sp=%d, lT=%d", ledIx, ledValid, setpntVal, _ledType );
if ( _ledData.state == NOTATTACHED ) return; // this is not a valid instance
if ( setpntVal == ON ) on(); else off();
#ifdef debug
// im Debugmode hier die Led-Daten ausgeben
//DB_PRINT( "_ledData[%d]\n\speed=%d, Type=%d, aStep=%d, stpCnt=%d, state=%d, _setpoint= %d", ledValid, _ledSpeed, _ledType, _ledData.aStep, _ledData.stpCnt, _ledData.state, _setpoint);
//DB_PRINT( "ON=%d, NextCyc=%d, CycleCnt=%d, StepIx=%d, NextStep=%d",
// ON, ledNextCyc, ledCycleCnt, ledStepIx, ledNextStep);
#endif
}
void MoToSoftLed::riseTime( uint16_t riseTime ) {
if ( _ledData.state == NOTATTACHED ) return;
// length of startphase in ms (min 20ms )
// The max value ist slower, if CYCLETIME is reduced.
// risetime is computed to a 'speed' Value with 16 beeing the slowest
// with speed value = 16 means risetime is (LED_CYCLE_MAX * LED_PWMTIME * DELTATIME / 16)
// risetime = (LED_CYCLE_MAX * LED_PWMTIME * DELTATIME) / speed
//
long riseMax = ((long) LED_CYCLE_MAX * DELTASTEPS * LED_PWMTIME );
if ( riseTime <= 20 ) riseTime = 20;
if ( riseTime >= riseMax/16 ) riseTime = riseMax/16;
int tmp = ( ((long)riseMax *10) / ( riseTime ) +5 ) /10;
_ledSpeed = tmp;
DB_PRINT( "_ledSpeed = %d ( risetime=%d, riseMax=%d, PWMTIME=%d )", _ledSpeed, riseTime, riseMax, LED_PWMTIME );
}
#endif // ESP
<commit_msg>Update MoToSoftled.cpp<commit_after>/*
MobaTools.h - a library for model railroaders
Author: fpm, fpm@mnet-mail.de
Copyright (c) 2020 All right reserved.
Functions for the stepper part of MobaTools
*/
#ifdef ARDUINO_ARCH_AVR //this is only for 8Bit AVR controllers
#define COMPILING_MOTOSOFTLED_CPP
#include <MobaTools.h>
//#define debugPrint
//#define debugTP
#include <utilities/MoToDbg.h>
// Global Data for all instances and classes --------------------------------
// variables for softLeds
static ledData_t* ledRootP = NULL; //start of _ledData-chain
static uint8_t ledNextCyc = TIMERPERIODE / CYCLETIME; // next Cycle that is relevant for leds
static uint8_t ledCycleCnt = 0; // count IRQ cycles within PWM cycle
static ledData_t* ledDataP; // pointer to active Led in ISR
void softledISR(uintx8_t cyclesLastIRQ) { // uint8 for AVR, uint32 for 32-Bit processors
// ---------------------- softleds -----------------------------------------------
SET_TP2;
ledCycleCnt += cyclesLastIRQ;
if ( ledCycleCnt >= ledNextCyc ) {
// this IRQ is relevant for softleds
ledNextCyc = LED_CYCLE_MAX; // there must be atleast one IRQ per PWM Cycle
if ( ledCycleCnt >= LED_CYCLE_MAX ) {
// start of a new PWM Cycle - switch all leds with rising/falling state to on
// When rising, check if full on is reached
ledCycleCnt = 0;
for ( ledDataP=ledRootP; ledDataP!=NULL; ledDataP = ledDataP->nextLedDataP ) {
//SET_TP1;
// loop over led-objects
switch ( ledDataP->state ) {
case INCBULB:
case INCLIN:
// led with rising brightness
noInterrupts();
if (ledDataP->invFlg ) {
#ifdef FAST_PORTWRT
*ledDataP->portPin.Adr &= ~ledDataP->portPin.Mask;
#else
digitalWrite( ledDataP->pin, LOW );
#endif
} else {
#ifdef FAST_PORTWRT
*ledDataP->portPin.Adr |= ledDataP->portPin.Mask;
#else
digitalWrite( ledDataP->pin, HIGH );
#endif
}
interrupts();
// check if led on is reached
if ( ledDataP->aCycle >= LED_CYCLE_MAX ) { // led is full on, remove from active-chain
SET_TP4;
ledDataP->state = STATE_ON;
*ledDataP->backLedDataPP = ledDataP->nextLedDataP;
if ( ledDataP->nextLedDataP ) ledDataP->nextLedDataP->backLedDataPP = ledDataP->backLedDataPP;
ledDataP->aCycle = 0;
CLR_TP4;
} else { // set off-time
if ( ledNextCyc > ledDataP->aCycle ) ledNextCyc = ledDataP->aCycle;
ledDataP->actPulse = true;
}
break;
case DECBULB:
case DECLIN:
// led with falling brightness
if (ledDataP->invFlg ) {
#ifdef FAST_PORTWRT
*ledDataP->portPin.Adr &= ~ledDataP->portPin.Mask;
#else
digitalWrite( ledDataP->pin, LOW );
#endif
} else {
#ifdef FAST_PORTWRT
*ledDataP->portPin.Adr |= ledDataP->portPin.Mask;
#else
digitalWrite( ledDataP->pin, HIGH );
#endif
}
// set off-time
if ( ledNextCyc > ledDataP->aCycle ) ledNextCyc = ledDataP->aCycle;
ledDataP->actPulse = true;
break;
default: ;
} // end of 'switch'
//CLR_TP1;
} // end of led loop
} else { // is switchofftime within PWM cycle
SET_TP3;
for ( ledDataP=ledRootP; ledDataP!=NULL; ledDataP = ledDataP->nextLedDataP ) {
//SET_TP4;
if ( ledDataP->actPulse ) {
// led is within PWM cycle with output high
if ( ledDataP->aCycle <= ledCycleCnt ) {
uint8_t tmpIx;
// End of ON-time is reached
SET_TP4;
if (ledDataP->invFlg ) {
#ifdef FAST_PORTWRT
*ledDataP->portPin.Adr |= ledDataP->portPin.Mask;
#else
digitalWrite( ledDataP->pin, HIGH );
#endif
} else {
#ifdef FAST_PORTWRT
*ledDataP->portPin.Adr &= ~ledDataP->portPin.Mask;
#else
digitalWrite( ledDataP->pin, LOW );
#endif
}
CLR_TP4;
ledDataP->actPulse = false; // Led pulse is LOW now
// determine length of next PWM Cyle
//SET_TP1;
SET_TP4;
ledDataP->aStep += ledDataP->speed;
tmpIx = (ledDataP->aStep/DELTASTEPS);
if ( tmpIx > LED_IX_MAX ) {
// the end is reached
CLR_TP4;
switch ( ledDataP->state ) {
case DECBULB:
case DECLIN:
// led is off -> remove from chain
ledDataP->state = STATE_OFF;
*ledDataP->backLedDataPP = ledDataP->nextLedDataP;
if ( ledDataP->nextLedDataP ) ledDataP->nextLedDataP->backLedDataPP = ledDataP->backLedDataPP;
break;
case INCBULB:
case INCLIN:
// switch permanetly on wirh next cycle
ledDataP->aCycle = LED_CYCLE_MAX;
break;
default:
;
}
SET_TP4;
} else {
// we are still in up/down
CLR_TP4;
switch ( ledDataP->state ) {
case INCBULB:
ledDataP->aCycle = pgm_read_byte(&(iSteps[tmpIx]));
break;
case DECBULB:
//CLR_TP1;
ledDataP->aCycle = LED_CYCLE_MAX-pgm_read_byte(&(iSteps[tmpIx]));
//SET_TP1;
break;
case INCLIN:
ledDataP->aCycle = tmpIx;
break;
case DECLIN:
ledDataP->aCycle = LED_CYCLE_MAX - tmpIx;
break;
default:
// no action if state is one of NOTATTACHED, STATE_ON, STATE_OFF
break;
}
SET_TP4;
}
CLR_TP4;
} else {
// End of ON-time not yet reached, compute next necessary step
CLR_TP3;
ledNextCyc = min( ledDataP->aCycle, ledNextCyc);
SET_TP3;
}
}
//CLR_TP4;
}
CLR_TP3;
}
//CLR_TP3;
} // end of softleds
//CLR_TP3;
nextCycle = min( nextCycle, ( ledNextCyc-ledCycleCnt ) );
//SET_TP3;
CLR_TP2;
} //=============================== End of softledISR ========================================
/////////////////////////////////////////////////////////////////////////////
//Class MoToMoToSoftLed - for Led with soft on / soft off ---------------------------
// Version with Software PWM
MoToSoftLed::MoToSoftLed() {
_ledData.speed = 0; // defines rising/falling timer
_ledData.aStep = DELTASTEPS ; // actual PWM step
_ledData.aCycle = 0; // actual cycle ( =length of PWM pule )
_ledData.actPulse = false; // PWM pulse is active
_ledData.state = NOTATTACHED; // initialize
_setpoint = OFF ; // initialize to off
_ledType = LINEAR;
_ledData.nextLedDataP = NULL; // don't put in ISR chain
_ledData.invFlg = false;
}
void MoToSoftLed::mount( LedStats_t stateVal ) {
// mount softLed to ISR chain ( if not already in )
// new active Softleds are always inserted at the beginning of the chain
// only leds in the ISR chain are processed in ISR
noInterrupts();
//SET_TP2;
// check if it's not already active (mounted)
// Leds must not be mounted twice!
if ( _ledData.state < ACTIVE ) {
// write backward reference into the existing first entry
// only if the chain is not empty
if ( ledRootP ) ledRootP->backLedDataPP = &_ledData.nextLedDataP;
//CLR_TP2;
_ledData.nextLedDataP = ledRootP;
ledRootP = &_ledData;
_ledData.backLedDataPP = &ledRootP;
//SET_TP2;
}
_ledData.state = stateVal;
//CLR_TP2;
interrupts();
}
uint8_t MoToSoftLed::attach(uint8_t pinArg, uint8_t invArg ){
// Led-Ausgang mit Softstart.
_ledData.invFlg = invArg;
pinMode( pinArg, OUTPUT );
//DB_PRINT( "Led attached, ledIx = 0x%x, Count = %d", ledIx, ledCount );
_ledData.state = STATE_OFF ; // initialize
riseTime( LED_DEFAULT_RISETIME );
if ( _ledData.invFlg ) {
digitalWrite( pinArg, HIGH );
} else {
digitalWrite( pinArg, LOW );
}
#ifdef FAST_PORTWRT
_ledData.portPin.Adr = (byte *) pgm_read_word_near(&port_to_output_PGM[pgm_read_byte_near(&digital_pin_to_port_PGM[pinArg])]);
_ledData.portPin.Mask = pgm_read_byte_near(&digital_pin_to_bit_mask_PGM[pinArg]);
#else
_ledData.pin=pinArg ; // Pin-Nbr
#endif
seizeTimerAS();
// enable compareB- interrupt
#if defined(__AVR_ATmega8__)|| defined(__AVR_ATmega128__)
TIMSK |= ( _BV(OCIExB) ); // enable compare interrupts
#else
TIMSKx |= _BV(OCIExB) ;
#endif
DB_PRINT("IX_MAX=%d, CYCLE_MAX=%d, PWMTIME=%d", LED_IX_MAX, LED_CYCLE_MAX, LED_PWMTIME );
return true;
}
void MoToSoftLed::on(){
if ( _ledData.state == NOTATTACHED ) return; // this is not a valid instance
LedStats_t stateT;
// Don't do anything if its already ON
if ( _setpoint != ON ) {
_setpoint = ON ;
/*if ( _ledData.state < ACTIVE ) {
// is full off*/
_ledData.aStep = DELTASTEPS;
/*} else {
// is counting up
_ledData.aStep = LED_STEP_MAX - _ledData.aStep;
}*/
_ledData.speed = _ledSpeed;
if ( _ledType == LINEAR ) {
stateT = INCLIN;
_ledData.aCycle = 1;
} else { // is bulb simulation
stateT = INCBULB;
_ledData.aCycle = iSteps[1];
}
mount(stateT);
}
DB_PRINT( "Led %04X On, state=%d, ledRoot=%04X", (uint32_t)this, _ledData.state, (uintxx_t)ledRootP);
}
void MoToSoftLed::off(){
if ( _ledData.state == NOTATTACHED ) return; // this is not a valid instance
LedStats_t stateT;
// Dont do anything if its already OFF
if ( _setpoint != OFF ) {
//SET_TP3;
_setpoint = OFF;
/*if ( _ledData.state < ACTIVE ) {
// is full on*/
_ledData.aStep = DELTASTEPS;
/*} else {
// is counting up
_ledData.aStep = LED_STEP_MAX -_ledData.aStep;
}*/
_ledData.speed = _ledSpeed;
if ( _ledType == LINEAR ) {
stateT = DECLIN;
_ledData.aCycle = LED_IX_MAX;
} else { // is bulb simulation
//CLR_TP3;
stateT = DECBULB;
_ledData.aCycle = LED_CYCLE_MAX - iSteps[1];
}
//CLR_TP3;
mount(stateT);
}
DB_PRINT( "Led %04X Off, state=%d", (uint32_t)this, _ledData.state);
}
void MoToSoftLed::toggle( void ) {
if ( _ledData.state == NOTATTACHED ) return; // this is not a valid instance
if ( _setpoint == ON ) off();
else on();
}
void MoToSoftLed::write( uint8_t setpntVal, uint8_t ledPar ){
if ( _ledData.state == NOTATTACHED ) return; // this is not a valid instance
_ledType = ledPar;
write( setpntVal ) ;
}
void MoToSoftLed::write( uint8_t setpntVal ){
//DB_PRINT( "LedWrite ix= %d, valid= 0x%x, sp=%d, lT=%d", ledIx, ledValid, setpntVal, _ledType );
if ( _ledData.state == NOTATTACHED ) return; // this is not a valid instance
if ( setpntVal == ON ) on(); else off();
#ifdef debug
// im Debugmode hier die Led-Daten ausgeben
//DB_PRINT( "_ledData[%d]\n\speed=%d, Type=%d, aStep=%d, stpCnt=%d, state=%d, _setpoint= %d", ledValid, _ledSpeed, _ledType, _ledData.aStep, _ledData.stpCnt, _ledData.state, _setpoint);
//DB_PRINT( "ON=%d, NextCyc=%d, CycleCnt=%d, StepIx=%d, NextStep=%d",
// ON, ledNextCyc, ledCycleCnt, ledStepIx, ledNextStep);
#endif
}
void MoToSoftLed::riseTime( uint16_t riseTime ) {
if ( _ledData.state == NOTATTACHED ) return;
// length of startphase in ms (min 20ms )
// The max value ist slower, if CYCLETIME is reduced.
// risetime is computed to a 'speed' Value with 16 beeing the slowest
// with speed value = 16 means risetime is (LED_CYCLE_MAX * LED_PWMTIME * DELTATIME / 16)
// risetime = (LED_CYCLE_MAX * LED_PWMTIME * DELTATIME) / speed
//
long riseMax = ((long) LED_CYCLE_MAX * DELTASTEPS * LED_PWMTIME );
if ( riseTime <= 20 ) riseTime = 20;
if ( riseTime >= riseMax/16 ) riseTime = riseMax/16;
int tmp = ( ((long)riseMax *10) / ( riseTime ) +5 ) /10;
_ledSpeed = tmp;
DB_PRINT( "_ledSpeed = %d ( risetime=%d, riseMax=%d, PWMTIME=%d )", _ledSpeed, riseTime, riseMax, LED_PWMTIME );
}
// For compatibility with code written for other platforms too
// The avr implementation ignores parameters in the on and off method
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wunused-parameter"
void MoToSoftLed::on(uint8_t value){
on();
}
void MoToSoftLed::off(uint8_t value){
off();
}
#pragma GCC diagnostic pop
#endif // ARDUINO_ARCH_AVR
<|endoftext|> |
<commit_before>/*
* Copyright (c) 2014 The WebRTC project authors. All Rights Reserved.
*
* Use of this source code is governed by a BSD-style license
* that can be found in the LICENSE file in the root of the source
* tree. An additional intellectual property rights grant can be found
* in the file PATENTS. All contributing project authors may
* be found in the AUTHORS file in the root of the source tree.
*/
#include "webrtc/modules/audio_coding/codecs/g722/include/audio_encoder_g722.h"
#include <limits>
#include "webrtc/base/checks.h"
#include "webrtc/modules/audio_coding/codecs/g722/include/g722_interface.h"
namespace webrtc {
namespace {
const int kSampleRateHz = 16000;
} // namespace
AudioEncoderG722::EncoderState::EncoderState() {
CHECK_EQ(0, WebRtcG722_CreateEncoder(&encoder));
CHECK_EQ(0, WebRtcG722_EncoderInit(encoder));
}
AudioEncoderG722::EncoderState::~EncoderState() {
CHECK_EQ(0, WebRtcG722_FreeEncoder(encoder));
}
AudioEncoderG722::AudioEncoderG722(const Config& config)
: num_channels_(config.num_channels),
payload_type_(config.payload_type),
num_10ms_frames_per_packet_(config.frame_size_ms / 10),
num_10ms_frames_buffered_(0),
first_timestamp_in_buffer_(0),
encoders_(new EncoderState[num_channels_]),
interleave_buffer_(new uint8_t[2 * num_channels_]) {
CHECK_EQ(config.frame_size_ms % 10, 0)
<< "Frame size must be an integer multiple of 10 ms.";
const int samples_per_channel =
kSampleRateHz / 100 * num_10ms_frames_per_packet_;
for (int i = 0; i < num_channels_; ++i) {
encoders_[i].speech_buffer.reset(new int16_t[samples_per_channel]);
encoders_[i].encoded_buffer.reset(new uint8_t[samples_per_channel / 2]);
}
}
AudioEncoderG722::~AudioEncoderG722() {}
int AudioEncoderG722::SampleRateHz() const {
return kSampleRateHz;
}
int AudioEncoderG722::RtpTimestampRateHz() const {
// The RTP timestamp rate for G.722 is 8000 Hz, even though it is a 16 kHz
// codec.
return kSampleRateHz / 2;
}
int AudioEncoderG722::NumChannels() const {
return num_channels_;
}
int AudioEncoderG722::Num10MsFramesInNextPacket() const {
return num_10ms_frames_per_packet_;
}
int AudioEncoderG722::Max10MsFramesInAPacket() const {
return num_10ms_frames_per_packet_;
}
bool AudioEncoderG722::EncodeInternal(uint32_t rtp_timestamp,
const int16_t* audio,
size_t max_encoded_bytes,
uint8_t* encoded,
EncodedInfo* info) {
const int samples_per_channel =
kSampleRateHz / 100 * num_10ms_frames_per_packet_;
CHECK_GE(max_encoded_bytes,
static_cast<size_t>(samples_per_channel) / 2 * num_channels_);
if (num_10ms_frames_buffered_ == 0)
first_timestamp_in_buffer_ = rtp_timestamp;
// Deinterleave samples and save them in each channel's buffer.
const int start = kSampleRateHz / 100 * num_10ms_frames_buffered_;
for (int i = 0; i < kSampleRateHz / 100; ++i)
for (int j = 0; j < num_channels_; ++j)
encoders_[j].speech_buffer[start + i] = audio[i * num_channels_ + j];
// If we don't yet have enough samples for a packet, we're done for now.
if (++num_10ms_frames_buffered_ < num_10ms_frames_per_packet_) {
info->encoded_bytes = 0;
return true;
}
// Encode each channel separately.
CHECK_EQ(num_10ms_frames_buffered_, num_10ms_frames_per_packet_);
num_10ms_frames_buffered_ = 0;
for (int i = 0; i < num_channels_; ++i) {
const int encoded = WebRtcG722_Encode(
encoders_[i].encoder, encoders_[i].speech_buffer.get(),
samples_per_channel, encoders_[i].encoded_buffer.get());
if (encoded < 0)
return false;
CHECK_EQ(encoded, samples_per_channel / 2);
}
// Interleave the encoded bytes of the different channels. Each separate
// channel and the interleaved stream encodes two samples per byte, most
// significant half first.
for (int i = 0; i < samples_per_channel / 2; ++i) {
for (int j = 0; j < num_channels_; ++j) {
uint8_t two_samples = encoders_[j].encoded_buffer[i];
interleave_buffer_[j] = two_samples >> 4;
interleave_buffer_[num_channels_ + j] = two_samples & 0xf;
}
for (int j = 0; j < num_channels_; ++j)
encoded[i * num_channels_ + j] =
interleave_buffer_[2 * j] << 4 | interleave_buffer_[2 * j + 1];
}
info->encoded_bytes = samples_per_channel / 2 * num_channels_;
info->encoded_timestamp = first_timestamp_in_buffer_;
info->payload_type = payload_type_;
return true;
}
} // namespace webrtc
<commit_msg>Method WebRtc_g722_encode that is eventually called always returns non-negative integer (internal counter)<commit_after>/*
* Copyright (c) 2014 The WebRTC project authors. All Rights Reserved.
*
* Use of this source code is governed by a BSD-style license
* that can be found in the LICENSE file in the root of the source
* tree. An additional intellectual property rights grant can be found
* in the file PATENTS. All contributing project authors may
* be found in the AUTHORS file in the root of the source tree.
*/
#include "webrtc/modules/audio_coding/codecs/g722/include/audio_encoder_g722.h"
#include <limits>
#include "webrtc/base/checks.h"
#include "webrtc/modules/audio_coding/codecs/g722/include/g722_interface.h"
namespace webrtc {
namespace {
const int kSampleRateHz = 16000;
} // namespace
AudioEncoderG722::EncoderState::EncoderState() {
CHECK_EQ(0, WebRtcG722_CreateEncoder(&encoder));
CHECK_EQ(0, WebRtcG722_EncoderInit(encoder));
}
AudioEncoderG722::EncoderState::~EncoderState() {
CHECK_EQ(0, WebRtcG722_FreeEncoder(encoder));
}
AudioEncoderG722::AudioEncoderG722(const Config& config)
: num_channels_(config.num_channels),
payload_type_(config.payload_type),
num_10ms_frames_per_packet_(config.frame_size_ms / 10),
num_10ms_frames_buffered_(0),
first_timestamp_in_buffer_(0),
encoders_(new EncoderState[num_channels_]),
interleave_buffer_(new uint8_t[2 * num_channels_]) {
CHECK_EQ(config.frame_size_ms % 10, 0)
<< "Frame size must be an integer multiple of 10 ms.";
const int samples_per_channel =
kSampleRateHz / 100 * num_10ms_frames_per_packet_;
for (int i = 0; i < num_channels_; ++i) {
encoders_[i].speech_buffer.reset(new int16_t[samples_per_channel]);
encoders_[i].encoded_buffer.reset(new uint8_t[samples_per_channel / 2]);
}
}
AudioEncoderG722::~AudioEncoderG722() {}
int AudioEncoderG722::SampleRateHz() const {
return kSampleRateHz;
}
int AudioEncoderG722::RtpTimestampRateHz() const {
// The RTP timestamp rate for G.722 is 8000 Hz, even though it is a 16 kHz
// codec.
return kSampleRateHz / 2;
}
int AudioEncoderG722::NumChannels() const {
return num_channels_;
}
int AudioEncoderG722::Num10MsFramesInNextPacket() const {
return num_10ms_frames_per_packet_;
}
int AudioEncoderG722::Max10MsFramesInAPacket() const {
return num_10ms_frames_per_packet_;
}
bool AudioEncoderG722::EncodeInternal(uint32_t rtp_timestamp,
const int16_t* audio,
size_t max_encoded_bytes,
uint8_t* encoded,
EncodedInfo* info) {
const int samples_per_channel =
kSampleRateHz / 100 * num_10ms_frames_per_packet_;
CHECK_GE(max_encoded_bytes,
static_cast<size_t>(samples_per_channel) / 2 * num_channels_);
if (num_10ms_frames_buffered_ == 0)
first_timestamp_in_buffer_ = rtp_timestamp;
// Deinterleave samples and save them in each channel's buffer.
const int start = kSampleRateHz / 100 * num_10ms_frames_buffered_;
for (int i = 0; i < kSampleRateHz / 100; ++i)
for (int j = 0; j < num_channels_; ++j)
encoders_[j].speech_buffer[start + i] = audio[i * num_channels_ + j];
// If we don't yet have enough samples for a packet, we're done for now.
if (++num_10ms_frames_buffered_ < num_10ms_frames_per_packet_) {
info->encoded_bytes = 0;
return true;
}
// Encode each channel separately.
CHECK_EQ(num_10ms_frames_buffered_, num_10ms_frames_per_packet_);
num_10ms_frames_buffered_ = 0;
for (int i = 0; i < num_channels_; ++i) {
const int encoded = WebRtcG722_Encode(
encoders_[i].encoder, encoders_[i].speech_buffer.get(),
samples_per_channel, encoders_[i].encoded_buffer.get());
CHECK_EQ(encoded, samples_per_channel / 2);
}
// Interleave the encoded bytes of the different channels. Each separate
// channel and the interleaved stream encodes two samples per byte, most
// significant half first.
for (int i = 0; i < samples_per_channel / 2; ++i) {
for (int j = 0; j < num_channels_; ++j) {
uint8_t two_samples = encoders_[j].encoded_buffer[i];
interleave_buffer_[j] = two_samples >> 4;
interleave_buffer_[num_channels_ + j] = two_samples & 0xf;
}
for (int j = 0; j < num_channels_; ++j)
encoded[i * num_channels_ + j] =
interleave_buffer_[2 * j] << 4 | interleave_buffer_[2 * j + 1];
}
info->encoded_bytes = samples_per_channel / 2 * num_channels_;
info->encoded_timestamp = first_timestamp_in_buffer_;
info->payload_type = payload_type_;
return true;
}
} // namespace webrtc
<|endoftext|> |
<commit_before>#include "ClientWrapper.hpp"
#include <bts/net/upnp.hpp>
#include <bts/net/config.hpp>
#include <bts/db/exception.hpp>
#include <QApplication>
#include <QResource>
#include <QSettings>
#include <QJsonDocument>
#include <QUrl>
#include <QMessageBox>
#include <QDir>
#include <iostream>
void get_htdocs_file( const fc::path& filename, const fc::http::server::response& r )
{
std::cout << filename.generic_string() << "\n";
QResource file_to_send( ("/htdocs/htdocs/" + filename.generic_string()).c_str() );
if( !file_to_send.data() )
{
std::string not_found = "this is not the file you are looking for: " + filename.generic_string();
r.set_status( fc::http::reply::NotFound );
r.set_length( not_found.size() );
r.write( not_found.c_str(), not_found.size() );
return;
}
r.set_status( fc::http::reply::OK );
if( file_to_send.isCompressed() )
{
auto data = qUncompress( file_to_send.data(), file_to_send.size() );
r.set_length( data.size() );
r.write( (const char*)data.data(), data.size() );
}
else
{
r.set_length( file_to_send.size() );
r.write( (const char*)file_to_send.data(), file_to_send.size() );
}
}
ClientWrapper::ClientWrapper(QObject *parent)
: QObject(parent),
_bitshares_thread("bitshares"),
_settings("BitShares", BTS_BLOCKCHAIN_NAME)
{
}
ClientWrapper::~ClientWrapper()
{
try {
_init_complete.wait();
_bitshares_thread.async( [this](){ _client->stop(); _client.reset(); } ).wait();
} catch ( ... )
{
elog( "uncaught exception" );
}
}
void ClientWrapper::handle_crash()
{
auto response = QMessageBox::question(nullptr,
tr("Crash Detected"),
tr("It appears that %1 crashed last time it was running. "
"If this is happening frequently, it could be caused by a "
"corrupted database. Would you like "
"to reset the database (this will take several minutes) or "
"to continue normally? Resetting the database will "
"NOT lose any of your information or funds.").arg(qApp->applicationName()),
tr("Reset Database"),
tr("Continue Normally"),
QString(), 1);
if (response == 0)
QDir((get_data_dir() + "/chain").c_str()).removeRecursively();
}
std::string ClientWrapper::get_data_dir()
{
auto data_dir = bts::client::get_data_dir(boost::program_options::variables_map()).to_native_ansi_path();
if (_settings.contains("data_dir"))
data_dir = _settings.value("data_dir").toString().toStdString();
int data_dir_index = qApp->arguments().indexOf("--data-dir");
if (data_dir_index != -1 && qApp->arguments().size() > data_dir_index+1)
data_dir = qApp->arguments()[data_dir_index+1].toStdString();
return data_dir;
}
void ClientWrapper::initialize(INotifier* notifier)
{
bool upnp = _settings.value( "network/p2p/use_upnp", true ).toBool();
uint32_t default_port = BTS_NET_DEFAULT_P2P_PORT;
if( BTS_TEST_NETWORK ) default_port += BTS_TEST_NETWORK_VERSION;
uint32_t p2pport = _settings.value( "network/p2p/port", default_port ).toInt();
std::string default_wallet_name = _settings.value("client/default_wallet_name", "default").toString().toStdString();
_settings.setValue("client/default_wallet_name", QString::fromStdString(default_wallet_name));
#ifdef _WIN32
_cfg.rpc.rpc_user = "";
_cfg.rpc.rpc_password = "";
#else
_cfg.rpc.rpc_user = "randomuser";
_cfg.rpc.rpc_password = fc::variant(fc::ecc::private_key::generate()).as_string();
#endif
_cfg.rpc.httpd_endpoint = fc::ip::endpoint::from_string( "127.0.0.1:9999" );
_cfg.rpc.httpd_endpoint.set_port(0);
ilog( "config: ${d}", ("d", fc::json::to_pretty_string(_cfg) ) );
auto data_dir = get_data_dir();
wlog("Starting client with data-dir: ${ddir}", ("ddir", data_dir));
fc::thread* main_thread = &fc::thread::current();
_init_complete = _bitshares_thread.async( [this,main_thread,data_dir,upnp,p2pport,default_wallet_name, notifier](){
try
{
main_thread->async( [&]{ Q_EMIT status_update(tr("Starting %1").arg(qApp->applicationName())); });
_client = std::make_shared<bts::client::client>();
_client->open( data_dir, fc::optional<fc::path>(), [=](uint32_t blocks_processed) {
if( blocks_processed % 1000 == 0 )
main_thread->async( [&]{ Q_EMIT status_update(tr("Reindexing database; please wait... This may take several minutes.").arg(blocks_processed)); } );
} );
// setup RPC / HTTP services
main_thread->async( [&]{ Q_EMIT status_update(tr("Loading...")); });
_client->get_rpc_server()->set_http_file_callback( get_htdocs_file );
_client->get_rpc_server()->configure_http( _cfg.rpc );
_actual_httpd_endpoint = _client->get_rpc_server()->get_httpd_endpoint();
// load config for p2p node.. creates cli
const bts::client::config& loadedCfg = _client->configure( data_dir );
if(notifier != nullptr)
notifier->on_config_loaded(loadedCfg);
_client->init_cli();
main_thread->async( [&]{ Q_EMIT status_update(tr("Connecting to %1 network").arg(qApp->applicationName())); });
_client->listen_on_port(0, false /*don't wait if not available*/);
fc::ip::endpoint actual_p2p_endpoint = _client->get_p2p_listening_endpoint();
_client->set_daemon_mode(true);
_client->start();
if( !_actual_httpd_endpoint )
{
main_thread->async( [&]{ Q_EMIT error( tr("Unable to start HTTP server...")); });
}
_client->start_networking([=]{
for (std::string default_peer : _cfg.default_peers)
_client->connect_to_peer(default_peer);
});
if( upnp )
{
auto upnp_service = new bts::net::upnp_service();
upnp_service->map_port( actual_p2p_endpoint.port() );
}
try
{
_client->wallet_open(default_wallet_name);
}
catch(...)
{}
main_thread->async( [&]{ Q_EMIT initialized(); });
}
catch (const bts::db::db_in_use_exception&)
{
main_thread->async( [&]{ Q_EMIT error( tr("An instance of %1 is already running! Please close it and try again.").arg(qApp->applicationName())); });
}
catch (const fc::exception &e)
{
ilog("Failure when attempting to initialize client");
main_thread->async( [&]{ Q_EMIT error( tr("An error occurred while trying to start")); });
}
});
}
void ClientWrapper::close()
{
_bitshares_thread.async([this]{
_client->wallet_close();
_client->get_chain()->close();
_client->get_rpc_server()->shutdown_rpc_server();
_client->get_rpc_server()->wait_till_rpc_server_shutdown();
}).wait();
}
QUrl ClientWrapper::http_url() const
{
QUrl url = QString::fromStdString("http://" + std::string( *_actual_httpd_endpoint ) );
url.setUserName(_cfg.rpc.rpc_user.c_str() );
url.setPassword(_cfg.rpc.rpc_password.c_str() );
return url;
}
QVariant ClientWrapper::get_info( )
{
fc::variant_object result = _bitshares_thread.async( [this](){ return _client->get_info(); }).wait();
std::string sresult = fc::json::to_string( result );
return QJsonDocument::fromJson( QByteArray( sresult.c_str(), sresult.length() ) ).toVariant();
}
QString ClientWrapper::get_http_auth_token()
{
QByteArray result = _cfg.rpc.rpc_user.c_str();
result += ":";
result += _cfg.rpc.rpc_password.c_str();
return result.toBase64( QByteArray::Base64Encoding | QByteArray::KeepTrailingEquals );
}
void ClientWrapper::set_data_dir(QString data_dir)
{
QSettings ("BitShares", BTS_BLOCKCHAIN_NAME).setValue("data_dir", data_dir);
}
void ClientWrapper::confirm_and_set_approval(QString delegate_name, bool approve)
{
auto account = get_client()->blockchain_get_account(delegate_name.toStdString());
if( account.valid() && account->is_delegate() )
{
if( QMessageBox::question(nullptr,
tr("Set Delegate Approval"),
tr("Would you like to update approval rating of Delegate %1 to %2?")
.arg(delegate_name)
.arg(approve?"Approve":"Disapprove")
)
== QMessageBox::Yes )
get_client()->wallet_account_set_approval(delegate_name.toStdString(), approve);
}
else
QMessageBox::warning(nullptr, tr("Invalid Account"), tr("Account %1 is not a delegate, so its approval cannot be set.").arg(delegate_name));
}
<commit_msg>Fixed #36, BTS_TEST_NETWORK macro usage<commit_after>#include "ClientWrapper.hpp"
#include <bts/net/upnp.hpp>
#include <bts/net/config.hpp>
#include <bts/db/exception.hpp>
#include <QApplication>
#include <QResource>
#include <QSettings>
#include <QJsonDocument>
#include <QUrl>
#include <QMessageBox>
#include <QDir>
#include <iostream>
void get_htdocs_file( const fc::path& filename, const fc::http::server::response& r )
{
std::cout << filename.generic_string() << "\n";
QResource file_to_send( ("/htdocs/htdocs/" + filename.generic_string()).c_str() );
if( !file_to_send.data() )
{
std::string not_found = "this is not the file you are looking for: " + filename.generic_string();
r.set_status( fc::http::reply::NotFound );
r.set_length( not_found.size() );
r.write( not_found.c_str(), not_found.size() );
return;
}
r.set_status( fc::http::reply::OK );
if( file_to_send.isCompressed() )
{
auto data = qUncompress( file_to_send.data(), file_to_send.size() );
r.set_length( data.size() );
r.write( (const char*)data.data(), data.size() );
}
else
{
r.set_length( file_to_send.size() );
r.write( (const char*)file_to_send.data(), file_to_send.size() );
}
}
ClientWrapper::ClientWrapper(QObject *parent)
: QObject(parent),
_bitshares_thread("bitshares"),
_settings("BitShares", BTS_BLOCKCHAIN_NAME)
{
}
ClientWrapper::~ClientWrapper()
{
try {
_init_complete.wait();
_bitshares_thread.async( [this](){ _client->stop(); _client.reset(); } ).wait();
} catch ( ... )
{
elog( "uncaught exception" );
}
}
void ClientWrapper::handle_crash()
{
auto response = QMessageBox::question(nullptr,
tr("Crash Detected"),
tr("It appears that %1 crashed last time it was running. "
"If this is happening frequently, it could be caused by a "
"corrupted database. Would you like "
"to reset the database (this will take several minutes) or "
"to continue normally? Resetting the database will "
"NOT lose any of your information or funds.").arg(qApp->applicationName()),
tr("Reset Database"),
tr("Continue Normally"),
QString(), 1);
if (response == 0)
QDir((get_data_dir() + "/chain").c_str()).removeRecursively();
}
std::string ClientWrapper::get_data_dir()
{
auto data_dir = bts::client::get_data_dir(boost::program_options::variables_map()).to_native_ansi_path();
if (_settings.contains("data_dir"))
data_dir = _settings.value("data_dir").toString().toStdString();
int data_dir_index = qApp->arguments().indexOf("--data-dir");
if (data_dir_index != -1 && qApp->arguments().size() > data_dir_index+1)
data_dir = qApp->arguments()[data_dir_index+1].toStdString();
return data_dir;
}
void ClientWrapper::initialize(INotifier* notifier)
{
bool upnp = _settings.value( "network/p2p/use_upnp", true ).toBool();
uint32_t default_port = BTS_NET_DEFAULT_P2P_PORT;
#ifdef BTS_TEST_NETWORK
default_port += BTS_TEST_NETWORK_VERSION;
#endif
uint32_t p2pport = _settings.value( "network/p2p/port", default_port ).toInt();
std::string default_wallet_name = _settings.value("client/default_wallet_name", "default").toString().toStdString();
_settings.setValue("client/default_wallet_name", QString::fromStdString(default_wallet_name));
#ifdef _WIN32
_cfg.rpc.rpc_user = "";
_cfg.rpc.rpc_password = "";
#else
_cfg.rpc.rpc_user = "randomuser";
_cfg.rpc.rpc_password = fc::variant(fc::ecc::private_key::generate()).as_string();
#endif
_cfg.rpc.httpd_endpoint = fc::ip::endpoint::from_string( "127.0.0.1:9999" );
_cfg.rpc.httpd_endpoint.set_port(0);
ilog( "config: ${d}", ("d", fc::json::to_pretty_string(_cfg) ) );
auto data_dir = get_data_dir();
wlog("Starting client with data-dir: ${ddir}", ("ddir", data_dir));
fc::thread* main_thread = &fc::thread::current();
_init_complete = _bitshares_thread.async( [this,main_thread,data_dir,upnp,p2pport,default_wallet_name, notifier](){
try
{
main_thread->async( [&]{ Q_EMIT status_update(tr("Starting %1").arg(qApp->applicationName())); });
_client = std::make_shared<bts::client::client>();
_client->open( data_dir, fc::optional<fc::path>(), [=](uint32_t blocks_processed) {
if( blocks_processed % 1000 == 0 )
main_thread->async( [&]{ Q_EMIT status_update(tr("Reindexing database; please wait... This may take several minutes.").arg(blocks_processed)); } );
} );
// setup RPC / HTTP services
main_thread->async( [&]{ Q_EMIT status_update(tr("Loading...")); });
_client->get_rpc_server()->set_http_file_callback( get_htdocs_file );
_client->get_rpc_server()->configure_http( _cfg.rpc );
_actual_httpd_endpoint = _client->get_rpc_server()->get_httpd_endpoint();
// load config for p2p node.. creates cli
const bts::client::config& loadedCfg = _client->configure( data_dir );
if(notifier != nullptr)
notifier->on_config_loaded(loadedCfg);
_client->init_cli();
main_thread->async( [&]{ Q_EMIT status_update(tr("Connecting to %1 network").arg(qApp->applicationName())); });
_client->listen_on_port(0, false /*don't wait if not available*/);
fc::ip::endpoint actual_p2p_endpoint = _client->get_p2p_listening_endpoint();
_client->set_daemon_mode(true);
_client->start();
if( !_actual_httpd_endpoint )
{
main_thread->async( [&]{ Q_EMIT error( tr("Unable to start HTTP server...")); });
}
_client->start_networking([=]{
for (std::string default_peer : _cfg.default_peers)
_client->connect_to_peer(default_peer);
});
if( upnp )
{
auto upnp_service = new bts::net::upnp_service();
upnp_service->map_port( actual_p2p_endpoint.port() );
}
try
{
_client->wallet_open(default_wallet_name);
}
catch(...)
{}
main_thread->async( [&]{ Q_EMIT initialized(); });
}
catch (const bts::db::db_in_use_exception&)
{
main_thread->async( [&]{ Q_EMIT error( tr("An instance of %1 is already running! Please close it and try again.").arg(qApp->applicationName())); });
}
catch (const fc::exception &e)
{
ilog("Failure when attempting to initialize client");
main_thread->async( [&]{ Q_EMIT error( tr("An error occurred while trying to start")); });
}
});
}
void ClientWrapper::close()
{
_bitshares_thread.async([this]{
_client->wallet_close();
_client->get_chain()->close();
_client->get_rpc_server()->shutdown_rpc_server();
_client->get_rpc_server()->wait_till_rpc_server_shutdown();
}).wait();
}
QUrl ClientWrapper::http_url() const
{
QUrl url = QString::fromStdString("http://" + std::string( *_actual_httpd_endpoint ) );
url.setUserName(_cfg.rpc.rpc_user.c_str() );
url.setPassword(_cfg.rpc.rpc_password.c_str() );
return url;
}
QVariant ClientWrapper::get_info( )
{
fc::variant_object result = _bitshares_thread.async( [this](){ return _client->get_info(); }).wait();
std::string sresult = fc::json::to_string( result );
return QJsonDocument::fromJson( QByteArray( sresult.c_str(), sresult.length() ) ).toVariant();
}
QString ClientWrapper::get_http_auth_token()
{
QByteArray result = _cfg.rpc.rpc_user.c_str();
result += ":";
result += _cfg.rpc.rpc_password.c_str();
return result.toBase64( QByteArray::Base64Encoding | QByteArray::KeepTrailingEquals );
}
void ClientWrapper::set_data_dir(QString data_dir)
{
QSettings ("BitShares", BTS_BLOCKCHAIN_NAME).setValue("data_dir", data_dir);
}
void ClientWrapper::confirm_and_set_approval(QString delegate_name, bool approve)
{
auto account = get_client()->blockchain_get_account(delegate_name.toStdString());
if( account.valid() && account->is_delegate() )
{
if( QMessageBox::question(nullptr,
tr("Set Delegate Approval"),
tr("Would you like to update approval rating of Delegate %1 to %2?")
.arg(delegate_name)
.arg(approve?"Approve":"Disapprove")
)
== QMessageBox::Yes )
get_client()->wallet_account_set_approval(delegate_name.toStdString(), approve);
}
else
QMessageBox::warning(nullptr, tr("Invalid Account"), tr("Account %1 is not a delegate, so its approval cannot be set.").arg(delegate_name));
}
<|endoftext|> |
<commit_before>// Mike Zrimsek
// Computer Graphics
// Homework 2
#include <GL/glut.h>
static int WINDOW_WIDTH = 500;
static int WINDOW_HEIGHT = 500;
void myDisplay()
{
glClear(GL_COLOR_BUFFER_BIT);
glFlush();
}
int main(int argc, char** argv)
{
glutInit(&argc, argv);
glutInitDisplayMode(GLUT_SINGLE|GLUT_RGB);
glutInitWindowSize(WINDOW_WIDTH, WINDOW_HEIGHT);
glutInitWindowPosition(0,0);
glutCreateWindow("Homework 2");
glutDisplayFunc(myDisplay);
glutMainLoop();
}
<commit_msg>added menu<commit_after>// Mike Zrimsek
// Computer Graphics
// Homework 2
#include <GL/glut.h>
static int WINDOW_WIDTH = 500;
static int WINDOW_HEIGHT = 500;
static int mainMenuId;
void myDisplay()
{
glClear(GL_COLOR_BUFFER_BIT);
glFlush();
}
void mainMenu(int value)
{
}
int main(int argc, char** argv)
{
glutInit(&argc, argv);
glutInitDisplayMode(GLUT_SINGLE|GLUT_RGB);
glutInitWindowSize(WINDOW_WIDTH, WINDOW_HEIGHT);
glutInitWindowPosition(0,0);
glutCreateWindow("Homework 2");
glutDisplayFunc(myDisplay);
mainMenuId = glutCreateMenu(mainMenu);
glutAddMenuEntry("Rectangles", 1);
glutAddMenuEntry("Circle", 2);
glutAddMenuEntry("Rubberbanding Circle", 3);
glutAttachMenu(GLUT_RIGHT_BUTTON);
glutMainLoop();
return 0;
}
<|endoftext|> |
<commit_before>//* This file is part of the MOOSE framework
//* https://www.mooseframework.org
//*
//* All rights reserved, see COPYRIGHT for full restrictions
//* https://github.com/idaholab/moose/blob/master/COPYRIGHT
//*
//* Licensed under LGPL 2.1, please see LICENSE for details
//* https://www.gnu.org/licenses/lgpl-2.1.html
#include "PhysicsBasedPreconditioner.h"
// MOOSE includes
#include "ComputeJacobianBlocksThread.h"
#include "FEProblem.h"
#include "MooseEnum.h"
#include "MooseVariableFE.h"
#include "NonlinearSystem.h"
#include "PetscSupport.h"
#include "libmesh/libmesh_common.h"
#include "libmesh/equation_systems.h"
#include "libmesh/nonlinear_implicit_system.h"
#include "libmesh/nonlinear_solver.h"
#include "libmesh/linear_implicit_system.h"
#include "libmesh/transient_system.h"
#include "libmesh/numeric_vector.h"
#include "libmesh/sparse_matrix.h"
#include "libmesh/string_to_enum.h"
#include "libmesh/coupling_matrix.h"
registerMooseObjectAliased("MooseApp", PhysicsBasedPreconditioner, "PBP");
template <>
InputParameters
validParams<PhysicsBasedPreconditioner>()
{
InputParameters params = validParams<MoosePreconditioner>();
params.addRequiredParam<std::vector<std::string>>(
"solve_order",
"The order the block rows will be solved in. Put the name of variables here "
"to stand for solving that variable's block row. A variable may appear more "
"than once (to create cylces if you like).");
params.addRequiredParam<std::vector<std::string>>("preconditioner", "TODO: docstring");
params.addParam<std::vector<std::string>>(
"off_diag_row",
"The off diagonal row you want to add into the matrix, it will be associated "
"with an off diagonal column from the same position in off_diag_colum.");
params.addParam<std::vector<std::string>>("off_diag_column",
"The off diagonal column you want to add into the "
"matrix, it will be associated with an off diagonal "
"row from the same position in off_diag_row.");
return params;
}
PhysicsBasedPreconditioner::PhysicsBasedPreconditioner(const InputParameters & params)
: MoosePreconditioner(params),
Preconditioner<Number>(MoosePreconditioner::_communicator),
_nl(_fe_problem.getNonlinearSystemBase())
{
unsigned int num_systems = _nl.system().n_vars();
_systems.resize(num_systems);
_preconditioners.resize(num_systems);
_off_diag.resize(num_systems);
_off_diag_mats.resize(num_systems);
_pre_type.resize(num_systems);
{ // Setup the Coupling Matrix so MOOSE knows what we're doing
NonlinearSystemBase & nl = _fe_problem.getNonlinearSystemBase();
unsigned int n_vars = nl.nVariables();
// The coupling matrix is held and released by FEProblemBase, so it is not released in this
// object
std::unique_ptr<CouplingMatrix> cm = libmesh_make_unique<CouplingMatrix>(n_vars);
bool full = false; // getParam<bool>("full"); // TODO: add a FULL option for PBP
if (!full)
{
// put 1s on diagonal
for (unsigned int i = 0; i < n_vars; i++)
(*cm)(i, i) = 1;
// off-diagonal entries
std::vector<std::vector<unsigned int>> off_diag(n_vars);
for (unsigned int i = 0; i < getParam<std::vector<std::string>>("off_diag_row").size(); i++)
{
unsigned int row =
nl.getVariable(0, getParam<std::vector<std::string>>("off_diag_row")[i]).number();
unsigned int column =
nl.getVariable(0, getParam<std::vector<std::string>>("off_diag_column")[i]).number();
(*cm)(row, column) = 1;
}
// TODO: handle coupling entries between NL-vars and SCALAR-vars
}
else
{
for (unsigned int i = 0; i < n_vars; i++)
for (unsigned int j = 0; j < n_vars; j++)
(*cm)(i, j) = 1;
}
_fe_problem.setCouplingMatrix(std::move(cm));
}
// PC types
const std::vector<std::string> & pc_types = getParam<std::vector<std::string>>("preconditioner");
for (unsigned int i = 0; i < num_systems; i++)
_pre_type[i] = Utility::string_to_enum<PreconditionerType>(pc_types[i]);
// solve order
const std::vector<std::string> & solve_order = getParam<std::vector<std::string>>("solve_order");
_solve_order.resize(solve_order.size());
for (unsigned int i = 0; i < solve_order.size(); i++)
_solve_order[i] = _nl.system().variable_number(solve_order[i]);
// diag and off-diag systems
unsigned int n_vars = _nl.system().n_vars();
// off-diagonal entries
const std::vector<std::string> & odr = getParam<std::vector<std::string>>("off_diag_row");
const std::vector<std::string> & odc = getParam<std::vector<std::string>>("off_diag_column");
std::vector<std::vector<unsigned int>> off_diag(n_vars);
for (unsigned int i = 0; i < odr.size(); i++)
{
unsigned int row = _nl.system().variable_number(odr[i]);
unsigned int column = _nl.system().variable_number(odc[i]);
off_diag[row].push_back(column);
}
// Add all of the preconditioning systems
for (unsigned int var = 0; var < n_vars; var++)
addSystem(var, off_diag[var], _pre_type[var]);
_nl.nonlinearSolver()->attach_preconditioner(this);
if (_fe_problem.solverParams()._type != Moose::ST_JFNK)
mooseError("PBP must be used with JFNK solve type");
}
PhysicsBasedPreconditioner::~PhysicsBasedPreconditioner()
{
this->clear();
}
void
PhysicsBasedPreconditioner::addSystem(unsigned int var,
std::vector<unsigned int> off_diag,
PreconditionerType type)
{
std::string var_name = _nl.system().variable_name(var);
LinearImplicitSystem & precond_system =
_fe_problem.es().add_system<LinearImplicitSystem>(var_name + "_system");
precond_system.assemble_before_solve = false;
const std::set<SubdomainID> * active_subdomains = _nl.getVariableBlocks(var);
precond_system.add_variable(
var_name + "_prec", _nl.system().variable(var).type(), active_subdomains);
_systems[var] = &precond_system;
_pre_type[var] = type;
_off_diag_mats[var].resize(off_diag.size());
for (unsigned int i = 0; i < off_diag.size(); i++)
{
// Add the matrix to hold the off-diagonal piece
_off_diag_mats[var][i] = &precond_system.add_matrix(_nl.system().variable_name(off_diag[i]));
}
_off_diag[var] = off_diag;
}
void
PhysicsBasedPreconditioner::init()
{
Moose::perf_log.push("init()", "PhysicsBasedPreconditioner");
// Tell libMesh that this is initialized!
_is_initialized = true;
const unsigned int num_systems = _systems.size();
// If no order was specified, just solve them in increasing order
if (_solve_order.size() == 0)
{
_solve_order.resize(num_systems);
for (unsigned int i = 0; i < num_systems; i++)
_solve_order[i] = i;
}
// Loop over variables
for (unsigned int system_var = 0; system_var < num_systems; system_var++)
{
LinearImplicitSystem & u_system = *_systems[system_var];
if (!_preconditioners[system_var])
_preconditioners[system_var] =
Preconditioner<Number>::build_preconditioner(MoosePreconditioner::_communicator);
// we have to explicitly set the matrix in the preconditioner, because h-adaptivity could have
// changed it and we have to work with the current one
Preconditioner<Number> * preconditioner = _preconditioners[system_var].get();
preconditioner->set_matrix(*u_system.matrix);
preconditioner->set_type(_pre_type[system_var]);
preconditioner->init();
}
Moose::perf_log.pop("init()", "PhysicsBasedPreconditioner");
}
void
PhysicsBasedPreconditioner::setup()
{
const unsigned int num_systems = _systems.size();
std::vector<JacobianBlock *> blocks;
// Loop over variables
for (unsigned int system_var = 0; system_var < num_systems; system_var++)
{
LinearImplicitSystem & u_system = *_systems[system_var];
{
JacobianBlock * block = new JacobianBlock(u_system, *u_system.matrix, system_var, system_var);
blocks.push_back(block);
}
for (unsigned int diag = 0; diag < _off_diag[system_var].size(); diag++)
{
unsigned int coupled_var = _off_diag[system_var][diag];
std::string coupled_name = _nl.system().variable_name(coupled_var);
JacobianBlock * block =
new JacobianBlock(u_system, *_off_diag_mats[system_var][diag], system_var, coupled_var);
blocks.push_back(block);
}
}
_fe_problem.computeJacobianBlocks(blocks);
// cleanup
for (auto & block : blocks)
delete block;
}
void
PhysicsBasedPreconditioner::apply(const NumericVector<Number> & x, NumericVector<Number> & y)
{
Moose::perf_log.push("apply()", "PhysicsBasedPreconditioner");
const unsigned int num_systems = _systems.size();
MooseMesh & mesh = _fe_problem.mesh();
// Zero out the solution vectors
for (unsigned int sys = 0; sys < num_systems; sys++)
_systems[sys]->solution->zero();
// Loop over solve order
for (unsigned int i = 0; i < _solve_order.size(); i++)
{
unsigned int system_var = _solve_order[i];
LinearImplicitSystem & u_system = *_systems[system_var];
// Copy rhs from the big system into the small one
MoosePreconditioner::copyVarValues(
mesh, _nl.system().number(), system_var, x, u_system.number(), 0, *u_system.rhs);
// Modify the RHS by subtracting off the matvecs of the solutions for the other preconditioning
// systems with the off diagonal blocks in this system.
for (unsigned int diag = 0; diag < _off_diag[system_var].size(); diag++)
{
unsigned int coupled_var = _off_diag[system_var][diag];
LinearImplicitSystem & coupled_system = *_systems[coupled_var];
SparseMatrix<Number> & off_diag = *_off_diag_mats[system_var][diag];
NumericVector<Number> & rhs = *u_system.rhs;
// This next bit computes rhs -= A*coupled_solution
// It does what it does because there is no vector_mult_sub()
rhs.close();
rhs.scale(-1.0);
rhs.close();
off_diag.vector_mult_add(rhs, *coupled_system.solution);
rhs.close();
rhs.scale(-1.0);
rhs.close();
}
// Apply the preconditioner to the small system
_preconditioners[system_var]->apply(*u_system.rhs, *u_system.solution);
// Copy solution from small system into the big one
// copyVarValues(mesh,system,0,*u_system.solution,0,system_var,y);
}
// Copy the solutions out
for (unsigned int system_var = 0; system_var < num_systems; system_var++)
{
LinearImplicitSystem & u_system = *_systems[system_var];
MoosePreconditioner::copyVarValues(
mesh, u_system.number(), 0, *u_system.solution, _nl.system().number(), system_var, y);
}
y.close();
Moose::perf_log.pop("apply()", "PhysicsBasedPreconditioner");
}
void
PhysicsBasedPreconditioner::clear()
{
}
<commit_msg>Satisfy dumb clang format thing refs #11552<commit_after>//* This file is part of the MOOSE framework
//* https://www.mooseframework.org
//*
//* All rights reserved, see COPYRIGHT for full restrictions
//* https://github.com/idaholab/moose/blob/master/COPYRIGHT
//*
//* Licensed under LGPL 2.1, please see LICENSE for details
//* https://www.gnu.org/licenses/lgpl-2.1.html
#include "PhysicsBasedPreconditioner.h"
// MOOSE includes
#include "ComputeJacobianBlocksThread.h"
#include "FEProblem.h"
#include "MooseEnum.h"
#include "MooseVariableFE.h"
#include "NonlinearSystem.h"
#include "PetscSupport.h"
#include "libmesh/libmesh_common.h"
#include "libmesh/equation_systems.h"
#include "libmesh/nonlinear_implicit_system.h"
#include "libmesh/nonlinear_solver.h"
#include "libmesh/linear_implicit_system.h"
#include "libmesh/transient_system.h"
#include "libmesh/numeric_vector.h"
#include "libmesh/sparse_matrix.h"
#include "libmesh/string_to_enum.h"
#include "libmesh/coupling_matrix.h"
registerMooseObjectAliased("MooseApp", PhysicsBasedPreconditioner, "PBP");
template <>
InputParameters
validParams<PhysicsBasedPreconditioner>()
{
InputParameters params = validParams<MoosePreconditioner>();
params.addRequiredParam<std::vector<std::string>>(
"solve_order",
"The order the block rows will be solved in. Put the name of variables here "
"to stand for solving that variable's block row. A variable may appear more "
"than once (to create cylces if you like).");
params.addRequiredParam<std::vector<std::string>>("preconditioner", "TODO: docstring");
params.addParam<std::vector<std::string>>(
"off_diag_row",
"The off diagonal row you want to add into the matrix, it will be associated "
"with an off diagonal column from the same position in off_diag_colum.");
params.addParam<std::vector<std::string>>("off_diag_column",
"The off diagonal column you want to add into the "
"matrix, it will be associated with an off diagonal "
"row from the same position in off_diag_row.");
return params;
}
PhysicsBasedPreconditioner::PhysicsBasedPreconditioner(const InputParameters & params)
: MoosePreconditioner(params),
Preconditioner<Number>(MoosePreconditioner::_communicator),
_nl(_fe_problem.getNonlinearSystemBase())
{
unsigned int num_systems = _nl.system().n_vars();
_systems.resize(num_systems);
_preconditioners.resize(num_systems);
_off_diag.resize(num_systems);
_off_diag_mats.resize(num_systems);
_pre_type.resize(num_systems);
{ // Setup the Coupling Matrix so MOOSE knows what we're doing
NonlinearSystemBase & nl = _fe_problem.getNonlinearSystemBase();
unsigned int n_vars = nl.nVariables();
// The coupling matrix is held and released by FEProblemBase, so it is not released in this
// object
std::unique_ptr<CouplingMatrix> cm = libmesh_make_unique<CouplingMatrix>(n_vars);
bool full = false; // getParam<bool>("full"); // TODO: add a FULL option for PBP
if (!full)
{
// put 1s on diagonal
for (unsigned int i = 0; i < n_vars; i++)
(*cm)(i, i) = 1;
// off-diagonal entries
std::vector<std::vector<unsigned int>> off_diag(n_vars);
for (unsigned int i = 0; i < getParam<std::vector<std::string>>("off_diag_row").size(); i++)
{
unsigned int row =
nl.getVariable(0, getParam<std::vector<std::string>>("off_diag_row")[i]).number();
unsigned int column =
nl.getVariable(0, getParam<std::vector<std::string>>("off_diag_column")[i]).number();
(*cm)(row, column) = 1;
}
// TODO: handle coupling entries between NL-vars and SCALAR-vars
}
else
{
for (unsigned int i = 0; i < n_vars; i++)
for (unsigned int j = 0; j < n_vars; j++)
(*cm)(i, j) = 1;
}
_fe_problem.setCouplingMatrix(std::move(cm));
}
// PC types
const std::vector<std::string> & pc_types = getParam<std::vector<std::string>>("preconditioner");
for (unsigned int i = 0; i < num_systems; i++)
_pre_type[i] = Utility::string_to_enum<PreconditionerType>(pc_types[i]);
// solve order
const std::vector<std::string> & solve_order = getParam<std::vector<std::string>>("solve_order");
_solve_order.resize(solve_order.size());
for (unsigned int i = 0; i < solve_order.size(); i++)
_solve_order[i] = _nl.system().variable_number(solve_order[i]);
// diag and off-diag systems
unsigned int n_vars = _nl.system().n_vars();
// off-diagonal entries
const std::vector<std::string> & odr = getParam<std::vector<std::string>>("off_diag_row");
const std::vector<std::string> & odc = getParam<std::vector<std::string>>("off_diag_column");
std::vector<std::vector<unsigned int>> off_diag(n_vars);
for (unsigned int i = 0; i < odr.size(); i++)
{
unsigned int row = _nl.system().variable_number(odr[i]);
unsigned int column = _nl.system().variable_number(odc[i]);
off_diag[row].push_back(column);
}
// Add all of the preconditioning systems
for (unsigned int var = 0; var < n_vars; var++)
addSystem(var, off_diag[var], _pre_type[var]);
_nl.nonlinearSolver()->attach_preconditioner(this);
if (_fe_problem.solverParams()._type != Moose::ST_JFNK)
mooseError("PBP must be used with JFNK solve type");
}
PhysicsBasedPreconditioner::~PhysicsBasedPreconditioner() { this->clear(); }
void
PhysicsBasedPreconditioner::addSystem(unsigned int var,
std::vector<unsigned int> off_diag,
PreconditionerType type)
{
std::string var_name = _nl.system().variable_name(var);
LinearImplicitSystem & precond_system =
_fe_problem.es().add_system<LinearImplicitSystem>(var_name + "_system");
precond_system.assemble_before_solve = false;
const std::set<SubdomainID> * active_subdomains = _nl.getVariableBlocks(var);
precond_system.add_variable(
var_name + "_prec", _nl.system().variable(var).type(), active_subdomains);
_systems[var] = &precond_system;
_pre_type[var] = type;
_off_diag_mats[var].resize(off_diag.size());
for (unsigned int i = 0; i < off_diag.size(); i++)
{
// Add the matrix to hold the off-diagonal piece
_off_diag_mats[var][i] = &precond_system.add_matrix(_nl.system().variable_name(off_diag[i]));
}
_off_diag[var] = off_diag;
}
void
PhysicsBasedPreconditioner::init()
{
Moose::perf_log.push("init()", "PhysicsBasedPreconditioner");
// Tell libMesh that this is initialized!
_is_initialized = true;
const unsigned int num_systems = _systems.size();
// If no order was specified, just solve them in increasing order
if (_solve_order.size() == 0)
{
_solve_order.resize(num_systems);
for (unsigned int i = 0; i < num_systems; i++)
_solve_order[i] = i;
}
// Loop over variables
for (unsigned int system_var = 0; system_var < num_systems; system_var++)
{
LinearImplicitSystem & u_system = *_systems[system_var];
if (!_preconditioners[system_var])
_preconditioners[system_var] =
Preconditioner<Number>::build_preconditioner(MoosePreconditioner::_communicator);
// we have to explicitly set the matrix in the preconditioner, because h-adaptivity could have
// changed it and we have to work with the current one
Preconditioner<Number> * preconditioner = _preconditioners[system_var].get();
preconditioner->set_matrix(*u_system.matrix);
preconditioner->set_type(_pre_type[system_var]);
preconditioner->init();
}
Moose::perf_log.pop("init()", "PhysicsBasedPreconditioner");
}
void
PhysicsBasedPreconditioner::setup()
{
const unsigned int num_systems = _systems.size();
std::vector<JacobianBlock *> blocks;
// Loop over variables
for (unsigned int system_var = 0; system_var < num_systems; system_var++)
{
LinearImplicitSystem & u_system = *_systems[system_var];
{
JacobianBlock * block = new JacobianBlock(u_system, *u_system.matrix, system_var, system_var);
blocks.push_back(block);
}
for (unsigned int diag = 0; diag < _off_diag[system_var].size(); diag++)
{
unsigned int coupled_var = _off_diag[system_var][diag];
std::string coupled_name = _nl.system().variable_name(coupled_var);
JacobianBlock * block =
new JacobianBlock(u_system, *_off_diag_mats[system_var][diag], system_var, coupled_var);
blocks.push_back(block);
}
}
_fe_problem.computeJacobianBlocks(blocks);
// cleanup
for (auto & block : blocks)
delete block;
}
void
PhysicsBasedPreconditioner::apply(const NumericVector<Number> & x, NumericVector<Number> & y)
{
Moose::perf_log.push("apply()", "PhysicsBasedPreconditioner");
const unsigned int num_systems = _systems.size();
MooseMesh & mesh = _fe_problem.mesh();
// Zero out the solution vectors
for (unsigned int sys = 0; sys < num_systems; sys++)
_systems[sys]->solution->zero();
// Loop over solve order
for (unsigned int i = 0; i < _solve_order.size(); i++)
{
unsigned int system_var = _solve_order[i];
LinearImplicitSystem & u_system = *_systems[system_var];
// Copy rhs from the big system into the small one
MoosePreconditioner::copyVarValues(
mesh, _nl.system().number(), system_var, x, u_system.number(), 0, *u_system.rhs);
// Modify the RHS by subtracting off the matvecs of the solutions for the other preconditioning
// systems with the off diagonal blocks in this system.
for (unsigned int diag = 0; diag < _off_diag[system_var].size(); diag++)
{
unsigned int coupled_var = _off_diag[system_var][diag];
LinearImplicitSystem & coupled_system = *_systems[coupled_var];
SparseMatrix<Number> & off_diag = *_off_diag_mats[system_var][diag];
NumericVector<Number> & rhs = *u_system.rhs;
// This next bit computes rhs -= A*coupled_solution
// It does what it does because there is no vector_mult_sub()
rhs.close();
rhs.scale(-1.0);
rhs.close();
off_diag.vector_mult_add(rhs, *coupled_system.solution);
rhs.close();
rhs.scale(-1.0);
rhs.close();
}
// Apply the preconditioner to the small system
_preconditioners[system_var]->apply(*u_system.rhs, *u_system.solution);
// Copy solution from small system into the big one
// copyVarValues(mesh,system,0,*u_system.solution,0,system_var,y);
}
// Copy the solutions out
for (unsigned int system_var = 0; system_var < num_systems; system_var++)
{
LinearImplicitSystem & u_system = *_systems[system_var];
MoosePreconditioner::copyVarValues(
mesh, u_system.number(), 0, *u_system.solution, _nl.system().number(), system_var, y);
}
y.close();
Moose::perf_log.pop("apply()", "PhysicsBasedPreconditioner");
}
void
PhysicsBasedPreconditioner::clear()
{
}
<|endoftext|> |
<commit_before> /* Appodeal_exchange_connector.cc
Eric Robert, 7 May 2013
Implementation of the OpenRTB exchange connector.
*/
#include "appodeal_exchange_connector.h"
#include "rtbkit/common/testing/exchange_source.h"
#include "rtbkit/plugins/bid_request/openrtb_bid_source.h"
#include "rtbkit/plugins/bid_request/openrtb_bid_request_parser.h"
#include "rtbkit/plugins/exchange/http_auction_handler.h"
#include "rtbkit/core/agent_configuration/agent_config.h"
#include "rtbkit/openrtb/openrtb_parsing.h"
#include "soa/types/json_printing.h"
#include <boost/any.hpp>
#include <boost/lexical_cast.hpp>
#include "jml/utils/file_functions.h"
#include "jml/arch/info.h"
#include "jml/utils/rng.h"
#include <sstream>
using namespace std;
using namespace Datacratic;
namespace Datacratic {
template<typename T, int I, typename S>
Json::Value jsonEncode(const ML::compact_vector<T, I, S> & vec)
{
Json::Value result(Json::arrayValue);
for (unsigned i = 0; i < vec.size(); ++i)
result[i] = jsonEncode(vec[i]);
return result;
}
template<typename T, int I, typename S>
ML::compact_vector<T, I, S>
jsonDecode(const Json::Value & val, ML::compact_vector<T, I, S> *)
{
ExcAssert(val.isArray());
ML::compact_vector<T, I, S> res;
res.reserve(val.size());
for (unsigned i = 0; i < val.size(); ++i)
res.push_back(jsonDecode(val[i], (T*)0));
return res;
}
} // namespace Datacratic
namespace OpenRTB {
template<typename T>
Json::Value jsonEncode(const OpenRTB::List<T> & vec)
{
using Datacratic::jsonEncode;
Json::Value result(Json::arrayValue);
for (unsigned i = 0; i < vec.size(); ++i)
result[i] = jsonEncode(vec[i]);
return result;
}
template<typename T>
OpenRTB::List<T>
jsonDecode(const Json::Value & val,OpenRTB::List<T> *)
{
using Datacratic::jsonDecode;
ExcAssert(val.isArray());
OpenRTB::List<T> res;
res.reserve(val.size());
for (unsigned i = 0; i < val.size(); ++i)
res.push_back(jsonDecode(val[i], (T*)0));
return res;
}
} // namespace Appodeal
namespace RTBKIT {
BOOST_STATIC_ASSERT(hasFromJson<Datacratic::Id>::value == true);
BOOST_STATIC_ASSERT(hasFromJson<int>::value == false);
/*****************************************************************************/
/* Appodeal EXCHANGE CONNECTOR */
/*****************************************************************************/
AppodealExchangeConnector::
AppodealExchangeConnector(ServiceBase & owner, const std::string & name)
: HttpExchangeConnector(name, owner)
{
}
AppodealExchangeConnector::
AppodealExchangeConnector(const std::string & name,
std::shared_ptr<ServiceProxies> proxies)
: HttpExchangeConnector(name, proxies)
{
}
std::shared_ptr<BidRequest>
AppodealExchangeConnector::
parseBidRequest(HttpAuctionHandler & connection,
const HttpHeader & header,
const std::string & payload)
{
std::shared_ptr<BidRequest> none;
// Check for JSON content-type
if (!header.contentType.empty()) {
static const std::string delimiter = ";";
std::string::size_type posDelim = header.contentType.find(delimiter);
std::string content;
if(posDelim == std::string::npos)
content = header.contentType;
else {
content = header.contentType.substr(0, posDelim);
#if 0
std::string charset = header.contentType.substr(posDelim, header.contentType.length());
#endif
}
if(content != "application/json") {
connection.sendErrorResponse("UNSUPPORTED_CONTENT_TYPE", "The request is required to use the 'Content-Type: application/json' header");
return none;
}
}
else {
connection.sendErrorResponse("MISSING_CONTENT_TYPE_HEADER", "The request is missing the 'Content-Type' header");
return none;
}
// Check for the x-openrtb-version header
auto it = header.headers.find("x-openrtb-version");
// if (it == header.headers.end()) {
// connection.sendErrorResponse("MISSING_OPENRTB_HEADER", "The request is missing the 'x-openrtb-version' header");
// myfile << "MISSING_OPENRTB_HEADER\n";
// return none;
// }
// Check that it's version 2.1
// std::string openRtbVersion = "it->second";
std::string openRtbVersion = "2.2";
// if (openRtbVersion != "2.1" && openRtbVersion != "2.2") {
// connection.sendErrorResponse("UNSUPPORTED_OPENRTB_VERSION", "The request is required to be using version 2.1 or 2.2 of the OpenRTB protocol but requested " + openRtbVersion);
// myfile << "UNSUPPORTED_OPENRTB_VERSION\n";
// return none;
// }
if(payload.empty()) {
this->recordHit("error.emptyBidRequest");
connection.sendErrorResponse("EMPTY_BID_REQUEST", "The request is empty");
return none;
}
// Parse the bid request
std::shared_ptr<BidRequest> result;
try {
ML::Parse_Context context("Bid Request", payload.c_str(), payload.size());
result.reset(OpenRTBBidRequestParser::openRTBBidRequestParserFactory(openRtbVersion)->parseBidRequest(context,
exchangeName(),
exchangeName()));
}
catch(ML::Exception const & e) {
this->recordHit("error.parsingBidRequest");
throw;
}
catch(...) {
throw;
}
// Check if we want some reporting
auto verbose = header.headers.find("x-openrtb-verbose");
if(header.headers.end() != verbose) {
if(verbose->second == "1") {
if(!result->auctionId.notNull()) {
connection.sendErrorResponse("MISSING_ID", "The bid request requires the 'id' field");
return none;
}
}
}
return result;
}
double
AppodealExchangeConnector::
getTimeAvailableMs(HttpAuctionHandler & connection,
const HttpHeader & header,
const std::string & payload)
{
// Scan the payload quickly for the tmax parameter.
static const std::string toFind = "\"tmax\":";
std::string::size_type pos = payload.find(toFind);
if (pos == std::string::npos)
return 45.0;
int tmax = atoi(payload.c_str() + pos + toFind.length());
return (absoluteTimeMax < tmax) ? absoluteTimeMax : tmax;
}
HttpResponse
AppodealExchangeConnector::
getResponse(const HttpAuctionHandler & connection,
const HttpHeader & requestHeader,
const Auction & auction) const
{
const Auction::Data * current = auction.getCurrentData();
if (current->hasError())
return getErrorResponse(connection,
current->error + ": " + current->details);
OpenRTB::BidResponse response;
response.id = auction.id;
response.ext = getResponseExt(connection, auction);
// Create a spot for each of the bid responses
for (unsigned spotNum = 0; spotNum < current->responses.size(); ++spotNum) {
if (!current->hasValidResponse(spotNum))
continue;
setSeatBid(auction, spotNum, response);
}
if (response.seatbid.empty())
return HttpResponse(204, "none", "");
static Datacratic::DefaultDescription<OpenRTB::BidResponse> desc;
std::ostringstream stream;
StreamJsonPrintingContext context(stream);
desc.printJsonTyped(&response, context);
cerr << "apposeal connector response 200:" << stream.str() << endl;
return HttpResponse(200, "application/json", stream.str());
}
Json::Value
AppodealExchangeConnector::
getResponseExt(const HttpAuctionHandler & connection,
const Auction & auction) const
{
return {};
}
HttpResponse
AppodealExchangeConnector::
getDroppedAuctionResponse(const HttpAuctionHandler & connection,
const std::string & reason) const
{
cerr << "apposeal connector response 204: none" << endl;
return HttpResponse(204, "none", "");
}
HttpResponse
AppodealExchangeConnector::
getErrorResponse(const HttpAuctionHandler & connection,
const std::string & message) const
{
Json::Value response;
response["error"] = message;
cerr << "apposeal connector response 400:" << message << endl;
return HttpResponse(400, response);
}
std::string
AppodealExchangeConnector::
getBidSourceConfiguration() const
{
auto suffix = std::to_string(port());
return ML::format("{\"type\":\"openrtb\",\"url\":\"%s\"}",
ML::fqdn_hostname(suffix) + ":" + suffix);
}
void
AppodealExchangeConnector::
setSeatBid(Auction const & auction,
int spotNum,
OpenRTB::BidResponse & response) const
{
const Auction::Data * data = auction.getCurrentData();
// Get the winning bid
auto & resp = data->winningResponse(spotNum);
int seatIndex = 0;
if(response.seatbid.empty()) {
response.seatbid.emplace_back();
}
OpenRTB::SeatBid & seatBid = response.seatbid.at(seatIndex);
// Add a new bid to the array
seatBid.bid.emplace_back();
// Put in the variable parts
auto & b = seatBid.bid.back();
b.cid = Id(resp.agentConfig->externalId);
b.crid = Id(resp.creativeId);
b.id = Id(auction.id, auction.request->imp[0].id);
b.impid = auction.request->imp[spotNum].id;
b.price.val = getAmountIn<CPM>(resp.price.maxPrice);
}
} // namespace RTBKIT
namespace {
using namespace RTBKIT;
struct AtInit {
AtInit() {
ExchangeConnector::registerFactory<AppodealExchangeConnector>();
}
} atInit;
}
<commit_msg>for amazon<commit_after> /* Appodeal_exchange_connector.cc
Eric Robert, 7 May 2013
Implementation of the OpenRTB exchange connector.
*/
#include "appodeal_exchange_connector.h"
#include "rtbkit/common/testing/exchange_source.h"
#include "rtbkit/plugins/bid_request/openrtb_bid_source.h"
#include "rtbkit/plugins/bid_request/openrtb_bid_request_parser.h"
#include "rtbkit/plugins/exchange/http_auction_handler.h"
#include "rtbkit/core/agent_configuration/agent_config.h"
#include "rtbkit/openrtb/openrtb_parsing.h"
#include "soa/types/json_printing.h"
#include <boost/any.hpp>
#include <boost/lexical_cast.hpp>
#include "jml/utils/file_functions.h"
#include "jml/arch/info.h"
#include "jml/utils/rng.h"
#include <sstream>
using namespace std;
void writeFile (std::string s) {
std::ofstream ofs;
ofs.open ("appobelnew.txt", std::ofstream::out | std::ofstream::app);
ofs << s << endl;
ofs.close();
}
using namespace Datacratic;
namespace Datacratic {
template<typename T, int I, typename S>
Json::Value jsonEncode(const ML::compact_vector<T, I, S> & vec)
{
Json::Value result(Json::arrayValue);
for (unsigned i = 0; i < vec.size(); ++i)
result[i] = jsonEncode(vec[i]);
return result;
}
template<typename T, int I, typename S>
ML::compact_vector<T, I, S>
jsonDecode(const Json::Value & val, ML::compact_vector<T, I, S> *)
{
ExcAssert(val.isArray());
ML::compact_vector<T, I, S> res;
res.reserve(val.size());
for (unsigned i = 0; i < val.size(); ++i)
res.push_back(jsonDecode(val[i], (T*)0));
return res;
}
} // namespace Datacratic
namespace OpenRTB {
template<typename T>
Json::Value jsonEncode(const OpenRTB::List<T> & vec)
{
using Datacratic::jsonEncode;
Json::Value result(Json::arrayValue);
for (unsigned i = 0; i < vec.size(); ++i)
result[i] = jsonEncode(vec[i]);
return result;
}
template<typename T>
OpenRTB::List<T>
jsonDecode(const Json::Value & val,OpenRTB::List<T> *)
{
using Datacratic::jsonDecode;
ExcAssert(val.isArray());
OpenRTB::List<T> res;
res.reserve(val.size());
for (unsigned i = 0; i < val.size(); ++i)
res.push_back(jsonDecode(val[i], (T*)0));
return res;
}
} // namespace Appodeal
namespace RTBKIT {
BOOST_STATIC_ASSERT(hasFromJson<Datacratic::Id>::value == true);
BOOST_STATIC_ASSERT(hasFromJson<int>::value == false);
/*****************************************************************************/
/* Appodeal EXCHANGE CONNECTOR */
/*****************************************************************************/
AppodealExchangeConnector::
AppodealExchangeConnector(ServiceBase & owner, const std::string & name)
: HttpExchangeConnector(name, owner)
{
}
AppodealExchangeConnector::
AppodealExchangeConnector(const std::string & name,
std::shared_ptr<ServiceProxies> proxies)
: HttpExchangeConnector(name, proxies)
{
}
std::shared_ptr<BidRequest>
AppodealExchangeConnector::
parseBidRequest(HttpAuctionHandler & connection,
const HttpHeader & header,
const std::string & payload)
{
std::shared_ptr<BidRequest> none;
writeFile(payload);
// Check for JSON content-type
if (!header.contentType.empty()) {
static const std::string delimiter = ";";
std::string::size_type posDelim = header.contentType.find(delimiter);
std::string content;
if(posDelim == std::string::npos)
content = header.contentType;
else {
content = header.contentType.substr(0, posDelim);
#if 0
std::string charset = header.contentType.substr(posDelim, header.contentType.length());
#endif
}
if(content != "application/json") {
connection.sendErrorResponse("UNSUPPORTED_CONTENT_TYPE", "The request is required to use the 'Content-Type: application/json' header");
return none;
}
}
else {
connection.sendErrorResponse("MISSING_CONTENT_TYPE_HEADER", "The request is missing the 'Content-Type' header");
return none;
}
// Check for the x-openrtb-version header
auto it = header.headers.find("x-openrtb-version");
// if (it == header.headers.end()) {
// connection.sendErrorResponse("MISSING_OPENRTB_HEADER", "The request is missing the 'x-openrtb-version' header");
// myfile << "MISSING_OPENRTB_HEADER\n";
// return none;
// }
// Check that it's version 2.1
// std::string openRtbVersion = "it->second";
std::string openRtbVersion = "2.2";
// if (openRtbVersion != "2.1" && openRtbVersion != "2.2") {
// connection.sendErrorResponse("UNSUPPORTED_OPENRTB_VERSION", "The request is required to be using version 2.1 or 2.2 of the OpenRTB protocol but requested " + openRtbVersion);
// myfile << "UNSUPPORTED_OPENRTB_VERSION\n";
// return none;
// }
if(payload.empty()) {
this->recordHit("error.emptyBidRequest");
connection.sendErrorResponse("EMPTY_BID_REQUEST", "The request is empty");
return none;
}
// Parse the bid request
std::shared_ptr<BidRequest> result;
try {
ML::Parse_Context context("Bid Request", payload.c_str(), payload.size());
result.reset(OpenRTBBidRequestParser::openRTBBidRequestParserFactory(openRtbVersion)->parseBidRequest(context,
exchangeName(),
exchangeName()));
}
catch(ML::Exception const & e) {
this->recordHit("error.parsingBidRequest");
throw;
}
catch(...) {
throw;
}
// Check if we want some reporting
auto verbose = header.headers.find("x-openrtb-verbose");
if(header.headers.end() != verbose) {
if(verbose->second == "1") {
if(!result->auctionId.notNull()) {
connection.sendErrorResponse("MISSING_ID", "The bid request requires the 'id' field");
return none;
}
}
}
return result;
}
double
AppodealExchangeConnector::
getTimeAvailableMs(HttpAuctionHandler & connection,
const HttpHeader & header,
const std::string & payload)
{
// Scan the payload quickly for the tmax parameter.
static const std::string toFind = "\"tmax\":";
std::string::size_type pos = payload.find(toFind);
if (pos == std::string::npos)
return 45.0;
int tmax = atoi(payload.c_str() + pos + toFind.length());
return (absoluteTimeMax < tmax) ? absoluteTimeMax : tmax;
}
HttpResponse
AppodealExchangeConnector::
getResponse(const HttpAuctionHandler & connection,
const HttpHeader & requestHeader,
const Auction & auction) const
{
/* const Auction::Data * current = auction.getCurrentData();
if (current->hasError())
return getErrorResponse(connection,
current->error + ": " + current->details);
OpenRTB::BidResponse response;
response.id = auction.id;
response.ext = getResponseExt(connection, auction);
// Create a spot for each of the bid responses
for (unsigned spotNum = 0; spotNum < current->responses.size(); ++spotNum) {
if (!current->hasValidResponse(spotNum))
continue;
setSeatBid(auction, spotNum, response);
}
if (response.seatbid.empty())
return HttpResponse(204, "none", "");
static Datacratic::DefaultDescription<OpenRTB::BidResponse> desc;
std::ostringstream stream;
StreamJsonPrintingContext context(stream);
desc.printJsonTyped(&response, context);
cerr << "apposeal connector response 200:" << stream.str() << endl;
return HttpResponse(200, "application/json", stream.str()); */
return HttpResponse(204, "none", "");
}
Json::Value
AppodealExchangeConnector::
getResponseExt(const HttpAuctionHandler & connection,
const Auction & auction) const
{
return {};
}
HttpResponse
AppodealExchangeConnector::
getDroppedAuctionResponse(const HttpAuctionHandler & connection,
const std::string & reason) const
{
cerr << "apposeal connector response 204: none" << endl;
return HttpResponse(204, "none", "");
}
HttpResponse
AppodealExchangeConnector::
getErrorResponse(const HttpAuctionHandler & connection,
const std::string & message) const
{
Json::Value response;
response["error"] = message;
cerr << "apposeal connector response 400:" << message << endl;
return HttpResponse(400, response);
}
std::string
AppodealExchangeConnector::
getBidSourceConfiguration() const
{
auto suffix = std::to_string(port());
return ML::format("{\"type\":\"openrtb\",\"url\":\"%s\"}",
ML::fqdn_hostname(suffix) + ":" + suffix);
}
void
AppodealExchangeConnector::
setSeatBid(Auction const & auction,
int spotNum,
OpenRTB::BidResponse & response) const
{
const Auction::Data * data = auction.getCurrentData();
// Get the winning bid
auto & resp = data->winningResponse(spotNum);
int seatIndex = 0;
if(response.seatbid.empty()) {
response.seatbid.emplace_back();
}
OpenRTB::SeatBid & seatBid = response.seatbid.at(seatIndex);
// Add a new bid to the array
seatBid.bid.emplace_back();
// Put in the variable parts
auto & b = seatBid.bid.back();
b.cid = Id(resp.agentConfig->externalId);
b.crid = Id(resp.creativeId);
b.id = Id(auction.id, auction.request->imp[0].id);
b.impid = auction.request->imp[spotNum].id;
b.price.val = getAmountIn<CPM>(resp.price.maxPrice);
}
} // namespace RTBKIT
namespace {
using namespace RTBKIT;
struct AtInit {
AtInit() {
ExchangeConnector::registerFactory<AppodealExchangeConnector>();
}
} atInit;
}
<|endoftext|> |
<commit_before>//===-- PrologEpilogInserter.cpp - Insert Prolog/Epilog code in function --===//
//
// The LLVM Compiler Infrastructure
//
// This file was developed by the LLVM research group and is distributed under
// the University of Illinois Open Source License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This pass is responsible for finalizing the functions frame layout, saving
// callee saved registers, and for emitting prolog & epilog code for the
// function.
//
// This pass must be run after register allocation. After this pass is
// executed, it is illegal to construct MO_FrameIndex operands.
//
//===----------------------------------------------------------------------===//
#include "llvm/CodeGen/Passes.h"
#include "llvm/CodeGen/MachineFunctionPass.h"
#include "llvm/CodeGen/MachineInstr.h"
#include "llvm/CodeGen/MachineFrameInfo.h"
#include "llvm/Target/TargetMachine.h"
#include "llvm/Target/MRegisterInfo.h"
#include "llvm/Target/TargetFrameInfo.h"
#include "llvm/Target/TargetInstrInfo.h"
using namespace llvm;
namespace {
struct PEI : public MachineFunctionPass {
const char *getPassName() const {
return "Prolog/Epilog Insertion & Frame Finalization";
}
/// runOnMachineFunction - Insert prolog/epilog code and replace abstract
/// frame indexes with appropriate references.
///
bool runOnMachineFunction(MachineFunction &Fn) {
// Scan the function for modified caller saved registers and insert spill
// code for any caller saved registers that are modified. Also calculate
// the MaxCallFrameSize and HasCalls variables for the function's frame
// information and eliminates call frame pseudo instructions.
calculateCallerSavedRegisters(Fn);
// Add the code to save and restore the caller saved registers
saveCallerSavedRegisters(Fn);
// Allow the target machine to make final modifications to the function
// before the frame layout is finalized.
Fn.getTarget().getRegisterInfo()->processFunctionBeforeFrameFinalized(Fn);
// Calculate actual frame offsets for all of the abstract stack objects...
calculateFrameObjectOffsets(Fn);
// Add prolog and epilog code to the function. This function is required
// to align the stack frame as necessary for any stack variables or
// called functions. Because of this, calculateCallerSavedRegisters
// must be called before this function in order to set the HasCalls
// and MaxCallFrameSize variables.
insertPrologEpilogCode(Fn);
// Replace all MO_FrameIndex operands with physical register references
// and actual offsets.
//
replaceFrameIndices(Fn);
RegsToSave.clear();
StackSlots.clear();
return true;
}
private:
std::vector<unsigned> RegsToSave;
std::vector<int> StackSlots;
void calculateCallerSavedRegisters(MachineFunction &Fn);
void saveCallerSavedRegisters(MachineFunction &Fn);
void calculateFrameObjectOffsets(MachineFunction &Fn);
void replaceFrameIndices(MachineFunction &Fn);
void insertPrologEpilogCode(MachineFunction &Fn);
};
}
/// createPrologEpilogCodeInserter - This function returns a pass that inserts
/// prolog and epilog code, and eliminates abstract frame references.
///
FunctionPass *llvm::createPrologEpilogCodeInserter() { return new PEI(); }
/// calculateCallerSavedRegisters - Scan the function for modified caller saved
/// registers. Also calculate the MaxCallFrameSize and HasCalls variables for
/// the function's frame information and eliminates call frame pseudo
/// instructions.
///
void PEI::calculateCallerSavedRegisters(MachineFunction &Fn) {
const MRegisterInfo *RegInfo = Fn.getTarget().getRegisterInfo();
const TargetFrameInfo *TFI = Fn.getTarget().getFrameInfo();
// Get the callee saved register list...
const unsigned *CSRegs = RegInfo->getCalleeSaveRegs();
// Get the function call frame set-up and tear-down instruction opcode
int FrameSetupOpcode = RegInfo->getCallFrameSetupOpcode();
int FrameDestroyOpcode = RegInfo->getCallFrameDestroyOpcode();
// Early exit for targets which have no callee saved registers and no call
// frame setup/destroy pseudo instructions.
if ((CSRegs == 0 || CSRegs[0] == 0) &&
FrameSetupOpcode == -1 && FrameDestroyOpcode == -1)
return;
// This bitset contains an entry for each physical register for the target...
std::vector<bool> ModifiedRegs(RegInfo->getNumRegs());
unsigned MaxCallFrameSize = 0;
bool HasCalls = false;
for (MachineFunction::iterator BB = Fn.begin(), E = Fn.end(); BB != E; ++BB)
for (MachineBasicBlock::iterator I = BB->begin(); I != BB->end(); )
if (I->getOpcode() == FrameSetupOpcode ||
I->getOpcode() == FrameDestroyOpcode) {
assert(I->getNumOperands() == 1 && "Call Frame Setup/Destroy Pseudo"
" instructions should have a single immediate argument!");
unsigned Size = I->getOperand(0).getImmedValue();
if (Size > MaxCallFrameSize) MaxCallFrameSize = Size;
HasCalls = true;
RegInfo->eliminateCallFramePseudoInstr(Fn, *BB, I++);
} else {
for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) {
MachineOperand &MO = I->getOperand(i);
if (MO.isRegister() && MO.isDef()) {
assert(MRegisterInfo::isPhysicalRegister(MO.getReg()) &&
"Register allocation must be performed!");
ModifiedRegs[MO.getReg()] = true; // Register is modified
}
}
++I;
}
MachineFrameInfo *FFI = Fn.getFrameInfo();
FFI->setHasCalls(HasCalls);
FFI->setMaxCallFrameSize(MaxCallFrameSize);
// Now figure out which *callee saved* registers are modified by the current
// function, thus needing to be saved and restored in the prolog/epilog.
//
for (unsigned i = 0; CSRegs[i]; ++i) {
unsigned Reg = CSRegs[i];
if (ModifiedRegs[Reg]) {
RegsToSave.push_back(Reg); // If modified register...
} else {
for (const unsigned *AliasSet = RegInfo->getAliasSet(Reg);
*AliasSet; ++AliasSet) { // Check alias registers too...
if (ModifiedRegs[*AliasSet]) {
RegsToSave.push_back(Reg);
break;
}
}
}
}
if (RegsToSave.empty())
return; // Early exit if no caller saved registers are modified!
unsigned NumFixedSpillSlots;
const std::pair<unsigned,int> *FixedSpillSlots =
TFI->getCalleeSaveSpillSlots(NumFixedSpillSlots);
// Now that we know which registers need to be saved and restored, allocate
// stack slots for them.
for (unsigned i = 0, e = RegsToSave.size(); i != e; ++i) {
unsigned Reg = RegsToSave[i];
// Check to see if this physreg must be spilled to a particular stack slot
// on this target.
const std::pair<unsigned,int> *FixedSlot = FixedSpillSlots;
while (FixedSlot != FixedSpillSlots+NumFixedSpillSlots &&
FixedSlot->first != Reg)
++FixedSlot;
int FrameIdx;
if (FixedSlot == FixedSpillSlots+NumFixedSpillSlots) {
// Nope, just spill it anywhere convenient.
FrameIdx = FFI->CreateStackObject(RegInfo->getSpillSize(Reg)/8,
RegInfo->getSpillAlignment(Reg)/8);
} else {
// Spill it to the stack where we must.
FrameIdx = FFI->CreateFixedObject(RegInfo->getSpillSize(Reg)/8,
FixedSlot->second);
}
StackSlots.push_back(FrameIdx);
}
}
/// saveCallerSavedRegisters - Insert spill code for any caller saved registers
/// that are modified in the function.
///
void PEI::saveCallerSavedRegisters(MachineFunction &Fn) {
// Early exit if no caller saved registers are modified!
if (RegsToSave.empty())
return;
const MRegisterInfo *RegInfo = Fn.getTarget().getRegisterInfo();
// Now that we have a stack slot for each register to be saved, insert spill
// code into the entry block...
MachineBasicBlock *MBB = Fn.begin();
MachineBasicBlock::iterator I = MBB->begin();
for (unsigned i = 0, e = RegsToSave.size(); i != e; ++i) {
// Insert the spill to the stack frame.
RegInfo->storeRegToStackSlot(*MBB, I, RegsToSave[i], StackSlots[i]);
}
// Add code to restore the callee-save registers in each exiting block.
const TargetInstrInfo &TII = *Fn.getTarget().getInstrInfo();
for (MachineFunction::iterator FI = Fn.begin(), E = Fn.end(); FI != E; ++FI) {
// If last instruction is a return instruction, add an epilogue
if (!FI->empty() && TII.isReturn(FI->back().getOpcode())) {
MBB = FI;
I = MBB->end(); --I;
for (unsigned i = 0, e = RegsToSave.size(); i != e; ++i) {
RegInfo->loadRegFromStackSlot(*MBB, I, RegsToSave[i], StackSlots[i]);
assert(I != MBB->begin() &&
"loadRegFromStackSlot didn't insert any code!");
--I; // Insert in reverse order
}
}
}
}
/// calculateFrameObjectOffsets - Calculate actual frame offsets for all of the
/// abstract stack objects...
///
void PEI::calculateFrameObjectOffsets(MachineFunction &Fn) {
const TargetFrameInfo &TFI = *Fn.getTarget().getFrameInfo();
bool StackGrowsDown =
TFI.getStackGrowthDirection() == TargetFrameInfo::StackGrowsDown;
// Loop over all of the stack objects, assigning sequential addresses...
MachineFrameInfo *FFI = Fn.getFrameInfo();
unsigned StackAlignment = TFI.getStackAlignment();
// Start at the beginning of the local area.
// The Offset is the distance from the stack top in the direction
// of stack growth -- so it's always positive.
int Offset = TFI.getOffsetOfLocalArea();
if (StackGrowsDown)
Offset = -Offset;
assert(Offset >= 0
&& "Local area offset should be in direction of stack growth");
// If there are fixed sized objects that are preallocated in the local area,
// non-fixed objects can't be allocated right at the start of local area.
// We currently don't support filling in holes in between fixed sized objects,
// so we adjust 'Offset' to point to the end of last fixed sized
// preallocated object.
for (int i = FFI->getObjectIndexBegin(); i != 0; ++i) {
int FixedOff;
if (StackGrowsDown) {
// The maximum distance from the stack pointer is at lower address of
// the object -- which is given by offset. For down growing stack
// the offset is negative, so we negate the offset to get the distance.
FixedOff = -FFI->getObjectOffset(i);
} else {
// The maximum distance from the start pointer is at the upper
// address of the object.
FixedOff = FFI->getObjectOffset(i) + FFI->getObjectSize(i);
}
if (FixedOff > Offset) Offset = FixedOff;
}
for (unsigned i = 0, e = FFI->getObjectIndexEnd(); i != e; ++i) {
// If stack grows down, we need to add size of find the lowest
// address of the object.
if (StackGrowsDown)
Offset += FFI->getObjectSize(i);
unsigned Align = FFI->getObjectAlignment(i);
assert(Align <= StackAlignment && "Cannot align stack object to higher "
"alignment boundary than the stack itself!");
Offset = (Offset+Align-1)/Align*Align; // Adjust to Alignment boundary...
if (StackGrowsDown) {
FFI->setObjectOffset(i, -Offset); // Set the computed offset
} else {
FFI->setObjectOffset(i, Offset);
Offset += FFI->getObjectSize(i);
}
}
// Align the final stack pointer offset, but only if there are calls in the
// function. This ensures that any calls to subroutines have their stack
// frames suitable aligned.
if (FFI->hasCalls())
Offset = (Offset+StackAlignment-1)/StackAlignment*StackAlignment;
// Set the final value of the stack pointer...
FFI->setStackSize(Offset+TFI.getOffsetOfLocalArea());
}
/// insertPrologEpilogCode - Scan the function for modified caller saved
/// registers, insert spill code for these caller saved registers, then add
/// prolog and epilog code to the function.
///
void PEI::insertPrologEpilogCode(MachineFunction &Fn) {
// Add prologue to the function...
Fn.getTarget().getRegisterInfo()->emitPrologue(Fn);
// Add epilogue to restore the callee-save registers in each exiting block
const TargetInstrInfo &TII = *Fn.getTarget().getInstrInfo();
for (MachineFunction::iterator I = Fn.begin(), E = Fn.end(); I != E; ++I) {
// If last instruction is a return instruction, add an epilogue
if (!I->empty() && TII.isReturn(I->back().getOpcode()))
Fn.getTarget().getRegisterInfo()->emitEpilogue(Fn, *I);
}
}
/// replaceFrameIndices - Replace all MO_FrameIndex operands with physical
/// register references and actual offsets.
///
void PEI::replaceFrameIndices(MachineFunction &Fn) {
if (!Fn.getFrameInfo()->hasStackObjects()) return; // Nothing to do?
const TargetMachine &TM = Fn.getTarget();
assert(TM.getRegisterInfo() && "TM::getRegisterInfo() must be implemented!");
const MRegisterInfo &MRI = *TM.getRegisterInfo();
for (MachineFunction::iterator BB = Fn.begin(), E = Fn.end(); BB != E; ++BB)
for (MachineBasicBlock::iterator I = BB->begin(); I != BB->end(); ++I)
for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
if (I->getOperand(i).isFrameIndex()) {
// If this instruction has a FrameIndex operand, we need to use that
// target machine register info object to eliminate it.
MRI.eliminateFrameIndex(I);
break;
}
}
<commit_msg>Implicitly defined registers can clobber callee saved registers too! This fixes the return-address-not-being-saved problem in the Alpha backend.<commit_after>//===-- PrologEpilogInserter.cpp - Insert Prolog/Epilog code in function --===//
//
// The LLVM Compiler Infrastructure
//
// This file was developed by the LLVM research group and is distributed under
// the University of Illinois Open Source License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This pass is responsible for finalizing the functions frame layout, saving
// callee saved registers, and for emitting prolog & epilog code for the
// function.
//
// This pass must be run after register allocation. After this pass is
// executed, it is illegal to construct MO_FrameIndex operands.
//
//===----------------------------------------------------------------------===//
#include "llvm/CodeGen/Passes.h"
#include "llvm/CodeGen/MachineFunctionPass.h"
#include "llvm/CodeGen/MachineInstr.h"
#include "llvm/CodeGen/MachineFrameInfo.h"
#include "llvm/Target/TargetMachine.h"
#include "llvm/Target/MRegisterInfo.h"
#include "llvm/Target/TargetFrameInfo.h"
#include "llvm/Target/TargetInstrInfo.h"
using namespace llvm;
namespace {
struct PEI : public MachineFunctionPass {
const char *getPassName() const {
return "Prolog/Epilog Insertion & Frame Finalization";
}
/// runOnMachineFunction - Insert prolog/epilog code and replace abstract
/// frame indexes with appropriate references.
///
bool runOnMachineFunction(MachineFunction &Fn) {
// Scan the function for modified caller saved registers and insert spill
// code for any caller saved registers that are modified. Also calculate
// the MaxCallFrameSize and HasCalls variables for the function's frame
// information and eliminates call frame pseudo instructions.
calculateCallerSavedRegisters(Fn);
// Add the code to save and restore the caller saved registers
saveCallerSavedRegisters(Fn);
// Allow the target machine to make final modifications to the function
// before the frame layout is finalized.
Fn.getTarget().getRegisterInfo()->processFunctionBeforeFrameFinalized(Fn);
// Calculate actual frame offsets for all of the abstract stack objects...
calculateFrameObjectOffsets(Fn);
// Add prolog and epilog code to the function. This function is required
// to align the stack frame as necessary for any stack variables or
// called functions. Because of this, calculateCallerSavedRegisters
// must be called before this function in order to set the HasCalls
// and MaxCallFrameSize variables.
insertPrologEpilogCode(Fn);
// Replace all MO_FrameIndex operands with physical register references
// and actual offsets.
//
replaceFrameIndices(Fn);
RegsToSave.clear();
StackSlots.clear();
return true;
}
private:
std::vector<unsigned> RegsToSave;
std::vector<int> StackSlots;
void calculateCallerSavedRegisters(MachineFunction &Fn);
void saveCallerSavedRegisters(MachineFunction &Fn);
void calculateFrameObjectOffsets(MachineFunction &Fn);
void replaceFrameIndices(MachineFunction &Fn);
void insertPrologEpilogCode(MachineFunction &Fn);
};
}
/// createPrologEpilogCodeInserter - This function returns a pass that inserts
/// prolog and epilog code, and eliminates abstract frame references.
///
FunctionPass *llvm::createPrologEpilogCodeInserter() { return new PEI(); }
/// calculateCallerSavedRegisters - Scan the function for modified caller saved
/// registers. Also calculate the MaxCallFrameSize and HasCalls variables for
/// the function's frame information and eliminates call frame pseudo
/// instructions.
///
void PEI::calculateCallerSavedRegisters(MachineFunction &Fn) {
const MRegisterInfo *RegInfo = Fn.getTarget().getRegisterInfo();
const TargetFrameInfo *TFI = Fn.getTarget().getFrameInfo();
const TargetInstrInfo &TII = *Fn.getTarget().getInstrInfo();
// Get the callee saved register list...
const unsigned *CSRegs = RegInfo->getCalleeSaveRegs();
// Get the function call frame set-up and tear-down instruction opcode
int FrameSetupOpcode = RegInfo->getCallFrameSetupOpcode();
int FrameDestroyOpcode = RegInfo->getCallFrameDestroyOpcode();
// Early exit for targets which have no callee saved registers and no call
// frame setup/destroy pseudo instructions.
if ((CSRegs == 0 || CSRegs[0] == 0) &&
FrameSetupOpcode == -1 && FrameDestroyOpcode == -1)
return;
// This bitset contains an entry for each physical register for the target...
std::vector<bool> ModifiedRegs(RegInfo->getNumRegs());
unsigned MaxCallFrameSize = 0;
bool HasCalls = false;
for (MachineFunction::iterator BB = Fn.begin(), E = Fn.end(); BB != E; ++BB)
for (MachineBasicBlock::iterator I = BB->begin(); I != BB->end(); )
if (I->getOpcode() == FrameSetupOpcode ||
I->getOpcode() == FrameDestroyOpcode) {
assert(I->getNumOperands() == 1 && "Call Frame Setup/Destroy Pseudo"
" instructions should have a single immediate argument!");
unsigned Size = I->getOperand(0).getImmedValue();
if (Size > MaxCallFrameSize) MaxCallFrameSize = Size;
HasCalls = true;
RegInfo->eliminateCallFramePseudoInstr(Fn, *BB, I++);
} else {
for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) {
MachineOperand &MO = I->getOperand(i);
if (MO.isRegister() && MO.isDef()) {
assert(MRegisterInfo::isPhysicalRegister(MO.getReg()) &&
"Register allocation must be performed!");
ModifiedRegs[MO.getReg()] = true; // Register is modified
}
// Mark any implicitly defined registers as being modified.
for (const unsigned *ImpDefs = TII.getImplicitDefs(I->getOpcode());
*ImpDefs; ++ImpDefs)
ModifiedRegs[*ImpDefs] = true;
}
++I;
}
MachineFrameInfo *FFI = Fn.getFrameInfo();
FFI->setHasCalls(HasCalls);
FFI->setMaxCallFrameSize(MaxCallFrameSize);
// Now figure out which *callee saved* registers are modified by the current
// function, thus needing to be saved and restored in the prolog/epilog.
//
for (unsigned i = 0; CSRegs[i]; ++i) {
unsigned Reg = CSRegs[i];
if (ModifiedRegs[Reg]) {
RegsToSave.push_back(Reg); // If modified register...
} else {
for (const unsigned *AliasSet = RegInfo->getAliasSet(Reg);
*AliasSet; ++AliasSet) { // Check alias registers too...
if (ModifiedRegs[*AliasSet]) {
RegsToSave.push_back(Reg);
break;
}
}
}
}
if (RegsToSave.empty())
return; // Early exit if no caller saved registers are modified!
unsigned NumFixedSpillSlots;
const std::pair<unsigned,int> *FixedSpillSlots =
TFI->getCalleeSaveSpillSlots(NumFixedSpillSlots);
// Now that we know which registers need to be saved and restored, allocate
// stack slots for them.
for (unsigned i = 0, e = RegsToSave.size(); i != e; ++i) {
unsigned Reg = RegsToSave[i];
// Check to see if this physreg must be spilled to a particular stack slot
// on this target.
const std::pair<unsigned,int> *FixedSlot = FixedSpillSlots;
while (FixedSlot != FixedSpillSlots+NumFixedSpillSlots &&
FixedSlot->first != Reg)
++FixedSlot;
int FrameIdx;
if (FixedSlot == FixedSpillSlots+NumFixedSpillSlots) {
// Nope, just spill it anywhere convenient.
FrameIdx = FFI->CreateStackObject(RegInfo->getSpillSize(Reg)/8,
RegInfo->getSpillAlignment(Reg)/8);
} else {
// Spill it to the stack where we must.
FrameIdx = FFI->CreateFixedObject(RegInfo->getSpillSize(Reg)/8,
FixedSlot->second);
}
StackSlots.push_back(FrameIdx);
}
}
/// saveCallerSavedRegisters - Insert spill code for any caller saved registers
/// that are modified in the function.
///
void PEI::saveCallerSavedRegisters(MachineFunction &Fn) {
// Early exit if no caller saved registers are modified!
if (RegsToSave.empty())
return;
const MRegisterInfo *RegInfo = Fn.getTarget().getRegisterInfo();
// Now that we have a stack slot for each register to be saved, insert spill
// code into the entry block...
MachineBasicBlock *MBB = Fn.begin();
MachineBasicBlock::iterator I = MBB->begin();
for (unsigned i = 0, e = RegsToSave.size(); i != e; ++i) {
// Insert the spill to the stack frame.
RegInfo->storeRegToStackSlot(*MBB, I, RegsToSave[i], StackSlots[i]);
}
// Add code to restore the callee-save registers in each exiting block.
const TargetInstrInfo &TII = *Fn.getTarget().getInstrInfo();
for (MachineFunction::iterator FI = Fn.begin(), E = Fn.end(); FI != E; ++FI) {
// If last instruction is a return instruction, add an epilogue
if (!FI->empty() && TII.isReturn(FI->back().getOpcode())) {
MBB = FI;
I = MBB->end(); --I;
for (unsigned i = 0, e = RegsToSave.size(); i != e; ++i) {
RegInfo->loadRegFromStackSlot(*MBB, I, RegsToSave[i], StackSlots[i]);
assert(I != MBB->begin() &&
"loadRegFromStackSlot didn't insert any code!");
--I; // Insert in reverse order
}
}
}
}
/// calculateFrameObjectOffsets - Calculate actual frame offsets for all of the
/// abstract stack objects...
///
void PEI::calculateFrameObjectOffsets(MachineFunction &Fn) {
const TargetFrameInfo &TFI = *Fn.getTarget().getFrameInfo();
bool StackGrowsDown =
TFI.getStackGrowthDirection() == TargetFrameInfo::StackGrowsDown;
// Loop over all of the stack objects, assigning sequential addresses...
MachineFrameInfo *FFI = Fn.getFrameInfo();
unsigned StackAlignment = TFI.getStackAlignment();
// Start at the beginning of the local area.
// The Offset is the distance from the stack top in the direction
// of stack growth -- so it's always positive.
int Offset = TFI.getOffsetOfLocalArea();
if (StackGrowsDown)
Offset = -Offset;
assert(Offset >= 0
&& "Local area offset should be in direction of stack growth");
// If there are fixed sized objects that are preallocated in the local area,
// non-fixed objects can't be allocated right at the start of local area.
// We currently don't support filling in holes in between fixed sized objects,
// so we adjust 'Offset' to point to the end of last fixed sized
// preallocated object.
for (int i = FFI->getObjectIndexBegin(); i != 0; ++i) {
int FixedOff;
if (StackGrowsDown) {
// The maximum distance from the stack pointer is at lower address of
// the object -- which is given by offset. For down growing stack
// the offset is negative, so we negate the offset to get the distance.
FixedOff = -FFI->getObjectOffset(i);
} else {
// The maximum distance from the start pointer is at the upper
// address of the object.
FixedOff = FFI->getObjectOffset(i) + FFI->getObjectSize(i);
}
if (FixedOff > Offset) Offset = FixedOff;
}
for (unsigned i = 0, e = FFI->getObjectIndexEnd(); i != e; ++i) {
// If stack grows down, we need to add size of find the lowest
// address of the object.
if (StackGrowsDown)
Offset += FFI->getObjectSize(i);
unsigned Align = FFI->getObjectAlignment(i);
assert(Align <= StackAlignment && "Cannot align stack object to higher "
"alignment boundary than the stack itself!");
Offset = (Offset+Align-1)/Align*Align; // Adjust to Alignment boundary...
if (StackGrowsDown) {
FFI->setObjectOffset(i, -Offset); // Set the computed offset
} else {
FFI->setObjectOffset(i, Offset);
Offset += FFI->getObjectSize(i);
}
}
// Align the final stack pointer offset, but only if there are calls in the
// function. This ensures that any calls to subroutines have their stack
// frames suitable aligned.
if (FFI->hasCalls())
Offset = (Offset+StackAlignment-1)/StackAlignment*StackAlignment;
// Set the final value of the stack pointer...
FFI->setStackSize(Offset+TFI.getOffsetOfLocalArea());
}
/// insertPrologEpilogCode - Scan the function for modified caller saved
/// registers, insert spill code for these caller saved registers, then add
/// prolog and epilog code to the function.
///
void PEI::insertPrologEpilogCode(MachineFunction &Fn) {
// Add prologue to the function...
Fn.getTarget().getRegisterInfo()->emitPrologue(Fn);
// Add epilogue to restore the callee-save registers in each exiting block
const TargetInstrInfo &TII = *Fn.getTarget().getInstrInfo();
for (MachineFunction::iterator I = Fn.begin(), E = Fn.end(); I != E; ++I) {
// If last instruction is a return instruction, add an epilogue
if (!I->empty() && TII.isReturn(I->back().getOpcode()))
Fn.getTarget().getRegisterInfo()->emitEpilogue(Fn, *I);
}
}
/// replaceFrameIndices - Replace all MO_FrameIndex operands with physical
/// register references and actual offsets.
///
void PEI::replaceFrameIndices(MachineFunction &Fn) {
if (!Fn.getFrameInfo()->hasStackObjects()) return; // Nothing to do?
const TargetMachine &TM = Fn.getTarget();
assert(TM.getRegisterInfo() && "TM::getRegisterInfo() must be implemented!");
const MRegisterInfo &MRI = *TM.getRegisterInfo();
for (MachineFunction::iterator BB = Fn.begin(), E = Fn.end(); BB != E; ++BB)
for (MachineBasicBlock::iterator I = BB->begin(); I != BB->end(); ++I)
for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
if (I->getOperand(i).isFrameIndex()) {
// If this instruction has a FrameIndex operand, we need to use that
// target machine register info object to eliminate it.
MRI.eliminateFrameIndex(I);
break;
}
}
<|endoftext|> |
<commit_before>/**
* \file
* \brief SoftwareTimer class header
*
* \author Copyright (C) 2015 Kamil Szczygiel http://www.distortec.com http://www.freddiechopin.info
*
* \par License
* This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0. If a copy of the MPL was not
* distributed with this file, You can obtain one at http://mozilla.org/MPL/2.0/.
*
* \date 2015-11-15
*/
#ifndef INCLUDE_DISTORTOS_SOFTWARETIMER_HPP_
#define INCLUDE_DISTORTOS_SOFTWARETIMER_HPP_
#include "distortos/scheduler/SoftwareTimerControlBlock.hpp"
namespace distortos
{
/// SoftwareTimer is a base for software timers
class SoftwareTimer : private scheduler::SoftwareTimerControlBlock
{
public:
/**
* \brief SoftwareTimer's constructor
*/
SoftwareTimer() :
SoftwareTimerControlBlock{softwareTimerRunner, *this}
{
}
/**
* \return true if the timer is running, false otherwise
*/
bool isRunning() const
{
return SoftwareTimerControlBlock::isRunning();
}
using SoftwareTimerControlBlock::start;
using SoftwareTimerControlBlock::stop;
protected:
/**
* \brief SoftwareTimer's destructor
*
* \note Polymorphic objects of SoftwareTimer type must not be deleted via pointer/reference
*/
~SoftwareTimer()
{
}
private:
/**
* \brief "Run" function of software timer
*
* This should be overridden by derived classes.
*/
virtual void run() = 0;
/**
* \brief Software timer's function runner
*
* \param [in] softwareTimer is a reference to SoftwareTimer object that is being run
*/
static void softwareTimerRunner(SoftwareTimer& softwareTimer);
};
} // namespace distortos
#endif // INCLUDE_DISTORTOS_SOFTWARETIMER_HPP_
<commit_msg>SoftwareTimer::start(): provide real functions instead of "using ..."<commit_after>/**
* \file
* \brief SoftwareTimer class header
*
* \author Copyright (C) 2015 Kamil Szczygiel http://www.distortec.com http://www.freddiechopin.info
*
* \par License
* This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0. If a copy of the MPL was not
* distributed with this file, You can obtain one at http://mozilla.org/MPL/2.0/.
*
* \date 2015-11-15
*/
#ifndef INCLUDE_DISTORTOS_SOFTWARETIMER_HPP_
#define INCLUDE_DISTORTOS_SOFTWARETIMER_HPP_
#include "distortos/scheduler/SoftwareTimerControlBlock.hpp"
namespace distortos
{
/// SoftwareTimer is a base for software timers
class SoftwareTimer : private scheduler::SoftwareTimerControlBlock
{
public:
/**
* \brief SoftwareTimer's constructor
*/
SoftwareTimer() :
SoftwareTimerControlBlock{softwareTimerRunner, *this}
{
}
/**
* \return true if the timer is running, false otherwise
*/
bool isRunning() const
{
return SoftwareTimerControlBlock::isRunning();
}
/**
* \brief Starts the timer.
*
* \note The duration will never be shorter, so one additional tick is always added to the duration.
*
* \param [in] duration is the duration after which the function will be executed
*/
void start(const TickClock::duration duration)
{
SoftwareTimerControlBlock::start(duration);
}
/**
* \brief Starts the timer.
*
* \note The duration must not be shorter, so one additional tick is always added to the duration.
*
* \param Rep is type of tick counter
* \param Period is std::ratio type representing the tick period of the clock, in seconds
*
* \param [in] duration is the duration after which the function will be executed
*/
template<typename Rep, typename Period>
void start(const std::chrono::duration<Rep, Period> duration)
{
start(std::chrono::duration_cast<TickClock::duration>(duration));
}
/**
* \brief Starts the timer.
*
* \param [in] timePoint is the time point at which the function will be executed
*/
void start(const TickClock::time_point timePoint)
{
SoftwareTimerControlBlock::start(timePoint);
}
/**
* \brief Starts the timer.
*
* \param Duration is a std::chrono::duration type used to measure duration
*
* \param [in] timePoint is the time point at which the function will be executed
*/
template<typename Duration>
void start(const std::chrono::time_point<TickClock, Duration> timePoint)
{
start(std::chrono::time_point_cast<TickClock::duration>(timePoint));
}
using SoftwareTimerControlBlock::stop;
protected:
/**
* \brief SoftwareTimer's destructor
*
* \note Polymorphic objects of SoftwareTimer type must not be deleted via pointer/reference
*/
~SoftwareTimer()
{
}
private:
/**
* \brief "Run" function of software timer
*
* This should be overridden by derived classes.
*/
virtual void run() = 0;
/**
* \brief Software timer's function runner
*
* \param [in] softwareTimer is a reference to SoftwareTimer object that is being run
*/
static void softwareTimerRunner(SoftwareTimer& softwareTimer);
};
} // namespace distortos
#endif // INCLUDE_DISTORTOS_SOFTWARETIMER_HPP_
<|endoftext|> |
<commit_before>#pragma once
#include <cassert>
#include <list>
namespace AGE
{
// Buffer pool largely inspired by :
// http://www.codeproject.com/Articles/3526/Buffer-Pool-Object-Pool
// Still need a LOOOOOOOTS of improvements
class BufferPool
{
protected:
virtual ~BufferPool()
{
_destroy();
}
BufferPool()
: _objectPerChunk(0)
, _objectSize(0)
, _chunksNumber(0)
, _freeObjectNumber(0)
, _chunkAlignement(0)
, _objectAlignement(0)
{}
struct Link
{
Link *next;
Link() : next(nullptr) {}
inline void init() { next = nullptr; }
inline bool empty() const { return (next == nullptr); }
inline Link *pop()
{
auto res = next;
next = next->next;
return res;
}
inline void push(Link *l)
{
l->next = next;
next = l;
}
};
struct Chunk
{
std::size_t emptySlotsNumber;
Link emptySlotsList;
};
struct ChunkHeader
{
std::size_t index;
};
std::list<Chunk*> _chunks;
std::size_t _objectPerChunk;
std::size_t _objectSize;
std::size_t _chunksNumber;
std::size_t _freeObjectNumber;
std::size_t _chunkAlignement;
std::size_t _objectAlignement;
bool _allocateChunk()
{
auto chunkSize = _getChunkSize();
auto newChunk = (Chunk*)(new unsigned char[chunkSize]);
if (!newChunk)
return false;
newChunk->emptySlotsNumber = _objectPerChunk;
newChunk->emptySlotsList.init();
_chunks.push_front(newChunk);
_freeObjectNumber += _objectPerChunk;
++_chunksNumber;
auto data = (unsigned char*)(newChunk + _chunkAlignement + 1);
for (std::size_t i = 0; i < _objectPerChunk; ++i)
{
((ChunkHeader*)(data))->index = i;
data += sizeof(ChunkHeader);
newChunk->emptySlotsList.push((Link*)(data));
data += _objectSize + _objectAlignement;
}
return true;
}
bool _allocateObject(void *&addr)
{
if (_freeObjectNumber == 0)
{
auto noError = _allocateChunk();
assert(noError);
}
for (auto &e : _chunks)
{
if (e->emptySlotsNumber != 0)
{
auto ptr = e->emptySlotsList.pop();
--e->emptySlotsNumber;
--_freeObjectNumber;
addr = ptr;
return true;
}
}
return false;
}
bool _dealocateObject(void *addr)
{
auto data = (unsigned char *)(addr);
data -= sizeof(ChunkHeader);
auto chunk = (Chunk*)(data - (((ChunkHeader*)(data))->index * (sizeof(ChunkHeader) + _objectSize + _objectAlignement)) - _chunkAlignement) - 1;
++chunk->emptySlotsNumber;
chunk->emptySlotsList.push((Link*)(addr));
++_freeObjectNumber;
return false;
}
void _destroy()
{
//for (auto &e : _chunks)
//{
// delete[](unsigned char *)e;
//}
}
inline std::size_t _getChunkSize() const { return _chunkAlignement + sizeof(Chunk) + _objectPerChunk * (_objectSize + _objectAlignement + sizeof(ChunkHeader)); }
bool _init(std::size_t objectSize, std::size_t objectAlignment, std::size_t chunkSize /* object per chunk */)
{
_objectSize = sizeof(Link);
_objectPerChunk = chunkSize;
if (objectSize > _objectSize)
_objectSize = objectSize;
_objectAlignement = objectAlignment - ((sizeof(ChunkHeader) + _objectSize) % objectAlignment);
if (_objectAlignement == objectAlignment)
_objectAlignement = 0;
_chunkAlignement = objectAlignment - ((sizeof(ChunkHeader) + sizeof(Chunk)) % objectAlignment);
if (_chunkAlignement == objectAlignment)
_chunkAlignement = 0;
return true;
}
};
}<commit_msg>alignement fixed<commit_after>#pragma once
#include <cassert>
#include <list>
namespace AGE
{
// Buffer pool largely inspired by :
// http://www.codeproject.com/Articles/3526/Buffer-Pool-Object-Pool
// Still need a LOOOOOOOTS of improvements
class BufferPool
{
protected:
virtual ~BufferPool()
{
_destroy();
}
BufferPool()
: _objectPerChunk(0)
, _objectSize(0)
, _chunksNumber(0)
, _freeObjectNumber(0)
, _chunkAlignement(0)
, _objectAlignement(0)
{}
struct Link
{
Link *next;
Link() : next(nullptr) {}
inline void init() { next = nullptr; }
inline bool empty() const { return (next == nullptr); }
inline Link *pop()
{
auto res = next;
next = next->next;
return res;
}
inline void push(Link *l)
{
l->next = next;
next = l;
}
};
struct Chunk
{
std::size_t emptySlotsNumber;
Link emptySlotsList;
};
struct ChunkHeader
{
std::size_t index;
};
std::list<Chunk*> _chunks;
std::size_t _objectPerChunk;
std::size_t _objectSize;
std::size_t _chunksNumber;
std::size_t _freeObjectNumber;
std::size_t _chunkAlignement;
std::size_t _objectAlignement;
bool _allocateChunk()
{
auto chunkSize = _getChunkSize();
auto newChunk = (Chunk*)(new unsigned char[chunkSize]);
if (!newChunk)
return false;
newChunk->emptySlotsNumber = _objectPerChunk;
newChunk->emptySlotsList.init();
_chunks.push_front(newChunk);
_freeObjectNumber += _objectPerChunk;
++_chunksNumber;
auto data = (unsigned char*)(newChunk + 1);
data += _chunkAlignement;
for (std::size_t i = 0; i < _objectPerChunk; ++i)
{
((ChunkHeader*)(data))->index = i;
data += sizeof(ChunkHeader);
newChunk->emptySlotsList.push((Link*)(data));
data += _objectSize + _objectAlignement;
}
return true;
}
bool _allocateObject(void *&addr)
{
if (_freeObjectNumber == 0)
{
auto noError = _allocateChunk();
assert(noError);
}
for (auto &e : _chunks)
{
if (e->emptySlotsNumber != 0)
{
auto ptr = e->emptySlotsList.pop();
--e->emptySlotsNumber;
--_freeObjectNumber;
addr = ptr;
return true;
}
}
return false;
}
bool _dealocateObject(void *addr)
{
auto data = (unsigned char *)(addr);
data -= sizeof(ChunkHeader);
auto chunk = (Chunk*)(data - (((ChunkHeader*)(data))->index * (sizeof(ChunkHeader) + _objectSize + _objectAlignement)) - _chunkAlignement) - 1;
++chunk->emptySlotsNumber;
chunk->emptySlotsList.push((Link*)(addr));
++_freeObjectNumber;
return false;
}
void _destroy()
{
//for (auto &e : _chunks)
//{
// delete[](unsigned char *)e;
//}
}
inline std::size_t _getChunkSize() const { return _chunkAlignement + sizeof(Chunk) + _objectPerChunk * (_objectSize + _objectAlignement + sizeof(ChunkHeader)); }
bool _init(std::size_t objectSize, std::size_t objectAlignment, std::size_t chunkSize /* object per chunk */)
{
_objectSize = sizeof(Link);
_objectPerChunk = chunkSize;
if (objectSize > _objectSize)
_objectSize = objectSize;
_objectAlignement = objectAlignment - ((sizeof(ChunkHeader) + _objectSize) % objectAlignment);
if (_objectAlignement == objectAlignment)
_objectAlignement = 0;
_chunkAlignement = objectAlignment - ((sizeof(ChunkHeader) + sizeof(Chunk)) % objectAlignment);
if (_chunkAlignement == objectAlignment)
_chunkAlignement = 0;
return true;
}
};
}<|endoftext|> |
<commit_before>//===--------------------------------------------------------------------------------*- C++ -*-===//
// _
// | |
// __| | __ ___ ___ ___
// / _` |/ _` \ \ /\ / / '_ |
// | (_| | (_| |\ V V /| | | |
// \__,_|\__,_| \_/\_/ |_| |_| - Compiler Toolchain
//
//
// This file is distributed under the MIT License (MIT).
// See LICENSE.txt for details.
//
//===------------------------------------------------------------------------------------------===//
#include "dawn/Compiler/DawnCompiler.h"
#include "dawn/Compiler/Options.h"
#include "dawn/IIR/StencilInstantiation.h"
#include "dawn/Serialization/IIRSerializer.h"
#include <cxxopts.hpp>
#include <fstream>
#include <memory>
enum class SerializationFormat { Byte, Json };
// toString is used because #DEFAULT_VALUE in the options does not work consistently for both string
// and non-string values
template <typename T>
std::string toString(const T& t) {
return std::to_string(t);
}
std::string toString(const char* t) { return t; }
std::string toString(const std::string& t) { return t; }
std::shared_ptr<dawn::iir::StencilInstantiation> deserializeInput(const std::string& input) {
std::shared_ptr<dawn::iir::StencilInstantiation> internalIR = nullptr;
SerializationFormat format = SerializationFormat::Byte;
{
try {
internalIR =
dawn::IIRSerializer::deserializeFromString(input, dawn::IIRSerializer::Format::Byte);
format = SerializationFormat::Byte;
} catch(...) {
// Do nothing
}
}
if(!internalIR) {
try {
internalIR =
dawn::IIRSerializer::deserializeFromString(input, dawn::IIRSerializer::Format::Json);
SerializationFormat::Json;
} catch(...) {
// Exhausted possibilities, so throw
throw std::runtime_error("Cannot deserialize input");
}
}
// Deserialize again, only this time do not catch exceptions
if(format == SerializationFormat::Byte) {
internalIR =
dawn::IIRSerializer::deserializeFromString(input, dawn::IIRSerializer::Format::Byte);
} else {
internalIR =
dawn::IIRSerializer::deserializeFromString(input, dawn::IIRSerializer::Format::Json);
}
return internalIR;
}
int main(int argc, char* argv[]) {
cxxopts::Options options("dawn-codegen", "Code generation for the Dawn DSL compiler toolchain");
options.positional_help("[IIR file. If unset, reads from stdin]");
// clang-format off
options.add_options()
("i,input", "Input IIR file. If unset, uses stdin.", cxxopts::value<std::string>())
("o,out", "Output filename. If unset, writes code to stdout.", cxxopts::value<std::string>())
("v,verbose", "Set verbosity level to info. If set, use -o or --out to redirect code to file.")
("b,backend", "Backend code generator: [gridtools|gt, c++-naive|naive, cxx-naive-ico|naive-ico, cuda, cxx-opt].",
cxxopts::value<std::string>()->default_value("c++-naive"))
("h,help", "Display usage.");
options.add_options("CodeGen")
#define OPT(TYPE, NAME, DEFAULT_VALUE, OPTION, OPTION_SHORT, HELP, VALUE_NAME, HAS_VALUE, F_GROUP) \
(OPTION, HELP, cxxopts::value<TYPE>()->default_value(toString(DEFAULT_VALUE)))
#include "dawn/CodeGen/Options.inc"
#undef OPT
;
// clang-format on
// This is how the positional argument is specified
options.parse_positional({"input"});
const int numArgs = argc;
auto result = options.parse(argc, argv);
if(result.count("help")) {
std::cout << options.help() << std::endl;
return 0;
}
// Get input = string
std::string input;
if(result.count("input") > 0) {
std::ifstream t(result["input"].as<std::string>());
input.insert(input.begin(), (std::istreambuf_iterator<char>(t)),
std::istreambuf_iterator<char>());
} else {
std::istreambuf_iterator<char> begin(std::cin), end;
input.insert(input.begin(), begin, end);
}
dawn::Options dawnOptions;
#define OPT(TYPE, NAME, DEFAULT_VALUE, OPTION, OPTION_SHORT, HELP, VALUE_NAME, HAS_VALUE, F_GROUP) \
dawnOptions.NAME = result[OPTION].as<TYPE>();
#include "dawn/CodeGen/Options.inc"
#undef OPT
dawnOptions.Backend = result["backend"].as<std::string>();
dawn::DawnCompiler compiler(dawnOptions);
auto internalIR = deserializeInput(input);
std::map<std::string, std::shared_ptr<dawn::iir::StencilInstantiation>> stencilInstantiationMap{
{"restoredIIR", internalIR}};
auto translationUnit = compiler.generate(stencilInstantiationMap);
std::string code;
for(auto p : translationUnit->getPPDefines())
code += p + "\n";
code += translationUnit->getGlobals() + "\n\n";
for(auto p : translationUnit->getStencils())
code += p.second;
if(result.count("out") > 0) {
std::ofstream out(result["out"].as<std::string>());
out << code << std::endl;
} else {
std::cout << code << std::endl;
}
return 0;
}
<commit_msg>Propogate fixes from dawn-opt to dawn-codegen (#873)<commit_after>//===--------------------------------------------------------------------------------*- C++ -*-===//
// _
// | |
// __| | __ ___ ___ ___
// / _` |/ _` \ \ /\ / / '_ |
// | (_| | (_| |\ V V /| | | |
// \__,_|\__,_| \_/\_/ |_| |_| - Compiler Toolchain
//
//
// This file is distributed under the MIT License (MIT).
// See LICENSE.txt for details.
//
//===------------------------------------------------------------------------------------------===//
#include "dawn/Compiler/DawnCompiler.h"
#include "dawn/Compiler/Options.h"
#include "dawn/IIR/StencilInstantiation.h"
#include "dawn/Serialization/IIRSerializer.h"
#include <cxxopts.hpp>
#include <fstream>
#include <memory>
enum class SerializationFormat { Byte, Json };
// toString is used because #DEFAULT_VALUE in the options does not work consistently for both string
// and non-string values
template <typename T>
std::string toString(const T& t) {
return std::to_string(t);
}
std::string toString(const char* t) { return t; }
std::string toString(const std::string& t) { return t; }
std::shared_ptr<dawn::iir::StencilInstantiation> deserializeInput(const std::string& input) {
std::shared_ptr<dawn::iir::StencilInstantiation> internalIR = nullptr;
SerializationFormat format = SerializationFormat::Byte;
{
try {
internalIR =
dawn::IIRSerializer::deserializeFromString(input, dawn::IIRSerializer::Format::Byte);
format = SerializationFormat::Byte;
} catch(...) {
internalIR = nullptr;
}
}
if(!internalIR) {
try {
internalIR =
dawn::IIRSerializer::deserializeFromString(input, dawn::IIRSerializer::Format::Json);
format = SerializationFormat::Json;
} catch(...) {
// Exhausted possibilities, so throw
throw std::runtime_error("Cannot deserialize input");
}
}
// Deserialize again, only this time do not catch exceptions
if(format == SerializationFormat::Byte) {
internalIR =
dawn::IIRSerializer::deserializeFromString(input, dawn::IIRSerializer::Format::Byte);
} else {
internalIR =
dawn::IIRSerializer::deserializeFromString(input, dawn::IIRSerializer::Format::Json);
}
return internalIR;
}
int main(int argc, char* argv[]) {
cxxopts::Options options("dawn-codegen", "Code generation for the Dawn DSL compiler toolchain");
options.positional_help("[IIR file. If unset, reads from stdin]");
// clang-format off
options.add_options()
("i,input", "Input IIR file. If unset, uses stdin.", cxxopts::value<std::string>())
("o,out", "Output filename. If unset, writes code to stdout.", cxxopts::value<std::string>())
("v,verbose", "Set verbosity level to info. If set, use -o or --out to redirect code to file.")
("b,backend", "Backend code generator: [gridtools|gt, c++-naive|naive, cxx-naive-ico|naive-ico, cuda, cxx-opt].",
cxxopts::value<std::string>()->default_value("c++-naive"))
("h,help", "Display usage.");
options.add_options("CodeGen")
#define OPT(TYPE, NAME, DEFAULT_VALUE, OPTION, OPTION_SHORT, HELP, VALUE_NAME, HAS_VALUE, F_GROUP) \
(OPTION, HELP, cxxopts::value<TYPE>()->default_value(toString(DEFAULT_VALUE)))
#include "dawn/CodeGen/Options.inc"
#undef OPT
;
// clang-format on
// This is how the positional argument is specified
options.parse_positional({"input"});
const int numArgs = argc;
auto result = options.parse(argc, argv);
if(result.count("help")) {
std::cout << options.help() << std::endl;
return 0;
}
// Get input = string
std::string input;
if(result.count("input") > 0) {
std::ifstream t(result["input"].as<std::string>());
input.insert(input.begin(), (std::istreambuf_iterator<char>(t)),
std::istreambuf_iterator<char>());
} else {
std::istreambuf_iterator<char> begin(std::cin), end;
input.insert(input.begin(), begin, end);
}
dawn::Options dawnOptions;
#define OPT(TYPE, NAME, DEFAULT_VALUE, OPTION, OPTION_SHORT, HELP, VALUE_NAME, HAS_VALUE, F_GROUP) \
dawnOptions.NAME = result[OPTION].as<TYPE>();
#include "dawn/CodeGen/Options.inc"
#undef OPT
dawnOptions.Backend = result["backend"].as<std::string>();
dawn::DawnCompiler compiler(dawnOptions);
auto internalIR = deserializeInput(input);
std::map<std::string, std::shared_ptr<dawn::iir::StencilInstantiation>> stencilInstantiationMap{
{"restoredIIR", internalIR}};
auto translationUnit = compiler.generate(stencilInstantiationMap);
std::string code;
for(auto p : translationUnit->getPPDefines())
code += p + "\n";
code += translationUnit->getGlobals() + "\n\n";
for(auto p : translationUnit->getStencils())
code += p.second;
if(result.count("out") > 0) {
std::ofstream out(result["out"].as<std::string>());
out << code << std::endl;
} else {
std::cout << code << std::endl;
}
return 0;
}
<|endoftext|> |
<commit_before>//=======================================================================
// Copyright (c) 2014-2016 Baptiste Wicht
// Distributed under the terms of the MIT License.
// (See accompanying file LICENSE or copy at
// http://opensource.org/licenses/MIT)
//=======================================================================
#pragma once
#include "etl/etl.hpp"
#include "dll/util/labels.hpp"
#include "dll/test.hpp"
#include "dll/dbn_traits.hpp"
namespace dll {
template <typename Iterator>
struct range {
private:
Iterator first;
Iterator last;
public:
range(Iterator first, Iterator last)
: first(first), last(last) {}
Iterator begin() const {
return first;
}
Iterator end() const {
return last;
}
};
template <typename Iterator>
range<Iterator> make_range(Iterator first, Iterator last) {
return {first, last};
}
/*!
* \brief A generic trainer for Deep Belief Network
*
* This trainer use the specified trainer of the DBN to perform supervised
* fine-tuning.
*/
template <typename DBN>
struct dbn_trainer {
using dbn_t = DBN;
using error_type = typename dbn_t::weight;
template <typename R>
using trainer_t = typename dbn_t::desc::template trainer_t<R>;
template <typename R>
using watcher_t = typename dbn_t::desc::template watcher_t<R>;
template <typename Iterator, typename LIterator>
error_type train(DBN& dbn, Iterator first, Iterator last, LIterator lfirst, LIterator llast, std::size_t max_epochs) const {
auto error_function = [&dbn, first, last, lfirst, llast]() {
return test_set(dbn, first, last, lfirst, llast,
[](dbn_t& dbn, auto& image) { return dbn.predict(image); });
};
auto label_transformer = [](auto first, auto last) {
return dll::make_fake(first, last);
};
return train_impl(dbn, first, last, lfirst, llast, max_epochs, error_function, label_transformer);
}
template <typename Iterator>
error_type train_ae(DBN& dbn, Iterator first, Iterator last, std::size_t max_epochs) const {
auto error_function = [&dbn, first, last]() {
return test_set_ae(dbn, first, last);
};
auto label_transformer = [](auto first, auto last) {
return make_range(first, last);
};
return train_impl(dbn, first, last, first, last, max_epochs, error_function, label_transformer);
}
template <typename Iterator, typename LIterator, typename Error, typename LabelTransformer>
error_type train_impl(DBN& dbn, Iterator first, Iterator last, LIterator lfirst, LIterator llast, std::size_t max_epochs, Error error_function, LabelTransformer label_transformer) const {
constexpr const auto batch_size = std::decay_t<DBN>::batch_size;
constexpr const auto big_batch_size = std::decay_t<DBN>::big_batch_size;
//Get types for the batch
using samples_t = std::vector<typename std::iterator_traits<Iterator>::value_type>;
using labels_t = std::vector<typename std::iterator_traits<LIterator>::value_type>;
//Initialize the momentum
dbn.momentum = dbn.initial_momentum;
//Initialize the watcher
watcher_t<dbn_t> watcher;
watcher.fine_tuning_begin(dbn);
auto trainer = std::make_unique<trainer_t<dbn_t>>(dbn);
//Initialize the trainer if necessary
trainer->init_training(batch_size);
error_type error = 0.0;
if (!dbn.batch_mode()) {
//Convert labels to an useful form
auto fake_labels = label_transformer(lfirst, llast);
//Make sure data is contiguous
samples_t data;
data.reserve(std::distance(first, last));
std::for_each(first, last, [&data](auto& sample) {
data.emplace_back(sample);
});
//Compute the number of batches
auto batches = data.size() / batch_size + (data.size() % batch_size == 0 ? 0 : 1);
//Train for max_epochs epoch
for (std::size_t epoch = 0; epoch < max_epochs; ++epoch) {
// Shuffle before the epoch if necessary
if(dbn_traits<dbn_t>::shuffle()){
static std::random_device rd;
static std::mt19937_64 g(rd());
std::shuffle(data.begin(), data.end(), g);
}
//Train one mini-batch at a time
for (std::size_t i = 0; i < batches; ++i) {
auto start = i * batch_size;
auto end = std::min(start + batch_size, data.size());
auto data_batch = make_batch(data.begin() + start, data.begin() + end);
auto label_batch = make_batch(fake_labels.begin() + start, fake_labels.begin() + end);
trainer->train_batch(epoch, data_batch, label_batch);
}
auto last_error = error;
error = error_function();
//After some time increase the momentum
if (dbn_traits<dbn_t>::has_momentum() && epoch == dbn.final_momentum_epoch) {
dbn.momentum = dbn.final_momentum;
}
watcher.ft_epoch_end(epoch, error, dbn);
//Once the goal is reached, stop training
if (error <= dbn.goal) {
break;
}
if (dbn_traits<dbn_t>::lr_driver() == lr_driver_type::BOLD) {
if (epoch) {
if (error > last_error + 1e-8) {
//Error increased
dbn.learning_rate *= dbn.lr_bold_dec;
watcher.lr_adapt(dbn);
dbn.restore_weights();
} else if (error < last_error - 1e-10) {
//Error decreased
dbn.learning_rate *= dbn.lr_bold_inc;
watcher.lr_adapt(dbn);
dbn.backup_weights();
} else {
//Error didn't change enough
dbn.backup_weights();
}
} else {
dbn.backup_weights();
}
}
if (dbn_traits<dbn_t>::lr_driver() == lr_driver_type::STEP) {
if (epoch && epoch % dbn.lr_step_size == 0) {
dbn.learning_rate *= dbn.lr_step_gamma;
watcher.lr_adapt(dbn);
}
}
}
} else {
auto total_batch_size = big_batch_size * batch_size;
//Prepare some space for converted data
samples_t input_cache(total_batch_size);
labels_t label_cache(total_batch_size);
//Train for max_epochs epoch
for (std::size_t epoch = 0; epoch < max_epochs; ++epoch) {
auto it = first;
auto lit = lfirst;
//Train all mini-batches
while (it != last) {
//Fill the input caches
std::size_t i = 0;
while (it != last && i < total_batch_size) {
input_cache[i] = *it++;
label_cache[i] = *lit++;
++i;
}
//Convert labels to an useful form
auto fake_labels = label_transformer(label_cache.begin(), label_cache.end());
auto full_batches = i / batch_size;
//Train all the full batches
for (std::size_t b = 0; b < full_batches; ++b) {
auto data_batch = make_batch(input_cache.begin() + b * batch_size, input_cache.begin() + (b + 1) * batch_size);
auto label_batch = make_batch(fake_labels.begin() + b * batch_size, fake_labels.begin() + (b + 1) * batch_size);
trainer->train_batch(epoch, data_batch, label_batch);
}
//Train the last incomplete batch, if any
if (i % batch_size > 0) {
auto data_batch = make_batch(input_cache.begin() + full_batches * batch_size, input_cache.begin() + i);
auto label_batch = make_batch(fake_labels.begin() + full_batches * batch_size, fake_labels.begin() + i);
trainer->train_batch(epoch, data_batch, label_batch);
}
}
error = error_function();
//After some time increase the momentum
if (dbn_traits<dbn_t>::has_momentum() && epoch == dbn.final_momentum_epoch) {
dbn.momentum = dbn.final_momentum;
}
watcher.ft_epoch_end(epoch, error, dbn);
//Once the goal is reached, stop training
if (error <= dbn.goal) {
break;
}
}
}
watcher.fine_tuning_end(dbn);
return error;
}
};
} //end of dll namespace
<commit_msg>Fix shuffle<commit_after>//=======================================================================
// Copyright (c) 2014-2016 Baptiste Wicht
// Distributed under the terms of the MIT License.
// (See accompanying file LICENSE or copy at
// http://opensource.org/licenses/MIT)
//=======================================================================
#pragma once
#include "etl/etl.hpp"
#include "dll/util/labels.hpp"
#include "dll/test.hpp"
#include "dll/dbn_traits.hpp"
namespace dll {
template <typename Iterator>
struct range {
private:
Iterator first;
Iterator last;
public:
range(Iterator first, Iterator last)
: first(first), last(last) {}
Iterator begin() const {
return first;
}
Iterator end() const {
return last;
}
};
template <typename Iterator>
range<Iterator> make_range(Iterator first, Iterator last) {
return {first, last};
}
/*!
* \brief A generic trainer for Deep Belief Network
*
* This trainer use the specified trainer of the DBN to perform supervised
* fine-tuning.
*/
template <typename DBN>
struct dbn_trainer {
using dbn_t = DBN;
using error_type = typename dbn_t::weight;
template <typename R>
using trainer_t = typename dbn_t::desc::template trainer_t<R>;
template <typename R>
using watcher_t = typename dbn_t::desc::template watcher_t<R>;
template <typename Iterator, typename LIterator>
error_type train(DBN& dbn, Iterator first, Iterator last, LIterator lfirst, LIterator llast, std::size_t max_epochs) const {
auto error_function = [&dbn, first, last, lfirst, llast]() {
return test_set(dbn, first, last, lfirst, llast,
[](dbn_t& dbn, auto& image) { return dbn.predict(image); });
};
auto label_transformer = [](auto first, auto last) {
return dll::make_fake(first, last);
};
return train_impl(dbn, first, last, lfirst, llast, max_epochs, error_function, label_transformer);
}
template <typename Iterator>
error_type train_ae(DBN& dbn, Iterator first, Iterator last, std::size_t max_epochs) const {
auto error_function = [&dbn, first, last]() {
return test_set_ae(dbn, first, last);
};
auto label_transformer = [](auto first, auto last) {
return make_range(first, last);
};
return train_impl(dbn, first, last, first, last, max_epochs, error_function, label_transformer);
}
template <typename Iterator, typename LIterator, typename Error, typename LabelTransformer>
error_type train_impl(DBN& dbn, Iterator first, Iterator last, LIterator lfirst, LIterator llast, std::size_t max_epochs, Error error_function, LabelTransformer label_transformer) const {
constexpr const auto batch_size = std::decay_t<DBN>::batch_size;
constexpr const auto big_batch_size = std::decay_t<DBN>::big_batch_size;
//Get types for the batch
using samples_t = std::vector<typename std::iterator_traits<Iterator>::value_type>;
using labels_t = std::vector<typename std::iterator_traits<LIterator>::value_type>;
//Initialize the momentum
dbn.momentum = dbn.initial_momentum;
//Initialize the watcher
watcher_t<dbn_t> watcher;
watcher.fine_tuning_begin(dbn);
auto trainer = std::make_unique<trainer_t<dbn_t>>(dbn);
//Initialize the trainer if necessary
trainer->init_training(batch_size);
error_type error = 0.0;
if (!dbn.batch_mode()) {
//Convert labels to an useful form
auto fake_labels = label_transformer(lfirst, llast);
//Make sure data is contiguous
samples_t data;
data.reserve(std::distance(first, last));
std::for_each(first, last, [&data](auto& sample) {
data.emplace_back(sample);
});
//Compute the number of batches
auto batches = data.size() / batch_size + (data.size() % batch_size == 0 ? 0 : 1);
//Train for max_epochs epoch
for (std::size_t epoch = 0; epoch < max_epochs; ++epoch) {
// Shuffle before the epoch if necessary
if(dbn_traits<dbn_t>::shuffle()){
static std::random_device rd;
static std::mt19937_64 g(rd());
cpp::parallel_shuffle(data.begin(), data.end(), fake_labels.begin(), fake_labels.end(), g);
}
//Train one mini-batch at a time
for (std::size_t i = 0; i < batches; ++i) {
auto start = i * batch_size;
auto end = std::min(start + batch_size, data.size());
auto data_batch = make_batch(data.begin() + start, data.begin() + end);
auto label_batch = make_batch(fake_labels.begin() + start, fake_labels.begin() + end);
trainer->train_batch(epoch, data_batch, label_batch);
}
auto last_error = error;
error = error_function();
//After some time increase the momentum
if (dbn_traits<dbn_t>::has_momentum() && epoch == dbn.final_momentum_epoch) {
dbn.momentum = dbn.final_momentum;
}
watcher.ft_epoch_end(epoch, error, dbn);
//Once the goal is reached, stop training
if (error <= dbn.goal) {
break;
}
if (dbn_traits<dbn_t>::lr_driver() == lr_driver_type::BOLD) {
if (epoch) {
if (error > last_error + 1e-8) {
//Error increased
dbn.learning_rate *= dbn.lr_bold_dec;
watcher.lr_adapt(dbn);
dbn.restore_weights();
} else if (error < last_error - 1e-10) {
//Error decreased
dbn.learning_rate *= dbn.lr_bold_inc;
watcher.lr_adapt(dbn);
dbn.backup_weights();
} else {
//Error didn't change enough
dbn.backup_weights();
}
} else {
dbn.backup_weights();
}
}
if (dbn_traits<dbn_t>::lr_driver() == lr_driver_type::STEP) {
if (epoch && epoch % dbn.lr_step_size == 0) {
dbn.learning_rate *= dbn.lr_step_gamma;
watcher.lr_adapt(dbn);
}
}
}
} else {
auto total_batch_size = big_batch_size * batch_size;
//Prepare some space for converted data
samples_t input_cache(total_batch_size);
labels_t label_cache(total_batch_size);
//Train for max_epochs epoch
for (std::size_t epoch = 0; epoch < max_epochs; ++epoch) {
auto it = first;
auto lit = lfirst;
//Train all mini-batches
while (it != last) {
//Fill the input caches
std::size_t i = 0;
while (it != last && i < total_batch_size) {
input_cache[i] = *it++;
label_cache[i] = *lit++;
++i;
}
//Convert labels to an useful form
auto fake_labels = label_transformer(label_cache.begin(), label_cache.end());
auto full_batches = i / batch_size;
//Train all the full batches
for (std::size_t b = 0; b < full_batches; ++b) {
auto data_batch = make_batch(input_cache.begin() + b * batch_size, input_cache.begin() + (b + 1) * batch_size);
auto label_batch = make_batch(fake_labels.begin() + b * batch_size, fake_labels.begin() + (b + 1) * batch_size);
trainer->train_batch(epoch, data_batch, label_batch);
}
//Train the last incomplete batch, if any
if (i % batch_size > 0) {
auto data_batch = make_batch(input_cache.begin() + full_batches * batch_size, input_cache.begin() + i);
auto label_batch = make_batch(fake_labels.begin() + full_batches * batch_size, fake_labels.begin() + i);
trainer->train_batch(epoch, data_batch, label_batch);
}
}
error = error_function();
//After some time increase the momentum
if (dbn_traits<dbn_t>::has_momentum() && epoch == dbn.final_momentum_epoch) {
dbn.momentum = dbn.final_momentum;
}
watcher.ft_epoch_end(epoch, error, dbn);
//Once the goal is reached, stop training
if (error <= dbn.goal) {
break;
}
}
}
watcher.fine_tuning_end(dbn);
return error;
}
};
} //end of dll namespace
<|endoftext|> |
<commit_before>//===--- CrossTranslationUnit.cpp - -----------------------------*- C++ -*-===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file implements the CrossTranslationUnit interface.
//
//===----------------------------------------------------------------------===//
#include "clang/CrossTU/CrossTranslationUnit.h"
#include "clang/AST/ASTImporter.h"
#include "clang/AST/Decl.h"
#include "clang/Basic/TargetInfo.h"
#include "clang/CrossTU/CrossTUDiagnostic.h"
#include "clang/Frontend/ASTUnit.h"
#include "clang/Frontend/CompilerInstance.h"
#include "clang/Frontend/FrontendDiagnostic.h"
#include "clang/Frontend/TextDiagnosticPrinter.h"
#include "clang/Index/USRGeneration.h"
#include "llvm/ADT/Triple.h"
#include "llvm/Support/ErrorHandling.h"
#include "llvm/Support/ManagedStatic.h"
#include "llvm/Support/Path.h"
#include "llvm/Support/raw_ostream.h"
#include <fstream>
#include <sstream>
namespace clang {
namespace cross_tu {
namespace {
// FIXME: This class is will be removed after the transition to llvm::Error.
class IndexErrorCategory : public std::error_category {
public:
const char *name() const noexcept override { return "clang.index"; }
std::string message(int Condition) const override {
switch (static_cast<index_error_code>(Condition)) {
case index_error_code::unspecified:
return "An unknown error has occurred.";
case index_error_code::missing_index_file:
return "The index file is missing.";
case index_error_code::invalid_index_format:
return "Invalid index file format.";
case index_error_code::multiple_definitions:
return "Multiple definitions in the index file.";
case index_error_code::missing_definition:
return "Missing definition from the index file.";
case index_error_code::failed_import:
return "Failed to import the definition.";
case index_error_code::failed_to_get_external_ast:
return "Failed to load external AST source.";
case index_error_code::failed_to_generate_usr:
return "Failed to generate USR.";
}
llvm_unreachable("Unrecognized index_error_code.");
}
};
static llvm::ManagedStatic<IndexErrorCategory> Category;
} // end anonymous namespace
char IndexError::ID;
void IndexError::log(raw_ostream &OS) const {
OS << Category->message(static_cast<int>(Code)) << '\n';
}
std::error_code IndexError::convertToErrorCode() const {
return std::error_code(static_cast<int>(Code), *Category);
}
llvm::Expected<llvm::StringMap<std::string>>
parseCrossTUIndex(StringRef IndexPath, StringRef CrossTUDir) {
std::ifstream ExternalFnMapFile(IndexPath);
if (!ExternalFnMapFile)
return llvm::make_error<IndexError>(index_error_code::missing_index_file,
IndexPath.str());
llvm::StringMap<std::string> Result;
std::string Line;
unsigned LineNo = 1;
while (std::getline(ExternalFnMapFile, Line)) {
const size_t Pos = Line.find(" ");
if (Pos > 0 && Pos != std::string::npos) {
StringRef LineRef{Line};
StringRef FunctionLookupName = LineRef.substr(0, Pos);
if (Result.count(FunctionLookupName))
return llvm::make_error<IndexError>(
index_error_code::multiple_definitions, IndexPath.str(), LineNo);
StringRef FileName = LineRef.substr(Pos + 1);
SmallString<256> FilePath = CrossTUDir;
if (llvm::sys::path::is_absolute(FileName))
FilePath = FileName;
else
llvm::sys::path::append(FilePath, FileName);
Result[FunctionLookupName] = FilePath.str().str();
} else
return llvm::make_error<IndexError>(
index_error_code::invalid_index_format, IndexPath.str(), LineNo);
LineNo++;
}
return Result;
}
std::string
createCrossTUIndexString(const llvm::StringMap<std::string> &Index) {
std::ostringstream Result;
for (const auto &E : Index)
Result << E.getKey().str() << " " << E.getValue() << '\n';
return Result.str();
}
CrossTranslationUnitContext::CrossTranslationUnitContext(CompilerInstance &CI)
: CI(CI), Context(CI.getASTContext()) {}
CrossTranslationUnitContext::~CrossTranslationUnitContext() {}
std::string CrossTranslationUnitContext::getLookupName(const NamedDecl *ND) {
SmallString<128> DeclUSR;
bool Ret = index::generateUSRForDecl(ND, DeclUSR);
assert(!Ret && "Unable to generate USR");
return DeclUSR.str();
}
/// Recursively visits the function decls of a DeclContext, and looks up a
/// function based on USRs.
const FunctionDecl *
CrossTranslationUnitContext::findFunctionInDeclContext(const DeclContext *DC,
StringRef LookupFnName) {
assert(DC && "Declaration Context must not be null");
for (const Decl *D : DC->decls()) {
const auto *SubDC = dyn_cast<DeclContext>(D);
if (SubDC)
if (const auto *FD = findFunctionInDeclContext(SubDC, LookupFnName))
return FD;
const auto *ND = dyn_cast<FunctionDecl>(D);
const FunctionDecl *ResultDecl;
if (!ND || !ND->hasBody(ResultDecl))
continue;
if (getLookupName(ResultDecl) != LookupFnName)
continue;
return ResultDecl;
}
return nullptr;
}
llvm::Expected<const FunctionDecl *>
CrossTranslationUnitContext::getCrossTUDefinition(const FunctionDecl *FD,
StringRef CrossTUDir,
StringRef IndexName) {
assert(!FD->hasBody() && "FD has a definition in current translation unit!");
const std::string LookupFnName = getLookupName(FD);
if (LookupFnName.empty())
return llvm::make_error<IndexError>(
index_error_code::failed_to_generate_usr);
llvm::Expected<ASTUnit *> ASTUnitOrError =
loadExternalAST(LookupFnName, CrossTUDir, IndexName);
if (!ASTUnitOrError)
return ASTUnitOrError.takeError();
ASTUnit *Unit = *ASTUnitOrError;
if (!Unit)
return llvm::make_error<IndexError>(
index_error_code::failed_to_get_external_ast);
assert(&Unit->getFileManager() ==
&Unit->getASTContext().getSourceManager().getFileManager());
TranslationUnitDecl *TU = Unit->getASTContext().getTranslationUnitDecl();
if (const FunctionDecl *ResultDecl =
findFunctionInDeclContext(TU, LookupFnName))
return importDefinition(ResultDecl);
return llvm::make_error<IndexError>(index_error_code::failed_import);
}
void CrossTranslationUnitContext::emitCrossTUDiagnostics(const IndexError &IE) {
switch (IE.getCode()) {
case index_error_code::missing_index_file:
Context.getDiagnostics().Report(diag::err_fe_error_opening)
<< IE.getFileName() << "required by the CrossTU functionality";
break;
case index_error_code::invalid_index_format:
Context.getDiagnostics().Report(diag::err_fnmap_parsing)
<< IE.getFileName() << IE.getLineNum();
case index_error_code::multiple_definitions:
Context.getDiagnostics().Report(diag::err_multiple_def_index)
<< IE.getLineNum();
break;
default:
break;
}
}
llvm::Expected<ASTUnit *> CrossTranslationUnitContext::loadExternalAST(
StringRef LookupName, StringRef CrossTUDir, StringRef IndexName) {
// FIXME: The current implementation only supports loading functions with
// a lookup name from a single translation unit. If multiple
// translation units contains functions with the same lookup name an
// error will be returned.
ASTUnit *Unit = nullptr;
auto FnUnitCacheEntry = FunctionASTUnitMap.find(LookupName);
if (FnUnitCacheEntry == FunctionASTUnitMap.end()) {
if (FunctionFileMap.empty()) {
SmallString<256> IndexFile = CrossTUDir;
if (llvm::sys::path::is_absolute(IndexName))
IndexFile = IndexName;
else
llvm::sys::path::append(IndexFile, IndexName);
llvm::Expected<llvm::StringMap<std::string>> IndexOrErr =
parseCrossTUIndex(IndexFile, CrossTUDir);
if (IndexOrErr)
FunctionFileMap = *IndexOrErr;
else
return IndexOrErr.takeError();
}
auto It = FunctionFileMap.find(LookupName);
if (It == FunctionFileMap.end())
return llvm::make_error<IndexError>(index_error_code::missing_definition);
StringRef ASTFileName = It->second;
auto ASTCacheEntry = FileASTUnitMap.find(ASTFileName);
if (ASTCacheEntry == FileASTUnitMap.end()) {
IntrusiveRefCntPtr<DiagnosticOptions> DiagOpts = new DiagnosticOptions();
TextDiagnosticPrinter *DiagClient =
new TextDiagnosticPrinter(llvm::errs(), &*DiagOpts);
IntrusiveRefCntPtr<DiagnosticIDs> DiagID(new DiagnosticIDs());
IntrusiveRefCntPtr<DiagnosticsEngine> Diags(
new DiagnosticsEngine(DiagID, &*DiagOpts, DiagClient));
std::unique_ptr<ASTUnit> LoadedUnit(ASTUnit::LoadFromASTFile(
ASTFileName, CI.getPCHContainerOperations()->getRawReader(),
ASTUnit::LoadEverything, Diags, CI.getFileSystemOpts()));
Unit = LoadedUnit.get();
FileASTUnitMap[ASTFileName] = std::move(LoadedUnit);
} else {
Unit = ASTCacheEntry->second.get();
}
FunctionASTUnitMap[LookupName] = Unit;
} else {
Unit = FnUnitCacheEntry->second;
}
return Unit;
}
llvm::Expected<const FunctionDecl *>
CrossTranslationUnitContext::importDefinition(const FunctionDecl *FD) {
ASTImporter &Importer = getOrCreateASTImporter(FD->getASTContext());
auto *ToDecl =
cast<FunctionDecl>(Importer.Import(const_cast<FunctionDecl *>(FD)));
assert(ToDecl->hasBody());
assert(FD->hasBody() && "Functions already imported should have body.");
return ToDecl;
}
ASTImporter &
CrossTranslationUnitContext::getOrCreateASTImporter(ASTContext &From) {
auto I = ASTUnitImporterMap.find(From.getTranslationUnitDecl());
if (I != ASTUnitImporterMap.end())
return *I->second;
ASTImporter *NewImporter =
new ASTImporter(Context, Context.getSourceManager().getFileManager(),
From, From.getSourceManager().getFileManager(), false);
ASTUnitImporterMap[From.getTranslationUnitDecl()].reset(NewImporter);
return *NewImporter;
}
} // namespace cross_tu
} // namespace clang
<commit_msg>Fix unused variable warning in non-debug builds.<commit_after>//===--- CrossTranslationUnit.cpp - -----------------------------*- C++ -*-===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file implements the CrossTranslationUnit interface.
//
//===----------------------------------------------------------------------===//
#include "clang/CrossTU/CrossTranslationUnit.h"
#include "clang/AST/ASTImporter.h"
#include "clang/AST/Decl.h"
#include "clang/Basic/TargetInfo.h"
#include "clang/CrossTU/CrossTUDiagnostic.h"
#include "clang/Frontend/ASTUnit.h"
#include "clang/Frontend/CompilerInstance.h"
#include "clang/Frontend/FrontendDiagnostic.h"
#include "clang/Frontend/TextDiagnosticPrinter.h"
#include "clang/Index/USRGeneration.h"
#include "llvm/ADT/Triple.h"
#include "llvm/Support/ErrorHandling.h"
#include "llvm/Support/ManagedStatic.h"
#include "llvm/Support/Path.h"
#include "llvm/Support/raw_ostream.h"
#include <fstream>
#include <sstream>
namespace clang {
namespace cross_tu {
namespace {
// FIXME: This class is will be removed after the transition to llvm::Error.
class IndexErrorCategory : public std::error_category {
public:
const char *name() const noexcept override { return "clang.index"; }
std::string message(int Condition) const override {
switch (static_cast<index_error_code>(Condition)) {
case index_error_code::unspecified:
return "An unknown error has occurred.";
case index_error_code::missing_index_file:
return "The index file is missing.";
case index_error_code::invalid_index_format:
return "Invalid index file format.";
case index_error_code::multiple_definitions:
return "Multiple definitions in the index file.";
case index_error_code::missing_definition:
return "Missing definition from the index file.";
case index_error_code::failed_import:
return "Failed to import the definition.";
case index_error_code::failed_to_get_external_ast:
return "Failed to load external AST source.";
case index_error_code::failed_to_generate_usr:
return "Failed to generate USR.";
}
llvm_unreachable("Unrecognized index_error_code.");
}
};
static llvm::ManagedStatic<IndexErrorCategory> Category;
} // end anonymous namespace
char IndexError::ID;
void IndexError::log(raw_ostream &OS) const {
OS << Category->message(static_cast<int>(Code)) << '\n';
}
std::error_code IndexError::convertToErrorCode() const {
return std::error_code(static_cast<int>(Code), *Category);
}
llvm::Expected<llvm::StringMap<std::string>>
parseCrossTUIndex(StringRef IndexPath, StringRef CrossTUDir) {
std::ifstream ExternalFnMapFile(IndexPath);
if (!ExternalFnMapFile)
return llvm::make_error<IndexError>(index_error_code::missing_index_file,
IndexPath.str());
llvm::StringMap<std::string> Result;
std::string Line;
unsigned LineNo = 1;
while (std::getline(ExternalFnMapFile, Line)) {
const size_t Pos = Line.find(" ");
if (Pos > 0 && Pos != std::string::npos) {
StringRef LineRef{Line};
StringRef FunctionLookupName = LineRef.substr(0, Pos);
if (Result.count(FunctionLookupName))
return llvm::make_error<IndexError>(
index_error_code::multiple_definitions, IndexPath.str(), LineNo);
StringRef FileName = LineRef.substr(Pos + 1);
SmallString<256> FilePath = CrossTUDir;
if (llvm::sys::path::is_absolute(FileName))
FilePath = FileName;
else
llvm::sys::path::append(FilePath, FileName);
Result[FunctionLookupName] = FilePath.str().str();
} else
return llvm::make_error<IndexError>(
index_error_code::invalid_index_format, IndexPath.str(), LineNo);
LineNo++;
}
return Result;
}
std::string
createCrossTUIndexString(const llvm::StringMap<std::string> &Index) {
std::ostringstream Result;
for (const auto &E : Index)
Result << E.getKey().str() << " " << E.getValue() << '\n';
return Result.str();
}
CrossTranslationUnitContext::CrossTranslationUnitContext(CompilerInstance &CI)
: CI(CI), Context(CI.getASTContext()) {}
CrossTranslationUnitContext::~CrossTranslationUnitContext() {}
std::string CrossTranslationUnitContext::getLookupName(const NamedDecl *ND) {
SmallString<128> DeclUSR;
bool Ret = index::generateUSRForDecl(ND, DeclUSR); (void)Ret;
assert(!Ret && "Unable to generate USR");
return DeclUSR.str();
}
/// Recursively visits the function decls of a DeclContext, and looks up a
/// function based on USRs.
const FunctionDecl *
CrossTranslationUnitContext::findFunctionInDeclContext(const DeclContext *DC,
StringRef LookupFnName) {
assert(DC && "Declaration Context must not be null");
for (const Decl *D : DC->decls()) {
const auto *SubDC = dyn_cast<DeclContext>(D);
if (SubDC)
if (const auto *FD = findFunctionInDeclContext(SubDC, LookupFnName))
return FD;
const auto *ND = dyn_cast<FunctionDecl>(D);
const FunctionDecl *ResultDecl;
if (!ND || !ND->hasBody(ResultDecl))
continue;
if (getLookupName(ResultDecl) != LookupFnName)
continue;
return ResultDecl;
}
return nullptr;
}
llvm::Expected<const FunctionDecl *>
CrossTranslationUnitContext::getCrossTUDefinition(const FunctionDecl *FD,
StringRef CrossTUDir,
StringRef IndexName) {
assert(!FD->hasBody() && "FD has a definition in current translation unit!");
const std::string LookupFnName = getLookupName(FD);
if (LookupFnName.empty())
return llvm::make_error<IndexError>(
index_error_code::failed_to_generate_usr);
llvm::Expected<ASTUnit *> ASTUnitOrError =
loadExternalAST(LookupFnName, CrossTUDir, IndexName);
if (!ASTUnitOrError)
return ASTUnitOrError.takeError();
ASTUnit *Unit = *ASTUnitOrError;
if (!Unit)
return llvm::make_error<IndexError>(
index_error_code::failed_to_get_external_ast);
assert(&Unit->getFileManager() ==
&Unit->getASTContext().getSourceManager().getFileManager());
TranslationUnitDecl *TU = Unit->getASTContext().getTranslationUnitDecl();
if (const FunctionDecl *ResultDecl =
findFunctionInDeclContext(TU, LookupFnName))
return importDefinition(ResultDecl);
return llvm::make_error<IndexError>(index_error_code::failed_import);
}
void CrossTranslationUnitContext::emitCrossTUDiagnostics(const IndexError &IE) {
switch (IE.getCode()) {
case index_error_code::missing_index_file:
Context.getDiagnostics().Report(diag::err_fe_error_opening)
<< IE.getFileName() << "required by the CrossTU functionality";
break;
case index_error_code::invalid_index_format:
Context.getDiagnostics().Report(diag::err_fnmap_parsing)
<< IE.getFileName() << IE.getLineNum();
case index_error_code::multiple_definitions:
Context.getDiagnostics().Report(diag::err_multiple_def_index)
<< IE.getLineNum();
break;
default:
break;
}
}
llvm::Expected<ASTUnit *> CrossTranslationUnitContext::loadExternalAST(
StringRef LookupName, StringRef CrossTUDir, StringRef IndexName) {
// FIXME: The current implementation only supports loading functions with
// a lookup name from a single translation unit. If multiple
// translation units contains functions with the same lookup name an
// error will be returned.
ASTUnit *Unit = nullptr;
auto FnUnitCacheEntry = FunctionASTUnitMap.find(LookupName);
if (FnUnitCacheEntry == FunctionASTUnitMap.end()) {
if (FunctionFileMap.empty()) {
SmallString<256> IndexFile = CrossTUDir;
if (llvm::sys::path::is_absolute(IndexName))
IndexFile = IndexName;
else
llvm::sys::path::append(IndexFile, IndexName);
llvm::Expected<llvm::StringMap<std::string>> IndexOrErr =
parseCrossTUIndex(IndexFile, CrossTUDir);
if (IndexOrErr)
FunctionFileMap = *IndexOrErr;
else
return IndexOrErr.takeError();
}
auto It = FunctionFileMap.find(LookupName);
if (It == FunctionFileMap.end())
return llvm::make_error<IndexError>(index_error_code::missing_definition);
StringRef ASTFileName = It->second;
auto ASTCacheEntry = FileASTUnitMap.find(ASTFileName);
if (ASTCacheEntry == FileASTUnitMap.end()) {
IntrusiveRefCntPtr<DiagnosticOptions> DiagOpts = new DiagnosticOptions();
TextDiagnosticPrinter *DiagClient =
new TextDiagnosticPrinter(llvm::errs(), &*DiagOpts);
IntrusiveRefCntPtr<DiagnosticIDs> DiagID(new DiagnosticIDs());
IntrusiveRefCntPtr<DiagnosticsEngine> Diags(
new DiagnosticsEngine(DiagID, &*DiagOpts, DiagClient));
std::unique_ptr<ASTUnit> LoadedUnit(ASTUnit::LoadFromASTFile(
ASTFileName, CI.getPCHContainerOperations()->getRawReader(),
ASTUnit::LoadEverything, Diags, CI.getFileSystemOpts()));
Unit = LoadedUnit.get();
FileASTUnitMap[ASTFileName] = std::move(LoadedUnit);
} else {
Unit = ASTCacheEntry->second.get();
}
FunctionASTUnitMap[LookupName] = Unit;
} else {
Unit = FnUnitCacheEntry->second;
}
return Unit;
}
llvm::Expected<const FunctionDecl *>
CrossTranslationUnitContext::importDefinition(const FunctionDecl *FD) {
ASTImporter &Importer = getOrCreateASTImporter(FD->getASTContext());
auto *ToDecl =
cast<FunctionDecl>(Importer.Import(const_cast<FunctionDecl *>(FD)));
assert(ToDecl->hasBody());
assert(FD->hasBody() && "Functions already imported should have body.");
return ToDecl;
}
ASTImporter &
CrossTranslationUnitContext::getOrCreateASTImporter(ASTContext &From) {
auto I = ASTUnitImporterMap.find(From.getTranslationUnitDecl());
if (I != ASTUnitImporterMap.end())
return *I->second;
ASTImporter *NewImporter =
new ASTImporter(Context, Context.getSourceManager().getFileManager(),
From, From.getSourceManager().getFileManager(), false);
ASTUnitImporterMap[From.getTranslationUnitDecl()].reset(NewImporter);
return *NewImporter;
}
} // namespace cross_tu
} // namespace clang
<|endoftext|> |
<commit_before>//
// Copyright (c) 2014 CNRS
// Authors: Florent Lamiraux
//
// This file is part of hpp-core
// hpp-core 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
// 3 of the License, or (at your option) any later version.
//
// hpp-core 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
// General Lesser Public License for more details. You should have
// received a copy of the GNU Lesser General Public License along with
// hpp-core If not, see
// <http://www.gnu.org/licenses/>.
#ifndef HPP_CORE_RANDOM_SHORTCUT_HH
# define HPP_CORE_RANDOM_SHORTCUT_HH
# warning "This file is deprecated. Include <hpp/constraints/explicit.hh> instead."
# include <hpp/core/path-optimization/random-shortcut.hh>
# include <hpp/core/deprecated.hh>
namespace hpp {
namespace core {
typedef HPP_CORE_DEPRECATED pathOptimization::RandomShortcut RandomShortcut ;
typedef HPP_CORE_DEPRECATED pathOptimization::RandomShortcutPtr_t RandomShortcutPtr_t;
} // namespace core
} // namespace hpp
#endif // HPP_CORE_RANDOM_SHORTCUT_HH
<commit_msg>Fix warning message in deprecated header.<commit_after>//
// Copyright (c) 2014 CNRS
// Authors: Florent Lamiraux
//
// This file is part of hpp-core
// hpp-core 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
// 3 of the License, or (at your option) any later version.
//
// hpp-core 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
// General Lesser Public License for more details. You should have
// received a copy of the GNU Lesser General Public License along with
// hpp-core If not, see
// <http://www.gnu.org/licenses/>.
#ifndef HPP_CORE_RANDOM_SHORTCUT_HH
# define HPP_CORE_RANDOM_SHORTCUT_HH
# warning "This file is deprecated. Include <hpp/core/path-optimization/random-shortcut.hh> instead."
# include <hpp/core/path-optimization/random-shortcut.hh>
# include <hpp/core/deprecated.hh>
namespace hpp {
namespace core {
typedef HPP_CORE_DEPRECATED pathOptimization::RandomShortcut RandomShortcut ;
typedef HPP_CORE_DEPRECATED pathOptimization::RandomShortcutPtr_t RandomShortcutPtr_t;
} // namespace core
} // namespace hpp
#endif // HPP_CORE_RANDOM_SHORTCUT_HH
<|endoftext|> |
<commit_before>//
// Copyright (c) 2014 CNRS
// Authors: Florent Lamiraux
//
// This file is part of hpp-core
// hpp-core 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
// 3 of the License, or (at your option) any later version.
//
// hpp-core 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
// General Lesser Public License for more details. You should have
// received a copy of the GNU Lesser General Public License along with
// hpp-core If not, see
// <http://www.gnu.org/licenses/>.
#ifndef HPP_CORE_STEERING_METHOD_HH
# define HPP_CORE_STEERING_METHOD_HH
# include <hpp/util/debug.hh>
# include <hpp/core/fwd.hh>
# include <hpp/core/path.hh>
# include <hpp/core/projection-error.hh>
namespace hpp {
namespace core {
/// \addtogroup steering_method
/// \{
/// Steering method
///
/// A steering method creates paths between pairs of
/// configurations for a robot. They are usually used to take
/// into account nonholonomic constraints of some robots
class HPP_CORE_DLLAPI SteeringMethod
{
public:
/// create a path between two configurations
/// \return a Path from q1 to q2 if found. An empty
/// Path if Path could not be built.
PathPtr_t operator() (ConfigurationIn_t q1,
ConfigurationIn_t q2) const
{
try {
return impl_compute (q1, q2);
} catch (const projection_error& e) {
hppDout (info, "Could not build path: " << e.what());
}
return PathPtr_t ();
}
/// Copy instance and return shared pointer
virtual SteeringMethodPtr_t copy () const = 0;
/// \name Constraints applicable to the robot.
/// These constraints are not automatically taken into
/// account. Child class can use it if they need.
/// \{
/// Set constraint set
void constraints (const ConstraintSetPtr_t& constraints)
{
constraints_ = constraints;
}
/// Get constraint set
const ConstraintSetPtr_t& constraints () const
{
return constraints_;
}
/// \}
protected:
/// Constructor
SteeringMethod (ProblemPtr_t problem) :
problem_ (problem), constraints_ (), weak_ ()
{
}
/// Copy constructor
///
/// Constraints are copied
SteeringMethod (const SteeringMethod& other) :
problem_ (other.problem_), constraints_ (), weak_ ()
{
if (other.constraints_) {
constraints_ = HPP_DYNAMIC_PTR_CAST (ConstraintSet,
other.constraints_->copy ());
}
}
/// create a path between two configurations
virtual PathPtr_t impl_compute (ConfigurationIn_t q1,
ConfigurationIn_t q2) const = 0;
/// Store weak pointer to itself.
void init (SteeringMethodWkPtr_t weak)
{
weak_ = weak;
}
ProblemPtr_t problem_;
private:
/// Set of constraints to apply on the paths produced
ConstraintSetPtr_t constraints_;
/// Weak pointer to itself
SteeringMethodWkPtr_t weak_;
}; // class SteeringMethod
/// \}
} // namespace core
} // namespace hpp
#endif // HPP_CORE_STEERING_METHOD_HH
<commit_msg>Add accessor to the SteeringMethod::problem_<commit_after>//
// Copyright (c) 2014 CNRS
// Authors: Florent Lamiraux
//
// This file is part of hpp-core
// hpp-core 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
// 3 of the License, or (at your option) any later version.
//
// hpp-core 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
// General Lesser Public License for more details. You should have
// received a copy of the GNU Lesser General Public License along with
// hpp-core If not, see
// <http://www.gnu.org/licenses/>.
#ifndef HPP_CORE_STEERING_METHOD_HH
# define HPP_CORE_STEERING_METHOD_HH
# include <hpp/util/debug.hh>
# include <hpp/core/fwd.hh>
# include <hpp/core/path.hh>
# include <hpp/core/projection-error.hh>
namespace hpp {
namespace core {
/// \addtogroup steering_method
/// \{
/// Steering method
///
/// A steering method creates paths between pairs of
/// configurations for a robot. They are usually used to take
/// into account nonholonomic constraints of some robots
class HPP_CORE_DLLAPI SteeringMethod
{
public:
/// create a path between two configurations
/// \return a Path from q1 to q2 if found. An empty
/// Path if Path could not be built.
PathPtr_t operator() (ConfigurationIn_t q1,
ConfigurationIn_t q2) const
{
try {
return impl_compute (q1, q2);
} catch (const projection_error& e) {
hppDout (info, "Could not build path: " << e.what());
}
return PathPtr_t ();
}
/// Copy instance and return shared pointer
virtual SteeringMethodPtr_t copy () const = 0;
const ProblemPtr_t& problem() const
{
return problem_;
}
/// \name Constraints applicable to the robot.
/// These constraints are not automatically taken into
/// account. Child class can use it if they need.
/// \{
/// Set constraint set
void constraints (const ConstraintSetPtr_t& constraints)
{
constraints_ = constraints;
}
/// Get constraint set
const ConstraintSetPtr_t& constraints () const
{
return constraints_;
}
/// \}
protected:
/// Constructor
SteeringMethod (ProblemPtr_t problem) :
problem_ (problem), constraints_ (), weak_ ()
{
}
/// Copy constructor
///
/// Constraints are copied
SteeringMethod (const SteeringMethod& other) :
problem_ (other.problem_), constraints_ (), weak_ ()
{
if (other.constraints_) {
constraints_ = HPP_DYNAMIC_PTR_CAST (ConstraintSet,
other.constraints_->copy ());
}
}
/// create a path between two configurations
virtual PathPtr_t impl_compute (ConfigurationIn_t q1,
ConfigurationIn_t q2) const = 0;
/// Store weak pointer to itself.
void init (SteeringMethodWkPtr_t weak)
{
weak_ = weak;
}
ProblemPtr_t problem_;
private:
/// Set of constraints to apply on the paths produced
ConstraintSetPtr_t constraints_;
/// Weak pointer to itself
SteeringMethodWkPtr_t weak_;
}; // class SteeringMethod
/// \}
} // namespace core
} // namespace hpp
#endif // HPP_CORE_STEERING_METHOD_HH
<|endoftext|> |
<commit_before>/*=========================================================================
*
* Copyright Bradley Lowekamp
*
* 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.txt
*
* 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 __itkBinShrinkImageFilter_hxx
#define __itkBinShrinkImageFilter_hxx
#include "itkBinShrinkImageFilter.h"
#include "itkImageScanlineIterator.h"
#include "itkProgressReporter.h"
#include <numeric>
namespace itk
{
/**
*
*/
template< class TInputImage, class TOutputImage >
BinShrinkImageFilter< TInputImage, TOutputImage >
::BinShrinkImageFilter()
{
for ( unsigned int j = 0; j < ImageDimension; j++ )
{
m_ShrinkFactors[j] = 1;
}
}
/**
*
*/
template< class TInputImage, class TOutputImage >
void
BinShrinkImageFilter< TInputImage, TOutputImage >
::PrintSelf(std::ostream & os, Indent indent) const
{
Superclass::PrintSelf(os, indent);
os << indent << "Shrink Factor: ";
for ( unsigned int j = 0; j < ImageDimension; j++ )
{
os << m_ShrinkFactors[j] << " ";
}
os << std::endl;
}
/**
*
*/
template< class TInputImage, class TOutputImage >
void
BinShrinkImageFilter< TInputImage, TOutputImage >
::SetShrinkFactors(unsigned int factor)
{
unsigned int j;
for ( j = 0; j < ImageDimension; j++ )
{
if ( factor != m_ShrinkFactors[j] ) { break; }
}
if ( j < ImageDimension )
{
this->Modified();
for ( j = 0; j < ImageDimension; j++ )
{
m_ShrinkFactors[j] = factor;
if ( m_ShrinkFactors[j] < 1 )
{
m_ShrinkFactors[j] = 1;
}
}
}
}
template< class TInputImage, class TOutputImage >
void
BinShrinkImageFilter< TInputImage, TOutputImage >
::SetShrinkFactor(unsigned int i, unsigned int factor)
{
if ( m_ShrinkFactors[i] == factor )
{
return;
}
this->Modified();
m_ShrinkFactors[i] = factor;
}
/**
*
*/
template <class TInputImage, class TOutputImage>
void
BinShrinkImageFilter<TInputImage,TOutputImage>
::ThreadedGenerateData(const OutputImageRegionType& outputRegionForThread,
ThreadIdType threadId)
{
itkDebugMacro(<<"Actually executing on region:" << outputRegionForThread);
// Get the input and output pointers
InputImageConstPointer inputPtr = this->GetInput();
OutputImagePointer outputPtr = this->GetOutput();
typedef typename NumericTraits<typename TInputImage::PixelType>::RealType AccumulatePixelType;
typedef typename TOutputImage::PixelType OutputPixelType;
typedef ImageScanlineConstIterator< TOutputImage > InputConstIteratorType;
typedef ImageScanlineIterator< TOutputImage > OutputIteratorType;
InputConstIteratorType inputIterator(inputPtr, inputPtr->GetRequestedRegion());
OutputIteratorType outputIterator(outputPtr, outputRegionForThread);
// allocate acumulate line
const size_t ln = outputRegionForThread.GetSize(0);
AccumulatePixelType *accBuffer = 0;
accBuffer = new AccumulatePixelType[ln];
// Set up shaped neighbor hood by defining the offsets
OutputOffsetType negativeOffset, positiveOffset, iOffset;
typedef typename OutputOffsetType::OffsetValueType OffsetValueType;
negativeOffset[0] = 0;
positiveOffset[0] = 0;
for ( unsigned int i=1; i < TInputImage::ImageDimension; ++i)
{
negativeOffset[i] = 0;
positiveOffset[i] = this->GetShrinkFactors()[i]-1;
}
std::vector<OutputOffsetType> offsets;
iOffset = negativeOffset;
while (iOffset[TInputImage::ImageDimension-1] <= positiveOffset[TInputImage::ImageDimension-1])
{
offsets.push_back(iOffset);
++iOffset[0];
for (unsigned int i=0; i < TInputImage::ImageDimension - 1; ++i)
{
if (iOffset[i] > positiveOffset[i])
{
iOffset[i] = negativeOffset[i];
++iOffset[i+1];
}
}
}
// convert the shrink factor for convenient multiplication
typename TOutputImage::SizeType factorSize;
for (unsigned int i=0; i < TInputImage::ImageDimension; ++i)
{
factorSize[i] = this->GetShrinkFactors()[i];
}
const size_t numSamples = std::accumulate( this->GetShrinkFactors().Begin(), this->GetShrinkFactors().End(), 1u, std::multiplies<size_t>() );
const double inumSamples = 1.0 / (double)numSamples;
const unsigned int numberOfLinesToProcess = outputRegionForThread.GetNumberOfPixels() / outputRegionForThread.GetSize(0);
ProgressReporter progress(this, threadId, numberOfLinesToProcess );
while ( !outputIterator.IsAtEnd() )
{
const OutputIndexType outputIndex = outputIterator.GetIndex();
typename std::vector<OutputOffsetType>::const_iterator offset = offsets.begin();
const InputIndexType startInputIndex = outputIndex * factorSize;
inputIterator.SetIndex( startInputIndex+*offset );
for( size_t i = 0; i < ln; ++i )
{
accBuffer[i] = inputIterator.Get();
++inputIterator;
for (size_t j = 1; j < factorSize[0]; ++j)
{
assert( !inputIterator.IsAtEndOfLine() );
accBuffer[i] += inputIterator.Get();
++inputIterator;
}
}
while ( ++offset != offsets.end() )
{
inputIterator.SetIndex( startInputIndex+*offset );
// Note: If the output image is small then we might not split
// the fastest direction. So we may not actually be at the start
// of the line...
//inputIterator.GoToBeginOfLine();
for( size_t i = 0; i < ln; ++i )
{
for( size_t j = 0; j < factorSize[0]; ++j)
{
assert( !inputIterator.IsAtEndOfLine() );
accBuffer[i] += inputIterator.Get();
++inputIterator;
}
}
}
for ( size_t j = 0; j <ln;++j)
{
assert(!outputIterator.IsAtEndOfLine());
// this statement is made to work with RGB pixel types
accBuffer[j] = accBuffer[j] * inumSamples;
outputIterator.Set( static_cast<OutputPixelType>(accBuffer[j]) );
++outputIterator;
}
outputIterator.NextLine();
// Although the method name is CompletedPixel(),
// this is being called after each line is processed
progress.CompletedPixel();
}
}
/**
*
*/
template <class TInputImage, class TOutputImage>
void
BinShrinkImageFilter<TInputImage,TOutputImage>
::GenerateInputRequestedRegion()
{
// call the superclass' implementation of this method
Superclass::GenerateInputRequestedRegion();
// get pointers to the input and output
InputImagePointer inputPtr = const_cast<TInputImage *> (this->GetInput());
OutputImagePointer outputPtr = this->GetOutput();
// Compute the input requested region (size and start index)
// Use the image transformations to insure an input requested region
// that will provide the proper range
const typename TOutputImage::SizeType& outputRequestedRegionSize = outputPtr->GetRequestedRegion().GetSize();
const typename TOutputImage::IndexType& outputRequestedRegionStartIndex = outputPtr->GetRequestedRegion().GetIndex();
typename TInputImage::IndexType inputIndex0;
typename TInputImage::SizeType inputSize;
for ( unsigned int i=0; i < TInputImage::ImageDimension; ++i)
{
inputIndex0[i] = outputRequestedRegionStartIndex[i]*m_ShrinkFactors[i];
inputSize[i] = outputRequestedRegionSize[i]*m_ShrinkFactors[i];
}
typename TInputImage::RegionType inputRequestedRegion;
inputRequestedRegion.SetIndex( inputIndex0 );
inputRequestedRegion.SetSize( inputSize );
// actually if we need to crop an exceptions should be thrown!
//inputRequestedRegion.Crop( inputPtr->GetLargestPossibleRegion() );
if ( !inputPtr->GetLargestPossibleRegion().IsInside( inputRequestedRegion.GetIndex() ) ||
!inputPtr->GetLargestPossibleRegion().IsInside( inputRequestedRegion.GetUpperIndex() ) )
{
itkExceptionMacro( "Unexpected error calculating RR");
}
itkDebugMacro( "InputRequestedRegion: " << inputRequestedRegion );
inputPtr->SetRequestedRegion( inputRequestedRegion );
}
template <class TInputImage, class TOutputImage>
void
BinShrinkImageFilter<TInputImage,TOutputImage>
::GenerateOutputInformation()
{
// Call the superclass' implementation of this method
Superclass::GenerateOutputInformation();
// Get pointers to the input and output
InputImageConstPointer inputPtr = this->GetInput();
OutputImagePointer outputPtr = this->GetOutput();
if ( !inputPtr || !outputPtr )
{
return;
}
// Compute the output spacing, the output image size, and the
// output image start index
const typename TInputImage::SpacingType & inputSpacing = inputPtr->GetSpacing();
const typename TInputImage::SizeType & inputSize = inputPtr->GetLargestPossibleRegion().GetSize();
const typename TInputImage::IndexType & inputStartIndex = inputPtr->GetLargestPossibleRegion().GetIndex();
ContinuousIndex<double,ImageDimension> inputIndexOutputOrigin;
typename TOutputImage::SpacingType outputSpacing(inputSpacing);
typename TOutputImage::SizeType outputSize;
typename TOutputImage::PointType outputOrigin;
typename TOutputImage::IndexType outputStartIndex;
for ( unsigned int i = 0; i < TOutputImage::ImageDimension; i++ )
{
outputSpacing[i] *= m_ShrinkFactors[i];
inputIndexOutputOrigin[i] = 0.5*(m_ShrinkFactors[i]-1);
outputStartIndex[i] = Math::Ceil<SizeValueType>(inputStartIndex[i]/static_cast<double>( m_ShrinkFactors[i]) );
// Round down so that all output pixels fit input input region
outputSize[i] = Math::Floor<SizeValueType>((double)(inputSize[i] - outputStartIndex[i]*m_ShrinkFactors[i]+inputStartIndex[i])
/ (double)m_ShrinkFactors[i]);
if ( outputSize[i] < 1 )
{
itkExceptionMacro("InputImage is too small! An output pixel does not map to a whole input bin.");
}
}
inputPtr->TransformContinuousIndexToPhysicalPoint(inputIndexOutputOrigin, outputOrigin);
outputPtr->SetSpacing(outputSpacing);
outputPtr->SetOrigin(outputOrigin);
// Set region
typename TOutputImage::RegionType outputLargestPossibleRegion;
outputLargestPossibleRegion.SetSize(outputSize);
outputLargestPossibleRegion.SetIndex(outputStartIndex);
outputPtr->SetLargestPossibleRegion(outputLargestPossibleRegion);
}
} // end namespace itk
#endif
<commit_msg>BUG: fix memory leak of accbuffer<commit_after>/*=========================================================================
*
* Copyright Bradley Lowekamp
*
* 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.txt
*
* 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 __itkBinShrinkImageFilter_hxx
#define __itkBinShrinkImageFilter_hxx
#include "itkBinShrinkImageFilter.h"
#include "itkImageScanlineIterator.h"
#include "itkProgressReporter.h"
#include <numeric>
namespace itk
{
/**
*
*/
template< class TInputImage, class TOutputImage >
BinShrinkImageFilter< TInputImage, TOutputImage >
::BinShrinkImageFilter()
{
for ( unsigned int j = 0; j < ImageDimension; j++ )
{
m_ShrinkFactors[j] = 1;
}
}
/**
*
*/
template< class TInputImage, class TOutputImage >
void
BinShrinkImageFilter< TInputImage, TOutputImage >
::PrintSelf(std::ostream & os, Indent indent) const
{
Superclass::PrintSelf(os, indent);
os << indent << "Shrink Factor: ";
for ( unsigned int j = 0; j < ImageDimension; j++ )
{
os << m_ShrinkFactors[j] << " ";
}
os << std::endl;
}
/**
*
*/
template< class TInputImage, class TOutputImage >
void
BinShrinkImageFilter< TInputImage, TOutputImage >
::SetShrinkFactors(unsigned int factor)
{
unsigned int j;
for ( j = 0; j < ImageDimension; j++ )
{
if ( factor != m_ShrinkFactors[j] ) { break; }
}
if ( j < ImageDimension )
{
this->Modified();
for ( j = 0; j < ImageDimension; j++ )
{
m_ShrinkFactors[j] = factor;
if ( m_ShrinkFactors[j] < 1 )
{
m_ShrinkFactors[j] = 1;
}
}
}
}
template< class TInputImage, class TOutputImage >
void
BinShrinkImageFilter< TInputImage, TOutputImage >
::SetShrinkFactor(unsigned int i, unsigned int factor)
{
if ( m_ShrinkFactors[i] == factor )
{
return;
}
this->Modified();
m_ShrinkFactors[i] = factor;
}
/**
*
*/
template <class TInputImage, class TOutputImage>
void
BinShrinkImageFilter<TInputImage,TOutputImage>
::ThreadedGenerateData(const OutputImageRegionType& outputRegionForThread,
ThreadIdType threadId)
{
itkDebugMacro(<<"Actually executing on region:" << outputRegionForThread);
// Get the input and output pointers
InputImageConstPointer inputPtr = this->GetInput();
OutputImagePointer outputPtr = this->GetOutput();
typedef typename NumericTraits<typename TInputImage::PixelType>::RealType AccumulatePixelType;
typedef typename TOutputImage::PixelType OutputPixelType;
typedef ImageScanlineConstIterator< TOutputImage > InputConstIteratorType;
typedef ImageScanlineIterator< TOutputImage > OutputIteratorType;
InputConstIteratorType inputIterator(inputPtr, inputPtr->GetRequestedRegion());
OutputIteratorType outputIterator(outputPtr, outputRegionForThread);
// Set up shaped neighbor hood by defining the offsets
OutputOffsetType negativeOffset, positiveOffset, iOffset;
typedef typename OutputOffsetType::OffsetValueType OffsetValueType;
negativeOffset[0] = 0;
positiveOffset[0] = 0;
for ( unsigned int i=1; i < TInputImage::ImageDimension; ++i)
{
negativeOffset[i] = 0;
positiveOffset[i] = this->GetShrinkFactors()[i]-1;
}
std::vector<OutputOffsetType> offsets;
iOffset = negativeOffset;
while (iOffset[TInputImage::ImageDimension-1] <= positiveOffset[TInputImage::ImageDimension-1])
{
offsets.push_back(iOffset);
++iOffset[0];
for (unsigned int i=0; i < TInputImage::ImageDimension - 1; ++i)
{
if (iOffset[i] > positiveOffset[i])
{
iOffset[i] = negativeOffset[i];
++iOffset[i+1];
}
}
}
// allocate acumulate line
const size_t ln = outputRegionForThread.GetSize(0);
AccumulatePixelType *accBuffer = 0;
accBuffer = new AccumulatePixelType[ln];
try
{
// convert the shrink factor for convenient multiplication
typename TOutputImage::SizeType factorSize;
for (unsigned int i=0; i < TInputImage::ImageDimension; ++i)
{
factorSize[i] = this->GetShrinkFactors()[i];
}
const size_t numSamples = std::accumulate( this->GetShrinkFactors().Begin(), this->GetShrinkFactors().End(), 1u, std::multiplies<size_t>() );
const double inumSamples = 1.0 / (double)numSamples;
const unsigned int numberOfLinesToProcess = outputRegionForThread.GetNumberOfPixels() / outputRegionForThread.GetSize(0);
ProgressReporter progress(this, threadId, numberOfLinesToProcess );
while ( !outputIterator.IsAtEnd() )
{
const OutputIndexType outputIndex = outputIterator.GetIndex();
typename std::vector<OutputOffsetType>::const_iterator offset = offsets.begin();
const InputIndexType startInputIndex = outputIndex * factorSize;
inputIterator.SetIndex( startInputIndex+*offset );
for( size_t i = 0; i < ln; ++i )
{
accBuffer[i] = inputIterator.Get();
++inputIterator;
for (size_t j = 1; j < factorSize[0]; ++j)
{
assert( !inputIterator.IsAtEndOfLine() );
accBuffer[i] += inputIterator.Get();
++inputIterator;
}
}
while ( ++offset != offsets.end() )
{
inputIterator.SetIndex( startInputIndex+*offset );
// Note: If the output image is small then we might not split
// the fastest direction. So we may not actually be at the start
// of the line...
//inputIterator.GoToBeginOfLine();
for( size_t i = 0; i < ln; ++i )
{
for( size_t j = 0; j < factorSize[0]; ++j)
{
assert( !inputIterator.IsAtEndOfLine() );
accBuffer[i] += inputIterator.Get();
++inputIterator;
}
}
}
for ( size_t j = 0; j <ln;++j)
{
assert(!outputIterator.IsAtEndOfLine());
// this statement is made to work with RGB pixel types
accBuffer[j] = accBuffer[j] * inumSamples;
outputIterator.Set( static_cast<OutputPixelType>(accBuffer[j]) );
++outputIterator;
}
outputIterator.NextLine();
// Although the method name is CompletedPixel(),
// this is being called after each line is processed
progress.CompletedPixel();
}
}
catch(..)
{
delete accBuffer;
throw;
}
delete accBuffer;
}
/**
*
*/
template <class TInputImage, class TOutputImage>
void
BinShrinkImageFilter<TInputImage,TOutputImage>
::GenerateInputRequestedRegion()
{
// call the superclass' implementation of this method
Superclass::GenerateInputRequestedRegion();
// get pointers to the input and output
InputImagePointer inputPtr = const_cast<TInputImage *> (this->GetInput());
OutputImagePointer outputPtr = this->GetOutput();
// Compute the input requested region (size and start index)
// Use the image transformations to insure an input requested region
// that will provide the proper range
const typename TOutputImage::SizeType& outputRequestedRegionSize = outputPtr->GetRequestedRegion().GetSize();
const typename TOutputImage::IndexType& outputRequestedRegionStartIndex = outputPtr->GetRequestedRegion().GetIndex();
typename TInputImage::IndexType inputIndex0;
typename TInputImage::SizeType inputSize;
for ( unsigned int i=0; i < TInputImage::ImageDimension; ++i)
{
inputIndex0[i] = outputRequestedRegionStartIndex[i]*m_ShrinkFactors[i];
inputSize[i] = outputRequestedRegionSize[i]*m_ShrinkFactors[i];
}
typename TInputImage::RegionType inputRequestedRegion;
inputRequestedRegion.SetIndex( inputIndex0 );
inputRequestedRegion.SetSize( inputSize );
// actually if we need to crop an exceptions should be thrown!
//inputRequestedRegion.Crop( inputPtr->GetLargestPossibleRegion() );
if ( !inputPtr->GetLargestPossibleRegion().IsInside( inputRequestedRegion.GetIndex() ) ||
!inputPtr->GetLargestPossibleRegion().IsInside( inputRequestedRegion.GetUpperIndex() ) )
{
itkExceptionMacro( "Unexpected error calculating RR");
}
itkDebugMacro( "InputRequestedRegion: " << inputRequestedRegion );
inputPtr->SetRequestedRegion( inputRequestedRegion );
}
template <class TInputImage, class TOutputImage>
void
BinShrinkImageFilter<TInputImage,TOutputImage>
::GenerateOutputInformation()
{
// Call the superclass' implementation of this method
Superclass::GenerateOutputInformation();
// Get pointers to the input and output
InputImageConstPointer inputPtr = this->GetInput();
OutputImagePointer outputPtr = this->GetOutput();
if ( !inputPtr || !outputPtr )
{
return;
}
// Compute the output spacing, the output image size, and the
// output image start index
const typename TInputImage::SpacingType & inputSpacing = inputPtr->GetSpacing();
const typename TInputImage::SizeType & inputSize = inputPtr->GetLargestPossibleRegion().GetSize();
const typename TInputImage::IndexType & inputStartIndex = inputPtr->GetLargestPossibleRegion().GetIndex();
ContinuousIndex<double,ImageDimension> inputIndexOutputOrigin;
typename TOutputImage::SpacingType outputSpacing(inputSpacing);
typename TOutputImage::SizeType outputSize;
typename TOutputImage::PointType outputOrigin;
typename TOutputImage::IndexType outputStartIndex;
for ( unsigned int i = 0; i < TOutputImage::ImageDimension; i++ )
{
outputSpacing[i] *= m_ShrinkFactors[i];
inputIndexOutputOrigin[i] = 0.5*(m_ShrinkFactors[i]-1);
outputStartIndex[i] = Math::Ceil<SizeValueType>(inputStartIndex[i]/static_cast<double>( m_ShrinkFactors[i]) );
// Round down so that all output pixels fit input input region
outputSize[i] = Math::Floor<SizeValueType>((double)(inputSize[i] - outputStartIndex[i]*m_ShrinkFactors[i]+inputStartIndex[i])
/ (double)m_ShrinkFactors[i]);
if ( outputSize[i] < 1 )
{
itkExceptionMacro("InputImage is too small! An output pixel does not map to a whole input bin.");
}
}
inputPtr->TransformContinuousIndexToPhysicalPoint(inputIndexOutputOrigin, outputOrigin);
outputPtr->SetSpacing(outputSpacing);
outputPtr->SetOrigin(outputOrigin);
// Set region
typename TOutputImage::RegionType outputLargestPossibleRegion;
outputLargestPossibleRegion.SetSize(outputSize);
outputLargestPossibleRegion.SetIndex(outputStartIndex);
outputPtr->SetLargestPossibleRegion(outputLargestPossibleRegion);
}
} // end namespace itk
#endif
<|endoftext|> |
<commit_before><commit_msg>Control: added estop and pad msg to control_core_command in mpc_controller_submodule<commit_after><|endoftext|> |
<commit_before>#include "Engine.h"
#include "Game.h"
#include "ObjectDummy.h"
#include "BodyRigid.h"
#include "BodyDummy.h"
#include "Physics.h"
#include "ShapeCapsule.h"
#include "ActorBase.h"
#include "Visualizer.h"
#include "sys/SysControl.h"
using namespace MathLib;
#ifdef MEMORY_INFO
#define new new(__FILE__, __LINE__)
#endif // MEMORY_INFO
/*
*/
#define ACTOR_BASE_IFPS (1.0f / 60.0f)
#define ACTOR_BASE_CLAMP 89.9f
#define ACTOR_BASE_COLLISIONS 4
/*
*/
CActorBase::CActorBase()
{
m_vUp = vec3(0.0f, 0.0f, 1.0f);
m_pObject = new CObjectDummy();
m_pDummy = new CBodyDummy();
m_pShape = new CShapeCapsule(1.0f, 1.0f);
m_nFlush = 0;
m_vPosition = Vec3_zero;
m_vVelocity = Vec3_zero;
m_fPhiAngle = 0.0f; //倾斜角 二维平面坐标系中,直线向Y周延伸的方向与X轴正向之间的夹角
m_fThetaAngle = 0.0f; //方位角,正北方那条线与当前线条按照顺时针走过的角度
for (int i = 0; i < NUM_STATES; i++)
{
m_pStates[i] = 0;
m_pTimes[i] = 0.0f;
}
m_pDummy->SetEnabled(1);
m_pObject->SetBody(NULL);
m_pObject->SetBody(m_pDummy);
m_pShape->SetBody(NULL);
m_pShape->SetBody(m_pDummy);
m_pObject->SetWorldTransform(Get_Body_Transform());
m_pShape->SetRestitution(0.0f);
m_pShape->SetCollisionMask(2);
SetEnabled(1);
SetViewDirection(vec3(0.0f, 1.0f, 0.0f));
SetCollision(1);
SetCollisionRadius(0.3f);
SetCollisionHeight(1.0f);
SetFriction(2.0f);
SetMinVelocity(2.0f);
SetMaxVelocity(4.0f);
SetAcceleration(8.0f);
SetDamping(8.0f);
SetJumping(1.5f);
SetGround(0);
SetCeiling(0);
}
CActorBase::~CActorBase()
{
m_pDummy->SetObject(NULL);
delete m_pObject;
delete m_pDummy;
}
void CActorBase::SetEnabled(int enable)
{
m_nEnable = enable;
m_pDummy->SetEnabled(m_nEnable);
}
int CActorBase::IsEnabled() const
{
return m_nEnable;
}
void CActorBase::Update(float ifps)
{
if (!m_nEnable)
{
return;
}
// impulse
vec3 impulse = vec3_zero;
// ortho basis
vec3 tangent, binormal;
OrthoBasis(m_vUp, tangent, binormal);
// current basis
vec3 x = quat(m_vUp, -m_fPhiAngle) * binormal;
vec3 y = Normalize(Cross(m_vUp, x));
vec3 z = Normalize(Cross(x, y));
handle states
Update_States(1, ifps);
// old velocity
float x_velocity = Dot(x, m_vVelocity);
float y_velocity = Dot(y, m_vVelocity);
float z_velocity = Dot(z, m_vVelocity);
// movement
if (m_pStates[STATE_FORWARD]) impulse += x;
if (m_pStates[STATE_BACKWARD]) impulse -= x;
if (m_pStates[STATE_MOVE_LEFT]) impulse += y;
if (m_pStates[STATE_MOVE_RIGHT]) impulse -= y;
impulse.normalize();
//velocity
if (m_pStates[STATE_RUN])
impulse *= m_fMaxVelocity;
else
impulse *= m_fMinVelocity;
// jump
if (m_pStates[STATE_JUMP] == STATE_BEGIN)
{
impulse += z * CMathCore::Sqrt(2.0f * 9.8f * m_fJumping) / (m_fAcceleration * ifps);
}
// rotate velocity
if (GetGround())
{
m_vVelocity = x * x_velocity + y * y_velocity + z * z_velocity;
}
// time
float time = ifps * g_Engine.pPhysics->GetScale();
// target velocity
float target_velocity = Length(vec2(Dot(x, impulse), Dot(y, impulse)));
// penetration tolerance
float penetration = g_Engine.pPhysics->GetPenetrationTolerance();
float penetration_2 = penetration * 2.0f;
// frozen linear velocity
float frozen_velocity = g_Engine.pPhysics->GetFrozenLinearVelocity();
// friction
float friction = 0.0f;
if (target_velocity < EPSILON)
{
friction = m_fFriction;
}
//clear collision flags
if (GetCollision())
{
m_nGround = 0;
m_nCeiling = 0;
}
// movement
do
{
// adaptive time step
float ifps = Min(time, ACTOR_BASE_IFPS);
time -= ifps;
// save old velocity
float old_velocity = Length(vec2(Dot(x, m_vVelocity), Dot(y, m_vVelocity)));
// integrate velocity
m_vVelocity += impulse * (m_fAcceleration * ifps);
m_vVelocity += g_Engine.pPhysics->GetGravity() * ifps;
// damping
float current_velocity = Length(vec2(Dot(x, m_vVelocity), Dot(y, m_vVelocity)));
if (target_velocity < EPSILON || current_velocity > target_velocity)
{
m_vVelocity = (x * Dot(x, m_vVelocity) + y * Dot(y, m_vVelocity)) * CMathCore::Exp(-m_fDamping * ifps) + z * Dot(z, m_vVelocity);
}
// clamp maximum velocity
current_velocity = Length(vec2(Dot(x, m_vVelocity), Dot(y, m_vVelocity)));
if (current_velocity > old_velocity)
{
if (current_velocity > target_velocity)
{
m_vVelocity = (x * Dot(x, m_vVelocity) + y * Dot(y, m_vVelocity)) * target_velocity / current_velocity + z * Dot(z, m_vVelocity);
}
}
// frozen velocity
int is_frozen = 0;
if (current_velocity < frozen_velocity)
{
m_vVelocity = z * Dot(z, m_vVelocity);
is_frozen = 1;
}
// integrate position
//m_vPosition += Vec3(m_vVelocity * ifps);
// world collision
if (GetCollision())
{
// get collision
vec3 tangent, binormal;
const Vec3 *caps = m_pShape->GetCaps();
for (int i = 0; i < ACTOR_BASE_COLLISIONS; i++)
{
m_pDummy->SetTransform(Get_Body_Transform());
m_pShape->GetCollision(m_vecContacts, 0.0f);
if (m_vecContacts.Size() == 0) break;
float inum_contacts = 1.0f / CMathCore::Itof(m_vecContacts.Size());
for (int j = 0; j < m_vecContacts.Size(); j++)
{
const CShape::Contact &c = m_vecContacts[j];
vec3 normalCollision = c.normal;
if (is_frozen && c.depth < penetration_2)
{
m_vPosition += Vec3(z * (Max(c.depth - penetration, 0.0f) * inum_contacts * Dot(z, normalCollision)));
}
else
{
m_vPosition += Vec3(normalCollision * (Max(c.depth - penetration, 0.0f) * inum_contacts));
is_frozen = 0;
}
float normal_velocity = Dot(normalCollision, m_vVelocity);
if (normal_velocity < 0.0f)
{
m_vVelocity -= normalCollision * normal_velocity;
}
if (friction > EPSILON)
{
OrthoBasis(c.normal, tangent, binormal);
float tangent_velocity = Dot(tangent, m_vVelocity);
float binormal_velocity = Dot(binormal, m_vVelocity);
if (CMathCore::Abs(tangent_velocity) > EPSILON || CMathCore::Abs(binormal_velocity) > EPSILON) {
float friction_velocity = Clamp(Max(-normal_velocity, 0.0f) * friction * CMathCore::RSqrt(tangent_velocity * tangent_velocity + binormal_velocity * binormal_velocity), -1.0f, 1.0f);
m_vVelocity -= tangent * tangent_velocity * friction_velocity;
m_vVelocity -= binormal * binormal_velocity * friction_velocity;
}
}
if (Dot(c.normal, m_vUp) > 0.5f && Dot(vec3(c.point - caps[0]), m_vUp) < 0.0f) m_nGround = 1;
if (Dot(c.normal, m_vUp) < -0.5f && Dot(vec3(c.point - caps[1]), m_vUp) > 0.0f) m_nCeiling = 1;
}
}
m_vPosition += Vec3(m_vVelocity * ifps);
}
while (time > EPSILON);
// current position
m_pObject->SetWorldTransform(Get_Body_Transform());
m_WorldBoundBox.Set(m_BoundBox, Translate(m_vPosition));
m_WorldBoundSphere.Set(m_BoundSphere, Translate(m_vPosition));
}
}
/*
*/
void CActorBase::Update_Bounds()
{
float radius = m_pShape->GetRadius();
float hheight = m_pShape->GetHHeight();
m_BoundBox.Set(vec3(-radius, -radius, 0.0f), vec3(radius, radius, (radius + hheight) * 2.0f));
m_BoundSphere.Set(vec3(0.0f, 0.0f, radius + hheight), radius + hheight);
m_WorldBoundBox.Set(m_BoundBox, Translate(m_vPosition));
m_WorldBoundSphere.Set(m_BoundSphere, Translate(m_vPosition));
}
/*
*/
void CActorBase::SetIntersectionMask(int mask)
{
m_pShape->SetIntersectionMask(mask);
}
int CActorBase::GetIntersectionMask() const
{
return m_pShape->GetIntersectionMask();
}
/*
*/
void CActorBase::SetCollision(int c)
{
m_nCollision = c;
}
int CActorBase::GetCollision() const
{
return m_nCollision;
}
void CActorBase::SetCollisionMask(int mask)
{
m_pShape->SetCollisionMask(mask);
}
int CActorBase::GetCollisionMask() const
{
return m_pShape->GetCollisionMask();
}
void CActorBase::SetCollisionRadius(float radius)
{
if (!Compare(m_pShape->GetRadius(), radius))
{
m_pDummy->SetPreserveTransform(Mat4(Translate(m_vUp * (radius - m_pShape->GetRadius()))) * m_pDummy->GetTransform());
m_pShape->SetRadius(radius);
}
Update_Bounds();
}
float CActorBase::GetCollisionRadius() const
{
return m_pShape->GetRadius();
}
/*
*/
void CActorBase::SetCollisionHeight(float height)
{
if (!Compare(m_pShape->GetHeight(), height))
{
m_pDummy->SetPreserveTransform(Mat4(Translate(m_vUp * (height - m_pShape->GetHeight()) * 0.5f)) * m_pDummy->GetTransform());
m_pShape->SetHeight(height);
}
Update_Bounds();
}
float CActorBase::GetCollisionHeight() const
{
return m_pShape->GetHeight();
}
void CActorBase::SetMinVelocity(float velocity)
{
m_fMinVelocity = Max(velocity, 0.0f);
}
float CActorBase::GetMinVelocity() const
{
return m_fMinVelocity;
}
/*
*/
void CActorBase::SetMaxVelocity(float velocity)
{
m_fMaxVelocity = Max(velocity, 0.0f);
}
float CActorBase::GetMaxVelocity() const
{
return m_fMaxVelocity;
}
/*
*/
void CActorBase::SetAcceleration(float accel)
{
m_fAcceleration = Max(accel, 0.0f);
}
float CActorBase::GetAcceleration() const
{
return m_fAcceleration;
}
/*
*/
void CActorBase::SetDamping(float d)
{
m_fDamping = Max(d, 0.0f);
}
float CActorBase::GetDamping() const
{
return m_fDamping;
}
/*
*/
void CActorBase::SetJumping(float j)
{
m_fJumping = Max(j, 0.0f);
}
float CActorBase::GetJumping() const
{
return m_fJumping;
}
/*
*/
void CActorBase::SetViewDirection(const vec3 &d)
{
m_vDirection = Normalize(d);
// ortho basis
vec3 tangent, binormal;
OrthoBasis(m_vUp, tangent, binormal);
// decompose direction
m_fPhiAngle = CMathCore::ATan2(Dot(m_vDirection, tangent), Dot(m_vDirection, binormal)) * RAD2DEG;
m_fThetaAngle = CMathCore::ACos(Clamp(Dot(m_vDirection, m_vUp), -1.0f, 1.0f)) * RAD2DEG - 90.0f;
m_pObject->SetWorldTransform(Get_Body_Transform());
}
const vec3 &CActorBase::GetViewDirection() const
{
return m_vDirection;
}
/******************************************************************************\
*
* States
*
\******************************************************************************/
/*
*/
int CActorBase::GetState(int state) const
{
assert(state >= 0 && state < NUM_STATES && "CPlayerActor::GetState(): bad state number");
return m_pStates[state];
}
<commit_msg>Signed-off-by: mrlitong <litongtongxue@gmail.com><commit_after>#include "Engine.h"
#include "Game.h"
#include "ObjectDummy.h"
#include "BodyRigid.h"
#include "BodyDummy.h"
#include "Physics.h"
#include "ShapeCapsule.h"
#include "ActorBase.h"
#include "Visualizer.h"
#include "sys/SysControl.h"
using namespace MathLib;
#ifdef MEMORY_INFO
#define new new(__FILE__, __LINE__)
#endif // MEMORY_INFO
/*
*/
#define ACTOR_BASE_IFPS (1.0f / 60.0f)
#define ACTOR_BASE_CLAMP 89.9f
#define ACTOR_BASE_COLLISIONS 4
/*
*/
CActorBase::CActorBase()
{
m_vUp = vec3(0.0f, 0.0f, 1.0f);
m_pObject = new CObjectDummy();
m_pDummy = new CBodyDummy();
m_pShape = new CShapeCapsule(1.0f, 1.0f);
m_nFlush = 0;
m_vPosition = Vec3_zero;
m_vVelocity = Vec3_zero;
m_fPhiAngle = 0.0f; //倾斜角 二维平面坐标系中,直线向Y周延伸的方向与X轴正向之间的夹角
m_fThetaAngle = 0.0f; //方位角,正北方那条线与当前线条按照顺时针走过的角度
for (int i = 0; i < NUM_STATES; i++)
{
m_pStates[i] = 0;
m_pTimes[i] = 0.0f;
}
m_pDummy->SetEnabled(1);
m_pObject->SetBody(NULL);
m_pObject->SetBody(m_pDummy);
m_pShape->SetBody(NULL);
m_pShape->SetBody(m_pDummy);
m_pObject->SetWorldTransform(Get_Body_Transform());
m_pShape->SetRestitution(0.0f);
m_pShape->SetCollisionMask(2);
SetEnabled(1);
SetViewDirection(vec3(0.0f, 1.0f, 0.0f));
SetCollision(1);
SetCollisionRadius(0.3f);
SetCollisionHeight(1.0f);
SetFriction(2.0f);
SetMinVelocity(2.0f);
SetMaxVelocity(4.0f);
SetAcceleration(8.0f);
SetDamping(8.0f);
SetJumping(1.5f);
SetGround(0);
SetCeiling(0);
}
CActorBase::~CActorBase()
{
m_pDummy->SetObject(NULL);
delete m_pObject;
delete m_pDummy;
}
void CActorBase::SetEnabled(int enable)
{
m_nEnable = enable;
m_pDummy->SetEnabled(m_nEnable);
}
int CActorBase::IsEnabled() const
{
return m_nEnable;
}
void CActorBase::Update(float ifps)
{
if (!m_nEnable)
{
return;
}
// impulse
vec3 impulse = vec3_zero;
// ortho basis
vec3 tangent, binormal;
OrthoBasis(m_vUp, tangent, binormal);
// current basis
vec3 x = quat(m_vUp, -m_fPhiAngle) * binormal;
vec3 y = Normalize(Cross(m_vUp, x));
vec3 z = Normalize(Cross(x, y));
handle states
Update_States(1, ifps);
// old velocity
float x_velocity = Dot(x, m_vVelocity);
float y_velocity = Dot(y, m_vVelocity);
float z_velocity = Dot(z, m_vVelocity);
// movement
if (m_pStates[STATE_FORWARD]) impulse += x;
if (m_pStates[STATE_BACKWARD]) impulse -= x;
if (m_pStates[STATE_MOVE_LEFT]) impulse += y;
if (m_pStates[STATE_MOVE_RIGHT]) impulse -= y;
impulse.normalize();
//velocity
if (m_pStates[STATE_RUN])
impulse *= m_fMaxVelocity;
else
impulse *= m_fMinVelocity;
// jump
if (m_pStates[STATE_JUMP] == STATE_BEGIN)
{
impulse += z * CMathCore::Sqrt(2.0f * 9.8f * m_fJumping) / (m_fAcceleration * ifps);
}
// rotate velocity
if (GetGround())
{
m_vVelocity = x * x_velocity + y * y_velocity + z * z_velocity;
}
// time
float time = ifps * g_Engine.pPhysics->GetScale();
// target velocity
float target_velocity = Length(vec2(Dot(x, impulse), Dot(y, impulse)));
// penetration tolerance
float penetration = g_Engine.pPhysics->GetPenetrationTolerance();
float penetration_2 = penetration * 2.0f;
// frozen linear velocity
float frozen_velocity = g_Engine.pPhysics->GetFrozenLinearVelocity();
// friction
float friction = 0.0f;
if (target_velocity < EPSILON)
{
friction = m_fFriction;
}
//clear collision flags
if (GetCollision())
{
m_nGround = 0;
m_nCeiling = 0;
}
// movement
do
{
// adaptive time step
float ifps = Min(time, ACTOR_BASE_IFPS);
time -= ifps;
// save old velocity
float old_velocity = Length(vec2(Dot(x, m_vVelocity), Dot(y, m_vVelocity)));
// integrate velocity
m_vVelocity += impulse * (m_fAcceleration * ifps);
m_vVelocity += g_Engine.pPhysics->GetGravity() * ifps;
// damping
float current_velocity = Length(vec2(Dot(x, m_vVelocity), Dot(y, m_vVelocity)));
if (target_velocity < EPSILON || current_velocity > target_velocity)
{
m_vVelocity = (x * Dot(x, m_vVelocity) + y * Dot(y, m_vVelocity)) * CMathCore::Exp(-m_fDamping * ifps) + z * Dot(z, m_vVelocity);
}
// clamp maximum velocity
current_velocity = Length(vec2(Dot(x, m_vVelocity), Dot(y, m_vVelocity)));
if (current_velocity > old_velocity)
{
if (current_velocity > target_velocity)
{
m_vVelocity = (x * Dot(x, m_vVelocity) + y * Dot(y, m_vVelocity)) * target_velocity / current_velocity + z * Dot(z, m_vVelocity);
}
}
// frozen velocity
int is_frozen = 0;
if (current_velocity < frozen_velocity)
{
m_vVelocity = z * Dot(z, m_vVelocity);
is_frozen = 1;
}
// integrate position
//m_vPosition += Vec3(m_vVelocity * ifps);
// world collision
if (GetCollision())
{
// get collision
vec3 tangent, binormal;
const Vec3 *caps = m_pShape->GetCaps();
for (int i = 0; i < ACTOR_BASE_COLLISIONS; i++)
{
m_pDummy->SetTransform(Get_Body_Transform());
m_pShape->GetCollision(m_vecContacts, 0.0f);
if (m_vecContacts.Size() == 0) break;
float inum_contacts = 1.0f / CMathCore::Itof(m_vecContacts.Size());
for (int j = 0; j < m_vecContacts.Size(); j++)
{
const CShape::Contact &c = m_vecContacts[j];
vec3 normalCollision = c.normal;
if (is_frozen && c.depth < penetration_2)
{
m_vPosition += Vec3(z * (Max(c.depth - penetration, 0.0f) * inum_contacts * Dot(z, normalCollision)));
}
else
{
m_vPosition += Vec3(normalCollision * (Max(c.depth - penetration, 0.0f) * inum_contacts));
is_frozen = 0;
}
float normal_velocity = Dot(normalCollision, m_vVelocity);
if (normal_velocity < 0.0f)
{
m_vVelocity -= normalCollision * normal_velocity;
}
if (friction > EPSILON)
{
OrthoBasis(c.normal, tangent, binormal);
float tangent_velocity = Dot(tangent, m_vVelocity);
float binormal_velocity = Dot(binormal, m_vVelocity);
if (CMathCore::Abs(tangent_velocity) > EPSILON || CMathCore::Abs(binormal_velocity) > EPSILON) {
float friction_velocity = Clamp(Max(-normal_velocity, 0.0f) * friction * CMathCore::RSqrt(tangent_velocity * tangent_velocity + binormal_velocity * binormal_velocity), -1.0f, 1.0f);
m_vVelocity -= tangent * tangent_velocity * friction_velocity;
m_vVelocity -= binormal * binormal_velocity * friction_velocity;
}
}
if (Dot(c.normal, m_vUp) > 0.5f && Dot(vec3(c.point - caps[0]), m_vUp) < 0.0f) m_nGround = 1;
if (Dot(c.normal, m_vUp) < -0.5f && Dot(vec3(c.point - caps[1]), m_vUp) > 0.0f) m_nCeiling = 1;
}
}
m_vPosition += Vec3(m_vVelocity * ifps);
}
while (time > EPSILON);
// current position
m_pObject->SetWorldTransform(Get_Body_Transform());
m_WorldBoundBox.Set(m_BoundBox, Translate(m_vPosition));
m_WorldBoundSphere.Set(m_BoundSphere, Translate(m_vPosition));
}
}
/*
*/
void CActorBase::Update_Bounds()
{
float radius = m_pShape->GetRadius();
float hheight = m_pShape->GetHHeight();
m_BoundBox.Set(vec3(-radius, -radius, 0.0f), vec3(radius, radius, (radius + hheight) * 2.0f));
m_BoundSphere.Set(vec3(0.0f, 0.0f, radius + hheight), radius + hheight);
m_WorldBoundBox.Set(m_BoundBox, Translate(m_vPosition));
m_WorldBoundSphere.Set(m_BoundSphere, Translate(m_vPosition));
}
/*
*/
void CActorBase::SetIntersectionMask(int mask)
{
m_pShape->SetIntersectionMask(mask);
}
int CActorBase::GetIntersectionMask() const
{
return m_pShape->GetIntersectionMask();
}
/*
*/
void CActorBase::SetCollision(int c)
{
m_nCollision = c;
}
int CActorBase::GetCollision() const
{
return m_nCollision;
}
void CActorBase::SetCollisionMask(int mask)
{
m_pShape->SetCollisionMask(mask);
}
int CActorBase::GetCollisionMask() const
{
return m_pShape->GetCollisionMask();
}
void CActorBase::SetCollisionRadius(float radius)
{
if (!Compare(m_pShape->GetRadius(), radius))
{
m_pDummy->SetPreserveTransform(Mat4(Translate(m_vUp * (radius - m_pShape->GetRadius()))) * m_pDummy->GetTransform());
m_pShape->SetRadius(radius);
}
Update_Bounds();
}
float CActorBase::GetCollisionRadius() const
{
return m_pShape->GetRadius();
}
/*
*/
void CActorBase::SetCollisionHeight(float height)
{
if (!Compare(m_pShape->GetHeight(), height))
{
m_pDummy->SetPreserveTransform(Mat4(Translate(m_vUp * (height - m_pShape->GetHeight()) * 0.5f)) * m_pDummy->GetTransform());
m_pShape->SetHeight(height);
}
Update_Bounds();
}
float CActorBase::GetCollisionHeight() const
{
return m_pShape->GetHeight();
}
void CActorBase::SetMinVelocity(float velocity)
{
m_fMinVelocity = Max(velocity, 0.0f);
}
float CActorBase::GetMinVelocity() const
{
return m_fMinVelocity;
}
/*
*/
void CActorBase::SetMaxVelocity(float velocity)
{
m_fMaxVelocity = Max(velocity, 0.0f);
}
float CActorBase::GetMaxVelocity() const
{
return m_fMaxVelocity;
}
/*
*/
void CActorBase::SetAcceleration(float accel)
{
m_fAcceleration = Max(accel, 0.0f);
}
float CActorBase::GetAcceleration() const
{
return m_fAcceleration;
}
/*
*/
void CActorBase::SetDamping(float d)
{
m_fDamping = Max(d, 0.0f);
}
float CActorBase::GetDamping() const
{
return m_fDamping;
}
/*
*/
void CActorBase::SetJumping(float j)
{
m_fJumping = Max(j, 0.0f);
}
float CActorBase::GetJumping() const
{
return m_fJumping;
}
/*
*/
void CActorBase::SetViewDirection(const vec3 &d)
{
m_vDirection = Normalize(d);
// ortho basis
vec3 tangent, binormal;
OrthoBasis(m_vUp, tangent, binormal);
// decompose direction
m_fPhiAngle = CMathCore::ATan2(Dot(m_vDirection, tangent), Dot(m_vDirection, binormal)) * RAD2DEG;
m_fThetaAngle = CMathCore::ACos(Clamp(Dot(m_vDirection, m_vUp), -1.0f, 1.0f)) * RAD2DEG - 90.0f;
m_pObject->SetWorldTransform(Get_Body_Transform());
}
const vec3 &CActorBase::GetViewDirection() const
{
return m_vDirection;
}
/******************************************************************************\
*
* States
*
\******************************************************************************/
/*
*/
int CActorBase::GetState(int state) const
{
assert(state >= 0 && state < NUM_STATES && "CPlayerActor::GetState(): bad state number");
return m_pStates[state];
}
float CActorBase::GetStateTime(int state) const
{
assert(state >= 0 && state < NUM_STATES && "CPlayerActor::GetStateTime(): bad state number");
return m_pTimes[state];
}<|endoftext|> |
<commit_before><commit_msg>WaE: unused parameter 'bForceEvaluation'<commit_after><|endoftext|> |
<commit_before>/*****************************************************************************
*
* This file is part of Mapnik (c++ mapping toolkit)
*
* Copyright (C) 2012 Artem Pavlenko
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*
*****************************************************************************/
#ifndef MAPNIK_OFFSET_CONVERTER_HPP
#define MAPNIK_OFFSET_CONVERTER_HPP
#include <mapnik/debug.hpp>
#include <mapnik/box2d.hpp>
#include <mapnik/vertex.hpp>
#include <mapnik/coord_array.hpp>
#include <mapnik/proj_transform.hpp>
// boost
#include <boost/math/constants/constants.hpp>
namespace mapnik
{
const double pi = boost::math::constants::pi<double>();
const double half_pi = pi/2.0;
template <typename Geometry>
struct MAPNIK_DECL offset_converter
{
typedef std::size_t size_type;
//typedef typename Geometry::value_type value_type;
offset_converter(Geometry & geom)
: geom_(geom)
, offset_(0.0)
, half_turn_segments_(16)
, status_(initial)
, pre_first_(vertex2d::no_init)
, pre_(vertex2d::no_init)
, cur_(vertex2d::no_init)
{}
enum status
{
initial,
process,
last_vertex,
angle_joint,
end
};
double get_offset() const
{
return offset_;
}
void set_offset(double offset)
{
if (offset != offset_)
{
offset_ = offset;
reset();
}
}
unsigned vertex(double * x, double * y)
{
if (offset_ == 0.0)
return geom_.vertex(x, y);
if (status_ == initial)
init_vertices();
if (pos_ >= vertices_.size())
return SEG_END;
pre_ = (pos_ ? cur_ : pre_first_);
cur_ = vertices_[pos_++];
if (pos_ == vertices_.size())
return output_vertex(x, y);
double t = 1.0;
double vt, ut;
for (size_t i = pos_; i+1 < vertices_.size(); ++i)
{
//break; // uncomment this to see all the curls
vertex2d const& u0 = vertices_[i];
vertex2d const& u1 = vertices_[i+1];
if (!intersection(pre_, cur_, &vt, u0, u1, &ut))
continue;
if (vt < 0.0 || vt > t || ut < 0.0 || ut > 1.0)
continue;
t = vt;
pos_ = i+1;
}
cur_.x = pre_.x + t * (cur_.x - pre_.x);
cur_.y = pre_.y + t * (cur_.y - pre_.y);
return output_vertex(x, y);
}
void reset()
{
geom_.rewind(0);
vertices_.clear();
status_ = initial;
pos_ = 0;
}
void rewind(unsigned)
{
pos_ = 0;
}
private:
static double explement_reflex_angle(double angle)
{
if (angle > pi)
return angle - 2 * pi;
else if (angle < -pi)
return angle + 2 * pi;
else
return angle;
}
static bool intersection(vertex2d const& u1, vertex2d const& u2, double* ut,
vertex2d const& v1, vertex2d const& v2, double* vt)
{
double const dx = v1.x - u1.x;
double const dy = v1.y - u1.y;
double const ux = u2.x - u1.x;
double const uy = u2.y - u1.y;
double const vx = v2.x - v1.x;
double const vy = v2.y - v1.y;
// the first line is not vertical
if (ux < -1e-6 || ux > 1e-6)
{
double const up = ux * dy - dx * uy;
double const dn = vx * uy - ux * vy;
if (dn > -1e-6 && dn < 1e-6)
return false; // they are parallel
*vt = up / dn;
*ut = (*vt * vx + dx) / ux;
return true;
}
// the first line is not horizontal
if (uy < -1e-6 || uy > 1e-6)
{
double const up = uy * dx - dy * ux;
double const dn = vy * ux - uy * vx;
if (dn > -1e-6 && dn < 1e-6)
return false; // they are parallel
*vt = up / dn;
*ut = (*vt * vy + dy) / uy;
return true;
}
// the first line is too short
return false;
}
/**
* @brief Translate (vx, vy) by rotated (dx, dy).
*/
static void displace(vertex2d & v, double dx, double dy, double a)
{
v.x += dx * cos(a) - dy * sin(a);
v.y += dx * sin(a) + dy * cos(a);
}
/**
* @brief Translate (vx, vy) by rotated (0, -offset).
*/
void displace(vertex2d & v, double a) const
{
v.x += offset_ * sin(a);
v.y -= offset_ * cos(a);
}
/**
* @brief (vx, vy) := (ux, uy) + rotated (0, -offset)
*/
void displace(vertex2d & v, vertex2d const& u, double a) const
{
v.x = u.x + offset_ * sin(a);
v.y = u.y - offset_ * cos(a);
v.cmd = u.cmd;
}
void displace2(vertex2d & v, double a, double b) const
{
double sa = offset_ * sin(a);
double ca = offset_ * cos(a);
double h = tan(0.5 * (b - a));
v.x = v.x + sa + h * ca;
v.y = v.y - ca + h * sa;
}
status init_vertices()
{
if (status_ != initial) // already initialized
return status_;
vertex2d v1(vertex2d::no_init);
vertex2d v2(vertex2d::no_init);
vertex2d w(vertex2d::no_init);
v1.cmd = geom_.vertex(&v1.x, &v1.y);
v2.cmd = geom_.vertex(&v2.x, &v2.y);
if (v2.cmd == SEG_END) // not enough vertices in source
return status_ = process;
double angle_a = 0;
double angle_b = atan2((v2.y - v1.y), (v2.x - v1.x));
double joint_angle;
// first vertex
displace(v1, angle_b);
push_vertex(v1);
// Sometimes when the first segment is too short, it causes ugly
// curls at the beginning of the line. To avoid this, we make up
// a fake vertex two offset-lengths before the first, and expect
// intersection detection smoothes it out.
pre_first_ = v1;
displace(pre_first_, -2 * fabs(offset_), 0, angle_b);
while ((v1 = v2, v2.cmd = geom_.vertex(&v2.x, &v2.y)) != SEG_END)
{
angle_a = angle_b;
angle_b = atan2((v2.y - v1.y), (v2.x - v1.x));
joint_angle = explement_reflex_angle(angle_b - angle_a);
double half_turns = half_turn_segments_ * fabs(joint_angle);
int bulge_steps = 0;
if (offset_ < 0.0)
{
if (joint_angle > 0.0)
joint_angle = joint_angle - 2 * pi;
else
bulge_steps = 1 + int(floor(half_turns / pi));
}
else
{
if (joint_angle < 0.0)
joint_angle = joint_angle + 2 * pi;
else
bulge_steps = 1 + int(floor(half_turns / pi));
}
#ifdef MAPNIK_LOG
if (bulge_steps == 0)
{
// inside turn (sharp/obtuse angle)
MAPNIK_LOG_DEBUG(ctrans) << "offset_converter:"
<< " Sharp joint [<< inside turn " << int(joint_angle*180/pi)
<< " degrees >>]";
}
else
{
// outside turn (reflex angle)
MAPNIK_LOG_DEBUG(ctrans) << "offset_converter:"
<< " Bulge joint >)) outside turn " << int(joint_angle*180/pi)
<< " degrees ((< with " << bulge_steps << " segments";
}
#endif
displace(w, v1, angle_a);
push_vertex(w);
for (int s = 0; ++s < bulge_steps; )
{
displace(w, v1, angle_a + (joint_angle * s) / bulge_steps);
push_vertex(w);
}
displace(v1, angle_b);
push_vertex(v1);
}
// last vertex
displace(v1, angle_b);
push_vertex(v1);
// initalization finished
return status_ = process;
}
unsigned output_vertex(double* px, double* py)
{
*px = cur_.x;
*py = cur_.y;
return cur_.cmd;
}
unsigned output_vertex(double* px, double* py, status st)
{
status_ = st;
return output_vertex(px, py);
}
void push_vertex(vertex2d const& v)
{
#ifdef MAPNIK_LOG
MAPNIK_LOG_DEBUG(ctrans) << "offset_converter: " << v;
#endif
vertices_.push_back(v);
}
Geometry & geom_;
double offset_;
unsigned half_turn_segments_;
status status_;
size_t pos_;
std::vector<vertex2d> vertices_;
vertex2d pre_first_;
vertex2d pre_;
vertex2d cur_;
};
}
#endif // MAPNIK_OFFSET_CONVERTER_HPP
<commit_msg>offset_converter: add threshold to avoid cutting large closed rings off<commit_after>/*****************************************************************************
*
* This file is part of Mapnik (c++ mapping toolkit)
*
* Copyright (C) 2012 Artem Pavlenko
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*
*****************************************************************************/
#ifndef MAPNIK_OFFSET_CONVERTER_HPP
#define MAPNIK_OFFSET_CONVERTER_HPP
#include <mapnik/debug.hpp>
#include <mapnik/box2d.hpp>
#include <mapnik/vertex.hpp>
#include <mapnik/coord_array.hpp>
#include <mapnik/proj_transform.hpp>
// boost
#include <boost/math/constants/constants.hpp>
namespace mapnik
{
const double pi = boost::math::constants::pi<double>();
const double half_pi = pi/2.0;
template <typename Geometry>
struct MAPNIK_DECL offset_converter
{
typedef std::size_t size_type;
//typedef typename Geometry::value_type value_type;
offset_converter(Geometry & geom)
: geom_(geom)
, offset_(0.0)
, threshold_(8.0)
, half_turn_segments_(16)
, status_(initial)
, pre_first_(vertex2d::no_init)
, pre_(vertex2d::no_init)
, cur_(vertex2d::no_init)
{}
enum status
{
initial,
process,
last_vertex,
angle_joint,
end
};
double get_offset() const
{
return offset_;
}
double get_threshold() const
{
return threshold_;
}
void set_offset(double value)
{
if (offset_ != value)
{
offset_ = value;
reset();
}
}
void set_threshold(double value)
{
threshold_ = value;
// no need to reset(), since threshold doesn't affect
// offset vertices' computation, it only controls how
// far will we be looking for self-intersections
}
unsigned vertex(double * x, double * y)
{
if (offset_ == 0.0)
return geom_.vertex(x, y);
if (status_ == initial)
init_vertices();
if (pos_ >= vertices_.size())
return SEG_END;
pre_ = (pos_ ? cur_ : pre_first_);
cur_ = vertices_[pos_++];
if (pos_ == vertices_.size())
return output_vertex(x, y);
double const check_dist = offset_ * threshold_;
double const check_dist2 = check_dist * check_dist;
double t = 1.0;
double vt, ut;
for (size_t i = pos_; i+1 < vertices_.size(); ++i)
{
//break; // uncomment this to see all the curls
vertex2d const& u0 = vertices_[i];
vertex2d const& u1 = vertices_[i+1];
double const dx = u0.x - cur_.x;
double const dy = u0.y - cur_.y;
if (dx*dx + dy*dy > check_dist2)
break;
if (!intersection(pre_, cur_, &vt, u0, u1, &ut))
continue;
if (vt < 0.0 || vt > t || ut < 0.0 || ut > 1.0)
continue;
t = vt;
pos_ = i+1;
}
cur_.x = pre_.x + t * (cur_.x - pre_.x);
cur_.y = pre_.y + t * (cur_.y - pre_.y);
return output_vertex(x, y);
}
void reset()
{
geom_.rewind(0);
vertices_.clear();
status_ = initial;
pos_ = 0;
}
void rewind(unsigned)
{
pos_ = 0;
}
private:
static double explement_reflex_angle(double angle)
{
if (angle > pi)
return angle - 2 * pi;
else if (angle < -pi)
return angle + 2 * pi;
else
return angle;
}
static bool intersection(vertex2d const& u1, vertex2d const& u2, double* ut,
vertex2d const& v1, vertex2d const& v2, double* vt)
{
double const dx = v1.x - u1.x;
double const dy = v1.y - u1.y;
double const ux = u2.x - u1.x;
double const uy = u2.y - u1.y;
double const vx = v2.x - v1.x;
double const vy = v2.y - v1.y;
// the first line is not vertical
if (ux < -1e-6 || ux > 1e-6)
{
double const up = ux * dy - dx * uy;
double const dn = vx * uy - ux * vy;
if (dn > -1e-6 && dn < 1e-6)
return false; // they are parallel
*vt = up / dn;
*ut = (*vt * vx + dx) / ux;
return true;
}
// the first line is not horizontal
if (uy < -1e-6 || uy > 1e-6)
{
double const up = uy * dx - dy * ux;
double const dn = vy * ux - uy * vx;
if (dn > -1e-6 && dn < 1e-6)
return false; // they are parallel
*vt = up / dn;
*ut = (*vt * vy + dy) / uy;
return true;
}
// the first line is too short
return false;
}
/**
* @brief Translate (vx, vy) by rotated (dx, dy).
*/
static void displace(vertex2d & v, double dx, double dy, double a)
{
v.x += dx * cos(a) - dy * sin(a);
v.y += dx * sin(a) + dy * cos(a);
}
/**
* @brief Translate (vx, vy) by rotated (0, -offset).
*/
void displace(vertex2d & v, double a) const
{
v.x += offset_ * sin(a);
v.y -= offset_ * cos(a);
}
/**
* @brief (vx, vy) := (ux, uy) + rotated (0, -offset)
*/
void displace(vertex2d & v, vertex2d const& u, double a) const
{
v.x = u.x + offset_ * sin(a);
v.y = u.y - offset_ * cos(a);
v.cmd = u.cmd;
}
void displace2(vertex2d & v, double a, double b) const
{
double sa = offset_ * sin(a);
double ca = offset_ * cos(a);
double h = tan(0.5 * (b - a));
v.x = v.x + sa + h * ca;
v.y = v.y - ca + h * sa;
}
status init_vertices()
{
if (status_ != initial) // already initialized
return status_;
vertex2d v1(vertex2d::no_init);
vertex2d v2(vertex2d::no_init);
vertex2d w(vertex2d::no_init);
v1.cmd = geom_.vertex(&v1.x, &v1.y);
v2.cmd = geom_.vertex(&v2.x, &v2.y);
if (v2.cmd == SEG_END) // not enough vertices in source
return status_ = process;
double angle_a = 0;
double angle_b = atan2((v2.y - v1.y), (v2.x - v1.x));
double joint_angle;
// first vertex
displace(v1, angle_b);
push_vertex(v1);
// Sometimes when the first segment is too short, it causes ugly
// curls at the beginning of the line. To avoid this, we make up
// a fake vertex two offset-lengths before the first, and expect
// intersection detection smoothes it out.
pre_first_ = v1;
displace(pre_first_, -2 * fabs(offset_), 0, angle_b);
while ((v1 = v2, v2.cmd = geom_.vertex(&v2.x, &v2.y)) != SEG_END)
{
angle_a = angle_b;
angle_b = atan2((v2.y - v1.y), (v2.x - v1.x));
joint_angle = explement_reflex_angle(angle_b - angle_a);
double half_turns = half_turn_segments_ * fabs(joint_angle);
int bulge_steps = 0;
if (offset_ < 0.0)
{
if (joint_angle > 0.0)
joint_angle = joint_angle - 2 * pi;
else
bulge_steps = 1 + int(floor(half_turns / pi));
}
else
{
if (joint_angle < 0.0)
joint_angle = joint_angle + 2 * pi;
else
bulge_steps = 1 + int(floor(half_turns / pi));
}
#ifdef MAPNIK_LOG
if (bulge_steps == 0)
{
// inside turn (sharp/obtuse angle)
MAPNIK_LOG_DEBUG(ctrans) << "offset_converter:"
<< " Sharp joint [<< inside turn " << int(joint_angle*180/pi)
<< " degrees >>]";
}
else
{
// outside turn (reflex angle)
MAPNIK_LOG_DEBUG(ctrans) << "offset_converter:"
<< " Bulge joint >)) outside turn " << int(joint_angle*180/pi)
<< " degrees ((< with " << bulge_steps << " segments";
}
#endif
displace(w, v1, angle_a);
push_vertex(w);
for (int s = 0; ++s < bulge_steps; )
{
displace(w, v1, angle_a + (joint_angle * s) / bulge_steps);
push_vertex(w);
}
displace(v1, angle_b);
push_vertex(v1);
}
// last vertex
displace(v1, angle_b);
push_vertex(v1);
// initialization finished
return status_ = process;
}
unsigned output_vertex(double* px, double* py)
{
*px = cur_.x;
*py = cur_.y;
return cur_.cmd;
}
unsigned output_vertex(double* px, double* py, status st)
{
status_ = st;
return output_vertex(px, py);
}
void push_vertex(vertex2d const& v)
{
#ifdef MAPNIK_LOG
MAPNIK_LOG_DEBUG(ctrans) << "offset_converter: " << v;
#endif
vertices_.push_back(v);
}
Geometry & geom_;
double offset_;
double threshold_;
unsigned half_turn_segments_;
status status_;
size_t pos_;
std::vector<vertex2d> vertices_;
vertex2d pre_first_;
vertex2d pre_;
vertex2d cur_;
};
}
#endif // MAPNIK_OFFSET_CONVERTER_HPP
<|endoftext|> |
<commit_before>/******************************************************************************
* Copyright (c) 2011, Michael P. Gerlek (mpg@flaxen.com)
*
* 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 Hobu, Inc. or Flaxen Geo Consulting 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 INCLUDED_DRIVERS_LAS_WRITER_HPP
#define INCLUDED_DRIVERS_LAS_WRITER_HPP
#include <pdal/Writer.hpp>
#include <pdal/drivers/las/Support.hpp>
#include <pdal/drivers/las/Header.hpp>
#include <pdal/drivers/las/SummaryData.hpp>
#include <pdal/StreamFactory.hpp>
#include <boost/scoped_ptr.hpp>
namespace pdal
{
namespace drivers
{
namespace las
{
//
// supported options:
// <uint32>id
// <bool>debug
// <uint32>verbose
// <string>a_srs
// <bool>compression
// <string>filename [required]
//
class PDAL_DLL Writer : public pdal::Writer
{
public:
SET_STAGE_NAME("drivers.las.writer", "Las Writer")
Writer(Stage& prevStage, const Options&);
Writer(Stage& prevStage, std::ostream*);
virtual ~Writer();
virtual void initialize();
virtual const Options getDefaultOptions() const;
void setFormatVersion(boost::uint8_t majorVersion, boost::uint8_t minorVersion);
void setPointFormat(PointFormat);
void setDate(boost::uint16_t dayOfYear, boost::uint16_t year);
void setProjectId(const boost::uuids::uuid&);
// up to 32 chars (default is "PDAL")
void setSystemIdentifier(const std::string& systemId);
// up to 32 chars (default is "PDAL x.y.z")
void setGeneratingSoftware(const std::string& softwareId);
void setHeaderPadding(boost::uint32_t const& v);
// default false
void setCompressed(bool);
// for dumping
virtual boost::property_tree::ptree toPTree() const;
protected:
virtual void writeBegin(boost::uint64_t targetNumPointsToWrite);
virtual void writeBufferBegin(PointBuffer const&);
virtual boost::uint32_t writeBuffer(const PointBuffer&);
virtual void writeBufferEnd(PointBuffer const&);
virtual void writeEnd(boost::uint64_t actualNumPointsWritten);
OutputStreamManager m_streamManager;
private:
LasHeader m_lasHeader;
boost::uint32_t m_numPointsWritten;
SummaryData m_summaryData;
#ifdef PDAL_HAVE_LASZIP
boost::scoped_ptr<LASzipper> m_zipper;
boost::scoped_ptr<ZipPoint> m_zipPoint;
#endif
bool m_headerInitialized;
boost::uint64_t m_streamOffset; // the first byte of the LAS file
void setOptions();
bool doForwardThisMetadata(std::string const& name) const;
void setVLRsFromMetadata(LasHeader& header, Metadata const& metadata, Options const& opts);
Writer& operator=(const Writer&); // not implemented
Writer(const Writer&); // not implemented
};
}
}
} // namespaces
#endif
<commit_msg>a method for fetching a default or specified metadata option value -- this maybe should be on Options:: too<commit_after>/******************************************************************************
* Copyright (c) 2011, Michael P. Gerlek (mpg@flaxen.com)
*
* 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 Hobu, Inc. or Flaxen Geo Consulting 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 INCLUDED_DRIVERS_LAS_WRITER_HPP
#define INCLUDED_DRIVERS_LAS_WRITER_HPP
#include <pdal/Writer.hpp>
#include <pdal/drivers/las/Support.hpp>
#include <pdal/drivers/las/Header.hpp>
#include <pdal/drivers/las/SummaryData.hpp>
#include <pdal/StreamFactory.hpp>
#include <boost/scoped_ptr.hpp>
namespace pdal
{
namespace drivers
{
namespace las
{
//
// supported options:
// <uint32>id
// <bool>debug
// <uint32>verbose
// <string>a_srs
// <bool>compression
// <string>filename [required]
//
class PDAL_DLL Writer : public pdal::Writer
{
public:
SET_STAGE_NAME("drivers.las.writer", "Las Writer")
Writer(Stage& prevStage, const Options&);
Writer(Stage& prevStage, std::ostream*);
virtual ~Writer();
virtual void initialize();
virtual const Options getDefaultOptions() const;
void setFormatVersion(boost::uint8_t majorVersion, boost::uint8_t minorVersion);
void setPointFormat(PointFormat);
void setDate(boost::uint16_t dayOfYear, boost::uint16_t year);
void setProjectId(const boost::uuids::uuid&);
// up to 32 chars (default is "PDAL")
void setSystemIdentifier(const std::string& systemId);
// up to 32 chars (default is "PDAL x.y.z")
void setGeneratingSoftware(const std::string& softwareId);
void setHeaderPadding(boost::uint32_t const& v);
// default false
void setCompressed(bool);
// for dumping
virtual boost::property_tree::ptree toPTree() const;
protected:
virtual void writeBegin(boost::uint64_t targetNumPointsToWrite);
virtual void writeBufferBegin(PointBuffer const&);
virtual boost::uint32_t writeBuffer(const PointBuffer&);
virtual void writeBufferEnd(PointBuffer const&);
virtual void writeEnd(boost::uint64_t actualNumPointsWritten);
OutputStreamManager m_streamManager;
private:
LasHeader m_lasHeader;
boost::uint32_t m_numPointsWritten;
SummaryData m_summaryData;
#ifdef PDAL_HAVE_LASZIP
boost::scoped_ptr<LASzipper> m_zipper;
boost::scoped_ptr<ZipPoint> m_zipPoint;
#endif
bool m_headerInitialized;
boost::uint64_t m_streamOffset; // the first byte of the LAS file
void setOptions();
bool doForwardThisMetadata(std::string const& name) const;
void setVLRsFromMetadata(LasHeader& header, Metadata const& metadata, Options const& opts);
Writer& operator=(const Writer&); // not implemented
Writer(const Writer&); // not implemented
template<typename T>
T getMetadataOption( pdal::Options const& options,
pdal::Metadata const& metadata,
std::string const& name,
T default_value) const
{
boost::optional<std::string> candidate = options.getMetadataOption<std::string>(name);
if (!candidate)
{
return default_value;
}
if (boost::algorithm::iequals(*candidate, "FORWARD"))
{
boost::optional<std::string> m =
metadata.getValueOptional<std::string>(name);
if (m)
{
T v = boost::lexical_cast<T>(*m) ;
return v;
}
}
else
{
T v = boost::lexical_cast<T>(*candidate) ;
return v;
}
return default_value;
}
};
}
}
} // namespaces
#endif
<|endoftext|> |
<commit_before>#ifndef VSMC_UTILITY_STOP_WATCH_HPP
#define VSMC_UTILITY_STOP_WATCH_HPP
#include <vsmc/internal/config.hpp>
#include <vsmc/internal/assert.hpp>
#include <vsmc/internal/defines.hpp>
#include <vsmc/internal/forward.hpp>
#if VSMC_HAS_CXX11LIB_CHRONO
#include <chrono>
namespace vsmc {
class StopWatch
{
public :
typedef std::chrono::high_resolution_clock clock_type;
StopWatch () : elapsed_(0) {}
void start () const
{
start_time_ = clock_type::now();
}
void stop () const
{
clock_type::time_point stop_time = clock_type::now();
elapsed_ += stop_time - start_time_;
}
void reset () const
{
elapsed_ = clock_type::duration(0);
}
double nanoseconds () const
{
return std::chrono::duration_cast<std::chrono::duration<
double, std::nano> >(elapsed_).count();
}
double microseconds () const
{
return std::chrono::duration_cast<std::chrono::duration<
double, std::micro> >(elapsed_).count();
}
double milliseconds () const
{
return std::chrono::duration_cast<std::chrono::duration<
double, std::milli> >(elapsed_).count();
}
double seconds () const
{
return std::chrono::duration_cast<std::chrono::duration<
double, std::ratio<1> > >(elapsed_).count();
}
double minutes () const
{
return std::chrono::duration_cast<std::chrono::duration<
double, std::ratio<60> > >(elapsed_).count();
}
double hours () const
{
return std::chrono::duration_cast<std::chrono::duration<
double, std::ratio<3600> > >(elapsed_).count();
}
private :
mutable clock_type::duration elapsed_;
mutable clock_type::time_point start_time_;
}; // class StopWatch
} // namespace vsmc
#elif defined(__APPLE__) || defined(__MACOSX)
namespace vsmc {
class StopWatch
{
public :
void start () const {}
void stop () const {}
void reset () const {}
double nanoseconds () const { return 0; }
double microseconds () const { return 0; }
double milliseconds () const { return 0; }
double seconds () const { return 0; }
double minutes () const { return 0; }
double hours () const { return 0; }
}; // class StopWatch
} // namespace vsmc
#elif defined(__linux__)
namespace vsmc {
class StopWatch
{
public :
void start () const {}
void stop () const {}
void reset () const {}
double nanoseconds () const { return 0; }
double microseconds () const { return 0; }
double milliseconds () const { return 0; }
double seconds () const { return 0; }
double minutes () const { return 0; }
double hours () const { return 0; }
}; // class StopWatch
} // namespace vsmc
#elif defined(__posix__)
namespace vsmc {
class StopWatch
{
public :
void start () const {}
void stop () const {}
void reset () const {}
double nanoseconds () const { return 0; }
double microseconds () const { return 0; }
double milliseconds () const { return 0; }
double seconds () const { return 0; }
double minutes () const { return 0; }
double hours () const { return 0; }
}; // class StopWatch
} // namespace vsmc
#else // VSMC_HAS_CXX11LIB_CHRONO
namespace vsmc {
class StopWatch
{
public :
void start () const {}
void stop () const {}
void reset () const {}
double nanoseconds () const { return 0; }
double microseconds () const { return 0; }
double milliseconds () const { return 0; }
double seconds () const { return 0; }
double minutes () const { return 0; }
double hours () const { return 0; }
}; // class StopWatch
} // namespace vsmc
#endif // VSMC_HAS_CXX11LIB_CHRONO
#endif // VSMC_UTILITY_STOP_WATCH_HPP
<commit_msg>implement linux clock<commit_after>#ifndef VSMC_UTILITY_STOP_WATCH_HPP
#define VSMC_UTILITY_STOP_WATCH_HPP
#include <vsmc/internal/config.hpp>
#include <vsmc/internal/assert.hpp>
#include <vsmc/internal/defines.hpp>
#include <vsmc/internal/forward.hpp>
#if VSMC_HAS_CXX11LIB_CHRONO
#define VSMC_STOP_WATCH_DEFINED
#include <chrono>
namespace vsmc {
class StopWatch
{
public :
typedef std::chrono::high_resolution_clock clock_type;
StopWatch () : elapsed_(0) {}
void start () const
{
start_time_ = clock_type::now();
}
void stop () const
{
clock_type::time_point stop_time = clock_type::now();
elapsed_ += stop_time - start_time_;
}
void reset () const
{
elapsed_ = clock_type::duration(0);
}
double nanoseconds () const
{
return std::chrono::duration_cast<std::chrono::duration<
double, std::nano> >(elapsed_).count();
}
double microseconds () const
{
return std::chrono::duration_cast<std::chrono::duration<
double, std::micro> >(elapsed_).count();
}
double milliseconds () const
{
return std::chrono::duration_cast<std::chrono::duration<
double, std::milli> >(elapsed_).count();
}
double seconds () const
{
return std::chrono::duration_cast<std::chrono::duration<
double, std::ratio<1> > >(elapsed_).count();
}
double minutes () const
{
return std::chrono::duration_cast<std::chrono::duration<
double, std::ratio<60> > >(elapsed_).count();
}
double hours () const
{
return std::chrono::duration_cast<std::chrono::duration<
double, std::ratio<3600> > >(elapsed_).count();
}
private :
mutable clock_type::duration elapsed_;
mutable clock_type::time_point start_time_;
}; // class StopWatch
} // namespace vsmc
#elif defined(__APPLE__) || defined(__MACOSX)
#define VSMC_STOP_WATCH_DEFINED
namespace vsmc {
class StopWatch
{
public :
void start () const {}
void stop () const {}
void reset () const {}
double nanoseconds () const { return 0; }
double microseconds () const { return 0; }
double milliseconds () const { return 0; }
double seconds () const { return 0; }
double minutes () const { return 0; }
double hours () const { return 0; }
}; // class StopWatch
} // namespace vsmc
#elif defined(__linux__)
#include <time.h>
#include <features.h>
#if defined(_POSIX_C_SOURCE) && _POSIX_C_SOURCE >= 199309L
#define VSMC_STOP_WATCH_DEFINED
namespace vsmc {
class StopWatch
{
public :
StopWatch ()
{
reset();
}
void start () const
{
clock_gettime(CLOCK_REALTIME, &start_time_);
}
void stop () const
{
clock_gettime(CLOCK_REALTIME, &stop_time_);
time_t sec = stop_time_.tv_sec - start_time_.tv_sec;
long nsec = stop_time_.tv_nsec - start_time_.tv_nsec;
elapsed_.tv_sec += sec;
elapsed_.tv_nsec += nsec;
long inc_sec = elapsed_.tv_nsec / ratio_;
elapsed_.tv_sec += static_cast<time_t>(inc_sec);
elapsed_.tv_nsec -= inc_sec * ratio_;
}
void reset () const
{
elapsed_.tv_sec = 0;
elapsed_.tv_nsec = 0;
}
double nanoseconds () const
{
return static_cast<double>(elapsed_.tv_sec) * 1e9 +
static_cast<double>(elapsed_.tv_nsec);
}
double microseconds () const
{
return static_cast<double>(elapsed_.tv_sec) * 1e6 +
static_cast<double>(elapsed_.tv_nsec) / 1e3;
}
double milliseconds () const
{
return static_cast<double>(elapsed_.tv_sec) * 1e3 +
static_cast<double>(elapsed_.tv_nsec) / 1e6;
}
double seconds () const
{
return static_cast<double>(elapsed_.tv_sec) +
static_cast<double>(elapsed_.tv_nsec) / 1e9;
}
double minutes () const
{
return static_cast<double>(elapsed_.tv_sec) / 60.0+
static_cast<double>(elapsed_.tv_nsec) / 1e9 / 60.0;
}
double hours () const
{
return static_cast<double>(elapsed_.tv_sec) / 3600.0+
static_cast<double>(elapsed_.tv_nsec) / 1e9 / 3600.0;
}
private :
mutable timespec elapsed_;
mutable timespec start_time_;
mutable timespec stop_time_;
static const long ratio_ = 1000000000L; // 9 zero
}; // class StopWatch
} // namespace vsmc
#endif // _POSIX_C_SOURCE
#endif // VSMC_HAS_CXX11LIB_CHRONO
#ifndef VSMC_STOP_WATCH_DEFINED
namespace vsmc {
class StopWatch
{
public :
void start () const {}
void stop () const {}
void reset () const {}
double nanoseconds () const { return 0; }
double microseconds () const { return 0; }
double milliseconds () const { return 0; }
double seconds () const { return 0; }
double minutes () const { return 0; }
double hours () const { return 0; }
}; // class StopWatch
} // namespace vsmc
#endif // VSMC_STOP_WATCH_DEFINED
#ifdef VSMC_STOP_WATCH_DEFINED
#undef VSMC_STOP_WATCH_DEFINED
#endif
#endif // VSMC_UTILITY_STOP_WATCH_HPP
<|endoftext|> |
<commit_before>/***************************************************************************
* Copyright (c) Johan Mabille, Sylvain Corlay, Wolf Vollprecht and *
* Martin Renou *
* Copyright (c) QuantStack *
* *
* Distributed under the terms of the BSD 3-Clause License. *
* *
* The full license is in the file LICENSE, distributed with this software. *
****************************************************************************/
#ifndef XSIMD_UTILS_HPP
#define XSIMD_UTILS_HPP
#include <complex>
#include <cstdint>
#include <type_traits>
#ifdef XSIMD_ENABLE_XTL_COMPLEX
#include "xtl/xcomplex.hpp"
#endif
namespace xsimd
{
template <class T, size_t N>
class batch;
template <class T, std::size_t N>
class batch_bool;
/**************
* as_integer *
**************/
template <class T>
struct as_integer : std::make_signed<T>
{
};
template <>
struct as_integer<float>
{
using type = int32_t;
};
template <>
struct as_integer<double>
{
using type = int64_t;
};
template <class T, std::size_t N>
struct as_integer<batch<T, N>>
{
using type = batch<typename as_integer<T>::type, N>;
};
template <class T>
using as_integer_t = typename as_integer<T>::type;
/***********************
* as_unsigned_integer *
***********************/
template <class T>
struct as_unsigned_integer : std::make_unsigned<T>
{
};
template <>
struct as_unsigned_integer<float>
{
using type = uint32_t;
};
template <>
struct as_unsigned_integer<double>
{
using type = uint64_t;
};
template <class T, std::size_t N>
struct as_unsigned_integer<batch<T, N>>
{
using type = batch<typename as_unsigned_integer<T>::type, N>;
};
template <class T>
using as_unsigned_integer_t = typename as_unsigned_integer<T>::type;
/******************
* flip_sign_type *
******************/
namespace detail
{
template <class T, bool is_signed>
struct flipped_sign_type_impl : std::make_signed<T>
{
};
template <class T>
struct flipped_sign_type_impl<T, true> : std::make_unsigned<T>
{
};
}
template <class T>
struct flipped_sign_type
: detail::flipped_sign_type_impl<T, std::is_signed<T>::value>
{
};
template <class T>
using flipped_sign_type_t = typename flipped_sign_type<T>::type;
/***********
* as_float *
************/
template <class T>
struct as_float;
template <>
struct as_float<int32_t>
{
using type = float;
};
template <>
struct as_float<int64_t>
{
using type = double;
};
template <class T, std::size_t N>
struct as_float<batch<T, N>>
{
using type = batch<typename as_float<T>::type, N>;
};
template <class T>
using as_float_t = typename as_float<T>::type;
/**************
* as_logical *
**************/
template <class T>
struct as_logical;
template <class T, std::size_t N>
struct as_logical<batch<T, N>>
{
using type = batch_bool<T, N>;
};
template <class T>
using as_logical_t = typename as_logical<T>::type;
/********************
* primitive caster *
********************/
namespace detail
{
template <class UI, class I, class F>
union generic_caster {
UI ui;
I i;
F f;
constexpr generic_caster(UI t)
: ui(t) {}
constexpr generic_caster(I t)
: i(t) {}
constexpr generic_caster(F t)
: f(t) {}
};
using caster32_t = generic_caster<uint32_t, int32_t, float>;
using caster64_t = generic_caster<uint64_t, int64_t, double>;
template <class T>
struct caster;
template <>
struct caster<float>
{
using type = caster32_t;
};
template <>
struct caster<double>
{
using type = caster64_t;
};
template <class T>
using caster_t = typename caster<T>::type;
}
/****************************
* to/from_unsigned_integer *
****************************/
namespace detail
{
template <typename T>
union unsigned_convertor {
T data;
as_unsigned_integer_t<T> bits;
};
template <typename T>
as_unsigned_integer_t<T> to_unsigned_integer(const T& input) {
unsigned_convertor<T> convertor;
convertor.data = input;
return convertor.bits;
}
template <typename T>
T from_unsigned_integer(const as_unsigned_integer_t<T>& input) {
unsigned_convertor<T> convertor;
convertor.bits = input;
return convertor.data;
}
}
/*****************************************
* Backport of index_sequence from c++14 *
*****************************************/
// TODO: Remove this once we drop C++11 support
namespace detail
{
template <typename T>
struct identity { using type = T; };
#ifdef __cpp_lib_integer_sequence
using std::integer_sequence;
using std::index_sequence;
using std::make_index_sequence;
using std::index_sequence_for;
#else
template <typename T, T... Is>
struct integer_sequence {
using value_type = T;
static constexpr std::size_t size() noexcept { return sizeof...(Is); }
};
template <std::size_t... Is>
using index_sequence = integer_sequence<std::size_t, Is...>;
template <typename Lhs, typename Rhs>
struct make_index_sequence_concat;
template <std::size_t... Lhs, std::size_t... Rhs>
struct make_index_sequence_concat<index_sequence<Lhs...>,
index_sequence<Rhs...>>
: identity<index_sequence<Lhs..., (sizeof...(Lhs) + Rhs)...>> {};
template <std::size_t N>
struct make_index_sequence_impl;
template <std::size_t N>
using make_index_sequence = typename make_index_sequence_impl<N>::type;
template <std::size_t N>
struct make_index_sequence_impl
: make_index_sequence_concat<make_index_sequence<N / 2>,
make_index_sequence<N - (N / 2)>> {};
template <>
struct make_index_sequence_impl<0> : identity<index_sequence<>> {};
template <>
struct make_index_sequence_impl<1> : identity<index_sequence<0>> {};
template <typename... Ts>
using index_sequence_for = make_index_sequence<sizeof...(Ts)>;
#endif
}
#define XSIMD_MACRO_UNROLL_BINARY(FUNC) \
constexpr std::size_t size = simd_batch_traits<batch_type>::size; \
using value_type = typename simd_batch_traits<batch_type>::value_type; \
alignas(simd_batch_traits<batch_type>::align) value_type tmp_lhs[size], tmp_rhs[size], tmp_res[size]; \
lhs.store_aligned(tmp_lhs); \
rhs.store_aligned(tmp_rhs); \
unroller<size>([&](std::size_t i) { \
tmp_res[i] = tmp_lhs[i] FUNC tmp_rhs[i]; \
}); \
return batch_type(&tmp_res[0], aligned_mode());
template <class F, std::size_t... I>
inline void unroller_impl(F&& f, detail::index_sequence<I...>)
{
static_cast<void>(std::initializer_list<int>{(f(I), 0)...});
}
template <std::size_t N, class F>
inline void unroller(F&& f)
{
unroller_impl(f, detail::make_index_sequence<N>{});
}
/*****************************************
* Supplementary std::array constructors *
*****************************************/
namespace detail
{
// std::array constructor from scalar value ("broadcast")
template <typename T, std::size_t... Is>
constexpr std::array<T, sizeof...(Is)>
array_from_scalar_impl(const T& scalar, index_sequence<Is...>) {
// You can safely ignore this silly ternary, the "scalar" is all
// that matters. The rest is just a dirty workaround...
return std::array<T, sizeof...(Is)>{ (Is+1) ? scalar : T() ... };
}
template <typename T, std::size_t N>
constexpr std::array<T, N>
array_from_scalar(const T& scalar) {
return array_from_scalar_impl(scalar, make_index_sequence<N>());
}
// std::array constructor from C-style pointer (handled as an array)
template <typename T, std::size_t... Is>
constexpr std::array<T, sizeof...(Is)>
array_from_pointer_impl(const T* c_array, index_sequence<Is...>) {
return std::array<T, sizeof...(Is)>{ c_array[Is]... };
}
template <typename T, std::size_t N>
constexpr std::array<T, N>
array_from_pointer(const T* c_array) {
return array_from_pointer_impl(c_array, make_index_sequence<N>());
}
}
/************************
* is_array_initializer *
************************/
namespace detail
{
template <bool...> struct bool_pack;
template <bool... bs>
using all_true = std::is_same<
bool_pack<bs..., true>, bool_pack<true, bs...>
>;
template <typename T, typename... Args>
using is_all_convertible = all_true<std::is_convertible<Args, T>::value...>;
template <typename T, std::size_t N, typename... Args>
using is_array_initializer = std::enable_if<
(sizeof...(Args) == N) && is_all_convertible<T, Args...>::value
>;
// Check that a variadic argument pack is a list of N values of type T,
// as usable for instantiating a value of type std::array<T, N>.
template <typename T, std::size_t N, typename... Args>
using is_array_initializer_t = typename is_array_initializer<T, N, Args...>::type;
}
/**************
* is_complex *
**************/
// This is used in both xsimd_complex_base.hpp and xsimd_traits.hpp
// However xsimd_traits.hpp indirectly includes xsimd_complex_base.hpp
// so we cannot define is_complex in xsimd_traits.hpp. Besides, if
// no file defining batches is included, we still need this definition
// in xsimd_traits.hpp, so let's define it here.
namespace detail
{
template <class T>
struct is_complex : std::false_type
{
};
template <class T>
struct is_complex<std::complex<T>> : std::true_type
{
};
#ifdef XSIMD_ENABLE_XTL_COMPLEX
template <class T, bool i3ec>
struct is_complex<xtl::xcomplex<T, T, i3ec>> : std::true_type
{
};
#endif
}
}
#endif
<commit_msg>xsimd_utils.hpp: Renamed a shadowing variable inside a macro<commit_after>/***************************************************************************
* Copyright (c) Johan Mabille, Sylvain Corlay, Wolf Vollprecht and *
* Martin Renou *
* Copyright (c) QuantStack *
* *
* Distributed under the terms of the BSD 3-Clause License. *
* *
* The full license is in the file LICENSE, distributed with this software. *
****************************************************************************/
#ifndef XSIMD_UTILS_HPP
#define XSIMD_UTILS_HPP
#include <complex>
#include <cstdint>
#include <type_traits>
#ifdef XSIMD_ENABLE_XTL_COMPLEX
#include "xtl/xcomplex.hpp"
#endif
namespace xsimd
{
template <class T, size_t N>
class batch;
template <class T, std::size_t N>
class batch_bool;
/**************
* as_integer *
**************/
template <class T>
struct as_integer : std::make_signed<T>
{
};
template <>
struct as_integer<float>
{
using type = int32_t;
};
template <>
struct as_integer<double>
{
using type = int64_t;
};
template <class T, std::size_t N>
struct as_integer<batch<T, N>>
{
using type = batch<typename as_integer<T>::type, N>;
};
template <class T>
using as_integer_t = typename as_integer<T>::type;
/***********************
* as_unsigned_integer *
***********************/
template <class T>
struct as_unsigned_integer : std::make_unsigned<T>
{
};
template <>
struct as_unsigned_integer<float>
{
using type = uint32_t;
};
template <>
struct as_unsigned_integer<double>
{
using type = uint64_t;
};
template <class T, std::size_t N>
struct as_unsigned_integer<batch<T, N>>
{
using type = batch<typename as_unsigned_integer<T>::type, N>;
};
template <class T>
using as_unsigned_integer_t = typename as_unsigned_integer<T>::type;
/******************
* flip_sign_type *
******************/
namespace detail
{
template <class T, bool is_signed>
struct flipped_sign_type_impl : std::make_signed<T>
{
};
template <class T>
struct flipped_sign_type_impl<T, true> : std::make_unsigned<T>
{
};
}
template <class T>
struct flipped_sign_type
: detail::flipped_sign_type_impl<T, std::is_signed<T>::value>
{
};
template <class T>
using flipped_sign_type_t = typename flipped_sign_type<T>::type;
/***********
* as_float *
************/
template <class T>
struct as_float;
template <>
struct as_float<int32_t>
{
using type = float;
};
template <>
struct as_float<int64_t>
{
using type = double;
};
template <class T, std::size_t N>
struct as_float<batch<T, N>>
{
using type = batch<typename as_float<T>::type, N>;
};
template <class T>
using as_float_t = typename as_float<T>::type;
/**************
* as_logical *
**************/
template <class T>
struct as_logical;
template <class T, std::size_t N>
struct as_logical<batch<T, N>>
{
using type = batch_bool<T, N>;
};
template <class T>
using as_logical_t = typename as_logical<T>::type;
/********************
* primitive caster *
********************/
namespace detail
{
template <class UI, class I, class F>
union generic_caster {
UI ui;
I i;
F f;
constexpr generic_caster(UI t)
: ui(t) {}
constexpr generic_caster(I t)
: i(t) {}
constexpr generic_caster(F t)
: f(t) {}
};
using caster32_t = generic_caster<uint32_t, int32_t, float>;
using caster64_t = generic_caster<uint64_t, int64_t, double>;
template <class T>
struct caster;
template <>
struct caster<float>
{
using type = caster32_t;
};
template <>
struct caster<double>
{
using type = caster64_t;
};
template <class T>
using caster_t = typename caster<T>::type;
}
/****************************
* to/from_unsigned_integer *
****************************/
namespace detail
{
template <typename T>
union unsigned_convertor {
T data;
as_unsigned_integer_t<T> bits;
};
template <typename T>
as_unsigned_integer_t<T> to_unsigned_integer(const T& input) {
unsigned_convertor<T> convertor;
convertor.data = input;
return convertor.bits;
}
template <typename T>
T from_unsigned_integer(const as_unsigned_integer_t<T>& input) {
unsigned_convertor<T> convertor;
convertor.bits = input;
return convertor.data;
}
}
/*****************************************
* Backport of index_sequence from c++14 *
*****************************************/
// TODO: Remove this once we drop C++11 support
namespace detail
{
template <typename T>
struct identity { using type = T; };
#ifdef __cpp_lib_integer_sequence
using std::integer_sequence;
using std::index_sequence;
using std::make_index_sequence;
using std::index_sequence_for;
#else
template <typename T, T... Is>
struct integer_sequence {
using value_type = T;
static constexpr std::size_t size() noexcept { return sizeof...(Is); }
};
template <std::size_t... Is>
using index_sequence = integer_sequence<std::size_t, Is...>;
template <typename Lhs, typename Rhs>
struct make_index_sequence_concat;
template <std::size_t... Lhs, std::size_t... Rhs>
struct make_index_sequence_concat<index_sequence<Lhs...>,
index_sequence<Rhs...>>
: identity<index_sequence<Lhs..., (sizeof...(Lhs) + Rhs)...>> {};
template <std::size_t N>
struct make_index_sequence_impl;
template <std::size_t N>
using make_index_sequence = typename make_index_sequence_impl<N>::type;
template <std::size_t N>
struct make_index_sequence_impl
: make_index_sequence_concat<make_index_sequence<N / 2>,
make_index_sequence<N - (N / 2)>> {};
template <>
struct make_index_sequence_impl<0> : identity<index_sequence<>> {};
template <>
struct make_index_sequence_impl<1> : identity<index_sequence<0>> {};
template <typename... Ts>
using index_sequence_for = make_index_sequence<sizeof...(Ts)>;
#endif
}
#define XSIMD_MACRO_UNROLL_BINARY(FUNC) \
constexpr std::size_t size = simd_batch_traits<batch_type>::size; \
using tmp_value_type = typename simd_batch_traits<batch_type>::value_type; \
alignas(simd_batch_traits<batch_type>::align) tmp_value_type tmp_lhs[size], tmp_rhs[size], tmp_res[size]; \
lhs.store_aligned(tmp_lhs); \
rhs.store_aligned(tmp_rhs); \
unroller<size>([&](std::size_t i) { \
tmp_res[i] = tmp_lhs[i] FUNC tmp_rhs[i]; \
}); \
return batch_type(&tmp_res[0], aligned_mode());
template <class F, std::size_t... I>
inline void unroller_impl(F&& f, detail::index_sequence<I...>)
{
static_cast<void>(std::initializer_list<int>{(f(I), 0)...});
}
template <std::size_t N, class F>
inline void unroller(F&& f)
{
unroller_impl(f, detail::make_index_sequence<N>{});
}
/*****************************************
* Supplementary std::array constructors *
*****************************************/
namespace detail
{
// std::array constructor from scalar value ("broadcast")
template <typename T, std::size_t... Is>
constexpr std::array<T, sizeof...(Is)>
array_from_scalar_impl(const T& scalar, index_sequence<Is...>) {
// You can safely ignore this silly ternary, the "scalar" is all
// that matters. The rest is just a dirty workaround...
return std::array<T, sizeof...(Is)>{ (Is+1) ? scalar : T() ... };
}
template <typename T, std::size_t N>
constexpr std::array<T, N>
array_from_scalar(const T& scalar) {
return array_from_scalar_impl(scalar, make_index_sequence<N>());
}
// std::array constructor from C-style pointer (handled as an array)
template <typename T, std::size_t... Is>
constexpr std::array<T, sizeof...(Is)>
array_from_pointer_impl(const T* c_array, index_sequence<Is...>) {
return std::array<T, sizeof...(Is)>{ c_array[Is]... };
}
template <typename T, std::size_t N>
constexpr std::array<T, N>
array_from_pointer(const T* c_array) {
return array_from_pointer_impl(c_array, make_index_sequence<N>());
}
}
/************************
* is_array_initializer *
************************/
namespace detail
{
template <bool...> struct bool_pack;
template <bool... bs>
using all_true = std::is_same<
bool_pack<bs..., true>, bool_pack<true, bs...>
>;
template <typename T, typename... Args>
using is_all_convertible = all_true<std::is_convertible<Args, T>::value...>;
template <typename T, std::size_t N, typename... Args>
using is_array_initializer = std::enable_if<
(sizeof...(Args) == N) && is_all_convertible<T, Args...>::value
>;
// Check that a variadic argument pack is a list of N values of type T,
// as usable for instantiating a value of type std::array<T, N>.
template <typename T, std::size_t N, typename... Args>
using is_array_initializer_t = typename is_array_initializer<T, N, Args...>::type;
}
/**************
* is_complex *
**************/
// This is used in both xsimd_complex_base.hpp and xsimd_traits.hpp
// However xsimd_traits.hpp indirectly includes xsimd_complex_base.hpp
// so we cannot define is_complex in xsimd_traits.hpp. Besides, if
// no file defining batches is included, we still need this definition
// in xsimd_traits.hpp, so let's define it here.
namespace detail
{
template <class T>
struct is_complex : std::false_type
{
};
template <class T>
struct is_complex<std::complex<T>> : std::true_type
{
};
#ifdef XSIMD_ENABLE_XTL_COMPLEX
template <class T, bool i3ec>
struct is_complex<xtl::xcomplex<T, T, i3ec>> : std::true_type
{
};
#endif
}
}
#endif
<|endoftext|> |
<commit_before>// (C) Copyright Gennadiy Rozental 2001-2014.
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
// See http://www.boost.org/libs/test for the library home page.
// Boost.Test
#include <boost/test/unit_test.hpp>
#include <boost/test/tools/floating_point_comparison.hpp>
#include <boost/test/parameterized_test.hpp>
using namespace boost::unit_test;
// BOOST
#include <boost/functional.hpp>
#include <boost/static_assert.hpp>
#include <boost/mem_fn.hpp>
#include <boost/bind.hpp>
// STL
#include <string>
#include <stdexcept>
#include <algorithm>
#include <functional>
#include <iostream>
#include <memory>
#include <list>
//____________________________________________________________________________//
template<int n>
struct power_of_10 {
BOOST_STATIC_CONSTANT( unsigned long, value = 10*power_of_10<n-1>::value );
};
template<>
struct power_of_10<0> {
BOOST_STATIC_CONSTANT( unsigned long, value = 1 );
};
//____________________________________________________________________________//
template<int AlphabetSize>
class hash_function {
public:
BOOST_STATIC_ASSERT( AlphabetSize <= 5 );
explicit hash_function( std::string const& alphabet )
: m_alphabet( alphabet )
{
if( m_alphabet.size() != AlphabetSize )
throw std::runtime_error( "Wrong alphabet size" );
std::sort( m_alphabet.begin(), m_alphabet.end() );
if( std::adjacent_find( m_alphabet.begin(), m_alphabet.end() ) != m_alphabet.end() )
throw std::logic_error( "Duplicate characters in alphabet" );
}
unsigned long operator()( std::string const& arg )
{
m_result = 0;
if( arg.length() > 8 )
throw std::runtime_error( "Wrong argument size" );
std::string::const_iterator it = std::find_if( arg.begin(), arg.end(),
std::bind1st( boost::mem_fun( &hash_function::helper_ ), this ) );
if( it != arg.end() )
throw std::out_of_range( std::string( "Invalid character " ) + *it );
return m_result;
}
private:
bool helper_( char c )
{
std::string::const_iterator it = std::find( m_alphabet.begin(), m_alphabet.end(), c );
if( it == m_alphabet.end() )
return true;
m_result += power_of_10_( it - m_alphabet.begin() );
return false;
}
unsigned long power_of_10_( int i ) {
switch( i ) {
case 0: return power_of_10<0>::value;
case 1: return power_of_10<1>::value;
case 2: return power_of_10<2>::value;
case 3: return power_of_10<3>::value;
case 4: return power_of_10<4>::value;
default: return 0;
}
}
// Data members
std::string m_alphabet;
unsigned long m_result;
};
//____________________________________________________________________________//
struct hash_function_test_data {
std::string orig_string;
unsigned long exp_value;
friend std::istream& operator>>( std::istream& istr, hash_function_test_data& test_data )
{
std::istream& tmp = istr >> test_data.orig_string;
return !tmp ? tmp : istr >> test_data.exp_value;
}
};
//____________________________________________________________________________//
class hash_function_tester {
public:
explicit hash_function_tester( std::string const& alphabet )
: m_function_under_test( alphabet ) {}
void test( hash_function_test_data const& test_data )
{
if( test_data.exp_value == (unsigned long)-1 )
BOOST_CHECK_THROW( m_function_under_test( test_data.orig_string ), std::runtime_error )
else if( test_data.exp_value == (unsigned long)-2 )
BOOST_CHECK_THROW( m_function_under_test( test_data.orig_string ), std::out_of_range )
else {
BOOST_TEST_MESSAGE( "Testing: " << test_data.orig_string );
BOOST_CHECK_EQUAL( m_function_under_test( test_data.orig_string ), test_data.exp_value );
}
}
private:
hash_function<4> m_function_under_test;
};
//____________________________________________________________________________//
struct massive_hash_function_test : test_suite {
massive_hash_function_test() : test_suite( "massive_hash_function_test" ) {
std::string alphabet;
std::cout << "Enter alphabet (4 characters without delimeters)\n";
std::cin >> alphabet;
boost::shared_ptr<hash_function_tester> instance( new hash_function_tester( alphabet ) );
std::cout << "\nEnter test data in a format [string] [value] to check correct calculation\n";
std::cout << "Enter test data in a format [string] -1 to check long string validation\n";
std::cout << "Enter test data in a format [string] -2 to check invalid argument string validation\n";
std::list<hash_function_test_data> test_data_store;
while( !std::cin.eof() ) {
hash_function_test_data test_data;
if( !(std::cin >> test_data) )
break;
test_data_store.push_back( test_data );
}
add( make_test_case( &hash_function_tester::test,
"hash_function_tester",
instance,
test_data_store.begin(),
test_data_store.end() ) );
}
};
//____________________________________________________________________________//
test_suite*
init_unit_test_suite( int, char* [] ) {
framework::master_test_suite().p_name.value = "Unit test example 12";
framework::master_test_suite().add( new massive_hash_function_test );
return 0;
}
//____________________________________________________________________________//
// EOF
<commit_msg>missing semi colons It looks like the proper call is this one (file and line should be specified)<commit_after>// (C) Copyright Gennadiy Rozental 2001-2014.
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
// See http://www.boost.org/libs/test for the library home page.
// Boost.Test
#include <boost/test/unit_test.hpp>
#include <boost/test/tools/floating_point_comparison.hpp>
#include <boost/test/parameterized_test.hpp>
using namespace boost::unit_test;
// BOOST
#include <boost/functional.hpp>
#include <boost/static_assert.hpp>
#include <boost/mem_fn.hpp>
#include <boost/bind.hpp>
// STL
#include <string>
#include <stdexcept>
#include <algorithm>
#include <functional>
#include <iostream>
#include <memory>
#include <list>
//____________________________________________________________________________//
template<int n>
struct power_of_10 {
BOOST_STATIC_CONSTANT( unsigned long, value = 10*power_of_10<n-1>::value );
};
template<>
struct power_of_10<0> {
BOOST_STATIC_CONSTANT( unsigned long, value = 1 );
};
//____________________________________________________________________________//
template<int AlphabetSize>
class hash_function {
public:
BOOST_STATIC_ASSERT( AlphabetSize <= 5 );
explicit hash_function( std::string const& alphabet )
: m_alphabet( alphabet )
{
if( m_alphabet.size() != AlphabetSize )
throw std::runtime_error( "Wrong alphabet size" );
std::sort( m_alphabet.begin(), m_alphabet.end() );
if( std::adjacent_find( m_alphabet.begin(), m_alphabet.end() ) != m_alphabet.end() )
throw std::logic_error( "Duplicate characters in alphabet" );
}
unsigned long operator()( std::string const& arg )
{
m_result = 0;
if( arg.length() > 8 )
throw std::runtime_error( "Wrong argument size" );
std::string::const_iterator it = std::find_if( arg.begin(), arg.end(),
std::bind1st( boost::mem_fun( &hash_function::helper_ ), this ) );
if( it != arg.end() )
throw std::out_of_range( std::string( "Invalid character " ) + *it );
return m_result;
}
private:
bool helper_( char c )
{
std::string::const_iterator it = std::find( m_alphabet.begin(), m_alphabet.end(), c );
if( it == m_alphabet.end() )
return true;
m_result += power_of_10_( it - m_alphabet.begin() );
return false;
}
unsigned long power_of_10_( int i ) {
switch( i ) {
case 0: return power_of_10<0>::value;
case 1: return power_of_10<1>::value;
case 2: return power_of_10<2>::value;
case 3: return power_of_10<3>::value;
case 4: return power_of_10<4>::value;
default: return 0;
}
}
// Data members
std::string m_alphabet;
unsigned long m_result;
};
//____________________________________________________________________________//
struct hash_function_test_data {
std::string orig_string;
unsigned long exp_value;
friend std::istream& operator>>( std::istream& istr, hash_function_test_data& test_data )
{
std::istream& tmp = istr >> test_data.orig_string;
return !tmp ? tmp : istr >> test_data.exp_value;
}
};
//____________________________________________________________________________//
class hash_function_tester {
public:
explicit hash_function_tester( std::string const& alphabet )
: m_function_under_test( alphabet ) {}
void test( hash_function_test_data const& test_data )
{
if( test_data.exp_value == (unsigned long)-1 )
BOOST_CHECK_THROW( m_function_under_test( test_data.orig_string ), std::runtime_error );
else if( test_data.exp_value == (unsigned long)-2 )
BOOST_CHECK_THROW( m_function_under_test( test_data.orig_string ), std::out_of_range );
else {
BOOST_TEST_MESSAGE( "Testing: " << test_data.orig_string );
BOOST_CHECK_EQUAL( m_function_under_test( test_data.orig_string ), test_data.exp_value );
}
}
private:
hash_function<4> m_function_under_test;
};
//____________________________________________________________________________//
struct massive_hash_function_test : test_suite {
massive_hash_function_test() : test_suite( "massive_hash_function_test" ) {
std::string alphabet;
std::cout << "Enter alphabet (4 characters without delimeters)\n";
std::cin >> alphabet;
boost::shared_ptr<hash_function_tester> instance( new hash_function_tester( alphabet ) );
std::cout << "\nEnter test data in a format [string] [value] to check correct calculation\n";
std::cout << "Enter test data in a format [string] -1 to check long string validation\n";
std::cout << "Enter test data in a format [string] -2 to check invalid argument string validation\n";
std::list<hash_function_test_data> test_data_store;
while( !std::cin.eof() ) {
hash_function_test_data test_data;
if( !(std::cin >> test_data) )
break;
test_data_store.push_back( test_data );
}
add( make_test_case( &hash_function_tester::test,
"hash_function_tester",
__FILE__,
__LINE__,
instance,
test_data_store.begin(),
test_data_store.end() ) );
}
};
//____________________________________________________________________________//
test_suite*
init_unit_test_suite( int, char* [] ) {
framework::master_test_suite().p_name.value = "Unit test example 12";
framework::master_test_suite().add( new massive_hash_function_test );
return 0;
}
//____________________________________________________________________________//
// EOF
<|endoftext|> |
<commit_before>/*=========================================================================
Program: Visualization Toolkit
Module: vtkXMLHierarchicalBoxDataFileConverter.cxx
Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen
All rights reserved.
See Copyright.txt or http://www.kitware.com/Copyright.htm for details.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE. See the above copyright notice for more information.
=========================================================================*/
#include "vtkXMLHierarchicalBoxDataFileConverter.h"
#include "vtkBoundingBox.h"
#include "vtkImageData.h"
#include "vtkMath.h"
#include "vtkNew.h"
#include "vtkObjectFactory.h"
#include "vtkSmartPointer.h"
#include "vtkXMLDataElement.h"
#include "vtkXMLDataParser.h"
#include "vtkXMLImageDataReader.h"
#include "vtkStructuredData.h"
#include "vtkExecutive.h"
#include "vtkInformation.h"
#include <string>
#include <set>
#include <map>
#include <vector>
#include <cassert>
vtkStandardNewMacro(vtkXMLHierarchicalBoxDataFileConverter);
//----------------------------------------------------------------------------
vtkXMLHierarchicalBoxDataFileConverter::vtkXMLHierarchicalBoxDataFileConverter()
{
this->InputFileName = 0;
this->OutputFileName = 0;
this->FilePath = 0;
}
//----------------------------------------------------------------------------
vtkXMLHierarchicalBoxDataFileConverter::~vtkXMLHierarchicalBoxDataFileConverter()
{
this->SetInputFileName(NULL);
this->SetOutputFileName(NULL);
this->SetFilePath(NULL);
}
//----------------------------------------------------------------------------
bool vtkXMLHierarchicalBoxDataFileConverter::Convert()
{
if (!this->InputFileName)
{
vtkErrorMacro("Missing InputFileName.");
return false;
}
if (!this->OutputFileName)
{
vtkErrorMacro("Missing OutputFileName.");
return false;
}
vtkSmartPointer<vtkXMLDataElement> dom;
dom.TakeReference(this->ParseXML(this->InputFileName));
if (!dom)
{
return false;
}
// Ensure this file we can convert.
if (dom->GetName() == NULL ||
strcmp(dom->GetName(), "VTKFile") != 0 ||
dom->GetAttribute("type") == NULL ||
strcmp(dom->GetAttribute("type"), "vtkHierarchicalBoxDataSet") != 0 ||
dom->GetAttribute("version") == NULL ||
strcmp(dom->GetAttribute("version"), "1.0") != 0)
{
vtkErrorMacro("Cannot convert the input file: " << this->InputFileName);
return false;
}
dom->SetAttribute("version", "1.1");
dom->SetAttribute("type", "vtkOverlappingAMR");
// locate primary element.
vtkXMLDataElement* ePrimary =
dom->FindNestedElementWithName("vtkHierarchicalBoxDataSet");
if (!ePrimary)
{
vtkErrorMacro("Failed to locate primary element.");
return false;
}
ePrimary->SetName("vtkOverlappingAMR");
// Find the path to this file in case the internal files are
// specified as relative paths.
std::string filePath = this->InputFileName;
std::string::size_type pos = filePath.find_last_of("/\\");
if (pos != filePath.npos)
{
filePath = filePath.substr(0, pos);
}
else
{
filePath = "";
}
this->SetFilePath(filePath.c_str());
// We need origin for level 0, and spacing for all levels.
double origin[3];
double *spacing = NULL;
int gridDescription = this->GetOriginAndSpacing(
ePrimary, origin, spacing);
if (gridDescription < VTK_XY_PLANE || gridDescription > VTK_XYZ_GRID)
{
delete [] spacing;
vtkErrorMacro("Failed to determine origin/spacing/grid description.");
return false;
}
// cout << "Origin: " << origin[0] <<", " << origin[1] << ", " << origin[2]
// << endl;
// cout << "Spacing: " << spacing[0] << ", " << spacing[1] << ", " << spacing[2]
// << endl;
const char* grid_description = "XYZ";
switch (gridDescription)
{
case VTK_XY_PLANE:
grid_description = "XY";
break;
case VTK_XZ_PLANE:
grid_description = "XZ";
break;
case VTK_YZ_PLANE:
grid_description = "YZ";
break;
}
ePrimary->SetAttribute("grid_description", grid_description);
ePrimary->SetVectorAttribute("origin", 3, origin);
// Now iterate over all "<Block>" elements and update them.
for (int cc=0; cc < ePrimary->GetNumberOfNestedElements(); cc++)
{
int level = 0;
vtkXMLDataElement* child = ePrimary->GetNestedElement(cc);
if (child && child->GetName() &&
strcmp(child->GetName(), "Block") == 0 &&
child->GetScalarAttribute("level", level) &&
level >= 0)
{
}
else
{
continue;
}
child->SetVectorAttribute("spacing", 3, &spacing[3*level]);
child->RemoveAttribute("refinement_ratio");
}
delete [] spacing;
// now save the xml out.
dom->PrintXML(this->OutputFileName);
return true;
}
//----------------------------------------------------------------------------
vtkXMLDataElement* vtkXMLHierarchicalBoxDataFileConverter::ParseXML(
const char* fname)
{
assert(fname);
vtkNew<vtkXMLDataParser> parser;
parser->SetFileName(fname);
if (!parser->Parse())
{
vtkErrorMacro("Failed to parse input XML: " << fname);
return NULL;
}
vtkXMLDataElement* element = parser->GetRootElement();
element->Register(this);
return element;
}
//----------------------------------------------------------------------------
int vtkXMLHierarchicalBoxDataFileConverter::GetOriginAndSpacing(
vtkXMLDataElement* ePrimary, double origin[3], double* &spacing)
{
// Build list of filenames for all levels.
std::map<int, std::set<std::string> > filenames;
for (int cc=0; cc < ePrimary->GetNumberOfNestedElements(); cc++)
{
int level = 0;
vtkXMLDataElement* child = ePrimary->GetNestedElement(cc);
if (child && child->GetName() &&
strcmp(child->GetName(), "Block") == 0 &&
child->GetScalarAttribute("level", level) &&
level >= 0)
{
}
else
{
continue;
}
for (int kk=0; kk < child->GetNumberOfNestedElements(); kk++)
{
vtkXMLDataElement* dsElement = child->GetNestedElement(cc);
if (dsElement && dsElement->GetName() &&
strcmp(dsElement->GetName(), "DataSet") == 0 &&
dsElement->GetAttribute("file") != 0)
{
std::string file = dsElement->GetAttribute("file");
if (file.c_str()[0] != '/' && file.c_str()[1] != ':')
{
std::string prefix = this->FilePath;
if (prefix.length())
{
prefix += "/";
}
file = prefix + file;
}
filenames[level].insert(file);
}
}
}
vtkBoundingBox bbox;
int gridDescription = VTK_UNCHANGED;
spacing = new double[3* filenames.size() + 1];
memset(spacing, 0, (3*filenames.size() + 1)*sizeof(double));
// Now read all the datasets at level 0.
for (std::set<std::string>::iterator iter = filenames[0].begin();
iter != filenames[0].end(); ++iter)
{
vtkNew<vtkXMLImageDataReader> imageReader;
imageReader->SetFileName((*iter).c_str());
imageReader->Update();
vtkImageData* image = imageReader->GetOutput();
if (image && vtkMath::AreBoundsInitialized(image->GetBounds()))
{
if (!bbox.IsValid())
{
gridDescription = vtkStructuredData::GetDataDescription(
image->GetDimensions());
}
bbox.AddBounds(image->GetBounds());
}
}
if (bbox.IsValid())
{
bbox.GetMinPoint(origin[0], origin[1], origin[2]);
}
// Read 1 dataset from each level to get information about spacing.
for (std::map<int, std::set<std::string> >::iterator iter =
filenames.begin(); iter != filenames.end(); ++iter)
{
if (iter->second.size() == 0)
{
continue;
}
std::string filename = (*iter->second.begin());
vtkNew<vtkXMLImageDataReader> imageReader;
imageReader->SetFileName(filename.c_str());
imageReader->UpdateInformation();
vtkInformation* outInfo =
imageReader->GetExecutive()->GetOutputInformation(0);
if (outInfo->Has(vtkDataObject::SPACING()))
{
assert(outInfo->Length(vtkDataObject::SPACING()) == 3);
outInfo->Get(vtkDataObject::SPACING(), &spacing[3*iter->first]);
}
}
return gridDescription;
}
//----------------------------------------------------------------------------
void vtkXMLHierarchicalBoxDataFileConverter::PrintSelf(ostream& os, vtkIndent indent)
{
this->Superclass::PrintSelf(os, indent);
os << indent << "InputFileName: "
<< (this->InputFileName? this->InputFileName : "(none)") << endl;
os << indent << "OutputFileName: "
<< (this->OutputFileName? this->OutputFileName : "(none)")<< endl;
}
<commit_msg>BUG: vthb file has the wrong directory.<commit_after>/*=========================================================================
Program: Visualization Toolkit
Module: vtkXMLHierarchicalBoxDataFileConverter.cxx
Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen
All rights reserved.
See Copyright.txt or http://www.kitware.com/Copyright.htm for details.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE. See the above copyright notice for more information.
=========================================================================*/
#include "vtkXMLHierarchicalBoxDataFileConverter.h"
#include "vtkBoundingBox.h"
#include "vtkImageData.h"
#include "vtkMath.h"
#include "vtkNew.h"
#include "vtkObjectFactory.h"
#include "vtkSmartPointer.h"
#include "vtkXMLDataElement.h"
#include "vtkXMLDataParser.h"
#include "vtkXMLImageDataReader.h"
#include "vtkStructuredData.h"
#include "vtksys/SystemTools.hxx"
#include "vtkExecutive.h"
#include "vtkInformation.h"
#include <string>
#include <set>
#include <map>
#include <vector>
#include <cassert>
vtkStandardNewMacro(vtkXMLHierarchicalBoxDataFileConverter);
//----------------------------------------------------------------------------
vtkXMLHierarchicalBoxDataFileConverter::vtkXMLHierarchicalBoxDataFileConverter()
{
this->InputFileName = 0;
this->OutputFileName = 0;
this->FilePath = 0;
}
//----------------------------------------------------------------------------
vtkXMLHierarchicalBoxDataFileConverter::~vtkXMLHierarchicalBoxDataFileConverter()
{
this->SetInputFileName(NULL);
this->SetOutputFileName(NULL);
this->SetFilePath(NULL);
}
//----------------------------------------------------------------------------
bool vtkXMLHierarchicalBoxDataFileConverter::Convert()
{
if (!this->InputFileName)
{
vtkErrorMacro("Missing InputFileName.");
return false;
}
if (!this->OutputFileName)
{
vtkErrorMacro("Missing OutputFileName.");
return false;
}
vtkSmartPointer<vtkXMLDataElement> dom;
dom.TakeReference(this->ParseXML(this->InputFileName));
if (!dom)
{
return false;
}
// Ensure this file we can convert.
if (dom->GetName() == NULL ||
strcmp(dom->GetName(), "VTKFile") != 0 ||
dom->GetAttribute("type") == NULL ||
strcmp(dom->GetAttribute("type"), "vtkHierarchicalBoxDataSet") != 0 ||
dom->GetAttribute("version") == NULL ||
strcmp(dom->GetAttribute("version"), "1.0") != 0)
{
vtkErrorMacro("Cannot convert the input file: " << this->InputFileName);
return false;
}
dom->SetAttribute("version", "1.1");
dom->SetAttribute("type", "vtkOverlappingAMR");
// locate primary element.
vtkXMLDataElement* ePrimary =
dom->FindNestedElementWithName("vtkHierarchicalBoxDataSet");
if (!ePrimary)
{
vtkErrorMacro("Failed to locate primary element.");
return false;
}
ePrimary->SetName("vtkOverlappingAMR");
// Find the path to this file in case the internal files are
// specified as relative paths.
std::string filePath = this->InputFileName;
std::string::size_type pos = filePath.find_last_of("/\\");
if (pos != filePath.npos)
{
filePath = filePath.substr(0, pos);
}
else
{
filePath = "";
}
this->SetFilePath(filePath.c_str());
// We need origin for level 0, and spacing for all levels.
double origin[3];
double *spacing = NULL;
int gridDescription = this->GetOriginAndSpacing(
ePrimary, origin, spacing);
if (gridDescription < VTK_XY_PLANE || gridDescription > VTK_XYZ_GRID)
{
delete [] spacing;
vtkErrorMacro("Failed to determine origin/spacing/grid description.");
return false;
}
// cout << "Origin: " << origin[0] <<", " << origin[1] << ", " << origin[2]
// << endl;
// cout << "Spacing: " << spacing[0] << ", " << spacing[1] << ", " << spacing[2]
// << endl;
const char* grid_description = "XYZ";
switch (gridDescription)
{
case VTK_XY_PLANE:
grid_description = "XY";
break;
case VTK_XZ_PLANE:
grid_description = "XZ";
break;
case VTK_YZ_PLANE:
grid_description = "YZ";
break;
}
ePrimary->SetAttribute("grid_description", grid_description);
ePrimary->SetVectorAttribute("origin", 3, origin);
// Now iterate over all "<Block>" elements and update them.
for (int cc=0; cc < ePrimary->GetNumberOfNestedElements(); cc++)
{
int level = 0;
vtkXMLDataElement* block = ePrimary->GetNestedElement(cc);
// iterate over all <DataSet> inside the current block
// and replace the folder for the file attribute.
for (int i = 0; i < block->GetNumberOfNestedElements(); ++i)
{
vtkXMLDataElement* dataset = block->GetNestedElement(i);
std::string file(dataset->GetAttribute("file"));
std::string fileNoDir (vtksys::SystemTools::GetFilenameName(file));
std::string dir (
vtksys::SystemTools::GetFilenameWithoutLastExtension(
this->OutputFileName));
dataset->SetAttribute("file", (dir + '/' + fileNoDir).c_str());
}
if (block && block->GetName() &&
strcmp(block->GetName(), "Block") == 0 &&
block->GetScalarAttribute("level", level) &&
level >= 0)
{
}
else
{
continue;
}
block->SetVectorAttribute("spacing", 3, &spacing[3*level]);
block->RemoveAttribute("refinement_ratio");
}
delete [] spacing;
// now save the xml out.
dom->PrintXML(this->OutputFileName);
return true;
}
//----------------------------------------------------------------------------
vtkXMLDataElement* vtkXMLHierarchicalBoxDataFileConverter::ParseXML(
const char* fname)
{
assert(fname);
vtkNew<vtkXMLDataParser> parser;
parser->SetFileName(fname);
if (!parser->Parse())
{
vtkErrorMacro("Failed to parse input XML: " << fname);
return NULL;
}
vtkXMLDataElement* element = parser->GetRootElement();
element->Register(this);
return element;
}
//----------------------------------------------------------------------------
int vtkXMLHierarchicalBoxDataFileConverter::GetOriginAndSpacing(
vtkXMLDataElement* ePrimary, double origin[3], double* &spacing)
{
// Build list of filenames for all levels.
std::map<int, std::set<std::string> > filenames;
for (int cc=0; cc < ePrimary->GetNumberOfNestedElements(); cc++)
{
int level = 0;
vtkXMLDataElement* child = ePrimary->GetNestedElement(cc);
if (child && child->GetName() &&
strcmp(child->GetName(), "Block") == 0 &&
child->GetScalarAttribute("level", level) &&
level >= 0)
{
}
else
{
continue;
}
for (int kk=0; kk < child->GetNumberOfNestedElements(); kk++)
{
vtkXMLDataElement* dsElement = child->GetNestedElement(cc);
if (dsElement && dsElement->GetName() &&
strcmp(dsElement->GetName(), "DataSet") == 0 &&
dsElement->GetAttribute("file") != 0)
{
std::string file = dsElement->GetAttribute("file");
if (file.c_str()[0] != '/' && file.c_str()[1] != ':')
{
std::string prefix = this->FilePath;
if (prefix.length())
{
prefix += "/";
}
file = prefix + file;
}
filenames[level].insert(file);
}
}
}
vtkBoundingBox bbox;
int gridDescription = VTK_UNCHANGED;
spacing = new double[3* filenames.size() + 1];
memset(spacing, 0, (3*filenames.size() + 1)*sizeof(double));
// Now read all the datasets at level 0.
for (std::set<std::string>::iterator iter = filenames[0].begin();
iter != filenames[0].end(); ++iter)
{
vtkNew<vtkXMLImageDataReader> imageReader;
imageReader->SetFileName((*iter).c_str());
imageReader->Update();
vtkImageData* image = imageReader->GetOutput();
if (image && vtkMath::AreBoundsInitialized(image->GetBounds()))
{
if (!bbox.IsValid())
{
gridDescription = vtkStructuredData::GetDataDescription(
image->GetDimensions());
}
bbox.AddBounds(image->GetBounds());
}
}
if (bbox.IsValid())
{
bbox.GetMinPoint(origin[0], origin[1], origin[2]);
}
// Read 1 dataset from each level to get information about spacing.
for (std::map<int, std::set<std::string> >::iterator iter =
filenames.begin(); iter != filenames.end(); ++iter)
{
if (iter->second.size() == 0)
{
continue;
}
std::string filename = (*iter->second.begin());
vtkNew<vtkXMLImageDataReader> imageReader;
imageReader->SetFileName(filename.c_str());
imageReader->UpdateInformation();
vtkInformation* outInfo =
imageReader->GetExecutive()->GetOutputInformation(0);
if (outInfo->Has(vtkDataObject::SPACING()))
{
assert(outInfo->Length(vtkDataObject::SPACING()) == 3);
outInfo->Get(vtkDataObject::SPACING(), &spacing[3*iter->first]);
}
}
return gridDescription;
}
//----------------------------------------------------------------------------
void vtkXMLHierarchicalBoxDataFileConverter::PrintSelf(ostream& os, vtkIndent indent)
{
this->Superclass::PrintSelf(os, indent);
os << indent << "InputFileName: "
<< (this->InputFileName? this->InputFileName : "(none)") << endl;
os << indent << "OutputFileName: "
<< (this->OutputFileName? this->OutputFileName : "(none)")<< endl;
}
<|endoftext|> |
<commit_before>// Copyright (c) 2018 RISC Software GmbH
//
// This file was generated by CPACSGen from CPACS XML Schema (c) German Aerospace Center (DLR/SC).
// Do not edit, all changes are lost when files are re-generated.
//
// 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.
#pragma once
#include <boost/optional.hpp>
#include <boost/utility/in_place_factory.hpp>
#include <string>
#include <tixi.h>
#include <vector>
#include "tigl_internal.h"
namespace tigl
{
namespace generated
{
// This class is used in:
// generated from /xsd:schema/xsd:complexType[1]
class CPACSRoot
{
public:
TIGL_EXPORT CPACSRoot();
TIGL_EXPORT virtual ~CPACSRoot();
TIGL_EXPORT virtual void ReadCPACS(const TixiDocumentHandle& tixiHandle, const std::string& xpath);
TIGL_EXPORT virtual void WriteCPACS(const TixiDocumentHandle& tixiHandle, const std::string& xpath) const;
TIGL_EXPORT virtual const int& GetA() const;
TIGL_EXPORT virtual void SetA(const int& value);
TIGL_EXPORT virtual const boost::optional<int>& GetB() const;
TIGL_EXPORT virtual void SetB(const boost::optional<int>& value);
TIGL_EXPORT virtual const int& GetC() const;
TIGL_EXPORT virtual void SetC(const int& value);
TIGL_EXPORT virtual const int& GetD() const;
TIGL_EXPORT virtual void SetD(const int& value);
TIGL_EXPORT virtual const std::vector<int>& GetEs() const;
TIGL_EXPORT virtual std::vector<int>& GetEs();
TIGL_EXPORT virtual const boost::optional<int>& GetF() const;
TIGL_EXPORT virtual void SetF(const boost::optional<int>& value);
TIGL_EXPORT virtual const std::vector<int>& GetGs() const;
TIGL_EXPORT virtual std::vector<int>& GetGs();
TIGL_EXPORT virtual const int& GetH() const;
TIGL_EXPORT virtual void SetH(const int& value);
TIGL_EXPORT virtual const std::vector<int>& GetIs() const;
TIGL_EXPORT virtual std::vector<int>& GetIs();
protected:
int m_a;
boost::optional<int> m_b;
int m_c;
int m_d;
std::vector<int> m_es;
boost::optional<int> m_f;
std::vector<int> m_gs;
int m_h;
std::vector<int> m_is;
private:
CPACSRoot(const CPACSRoot&) = delete;
CPACSRoot& operator=(const CPACSRoot&) = delete;
CPACSRoot(CPACSRoot&&) = delete;
CPACSRoot& operator=(CPACSRoot&&) = delete;
};
} // namespace generated
// Aliases in tigl namespace
using CCPACSRoot = generated::CPACSRoot;
} // namespace tigl
// Copyright (c) 2018 RISC Software GmbH
//
// This file was generated by CPACSGen from CPACS XML Schema (c) German Aerospace Center (DLR/SC).
// Do not edit, all changes are lost when files are re-generated.
//
// Licensed under the Apache License, Version 2.0 (the "License")
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include "CPACSRoot.h"
#include "CTiglError.h"
#include "CTiglLogging.h"
#include "TixiHelper.h"
namespace tigl
{
namespace generated
{
CPACSRoot::CPACSRoot()
: m_a(0)
, m_c(0)
, m_d(0)
, m_h(0)
{
}
CPACSRoot::~CPACSRoot()
{
}
void CPACSRoot::ReadCPACS(const TixiDocumentHandle& tixiHandle, const std::string& xpath)
{
// read element a
if (tixi::TixiCheckElement(tixiHandle, xpath + "/a")) {
m_a = tixi::TixiGetElement<int>(tixiHandle, xpath + "/a");
}
else {
LOG(ERROR) << "Required element a is missing at xpath " << xpath;
}
// read element b
if (tixi::TixiCheckElement(tixiHandle, xpath + "/b")) {
m_b = tixi::TixiGetElement<int>(tixiHandle, xpath + "/b");
}
// read element c
if (tixi::TixiCheckElement(tixiHandle, xpath + "/c")) {
m_c = tixi::TixiGetElement<int>(tixiHandle, xpath + "/c");
}
else {
LOG(ERROR) << "Required element c is missing at xpath " << xpath;
}
// read element d
if (tixi::TixiCheckElement(tixiHandle, xpath + "/d")) {
m_d = tixi::TixiGetElement<int>(tixiHandle, xpath + "/d");
}
else {
LOG(ERROR) << "Required element d is missing at xpath " << xpath;
}
// read element e
if (tixi::TixiCheckElement(tixiHandle, xpath + "/e")) {
tixi::TixiReadElements(tixiHandle, xpath + "/e", m_es, 1, tixi::xsdUnbounded);
}
// read element f
if (tixi::TixiCheckElement(tixiHandle, xpath + "/f")) {
m_f = tixi::TixiGetElement<int>(tixiHandle, xpath + "/f");
}
// read element g
if (tixi::TixiCheckElement(tixiHandle, xpath + "/g")) {
tixi::TixiReadElements(tixiHandle, xpath + "/g", m_gs, 0, tixi::xsdUnbounded);
}
// read element h
if (tixi::TixiCheckElement(tixiHandle, xpath + "/h")) {
m_h = tixi::TixiGetElement<int>(tixiHandle, xpath + "/h");
}
else {
LOG(ERROR) << "Required element h is missing at xpath " << xpath;
}
// read element i
if (tixi::TixiCheckElement(tixiHandle, xpath + "/i")) {
tixi::TixiReadElements(tixiHandle, xpath + "/i", m_is, 1, tixi::xsdUnbounded);
}
}
void CPACSRoot::WriteCPACS(const TixiDocumentHandle& tixiHandle, const std::string& xpath) const
{
// write element a
tixi::TixiCreateElementIfNotExists(tixiHandle, xpath + "/a");
tixi::TixiSaveElement(tixiHandle, xpath + "/a", m_a);
// write element b
if (m_b) {
tixi::TixiCreateElementIfNotExists(tixiHandle, xpath + "/b");
tixi::TixiSaveElement(tixiHandle, xpath + "/b", *m_b);
}
else {
if (tixi::TixiCheckElement(tixiHandle, xpath + "/b")) {
tixi::TixiRemoveElement(tixiHandle, xpath + "/b");
}
}
// write element c
tixi::TixiCreateElementIfNotExists(tixiHandle, xpath + "/c");
tixi::TixiSaveElement(tixiHandle, xpath + "/c", m_c);
// write element d
tixi::TixiCreateElementIfNotExists(tixiHandle, xpath + "/d");
tixi::TixiSaveElement(tixiHandle, xpath + "/d", m_d);
// write element e
tixi::TixiSaveElements(tixiHandle, xpath + "/e", m_es);
// write element f
if (m_f) {
tixi::TixiCreateElementIfNotExists(tixiHandle, xpath + "/f");
tixi::TixiSaveElement(tixiHandle, xpath + "/f", *m_f);
}
else {
if (tixi::TixiCheckElement(tixiHandle, xpath + "/f")) {
tixi::TixiRemoveElement(tixiHandle, xpath + "/f");
}
}
// write element g
tixi::TixiSaveElements(tixiHandle, xpath + "/g", m_gs);
// write element h
tixi::TixiCreateElementIfNotExists(tixiHandle, xpath + "/h");
tixi::TixiSaveElement(tixiHandle, xpath + "/h", m_h);
// write element i
tixi::TixiSaveElements(tixiHandle, xpath + "/i", m_is);
}
const int& CPACSRoot::GetA() const
{
return m_a;
}
void CPACSRoot::SetA(const int& value)
{
m_a = value;
}
const boost::optional<int>& CPACSRoot::GetB() const
{
return m_b;
}
void CPACSRoot::SetB(const boost::optional<int>& value)
{
m_b = value;
}
const int& CPACSRoot::GetC() const
{
return m_c;
}
void CPACSRoot::SetC(const int& value)
{
m_c = value;
}
const int& CPACSRoot::GetD() const
{
return m_d;
}
void CPACSRoot::SetD(const int& value)
{
m_d = value;
}
const std::vector<int>& CPACSRoot::GetEs() const
{
return m_es;
}
std::vector<int>& CPACSRoot::GetEs()
{
return m_es;
}
const boost::optional<int>& CPACSRoot::GetF() const
{
return m_f;
}
void CPACSRoot::SetF(const boost::optional<int>& value)
{
m_f = value;
}
const std::vector<int>& CPACSRoot::GetGs() const
{
return m_gs;
}
std::vector<int>& CPACSRoot::GetGs()
{
return m_gs;
}
const int& CPACSRoot::GetH() const
{
return m_h;
}
void CPACSRoot::SetH(const int& value)
{
m_h = value;
}
const std::vector<int>& CPACSRoot::GetIs() const
{
return m_is;
}
std::vector<int>& CPACSRoot::GetIs()
{
return m_is;
}
} // namespace generated
} // namespace tigl
<commit_msg>fixing reference result for sequence test case<commit_after>// Copyright (c) 2018 RISC Software GmbH
//
// This file was generated by CPACSGen from CPACS XML Schema (c) German Aerospace Center (DLR/SC).
// Do not edit, all changes are lost when files are re-generated.
//
// 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.
#pragma once
#include <boost/optional.hpp>
#include <boost/utility/in_place_factory.hpp>
#include <string>
#include <tixi.h>
#include <vector>
#include "tigl_internal.h"
namespace tigl
{
namespace generated
{
// This class is used in:
// generated from /xsd:schema/xsd:complexType[1]
class CPACSRoot
{
public:
TIGL_EXPORT CPACSRoot();
TIGL_EXPORT virtual ~CPACSRoot();
TIGL_EXPORT virtual void ReadCPACS(const TixiDocumentHandle& tixiHandle, const std::string& xpath);
TIGL_EXPORT virtual void WriteCPACS(const TixiDocumentHandle& tixiHandle, const std::string& xpath) const;
TIGL_EXPORT virtual const int& GetA() const;
TIGL_EXPORT virtual void SetA(const int& value);
TIGL_EXPORT virtual const boost::optional<int>& GetB() const;
TIGL_EXPORT virtual void SetB(const boost::optional<int>& value);
TIGL_EXPORT virtual const int& GetC() const;
TIGL_EXPORT virtual void SetC(const int& value);
TIGL_EXPORT virtual const int& GetD() const;
TIGL_EXPORT virtual void SetD(const int& value);
TIGL_EXPORT virtual const std::vector<int>& GetEs() const;
TIGL_EXPORT virtual std::vector<int>& GetEs();
TIGL_EXPORT virtual const boost::optional<int>& GetF() const;
TIGL_EXPORT virtual void SetF(const boost::optional<int>& value);
TIGL_EXPORT virtual const std::vector<int>& GetGs() const;
TIGL_EXPORT virtual std::vector<int>& GetGs();
TIGL_EXPORT virtual const int& GetH() const;
TIGL_EXPORT virtual void SetH(const int& value);
TIGL_EXPORT virtual const std::vector<int>& GetIs() const;
TIGL_EXPORT virtual std::vector<int>& GetIs();
protected:
int m_a;
boost::optional<int> m_b;
int m_c;
int m_d;
std::vector<int> m_es;
boost::optional<int> m_f;
std::vector<int> m_gs;
int m_h;
std::vector<int> m_is;
private:
CPACSRoot(const CPACSRoot&) = delete;
CPACSRoot& operator=(const CPACSRoot&) = delete;
CPACSRoot(CPACSRoot&&) = delete;
CPACSRoot& operator=(CPACSRoot&&) = delete;
};
} // namespace generated
// Aliases in tigl namespace
using CCPACSRoot = generated::CPACSRoot;
} // namespace tigl
// Copyright (c) 2018 RISC Software GmbH
//
// This file was generated by CPACSGen from CPACS XML Schema (c) German Aerospace Center (DLR/SC).
// Do not edit, all changes are lost when files are re-generated.
//
// Licensed under the Apache License, Version 2.0 (the "License")
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include "CPACSRoot.h"
#include "CTiglError.h"
#include "CTiglLogging.h"
#include "TixiHelper.h"
namespace tigl
{
namespace generated
{
namespace
{
const std::vector<std::string> childElemOrder = { "a", "b", "c", "d", "e", "f", "g", "h", "i" };
}
CPACSRoot::CPACSRoot()
: m_a(0)
, m_c(0)
, m_d(0)
, m_h(0)
{
}
CPACSRoot::~CPACSRoot()
{
}
void CPACSRoot::ReadCPACS(const TixiDocumentHandle& tixiHandle, const std::string& xpath)
{
// read element a
if (tixi::TixiCheckElement(tixiHandle, xpath + "/a")) {
m_a = tixi::TixiGetElement<int>(tixiHandle, xpath + "/a");
}
else {
LOG(ERROR) << "Required element a is missing at xpath " << xpath;
}
// read element b
if (tixi::TixiCheckElement(tixiHandle, xpath + "/b")) {
m_b = tixi::TixiGetElement<int>(tixiHandle, xpath + "/b");
}
// read element c
if (tixi::TixiCheckElement(tixiHandle, xpath + "/c")) {
m_c = tixi::TixiGetElement<int>(tixiHandle, xpath + "/c");
}
else {
LOG(ERROR) << "Required element c is missing at xpath " << xpath;
}
// read element d
if (tixi::TixiCheckElement(tixiHandle, xpath + "/d")) {
m_d = tixi::TixiGetElement<int>(tixiHandle, xpath + "/d");
}
else {
LOG(ERROR) << "Required element d is missing at xpath " << xpath;
}
// read element e
if (tixi::TixiCheckElement(tixiHandle, xpath + "/e")) {
tixi::TixiReadElements(tixiHandle, xpath + "/e", m_es, 1, tixi::xsdUnbounded);
}
// read element f
if (tixi::TixiCheckElement(tixiHandle, xpath + "/f")) {
m_f = tixi::TixiGetElement<int>(tixiHandle, xpath + "/f");
}
// read element g
if (tixi::TixiCheckElement(tixiHandle, xpath + "/g")) {
tixi::TixiReadElements(tixiHandle, xpath + "/g", m_gs, 0, tixi::xsdUnbounded);
}
// read element h
if (tixi::TixiCheckElement(tixiHandle, xpath + "/h")) {
m_h = tixi::TixiGetElement<int>(tixiHandle, xpath + "/h");
}
else {
LOG(ERROR) << "Required element h is missing at xpath " << xpath;
}
// read element i
if (tixi::TixiCheckElement(tixiHandle, xpath + "/i")) {
tixi::TixiReadElements(tixiHandle, xpath + "/i", m_is, 1, tixi::xsdUnbounded);
}
}
void CPACSRoot::WriteCPACS(const TixiDocumentHandle& tixiHandle, const std::string& xpath) const
{
// write element a
tixi::TixiCreateSequenceElementIfNotExists(tixiHandle, xpath + "/a", childElemOrder);
tixi::TixiSaveElement(tixiHandle, xpath + "/a", m_a);
// write element b
if (m_b) {
tixi::TixiCreateSequenceElementIfNotExists(tixiHandle, xpath + "/b", childElemOrder);
tixi::TixiSaveElement(tixiHandle, xpath + "/b", *m_b);
}
else {
if (tixi::TixiCheckElement(tixiHandle, xpath + "/b")) {
tixi::TixiRemoveElement(tixiHandle, xpath + "/b");
}
}
// write element c
tixi::TixiCreateSequenceElementIfNotExists(tixiHandle, xpath + "/c", childElemOrder);
tixi::TixiSaveElement(tixiHandle, xpath + "/c", m_c);
// write element d
tixi::TixiCreateSequenceElementIfNotExists(tixiHandle, xpath + "/d", childElemOrder);
tixi::TixiSaveElement(tixiHandle, xpath + "/d", m_d);
// write element e
tixi::TixiSaveElements(tixiHandle, xpath + "/e", m_es);
// write element f
if (m_f) {
tixi::TixiCreateSequenceElementIfNotExists(tixiHandle, xpath + "/f", childElemOrder);
tixi::TixiSaveElement(tixiHandle, xpath + "/f", *m_f);
}
else {
if (tixi::TixiCheckElement(tixiHandle, xpath + "/f")) {
tixi::TixiRemoveElement(tixiHandle, xpath + "/f");
}
}
// write element g
tixi::TixiSaveElements(tixiHandle, xpath + "/g", m_gs);
// write element h
tixi::TixiCreateSequenceElementIfNotExists(tixiHandle, xpath + "/h", childElemOrder);
tixi::TixiSaveElement(tixiHandle, xpath + "/h", m_h);
// write element i
tixi::TixiSaveElements(tixiHandle, xpath + "/i", m_is);
}
const int& CPACSRoot::GetA() const
{
return m_a;
}
void CPACSRoot::SetA(const int& value)
{
m_a = value;
}
const boost::optional<int>& CPACSRoot::GetB() const
{
return m_b;
}
void CPACSRoot::SetB(const boost::optional<int>& value)
{
m_b = value;
}
const int& CPACSRoot::GetC() const
{
return m_c;
}
void CPACSRoot::SetC(const int& value)
{
m_c = value;
}
const int& CPACSRoot::GetD() const
{
return m_d;
}
void CPACSRoot::SetD(const int& value)
{
m_d = value;
}
const std::vector<int>& CPACSRoot::GetEs() const
{
return m_es;
}
std::vector<int>& CPACSRoot::GetEs()
{
return m_es;
}
const boost::optional<int>& CPACSRoot::GetF() const
{
return m_f;
}
void CPACSRoot::SetF(const boost::optional<int>& value)
{
m_f = value;
}
const std::vector<int>& CPACSRoot::GetGs() const
{
return m_gs;
}
std::vector<int>& CPACSRoot::GetGs()
{
return m_gs;
}
const int& CPACSRoot::GetH() const
{
return m_h;
}
void CPACSRoot::SetH(const int& value)
{
m_h = value;
}
const std::vector<int>& CPACSRoot::GetIs() const
{
return m_is;
}
std::vector<int>& CPACSRoot::GetIs()
{
return m_is;
}
} // namespace generated
} // namespace tigl
<|endoftext|> |
<commit_before>/******************************************************************************
* This file is part of the Gluon Development Platform
* Copyright (C) 2010 Dan Leinir Turthra Jensen <admin@leinir.dk>
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
#include "scriptingcomponent.h"
#include "scriptingcomponentprivate.h"
#include "scriptingengine.h"
#include "game.h"
#include "gameobject.h"
#include "scene.h"
#include <qscriptclass.h>
#include <qscriptvalueiterator.h>
REGISTER_OBJECTTYPE(GluonEngine, ScriptingComponent)
using namespace GluonEngine;
ScriptingComponent::ScriptingComponent(QObject* parent)
: Component(parent)
, d(new ScriptingComponentPrivate)
{
}
ScriptingComponent::ScriptingComponent(const ScriptingComponent& other)
: d(other.d)
{
}
ScriptingComponent::~ScriptingComponent()
{
}
QString
ScriptingComponent::category() const
{
return QString("Game Logic");
}
ScriptingAsset* ScriptingComponent::script() const
{
return d->scriptingAsset;
}
void ScriptingComponent::setScript(GluonEngine::ScriptingAsset* newAsset)
{
d->scriptingAsset = newAsset;
connect(newAsset, SIGNAL(dataChanged()), this, SLOT(scriptAssetUpdated()));
d->scriptObject = ScriptingEngine::instance()->instantiateClass(newAsset);
// Set the convenience objects - this allows users to work in a consistent manner, as this needs to be done a lot
// Technically it could be done by object hierarchy, but consistency is a Good Thing(TM)
QScriptEngine::QObjectWrapOptions wrapOptions = QScriptEngine::AutoCreateDynamicProperties | QScriptEngine::ExcludeDeleteLater;
QScriptEngine::ValueOwnership ownership = QScriptEngine::QtOwnership;
QScriptValue component = ScriptingEngine::instance()->scriptEngine()->newQObject(this, ownership, wrapOptions);
d->scriptObject.setProperty("Component", component);
QScriptValue gameObj = ScriptingEngine::instance()->scriptEngine()->newQObject(gameObject(), ownership, wrapOptions);
d->scriptObject.setProperty("GameObject", gameObj);
QScriptValue sceneObj = ScriptingEngine::instance()->scriptEngine()->newQObject(gameObject()->scene(), ownership, wrapOptions);
d->scriptObject.setProperty("Scene", sceneObj);
QScriptValue game = ScriptingEngine::instance()->scriptEngine()->newQObject(GluonEngine::Game::instance(), ownership, wrapOptions);
d->scriptObject.setProperty("Game", game);
// Lastly, get the functions out so they're easy to call
d->initializeFunction = d->scriptObject.property("initialize");
d->startFunction = d->scriptObject.property("start");
d->updateFunction = d->scriptObject.property("update");
d->drawFunction = d->scriptObject.property("draw");
d->stopFunction = d->scriptObject.property("stop");
d->cleanupFunction = d->scriptObject.property("cleanup");
}
void ScriptingComponent::scriptAssetUpdated()
{
disconnect(this, SLOT(scriptAssetUpdated()));
setScript(this->script());
}
QScriptValue ScriptingComponent::scriptObject()
{
return d->scriptObject;
}
void ScriptingComponent::initialize()
{
if (d->initializeFunction.isFunction())
{
d->initializeFunction.call(d->scriptObject);
if (ScriptingEngine::instance()->scriptEngine()->uncaughtException().isValid())
// This needs to be mapped...
debug(QString("%1: %2")
.arg(ScriptingEngine::instance()->scriptEngine()->uncaughtException().toString())
.arg(ScriptingEngine::instance()->scriptEngine()->uncaughtExceptionBacktrace().join(" ")));
}
GluonEngine::Component::initialize();
}
void ScriptingComponent::start()
{
if (d->startFunction.isFunction())
{
d->startFunction.call(d->scriptObject);
if (ScriptingEngine::instance()->scriptEngine()->uncaughtException().isValid())
// This needs to be mapped...
debug(QString("%1: %2")
.arg(ScriptingEngine::instance()->scriptEngine()->uncaughtException().toString())
.arg(ScriptingEngine::instance()->scriptEngine()->uncaughtExceptionBacktrace().join(" ")));
}
GluonEngine::Component::start();
}
void ScriptingComponent::update(int elapsedMilliseconds)
{
if (d->updateFunction.isFunction())
{
d->updateFunction.call(d->scriptObject, QScriptValueList() << elapsedMilliseconds);
if (ScriptingEngine::instance()->scriptEngine()->uncaughtException().isValid())
// This needs to be mapped...
debug(QString("%1: %2")
.arg(ScriptingEngine::instance()->scriptEngine()->uncaughtException().toString())
.arg(ScriptingEngine::instance()->scriptEngine()->uncaughtExceptionBacktrace().join(" ")));
}
GluonEngine::Component::update(elapsedMilliseconds);
}
void ScriptingComponent::draw(int timeLapse)
{
if (d->drawFunction.isFunction())
{
d->drawFunction.call(d->scriptObject, QScriptValueList() << timeLapse);
if (ScriptingEngine::instance()->scriptEngine()->uncaughtException().isValid())
// This needs to be mapped...
debug(QString("%1: %2")
.arg(ScriptingEngine::instance()->scriptEngine()->uncaughtException().toString())
.arg(ScriptingEngine::instance()->scriptEngine()->uncaughtExceptionBacktrace().join(" ")));
}
GluonEngine::Component::draw();
}
void ScriptingComponent::stop()
{
if (d->stopFunction.isFunction())
{
d->stopFunction.call(d->scriptObject);
if (ScriptingEngine::instance()->scriptEngine()->uncaughtException().isValid())
// This needs to be mapped...
debug(QString("%1: %2")
.arg(ScriptingEngine::instance()->scriptEngine()->uncaughtException().toString())
.arg(ScriptingEngine::instance()->scriptEngine()->uncaughtExceptionBacktrace().join(" ")));
}
GluonEngine::Component::stop();
}
void ScriptingComponent::cleanup()
{
if (d->cleanupFunction.isFunction())
{
d->cleanupFunction.call(d->scriptObject);
if (ScriptingEngine::instance()->scriptEngine()->uncaughtException().isValid())
// This needs to be mapped...
debug(QString("%1: %2")
.arg(ScriptingEngine::instance()->scriptEngine()->uncaughtException().toString())
.arg(ScriptingEngine::instance()->scriptEngine()->uncaughtExceptionBacktrace().join(" ")));
}
GluonEngine::Component::cleanup();
}
#include "scriptingcomponent.moc"
<commit_msg>Add a GameObject accessor object on the ScriptingComponent's scripted object<commit_after>/******************************************************************************
* This file is part of the Gluon Development Platform
* Copyright (C) 2010 Dan Leinir Turthra Jensen <admin@leinir.dk>
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
#include "scriptingcomponent.h"
#include "scriptingcomponentprivate.h"
#include "scriptingengine.h"
#include "game.h"
#include "gameobject.h"
#include "scene.h"
#include <qscriptclass.h>
#include <qscriptvalueiterator.h>
REGISTER_OBJECTTYPE(GluonEngine, ScriptingComponent)
using namespace GluonEngine;
ScriptingComponent::ScriptingComponent(QObject* parent)
: Component(parent)
, d(new ScriptingComponentPrivate)
{
}
ScriptingComponent::ScriptingComponent(const ScriptingComponent& other)
: d(other.d)
{
}
ScriptingComponent::~ScriptingComponent()
{
}
QString
ScriptingComponent::category() const
{
return QString("Game Logic");
}
ScriptingAsset* ScriptingComponent::script() const
{
return d->scriptingAsset;
}
void ScriptingComponent::setScript(GluonEngine::ScriptingAsset* newAsset)
{
d->scriptingAsset = newAsset;
connect(newAsset, SIGNAL(dataChanged()), this, SLOT(scriptAssetUpdated()));
d->scriptObject = ScriptingEngine::instance()->instantiateClass(newAsset);
// Set the convenience objects - this allows users to work in a consistent manner, as this needs to be done a lot
// Technically it could be done by object hierarchy, but consistency is a Good Thing(TM)
QScriptEngine::QObjectWrapOptions wrapOptions = QScriptEngine::AutoCreateDynamicProperties | QScriptEngine::ExcludeDeleteLater;
QScriptEngine::ValueOwnership ownership = QScriptEngine::QtOwnership;
QScriptValue component = ScriptingEngine::instance()->scriptEngine()->newQObject(this, ownership, wrapOptions);
d->scriptObject.setProperty("Component", component);
QScriptValue gameObj = ScriptingEngine::instance()->scriptEngine()->newQObject(gameObject(), ownership, wrapOptions);
d->scriptObject.setProperty("GameObject", gameObj);
QScriptValue sceneObj = ScriptingEngine::instance()->scriptEngine()->newQObject(gameObject()->scene(), ownership, wrapOptions);
d->scriptObject.setProperty("Scene", sceneObj);
QScriptValue gameProjectObj = ScriptingEngine::instance()->scriptEngine()->newQObject(GluonEngine::Game::instance()->gameProject(), ownership, wrapOptions);
d->scriptObject.setProperty("GameProject", gameProjectObj);
QScriptValue game = ScriptingEngine::instance()->scriptEngine()->newQObject(GluonEngine::Game::instance(), ownership, wrapOptions);
d->scriptObject.setProperty("Game", game);
// Lastly, get the functions out so they're easy to call
d->initializeFunction = d->scriptObject.property("initialize");
d->startFunction = d->scriptObject.property("start");
d->updateFunction = d->scriptObject.property("update");
d->drawFunction = d->scriptObject.property("draw");
d->stopFunction = d->scriptObject.property("stop");
d->cleanupFunction = d->scriptObject.property("cleanup");
}
void ScriptingComponent::scriptAssetUpdated()
{
disconnect(this, SLOT(scriptAssetUpdated()));
setScript(this->script());
}
QScriptValue ScriptingComponent::scriptObject()
{
return d->scriptObject;
}
void ScriptingComponent::initialize()
{
if (d->initializeFunction.isFunction())
{
d->initializeFunction.call(d->scriptObject);
if (ScriptingEngine::instance()->scriptEngine()->uncaughtException().isValid())
// This needs to be mapped...
debug(QString("%1: %2")
.arg(ScriptingEngine::instance()->scriptEngine()->uncaughtException().toString())
.arg(ScriptingEngine::instance()->scriptEngine()->uncaughtExceptionBacktrace().join(" ")));
}
GluonEngine::Component::initialize();
}
void ScriptingComponent::start()
{
if (d->startFunction.isFunction())
{
d->startFunction.call(d->scriptObject);
if (ScriptingEngine::instance()->scriptEngine()->uncaughtException().isValid())
// This needs to be mapped...
debug(QString("%1: %2")
.arg(ScriptingEngine::instance()->scriptEngine()->uncaughtException().toString())
.arg(ScriptingEngine::instance()->scriptEngine()->uncaughtExceptionBacktrace().join(" ")));
}
GluonEngine::Component::start();
}
void ScriptingComponent::update(int elapsedMilliseconds)
{
if (d->updateFunction.isFunction())
{
d->updateFunction.call(d->scriptObject, QScriptValueList() << elapsedMilliseconds);
if (ScriptingEngine::instance()->scriptEngine()->uncaughtException().isValid())
// This needs to be mapped...
debug(QString("%1: %2")
.arg(ScriptingEngine::instance()->scriptEngine()->uncaughtException().toString())
.arg(ScriptingEngine::instance()->scriptEngine()->uncaughtExceptionBacktrace().join(" ")));
}
GluonEngine::Component::update(elapsedMilliseconds);
}
void ScriptingComponent::draw(int timeLapse)
{
if (d->drawFunction.isFunction())
{
d->drawFunction.call(d->scriptObject, QScriptValueList() << timeLapse);
if (ScriptingEngine::instance()->scriptEngine()->uncaughtException().isValid())
// This needs to be mapped...
debug(QString("%1: %2")
.arg(ScriptingEngine::instance()->scriptEngine()->uncaughtException().toString())
.arg(ScriptingEngine::instance()->scriptEngine()->uncaughtExceptionBacktrace().join(" ")));
}
GluonEngine::Component::draw();
}
void ScriptingComponent::stop()
{
if (d->stopFunction.isFunction())
{
d->stopFunction.call(d->scriptObject);
if (ScriptingEngine::instance()->scriptEngine()->uncaughtException().isValid())
// This needs to be mapped...
debug(QString("%1: %2")
.arg(ScriptingEngine::instance()->scriptEngine()->uncaughtException().toString())
.arg(ScriptingEngine::instance()->scriptEngine()->uncaughtExceptionBacktrace().join(" ")));
}
GluonEngine::Component::stop();
}
void ScriptingComponent::cleanup()
{
if (d->cleanupFunction.isFunction())
{
d->cleanupFunction.call(d->scriptObject);
if (ScriptingEngine::instance()->scriptEngine()->uncaughtException().isValid())
// This needs to be mapped...
debug(QString("%1: %2")
.arg(ScriptingEngine::instance()->scriptEngine()->uncaughtException().toString())
.arg(ScriptingEngine::instance()->scriptEngine()->uncaughtExceptionBacktrace().join(" ")));
}
GluonEngine::Component::cleanup();
}
#include "scriptingcomponent.moc"
<|endoftext|> |
<commit_before>#include <sstream>
#include <iomanip>
#include "Line.h"
namespace CppChart
{
LineChart::LineChart(const std::vector<DataElement>& d) :
m_anchorColor(sf::Color(88, 172, 250)), m_guideColor(sf::Color(100, 100, 100)),
m_lineColor(sf::Color::Black), m_fillColor(sf::Color::Cyan),
m_anchorSize(8.0f), m_lineThickness(2.0f), m_fill(true),
m_displayGuides(true), m_displayValues(true), m_data(d),
m_gap(0.0f), m_startPos(0.0f), m_max(0.0f),
m_hGuide(true), m_vGuide(true), m_xAxisGuide(true), m_yAxisGuide(true)
{
}
void LineChart::Render()
{
LogFnStart();
float x = m_chartOffsets.x / 2.0f, y = m_chartOffsets.y / 2.0f;
float ratio = (m_chartHeight - m_chartOffsets.y - m_anchorSize - 1.2f * m_axes.labels.fontSize) / m_max;
float item;
m_gap = (m_chartWidth - m_chartOffsets.x) / m_data.size();
float width = (m_chartWidth - 2.0f * m_chartOffsets.x - m_gap * static_cast<float>(m_data.size())) / static_cast<float>(m_data.size());
sf::RectangleShape line;
sf::Vector2f first, second;
sf::Text text, values;
m_fill = true;
if (!m_legend.m_exists)
{
text.setFont(m_axes.labels.font);
text.setColor(m_axes.labels.fontColor);
text.setCharacterSize(m_axes.labels.fontSize);
}
if (m_displayValues)
{
values.setFont(m_axes.labels.font);
values.setCharacterSize(m_axes.labels.fontSize);
}
DrawFillPolygon(ratio, m_gap);
bool isGuide = true;
for (auto data : m_data)
{
item = data.value * ratio;
second = sf::Vector2f(x, m_chartHeight - y - item);
// TODO: Log Function Improvement
// Log("Line : ", second);
line = MakeRect(first, second, m_lineThickness);
line.setFillColor(m_lineColor);
m_chartTexture.draw(line);
first = second;
if (!m_legend.m_exists)
{
text.setString(data.name);
SetTextAtCenter(text, x, m_chartHeight - y - 1.2f * m_axes.labels.fontSize, width + m_gap, m_axes.labels.fontSize);
text.move(sf::Vector2f(-m_gap / 2.0f, 0.0f));
m_chartTexture.draw(text);
}
if (m_displayValues)
{
values.setColor(data.color);
values.setString([&]()
{
std::ostringstream oss;
oss << std::setprecision(2) << data.value;
return oss.str();
}());
SetTextAtCenter(values, x, m_chartHeight - y - item - m_axes.labels.fontSize / 2.0f, width + m_gap, m_axes.labels.fontSize);
values.move(sf::Vector2f(-m_gap / 2.0f, -m_anchorSize - m_axes.labels.fontSize));
if (isGuide)
{
values.move(sf::Vector2f(values.getString().getSize() * m_axes.labels.fontSize / 2.0f, 0.0f));
}
m_chartTexture.draw(values);
}
if (isGuide)
{
DrawAxisGuides(first.x, first.y);
isGuide = false;
}
DrawAxisAnchors(first.x, first.y);
x += m_gap;
}
x = m_chartOffsets.x / 2.0f;
for (auto& data : m_data)
{
item = data.value * ratio;
DrawValueAnchor(x, m_chartHeight - y - item, data.color);
x += m_gap;
}
DrawAxes();
LogFnEnd();
}
void LineChart::DrawAxisAnchors(float x, float y)
{
LogFnStart();
if (m_yAxisGuide)
{
m_anchor.setPosition(sf::Vector2f(m_chartOffsets.x / 2.0f - m_anchorSize / 2.0f, y - m_anchorSize / 2.0f));
m_anchor.setRadius(m_anchorSize / 2.0f);
m_chartTexture.draw(m_anchor);
}
if (m_xAxisGuide)
{
m_anchor.setPosition(sf::Vector2f(x - m_anchorSize / 2.0f, m_chartHeight - m_chartOffsets.y / 2.0f - m_anchorSize / 2.0f - m_axes.labels.fontSize));
m_anchor.setRadius(m_anchorSize / 2.0f);
m_chartTexture.draw(m_anchor);
}
LogFnEnd();
}
void LineChart::DrawValueAnchor(float x, float y, const sf::Color& fillColor)
{
LogFnStart();
m_anchor.setPosition(sf::Vector2f(x - m_anchorSize, y - m_anchorSize));
m_anchor.setRadius(m_anchorSize);
m_anchor.setFillColor(fillColor);
m_chartTexture.draw(m_anchor);
LogFnEnd();
}
void DrawAxisGuides(float, float);
void DrawFillPolygon(float, float);
}
<commit_msg>Implement LineChart::DrawAxisGuides()<commit_after>#include <sstream>
#include <iomanip>
#include "Line.h"
namespace CppChart
{
LineChart::LineChart(const std::vector<DataElement>& d) :
m_anchorColor(sf::Color(88, 172, 250)), m_guideColor(sf::Color(100, 100, 100)),
m_lineColor(sf::Color::Black), m_fillColor(sf::Color::Cyan),
m_anchorSize(8.0f), m_lineThickness(2.0f), m_fill(true),
m_displayGuides(true), m_displayValues(true), m_data(d),
m_gap(0.0f), m_startPos(0.0f), m_max(0.0f),
m_hGuide(true), m_vGuide(true), m_xAxisGuide(true), m_yAxisGuide(true)
{
}
void LineChart::Render()
{
LogFnStart();
float x = m_chartOffsets.x / 2.0f, y = m_chartOffsets.y / 2.0f;
float ratio = (m_chartHeight - m_chartOffsets.y - m_anchorSize - 1.2f * m_axes.labels.fontSize) / m_max;
float item;
m_gap = (m_chartWidth - m_chartOffsets.x) / m_data.size();
float width = (m_chartWidth - 2.0f * m_chartOffsets.x - m_gap * static_cast<float>(m_data.size())) / static_cast<float>(m_data.size());
sf::RectangleShape line;
sf::Vector2f first, second;
sf::Text text, values;
m_fill = true;
if (!m_legend.m_exists)
{
text.setFont(m_axes.labels.font);
text.setColor(m_axes.labels.fontColor);
text.setCharacterSize(m_axes.labels.fontSize);
}
if (m_displayValues)
{
values.setFont(m_axes.labels.font);
values.setCharacterSize(m_axes.labels.fontSize);
}
DrawFillPolygon(ratio, m_gap);
bool isGuide = true;
for (auto data : m_data)
{
item = data.value * ratio;
second = sf::Vector2f(x, m_chartHeight - y - item);
// TODO: Log Function Improvement
// Log("Line : ", second);
line = MakeRect(first, second, m_lineThickness);
line.setFillColor(m_lineColor);
m_chartTexture.draw(line);
first = second;
if (!m_legend.m_exists)
{
text.setString(data.name);
SetTextAtCenter(text, x, m_chartHeight - y - 1.2f * m_axes.labels.fontSize, width + m_gap, m_axes.labels.fontSize);
text.move(sf::Vector2f(-m_gap / 2.0f, 0.0f));
m_chartTexture.draw(text);
}
if (m_displayValues)
{
values.setColor(data.color);
values.setString([&]()
{
std::ostringstream oss;
oss << std::setprecision(2) << data.value;
return oss.str();
}());
SetTextAtCenter(values, x, m_chartHeight - y - item - m_axes.labels.fontSize / 2.0f, width + m_gap, m_axes.labels.fontSize);
values.move(sf::Vector2f(-m_gap / 2.0f, -m_anchorSize - m_axes.labels.fontSize));
if (isGuide)
{
values.move(sf::Vector2f(values.getString().getSize() * m_axes.labels.fontSize / 2.0f, 0.0f));
}
m_chartTexture.draw(values);
}
if (isGuide)
{
DrawAxisGuides(first.x, first.y);
isGuide = false;
}
DrawAxisAnchors(first.x, first.y);
x += m_gap;
}
x = m_chartOffsets.x / 2.0f;
for (auto& data : m_data)
{
item = data.value * ratio;
DrawValueAnchor(x, m_chartHeight - y - item, data.color);
x += m_gap;
}
DrawAxes();
LogFnEnd();
}
void LineChart::DrawAxisAnchors(float x, float y)
{
LogFnStart();
if (m_yAxisGuide)
{
m_anchor.setPosition(sf::Vector2f(m_chartOffsets.x / 2.0f - m_anchorSize / 2.0f, y - m_anchorSize / 2.0f));
m_anchor.setRadius(m_anchorSize / 2.0f);
m_chartTexture.draw(m_anchor);
}
if (m_xAxisGuide)
{
m_anchor.setPosition(sf::Vector2f(x - m_anchorSize / 2.0f, m_chartHeight - m_chartOffsets.y / 2.0f - m_anchorSize / 2.0f - m_axes.labels.fontSize));
m_anchor.setRadius(m_anchorSize / 2.0f);
m_chartTexture.draw(m_anchor);
}
LogFnEnd();
}
void LineChart::DrawValueAnchor(float x, float y, const sf::Color& fillColor)
{
LogFnStart();
m_anchor.setPosition(sf::Vector2f(x - m_anchorSize, y - m_anchorSize));
m_anchor.setRadius(m_anchorSize);
m_anchor.setFillColor(fillColor);
m_chartTexture.draw(m_anchor);
LogFnEnd();
}
void LineChart::DrawAxisGuides(float x, float y)
{
LogFnStart();
if (m_vGuide)
{
DrawDottedLine(&m_chartTexture, sf::Vector2f(x, y),
sf::Vector2f(x, m_chartHeight - m_chartOffsets.y / 2.0f - m_axes.labels.fontSize), m_guideColor);
}
if (m_hGuide)
{
DrawDottedLine(&m_chartTexture, sf::Vector2f(m_chartOffsets.x / 2.0f, y),
sf::Vector2f(x, y), m_guideColor);
}
LogFnEnd();
}
void DrawFillPolygon(float, float);
}
<|endoftext|> |
<commit_before>#include "bmp.h"
#include <cstdint>
#include <cstdlib>
#include <pthread.h>
#include <queue>
#include "tracer.h"
#include "vector.h"
#include "color.h"
#include "sphere.h"
#include "plane.h"
#include "lambertian.h"
#include "metallic.h"
#include "dielectric.h"
using namespace gml;
const int NUM_THREADS = 4;
struct AppParams {
Tracer rt;
int numBounces = 4;
BMP * bmp = NULL;
int w = 0;
int h = 0;
bool singleThreaded = false;
bool useJobs = true;
// for jobs use only
bool allJobsQueued = false;
std::queue<int> jobQueue;
pthread_mutex_t jobQueue_mutex;
pthread_cond_t jobQueueAvailable;
};
AppParams params;
void * renderTile( void * t ) {
// do work
int threadSize = params.h / NUM_THREADS;
uint64_t threadId = (uint64_t) t;
Vec2 uv;
const Vec2 pixelSize = { 1.f / params.w, 1.f / params.h };
for ( int y = threadId * threadSize; y < ( threadId + 1 ) * threadSize; y++ ) {
for ( int x = 0; x < params.w; x++ ) {
uv.x = (float) x / params.w;
uv.y = (float) y / params.h;
params.bmp->SetPixel( x, y, degamma( params.rt.trace( uv, pixelSize, params.numBounces ) ) );
}
}
pthread_exit( t );
}
void * startWorker( void * t ) {
while ( !params.allJobsQueued || params.jobQueue.size() > 0 ) {
pthread_mutex_lock( ¶ms.jobQueue_mutex );
while ( params.jobQueue.size() == 0 && !params.allJobsQueued ) {
pthread_cond_wait( ¶ms.jobQueueAvailable, ¶ms.jobQueue_mutex );
}
if ( params.jobQueue.size() == 0 ) { // ==> params.allJobsQueued is true, so we've exhausted our supply of jobs
pthread_mutex_unlock( ¶ms.jobQueue_mutex );
break; // we're done
}
int y = params.jobQueue.front();
params.jobQueue.pop();
pthread_mutex_unlock( ¶ms.jobQueue_mutex );
Vec2 uv;
const Vec2 pixelSize = { 1.f / params.w, 1.f / params.h };
for ( int x = 0; x < params.w; x++ ) {
uv.x = (float) x / params.w;
uv.y = (float) y / params.h;
params.bmp->SetPixel( x, y, degamma( params.rt.trace( uv, pixelSize, params.numBounces ) ) );
}
}
pthread_exit( NULL );
}
int main( int argc, char **argv ) {
if ( argc >= 3 ) {
int w = atoi( argv[1] );
int h = atoi( argv[2] );
// parameter setup
params.bmp = new BMP( w, h );
params.w = w;
params.h = h;
params.rt.camera.focalLength = 1.0;
params.rt.camera.depthOfFocus = 40.0;
params.rt.camera.aperture = 1.0;
params.rt.camera.pos.y = -2; // raise the camera up slightly
params.rt.camera.aspectRatio = static_cast<float>( w ) / static_cast<float>( h );
rt::Sphere s1( Vec3( -9, -13, -44 ), 7, new Dielectric( 1.3 ) );
rt::Sphere s2( Vec3( -2, -13, -88 ), 7, new Metallic( Vec4( 0.7, 0.7, 0.7, 1 ), 0.5 ) );
rt::Sphere s3( Vec3( 10, -13, -66 ), 7, new Lambertian( Vec4( 0.7, 0.7, 0.7, 1 ) ) );
// cornell box faces
// top face
rt::Plane ptop( Vec3( 0, 20, 0 ), Vec3( 0, -1, 0 ), new Lambertian( Vec4( 0.9, 0.9, 0.9, 1 ) ) );
// bottom face
rt::Plane pbot( Vec3( 0, -20, 0 ), Vec3( 0, 1, 0 ), new Lambertian( Vec4( 0.8, 0.8, 0.8, 1 ) ) );
// back face
rt::Plane pbak( Vec3( 0, 0, -65 ), Vec3( 0, 0, 1 ), new Lambertian( Vec4( 0.9, 0.9, 0.9, 1 ) ) );
// side faces
rt::Plane pr( Vec3( 20, 0, 0 ), Vec3( -1, 0, 0 ), new Lambertian( Vec4( 0.8, 0.3, 0.3, 1 ) ) );
rt::Plane pl( Vec3( -20, 0, 0 ), Vec3( 1, 0, 0 ), new Lambertian( Vec4( 0.3, 0.8, 0.3, 1 ) ) );
params.rt.scene.objects.push_back( &s1 );
params.rt.scene.objects.push_back( &s2 );
params.rt.scene.objects.push_back( &s3 );
// params.rt.scene.objects.push_back( &ptop );
params.rt.scene.objects.push_back( &pbot );
// params.rt.scene.objects.push_back( &pbak );
// params.rt.scene.objects.push_back( &pl );
// params.rt.scene.objects.push_back( &pr );
if ( params.singleThreaded ) {
Vec2 uv;
const Vec2 pixelSize = { 1.f / params.w, 1.f / params.h };
for ( int y = 0; y < params.h; y++ ) {
for ( int x = 0; x < params.w; x++ ) {
uv.x = (float) x / params.w;
uv.y = (float) y / params.h;
params.bmp->SetPixel( x, y, degamma( params.rt.trace( uv, pixelSize, params.numBounces ) ) );
}
}
} else { // multithreaded
pthread_t threads[ NUM_THREADS ];
pthread_attr_t attr;
pthread_attr_init( &attr );
pthread_attr_setdetachstate( &attr, PTHREAD_CREATE_JOINABLE );
if ( params.useJobs ) {
pthread_mutex_init( ¶ms.jobQueue_mutex, NULL );
pthread_cond_init( ¶ms.jobQueueAvailable, NULL );
for ( int i = 0; i < NUM_THREADS; i++ ) {
uint64_t t = i;
int rc = pthread_create( &threads[i], &attr, startWorker, (void *) t );
}
// add jobs to the queue
for ( int y = 0; y < h; y++ ) {
pthread_mutex_lock( ¶ms.jobQueue_mutex );
params.jobQueue.push( y );
pthread_cond_signal( ¶ms.jobQueueAvailable );
pthread_mutex_unlock( ¶ms.jobQueue_mutex );
}
// we're done, wake up all waiting threads
pthread_mutex_lock( ¶ms.jobQueue_mutex );
params.allJobsQueued = true;
pthread_cond_broadcast( ¶ms.jobQueueAvailable );
pthread_mutex_unlock( ¶ms.jobQueue_mutex );
} else { // simple thread-index based work division
for ( int i = 0; i < NUM_THREADS; i++ ) {
uint64_t t = i;
int rc = pthread_create( &threads[i], &attr, renderTile, (void *) t );
}
}
void * status;
for ( int i = 0; i < NUM_THREADS; i++ ) {
pthread_join( threads[i], &status );
}
}
params.bmp->Write( "hello.bmp" );
// params.bmp will be automatically reclaimed by the OS, so no need to delete
return 0;
}
}
<commit_msg>stub program branching points<commit_after>#include "bmp.h"
#include <cstdio>
#include <cstdint>
#include <cstdlib>
#include <pthread.h>
#include <queue>
#include "tracer.h"
#include "vector.h"
#include "color.h"
#include "sphere.h"
#include "plane.h"
#include "lambertian.h"
#include "metallic.h"
#include "dielectric.h"
using namespace gml;
const int NUM_THREADS = 4;
struct AppParams {
Tracer rt;
int numBounces = 4;
BMP * bmp = NULL;
int w = 0;
int h = 0;
bool singleThreaded = false;
bool useJobs = true;
// for jobs use only
bool allJobsQueued = false;
std::queue<int> jobQueue;
pthread_mutex_t jobQueue_mutex;
pthread_cond_t jobQueueAvailable;
};
AppParams params;
void * renderTile( void * t ) {
// do work
int threadSize = params.h / NUM_THREADS;
uint64_t threadId = (uint64_t) t;
Vec2 uv;
const Vec2 pixelSize = { 1.f / params.w, 1.f / params.h };
for ( int y = threadId * threadSize; y < ( threadId + 1 ) * threadSize; y++ ) {
for ( int x = 0; x < params.w; x++ ) {
uv.x = (float) x / params.w;
uv.y = (float) y / params.h;
params.bmp->SetPixel( x, y, degamma( params.rt.trace( uv, pixelSize, params.numBounces ) ) );
}
}
pthread_exit( t );
}
void * startWorker( void * t ) {
while ( !params.allJobsQueued || params.jobQueue.size() > 0 ) {
pthread_mutex_lock( ¶ms.jobQueue_mutex );
while ( params.jobQueue.size() == 0 && !params.allJobsQueued ) {
pthread_cond_wait( ¶ms.jobQueueAvailable, ¶ms.jobQueue_mutex );
}
if ( params.jobQueue.size() == 0 ) { // ==> params.allJobsQueued is true, so we've exhausted our supply of jobs
pthread_mutex_unlock( ¶ms.jobQueue_mutex );
break; // we're done
}
int y = params.jobQueue.front();
params.jobQueue.pop();
pthread_mutex_unlock( ¶ms.jobQueue_mutex );
Vec2 uv;
const Vec2 pixelSize = { 1.f / params.w, 1.f / params.h };
for ( int x = 0; x < params.w; x++ ) {
uv.x = (float) x / params.w;
uv.y = (float) y / params.h;
params.bmp->SetPixel( x, y, degamma( params.rt.trace( uv, pixelSize, params.numBounces ) ) );
}
}
pthread_exit( NULL );
}
int main( int argc, char **argv ) {
if ( argc > 1 ) {
char * mode = argv[1];
if ( strcmp( mode, "server" ) == 0 ) {
printf( "STUB server mode.\n" );
} else if ( strcmp( mode, "client" ) == 0 ) {
printf( "STUB client mode.\n" );
} else if ( strcmp( mode, "local" ) == 0 ) {
if ( argc >= 4 ) {
int w = atoi( argv[2] );
int h = atoi( argv[3] );
// parameter setup
params.bmp = new BMP( w, h );
params.w = w;
params.h = h;
params.rt.camera.focalLength = 1.0;
params.rt.camera.depthOfFocus = 40.0;
params.rt.camera.aperture = 1.0;
params.rt.camera.pos.y = -2; // raise the camera up slightly
params.rt.camera.aspectRatio = static_cast<float>( w ) / static_cast<float>( h );
rt::Sphere s1( Vec3( -9, -13, -44 ), 7, new Dielectric( 1.3 ) );
rt::Sphere s2( Vec3( -2, -13, -88 ), 7, new Metallic( Vec4( 0.7, 0.7, 0.7, 1 ), 0.5 ) );
rt::Sphere s3( Vec3( 10, -13, -66 ), 7, new Lambertian( Vec4( 0.7, 0.7, 0.7, 1 ) ) );
// cornell box faces
// top face
rt::Plane ptop( Vec3( 0, 20, 0 ), Vec3( 0, -1, 0 ), new Lambertian( Vec4( 0.9, 0.9, 0.9, 1 ) ) );
// bottom face
rt::Plane pbot( Vec3( 0, -20, 0 ), Vec3( 0, 1, 0 ), new Lambertian( Vec4( 0.8, 0.8, 0.8, 1 ) ) );
// back face
rt::Plane pbak( Vec3( 0, 0, -65 ), Vec3( 0, 0, 1 ), new Lambertian( Vec4( 0.9, 0.9, 0.9, 1 ) ) );
// side faces
rt::Plane pr( Vec3( 20, 0, 0 ), Vec3( -1, 0, 0 ), new Lambertian( Vec4( 0.8, 0.3, 0.3, 1 ) ) );
rt::Plane pl( Vec3( -20, 0, 0 ), Vec3( 1, 0, 0 ), new Lambertian( Vec4( 0.3, 0.8, 0.3, 1 ) ) );
params.rt.scene.objects.push_back( &s1 );
params.rt.scene.objects.push_back( &s2 );
params.rt.scene.objects.push_back( &s3 );
// params.rt.scene.objects.push_back( &ptop );
params.rt.scene.objects.push_back( &pbot );
// params.rt.scene.objects.push_back( &pbak );
// params.rt.scene.objects.push_back( &pl );
// params.rt.scene.objects.push_back( &pr );
if ( params.singleThreaded ) {
Vec2 uv;
const Vec2 pixelSize = { 1.f / params.w, 1.f / params.h };
for ( int y = 0; y < params.h; y++ ) {
for ( int x = 0; x < params.w; x++ ) {
uv.x = (float) x / params.w;
uv.y = (float) y / params.h;
params.bmp->SetPixel( x, y, degamma( params.rt.trace( uv, pixelSize, params.numBounces ) ) );
}
}
} else { // multithreaded
pthread_t threads[ NUM_THREADS ];
pthread_attr_t attr;
pthread_attr_init( &attr );
pthread_attr_setdetachstate( &attr, PTHREAD_CREATE_JOINABLE );
if ( params.useJobs ) {
pthread_mutex_init( ¶ms.jobQueue_mutex, NULL );
pthread_cond_init( ¶ms.jobQueueAvailable, NULL );
for ( int i = 0; i < NUM_THREADS; i++ ) {
uint64_t t = i;
int rc = pthread_create( &threads[i], &attr, startWorker, (void *) t );
}
// add jobs to the queue
for ( int y = 0; y < h; y++ ) {
pthread_mutex_lock( ¶ms.jobQueue_mutex );
params.jobQueue.push( y );
pthread_cond_signal( ¶ms.jobQueueAvailable );
pthread_mutex_unlock( ¶ms.jobQueue_mutex );
}
// we're done, wake up all waiting threads
pthread_mutex_lock( ¶ms.jobQueue_mutex );
params.allJobsQueued = true;
pthread_cond_broadcast( ¶ms.jobQueueAvailable );
pthread_mutex_unlock( ¶ms.jobQueue_mutex );
} else { // simple thread-index based work division
for ( int i = 0; i < NUM_THREADS; i++ ) {
uint64_t t = i;
int rc = pthread_create( &threads[i], &attr, renderTile, (void *) t );
}
}
void * status;
for ( int i = 0; i < NUM_THREADS; i++ ) {
pthread_join( threads[i], &status );
}
}
params.bmp->Write( "hello.bmp" );
// params.bmp will be automatically reclaimed by the OS when we exit, so no need to delete
} else {
printf( "usage: ray local width height\n" );
}
} else {
printf( "usage: ray [server|client|local] args\n" );
}
} else {
printf( "usage: ray [server|client|local] args\n" );
}
return 0;
}
<|endoftext|> |
<commit_before>/*
* Copyright 2015 - 2021 gary@drinkingtea.net
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
*/
#pragma once
namespace ox::defines {
#if defined(OX_USE_STDLIB)
constexpr auto UseStdLib = true;
#else
constexpr auto UseStdLib = false;
#endif
#if defined(DEBUG)
constexpr auto Debug = true;
#else
constexpr auto Debug = false;
#endif
#if defined(NDEBUG)
constexpr auto NDebug = true;
#else
constexpr auto NDebug = false;
#endif
#if defined(__BIG_ENDIAN__)
constexpr auto BigEndian = true;
constexpr auto LittleEndian = false;
#else
constexpr auto BigEndian = false;
constexpr auto LittleEndian = true;
#endif
enum class OS {
BareMetal,
NetBSD,
OpenBSD,
FreeBSD,
DragonFlyBSD,
Linux,
Darwin,
Windows
};
#if defined(__FreeBSD__)
constexpr OS OS = OS::FreeBSD;
#define OX_OS_FreeBSD
#elif defined(__NetBSD__)
constexpr OS OS = OS::NetBSD;
#define OX_OS_NetBSD
#elif defined(__OpenBSD__)
constexpr OS OS = OS::OpenBSD;
#define OX_OS_OpenBSD
#elif defined(__DragonFly__)
constexpr OS OS = OS::DragonFlyBSD;
#define OX_OS_DragonFlyBSD
#elif defined(__gnu_linux__)
constexpr OS OS = OS::Linux;
#define OX_OS_Linux
#elif defined(_WIN32)
#define OX_OS_Windows
constexpr OS OS = OS::Windows;
#elif defined(__APPLE__)
#define OX_OS_Darwin
constexpr OS OS = OS::Darwin;
#else
#define OX_OS_BareMetal
constexpr OS OS = OS::BareMetal;
#endif
}
<commit_msg>[ox/std] Cleanup OS constexpr/define order in defines<commit_after>/*
* Copyright 2015 - 2021 gary@drinkingtea.net
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
*/
#pragma once
namespace ox::defines {
#if defined(OX_USE_STDLIB)
constexpr auto UseStdLib = true;
#else
constexpr auto UseStdLib = false;
#endif
#if defined(DEBUG)
constexpr auto Debug = true;
#else
constexpr auto Debug = false;
#endif
#if defined(NDEBUG)
constexpr auto NDebug = true;
#else
constexpr auto NDebug = false;
#endif
#if defined(__BIG_ENDIAN__)
constexpr auto BigEndian = true;
constexpr auto LittleEndian = false;
#else
constexpr auto BigEndian = false;
constexpr auto LittleEndian = true;
#endif
enum class OS {
BareMetal,
NetBSD,
OpenBSD,
FreeBSD,
DragonFlyBSD,
Linux,
Darwin,
Windows
};
#if defined(__FreeBSD__)
constexpr OS OS = OS::FreeBSD;
#define OX_OS_FreeBSD
#elif defined(__NetBSD__)
constexpr OS OS = OS::NetBSD;
#define OX_OS_NetBSD
#elif defined(__OpenBSD__)
constexpr OS OS = OS::OpenBSD;
#define OX_OS_OpenBSD
#elif defined(__DragonFly__)
constexpr OS OS = OS::DragonFlyBSD;
#define OX_OS_DragonFlyBSD
#elif defined(__gnu_linux__)
constexpr OS OS = OS::Linux;
#define OX_OS_Linux
#elif defined(_WIN32)
constexpr OS OS = OS::Windows;
#define OX_OS_Windows
#elif defined(__APPLE__)
constexpr OS OS = OS::Darwin;
#define OX_OS_Darwin
#else
constexpr OS OS = OS::BareMetal;
#define OX_OS_BareMetal
#endif
}
<|endoftext|> |
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: aststructinstance.cxx,v $
*
* $Revision: 1.5 $
*
* last change: $Author: obo $ $Date: 2006-09-17 08:13:26 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_idlc.hxx"
#include "idlc/aststructinstance.hxx"
#include "idlc/asttype.hxx"
#include "idlc/idlctypes.hxx"
#include "rtl/strbuf.hxx"
#include "rtl/string.hxx"
namespace {
rtl::OString createName(
AstType const * typeTemplate, DeclList const * typeArguments)
{
rtl::OStringBuffer buf(typeTemplate->getScopedName());
if (typeArguments != 0) {
buf.append('<');
for (DeclList::const_iterator i(typeArguments->begin());
i != typeArguments->end(); ++i)
{
if (i != typeArguments->begin()) {
buf.append(',');
}
if (*i != 0) {
buf.append((*i)->getScopedName());
}
}
buf.append('>');
}
return buf.makeStringAndClear();
}
}
AstStructInstance::AstStructInstance(
AstType const * typeTemplate, DeclList const * typeArguments,
AstScope * scope):
AstType(
NT_instantiated_struct, createName(typeTemplate, typeArguments), scope),
m_typeTemplate(typeTemplate), m_typeArguments(*typeArguments)
{}
<commit_msg>INTEGRATION: CWS changefileheader (1.5.58); FILE MERGED 2008/03/31 07:23:51 rt 1.5.58.1: #i87441# Change license header to LPGL v3.<commit_after>/*************************************************************************
*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* Copyright 2008 by Sun Microsystems, Inc.
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: aststructinstance.cxx,v $
* $Revision: 1.6 $
*
* This file is part of OpenOffice.org.
*
* OpenOffice.org is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License version 3
* only, as published by the Free Software Foundation.
*
* OpenOffice.org is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License version 3 for more details
* (a copy is included in the LICENSE file that accompanied this code).
*
* You should have received a copy of the GNU Lesser General Public License
* version 3 along with OpenOffice.org. If not, see
* <http://www.openoffice.org/license.html>
* for a copy of the LGPLv3 License.
*
************************************************************************/
// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_idlc.hxx"
#include "idlc/aststructinstance.hxx"
#include "idlc/asttype.hxx"
#include "idlc/idlctypes.hxx"
#include "rtl/strbuf.hxx"
#include "rtl/string.hxx"
namespace {
rtl::OString createName(
AstType const * typeTemplate, DeclList const * typeArguments)
{
rtl::OStringBuffer buf(typeTemplate->getScopedName());
if (typeArguments != 0) {
buf.append('<');
for (DeclList::const_iterator i(typeArguments->begin());
i != typeArguments->end(); ++i)
{
if (i != typeArguments->begin()) {
buf.append(',');
}
if (*i != 0) {
buf.append((*i)->getScopedName());
}
}
buf.append('>');
}
return buf.makeStringAndClear();
}
}
AstStructInstance::AstStructInstance(
AstType const * typeTemplate, DeclList const * typeArguments,
AstScope * scope):
AstType(
NT_instantiated_struct, createName(typeTemplate, typeArguments), scope),
m_typeTemplate(typeTemplate), m_typeArguments(*typeArguments)
{}
<|endoftext|> |
<commit_before>
#define CL_USE_DEPRECATED_OPENCL_1_1_APIS
#define CL_HPP_MINIMUM_OPENCL_VERSION 120
#define CL_HPP_TARGET_OPENCL_VERSION 120
#include <CL/opencl.hpp>
#include <string>
#include <vector>
#include <deque>
#include <chrono>
#include <mutex>
#include <cmath>
#include <condition_variable>
#include <map>
#include <set>
#include <thread>
#include <unordered_map>
#include <random>
#include <iostream>
#define TILE 16
#define X 640
#define Y 640
#define BUFSIZE (X*Y*4)
#define CHECK_CL_ERROR(EXPR, ...) \
if (EXPR != CL_SUCCESS) { std::cerr << __VA_ARGS__; return 12; }
int
main(int argc, char** argv)
{
cl::Platform platform;
std::vector<cl::Device> devices;
cl::Context ClContext;
cl::Device AccelDev;
cl::CommandQueue AccelQueue;
cl::Program AccelProgram;
cl::Kernel AccelKernel;
cl::NDRange Offset, Global, Local;
int err;
std::vector<cl::Platform> all_platforms;
cl::Platform::get(&all_platforms);
if(!all_platforms.size()) {
std::cerr << "No OpenCL platforms available!\n";
return 1;
}
platform = all_platforms[0];
platform.getDevices(CL_DEVICE_TYPE_ALL, &devices);
if(devices.size() == 0) {
std::cerr << "No OpenCL devices available!\n";
return 2;
}
const char* kernel_name = "pocl.add.i32";
const char* known_kernels[] = { "pocl.add.i32", "pocl.mul.i32",
"pocl.abs.f32",
"pocl.sgemm.local.f32",
NULL,
};
if (argc > 1)
{
kernel_name = argv[1];
std::string k{kernel_name};
int found = 0;
unsigned i = 0;
while (known_kernels[i]) {
if (k.compare(known_kernels[i]) == 0) found = 1;
++i;
}
if (!found) {
std::cerr << "unknown builtin kernel: " << kernel_name << "\n";
return 3;
}
}
std::string kernel_str{kernel_name};
for (auto& D : devices) {
std::string AccelBuiltinKernels = D.getInfo<CL_DEVICE_BUILT_IN_KERNELS>();
std::cout << "Device " << D.getInfo<CL_DEVICE_NAME>() <<
" has builtin kernels: " << AccelBuiltinKernels << "\n";
if (AccelBuiltinKernels.find(kernel_str) != std::string::npos)
{
AccelDev = D;
break;
}
}
if (AccelDev.get() == nullptr) {
std::cerr << "no devices which support builtin kernel " << kernel_str << "\n";
return 4;
}
std::cout << "Using device: " << AccelDev.getInfo<CL_DEVICE_NAME>() << "\n";
std::cout << "Using builtin kernel: " << kernel_str << "\n";
std::vector<cl::Device> AccelDevs = {AccelDev};
ClContext = cl::Context(AccelDevs, nullptr, nullptr, nullptr, &err);
CHECK_CL_ERROR(err, "Context creation failed\n");
AccelQueue = cl::CommandQueue(ClContext, AccelDev, 0, &err); // , CL_QUEUE_PROFILING_ENABLE
CHECK_CL_ERROR(err, "CmdQueue creation failed\n");
AccelProgram = cl::Program{ClContext, AccelDevs, kernel_str.c_str(), &err};
CHECK_CL_ERROR(err, "Program creation failed\n");
err = AccelProgram.build(AccelDevs);
CHECK_CL_ERROR(err, "Program build failed\n");
cl::Kernel Kernel = cl::Kernel(AccelProgram, kernel_str.c_str(), &err);
CHECK_CL_ERROR(err, "Kernel creation failed\n");
cl::Buffer Input1 = cl::Buffer(ClContext, CL_MEM_READ_WRITE, (cl::size_type)BUFSIZE, nullptr, &err);
CHECK_CL_ERROR(err, "Input1 buffer creation failed\n");
cl::Buffer Input2 = cl::Buffer(ClContext, CL_MEM_READ_WRITE, (cl::size_type)BUFSIZE, nullptr, &err);
CHECK_CL_ERROR(err, "Input2 buffer creation failed\n");
cl::Buffer Out1 = cl::Buffer(ClContext, CL_MEM_READ_WRITE, (cl::size_type)BUFSIZE, nullptr, &err);
CHECK_CL_ERROR(err, "OUtput1 buffer creation failed\n");
void *i1, *i2, *o1;
Offset = cl::NullRange;
Local = cl::NDRange(TILE, TILE);
Global = cl::NDRange(X, Y);
if (kernel_str.compare("pocl.add.i32") == 0 ||
kernel_str.compare("pocl.mul.i32") == 0)
{
Kernel.setArg(0, Input1);
Kernel.setArg(1, Input2);
Kernel.setArg(2, Out1);
}
if (kernel_str.compare("pocl.abs.f32") == 0)
{
Kernel.setArg(0, Input1);
Kernel.setArg(1, Out1);
}
if (kernel_str.compare("pocl.sgemm.local.f32") == 0)
{
Kernel.setArg(0, Input1);
Kernel.setArg(1, Input2);
Kernel.setArg(2, Out1);
Kernel.setArg(3, X);
Kernel.setArg(4, Y);
Kernel.setArg(5, X);
}
if (kernel_str.compare("pocl.sgemm.local.f32") == 0 ||
kernel_str.compare("pocl.abs.f32") == 0)
{
std::mt19937 mt{234545649UL};
std::uniform_real_distribution<float> dist(15.0, 25.0);
float* in1 = new float[X*Y];
float* in2 = new float[X*Y];
float* out1 = new float[X*Y];
for (size_t i = 0; i < X*Y; ++i) {
in1[i] = dist(mt);
in2[i] = dist(mt);
out1[i] = 0.0f;
}
i1 = in1; i2 = in2; o1 = out1;
}
else
{
std::mt19937 mt{234545649UL};
std::uniform_int_distribution<unsigned int> dist(10, 24);
uint32_t *in1 = new uint32_t[X*Y];
uint32_t *in2 = new uint32_t[X*Y];
uint32_t *out1 = new uint32_t[X*Y];
for (size_t i = 0; i < X*Y; ++i) {
in1[i] = dist(mt);
in2[i] = dist(mt);
out1[i] = 0;
}
i1 = in1; i2 = in2; o1 = out1;
}
using clock_type = std::chrono::steady_clock;
using second_type = std::chrono::duration<double, std::ratio<1> >;
std::chrono::time_point<clock_type> m_beg { clock_type::now() };
err = AccelQueue.enqueueWriteBuffer(Input1, CL_FALSE, 0, BUFSIZE, i1);
CHECK_CL_ERROR(err, "en 1");
err = AccelQueue.enqueueWriteBuffer(Input2, CL_FALSE, 0, BUFSIZE, i2);
CHECK_CL_ERROR(err, "en 2");
err = AccelQueue.enqueueNDRangeKernel(Kernel, Offset, Global, Local);
CHECK_CL_ERROR(err, "en 3");
err = AccelQueue.enqueueReadBuffer(Out1, CL_TRUE, 0, BUFSIZE, o1);
CHECK_CL_ERROR(err, "en 4");
std::chrono::time_point<clock_type> m_end { clock_type::now() };
double diff = std::chrono::duration_cast<second_type>(m_end - m_beg).count();
std::cout << "Execution time(s): " << diff << "\n\n";
if (kernel_str.compare("pocl.sgemm.local.f32") == 0 ||
kernel_str.compare("pocl.abs.f32") == 0)
{
float* in1 = (float *)i1;
float* in2 = (float *)i2;
float* out1 = (float *)o1;
for (size_t i = 0; i < 10; ++i)
{
std::cout << "IN1: " << in1[i] << " IN2: " << in2[i] <<
" OUT1: " << out1[i] << "\n";
}
delete [] in1;
delete [] in2;
delete [] out1;
}
else
{
uint32_t *in1 = (uint32_t *)i1;
uint32_t *in2 = (uint32_t *)i2;
uint32_t *out1 = (uint32_t *)o1;
for (size_t i = 0; i < 10; ++i)
{
std::cout << "IN1: " << in1[i] << " IN2: " << in2[i] <<
" OUT1: " << out1[i] << "\n";
}
delete [] in1;
delete [] in2;
delete [] out1;
}
return EXIT_SUCCESS;
}
<commit_msg>Accel example: fix NDRanges<commit_after>
#define CL_USE_DEPRECATED_OPENCL_1_1_APIS
#define CL_HPP_MINIMUM_OPENCL_VERSION 120
#define CL_HPP_TARGET_OPENCL_VERSION 120
#include <CL/opencl.hpp>
#include <string>
#include <vector>
#include <deque>
#include <chrono>
#include <mutex>
#include <cmath>
#include <condition_variable>
#include <map>
#include <set>
#include <thread>
#include <unordered_map>
#include <random>
#include <iostream>
#define TILE 16
#define X 640
#define Y 640
#define BUFSIZE (X*Y*4)
#define CHECK_CL_ERROR(EXPR, ...) \
if (EXPR != CL_SUCCESS) { std::cerr << __VA_ARGS__; return 12; }
int
main(int argc, char** argv)
{
cl::Platform platform;
std::vector<cl::Device> devices;
cl::Context ClContext;
cl::Device AccelDev;
cl::CommandQueue AccelQueue;
cl::Program AccelProgram;
cl::Kernel AccelKernel;
cl::NDRange Offset, Global2D, Local2D, Global, Local;
int err;
std::vector<cl::Platform> all_platforms;
cl::Platform::get(&all_platforms);
if(!all_platforms.size()) {
std::cerr << "No OpenCL platforms available!\n";
return 1;
}
platform = all_platforms[0];
platform.getDevices(CL_DEVICE_TYPE_ALL, &devices);
if(devices.size() == 0) {
std::cerr << "No OpenCL devices available!\n";
return 2;
}
const char* kernel_name = "pocl.add.i32";
const char* known_kernels[] = { "pocl.add.i32", "pocl.mul.i32",
"pocl.abs.f32",
"pocl.sgemm.local.f32",
NULL,
};
if (argc > 1)
{
kernel_name = argv[1];
std::string k{kernel_name};
int found = 0;
unsigned i = 0;
while (known_kernels[i]) {
if (k.compare(known_kernels[i]) == 0) found = 1;
++i;
}
if (!found) {
std::cerr << "unknown builtin kernel: " << kernel_name << "\n";
return 3;
}
}
std::string kernel_str{kernel_name};
for (auto& D : devices) {
std::string AccelBuiltinKernels = D.getInfo<CL_DEVICE_BUILT_IN_KERNELS>();
std::cout << "Device " << D.getInfo<CL_DEVICE_NAME>() <<
" has builtin kernels: " << AccelBuiltinKernels << "\n";
if (AccelBuiltinKernels.find(kernel_str) != std::string::npos)
{
AccelDev = D;
break;
}
}
if (AccelDev.get() == nullptr) {
std::cerr << "no devices which support builtin kernel " << kernel_str << "\n";
return 4;
}
std::cout << "Using device: " << AccelDev.getInfo<CL_DEVICE_NAME>() << "\n";
std::cout << "Using builtin kernel: " << kernel_str << "\n";
std::vector<cl::Device> AccelDevs = {AccelDev};
ClContext = cl::Context(AccelDevs, nullptr, nullptr, nullptr, &err);
CHECK_CL_ERROR(err, "Context creation failed\n");
AccelQueue = cl::CommandQueue(ClContext, AccelDev, 0, &err); // , CL_QUEUE_PROFILING_ENABLE
CHECK_CL_ERROR(err, "CmdQueue creation failed\n");
AccelProgram = cl::Program{ClContext, AccelDevs, kernel_str.c_str(), &err};
CHECK_CL_ERROR(err, "Program creation failed\n");
err = AccelProgram.build(AccelDevs);
CHECK_CL_ERROR(err, "Program build failed\n");
cl::Kernel Kernel = cl::Kernel(AccelProgram, kernel_str.c_str(), &err);
CHECK_CL_ERROR(err, "Kernel creation failed\n");
cl::Buffer Input1 = cl::Buffer(ClContext, CL_MEM_READ_WRITE, (cl::size_type)BUFSIZE, nullptr, &err);
CHECK_CL_ERROR(err, "Input1 buffer creation failed\n");
cl::Buffer Input2 = cl::Buffer(ClContext, CL_MEM_READ_WRITE, (cl::size_type)BUFSIZE, nullptr, &err);
CHECK_CL_ERROR(err, "Input2 buffer creation failed\n");
cl::Buffer Out1 = cl::Buffer(ClContext, CL_MEM_READ_WRITE, (cl::size_type)BUFSIZE, nullptr, &err);
CHECK_CL_ERROR(err, "OUtput1 buffer creation failed\n");
void *i1, *i2, *o1;
Offset = cl::NullRange;
Local2D = cl::NDRange(TILE, TILE);
Global2D = cl::NDRange(X, Y);
Local = cl::NDRange(TILE);
Global = cl::NDRange(X);
if (kernel_str.compare("pocl.add.i32") == 0 ||
kernel_str.compare("pocl.mul.i32") == 0)
{
Kernel.setArg(0, Input1);
Kernel.setArg(1, Input2);
Kernel.setArg(2, Out1);
}
if (kernel_str.compare("pocl.abs.f32") == 0)
{
Kernel.setArg(0, Input1);
Kernel.setArg(1, Out1);
}
if (kernel_str.compare("pocl.sgemm.local.f32") == 0)
{
Kernel.setArg(0, Input1);
Kernel.setArg(1, Input2);
Kernel.setArg(2, Out1);
Kernel.setArg(3, X);
Kernel.setArg(4, Y);
Kernel.setArg(5, X);
}
if (kernel_str.compare("pocl.sgemm.local.f32") == 0 ||
kernel_str.compare("pocl.abs.f32") == 0)
{
std::mt19937 mt{234545649UL};
std::uniform_real_distribution<float> dist(15.0, 25.0);
float* in1 = new float[X*Y];
float* in2 = new float[X*Y];
float* out1 = new float[X*Y];
for (size_t i = 0; i < X*Y; ++i) {
in1[i] = dist(mt);
in2[i] = dist(mt);
out1[i] = 0.0f;
}
i1 = in1; i2 = in2; o1 = out1;
}
else
{
std::mt19937 mt{234545649UL};
std::uniform_int_distribution<unsigned int> dist(10, 24);
uint32_t *in1 = new uint32_t[X*Y];
uint32_t *in2 = new uint32_t[X*Y];
uint32_t *out1 = new uint32_t[X*Y];
for (size_t i = 0; i < X*Y; ++i) {
in1[i] = dist(mt);
in2[i] = dist(mt);
out1[i] = 0;
}
i1 = in1; i2 = in2; o1 = out1;
}
using clock_type = std::chrono::steady_clock;
using second_type = std::chrono::duration<double, std::ratio<1> >;
std::chrono::time_point<clock_type> m_beg { clock_type::now() };
err = AccelQueue.enqueueWriteBuffer(Input1, CL_FALSE, 0, BUFSIZE, i1);
CHECK_CL_ERROR(err, "en 1");
err = AccelQueue.enqueueWriteBuffer(Input2, CL_FALSE, 0, BUFSIZE, i2);
CHECK_CL_ERROR(err, "en 2");
if (kernel_str.compare("pocl.sgemm.local.f32") == 0)
err = AccelQueue.enqueueNDRangeKernel(Kernel, Offset, Global2D, Local2D);
else
err = AccelQueue.enqueueNDRangeKernel(Kernel, Offset, Global, Local);
CHECK_CL_ERROR(err, "en 3");
err = AccelQueue.enqueueReadBuffer(Out1, CL_TRUE, 0, BUFSIZE, o1);
CHECK_CL_ERROR(err, "en 4");
std::chrono::time_point<clock_type> m_end { clock_type::now() };
double diff = std::chrono::duration_cast<second_type>(m_end - m_beg).count();
std::cout << "Execution time(s): " << diff << "\n\n";
if (kernel_str.compare("pocl.sgemm.local.f32") == 0 ||
kernel_str.compare("pocl.abs.f32") == 0)
{
float* in1 = (float *)i1;
float* in2 = (float *)i2;
float* out1 = (float *)o1;
for (size_t i = 0; i < 10; ++i)
{
std::cout << "IN1: " << in1[i] << " IN2: " << in2[i] <<
" OUT1: " << out1[i] << "\n";
}
delete [] in1;
delete [] in2;
delete [] out1;
}
else
{
uint32_t *in1 = (uint32_t *)i1;
uint32_t *in2 = (uint32_t *)i2;
uint32_t *out1 = (uint32_t *)o1;
for (size_t i = 0; i < 10; ++i)
{
std::cout << "IN1: " << in1[i] << " IN2: " << in2[i] <<
" OUT1: " << out1[i] << "\n";
}
delete [] in1;
delete [] in2;
delete [] out1;
}
return EXIT_SUCCESS;
}
<|endoftext|> |
<commit_before>/** \addtogroup examples
* @{
* \defgroup algebraic_multigrid algebraic_multigrid
* @{
* \brief Benchmark for smoothed algebraic multgrid
*/
#include <ctf.hpp>
using namespace CTF;
void smooth_jacobi(Matrix<> & A, Vector<> & x, Vector <> & b, int nsmooth){
Vector<> d(x.len, *x.wrld);
d["i"] = A["ii"];
Transform<>([](double & d){ d= fabs(d) > 0.0 ? 1./d : 0.0; })(d["i"]);
Matrix<> R(A);
R["ii"] = 0.0;
//20 iterations of Jacobi, should probably be a parameter or some convergence check instead
for (int i=0; i<nsmooth; i++){
x["i"] = -1.0*R["ij"]*x["j"];
x["i"] += b["i"];
x["i"] *= d["i"];
}
}
void vcycle(Matrix<> & A, Vector<> & x, Vector<> & b, Matrix<> * T, int n, int nlevel, int nsmooth){
//do smoothing using Jacobi
Vector<> r(b);
r["i"] -= A["ij"]*x["j"];
double rnorm0 = r.norm2();
smooth_jacobi(A,x,b,nsmooth);
r["i"] = b["i"];
r["i"] -= A["ij"]*x["j"];
double rnorm = r.norm2();
if (nlevel == 0){
if (A.wrld->rank == 0) printf("At level %d (coarsest level), residual norm was %1.2E initially\n",nlevel,rnorm0);
if (A.wrld->rank == 0) printf("At level %d (coarsest level), residual norm was %1.2E after smooth\n",nlevel,rnorm);
return;
}
Vector<> x2(x);
Vector<> r2(x);
smooth_jacobi(A,x2,b,nsmooth);
r2["i"] = b["i"];
r2["i"] -= A["ij"]*x2["j"];
double rnorm_alt = r2.norm2();
int m = T[0].lens[1];
// Vector<> d(x.len, *x.wrld);
// d["i"] = A["ii"];
// P["ik"] -= d["i"]*A["ij"]*T[0]["jk"];
//smooth the restriction/interpolation operator P = (I-omega*diag(A)^{-1}*A)T
Matrix<> P(T[0].lens[0], T[0].lens[1], SP, *T[0].wrld);
Matrix<> D(n,n,SP,*A.wrld);
D["ii"] = A["ii"];
double omega=.1;
Transform<>([=](double & d){ d= omega/d; })(D["ii"]);
P["ik"] = A["ij"]*T[0]["jk"];
P["ik"] = D["il"]*P["lk"];
P["ij"] += T[0]["ij"];
//restrict residual vector
Vector<> PTr(m, *x.wrld);
PTr["i"] = P["ji"]*r["j"];
//coarses initial guess should be zeros
Vector<> zx(m, *b.wrld);
int atr = 0;
if (A.is_sparse){
atr = atr | SP;
}
//atr = atr | A.symm;
Matrix<> AP(n, m, atr, *x.wrld);
Matrix<> PTAP(m, m, atr, *x.wrld);
//restrict A via triple matrix product, should probably be done outside v-cycle
AP["lj"] = A["lk"]*P["kj"];
PTAP["ij"] = P["li"]*AP["lj"];
//recurse into coarser level
vcycle(PTAP, zx, PTr, T+1, m, nlevel-1, nsmooth);
// zx.print();
//interpolate solution to residual equation at coraser level back
x["i"] += P["ij"]*zx["j"];
//smooth new solution
r["i"] = b["i"];
r["i"] -= A["ij"]*x["j"];
double rnorm2 = r.norm2();
smooth_jacobi(A,x,b,nsmooth);
r["i"] = b["i"];
r["i"] -= A["ij"]*x["j"];
double rnorm3 = r.norm2();
if (A.wrld->rank == 0) printf("At level %d, residual norm was %1.2E initially\n",nlevel,rnorm0);
if (A.wrld->rank == 0) printf("At level %d, residual norm was %1.2E after initial smooth\n",nlevel,rnorm);
if (A.wrld->rank == 0) printf("At level %d, residual norm was %1.2E after coarse recursion\n",nlevel,rnorm2);
if (A.wrld->rank == 0) printf("At level %d, residual norm was %1.2E after final smooth\n",nlevel,rnorm3);
if (A.wrld->rank == 0) printf("At level %d, residual norm was %1.2E if we skipped the coarsening\n",nlevel,rnorm_alt);
}
/**
* \brief computes Multigrid for a 3D regular discretization
*/
int algebraic_multigrid(int n,
double sp_frac,
int nlvl,
int ndiv,
int nsmooth,
int decay_exp,
World & dw){
Vector<> x(n, dw);
Vector<> b(n, dw);
x.fill_random(0.0, 1.0);
b.fill_random(0.0, 1.0);
Matrix<> A(n, n, SP, dw);
A.fill_sp_random(0.0, 1.0, sp_frac);
A["ij"] += A["ji"];
A["ii"] += sqrt((double)n);
// Transform<>([](double & d){ d = fabs(d).; })(A["ii"]);
// A.print();
Vector<int> N(n, dw);
int64_t * inds;
int * vals;
int64_t nvals;
N.read_local(&nvals, &inds, &vals);
for (int i=0; i<nvals; i++){
vals[i] = (int)inds[i];
}
N.write(nvals, inds, vals);
free(vals);
free(inds);
int curootn = (int)(pow((double)n,1./3.)+.001);
// printf("curootn = %d\n",curootn);
Matrix<std::pair<double, int>> B(n,n,SP,dw,Set<std::pair<double, int>>());
B["ij"] = Function< double, std::pair<double,int> >([](double d){ return std::pair<double,int>(d,0); })(A["ij"]);
Transform< int, std::pair<double,int> >([](int i, std::pair<double,int> & d){ d.second = i; } )(N["i"], B["ij"]);
Transform< int, std::pair<double,int> >([](int i, std::pair<double,int> & d){ d.second = abs(d.second-d.first); } )(N["j"], B["ij"]);
Transform< std::pair<double,int> >([=](std::pair<double,int> & d){
int x = d.second % curootn;
int y = (d.second / curootn) % curootn;
int z = d.second / curootn / curootn;
if (x+y+z > 0)
d.first = d.first/pow((double)(x+y+z),decay_exp/2.);
}
)(B["ij"]);
A["ij"] = Function< std::pair<double,int>, double >([](std::pair<double,int> p){ return p.first; })(B["ij"]);
Vector<> r(b);
r["i"] -= A["ij"]*x["j"];
double err = r.norm2();
Matrix<> * T = new Matrix<>[nlvl];
int m=n;
for (int i=0; i<nlvl; i++){
int m2 = m/ndiv;
T[i] = Matrix<>(m, m2, SP, dw);
std::vector< Pair<> > pairs;
for (int64_t j=dw.rank; j<m2; j+=dw.np){
for (int k=0; k<ndiv; k++){
pairs.push_back(Pair<>(j*m+j*ndiv+k, 1.0));
}
}
T[i].write(pairs.size(), &(pairs[0]));
m = m2;
}
vcycle(A, x, b, T, n, nlvl, nsmooth);
delete [] T;
r["i"] = b["i"];
r["i"] -= A["ij"]*x["j"];
double err2 = r.norm2();
bool pass = err2 < err;
if (dw.rank == 0){
#ifndef TEST_SUITE
printf("original err = %E, new err = %E\n",err,err2);
#endif
if (pass)
printf("{ algebraic multigrid method } passed \n");
else
printf("{ algebraic multigrid method } failed \n");
}
return pass;
}
#ifndef TEST_SUITE
char* getCmdOption(char ** begin,
char ** end,
const std::string & option){
char ** itr = std::find(begin, end, option);
if (itr != end && ++itr != end){
return *itr;
}
return 0;
}
int main(int argc, char ** argv){
int rank, np, n, pass, nlvl, ndiv, decay_exp, nsmooth;
double sp_frac;
int const in_num = argc;
char ** input_str = argv;
MPI_Init(&argc, &argv);
MPI_Comm_rank(MPI_COMM_WORLD, &rank);
MPI_Comm_size(MPI_COMM_WORLD, &np);
if (getCmdOption(input_str, input_str+in_num, "-n")){
n = atoi(getCmdOption(input_str, input_str+in_num, "-n"));
if (n < 0) n = 16;
} else n = 16;
if (getCmdOption(input_str, input_str+in_num, "-nlvl")){
nlvl = atoi(getCmdOption(input_str, input_str+in_num, "-nlvl"));
if (nlvl < 0) nlvl = 3;
} else nlvl = 3;
if (getCmdOption(input_str, input_str+in_num, "-ndiv")){
ndiv = atoi(getCmdOption(input_str, input_str+in_num, "-ndiv"));
if (ndiv < 0) ndiv = 2;
} else ndiv = 2;
if (getCmdOption(input_str, input_str+in_num, "-nsmooth")){
nsmooth = atoi(getCmdOption(input_str, input_str+in_num, "-nsmooth"));
if (nsmooth < 0) nsmooth = 3;
} else nsmooth = 3;
if (getCmdOption(input_str, input_str+in_num, "-decay_exp")){
decay_exp = atoi(getCmdOption(input_str, input_str+in_num, "-decay_exp"));
if (decay_exp < 0) decay_exp = 3;
} else decay_exp = 3;
if (getCmdOption(input_str, input_str+in_num, "-sp_frac")){
sp_frac = atof(getCmdOption(input_str, input_str+in_num, "-sp_frac"));
if (sp_frac < 0) sp_frac = .01;
} else sp_frac = .01;
int tot_ndiv=1;
for (int i=0; i<nlvl; i++){ tot_ndiv *= ndiv; }
assert(n%tot_ndiv == 0);
{
World dw(argc, argv);
if (rank == 0){
printf("Running algebraic smoothed multigrid method with %d levels with divisor %d in V-cycle, %d elements, %d smooth iterations, decayed based on 3D indexing with decay exponent of %d\n",nlvl,ndiv,n,nsmooth, decay_exp);
}
pass = algebraic_multigrid(n, sp_frac, nlvl, ndiv, nsmooth, decay_exp, dw);
assert(pass);
}
MPI_Finalize();
return 0;
}
/**
* @}
* @}
*/
#endif
<commit_msg>got rid of extra indent<commit_after>/** \addtogroup examples
* @{
* \defgroup algebraic_multigrid algebraic_multigrid
* @{
* \brief Benchmark for smoothed algebraic multgrid
*/
#include <ctf.hpp>
using namespace CTF;
void smooth_jacobi(Matrix<> & A, Vector<> & x, Vector <> & b, int nsmooth){
Vector<> d(x.len, *x.wrld);
d["i"] = A["ii"];
Transform<>([](double & d){ d= fabs(d) > 0.0 ? 1./d : 0.0; })(d["i"]);
Matrix<> R(A);
R["ii"] = 0.0;
//20 iterations of Jacobi, should probably be a parameter or some convergence check instead
for (int i=0; i<nsmooth; i++){
x["i"] = -1.0*R["ij"]*x["j"];
x["i"] += b["i"];
x["i"] *= d["i"];
}
}
void vcycle(Matrix<> & A, Vector<> & x, Vector<> & b, Matrix<> * T, int n, int nlevel, int nsmooth){
//do smoothing using Jacobi
Vector<> r(b);
r["i"] -= A["ij"]*x["j"];
double rnorm0 = r.norm2();
smooth_jacobi(A,x,b,nsmooth);
r["i"] = b["i"];
r["i"] -= A["ij"]*x["j"];
double rnorm = r.norm2();
if (nlevel == 0){
if (A.wrld->rank == 0) printf("At level %d (coarsest level), residual norm was %1.2E initially\n",nlevel,rnorm0);
if (A.wrld->rank == 0) printf("At level %d (coarsest level), residual norm was %1.2E after smooth\n",nlevel,rnorm);
return;
}
Vector<> x2(x);
Vector<> r2(x);
smooth_jacobi(A,x2,b,nsmooth);
r2["i"] = b["i"];
r2["i"] -= A["ij"]*x2["j"];
double rnorm_alt = r2.norm2();
int m = T[0].lens[1];
// Vector<> d(x.len, *x.wrld);
// d["i"] = A["ii"];
// P["ik"] -= d["i"]*A["ij"]*T[0]["jk"];
//smooth the restriction/interpolation operator P = (I-omega*diag(A)^{-1}*A)T
Matrix<> P(T[0].lens[0], T[0].lens[1], SP, *T[0].wrld);
Matrix<> D(n,n,SP,*A.wrld);
D["ii"] = A["ii"];
double omega=.1;
Transform<>([=](double & d){ d= omega/d; })(D["ii"]);
P["ik"] = A["ij"]*T[0]["jk"];
P["ik"] = D["il"]*P["lk"];
P["ij"] += T[0]["ij"];
//restrict residual vector
Vector<> PTr(m, *x.wrld);
PTr["i"] = P["ji"]*r["j"];
//coarses initial guess should be zeros
Vector<> zx(m, *b.wrld);
int atr = 0;
if (A.is_sparse){
atr = atr | SP;
}
//atr = atr | A.symm;
Matrix<> AP(n, m, atr, *x.wrld);
Matrix<> PTAP(m, m, atr, *x.wrld);
//restrict A via triple matrix product, should probably be done outside v-cycle
AP["lj"] = A["lk"]*P["kj"];
PTAP["ij"] = P["li"]*AP["lj"];
//recurse into coarser level
vcycle(PTAP, zx, PTr, T+1, m, nlevel-1, nsmooth);
// zx.print();
//interpolate solution to residual equation at coraser level back
x["i"] += P["ij"]*zx["j"];
//smooth new solution
r["i"] = b["i"];
r["i"] -= A["ij"]*x["j"];
double rnorm2 = r.norm2();
smooth_jacobi(A,x,b,nsmooth);
r["i"] = b["i"];
r["i"] -= A["ij"]*x["j"];
double rnorm3 = r.norm2();
if (A.wrld->rank == 0) printf("At level %d, residual norm was %1.2E initially\n",nlevel,rnorm0);
if (A.wrld->rank == 0) printf("At level %d, residual norm was %1.2E after initial smooth\n",nlevel,rnorm);
if (A.wrld->rank == 0) printf("At level %d, residual norm was %1.2E after coarse recursion\n",nlevel,rnorm2);
if (A.wrld->rank == 0) printf("At level %d, residual norm was %1.2E after final smooth\n",nlevel,rnorm3);
if (A.wrld->rank == 0) printf("At level %d, residual norm was %1.2E if we skipped the coarsening\n",nlevel,rnorm_alt);
}
/**
* \brief computes Multigrid for a 3D regular discretization
*/
int algebraic_multigrid(int n,
double sp_frac,
int nlvl,
int ndiv,
int nsmooth,
int decay_exp,
World & dw){
Vector<> x(n, dw);
Vector<> b(n, dw);
x.fill_random(0.0, 1.0);
b.fill_random(0.0, 1.0);
Matrix<> A(n, n, SP, dw);
A.fill_sp_random(0.0, 1.0, sp_frac);
A["ij"] += A["ji"];
A["ii"] += sqrt((double)n);
// Transform<>([](double & d){ d = fabs(d).; })(A["ii"]);
// A.print();
Vector<int> N(n, dw);
int64_t * inds;
int * vals;
int64_t nvals;
N.read_local(&nvals, &inds, &vals);
for (int i=0; i<nvals; i++){
vals[i] = (int)inds[i];
}
N.write(nvals, inds, vals);
free(vals);
free(inds);
int curootn = (int)(pow((double)n,1./3.)+.001);
// printf("curootn = %d\n",curootn);
Matrix<std::pair<double, int>> B(n,n,SP,dw,Set<std::pair<double, int>>());
B["ij"] = Function< double, std::pair<double,int> >([](double d){ return std::pair<double,int>(d,0); })(A["ij"]);
Transform< int, std::pair<double,int> >([](int i, std::pair<double,int> & d){ d.second = i; } )(N["i"], B["ij"]);
Transform< int, std::pair<double,int> >([](int i, std::pair<double,int> & d){ d.second = abs(d.second-d.first); } )(N["j"], B["ij"]);
Transform< std::pair<double,int> >([=](std::pair<double,int> & d){
int x = d.second % curootn;
int y = (d.second / curootn) % curootn;
int z = d.second / curootn / curootn;
if (x+y+z > 0)
d.first = d.first/pow((double)(x+y+z),decay_exp/2.);
}
)(B["ij"]);
A["ij"] = Function< std::pair<double,int>, double >([](std::pair<double,int> p){ return p.first; })(B["ij"]);
Vector<> r(b);
r["i"] -= A["ij"]*x["j"];
double err = r.norm2();
Matrix<> * T = new Matrix<>[nlvl];
int m=n;
for (int i=0; i<nlvl; i++){
int m2 = m/ndiv;
T[i] = Matrix<>(m, m2, SP, dw);
std::vector< Pair<> > pairs;
for (int64_t j=dw.rank; j<m2; j+=dw.np){
for (int k=0; k<ndiv; k++){
pairs.push_back(Pair<>(j*m+j*ndiv+k, 1.0));
}
}
T[i].write(pairs.size(), &(pairs[0]));
m = m2;
}
vcycle(A, x, b, T, n, nlvl, nsmooth);
delete [] T;
r["i"] = b["i"];
r["i"] -= A["ij"]*x["j"];
double err2 = r.norm2();
bool pass = err2 < err;
if (dw.rank == 0){
#ifndef TEST_SUITE
printf("original err = %E, new err = %E\n",err,err2);
#endif
if (pass)
printf("{ algebraic multigrid method } passed \n");
else
printf("{ algebraic multigrid method } failed \n");
}
return pass;
}
#ifndef TEST_SUITE
char* getCmdOption(char ** begin,
char ** end,
const std::string & option){
char ** itr = std::find(begin, end, option);
if (itr != end && ++itr != end){
return *itr;
}
return 0;
}
int main(int argc, char ** argv){
int rank, np, n, pass, nlvl, ndiv, decay_exp, nsmooth;
double sp_frac;
int const in_num = argc;
char ** input_str = argv;
MPI_Init(&argc, &argv);
MPI_Comm_rank(MPI_COMM_WORLD, &rank);
MPI_Comm_size(MPI_COMM_WORLD, &np);
if (getCmdOption(input_str, input_str+in_num, "-n")){
n = atoi(getCmdOption(input_str, input_str+in_num, "-n"));
if (n < 0) n = 16;
} else n = 16;
if (getCmdOption(input_str, input_str+in_num, "-nlvl")){
nlvl = atoi(getCmdOption(input_str, input_str+in_num, "-nlvl"));
if (nlvl < 0) nlvl = 3;
} else nlvl = 3;
if (getCmdOption(input_str, input_str+in_num, "-ndiv")){
ndiv = atoi(getCmdOption(input_str, input_str+in_num, "-ndiv"));
if (ndiv < 0) ndiv = 2;
} else ndiv = 2;
if (getCmdOption(input_str, input_str+in_num, "-nsmooth")){
nsmooth = atoi(getCmdOption(input_str, input_str+in_num, "-nsmooth"));
if (nsmooth < 0) nsmooth = 3;
} else nsmooth = 3;
if (getCmdOption(input_str, input_str+in_num, "-decay_exp")){
decay_exp = atoi(getCmdOption(input_str, input_str+in_num, "-decay_exp"));
if (decay_exp < 0) decay_exp = 3;
} else decay_exp = 3;
if (getCmdOption(input_str, input_str+in_num, "-sp_frac")){
sp_frac = atof(getCmdOption(input_str, input_str+in_num, "-sp_frac"));
if (sp_frac < 0) sp_frac = .01;
} else sp_frac = .01;
int tot_ndiv=1;
for (int i=0; i<nlvl; i++){ tot_ndiv *= ndiv; }
assert(n%tot_ndiv == 0);
{
World dw(argc, argv);
if (rank == 0){
printf("Running algebraic smoothed multigrid method with %d levels with divisor %d in V-cycle, %d elements, %d smooth iterations, decayed based on 3D indexing with decay exponent of %d\n",nlvl,ndiv,n,nsmooth, decay_exp);
}
pass = algebraic_multigrid(n, sp_frac, nlvl, ndiv, nsmooth, decay_exp, dw);
assert(pass);
}
MPI_Finalize();
return 0;
}
/**
* @}
* @}
*/
#endif
<|endoftext|> |
<commit_before>#include "util/util.h"
#include <cstring>
#include <event2/thread.h>
#include <evhtp.h>
#include <fstream>
#include <glog/logging.h>
#include <iostream>
#include <netinet/in.h> // for resolv.h
#include <openssl/crypto.h>
#include <openssl/err.h>
#include <openssl/ssl.h>
#include <resolv.h> // for b64_ntop
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string>
#include <sstream>
#include <sys/time.h>
#include <unistd.h>
#include <vector>
#include "log/ct_extensions.h"
#include "version.h"
using std::getline;
using std::move;
using std::string;
using std::stringstream;
using std::vector;
namespace util {
namespace {
const char nibble[] = "0123456789abcdef";
char ByteValue(char high, char low) {
CHECK(('0' <= high && high <= '9') || ('a' <= high && high <= 'f'));
char ret;
if (high <= '9')
ret = (high - '0') << 4;
else
ret = (high - 'W') << 4; // 'a' - 'W' = 0x61 - 0x57 = 0x0a
if (low <= '9')
ret += low - '0';
else
ret += low - 'W';
return ret;
}
} // namespace
string HexString(const string& data) {
string ret;
for (unsigned int i = 0; i < data.size(); ++i) {
ret.push_back(nibble[(data[i] >> 4) & 0xf]);
ret.push_back(nibble[data[i] & 0xf]);
}
return ret;
}
string HexString(const string& data, char byte_delimiter) {
string ret;
if (data.empty())
return ret;
for (unsigned int i = 0; i < data.size(); ++i) {
if (i != 0)
ret.push_back(byte_delimiter);
ret.push_back(nibble[(data[i] >> 4) & 0xf]);
ret.push_back(nibble[data[i] & 0xf]);
}
return ret;
}
string BinaryString(const string& hex_string) {
string ret;
CHECK(!(hex_string.size() % 2));
for (size_t i = 0; i < hex_string.size(); i += 2)
ret.push_back(ByteValue(hex_string[i], hex_string[i + 1]));
return ret;
}
static char* ReadFileStreamToBuffer(std::ifstream& in, int* length) {
CHECK(in.good());
in.seekg(0, std::ios::end);
int file_length = in.tellg();
// Rewind.
in.seekg(0, std::ios::beg);
// Now write the proof.
char* buf = new char[file_length];
in.read(buf, file_length);
CHECK(!in.bad());
CHECK_EQ(in.gcount(), file_length);
in.close();
*length = file_length;
return buf;
}
bool ReadTextFile(const string& file, string* contents) {
int file_length;
std::ifstream in(file.c_str(), std::ios::in);
if (!in.good())
return false;
char* buf = ReadFileStreamToBuffer(in, &file_length);
contents->assign(string(buf, file_length));
delete[] buf;
return true;
}
bool ReadBinaryFile(const string& file, string* contents) {
int file_length;
std::ifstream in(file.c_str(), std::ios::in | std::ios::binary);
if (!in.good())
return false;
char* buf = ReadFileStreamToBuffer(in, &file_length);
contents->assign(string(buf, file_length));
delete[] buf;
return true;
}
string WriteTemporaryBinaryFile(const string& file_template,
const string& data) {
size_t strlen = file_template.size() + 1;
char* template_buf = new char[strlen];
memcpy(template_buf, file_template.data(), file_template.size());
template_buf[strlen - 1] = '\0';
int fd = mkstemp(template_buf);
string tmp_file;
if (fd >= 0) {
tmp_file = string(template_buf);
ssize_t bytes_written =
write(fd, reinterpret_cast<const char*>(data.data()), data.length());
close(fd);
if (bytes_written < 0 ||
static_cast<size_t>(bytes_written) < data.length()) {
// Write failed; try to clean up.
remove(tmp_file.c_str());
tmp_file.clear();
}
}
delete[] template_buf;
return tmp_file;
}
string CreateTemporaryDirectory(const string& dir_template) {
size_t strlen = dir_template.size() + 1;
char* template_buf = new char[strlen];
memcpy(template_buf, dir_template.data(), dir_template.size());
template_buf[strlen - 1] = '\0';
char* tmpdir = mkdtemp(template_buf);
string ret;
if (tmpdir != NULL)
ret = string(tmpdir);
delete[] template_buf;
return ret;
}
uint64_t TimeInMilliseconds() {
struct timeval tv;
gettimeofday(&tv, NULL);
return static_cast<uint64_t>(tv.tv_sec) * 1000 +
static_cast<uint64_t>(tv.tv_usec) / 1000;
}
string RandomString(size_t min_length, size_t max_length) {
size_t length = min_length == max_length
? min_length
: rand() % (max_length - min_length) + min_length;
string ret;
for (; length > 0; --length)
ret.append(1, rand() & 0xff);
return ret;
}
string FromBase64(const char* b64) {
size_t length = strlen(b64);
// Lazy: base 64 encoding is always >= in length to decoded value
// (equality occurs for zero length).
u_char* buf = new u_char[length];
int rlength = b64_pton(b64, buf, length);
// Treat decode errors as empty strings.
if (rlength < 0)
rlength = 0;
string ret(reinterpret_cast<char*>(buf), rlength);
delete[] buf;
return ret;
}
string ToBase64(const string& from) {
// base 64 is 4 output bytes for every 3 input bytes (rounded up).
size_t length = ((from.size() + 2) / 3) * 4;
char* buf = new char[length + 1];
length =
b64_ntop((const u_char*)from.data(), from.length(), buf, length + 1);
string ret(buf, length);
delete[] buf;
return ret;
}
vector<string> split(const string& in, char delim) {
vector<string> ret;
string item;
stringstream ss(in);
while (getline(ss, item, delim)) {
if (!item.empty()) {
ret.emplace_back(move(item));
}
}
return ret;
}
} // namespace util
<commit_msg>Removes unused includes from cpp/util/util.cc<commit_after>#include "util/util.h"
#include <cstring>
#include <fstream>
#include <glog/logging.h>
#include <iostream>
#include <netinet/in.h> // for resolv.h
#include <resolv.h> // for b64_ntop
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string>
#include <sstream>
#include <sys/time.h>
#include <unistd.h>
#include <vector>
#include "log/ct_extensions.h"
#include "version.h"
using std::getline;
using std::move;
using std::string;
using std::stringstream;
using std::vector;
namespace util {
namespace {
const char nibble[] = "0123456789abcdef";
char ByteValue(char high, char low) {
CHECK(('0' <= high && high <= '9') || ('a' <= high && high <= 'f'));
char ret;
if (high <= '9')
ret = (high - '0') << 4;
else
ret = (high - 'W') << 4; // 'a' - 'W' = 0x61 - 0x57 = 0x0a
if (low <= '9')
ret += low - '0';
else
ret += low - 'W';
return ret;
}
} // namespace
string HexString(const string& data) {
string ret;
for (unsigned int i = 0; i < data.size(); ++i) {
ret.push_back(nibble[(data[i] >> 4) & 0xf]);
ret.push_back(nibble[data[i] & 0xf]);
}
return ret;
}
string HexString(const string& data, char byte_delimiter) {
string ret;
if (data.empty())
return ret;
for (unsigned int i = 0; i < data.size(); ++i) {
if (i != 0)
ret.push_back(byte_delimiter);
ret.push_back(nibble[(data[i] >> 4) & 0xf]);
ret.push_back(nibble[data[i] & 0xf]);
}
return ret;
}
string BinaryString(const string& hex_string) {
string ret;
CHECK(!(hex_string.size() % 2));
for (size_t i = 0; i < hex_string.size(); i += 2)
ret.push_back(ByteValue(hex_string[i], hex_string[i + 1]));
return ret;
}
static char* ReadFileStreamToBuffer(std::ifstream& in, int* length) {
CHECK(in.good());
in.seekg(0, std::ios::end);
int file_length = in.tellg();
// Rewind.
in.seekg(0, std::ios::beg);
// Now write the proof.
char* buf = new char[file_length];
in.read(buf, file_length);
CHECK(!in.bad());
CHECK_EQ(in.gcount(), file_length);
in.close();
*length = file_length;
return buf;
}
bool ReadTextFile(const string& file, string* contents) {
int file_length;
std::ifstream in(file.c_str(), std::ios::in);
if (!in.good())
return false;
char* buf = ReadFileStreamToBuffer(in, &file_length);
contents->assign(string(buf, file_length));
delete[] buf;
return true;
}
bool ReadBinaryFile(const string& file, string* contents) {
int file_length;
std::ifstream in(file.c_str(), std::ios::in | std::ios::binary);
if (!in.good())
return false;
char* buf = ReadFileStreamToBuffer(in, &file_length);
contents->assign(string(buf, file_length));
delete[] buf;
return true;
}
string WriteTemporaryBinaryFile(const string& file_template,
const string& data) {
size_t strlen = file_template.size() + 1;
char* template_buf = new char[strlen];
memcpy(template_buf, file_template.data(), file_template.size());
template_buf[strlen - 1] = '\0';
int fd = mkstemp(template_buf);
string tmp_file;
if (fd >= 0) {
tmp_file = string(template_buf);
ssize_t bytes_written =
write(fd, reinterpret_cast<const char*>(data.data()), data.length());
close(fd);
if (bytes_written < 0 ||
static_cast<size_t>(bytes_written) < data.length()) {
// Write failed; try to clean up.
remove(tmp_file.c_str());
tmp_file.clear();
}
}
delete[] template_buf;
return tmp_file;
}
string CreateTemporaryDirectory(const string& dir_template) {
size_t strlen = dir_template.size() + 1;
char* template_buf = new char[strlen];
memcpy(template_buf, dir_template.data(), dir_template.size());
template_buf[strlen - 1] = '\0';
char* tmpdir = mkdtemp(template_buf);
string ret;
if (tmpdir != NULL)
ret = string(tmpdir);
delete[] template_buf;
return ret;
}
uint64_t TimeInMilliseconds() {
struct timeval tv;
gettimeofday(&tv, NULL);
return static_cast<uint64_t>(tv.tv_sec) * 1000 +
static_cast<uint64_t>(tv.tv_usec) / 1000;
}
string RandomString(size_t min_length, size_t max_length) {
size_t length = min_length == max_length
? min_length
: rand() % (max_length - min_length) + min_length;
string ret;
for (; length > 0; --length)
ret.append(1, rand() & 0xff);
return ret;
}
string FromBase64(const char* b64) {
size_t length = strlen(b64);
// Lazy: base 64 encoding is always >= in length to decoded value
// (equality occurs for zero length).
u_char* buf = new u_char[length];
int rlength = b64_pton(b64, buf, length);
// Treat decode errors as empty strings.
if (rlength < 0)
rlength = 0;
string ret(reinterpret_cast<char*>(buf), rlength);
delete[] buf;
return ret;
}
string ToBase64(const string& from) {
// base 64 is 4 output bytes for every 3 input bytes (rounded up).
size_t length = ((from.size() + 2) / 3) * 4;
char* buf = new char[length + 1];
length =
b64_ntop((const u_char*)from.data(), from.length(), buf, length + 1);
string ret(buf, length);
delete[] buf;
return ret;
}
vector<string> split(const string& in, char delim) {
vector<string> ret;
string item;
stringstream ss(in);
while (getline(ss, item, delim)) {
if (!item.empty()) {
ret.emplace_back(move(item));
}
}
return ret;
}
} // namespace util
<|endoftext|> |
<commit_before>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
#ifndef _PYUNO_PYUNO_HXX_
#define _PYUNO_PYUNO_HXX_
#ifndef Py_PYTHON_H
#if defined _MSC_VER
#pragma warning(push, 1)
#endif
#ifdef _DEBUG
#undef _DEBUG
#include <Python.h>
#define _DEBUG
#else
#include <Python.h>
#endif // #ifdef _DEBUG
#if defined _MSC_VER
#pragma warning(pop)
#endif
#endif // #ifdef Py_PYTHON_H
#include <com/sun/star/uno/XComponentContext.hpp>
#include <com/sun/star/script/CannotConvertException.hpp>
#include <com/sun/star/lang/IllegalArgumentException.hpp>
/**
External interface of the Python UNO bridge.
This is a C++ interface, because the core UNO components
invocation and proxyfactory are used to implement the bridge.
This interface is somewhat private and my change in future.
A scripting framework implementation may use this interface
to do the necessary conversions.
*/
#ifdef WIN32
#define PY_DLLEXPORT __declspec(dllexport)
#else
#define PY_DLLEXPORT
#endif
/** function called by the python runtime to initialize the
pyuno module.
preconditions: python has been initialized before and
the global interpreter lock is held
*/
extern "C" PY_DLLEXPORT
#if PY_MAJOR_VERSION >= 3
PyObject* SAL_CALL PyInit_pyuno();
#else
void SAL_CALL initpyuno();
#endif
namespace pyuno
{
/** Helper class for keeping references to python objects.
BEWARE: Look up every python function you use to check
wether you get an acquired or not acquired object pointer
(python terminus for a not acquired object pointer
is 'borrowed reference'). Use in the acquired pointer cases the
PyRef( pointer, SAL_NO_ACQUIRE) ctor.
precondition: python has been initialized before and
the global interpreter lock is held
*/
class PyRef
{
PyObject *m;
public:
PyRef () : m(0) {}
PyRef( PyObject * p ) : m( p ) { Py_XINCREF( m ); }
PyRef( PyObject * p, __sal_NoAcquire ) : m( p ) {}
PyRef( const PyRef &r ) : m( r.get() ) { Py_XINCREF( m ); }
~PyRef() { Py_XDECREF( m ); }
PyObject *get() const { return m; }
PyObject * getAcquired() const
{
Py_XINCREF( const_cast< PyObject*> (m) );
return m;
}
PyRef & operator = ( const PyRef & r )
{
PyObject *tmp = m;
m = r.getAcquired();
Py_XDECREF( tmp );
return *this;
}
bool operator == ( const PyRef & r ) const
{
return r.get() == m;
}
/** clears the reference without decreasing the reference count
only seldomly needed ! */
void scratch()
{
m = 0;
}
/** clears the reference decreasing the refcount of the holded object.
*/
void clear()
{
Py_XDECREF( m );
m = 0;
}
/** returns 1 when the reference points to a python object python object,
otherwise 0.
*/
sal_Bool is() const
{
return m != 0;
}
struct Hash
{
sal_IntPtr operator () ( const PyRef &r) const { return sal_IntPtr( r.get() ); }
};
};
struct stRuntimeImpl;
typedef struct stRuntimeImpl RuntimeImpl;
enum ConversionMode { ACCEPT_UNO_ANY, REJECT_UNO_ANY };
/** The pyuno::Runtime class keeps the internal state of the python UNO bridge
for the currently in use python interpreter.
You may keep a Runtime instance, use it from a different thread, etc. But you must
make sure to fulfill all preconditions mentioned for the specific methods.
*/
class PY_DLLEXPORT Runtime
{
RuntimeImpl *impl;
public:
~Runtime( );
/**
preconditions: python has been initialized before,
the global interpreter lock is held and pyuno
has been initialized for the currently used interpreter.
Note: This method exists for efficiency reasons to save
lookup costs for any2PyObject and pyObject2Any
@throw RuntimeException in case the runtime has not been
initialized before
*/
Runtime() throw( com::sun::star::uno::RuntimeException );
Runtime( const Runtime & );
Runtime & operator = ( const Runtime & );
/** Initializes the python-UNO bridge. May be called only once per python interpreter.
@param ctx the component context is used to instantiate bridge services needed
for bridging such as invocation, typeconverter, invocationadapterfactory, etc.
preconditions: python has been initialized before and
the global interpreter lock is held and pyuno is not
initialized (see isInitialized() ).
@throw RuntimeException in case the thread is not attached or the runtime
has not been initialized.
*/
static void SAL_CALL initialize(
const com::sun::star::uno::Reference< com::sun::star::uno::XComponentContext > & ctx )
throw ( com::sun::star::uno::RuntimeException );
/** Checks, whether the uno runtime is already initialized in the current python interpreter.
*/
static bool SAL_CALL isInitialized() throw (com::sun::star::uno::RuntimeException);
/** disposes the UNO bridge in this interpreter. All existing stubs/proxies
become non-functional, using these proxies/stubs leads to runtime errors.
preconditions: python has been initialized before and
the global interpreter lock is held and pyuno was
initialized before for the currently in use interpreter.
*/
static void SAL_CALL finalize() throw(com::sun::star::uno::RuntimeException );
/** converts something contained in an UNO Any to a Python object
preconditions: python has been initialized before,
the global interpreter lock is held and pyuno::Runtime
has been initialized.
*/
PyRef any2PyObject (const com::sun::star::uno::Any &source ) const
throw ( com::sun::star::script::CannotConvertException,
com::sun::star::lang::IllegalArgumentException,
com::sun::star::uno::RuntimeException );
/** converts a Python object to a UNO any
preconditions: python has been initialized before,
the global interpreter lock is held and pyuno
has been initialized
*/
com::sun::star::uno::Any pyObject2Any (
const PyRef & source , enum ConversionMode mode = REJECT_UNO_ANY ) const
throw ( com::sun::star::uno::RuntimeException);
/** extracts a proper uno exception from a given python exception
*/
com::sun::star::uno::Any extractUnoException(
const PyRef & excType, const PyRef & excValue, const PyRef & excTraceback) const;
/** Returns the internal handle. Should only be used by the module implementation
*/
RuntimeImpl *getImpl() const { return impl; }
};
/** helper class for attaching the current thread to the python runtime.
Attaching is done creating a new threadstate for the given interpreter
and acquiring the global interpreter lock.
Usage:
... don't use python here
{
PyThreadAttach guard( PyInterpreterState_Head() );
{
... do whatever python code you want
{
PyThreadDetach antiguard;
... don't use python here
}
... do whatever python code you want
}
}
... don't use python here
Note: The additional scope brackets after the PyThreadAttach are needed,
e.g. when you would leave them away, dtors of potential pyrefs
may be called after the thread has detached again.
*/
class PY_DLLEXPORT PyThreadAttach
{
PyThreadState *tstate;
PyThreadAttach ( const PyThreadAttach & ); // not implemented
PyThreadAttach & operator = ( const PyThreadAttach & );
public:
/** Creates a new python threadstate and acquires the global interpreter lock.
precondition: The current thread MUST NOT hold the global interpreter lock.
postcondition: The global interpreter lock is acquired
@raises com::sun::star::uno::RuntimeException
in case no pythread state could be created
*/
PyThreadAttach( PyInterpreterState *interp) throw ( com::sun::star::uno::RuntimeException );
/** Releases the global interpreter lock and destroys the thread state.
*/
~PyThreadAttach();
};
/** helper class for detaching the current thread from the python runtime
to do some blocking, non-python related operation.
@see PyThreadAttach
*/
class PY_DLLEXPORT PyThreadDetach
{
PyThreadState *tstate;
PyThreadDetach ( const PyThreadDetach & ); // not implemented
PyThreadDetach & operator = ( const PyThreadDetach & ); // not implemented
public:
/** Releases the global interpreter lock.
precondition: The current thread MUST hold the global interpreter lock.
postcondition: The current thread does not hold the global interpreter lock anymore.
*/
PyThreadDetach() throw ( com::sun::star::uno::RuntimeException );
/** Acquires the global interpreter lock again
*/
~PyThreadDetach();
};
}
#endif
/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
<commit_msg>Fix dbgutil build of pyuno<commit_after>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
#ifndef _PYUNO_PYUNO_HXX_
#define _PYUNO_PYUNO_HXX_
#ifndef Py_PYTHON_H
#if defined _MSC_VER
#pragma warning(push, 1)
#endif
#include <Python.h>
#if defined _MSC_VER
#pragma warning(pop)
#endif
#endif // #ifdef Py_PYTHON_H
#include <com/sun/star/uno/XComponentContext.hpp>
#include <com/sun/star/script/CannotConvertException.hpp>
#include <com/sun/star/lang/IllegalArgumentException.hpp>
/**
External interface of the Python UNO bridge.
This is a C++ interface, because the core UNO components
invocation and proxyfactory are used to implement the bridge.
This interface is somewhat private and my change in future.
A scripting framework implementation may use this interface
to do the necessary conversions.
*/
#ifdef WIN32
#define PY_DLLEXPORT __declspec(dllexport)
#else
#define PY_DLLEXPORT
#endif
/** function called by the python runtime to initialize the
pyuno module.
preconditions: python has been initialized before and
the global interpreter lock is held
*/
extern "C" PY_DLLEXPORT
#if PY_MAJOR_VERSION >= 3
PyObject* SAL_CALL PyInit_pyuno();
#else
void SAL_CALL initpyuno();
#endif
namespace pyuno
{
/** Helper class for keeping references to python objects.
BEWARE: Look up every python function you use to check
wether you get an acquired or not acquired object pointer
(python terminus for a not acquired object pointer
is 'borrowed reference'). Use in the acquired pointer cases the
PyRef( pointer, SAL_NO_ACQUIRE) ctor.
precondition: python has been initialized before and
the global interpreter lock is held
*/
class PyRef
{
PyObject *m;
public:
PyRef () : m(0) {}
PyRef( PyObject * p ) : m( p ) { Py_XINCREF( m ); }
PyRef( PyObject * p, __sal_NoAcquire ) : m( p ) {}
PyRef( const PyRef &r ) : m( r.get() ) { Py_XINCREF( m ); }
~PyRef() { Py_XDECREF( m ); }
PyObject *get() const { return m; }
PyObject * getAcquired() const
{
Py_XINCREF( const_cast< PyObject*> (m) );
return m;
}
PyRef & operator = ( const PyRef & r )
{
PyObject *tmp = m;
m = r.getAcquired();
Py_XDECREF( tmp );
return *this;
}
bool operator == ( const PyRef & r ) const
{
return r.get() == m;
}
/** clears the reference without decreasing the reference count
only seldomly needed ! */
void scratch()
{
m = 0;
}
/** clears the reference decreasing the refcount of the holded object.
*/
void clear()
{
Py_XDECREF( m );
m = 0;
}
/** returns 1 when the reference points to a python object python object,
otherwise 0.
*/
sal_Bool is() const
{
return m != 0;
}
struct Hash
{
sal_IntPtr operator () ( const PyRef &r) const { return sal_IntPtr( r.get() ); }
};
};
struct stRuntimeImpl;
typedef struct stRuntimeImpl RuntimeImpl;
enum ConversionMode { ACCEPT_UNO_ANY, REJECT_UNO_ANY };
/** The pyuno::Runtime class keeps the internal state of the python UNO bridge
for the currently in use python interpreter.
You may keep a Runtime instance, use it from a different thread, etc. But you must
make sure to fulfill all preconditions mentioned for the specific methods.
*/
class PY_DLLEXPORT Runtime
{
RuntimeImpl *impl;
public:
~Runtime( );
/**
preconditions: python has been initialized before,
the global interpreter lock is held and pyuno
has been initialized for the currently used interpreter.
Note: This method exists for efficiency reasons to save
lookup costs for any2PyObject and pyObject2Any
@throw RuntimeException in case the runtime has not been
initialized before
*/
Runtime() throw( com::sun::star::uno::RuntimeException );
Runtime( const Runtime & );
Runtime & operator = ( const Runtime & );
/** Initializes the python-UNO bridge. May be called only once per python interpreter.
@param ctx the component context is used to instantiate bridge services needed
for bridging such as invocation, typeconverter, invocationadapterfactory, etc.
preconditions: python has been initialized before and
the global interpreter lock is held and pyuno is not
initialized (see isInitialized() ).
@throw RuntimeException in case the thread is not attached or the runtime
has not been initialized.
*/
static void SAL_CALL initialize(
const com::sun::star::uno::Reference< com::sun::star::uno::XComponentContext > & ctx )
throw ( com::sun::star::uno::RuntimeException );
/** Checks, whether the uno runtime is already initialized in the current python interpreter.
*/
static bool SAL_CALL isInitialized() throw (com::sun::star::uno::RuntimeException);
/** disposes the UNO bridge in this interpreter. All existing stubs/proxies
become non-functional, using these proxies/stubs leads to runtime errors.
preconditions: python has been initialized before and
the global interpreter lock is held and pyuno was
initialized before for the currently in use interpreter.
*/
static void SAL_CALL finalize() throw(com::sun::star::uno::RuntimeException );
/** converts something contained in an UNO Any to a Python object
preconditions: python has been initialized before,
the global interpreter lock is held and pyuno::Runtime
has been initialized.
*/
PyRef any2PyObject (const com::sun::star::uno::Any &source ) const
throw ( com::sun::star::script::CannotConvertException,
com::sun::star::lang::IllegalArgumentException,
com::sun::star::uno::RuntimeException );
/** converts a Python object to a UNO any
preconditions: python has been initialized before,
the global interpreter lock is held and pyuno
has been initialized
*/
com::sun::star::uno::Any pyObject2Any (
const PyRef & source , enum ConversionMode mode = REJECT_UNO_ANY ) const
throw ( com::sun::star::uno::RuntimeException);
/** extracts a proper uno exception from a given python exception
*/
com::sun::star::uno::Any extractUnoException(
const PyRef & excType, const PyRef & excValue, const PyRef & excTraceback) const;
/** Returns the internal handle. Should only be used by the module implementation
*/
RuntimeImpl *getImpl() const { return impl; }
};
/** helper class for attaching the current thread to the python runtime.
Attaching is done creating a new threadstate for the given interpreter
and acquiring the global interpreter lock.
Usage:
... don't use python here
{
PyThreadAttach guard( PyInterpreterState_Head() );
{
... do whatever python code you want
{
PyThreadDetach antiguard;
... don't use python here
}
... do whatever python code you want
}
}
... don't use python here
Note: The additional scope brackets after the PyThreadAttach are needed,
e.g. when you would leave them away, dtors of potential pyrefs
may be called after the thread has detached again.
*/
class PY_DLLEXPORT PyThreadAttach
{
PyThreadState *tstate;
PyThreadAttach ( const PyThreadAttach & ); // not implemented
PyThreadAttach & operator = ( const PyThreadAttach & );
public:
/** Creates a new python threadstate and acquires the global interpreter lock.
precondition: The current thread MUST NOT hold the global interpreter lock.
postcondition: The global interpreter lock is acquired
@raises com::sun::star::uno::RuntimeException
in case no pythread state could be created
*/
PyThreadAttach( PyInterpreterState *interp) throw ( com::sun::star::uno::RuntimeException );
/** Releases the global interpreter lock and destroys the thread state.
*/
~PyThreadAttach();
};
/** helper class for detaching the current thread from the python runtime
to do some blocking, non-python related operation.
@see PyThreadAttach
*/
class PY_DLLEXPORT PyThreadDetach
{
PyThreadState *tstate;
PyThreadDetach ( const PyThreadDetach & ); // not implemented
PyThreadDetach & operator = ( const PyThreadDetach & ); // not implemented
public:
/** Releases the global interpreter lock.
precondition: The current thread MUST hold the global interpreter lock.
postcondition: The current thread does not hold the global interpreter lock anymore.
*/
PyThreadDetach() throw ( com::sun::star::uno::RuntimeException );
/** Acquires the global interpreter lock again
*/
~PyThreadDetach();
};
}
#endif
/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
<|endoftext|> |
<commit_before>// Copyright (c) 2013-2015 mogemimi.
// Distributed under the MIT license. See LICENSE.md file for details.
#ifndef POMDOG_ASSERT_7D111D58_HPP
#define POMDOG_ASSERT_7D111D58_HPP
#include "Pomdog/Basic/Platform.hpp"
#include <cassert>
#ifdef POMDOG_COMPILER_MSVC
# include <xutility>
#endif
namespace Pomdog {
namespace Detail {
namespace Assertion {
//inline void ReportAssertionFailure(char const* expression,
// char const* filename, int line, char const* function){
// // notes: std::cerr in <iostream>
// std::cerr << "Assertion failed: " << expression << ", function "
// << function << ", file " << filename << ", line " << line << ".\n";
//}
inline void RuntimeAssertion(char const* /*expression*/, char const* /*filename*/, int /*line*/)
{
//ReportAssertionFailure(expression, filename, line, "(unknown)");
assert(false);
}
inline constexpr bool ConstexprAssert(bool condition,
char const* expression, char const* filename, int line) {
return condition ? true: (RuntimeAssertion(expression, filename, line), false);
}
}// namespace Assertion
// @code
// //how to use:
// POMDOG_ASSERT(expr);
// POMDOG_ASSERT_MESSAGE(expr, "message");
// @endcode
#if defined(DEBUG) && defined(__APPLE_CC__)
# // Debug mode for Xcode 5
# define POMDOG_ASSERT(expression) POMDOG_ASSERT_MESSAGE(expression, "POMDOG_ASSERT")
# define POMDOG_ASSERT_MESSAGE(expression, message) \
do {\
if (!(expression)) {\
assert(message && expression);\
}\
} while(false)
# define POMDOG_CONSTEXPR_ASSERT(expression) \
static_cast<void>(Pomdog::Detail::Assertion::ConstexprAssert(\
static_cast<bool>(expression), #expression, __FILE__, __LINE__))
#elif defined(DEBUG) && defined(_MSC_VER)
# // Debug mode under Visual Studio
# define POMDOG_ASSERT(expression) \
static_cast<void>((!!(expression)) || (_CrtDbgBreak(), _ASSERT(expression), false))
# define POMDOG_ASSERT_MESSAGE(expression, message) \
static_cast<void>((!!(expression)) \
|| (1 != _CrtDbgReportW(_CRT_ASSERT, _CRT_WIDE(__FILE__), __LINE__, nullptr, L"%s", message)) \
|| (_CrtDbgBreak(), false))
#elif defined(DEBUG)
# // Debug mode
# if defined(_MSC_VER)
# define POMDOG_DEBUGBREAK() __debugbreak()
# elif defined(linux) || defined(__linux) || defined(__linux__)
# define POMDOG_DEBUGBREAK() raise(SIGTRAP)
# elif defined(POMDOG_ARCHITECTURE_POWERPC)
# define POMDOG_DEBUGBREAK() asm {trap}
# else
# define POMDOG_DEBUGBREAK() __asm { int 3 } // MS-style inline assembly
# endif
# define POMDOG_ASSERT(expression) POMDOG_ASSERT_MESSAGE(expression, "POMDOG_ASSERT")
# define POMDOG_ASSERT_MESSAGE(expression, message) \
do {\
if (!(expression)) {\
assert(message && expression) \
POMDOG_DEBUGBREAK(); \
}\
} while(false)
#else //!defined(DEBUG) || defined(NDEBUG)
# // Release mode
# define POMDOG_ASSERT(expression)
# define POMDOG_ASSERT_MESSAGE(expression, message)
# define POMDOG_CONSTEXPR_ASSERT(expression) static_cast<void const>(0)
#endif
}// namespace Detail
}// namespace Pomdog
#endif // POMDOG_ASSERT_7D111D58_HPP
<commit_msg>Clean up Assert.hpp<commit_after>// Copyright (c) 2013-2015 mogemimi.
// Distributed under the MIT license. See LICENSE.md file for details.
#ifndef POMDOG_ASSERT_7D111D58_HPP
#define POMDOG_ASSERT_7D111D58_HPP
#include "Pomdog/Basic/Platform.hpp"
#include <cassert>
#if defined(_MSC_VER)
#include <xutility>
#endif
namespace Pomdog {
namespace Detail {
namespace Assertion {
//inline void ReportAssertionFailure(char const* expression,
// char const* filename, int line, char const* function){
// // notes: std::cerr in <iostream>
// std::cerr << "Assertion failed: " << expression << ", function "
// << function << ", file " << filename << ", line " << line << ".\n";
//}
inline void RuntimeAssertion(char const* /*expression*/, char const* /*filename*/, int /*line*/)
{
//ReportAssertionFailure(expression, filename, line, "(unknown)");
assert(false);
}
inline constexpr bool ConstexprAssert(bool condition,
char const* expression, char const* filename, int line) {
return condition ? true: (RuntimeAssertion(expression, filename, line), false);
}
} // namespace Assertion
// How to use:
// POMDOG_ASSERT(expr);
// POMDOG_ASSERT_MESSAGE(expr, "message");
#if defined(DEBUG) && defined(__APPLE_CC__)
# // Debug mode under Xcode
# define POMDOG_ASSERT(expression) POMDOG_ASSERT_MESSAGE(expression, "POMDOG_ASSERT")
# define POMDOG_ASSERT_MESSAGE(expression, message) \
do {\
if (!(expression)) {\
assert(message && expression);\
}\
} while(false)
# define POMDOG_CONSTEXPR_ASSERT(expression) \
static_cast<void>(Pomdog::Detail::Assertion::ConstexprAssert(\
static_cast<bool>(expression), #expression, __FILE__, __LINE__))
#elif defined(DEBUG) && defined(_MSC_VER)
# // Debug mode under Visual Studio
# define POMDOG_ASSERT(expression) \
static_cast<void>((!!(expression)) || (_CrtDbgBreak(), _ASSERT(expression), false))
# define POMDOG_ASSERT_MESSAGE(expression, message) \
static_cast<void>((!!(expression)) \
|| (1 != _CrtDbgReportW(_CRT_ASSERT, _CRT_WIDE(__FILE__), __LINE__, nullptr, L"%s", message)) \
|| (_CrtDbgBreak(), false))
#elif defined(DEBUG)
# // Debug mode
# if defined(_MSC_VER)
# define POMDOG_DEBUGBREAK() __debugbreak()
# elif defined(linux) || defined(__linux) || defined(__linux__)
# define POMDOG_DEBUGBREAK() raise(SIGTRAP)
# elif defined(POMDOG_ARCHITECTURE_POWERPC)
# define POMDOG_DEBUGBREAK() asm {trap}
# else
# define POMDOG_DEBUGBREAK() __asm { int 3 } // MS-style inline assembly
# endif
# define POMDOG_ASSERT(expression) POMDOG_ASSERT_MESSAGE(expression, "POMDOG_ASSERT")
# define POMDOG_ASSERT_MESSAGE(expression, message) \
do {\
if (!(expression)) {\
assert(message && expression) \
POMDOG_DEBUGBREAK(); \
}\
} while(false)
#else
# // Release mode
# define POMDOG_ASSERT(expression)
# define POMDOG_ASSERT_MESSAGE(expression, message)
# define POMDOG_CONSTEXPR_ASSERT(expression) static_cast<void const>(0)
#endif
} // namespace Detail
} // namespace Pomdog
#endif // POMDOG_ASSERT_7D111D58_HPP
<|endoftext|> |
<commit_before>/*************************************************************************
*
* $RCSfile: arealink.hxx,v $
*
* $Revision: 1.5 $
*
* last change: $Author: dr $ $Date: 2001-04-24 14:43:38 $
*
* The Contents of this file are made available subject to the terms of
* either of the following licenses
*
* - GNU Lesser General Public License Version 2.1
* - Sun Industry Standards Source License Version 1.1
*
* Sun Microsystems Inc., October, 2000
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2000 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
*
* Sun Industry Standards Source License Version 1.1
* =================================================
* The contents of this file are subject to the Sun Industry Standards
* Source License Version 1.1 (the "License"); You may not use this file
* except in compliance with the License. You may obtain a copy of the
* License at http://www.openoffice.org/license.html.
*
* Software provided under this License is provided on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
* WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
* MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
* See the License for the specific provisions governing your rights and
* obligations concerning the Software.
*
* The Initial Developer of the Original Code is: Sun Microsystems, Inc.
*
* Copyright: 2000 by Sun Microsystems, Inc.
*
* All Rights Reserved.
*
* Contributor(s): _______________________________________
*
*
************************************************************************/
#ifndef SC_AREALINK_HXX
#define SC_AREALINK_HXX
#ifndef SC_SCGLOB_HXX
#include "global.hxx"
#endif
#ifndef SC_REFRESHTIMER_HXX
#include "refreshtimer.hxx"
#endif
#ifndef _LNKBASE_HXX //autogen
#include <so3/lnkbase.hxx>
#endif
class ScDocShell;
class SfxObjectShell;
class ScAreaLink : public ::so3::SvBaseLink, public ScRefreshTimer
{
private:
ScDocShell* pDocShell; // Container
String aFileName;
String aFilterName;
String aOptions;
String aSourceArea;
ScRange aDestArea;
BOOL bAddUndo;
BOOL bInCreate;
BOOL bDoInsert; // wird fuer das erste Update auf FALSE gesetzt
BOOL FindExtRange( ScRange& rRange, ScDocument* pSrcDoc, const String& rAreaName );
public:
TYPEINFO();
ScAreaLink( SfxObjectShell* pShell, const String& rFile,
const String& rFilter, const String& rOpt,
const String& rArea, const ScRange& rDest, ULONG nRefresh );
virtual ~ScAreaLink();
virtual void Closed();
virtual void DataChanged( const String& rMimeType,
const ::com::sun::star::uno::Any & rValue );
virtual BOOL Edit(Window* pParent);
BOOL Refresh( const String& rNewFile, const String& rNewFilter,
const String& rNewArea, ULONG nNewRefresh );
void SetInCreate(BOOL bSet) { bInCreate = bSet; }
void SetDoInsert(BOOL bSet) { bDoInsert = bSet; }
void SetDestArea(const ScRange& rNew);
void SetSource(const String& rDoc, const String& rFlt, const String& rOpt,
const String& rArea);
BOOL IsEqual( const String& rFile, const String& rFilter, const String& rOpt,
const String& rSource, const ScRange& rDest ) const;
const String& GetFile() const { return aFileName; }
const String& GetFilter() const { return aFilterName; }
const String& GetOptions() const { return aOptions; }
const String& GetSource() const { return aSourceArea; }
const ScRange& GetDestArea() const { return aDestArea; }
DECL_LINK( RefreshHdl, ScAreaLink* );
};
#endif
<commit_msg>INTEGRATION: CWS rowlimit (1.5.334); FILE MERGED 2003/11/28 19:47:16 er 1.5.334.1: #i1967# move ScAddress, ScRange from global.hxx to address.hxx<commit_after>/*************************************************************************
*
* $RCSfile: arealink.hxx,v $
*
* $Revision: 1.6 $
*
* last change: $Author: obo $ $Date: 2004-06-04 10:01:12 $
*
* The Contents of this file are made available subject to the terms of
* either of the following licenses
*
* - GNU Lesser General Public License Version 2.1
* - Sun Industry Standards Source License Version 1.1
*
* Sun Microsystems Inc., October, 2000
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2000 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
*
* Sun Industry Standards Source License Version 1.1
* =================================================
* The contents of this file are subject to the Sun Industry Standards
* Source License Version 1.1 (the "License"); You may not use this file
* except in compliance with the License. You may obtain a copy of the
* License at http://www.openoffice.org/license.html.
*
* Software provided under this License is provided on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
* WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
* MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
* See the License for the specific provisions governing your rights and
* obligations concerning the Software.
*
* The Initial Developer of the Original Code is: Sun Microsystems, Inc.
*
* Copyright: 2000 by Sun Microsystems, Inc.
*
* All Rights Reserved.
*
* Contributor(s): _______________________________________
*
*
************************************************************************/
#ifndef SC_AREALINK_HXX
#define SC_AREALINK_HXX
#ifndef SC_SCGLOB_HXX
#include "global.hxx"
#endif
#ifndef SC_REFRESHTIMER_HXX
#include "refreshtimer.hxx"
#endif
#ifndef SC_ADDRESS_HXX
#include "address.hxx"
#endif
#ifndef _LNKBASE_HXX //autogen
#include <so3/lnkbase.hxx>
#endif
class ScDocShell;
class SfxObjectShell;
class ScAreaLink : public ::so3::SvBaseLink, public ScRefreshTimer
{
private:
ScDocShell* pDocShell; // Container
String aFileName;
String aFilterName;
String aOptions;
String aSourceArea;
ScRange aDestArea;
BOOL bAddUndo;
BOOL bInCreate;
BOOL bDoInsert; // wird fuer das erste Update auf FALSE gesetzt
BOOL FindExtRange( ScRange& rRange, ScDocument* pSrcDoc, const String& rAreaName );
public:
TYPEINFO();
ScAreaLink( SfxObjectShell* pShell, const String& rFile,
const String& rFilter, const String& rOpt,
const String& rArea, const ScRange& rDest, ULONG nRefresh );
virtual ~ScAreaLink();
virtual void Closed();
virtual void DataChanged( const String& rMimeType,
const ::com::sun::star::uno::Any & rValue );
virtual BOOL Edit(Window* pParent);
BOOL Refresh( const String& rNewFile, const String& rNewFilter,
const String& rNewArea, ULONG nNewRefresh );
void SetInCreate(BOOL bSet) { bInCreate = bSet; }
void SetDoInsert(BOOL bSet) { bDoInsert = bSet; }
void SetDestArea(const ScRange& rNew);
void SetSource(const String& rDoc, const String& rFlt, const String& rOpt,
const String& rArea);
BOOL IsEqual( const String& rFile, const String& rFilter, const String& rOpt,
const String& rSource, const ScRange& rDest ) const;
const String& GetFile() const { return aFileName; }
const String& GetFilter() const { return aFilterName; }
const String& GetOptions() const { return aOptions; }
const String& GetSource() const { return aSourceArea; }
const ScRange& GetDestArea() const { return aDestArea; }
DECL_LINK( RefreshHdl, ScAreaLink* );
};
#endif
<|endoftext|> |
<commit_before>/**
* This file implements the _d2_ API.
*/
#define D2_SOURCE
#include <d2/api.hpp>
#include <d2/detail/basic_atomic.hpp>
#include <d2/detail/basic_mutex.hpp>
#include <d2/detail/config.hpp>
#include <d2/events.hpp>
#include <d2/filesystem_dispatcher.hpp>
#include <d2/sync_object.hpp>
#include <d2/thread.hpp>
#include <stddef.h>
namespace d2 {
namespace detail {
template <typename Value, typename Container>
bool contains(Value const& v, Container const& c) {
return c.find(v) != c.end();
}
static FilesystemDispatcher dispatcher;
static basic_atomic<bool> event_logging_enabled(false);
} // end namespace detail
} // end namespace d2
D2_API extern void d2_disable_event_logging(void) {
d2::detail::event_logging_enabled = false;
}
D2_API extern void d2_enable_event_logging(void) {
d2::detail::event_logging_enabled = true;
}
D2_API extern int d2_is_enabled(void) {
return d2::detail::event_logging_enabled ? 1 : 0;
}
D2_API extern int d2_is_disabled(void) {
return d2_is_enabled() ? 0 : 1;
}
D2_API extern int d2_set_log_repository(char const* path) {
// Note: 0 for success and anything else but 0 for failure.
return d2::detail::dispatcher.set_repository_noexcept(path) ? 0 : 1;
}
D2_API extern void d2_notify_acquire(size_t thread_id, size_t lock_id) {
using namespace d2;
using namespace d2::detail;
if (d2_is_enabled()) {
AcquireEvent event((SyncObject(lock_id)), Thread(thread_id));
// ignore current frame
event.info.init_call_stack(1);
dispatcher.dispatch(event);
}
}
D2_API extern void d2_notify_recursive_acquire(size_t thread_id,
size_t lock_id) {
using namespace d2;
using namespace d2::detail;
if (d2_is_enabled()) {
RecursiveAcquireEvent event((SyncObject(lock_id)), Thread(thread_id));
// ignore current frame
event.info.init_call_stack(1);
dispatcher.dispatch(event);
}
}
D2_API extern void d2_notify_release(size_t thread_id, size_t lock_id) {
using namespace d2;
using namespace d2::detail;
if (d2_is_enabled())
dispatcher.dispatch(ReleaseEvent((SyncObject(lock_id)),
Thread(thread_id)));
}
D2_API extern void d2_notify_recursive_release(size_t thread_id,
size_t lock_id) {
using namespace d2;
using namespace d2::detail;
if (d2_is_enabled())
dispatcher.dispatch(RecursiveReleaseEvent((SyncObject(lock_id)),
Thread(thread_id)));
}
namespace d2 { namespace detail {
// default initialized to the initial segment value
static Segment current_segment;
static basic_mutex segment_mutex;
static boost::unordered_map<Thread, Segment> segment_of;
}}
D2_API extern void d2_notify_start(size_t parent_id, size_t child_id) {
using namespace d2;
using namespace d2::detail;
if (d2_is_enabled()) {
Thread parent(parent_id), child(child_id);
Segment parent_segment, child_segment, new_parent_segment;
{
scoped_lock<basic_mutex> lock(segment_mutex);
BOOST_ASSERT_MSG(parent != child, "thread starting itself");
BOOST_ASSERT_MSG(segment_of.empty() || contains(parent,segment_of),
"starting a thread from another thread that has not been created yet");
// segment_of[parent] will be the initial segment value on the
// very first call, which is the same as current_segment. so this
// means two things:
// - parent_segment will be the initial segment value on the very
// first call, and the segment of `parent` on subsequent calls,
// which is fine.
// - we must PREincrement the current_segment so it is distinct
// from the initial value.
Segment& segment_of_parent = segment_of[parent];
parent_segment = segment_of_parent;
new_parent_segment = ++current_segment;
child_segment = ++current_segment;
segment_of[child] = child_segment;
segment_of_parent = new_parent_segment;
}
dispatcher.dispatch(StartEvent(parent_segment, new_parent_segment,
child_segment));
dispatcher.dispatch(SegmentHopEvent(parent, new_parent_segment));
dispatcher.dispatch(SegmentHopEvent(child, child_segment));
}
}
D2_API extern void d2_notify_join(size_t parent_id, size_t child_id) {
using namespace d2;
using namespace d2::detail;
if (d2_is_enabled()) {
Thread parent(parent_id), child(child_id);
Segment parent_segment, child_segment, new_parent_segment;
{
scoped_lock<basic_mutex> lock(segment_mutex);
BOOST_ASSERT_MSG(parent != child, "thread joining itself");
BOOST_ASSERT_MSG(contains(parent, segment_of),
"joining a thread into another thread that has not been created yet");
BOOST_ASSERT_MSG(contains(child, segment_of),
"joining a thread that has not been created yet");
Segment& segment_of_parent = segment_of[parent];
parent_segment = segment_of_parent;
child_segment = segment_of[child];
new_parent_segment = ++current_segment;
segment_of_parent = new_parent_segment;
segment_of.erase(child);
}
dispatcher.dispatch(JoinEvent(parent_segment, new_parent_segment,
child_segment));
dispatcher.dispatch(SegmentHopEvent(parent, new_parent_segment));
// We could possibly generate informative events like end-of-thread
// in the child thread, but that's not strictly necessary right now.
}
}
<commit_msg>Move the contains helper closer to its usage in api.cpp.<commit_after>/**
* This file implements the _d2_ API.
*/
#define D2_SOURCE
#include <d2/api.hpp>
#include <d2/detail/basic_atomic.hpp>
#include <d2/detail/basic_mutex.hpp>
#include <d2/detail/config.hpp>
#include <d2/events.hpp>
#include <d2/filesystem_dispatcher.hpp>
#include <d2/sync_object.hpp>
#include <d2/thread.hpp>
#include <stddef.h>
namespace d2 { namespace detail {
static FilesystemDispatcher dispatcher;
static basic_atomic<bool> event_logging_enabled(false);
}}
D2_API extern void d2_disable_event_logging(void) {
d2::detail::event_logging_enabled = false;
}
D2_API extern void d2_enable_event_logging(void) {
d2::detail::event_logging_enabled = true;
}
D2_API extern int d2_is_enabled(void) {
return d2::detail::event_logging_enabled ? 1 : 0;
}
D2_API extern int d2_is_disabled(void) {
return d2_is_enabled() ? 0 : 1;
}
D2_API extern int d2_set_log_repository(char const* path) {
// Note: 0 for success and anything else but 0 for failure.
return d2::detail::dispatcher.set_repository_noexcept(path) ? 0 : 1;
}
D2_API extern void d2_notify_acquire(size_t thread_id, size_t lock_id) {
using namespace d2;
using namespace d2::detail;
if (d2_is_enabled()) {
AcquireEvent event((SyncObject(lock_id)), Thread(thread_id));
// ignore current frame
event.info.init_call_stack(1);
dispatcher.dispatch(event);
}
}
D2_API extern void d2_notify_recursive_acquire(size_t thread_id,
size_t lock_id) {
using namespace d2;
using namespace d2::detail;
if (d2_is_enabled()) {
RecursiveAcquireEvent event((SyncObject(lock_id)), Thread(thread_id));
// ignore current frame
event.info.init_call_stack(1);
dispatcher.dispatch(event);
}
}
D2_API extern void d2_notify_release(size_t thread_id, size_t lock_id) {
using namespace d2;
using namespace d2::detail;
if (d2_is_enabled())
dispatcher.dispatch(ReleaseEvent((SyncObject(lock_id)),
Thread(thread_id)));
}
D2_API extern void d2_notify_recursive_release(size_t thread_id,
size_t lock_id) {
using namespace d2;
using namespace d2::detail;
if (d2_is_enabled())
dispatcher.dispatch(RecursiveReleaseEvent((SyncObject(lock_id)),
Thread(thread_id)));
}
namespace d2 { namespace detail {
// default initialized to the initial segment value
static Segment current_segment;
static basic_mutex segment_mutex;
static boost::unordered_map<Thread, Segment> segment_of;
template <typename Value, typename Container>
bool contains(Value const& v, Container const& c) {
return c.find(v) != c.end();
}
}}
D2_API extern void d2_notify_start(size_t parent_id, size_t child_id) {
using namespace d2;
using namespace d2::detail;
if (d2_is_enabled()) {
Thread parent(parent_id), child(child_id);
Segment parent_segment, child_segment, new_parent_segment;
{
scoped_lock<basic_mutex> lock(segment_mutex);
BOOST_ASSERT_MSG(parent != child, "thread starting itself");
BOOST_ASSERT_MSG(segment_of.empty() || contains(parent,segment_of),
"starting a thread from another thread that has not been created yet");
// segment_of[parent] will be the initial segment value on the
// very first call, which is the same as current_segment. so this
// means two things:
// - parent_segment will be the initial segment value on the very
// first call, and the segment of `parent` on subsequent calls,
// which is fine.
// - we must PREincrement the current_segment so it is distinct
// from the initial value.
Segment& segment_of_parent = segment_of[parent];
parent_segment = segment_of_parent;
new_parent_segment = ++current_segment;
child_segment = ++current_segment;
segment_of[child] = child_segment;
segment_of_parent = new_parent_segment;
}
dispatcher.dispatch(StartEvent(parent_segment, new_parent_segment,
child_segment));
dispatcher.dispatch(SegmentHopEvent(parent, new_parent_segment));
dispatcher.dispatch(SegmentHopEvent(child, child_segment));
}
}
D2_API extern void d2_notify_join(size_t parent_id, size_t child_id) {
using namespace d2;
using namespace d2::detail;
if (d2_is_enabled()) {
Thread parent(parent_id), child(child_id);
Segment parent_segment, child_segment, new_parent_segment;
{
scoped_lock<basic_mutex> lock(segment_mutex);
BOOST_ASSERT_MSG(parent != child, "thread joining itself");
BOOST_ASSERT_MSG(contains(parent, segment_of),
"joining a thread into another thread that has not been created yet");
BOOST_ASSERT_MSG(contains(child, segment_of),
"joining a thread that has not been created yet");
Segment& segment_of_parent = segment_of[parent];
parent_segment = segment_of_parent;
child_segment = segment_of[child];
new_parent_segment = ++current_segment;
segment_of_parent = new_parent_segment;
segment_of.erase(child);
}
dispatcher.dispatch(JoinEvent(parent_segment, new_parent_segment,
child_segment));
dispatcher.dispatch(SegmentHopEvent(parent, new_parent_segment));
// We could possibly generate informative events like end-of-thread
// in the child thread, but that's not strictly necessary right now.
}
}
<|endoftext|> |
<commit_before>// Copyright Verizon Media. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
#include "generic_lambda.h"
#include <vespa/eval/eval/llvm/compiled_function.h>
#include <vespa/eval/eval/llvm/compile_cache.h>
#include <assert.h>
using namespace vespalib::eval::tensor_function;
namespace vespalib::eval::instruction {
using Instruction = InterpretedFunction::Instruction;
using State = InterpretedFunction::State;
namespace {
//-----------------------------------------------------------------------------
bool step_labels(double *labels, const ValueType &type) {
for (size_t idx = type.dimensions().size(); idx-- > 0; ) {
if ((labels[idx] += 1.0) < type.dimensions()[idx].size) {
return true;
} else {
labels[idx] = 0.0;
}
}
return false;
}
struct ParamProxy : public LazyParams {
const std::vector<double> &labels;
const LazyParams ¶ms;
const std::vector<size_t> &bindings;
ParamProxy(const std::vector<double> &labels_in, const LazyParams ¶ms_in, const std::vector<size_t> &bindings_in)
: labels(labels_in), params(params_in), bindings(bindings_in) {}
const Value &resolve(size_t idx, Stash &stash) const override {
if (idx < labels.size()) {
return stash.create<DoubleValue>(labels[idx]);
}
return params.resolve(bindings[idx - labels.size()], stash);
}
};
//-----------------------------------------------------------------------------
struct CompiledParams {
const ValueType &result_type;
const std::vector<size_t> &bindings;
size_t num_cells;
CompileCache::Token::UP token;
CompiledParams(const Lambda &lambda)
: result_type(lambda.result_type()),
bindings(lambda.bindings()),
num_cells(result_type.dense_subspace_size()),
token(CompileCache::compile(lambda.lambda(), PassParams::ARRAY))
{
assert(lambda.lambda().num_params() == (result_type.dimensions().size() + bindings.size()));
}
};
template <typename CT>
void my_compiled_lambda_op(eval::InterpretedFunction::State &state, uint64_t param) {
const CompiledParams ¶ms = unwrap_param<CompiledParams>(param);
std::vector<double> args(params.result_type.dimensions().size() + params.bindings.size(), 0.0);
double *bind_next = &args[params.result_type.dimensions().size()];
for (size_t binding: params.bindings) {
*bind_next++ = state.params->resolve(binding, state.stash).as_double();
}
auto fun = params.token->get().get_function();
ArrayRef<CT> dst_cells = state.stash.create_array<CT>(params.num_cells);
CT *dst = &dst_cells[0];
do {
*dst++ = fun(&args[0]);
} while (step_labels(&args[0], params.result_type));
state.stack.push_back(state.stash.create<DenseValueView>(params.result_type, TypedCells(dst_cells)));
}
struct MyCompiledLambdaOp {
template <typename CT>
static auto invoke() { return my_compiled_lambda_op<CT>; }
};
//-----------------------------------------------------------------------------
struct InterpretedParams {
const ValueType &result_type;
const std::vector<size_t> &bindings;
size_t num_cells;
InterpretedFunction fun;
InterpretedParams(const Lambda &lambda, const ValueBuilderFactory &factory)
: result_type(lambda.result_type()),
bindings(lambda.bindings()),
num_cells(result_type.dense_subspace_size()),
fun(factory, lambda.lambda().root(), lambda.types())
{
assert(lambda.lambda().num_params() == (result_type.dimensions().size() + bindings.size()));
}
};
template <typename CT>
void my_interpreted_lambda_op(eval::InterpretedFunction::State &state, uint64_t param) {
const InterpretedParams ¶ms = unwrap_param<InterpretedParams>(param);
std::vector<double> labels(params.result_type.dimensions().size(), 0.0);
ParamProxy param_proxy(labels, *state.params, params.bindings);
InterpretedFunction::Context ctx(params.fun);
ArrayRef<CT> dst_cells = state.stash.create_array<CT>(params.num_cells);
CT *dst = &dst_cells[0];
do {
*dst++ = params.fun.eval(ctx, param_proxy).as_double();
} while (step_labels(&labels[0], params.result_type));
state.stack.push_back(state.stash.create<DenseValueView>(params.result_type, TypedCells(dst_cells)));
}
struct MyInterpretedLambdaOp {
template <typename CT>
static auto invoke() { return my_interpreted_lambda_op<CT>; }
};
//-----------------------------------------------------------------------------
} // namespace <unnamed>
Instruction
GenericLambda::make_instruction(const eval::tensor_function::Lambda &lambda_in,
const ValueBuilderFactory &factory, Stash &stash)
{
const ValueType & result_type = lambda_in.result_type();
assert(result_type.count_mapped_dimensions() == 0);
if (!CompiledFunction::detect_issues(lambda_in.lambda()) &&
lambda_in.types().all_types_are_double())
{
// can do compiled version
CompiledParams ¶ms = stash.create<CompiledParams>(lambda_in);
auto op = typify_invoke<1,TypifyCellType,MyCompiledLambdaOp>(result_type.cell_type());
return Instruction(op, wrap_param<CompiledParams>(params));
} else {
InterpretedParams ¶ms = stash.create<InterpretedParams>(lambda_in, factory);
auto op = typify_invoke<1,TypifyCellType,MyInterpretedLambdaOp>(result_type.cell_type());
return Instruction(op, wrap_param<InterpretedParams>(params));
}
}
} // namespace
<commit_msg>use stash.create_uninitialized_array<commit_after>// Copyright Verizon Media. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
#include "generic_lambda.h"
#include <vespa/eval/eval/llvm/compiled_function.h>
#include <vespa/eval/eval/llvm/compile_cache.h>
#include <assert.h>
using namespace vespalib::eval::tensor_function;
namespace vespalib::eval::instruction {
using Instruction = InterpretedFunction::Instruction;
using State = InterpretedFunction::State;
namespace {
//-----------------------------------------------------------------------------
bool step_labels(double *labels, const ValueType &type) {
for (size_t idx = type.dimensions().size(); idx-- > 0; ) {
if ((labels[idx] += 1.0) < type.dimensions()[idx].size) {
return true;
} else {
labels[idx] = 0.0;
}
}
return false;
}
struct ParamProxy : public LazyParams {
const std::vector<double> &labels;
const LazyParams ¶ms;
const std::vector<size_t> &bindings;
ParamProxy(const std::vector<double> &labels_in, const LazyParams ¶ms_in, const std::vector<size_t> &bindings_in)
: labels(labels_in), params(params_in), bindings(bindings_in) {}
const Value &resolve(size_t idx, Stash &stash) const override {
if (idx < labels.size()) {
return stash.create<DoubleValue>(labels[idx]);
}
return params.resolve(bindings[idx - labels.size()], stash);
}
};
//-----------------------------------------------------------------------------
struct CompiledParams {
const ValueType &result_type;
const std::vector<size_t> &bindings;
size_t num_cells;
CompileCache::Token::UP token;
CompiledParams(const Lambda &lambda)
: result_type(lambda.result_type()),
bindings(lambda.bindings()),
num_cells(result_type.dense_subspace_size()),
token(CompileCache::compile(lambda.lambda(), PassParams::ARRAY))
{
assert(lambda.lambda().num_params() == (result_type.dimensions().size() + bindings.size()));
}
};
template <typename CT>
void my_compiled_lambda_op(eval::InterpretedFunction::State &state, uint64_t param) {
const CompiledParams ¶ms = unwrap_param<CompiledParams>(param);
std::vector<double> args(params.result_type.dimensions().size() + params.bindings.size(), 0.0);
double *bind_next = &args[params.result_type.dimensions().size()];
for (size_t binding: params.bindings) {
*bind_next++ = state.params->resolve(binding, state.stash).as_double();
}
auto fun = params.token->get().get_function();
ArrayRef<CT> dst_cells = state.stash.create_uninitialized_array<CT>(params.num_cells);
CT *dst = &dst_cells[0];
do {
*dst++ = fun(&args[0]);
} while (step_labels(&args[0], params.result_type));
state.stack.push_back(state.stash.create<DenseValueView>(params.result_type, TypedCells(dst_cells)));
}
struct MyCompiledLambdaOp {
template <typename CT>
static auto invoke() { return my_compiled_lambda_op<CT>; }
};
//-----------------------------------------------------------------------------
struct InterpretedParams {
const ValueType &result_type;
const std::vector<size_t> &bindings;
size_t num_cells;
InterpretedFunction fun;
InterpretedParams(const Lambda &lambda, const ValueBuilderFactory &factory)
: result_type(lambda.result_type()),
bindings(lambda.bindings()),
num_cells(result_type.dense_subspace_size()),
fun(factory, lambda.lambda().root(), lambda.types())
{
assert(lambda.lambda().num_params() == (result_type.dimensions().size() + bindings.size()));
}
};
template <typename CT>
void my_interpreted_lambda_op(eval::InterpretedFunction::State &state, uint64_t param) {
const InterpretedParams ¶ms = unwrap_param<InterpretedParams>(param);
std::vector<double> labels(params.result_type.dimensions().size(), 0.0);
ParamProxy param_proxy(labels, *state.params, params.bindings);
InterpretedFunction::Context ctx(params.fun);
ArrayRef<CT> dst_cells = state.stash.create_array<CT>(params.num_cells);
CT *dst = &dst_cells[0];
do {
*dst++ = params.fun.eval(ctx, param_proxy).as_double();
} while (step_labels(&labels[0], params.result_type));
state.stack.push_back(state.stash.create<DenseValueView>(params.result_type, TypedCells(dst_cells)));
}
struct MyInterpretedLambdaOp {
template <typename CT>
static auto invoke() { return my_interpreted_lambda_op<CT>; }
};
//-----------------------------------------------------------------------------
} // namespace <unnamed>
Instruction
GenericLambda::make_instruction(const eval::tensor_function::Lambda &lambda_in,
const ValueBuilderFactory &factory, Stash &stash)
{
const ValueType & result_type = lambda_in.result_type();
assert(result_type.count_mapped_dimensions() == 0);
if (!CompiledFunction::detect_issues(lambda_in.lambda()) &&
lambda_in.types().all_types_are_double())
{
// can do compiled version
CompiledParams ¶ms = stash.create<CompiledParams>(lambda_in);
auto op = typify_invoke<1,TypifyCellType,MyCompiledLambdaOp>(result_type.cell_type());
return Instruction(op, wrap_param<CompiledParams>(params));
} else {
InterpretedParams ¶ms = stash.create<InterpretedParams>(lambda_in, factory);
auto op = typify_invoke<1,TypifyCellType,MyInterpretedLambdaOp>(result_type.cell_type());
return Instruction(op, wrap_param<InterpretedParams>(params));
}
}
} // namespace
<|endoftext|> |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.