text stringlengths 54 60.6k |
|---|
<commit_before><commit_msg>Planning: allow more iterations for calculating self-path.<commit_after><|endoftext|> |
<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.
=========================================================================*/
// Software Guide : BeginCommandLineArgs
// INPUTS: {${INPUTLARGEDATA}/QUICKBIRD/TOULOUSE/000000128955_01_P001_MUL/02APR01105228-M1BS-000000128955_01_P001.TIF}, {${INPUTLARGEDATA}/VECTOR/MidiPyrenees/roads.shp}
// ${OTB_DATA_ROOT}/Examples/DEM_srtm 1 ${OTB_DATA_ROOT}/Baseline/OTB/Files/DejaVuSans.ttf
// Software Guide : EndCommandLineArgs
// Software Guide : BeginLatex
//
// This example shows how to combine vector data and combine them with an image. Typically, the
// vector data would be a shapefile containing information from open street map (roads, etc), the
// image would be a high resolution image.
//
// This example is able to reproject the vector data on the fly, render them using mapnik (including
// road names) and display it as an overlay to a Quickbird image.
//
// For now the code is a bit convoluted, but it is helpful to illustrate the possibilities that it
// opens up.
//
// Software Guide : EndLatex
#include "otbVectorImage.h"
#include "itkRGBAPixel.h"
#include "otbImageFileReader.h"
#include "otbVectorDataFileReader.h"
#include "otbVectorData.h"
#include "otbVectorDataProjectionFilter.h"
#include "otbVectorDataToImageFilter.h"
#include "otbAlphaBlendingFunction.h"
#include "otbImageLayerRenderingModel.h"
#include "otbImageLayerGenerator.h"
#include "otbImageLayer.h"
#include "otbImageView.h"
#include "otbImageWidgetController.h"
#include "otbWidgetResizingActionHandler.h"
#include "otbChangeScaledExtractRegionActionHandler.h"
#include "otbChangeExtractRegionActionHandler.h"
#include "otbChangeScaleActionHandler.h"
#include "otbPixelDescriptionModel.h"
#include "otbPixelDescriptionActionHandler.h"
#include "otbPixelDescriptionView.h"
#include "otbPackedWidgetManager.h"
#include "otbHistogramCurve.h"
#include "otbCurves2DWidget.h"
int main( int argc, char * argv[] )
{
// params
const string infname = argv[1];
const string vectorfname = argv[2];
const string demdirectory = argv[3];
std::string fontfilename;
int run = 1;
bool inFont = false;
if (argc == 5)
{
run = atoi(argv[4]);
}
else if (argc == 6)
{
inFont = true;
std::string fontFilenameArg = argv[5];
fontfilename.assign(fontFilenameArg );
}
else if (argc != 4)
{
std::cout << "Invalid parameters: " << std::endl;
std::cout << argv[0] << " <image filename> <vector filename> <DEM directory> [<run> = 1] [<font filename> = default font]" << std::endl;
return EXIT_FAILURE;
}
typedef otb::VectorImage<double, 2> ImageType;
typedef ImageType::PixelType PixelType;
typedef itk::RGBAPixel<unsigned char> RGBAPixelType;
typedef otb::Image<RGBAPixelType, 2> OutputImageType;
// Reading input image
typedef otb::ImageFileReader<ImageType> ReaderType;
ReaderType::Pointer reader = ReaderType::New();
reader->SetFileName(infname);
reader->UpdateOutputInformation();
std::cout << "NumBands: " << reader->GetOutput()->GetNumberOfComponentsPerPixel() << std::endl;
// Instantiation of the visualization elements
typedef otb::ImageLayerRenderingModel<OutputImageType> ModelType;
ModelType::Pointer model = ModelType::New();
typedef otb::ImageView<ModelType> ViewType;
typedef otb::ImageWidgetController ControllerType;
typedef otb::WidgetResizingActionHandler
<ModelType, ViewType> ResizingHandlerType;
typedef otb::ChangeScaledExtractRegionActionHandler
<ModelType, ViewType> ChangeScaledRegionHandlerType;
typedef otb::ChangeExtractRegionActionHandler
<ModelType, ViewType> ChangeRegionHandlerType;
typedef otb::ChangeScaleActionHandler
<ModelType, ViewType> ChangeScaleHandlerType;
typedef otb::PixelDescriptionModel<OutputImageType> PixelDescriptionModelType;
typedef otb::PixelDescriptionActionHandler
< PixelDescriptionModelType, ViewType> PixelDescriptionActionHandlerType;
typedef otb::PixelDescriptionView
< PixelDescriptionModelType > PixelDescriptionViewType;
PixelDescriptionModelType::Pointer pixelModel = PixelDescriptionModelType::New();
pixelModel->SetLayers(model->GetLayers());
// Generate the first layer: the remote sensing image
typedef otb::ImageLayer<ImageType, OutputImageType> LayerType;
typedef otb::ImageLayerGenerator<LayerType> LayerGeneratorType;
LayerGeneratorType::Pointer generator = LayerGeneratorType::New();
generator->SetImage(reader->GetOutput());
generator->GetLayer()->SetName("Image");
generator->GenerateLayer();
// Generate the second layer: the rendered vector data
//Read the vector data
typedef otb::VectorData<> VectorDataType;
typedef otb::VectorDataFileReader<VectorDataType> VectorDataFileReaderType;
VectorDataFileReaderType::Pointer vectorDataReader = VectorDataFileReaderType::New();
vectorDataReader->SetFileName(vectorfname);
//Reproject the vector data in the proper projection, ie, the remote sensing image projection
typedef otb::VectorDataProjectionFilter<VectorDataType, VectorDataType> ProjectionFilterType;
ProjectionFilterType::Pointer projection = ProjectionFilterType::New();
projection->SetInput(vectorDataReader->GetOutput());
projection->SetOutputKeywordList(reader->GetOutput()->GetImageKeywordlist());
projection->SetOutputOrigin(reader->GetOutput()->GetOrigin());
projection->SetOutputSpacing(reader->GetOutput()->GetSpacing());
projection->SetDEMDirectory(demdirectory); // a good DEM is compulsory to get a reasonable registration
// get some usefull information from the image to make sure that we are
// going to render the vector data in the same geometry
ImageType::SizeType size;
size[0] = reader->GetOutput()->GetLargestPossibleRegion().GetSize()[0];
size[1] = reader->GetOutput()->GetLargestPossibleRegion().GetSize()[1];
ImageType::PointType origin;
origin[0] = reader->GetOutput()->GetOrigin()[0];
origin[1] = reader->GetOutput()->GetOrigin()[1];
ImageType::SpacingType spacing;
spacing[0] = reader->GetOutput()->GetSpacing()[0];
spacing[1] = reader->GetOutput()->GetSpacing()[1];
// set up the rendering of the vector data, the VectorDataToImageFilter uses the
// mapnik library to obtain a nice rendering
typedef itk::RGBAPixel<unsigned char> AlphaPixelType;
typedef otb::Image<AlphaPixelType, 2> AlphaImageType;
typedef otb::VectorDataToImageFilter<VectorDataType, AlphaImageType> VectorDataToImageFilterType;
VectorDataToImageFilterType::Pointer vectorDataRendering = VectorDataToImageFilterType::New();
vectorDataRendering->SetInput(projection->GetOutput());
vectorDataRendering->SetSize(size);
vectorDataRendering->SetOrigin(origin);
vectorDataRendering->SetSpacing(spacing);
vectorDataRendering->SetScaleFactor(2.4);
if (inFont)
vectorDataRendering->SetFontFileName(fontfilename);
// set up the style we want to use
vectorDataRendering->AddStyle("minor-roads-casing");
vectorDataRendering->AddStyle("minor-roads");
vectorDataRendering->AddStyle("roads");
vectorDataRendering->AddStyle("roads-text");
// rendering of the quicklook: the quicklook is at an entire different scale, so we don't want to
// render the same roads (only the main one).
VectorDataToImageFilterType::Pointer vectorDataRenderingQL = VectorDataToImageFilterType::New();
vectorDataRenderingQL->SetInput(projection->GetOutput());
double qlRatio = generator->GetOptimalSubSamplingRate();
std::cout << "Subsampling for QL: " << qlRatio << std::endl;
ImageType::SizeType sizeQL;
sizeQL[0] = size[0]/qlRatio;
sizeQL[1] = size[1]/qlRatio;
ImageType::SpacingType spacingQL;
spacingQL[0] = spacing[0]*qlRatio;
spacingQL[1] = spacing[1]*qlRatio;
vectorDataRenderingQL->SetSize(sizeQL);
vectorDataRenderingQL->SetOrigin(origin);
vectorDataRenderingQL->SetSpacing(spacingQL);
vectorDataRenderingQL->SetScaleFactor(2.4*qlRatio);
if (inFont)
vectorDataRenderingQL->SetFontFileName(fontfilename);
vectorDataRenderingQL->AddStyle("minor-roads-casing");
vectorDataRenderingQL->AddStyle("minor-roads");
vectorDataRenderingQL->AddStyle("roads");
vectorDataRenderingQL->AddStyle("roads-text");
// Now we are ready to create this second layer
typedef otb::ImageLayer<OutputImageType, OutputImageType> LayerRGBAType;
typedef otb::ImageLayerGenerator<LayerRGBAType> LayerGeneratorRGBAType;
LayerGeneratorRGBAType::Pointer generator2 = LayerGeneratorRGBAType::New();
generator2->SetImage(vectorDataRendering->GetOutput());
generator2->GetLayer()->SetName("OSM");
// with slight transparency of the vector data layer
typedef otb::Function::AlphaBlendingFunction<AlphaPixelType, RGBAPixelType> BlendingFunctionType;
BlendingFunctionType::Pointer blendingFunction = BlendingFunctionType::New();
blendingFunction->SetAlpha(0.8);
generator2->SetBlendingFunction(blendingFunction);
typedef otb::Function::StandardRenderingFunction<AlphaPixelType, RGBAPixelType> RenderingFunctionType;
RenderingFunctionType::Pointer renderingFunction = RenderingFunctionType::New();
renderingFunction->SetAutoMinMax(false);
generator2->SetRenderingFunction(renderingFunction);
generator2->SetQuicklook(vectorDataRenderingQL->GetOutput());
generator2->GenerateQuicklookOff();
generator2->GenerateLayer();
// Add the layer to the model
model->AddLayer(generator->GetLayer());
model->AddLayer(generator2->GetLayer());
// All the following code is the manual building of the viewer system
// Build a view
ViewType::Pointer view = ViewType::New();
view->SetModel(model);
// Build a controller
ControllerType::Pointer controller = ControllerType::New();
view->SetController(controller);
// Add the resizing handler
ResizingHandlerType::Pointer resizingHandler = ResizingHandlerType::New();
resizingHandler->SetModel(model);
resizingHandler->SetView(view);
controller->AddActionHandler(resizingHandler);
// Add the change scaled region handler
ChangeScaledRegionHandlerType::Pointer changeScaledHandler = ChangeScaledRegionHandlerType::New();
changeScaledHandler->SetModel(model);
changeScaledHandler->SetView(view);
controller->AddActionHandler(changeScaledHandler);
// Add the change extract region handler
ChangeRegionHandlerType::Pointer changeHandler = ChangeRegionHandlerType::New();
changeHandler->SetModel(model);
changeHandler->SetView(view);
controller->AddActionHandler(changeHandler);
// Add the change scaled handler
ChangeScaleHandlerType::Pointer changeScaleHandler =ChangeScaleHandlerType::New();
changeScaleHandler->SetModel(model);
changeScaleHandler->SetView(view);
controller->AddActionHandler(changeScaleHandler);
// Add the pixel description action handler
PixelDescriptionActionHandlerType::Pointer pixelActionHandler = PixelDescriptionActionHandlerType::New();
pixelActionHandler->SetView(view);
pixelActionHandler->SetModel(pixelModel);
controller->AddActionHandler(pixelActionHandler);
// Build a pixel description view
PixelDescriptionViewType::Pointer pixelView = PixelDescriptionViewType::New();
pixelView->SetModel(pixelModel);
// adding histograms rendering
model->Update();
// Colors
typedef LayerType::HistogramType HistogramType;
typedef otb::HistogramCurve<HistogramType> HistogramCurveType;
HistogramCurveType::ColorType red, green, blue;
red.Fill(0);
red[0]=1.;
red[3]=0.5;
green.Fill(0);
green[1]=1.;
green[3]=0.5;
blue.Fill(0);
blue[2]=1.;
blue[3]=0.5;
HistogramCurveType::Pointer rhistogram = HistogramCurveType::New();
rhistogram->SetHistogram(generator->GetLayer()->GetHistogramList()->GetNthElement(2));
rhistogram->SetHistogramColor(red);
rhistogram->SetLabelColor(red);
HistogramCurveType::Pointer ghistogram = HistogramCurveType::New();
ghistogram->SetHistogram(generator->GetLayer()->GetHistogramList()->GetNthElement(1));
ghistogram->SetHistogramColor(green);
ghistogram->SetLabelColor(green);
HistogramCurveType::Pointer bhistogram = HistogramCurveType::New();
bhistogram->SetHistogram(generator->GetLayer()->GetHistogramList()->GetNthElement(0));
bhistogram->SetHistogramColor(blue);
bhistogram->SetLabelColor(blue);
typedef otb::Curves2DWidget CurvesWidgetType;
typedef CurvesWidgetType::Pointer CurvesWidgetPointerType;
CurvesWidgetPointerType m_CurveWidget = CurvesWidgetType::New();
m_CurveWidget->AddCurve(rhistogram);
m_CurveWidget->AddCurve(ghistogram);
m_CurveWidget->AddCurve(bhistogram);
m_CurveWidget->SetXAxisLabel("Pixels");
m_CurveWidget->SetYAxisLabel("Frequency");
otb::PackedWidgetManager::Pointer windowManager = otb::PackedWidgetManager::New();
windowManager->RegisterFullWidget(view->GetFullWidget());
windowManager->RegisterZoomWidget(view->GetZoomWidget());
windowManager->RegisterScrollWidget(view->GetScrollWidget());
windowManager->RegisterPixelDescriptionWidget(pixelView->GetPixelDescriptionWidget());
windowManager->RegisterHistogramWidget(m_CurveWidget);
windowManager->Show();
if(run)
{
Fl::run();
}
else
{
Fl::check();
}
return EXIT_SUCCESS;
}
<commit_msg>BUG: test timeout<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.
=========================================================================*/
// Software Guide : BeginCommandLineArgs
// INPUTS: {${INPUTLARGEDATA}/QUICKBIRD/TOULOUSE/000000128955_01_P001_MUL/02APR01105228-M1BS-000000128955_01_P001.TIF}, {${INPUTLARGEDATA}/VECTOR/MidiPyrenees/roads.shp}
// ${OTB_DATA_ROOT}/Examples/DEM_srtm 1 ${OTB_DATA_ROOT}/Baseline/OTB/Files/DejaVuSans.ttf
// Software Guide : EndCommandLineArgs
// Software Guide : BeginLatex
//
// This example shows how to combine vector data and combine them with an image. Typically, the
// vector data would be a shapefile containing information from open street map (roads, etc), the
// image would be a high resolution image.
//
// This example is able to reproject the vector data on the fly, render them using mapnik (including
// road names) and display it as an overlay to a Quickbird image.
//
// For now the code is a bit convoluted, but it is helpful to illustrate the possibilities that it
// opens up.
//
// Software Guide : EndLatex
#include "otbVectorImage.h"
#include "itkRGBAPixel.h"
#include "otbImageFileReader.h"
#include "otbVectorDataFileReader.h"
#include "otbVectorData.h"
#include "otbVectorDataProjectionFilter.h"
#include "otbVectorDataToImageFilter.h"
#include "otbAlphaBlendingFunction.h"
#include "otbImageLayerRenderingModel.h"
#include "otbImageLayerGenerator.h"
#include "otbImageLayer.h"
#include "otbImageView.h"
#include "otbImageWidgetController.h"
#include "otbWidgetResizingActionHandler.h"
#include "otbChangeScaledExtractRegionActionHandler.h"
#include "otbChangeExtractRegionActionHandler.h"
#include "otbChangeScaleActionHandler.h"
#include "otbPixelDescriptionModel.h"
#include "otbPixelDescriptionActionHandler.h"
#include "otbPixelDescriptionView.h"
#include "otbPackedWidgetManager.h"
#include "otbHistogramCurve.h"
#include "otbCurves2DWidget.h"
int main( int argc, char * argv[] )
{
// params
const string infname = argv[1];
const string vectorfname = argv[2];
const string demdirectory = argv[3];
std::string fontfilename;
int run = 1;
bool inFont = false;
if (argc == 5)
{
run = atoi(argv[4]);
}
else if (argc == 6)
{
run = atoi(argv[4]);
inFont = true;
std::string fontFilenameArg = argv[5];
fontfilename.assign(fontFilenameArg );
}
else if (argc != 4)
{
std::cout << "Invalid parameters: " << std::endl;
std::cout << argv[0] << " <image filename> <vector filename> <DEM directory> [<run> = 1] [<font filename> = default font]" << std::endl;
return EXIT_FAILURE;
}
typedef otb::VectorImage<double, 2> ImageType;
typedef ImageType::PixelType PixelType;
typedef itk::RGBAPixel<unsigned char> RGBAPixelType;
typedef otb::Image<RGBAPixelType, 2> OutputImageType;
// Reading input image
typedef otb::ImageFileReader<ImageType> ReaderType;
ReaderType::Pointer reader = ReaderType::New();
reader->SetFileName(infname);
reader->UpdateOutputInformation();
std::cout << "NumBands: " << reader->GetOutput()->GetNumberOfComponentsPerPixel() << std::endl;
// Instantiation of the visualization elements
typedef otb::ImageLayerRenderingModel<OutputImageType> ModelType;
ModelType::Pointer model = ModelType::New();
typedef otb::ImageView<ModelType> ViewType;
typedef otb::ImageWidgetController ControllerType;
typedef otb::WidgetResizingActionHandler
<ModelType, ViewType> ResizingHandlerType;
typedef otb::ChangeScaledExtractRegionActionHandler
<ModelType, ViewType> ChangeScaledRegionHandlerType;
typedef otb::ChangeExtractRegionActionHandler
<ModelType, ViewType> ChangeRegionHandlerType;
typedef otb::ChangeScaleActionHandler
<ModelType, ViewType> ChangeScaleHandlerType;
typedef otb::PixelDescriptionModel<OutputImageType> PixelDescriptionModelType;
typedef otb::PixelDescriptionActionHandler
< PixelDescriptionModelType, ViewType> PixelDescriptionActionHandlerType;
typedef otb::PixelDescriptionView
< PixelDescriptionModelType > PixelDescriptionViewType;
PixelDescriptionModelType::Pointer pixelModel = PixelDescriptionModelType::New();
pixelModel->SetLayers(model->GetLayers());
// Generate the first layer: the remote sensing image
typedef otb::ImageLayer<ImageType, OutputImageType> LayerType;
typedef otb::ImageLayerGenerator<LayerType> LayerGeneratorType;
LayerGeneratorType::Pointer generator = LayerGeneratorType::New();
generator->SetImage(reader->GetOutput());
generator->GetLayer()->SetName("Image");
generator->GenerateLayer();
// Generate the second layer: the rendered vector data
//Read the vector data
typedef otb::VectorData<> VectorDataType;
typedef otb::VectorDataFileReader<VectorDataType> VectorDataFileReaderType;
VectorDataFileReaderType::Pointer vectorDataReader = VectorDataFileReaderType::New();
vectorDataReader->SetFileName(vectorfname);
//Reproject the vector data in the proper projection, ie, the remote sensing image projection
typedef otb::VectorDataProjectionFilter<VectorDataType, VectorDataType> ProjectionFilterType;
ProjectionFilterType::Pointer projection = ProjectionFilterType::New();
projection->SetInput(vectorDataReader->GetOutput());
projection->SetOutputKeywordList(reader->GetOutput()->GetImageKeywordlist());
projection->SetOutputOrigin(reader->GetOutput()->GetOrigin());
projection->SetOutputSpacing(reader->GetOutput()->GetSpacing());
projection->SetDEMDirectory(demdirectory); // a good DEM is compulsory to get a reasonable registration
// get some usefull information from the image to make sure that we are
// going to render the vector data in the same geometry
ImageType::SizeType size;
size[0] = reader->GetOutput()->GetLargestPossibleRegion().GetSize()[0];
size[1] = reader->GetOutput()->GetLargestPossibleRegion().GetSize()[1];
ImageType::PointType origin;
origin[0] = reader->GetOutput()->GetOrigin()[0];
origin[1] = reader->GetOutput()->GetOrigin()[1];
ImageType::SpacingType spacing;
spacing[0] = reader->GetOutput()->GetSpacing()[0];
spacing[1] = reader->GetOutput()->GetSpacing()[1];
// set up the rendering of the vector data, the VectorDataToImageFilter uses the
// mapnik library to obtain a nice rendering
typedef itk::RGBAPixel<unsigned char> AlphaPixelType;
typedef otb::Image<AlphaPixelType, 2> AlphaImageType;
typedef otb::VectorDataToImageFilter<VectorDataType, AlphaImageType> VectorDataToImageFilterType;
VectorDataToImageFilterType::Pointer vectorDataRendering = VectorDataToImageFilterType::New();
vectorDataRendering->SetInput(projection->GetOutput());
vectorDataRendering->SetSize(size);
vectorDataRendering->SetOrigin(origin);
vectorDataRendering->SetSpacing(spacing);
vectorDataRendering->SetScaleFactor(2.4);
if (inFont)
vectorDataRendering->SetFontFileName(fontfilename);
// set up the style we want to use
vectorDataRendering->AddStyle("minor-roads-casing");
vectorDataRendering->AddStyle("minor-roads");
vectorDataRendering->AddStyle("roads");
vectorDataRendering->AddStyle("roads-text");
// rendering of the quicklook: the quicklook is at an entire different scale, so we don't want to
// render the same roads (only the main one).
VectorDataToImageFilterType::Pointer vectorDataRenderingQL = VectorDataToImageFilterType::New();
vectorDataRenderingQL->SetInput(projection->GetOutput());
double qlRatio = generator->GetOptimalSubSamplingRate();
std::cout << "Subsampling for QL: " << qlRatio << std::endl;
ImageType::SizeType sizeQL;
sizeQL[0] = size[0]/qlRatio;
sizeQL[1] = size[1]/qlRatio;
ImageType::SpacingType spacingQL;
spacingQL[0] = spacing[0]*qlRatio;
spacingQL[1] = spacing[1]*qlRatio;
vectorDataRenderingQL->SetSize(sizeQL);
vectorDataRenderingQL->SetOrigin(origin);
vectorDataRenderingQL->SetSpacing(spacingQL);
vectorDataRenderingQL->SetScaleFactor(2.4*qlRatio);
if (inFont)
vectorDataRenderingQL->SetFontFileName(fontfilename);
vectorDataRenderingQL->AddStyle("minor-roads-casing");
vectorDataRenderingQL->AddStyle("minor-roads");
vectorDataRenderingQL->AddStyle("roads");
vectorDataRenderingQL->AddStyle("roads-text");
// Now we are ready to create this second layer
typedef otb::ImageLayer<OutputImageType, OutputImageType> LayerRGBAType;
typedef otb::ImageLayerGenerator<LayerRGBAType> LayerGeneratorRGBAType;
LayerGeneratorRGBAType::Pointer generator2 = LayerGeneratorRGBAType::New();
generator2->SetImage(vectorDataRendering->GetOutput());
generator2->GetLayer()->SetName("OSM");
// with slight transparency of the vector data layer
typedef otb::Function::AlphaBlendingFunction<AlphaPixelType, RGBAPixelType> BlendingFunctionType;
BlendingFunctionType::Pointer blendingFunction = BlendingFunctionType::New();
blendingFunction->SetAlpha(0.8);
generator2->SetBlendingFunction(blendingFunction);
typedef otb::Function::StandardRenderingFunction<AlphaPixelType, RGBAPixelType> RenderingFunctionType;
RenderingFunctionType::Pointer renderingFunction = RenderingFunctionType::New();
renderingFunction->SetAutoMinMax(false);
generator2->SetRenderingFunction(renderingFunction);
generator2->SetQuicklook(vectorDataRenderingQL->GetOutput());
generator2->GenerateQuicklookOff();
generator2->GenerateLayer();
// Add the layer to the model
model->AddLayer(generator->GetLayer());
model->AddLayer(generator2->GetLayer());
// All the following code is the manual building of the viewer system
// Build a view
ViewType::Pointer view = ViewType::New();
view->SetModel(model);
// Build a controller
ControllerType::Pointer controller = ControllerType::New();
view->SetController(controller);
// Add the resizing handler
ResizingHandlerType::Pointer resizingHandler = ResizingHandlerType::New();
resizingHandler->SetModel(model);
resizingHandler->SetView(view);
controller->AddActionHandler(resizingHandler);
// Add the change scaled region handler
ChangeScaledRegionHandlerType::Pointer changeScaledHandler = ChangeScaledRegionHandlerType::New();
changeScaledHandler->SetModel(model);
changeScaledHandler->SetView(view);
controller->AddActionHandler(changeScaledHandler);
// Add the change extract region handler
ChangeRegionHandlerType::Pointer changeHandler = ChangeRegionHandlerType::New();
changeHandler->SetModel(model);
changeHandler->SetView(view);
controller->AddActionHandler(changeHandler);
// Add the change scaled handler
ChangeScaleHandlerType::Pointer changeScaleHandler =ChangeScaleHandlerType::New();
changeScaleHandler->SetModel(model);
changeScaleHandler->SetView(view);
controller->AddActionHandler(changeScaleHandler);
// Add the pixel description action handler
PixelDescriptionActionHandlerType::Pointer pixelActionHandler = PixelDescriptionActionHandlerType::New();
pixelActionHandler->SetView(view);
pixelActionHandler->SetModel(pixelModel);
controller->AddActionHandler(pixelActionHandler);
// Build a pixel description view
PixelDescriptionViewType::Pointer pixelView = PixelDescriptionViewType::New();
pixelView->SetModel(pixelModel);
// adding histograms rendering
model->Update();
// Colors
typedef LayerType::HistogramType HistogramType;
typedef otb::HistogramCurve<HistogramType> HistogramCurveType;
HistogramCurveType::ColorType red, green, blue;
red.Fill(0);
red[0]=1.;
red[3]=0.5;
green.Fill(0);
green[1]=1.;
green[3]=0.5;
blue.Fill(0);
blue[2]=1.;
blue[3]=0.5;
HistogramCurveType::Pointer rhistogram = HistogramCurveType::New();
rhistogram->SetHistogram(generator->GetLayer()->GetHistogramList()->GetNthElement(2));
rhistogram->SetHistogramColor(red);
rhistogram->SetLabelColor(red);
HistogramCurveType::Pointer ghistogram = HistogramCurveType::New();
ghistogram->SetHistogram(generator->GetLayer()->GetHistogramList()->GetNthElement(1));
ghistogram->SetHistogramColor(green);
ghistogram->SetLabelColor(green);
HistogramCurveType::Pointer bhistogram = HistogramCurveType::New();
bhistogram->SetHistogram(generator->GetLayer()->GetHistogramList()->GetNthElement(0));
bhistogram->SetHistogramColor(blue);
bhistogram->SetLabelColor(blue);
typedef otb::Curves2DWidget CurvesWidgetType;
typedef CurvesWidgetType::Pointer CurvesWidgetPointerType;
CurvesWidgetPointerType m_CurveWidget = CurvesWidgetType::New();
m_CurveWidget->AddCurve(rhistogram);
m_CurveWidget->AddCurve(ghistogram);
m_CurveWidget->AddCurve(bhistogram);
m_CurveWidget->SetXAxisLabel("Pixels");
m_CurveWidget->SetYAxisLabel("Frequency");
otb::PackedWidgetManager::Pointer windowManager = otb::PackedWidgetManager::New();
windowManager->RegisterFullWidget(view->GetFullWidget());
windowManager->RegisterZoomWidget(view->GetZoomWidget());
windowManager->RegisterScrollWidget(view->GetScrollWidget());
windowManager->RegisterPixelDescriptionWidget(pixelView->GetPixelDescriptionWidget());
windowManager->RegisterHistogramWidget(m_CurveWidget);
windowManager->Show();
if(run)
{
Fl::run();
}
else
{
Fl::check();
}
return EXIT_SUCCESS;
}
<|endoftext|> |
<commit_before>/*********************************************************************************
*
* Inviwo - Interactive Visualization Workshop
*
* Copyright (c) 2017-2019 Inviwo Foundation
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
* ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
*********************************************************************************/
#include <inviwopy/pyprocessors.h>
#include <inviwopy/inviwopy.h>
#include <inviwopy/vectoridentifierwrapper.h>
#include <inviwo/core/processors/processor.h>
#include <inviwo/core/processors/processorfactory.h>
#include <inviwo/core/processors/processorfactoryobject.h>
#include <inviwo/core/processors/processorwidget.h>
#include <inviwo/core/processors/processorwidgetfactory.h>
#include <inviwo/core/processors/processorwidgetfactoryobject.h>
#include <inviwo/core/metadata/processormetadata.h>
#include <inviwo/core/datastructures/image/layer.h>
#include <inviwo/core/datastructures/image/layerram.h>
#include <inviwo/core/io/datawriterfactory.h>
#include <inviwo/core/util/filesystem.h>
#include <modules/python3/processors/pythonscriptprocessor.h>
namespace inviwo {
class ProcessorTrampoline : public Processor {
public:
/* Inherit the constructors */
using Processor::Processor;
/* Trampoline (need one for each virtual function) */
virtual void initializeResources() override {
PYBIND11_OVERLOAD(void, Processor, initializeResources, );
}
virtual void process() override { PYBIND11_OVERLOAD(void, Processor, process, ); }
virtual void doIfNotReady() override { PYBIND11_OVERLOAD(void, Processor, doIfNotReady, ); }
virtual void setValid() override { PYBIND11_OVERLOAD(void, Processor, setValid, ); }
virtual void invalidate(InvalidationLevel invalidationLevel,
Property *modifiedProperty = nullptr) override {
PYBIND11_OVERLOAD(void, Processor, invalidate, invalidationLevel, modifiedProperty);
}
virtual const ProcessorInfo getProcessorInfo() const override {
PYBIND11_OVERLOAD_PURE(const ProcessorInfo, Processor, getProcessorInfo, );
}
virtual void invokeEvent(Event *event) override {
PYBIND11_OVERLOAD(void, Processor, invokeEvent, event);
}
virtual void propagateEvent(Event *event, Outport *source) override {
PYBIND11_OVERLOAD(void, Processor, propagateEvent, event, source);
}
};
class ProcessorFactoryObjectTrampoline : public ProcessorFactoryObject {
public:
using ProcessorFactoryObject::ProcessorFactoryObject;
virtual pybind11::object createProcessor(InviwoApplication *app) {
PYBIND11_OVERLOAD(pybind11::object, ProcessorFactoryObjectTrampoline, createProcessor, app);
}
virtual std::unique_ptr<Processor> create(InviwoApplication *app) override {
auto proc = createProcessor(app);
auto p = std::unique_ptr<Processor>(proc.cast<Processor *>());
proc.release();
return p;
}
};
class ProcessorWidgetFactoryObjectTrampoline : public ProcessorWidgetFactoryObject {
public:
using ProcessorWidgetFactoryObject::ProcessorWidgetFactoryObject;
virtual pybind11::object createWidget(Processor *processor) {
PYBIND11_OVERLOAD(pybind11::object, ProcessorWidgetFactoryObjectTrampoline, createWidget,
processor);
}
virtual std::unique_ptr<ProcessorWidget> create(Processor *processor) override {
auto proc = createWidget(processor);
auto p = std::unique_ptr<ProcessorWidget>(proc.cast<ProcessorWidget *>());
proc.release();
return p;
}
};
void exposeProcessors(pybind11::module &m) {
namespace py = pybind11;
py::enum_<CodeState>(m, "CodeState")
.value("Broken", CodeState::Broken)
.value("Experimental", CodeState::Experimental)
.value("Stable", CodeState::Stable);
py::class_<Tag>(m, "Tag")
.def(py::init())
.def(py::init<std::string>())
.def(py::init<Tag>())
.def("getString", &Tag::getString);
py::class_<Tags>(m, "Tags")
.def(py::init())
.def(py::init<std::string>())
.def(py::init<Tags>())
.def("addTag", &Tags::addTag)
.def("addTags", &Tags::addTags)
.def("size", &Tags::size)
.def("empty", &Tags::empty)
.def("getString", &Tags::getString)
.def("getMatches", &Tags::getMatches)
.def_readwrite("tags", &Tags::tags_)
.def(py::self == py::self)
.def(py::self < py::self)
.def_readonly_static("CPU", &Tags::CPU)
.def_readonly_static("GL", &Tags::GL)
.def_readonly_static("CL", &Tags::CL)
.def_readonly_static("PY", &Tags::PY);
py::class_<ProcessorInfo>(m, "ProcessorInfo")
.def(py::init<std::string, std::string, std::string, CodeState, Tags, bool>(),
py::arg("classIdentifier"), py::arg("displayName"), py::arg("category") = "Python",
py::arg("codeState") = CodeState::Stable, py::arg("tags") = Tags::PY,
py::arg("visible") = true)
.def_readonly("classIdentifier", &ProcessorInfo::classIdentifier)
.def_readonly("displayName", &ProcessorInfo::displayName)
.def_readonly("category", &ProcessorInfo::category)
.def_readonly("codeState", &ProcessorInfo::codeState)
.def_readonly("tags", &ProcessorInfo::tags)
.def_readonly("visible", &ProcessorInfo::visible);
py::class_<ProcessorFactoryObject, ProcessorFactoryObjectTrampoline>(m,
"ProcessorFactoryObject")
.def(py::init<ProcessorInfo>())
.def("getProcessorInfo", &ProcessorFactoryObject::getProcessorInfo);
py::class_<ProcessorFactory>(m, "ProcessorFactory")
.def("hasKey", &ProcessorFactory::hasKey)
.def_property_readonly("keys", &ProcessorFactory::getKeys)
.def("create",
[](ProcessorFactory *pf, std::string key) { return pf->create(key).release(); })
.def("create",
[](ProcessorFactory *pf, std::string key, ivec2 pos) {
auto p = pf->create(key);
if (!p) {
throw py::key_error("failed to create processor of type '" + key + "'");
}
p->getMetaData<ProcessorMetaData>(ProcessorMetaData::CLASS_IDENTIFIER)
->setPosition(pos);
return p.release();
})
.def("registerObject", &ProcessorFactory::registerObject)
.def("unRegisterObject", &ProcessorFactory::unRegisterObject);
py::class_<ProcessorWidget>(m, "ProcessorWidget")
.def_property("visibility", &ProcessorWidget::isVisible, &ProcessorWidget::setVisible)
.def_property("dimensions", &ProcessorWidget::getDimensions,
&ProcessorWidget::setDimensions)
.def_property("position", &ProcessorWidget::getPosition, &ProcessorWidget::setPosition)
.def("show", &ProcessorWidget::show)
.def("hide", &ProcessorWidget::hide);
py::class_<ProcessorWidgetFactory>(m, "ProcessorWidgetFactory")
.def("registerObject", &ProcessorWidgetFactory::registerObject)
.def("unRegisterObject", &ProcessorWidgetFactory::unRegisterObject)
.def("create", [](ProcessorWidgetFactory *pf, Processor *p) { return pf->create(p); })
.def("hasKey", &ProcessorWidgetFactory::hasKey)
.def("getkeys", &ProcessorWidgetFactory::getKeys);
py::class_<ProcessorWidgetFactoryObject, ProcessorWidgetFactoryObjectTrampoline>(
m, "ProcessorWidgetFactoryObject")
.def(py::init<const std::string &>())
.def("getClassIdentifier", &ProcessorWidgetFactoryObject::getClassIdentifier);
py::class_<ProcessorMetaData>(m, "ProcessorMetaData")
.def_property("position", &ProcessorMetaData::getPosition, &ProcessorMetaData::setPosition)
.def_property("selected", &ProcessorMetaData::isSelected, &ProcessorMetaData::setSelected)
.def_property("visible", &ProcessorMetaData::isVisible, &ProcessorMetaData::setVisible);
using InportVecWrapper = VectorIdentifierWrapper<std::vector<Inport *>>;
exposeVectorIdentifierWrapper<std::vector<Inport *>>(m, "InportVectorWrapper");
using OutportVecWrapper = VectorIdentifierWrapper<std::vector<Outport *>>;
exposeVectorIdentifierWrapper<std::vector<Outport *>>(m, "OutportVectorWrapper");
py::class_<Processor, ProcessorTrampoline, PropertyOwner, ProcessorPtr<Processor>>(
m, "Processor", py::dynamic_attr{}, py::multiple_inheritance{})
.def(py::init<const std::string &, const std::string &>())
.def("__repr__", &Processor::getIdentifier)
.def_property_readonly("classIdentifier", &Processor::getClassIdentifier)
.def_property("displayName", &Processor::getDisplayName, &Processor::setDisplayName)
.def("getProcessorInfo", &Processor::getProcessorInfo)
.def_property_readonly("category", &Processor::getCategory)
.def_property_readonly("codeState", &Processor::getCodeState)
.def_property_readonly("tags", &Processor::getTags)
.def_property("identifier", &Processor::getIdentifier, &Processor::setIdentifier)
.def("hasProcessorWidget", &Processor::hasProcessorWidget)
.def_property_readonly("widget", &Processor::getProcessorWidget)
.def_property_readonly("network", &Processor::getNetwork,
py::return_value_policy::reference)
.def_property_readonly("inports",
[](Processor *p) { return InportVecWrapper(p->getInports()); })
.def_property_readonly("outports",
[](Processor *p) { return OutportVecWrapper(p->getOutports()); })
.def("getPort", &Processor::getPort, py::return_value_policy::reference)
.def("getInport", &Processor::getInport, py::return_value_policy::reference)
.def("getOutport", &Processor::getOutport, py::return_value_policy::reference)
.def("addInport",
[](Processor &p, Inport *port, const std::string &group, bool owner) {
if (owner) {
p.addPort(std::unique_ptr<Inport>(port), group);
} else {
p.addPort(*port, group);
}
},
py::arg("inport"), py::arg("group") = "default", py::arg("owner") = true,
py::keep_alive<1, 2>{})
.def("addOutport",
[](Processor &p, Outport *port, const std::string &group, bool owner) {
if (owner) {
p.addPort(std::unique_ptr<Outport>(port), group);
} else {
p.addPort(*port, group);
}
},
py::arg("outport"), py::arg("group") = "default", py::arg("owner") = true,
py::keep_alive<1, 2>{})
.def("removeInport", [](Processor &p, Inport *port) { return p.removePort(port); })
.def("removeOutport", [](Processor &p, Outport *port) { return p.removePort(port); })
.def("getPortGroup", &Processor::getPortGroup)
.def("getPortGroups", &Processor::getPortGroups)
.def("getPortsInGroup", &Processor::getPortsInGroup)
.def("getPortsInSameGroup", &Processor::getPortsInSameGroup)
.def("allInportsConnected", &Processor::allInportsConnected)
.def("allInportsAreReady", &Processor::allInportsAreReady)
.def("isSource", &Processor::isSource)
.def("isSink", &Processor::isSink)
.def("isReady", &Processor::isReady)
.def("initializeResources", &Processor::initializeResources)
.def("process", &Processor::process)
.def("doIfNotReady", &Processor::doIfNotReady)
.def("setValid", &Processor::setValid)
.def("invalidate", &Processor::invalidate, py::arg("invalidationLevel"),
py::arg("modifiedProperty") = nullptr)
.def("invokeEvent", &Processor::invokeEvent)
.def("propagateEvent", &Processor::propagateEvent)
.def_property_readonly(
"meta",
[](Processor *p) {
return p->getMetaData<ProcessorMetaData>(ProcessorMetaData::CLASS_IDENTIFIER);
},
py::return_value_policy::reference);
py::class_<CanvasProcessor, Processor, ProcessorPtr<CanvasProcessor>>(m, "CanvasProcessor")
.def_property("size", &CanvasProcessor::getCanvasSize, &CanvasProcessor::setCanvasSize)
.def("getUseCustomDimensions", &CanvasProcessor::getUseCustomDimensions)
.def_property_readonly("customDimensions", &CanvasProcessor::getCustomDimensions)
.def_property_readonly("image", [](CanvasProcessor *cp) { return cp->getImage().get(); },
py::return_value_policy::reference)
.def_property_readonly("ready", &CanvasProcessor::isReady)
.def("snapshot", [](CanvasProcessor *canvas, std::string filepath) {
auto ext = filesystem::getFileExtension(filepath);
auto writer = canvas->getNetwork()
->getApplication()
->getDataWriterFactory()
->getWriterForTypeAndExtension<Layer>(ext);
if (!writer) {
throw Exception("No write for extension " + ext);
}
auto layer = canvas->getVisibleLayer();
writer->writeData(layer, filepath);
});
py::class_<PythonScriptProcessor, Processor, ProcessorPtr<PythonScriptProcessor>>(
m, "PythonScriptProcessor", py::dynamic_attr{})
.def("setInitializeResources", &PythonScriptProcessor::setInitializeResources)
.def("setProcess", &PythonScriptProcessor::setProcess);
}
} // namespace inviwo
<commit_msg>Python: Bug fix for saving non-existing canvas image. Occur when Canvas is not ready for example.<commit_after>/*********************************************************************************
*
* Inviwo - Interactive Visualization Workshop
*
* Copyright (c) 2017-2019 Inviwo Foundation
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
* ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
*********************************************************************************/
#include <inviwopy/pyprocessors.h>
#include <inviwopy/inviwopy.h>
#include <inviwopy/vectoridentifierwrapper.h>
#include <inviwo/core/processors/processor.h>
#include <inviwo/core/processors/processorfactory.h>
#include <inviwo/core/processors/processorfactoryobject.h>
#include <inviwo/core/processors/processorwidget.h>
#include <inviwo/core/processors/processorwidgetfactory.h>
#include <inviwo/core/processors/processorwidgetfactoryobject.h>
#include <inviwo/core/metadata/processormetadata.h>
#include <inviwo/core/datastructures/image/layer.h>
#include <inviwo/core/datastructures/image/layerram.h>
#include <inviwo/core/io/datawriterfactory.h>
#include <inviwo/core/util/filesystem.h>
#include <modules/python3/processors/pythonscriptprocessor.h>
namespace inviwo {
class ProcessorTrampoline : public Processor {
public:
/* Inherit the constructors */
using Processor::Processor;
/* Trampoline (need one for each virtual function) */
virtual void initializeResources() override {
PYBIND11_OVERLOAD(void, Processor, initializeResources, );
}
virtual void process() override { PYBIND11_OVERLOAD(void, Processor, process, ); }
virtual void doIfNotReady() override { PYBIND11_OVERLOAD(void, Processor, doIfNotReady, ); }
virtual void setValid() override { PYBIND11_OVERLOAD(void, Processor, setValid, ); }
virtual void invalidate(InvalidationLevel invalidationLevel,
Property *modifiedProperty = nullptr) override {
PYBIND11_OVERLOAD(void, Processor, invalidate, invalidationLevel, modifiedProperty);
}
virtual const ProcessorInfo getProcessorInfo() const override {
PYBIND11_OVERLOAD_PURE(const ProcessorInfo, Processor, getProcessorInfo, );
}
virtual void invokeEvent(Event *event) override {
PYBIND11_OVERLOAD(void, Processor, invokeEvent, event);
}
virtual void propagateEvent(Event *event, Outport *source) override {
PYBIND11_OVERLOAD(void, Processor, propagateEvent, event, source);
}
};
class ProcessorFactoryObjectTrampoline : public ProcessorFactoryObject {
public:
using ProcessorFactoryObject::ProcessorFactoryObject;
virtual pybind11::object createProcessor(InviwoApplication *app) {
PYBIND11_OVERLOAD(pybind11::object, ProcessorFactoryObjectTrampoline, createProcessor, app);
}
virtual std::unique_ptr<Processor> create(InviwoApplication *app) override {
auto proc = createProcessor(app);
auto p = std::unique_ptr<Processor>(proc.cast<Processor *>());
proc.release();
return p;
}
};
class ProcessorWidgetFactoryObjectTrampoline : public ProcessorWidgetFactoryObject {
public:
using ProcessorWidgetFactoryObject::ProcessorWidgetFactoryObject;
virtual pybind11::object createWidget(Processor *processor) {
PYBIND11_OVERLOAD(pybind11::object, ProcessorWidgetFactoryObjectTrampoline, createWidget,
processor);
}
virtual std::unique_ptr<ProcessorWidget> create(Processor *processor) override {
auto proc = createWidget(processor);
auto p = std::unique_ptr<ProcessorWidget>(proc.cast<ProcessorWidget *>());
proc.release();
return p;
}
};
void exposeProcessors(pybind11::module &m) {
namespace py = pybind11;
py::enum_<CodeState>(m, "CodeState")
.value("Broken", CodeState::Broken)
.value("Experimental", CodeState::Experimental)
.value("Stable", CodeState::Stable);
py::class_<Tag>(m, "Tag")
.def(py::init())
.def(py::init<std::string>())
.def(py::init<Tag>())
.def("getString", &Tag::getString);
py::class_<Tags>(m, "Tags")
.def(py::init())
.def(py::init<std::string>())
.def(py::init<Tags>())
.def("addTag", &Tags::addTag)
.def("addTags", &Tags::addTags)
.def("size", &Tags::size)
.def("empty", &Tags::empty)
.def("getString", &Tags::getString)
.def("getMatches", &Tags::getMatches)
.def_readwrite("tags", &Tags::tags_)
.def(py::self == py::self)
.def(py::self < py::self)
.def_readonly_static("CPU", &Tags::CPU)
.def_readonly_static("GL", &Tags::GL)
.def_readonly_static("CL", &Tags::CL)
.def_readonly_static("PY", &Tags::PY);
py::class_<ProcessorInfo>(m, "ProcessorInfo")
.def(py::init<std::string, std::string, std::string, CodeState, Tags, bool>(),
py::arg("classIdentifier"), py::arg("displayName"), py::arg("category") = "Python",
py::arg("codeState") = CodeState::Stable, py::arg("tags") = Tags::PY,
py::arg("visible") = true)
.def_readonly("classIdentifier", &ProcessorInfo::classIdentifier)
.def_readonly("displayName", &ProcessorInfo::displayName)
.def_readonly("category", &ProcessorInfo::category)
.def_readonly("codeState", &ProcessorInfo::codeState)
.def_readonly("tags", &ProcessorInfo::tags)
.def_readonly("visible", &ProcessorInfo::visible);
py::class_<ProcessorFactoryObject, ProcessorFactoryObjectTrampoline>(m,
"ProcessorFactoryObject")
.def(py::init<ProcessorInfo>())
.def("getProcessorInfo", &ProcessorFactoryObject::getProcessorInfo);
py::class_<ProcessorFactory>(m, "ProcessorFactory")
.def("hasKey", &ProcessorFactory::hasKey)
.def_property_readonly("keys", &ProcessorFactory::getKeys)
.def("create",
[](ProcessorFactory *pf, std::string key) { return pf->create(key).release(); })
.def("create",
[](ProcessorFactory *pf, std::string key, ivec2 pos) {
auto p = pf->create(key);
if (!p) {
throw py::key_error("failed to create processor of type '" + key + "'");
}
p->getMetaData<ProcessorMetaData>(ProcessorMetaData::CLASS_IDENTIFIER)
->setPosition(pos);
return p.release();
})
.def("registerObject", &ProcessorFactory::registerObject)
.def("unRegisterObject", &ProcessorFactory::unRegisterObject);
py::class_<ProcessorWidget>(m, "ProcessorWidget")
.def_property("visibility", &ProcessorWidget::isVisible, &ProcessorWidget::setVisible)
.def_property("dimensions", &ProcessorWidget::getDimensions,
&ProcessorWidget::setDimensions)
.def_property("position", &ProcessorWidget::getPosition, &ProcessorWidget::setPosition)
.def("show", &ProcessorWidget::show)
.def("hide", &ProcessorWidget::hide);
py::class_<ProcessorWidgetFactory>(m, "ProcessorWidgetFactory")
.def("registerObject", &ProcessorWidgetFactory::registerObject)
.def("unRegisterObject", &ProcessorWidgetFactory::unRegisterObject)
.def("create", [](ProcessorWidgetFactory *pf, Processor *p) { return pf->create(p); })
.def("hasKey", &ProcessorWidgetFactory::hasKey)
.def("getkeys", &ProcessorWidgetFactory::getKeys);
py::class_<ProcessorWidgetFactoryObject, ProcessorWidgetFactoryObjectTrampoline>(
m, "ProcessorWidgetFactoryObject")
.def(py::init<const std::string &>())
.def("getClassIdentifier", &ProcessorWidgetFactoryObject::getClassIdentifier);
py::class_<ProcessorMetaData>(m, "ProcessorMetaData")
.def_property("position", &ProcessorMetaData::getPosition, &ProcessorMetaData::setPosition)
.def_property("selected", &ProcessorMetaData::isSelected, &ProcessorMetaData::setSelected)
.def_property("visible", &ProcessorMetaData::isVisible, &ProcessorMetaData::setVisible);
using InportVecWrapper = VectorIdentifierWrapper<std::vector<Inport *>>;
exposeVectorIdentifierWrapper<std::vector<Inport *>>(m, "InportVectorWrapper");
using OutportVecWrapper = VectorIdentifierWrapper<std::vector<Outport *>>;
exposeVectorIdentifierWrapper<std::vector<Outport *>>(m, "OutportVectorWrapper");
py::class_<Processor, ProcessorTrampoline, PropertyOwner, ProcessorPtr<Processor>>(
m, "Processor", py::dynamic_attr{}, py::multiple_inheritance{})
.def(py::init<const std::string &, const std::string &>())
.def("__repr__", &Processor::getIdentifier)
.def_property_readonly("classIdentifier", &Processor::getClassIdentifier)
.def_property("displayName", &Processor::getDisplayName, &Processor::setDisplayName)
.def("getProcessorInfo", &Processor::getProcessorInfo)
.def_property_readonly("category", &Processor::getCategory)
.def_property_readonly("codeState", &Processor::getCodeState)
.def_property_readonly("tags", &Processor::getTags)
.def_property("identifier", &Processor::getIdentifier, &Processor::setIdentifier)
.def("hasProcessorWidget", &Processor::hasProcessorWidget)
.def_property_readonly("widget", &Processor::getProcessorWidget)
.def_property_readonly("network", &Processor::getNetwork,
py::return_value_policy::reference)
.def_property_readonly("inports",
[](Processor *p) { return InportVecWrapper(p->getInports()); })
.def_property_readonly("outports",
[](Processor *p) { return OutportVecWrapper(p->getOutports()); })
.def("getPort", &Processor::getPort, py::return_value_policy::reference)
.def("getInport", &Processor::getInport, py::return_value_policy::reference)
.def("getOutport", &Processor::getOutport, py::return_value_policy::reference)
.def("addInport",
[](Processor &p, Inport *port, const std::string &group, bool owner) {
if (owner) {
p.addPort(std::unique_ptr<Inport>(port), group);
} else {
p.addPort(*port, group);
}
},
py::arg("inport"), py::arg("group") = "default", py::arg("owner") = true,
py::keep_alive<1, 2>{})
.def("addOutport",
[](Processor &p, Outport *port, const std::string &group, bool owner) {
if (owner) {
p.addPort(std::unique_ptr<Outport>(port), group);
} else {
p.addPort(*port, group);
}
},
py::arg("outport"), py::arg("group") = "default", py::arg("owner") = true,
py::keep_alive<1, 2>{})
.def("removeInport", [](Processor &p, Inport *port) { return p.removePort(port); })
.def("removeOutport", [](Processor &p, Outport *port) { return p.removePort(port); })
.def("getPortGroup", &Processor::getPortGroup)
.def("getPortGroups", &Processor::getPortGroups)
.def("getPortsInGroup", &Processor::getPortsInGroup)
.def("getPortsInSameGroup", &Processor::getPortsInSameGroup)
.def("allInportsConnected", &Processor::allInportsConnected)
.def("allInportsAreReady", &Processor::allInportsAreReady)
.def("isSource", &Processor::isSource)
.def("isSink", &Processor::isSink)
.def("isReady", &Processor::isReady)
.def("initializeResources", &Processor::initializeResources)
.def("process", &Processor::process)
.def("doIfNotReady", &Processor::doIfNotReady)
.def("setValid", &Processor::setValid)
.def("invalidate", &Processor::invalidate, py::arg("invalidationLevel"),
py::arg("modifiedProperty") = nullptr)
.def("invokeEvent", &Processor::invokeEvent)
.def("propagateEvent", &Processor::propagateEvent)
.def_property_readonly(
"meta",
[](Processor *p) {
return p->getMetaData<ProcessorMetaData>(ProcessorMetaData::CLASS_IDENTIFIER);
},
py::return_value_policy::reference);
py::class_<CanvasProcessor, Processor, ProcessorPtr<CanvasProcessor>>(m, "CanvasProcessor")
.def_property("size", &CanvasProcessor::getCanvasSize, &CanvasProcessor::setCanvasSize)
.def("getUseCustomDimensions", &CanvasProcessor::getUseCustomDimensions)
.def_property_readonly("customDimensions", &CanvasProcessor::getCustomDimensions)
.def_property_readonly("image", [](CanvasProcessor *cp) { return cp->getImage().get(); },
py::return_value_policy::reference)
.def_property_readonly("ready", &CanvasProcessor::isReady)
.def("snapshot", [](CanvasProcessor *canvas, std::string filepath) {
auto ext = filesystem::getFileExtension(filepath);
auto writer = canvas->getNetwork()
->getApplication()
->getDataWriterFactory()
->getWriterForTypeAndExtension<Layer>(ext);
if (!writer) {
throw Exception("No writer for extension " + ext);
}
if (auto layer = canvas->getVisibleLayer()) {
writer->writeData(layer, filepath);
} else {
throw Exception("No image in canvas " + canvas->getIdentifier());
}
});
py::class_<PythonScriptProcessor, Processor, ProcessorPtr<PythonScriptProcessor>>(
m, "PythonScriptProcessor", py::dynamic_attr{})
.def("setInitializeResources", &PythonScriptProcessor::setInitializeResources)
.def("setProcess", &PythonScriptProcessor::setProcess);
}
} // namespace inviwo
<|endoftext|> |
<commit_before>/*
This file is part of the MinSG library extension BlueSurfels.
Copyright (C) 2014 Claudius Jähn <claudius@uni-paderborn.de>
Copyright (C) 2016-2017 Sascha Brandt <myeti@mail.uni-paderborn.de>
This library is subject to the terms of the Mozilla Public License, v. 2.0.
You should have received a copy of the MPL along with this library; see the
file LICENSE. If not, you can obtain one at http://mozilla.org/MPL/2.0/.
*/
#ifdef MINSG_EXT_BLUE_SURFELS
#include "E_SurfelRenderer_FixedSize.h"
#include "../../Core/E_FrameContext.h"
#include "../../ELibMinSG.h"
#include "../ELibMinSGExt.h"
#include <EScript/EScript.h>
namespace E_MinSG {
namespace BlueSurfels{
using namespace MinSG;
using namespace MinSG::BlueSurfels;
EScript::Type* E_SurfelRendererFixedSize::typeObject=nullptr;
//! (static) initMembers
void E_SurfelRendererFixedSize::init(EScript::Namespace & lib) {
// E_SurfelRendererFixedSize ---|> E_NodeRendererState ---|> E_State ---|> Object
typeObject = new EScript::Type(E_NodeRendererState::getTypeObject());
declareConstant(&lib,getClassName(),typeObject);
addFactory<SurfelRendererFixedSize,E_SurfelRendererFixedSize>();
//! [ESF] new MinSG.SurfelRendererFixedSize
ES_CTOR(typeObject, 0, 0, EScript::create(new SurfelRendererFixedSize))
//! [ESMF] Number surfelRenderer.getCountFactor()
ES_MFUN(typeObject,const SurfelRendererFixedSize,"getCountFactor",0,0,thisObj->getCountFactor())
//! [ESMF] self surfelRenderer.setCountFactor( Number )
ES_MFUN(typeObject,SurfelRendererFixedSize,"setCountFactor",1,1, (thisObj->setCountFactor(parameter[0].to<float>(rt)),thisEObj) )
//! [ESMF] Number surfelRenderer.getSizeFactor()
ES_MFUN(typeObject,const SurfelRendererFixedSize,"getSizeFactor",0,0,thisObj->getSizeFactor())
//! [ESMF] self surfelRenderer.setSizeFactor( Number )
ES_MFUN(typeObject,SurfelRendererFixedSize,"setSizeFactor",1,1, (thisObj->setSizeFactor(parameter[0].to<float>(rt)),thisEObj) )
//! [ESMF] Number surfelRenderer.getMaxSurfelSize()
ES_MFUN(typeObject,const SurfelRendererFixedSize,"getMaxSurfelSize",0,0,thisObj->getMaxSurfelSize())
//! [ESMF] self surfelRenderer.setMaxSurfelSize( Number )
ES_MFUN(typeObject,SurfelRendererFixedSize,"setMaxSurfelSize",1,1, (thisObj->setMaxSurfelSize(parameter[0].to<float>(rt)),thisEObj) )
//! [ESMF] Bool surfelRenderer.getDebugHideSurfels()
ES_MFUN(typeObject,const SurfelRendererFixedSize,"getDebugHideSurfels",0,0,thisObj->getDebugHideSurfels())
//! [ESMF] self surfelRenderer.setDebugHideSurfels( Bool )
ES_MFUN(typeObject,SurfelRendererFixedSize,"setDebugHideSurfels",1,1, (thisObj->setDebugHideSurfels(parameter[0].toBool()),thisEObj) )
//! [ESMF] Bool surfelRenderer.isDebugCameraEnabled()
ES_MFUN(typeObject,const SurfelRendererFixedSize,"isDebugCameraEnabled",0,0,thisObj->isDebugCameraEnabled())
//! [ESMF] self surfelRenderer.setDebugCameraEnabled( Bool )
ES_MFUN(typeObject,SurfelRendererFixedSize,"setDebugCameraEnabled",1,1, (thisObj->setDebugCameraEnabled(parameter[0].toBool()),thisEObj) )
//! [ESMF] Bool surfelRenderer.getDeferredSurfels()
ES_MFUN(typeObject,const SurfelRendererFixedSize,"getDeferredSurfels",0,0,thisObj->getDeferredSurfels())
//! [ESMF] self surfelRenderer.setDeferredSurfels( Bool )
ES_MFUN(typeObject,SurfelRendererFixedSize,"setDeferredSurfels",1,1, (thisObj->setDeferredSurfels(parameter[0].toBool()),thisEObj) )
//! [ESMF] Bool surfelRenderer.isAdaptive()
ES_MFUN(typeObject,const SurfelRendererFixedSize,"isAdaptive",0,0,thisObj->isAdaptive())
//! [ESMF] self surfelRenderer.setDeferredSurfels( Bool )
ES_MFUN(typeObject,SurfelRendererFixedSize,"setAdaptive",1,1, (thisObj->setAdaptive(parameter[0].toBool()),thisEObj) )
//! [ESMF] Bool surfelRenderer.getMaxFrameTime()
ES_MFUN(typeObject,const SurfelRendererFixedSize,"getMaxFrameTime",0,0,thisObj->getMaxFrameTime())
//! [ESMF] self surfelRenderer.setMaxFrameTime( Number )
ES_MFUN(typeObject,SurfelRendererFixedSize,"setMaxFrameTime",1,1, (thisObj->setMaxFrameTime(parameter[0].toFloat()),thisEObj) )
//! [ESMF] self surfelRenderer.drawSurfels( FrameContext, [Number, Number] )
ES_MFUN(typeObject,SurfelRendererFixedSize,"drawSurfels",1,3, (thisObj->drawSurfels(parameter[0].to<MinSG::FrameContext&>(rt), parameter[1].toFloat(0), parameter[2].toFloat(1024)),thisEObj) )
}
//---
//! (ctor)
E_SurfelRendererFixedSize::E_SurfelRendererFixedSize(SurfelRendererFixedSize * _obj, EScript::Type * type):E_NodeRendererState(_obj,type?type:typeObject){
}
//! (ctor)
E_SurfelRendererFixedSize::~E_SurfelRendererFixedSize(){
}
}
}
#endif // MINSG_EXT_BLUE_SURFELS
<commit_msg>BlueSurfels: bindings for foveated rendering<commit_after>/*
This file is part of the MinSG library extension BlueSurfels.
Copyright (C) 2014 Claudius Jähn <claudius@uni-paderborn.de>
Copyright (C) 2016-2017 Sascha Brandt <myeti@mail.uni-paderborn.de>
This library is subject to the terms of the Mozilla Public License, v. 2.0.
You should have received a copy of the MPL along with this library; see the
file LICENSE. If not, you can obtain one at http://mozilla.org/MPL/2.0/.
*/
#ifdef MINSG_EXT_BLUE_SURFELS
#include "E_SurfelRenderer_FixedSize.h"
#include "../../Core/E_FrameContext.h"
#include "../../ELibMinSG.h"
#include "../ELibMinSGExt.h"
#include <EScript/EScript.h>
namespace E_MinSG {
namespace BlueSurfels{
using namespace MinSG;
using namespace MinSG::BlueSurfels;
EScript::Type* E_SurfelRendererFixedSize::typeObject=nullptr;
//! (static) initMembers
void E_SurfelRendererFixedSize::init(EScript::Namespace & lib) {
// E_SurfelRendererFixedSize ---|> E_NodeRendererState ---|> E_State ---|> Object
typeObject = new EScript::Type(E_NodeRendererState::getTypeObject());
declareConstant(&lib,getClassName(),typeObject);
addFactory<SurfelRendererFixedSize,E_SurfelRendererFixedSize>();
//! [ESF] new MinSG.SurfelRendererFixedSize
ES_CTOR(typeObject, 0, 0, EScript::create(new SurfelRendererFixedSize))
//! [ESMF] Number surfelRenderer.getCountFactor()
ES_MFUN(typeObject,const SurfelRendererFixedSize,"getCountFactor",0,0,thisObj->getCountFactor())
//! [ESMF] self surfelRenderer.setCountFactor( Number )
ES_MFUN(typeObject,SurfelRendererFixedSize,"setCountFactor",1,1, (thisObj->setCountFactor(parameter[0].to<float>(rt)),thisEObj) )
//! [ESMF] Number surfelRenderer.getSizeFactor()
ES_MFUN(typeObject,const SurfelRendererFixedSize,"getSizeFactor",0,0,thisObj->getSizeFactor())
//! [ESMF] self surfelRenderer.setSizeFactor( Number )
ES_MFUN(typeObject,SurfelRendererFixedSize,"setSizeFactor",1,1, (thisObj->setSizeFactor(parameter[0].to<float>(rt)),thisEObj) )
//! [ESMF] Number surfelRenderer.getSurfelSize()
ES_MFUN(typeObject,const SurfelRendererFixedSize,"getSurfelSize",0,0,thisObj->getSurfelSize())
//! [ESMF] self surfelRenderer.setSurfelSize( Number )
ES_MFUN(typeObject,SurfelRendererFixedSize,"setSurfelSize",1,1, (thisObj->setSurfelSize(parameter[0].to<float>(rt)),thisEObj) )
//! [ESMF] Number surfelRenderer.getMaxSurfelSize()
ES_MFUN(typeObject,const SurfelRendererFixedSize,"getMaxSurfelSize",0,0,thisObj->getMaxSurfelSize())
//! [ESMF] self surfelRenderer.setMaxSurfelSize( Number )
ES_MFUN(typeObject,SurfelRendererFixedSize,"setMaxSurfelSize",1,1, (thisObj->setMaxSurfelSize(parameter[0].to<float>(rt)),thisEObj) )
//! [ESMF] Bool surfelRenderer.getDebugHideSurfels()
ES_MFUN(typeObject,const SurfelRendererFixedSize,"getDebugHideSurfels",0,0,thisObj->getDebugHideSurfels())
//! [ESMF] self surfelRenderer.setDebugHideSurfels( Bool )
ES_MFUN(typeObject,SurfelRendererFixedSize,"setDebugHideSurfels",1,1, (thisObj->setDebugHideSurfels(parameter[0].toBool()),thisEObj) )
//! [ESMF] Bool surfelRenderer.isDebugCameraEnabled()
ES_MFUN(typeObject,const SurfelRendererFixedSize,"isDebugCameraEnabled",0,0,thisObj->isDebugCameraEnabled())
//! [ESMF] self surfelRenderer.setDebugCameraEnabled( Bool )
ES_MFUN(typeObject,SurfelRendererFixedSize,"setDebugCameraEnabled",1,1, (thisObj->setDebugCameraEnabled(parameter[0].toBool()),thisEObj) )
//! [ESMF] Bool surfelRenderer.getDeferredSurfels()
ES_MFUN(typeObject,const SurfelRendererFixedSize,"getDeferredSurfels",0,0,thisObj->getDeferredSurfels())
//! [ESMF] self surfelRenderer.setDeferredSurfels( Bool )
ES_MFUN(typeObject,SurfelRendererFixedSize,"setDeferredSurfels",1,1, (thisObj->setDeferredSurfels(parameter[0].toBool()),thisEObj) )
//! [ESMF] Bool surfelRenderer.isAdaptive()
ES_MFUN(typeObject,const SurfelRendererFixedSize,"isAdaptive",0,0,thisObj->isAdaptive())
//! [ESMF] self surfelRenderer.setDeferredSurfels( Bool )
ES_MFUN(typeObject,SurfelRendererFixedSize,"setAdaptive",1,1, (thisObj->setAdaptive(parameter[0].toBool()),thisEObj) )
//! [ESMF] Bool surfelRenderer.getMaxFrameTime()
ES_MFUN(typeObject,const SurfelRendererFixedSize,"getMaxFrameTime",0,0,thisObj->getMaxFrameTime())
//! [ESMF] self surfelRenderer.setMaxFrameTime( Number )
ES_MFUN(typeObject,SurfelRendererFixedSize,"setMaxFrameTime",1,1, (thisObj->setMaxFrameTime(parameter[0].toFloat()),thisEObj) )
//! [ESMF] self surfelRenderer.drawSurfels( FrameContext, [Number, Number] )
ES_MFUN(typeObject,SurfelRendererFixedSize,"drawSurfels",1,3, (thisObj->drawSurfels(parameter[0].to<MinSG::FrameContext&>(rt), parameter[1].toFloat(0), parameter[2].toFloat(1024)),thisEObj) )
//! [ESMF] Bool surfelRenderer.isFoveated()
ES_MFUN(typeObject,const SurfelRendererFixedSize,"isFoveated",0,0,thisObj->isFoveated())
//! [ESMF] self surfelRenderer.setFoveated( Bool )
ES_MFUN(typeObject,SurfelRendererFixedSize,"setFoveated",1,1, (thisObj->setFoveated(parameter[0].toBool()),thisEObj) )
//! [ESMF] Bool surfelRenderer.getFoveatZones()
ES_MFUNCTION(typeObject,const SurfelRendererFixedSize,"getFoveatZones",0,0,{
auto zones = thisObj->getFoveatZones();
auto a = EScript::Array::create();
for(const auto& zone : zones) {
a->pushBack(EScript::Number::create(zone.first));
a->pushBack(EScript::Number::create(zone.second));
}
return a;
})
//! [ESMF] self surfelRenderer.setFoveatZones( Array )
ES_MFUNCTION(typeObject,SurfelRendererFixedSize,"setFoveatZones",1,1, {
auto a = parameter[0].to<EScript::Array*>(rt);
auto zones = thisObj->getFoveatZones();
zones.clear();
for(uint32_t i=1; i<a->count(); i+=2) {
zones.push_back({a->get(i-1)->toFloat(), a->get(i)->toFloat()});
}
thisObj->setFoveatZones(zones);
return thisEObj;
})
}
//---
//! (ctor)
E_SurfelRendererFixedSize::E_SurfelRendererFixedSize(SurfelRendererFixedSize * _obj, EScript::Type * type):E_NodeRendererState(_obj,type?type:typeObject){
}
//! (ctor)
E_SurfelRendererFixedSize::~E_SurfelRendererFixedSize(){
}
}
}
#endif // MINSG_EXT_BLUE_SURFELS
<|endoftext|> |
<commit_before><commit_msg>Prevent base::debug::BreakDebugger() from being folded by the linker<commit_after><|endoftext|> |
<commit_before>/*
* Simulation.cpp
*
* The box2d simulation of the pinball machine
*/
#ifndef PINBALL_BOT_SIMULATION
#define PINBALL_BOT_SIMULATION
#include <stdio.h>
#include <Box2D/Box2D.h>
#include <cmath>
#include "../agent/Ball.cpp"
#include "../agent/State.cpp"
const int32 VELOCITY_ITERATIONS = 6;
const int32 POSITION_ITERATIONS = 2;
const int32 PLAYINGFIELD_VERTEX_NUMBER = 10;
const float GRAVITY_X = 0;
const float GRAVITY_Y = 5.0f; /* positive, cause we start in the top left corner */
const float FLIPPER_HEIGHT = 1.0f;
const float FLIPPER_WIDTH = 0.5f;
const float WALL_THICKNESS = 0.05f;
const float BALL_RADIUS = 0.025f;
const float BALL_DENSITY = 0.0001f;
const float BALL_FRICTION = 0.01f;
const float BALL_RESTITUTION = 0.9f;
const float FLIPPER_DENSITY = 0.0001f;
const float FLIPPER_FRICTION = 0.01f;
const float FLIPPER_RESTITUTION = 0.3f;
const float FLIPPER_REV_JOINT_LOWER_ANGLE = (float) 0.0f * b2_pi;
const float FLIPPER_REV_JOINT_UPPER_ANGLE = (float) 0.1f * b2_pi;
const float FLIPPER_REV_MOTOR_SPEED = (float) 1.5 * b2_pi; /* rad^-1 */
const float FLIPPER_REV_MOTOR_MAX_TORQUE = 5.0f;
/**
* Class used to simulate a pinball machine using Box2D
*/
class PinballSimulation{
private:
//The Box2D world where all the things take place
b2Vec2 gravity;
b2World world;
//The playing field
b2BodyDef playingFieldDef[PLAYINGFIELD_VERTEX_NUMBER];
b2Body* playingFieldBody[PLAYINGFIELD_VERTEX_NUMBER];
b2EdgeShape playingFieldEdge[PLAYINGFIELD_VERTEX_NUMBER];
//The ball used to play the game
b2BodyDef ballDef;
b2Body* ballBody;
b2CircleShape ballSphere;
b2FixtureDef ballFixtureDef;
//The flipper on the left hand side
b2BodyDef flipperLeftDef;
b2Body* flipperLeftBody;
b2PolygonShape flipperLeftTriangle;
b2FixtureDef flipperLeftFixtureDef;
b2RevoluteJointDef flipperLeftRevJointDef;
b2RevoluteJoint* flipperLeftRevJoint;
//The flipper on the right hand side
b2BodyDef flipperRightDef;
b2Body* flipperRightBody;
b2PolygonShape flipperRightTriangle;
b2FixtureDef flipperRightFixtureDef;
b2RevoluteJointDef flipperRightRevJointDef;
b2RevoluteJoint* flipperRightRevJoint;
public:
/**
* Inits the world and all of the needed objects
*/
PinballSimulation() : gravity(GRAVITY_X, GRAVITY_Y), world(this->gravity){
/* Initializes a world with gravity pulling downwards */
/* Remember: The origin (0|0) is the top left corner! */
/* Define edge shape of the playing field */
b2Vec2 playingFieldVertices[PLAYINGFIELD_VERTEX_NUMBER];
playingFieldVertices[0].Set(0, FLIPPER_HEIGHT / 8);
playingFieldVertices[1].Set((std::sin(b2_pi/20)*FLIPPER_HEIGHT/8), (FLIPPER_HEIGHT / 8) - (std::cos(b2_pi/20)*FLIPPER_HEIGHT / 8) );
playingFieldVertices[2].Set((std::sin(2 * b2_pi / 20)*FLIPPER_HEIGHT / 8), (FLIPPER_HEIGHT / 8) - (std::cos(2 * b2_pi / 20)*FLIPPER_HEIGHT / 8));
playingFieldVertices[3].Set((std::sin(3 * b2_pi / 20)*FLIPPER_HEIGHT / 8), (FLIPPER_HEIGHT / 8) - (std::cos(3 * b2_pi / 20)*FLIPPER_HEIGHT / 8));
playingFieldVertices[4].Set((std::sin(4 * b2_pi / 20)*FLIPPER_HEIGHT / 8), (FLIPPER_HEIGHT / 8) - (std::cos(4 * b2_pi / 20)*FLIPPER_HEIGHT / 8));
playingFieldVertices[5].Set((std::sin(5 * b2_pi / 20)*FLIPPER_HEIGHT / 8), (FLIPPER_HEIGHT / 8) - (std::cos(5 * b2_pi / 20)*FLIPPER_HEIGHT / 8));
playingFieldVertices[6].Set((std::sin(6 * b2_pi / 20)*FLIPPER_HEIGHT / 8), (FLIPPER_HEIGHT / 8) - (std::cos(6 * b2_pi / 20)*FLIPPER_HEIGHT / 8));
playingFieldVertices[7].Set((std::sin(7 * b2_pi / 20)*FLIPPER_HEIGHT / 8), (FLIPPER_HEIGHT / 8) - (std::cos(7 * b2_pi / 20)*FLIPPER_HEIGHT / 8));
playingFieldVertices[8].Set((std::sin(8 * b2_pi / 20)*FLIPPER_HEIGHT / 8), (FLIPPER_HEIGHT / 8) - (std::cos(8 * b2_pi / 20)*FLIPPER_HEIGHT / 8));
playingFieldVertices[9].Set((std::sin(9 * b2_pi / 20)*FLIPPER_HEIGHT / 8), (FLIPPER_HEIGHT / 8) - (std::cos(9 * b2_pi / 20)*FLIPPER_HEIGHT / 8));
drawPlayingField(playingFieldVertices);
/* Add 2 flippers */
flipperLeftDef.type = b2_dynamicBody;
flipperRightDef.type = b2_dynamicBody;
flipperLeftDef.position.Set(WALL_THICKNESS, (3*FLIPPER_HEIGHT/4));
flipperRightDef.position.Set(FLIPPER_WIDTH-WALL_THICKNESS, (3*FLIPPER_HEIGHT/4));
/* Triangle */
b2Vec2 leftFlipperVertices[3];
leftFlipperVertices[0].Set(0.0f, 0.0f);
leftFlipperVertices[1].Set(0.0f, 0.05f);
leftFlipperVertices[2].Set(0.15f, 0.05f);
flipperLeftTriangle.Set(leftFlipperVertices, 3);
/* Triangle */
b2Vec2 rightFlipperVertices[3];
rightFlipperVertices[0].Set(0.0f, 0.0f);
rightFlipperVertices[1].Set(0.0f, 0.05f);
rightFlipperVertices[2].Set(-0.15f, 0.05f);
flipperRightTriangle.Set(rightFlipperVertices, 3);
flipperLeftBody = world.CreateBody(&this->flipperLeftDef);
flipperRightBody = world.CreateBody(&this->flipperRightDef);
this->flipperLeftFixtureDef.shape = &this->flipperLeftTriangle;
this->flipperRightFixtureDef.shape = &this->flipperRightTriangle;
this->flipperLeftFixtureDef.density = this->flipperRightFixtureDef.density = FLIPPER_DENSITY;
this->flipperLeftFixtureDef.friction = this->flipperRightFixtureDef.friction = FLIPPER_FRICTION;
this->flipperLeftFixtureDef.restitution = this->flipperRightFixtureDef.restitution = FLIPPER_RESTITUTION;
this->flipperLeftBody->CreateFixture(&this->flipperLeftFixtureDef);
this->flipperRightBody->CreateFixture(&this->flipperRightFixtureDef);
/* Connect the flippers to the walls with a joint */
flipperLeftRevJointDef.bodyA = playingFieldBody[0];
flipperLeftRevJointDef.bodyB = flipperLeftBody;
flipperRightRevJointDef.bodyA = playingFieldBody[0];
flipperRightRevJointDef.bodyB = flipperRightBody;
flipperLeftRevJointDef.localAnchorA = b2Vec2((WALL_THICKNESS/2), 0.0f);
flipperLeftRevJointDef.localAnchorB = b2Vec2(0.0f, 0.0f);
flipperRightRevJointDef.localAnchorA = b2Vec2((-WALL_THICKNESS/2), 0.0f);
flipperRightRevJointDef.localAnchorB = b2Vec2(0.0f, 0.0f);
flipperLeftRevJointDef.collideConnected = flipperRightRevJointDef.collideConnected = false;
flipperLeftRevJointDef.lowerAngle = -1 * FLIPPER_REV_JOINT_UPPER_ANGLE;
flipperLeftRevJointDef.upperAngle = FLIPPER_REV_JOINT_LOWER_ANGLE;
flipperRightRevJointDef.lowerAngle = FLIPPER_REV_JOINT_LOWER_ANGLE;
flipperRightRevJointDef.upperAngle = FLIPPER_REV_JOINT_UPPER_ANGLE;
flipperLeftRevJointDef.enableLimit = flipperRightRevJointDef.enableLimit = true;
flipperLeftRevJointDef.maxMotorTorque = flipperRightRevJointDef.maxMotorTorque = FLIPPER_REV_MOTOR_MAX_TORQUE;
flipperLeftRevJointDef.enableMotor = flipperRightRevJointDef.enableMotor = false; // Not enabled by default
flipperLeftRevJointDef.motorSpeed = -1 * FLIPPER_REV_MOTOR_SPEED;
flipperRightRevJointDef.motorSpeed = FLIPPER_REV_MOTOR_SPEED;
flipperLeftRevJoint = (b2RevoluteJoint*)this->world.CreateJoint(&flipperLeftRevJointDef);
flipperRightRevJoint = (b2RevoluteJoint*)this->world.CreateJoint(&flipperRightRevJointDef);
/* Init playing ball */
ballDef.type = b2_dynamicBody;
ballDef.position.Set((FLIPPER_WIDTH/2), (FLIPPER_HEIGHT/2));
ballBody = world.CreateBody(&this->ballDef);
this->ballSphere.m_p.Set(0.0f, 0.0f);
this->ballSphere.m_radius = BALL_RADIUS;
this->ballFixtureDef.shape = &this->ballSphere;
this->ballFixtureDef.density = BALL_DENSITY;
this->ballFixtureDef.friction = BALL_FRICTION;
this->ballFixtureDef.restitution = BALL_RESTITUTION;
this->ballBody->CreateFixture(&this->ballFixtureDef);
}
void drawPlayingField(const b2Vec2* points){
for(int i=0;i<PLAYINGFIELD_VERTEX_NUMBER;i++){
playingFieldDef[i].type = b2_staticBody;
playingFieldDef[i].position.Set(0, 0);
playingFieldEdge[i].Set(points[i], points[i+1]);
playingFieldBody[i] = world.CreateBody(&playingFieldDef[i]);
playingFieldBody[i]->CreateFixture(&playingFieldEdge[i], 0.0f);
}
}
/**
* Steps a specific value forward in time
* @param time_step float32 The amount of time to step
* @return void
*/
void step(const float32 &time_step){
world.Step(time_step, VELOCITY_ITERATIONS, POSITION_ITERATIONS);
}
/**
* Sets the DebugDraw renderer of the Box2D world
* @param draw b2Draw A pointer to a class implementing the b2Draw functions
* @return void
*/
void setRenderer(b2Draw* draw){
this->world.SetDebugDraw( draw );
}
/**
* Renders the scene by calling the DrawDebugData function inside the Box2D world,
* which calls back to the initially set b2Draw class
* @return void
*/
void render(){
this->world.DrawDebugData();
}
/**
* Activates the left hand flipper. Will stay active until disableLeftFlipper() is called
* @return void
*/
void enableLeftFlipper(){
flipperLeftRevJoint->EnableMotor(true);
}
/**
* Deactivates the left hand flipper. Gravity will do it's job again
* @return void
*/
void disableLeftFlipper(){
flipperLeftRevJoint->EnableMotor(false);
}
/**
* Activates the right hand flipper. Will stay active until disableLeftFlipper() is called
* @return void
*/
void enableRightFlipper(){
flipperRightRevJoint->EnableMotor(true);
}
/**
* Deactivates the right hand flipper. Gravity will do it's job again
* @return void
*/
void disableRightFlipper(){
flipperRightRevJoint->EnableMotor(false);
}
/**
* Prints debugging information about the playing ball
* @return void
*/
void debugPlayingBall(){
b2Vec2 position = this->ballBody->GetPosition();
float32 angle = this->ballBody->GetAngle();
printf("%4.2f %4.2f %4.2f\n", position.x, position.y, angle);
}
State getCurrentState(){
return State(Ball(this->ballBody->GetPosition(), this->ballBody->GetLinearVelocity()), flipperLeftRevJoint->IsMotorEnabled(), flipperRightRevJoint->IsMotorEnabled());
}
class s{
};
};
#endif /* PINBALL_BOT_SIMULATION */
<commit_msg>Fixing local git issue<commit_after>/*
* Simulation.cpp
*
* The box2d simulation of the pinball machine
*/
#ifndef PINBALL_BOT_SIMULATION
#define PINBALL_BOT_SIMULATION
#include <stdio.h>
#include <Box2D/Box2D.h>
#include <cmath>
#include "../agent/Ball.cpp"
#include "../agent/State.cpp"
const int32 VELOCITY_ITERATIONS = 6;
const int32 POSITION_ITERATIONS = 2;
const int32 PLAYINGFIELD_VERTEX_NUMBER = 10;
const float GRAVITY_X = 0;
const float GRAVITY_Y = 5.0f; /* positive, cause we start in the top left corner */
const float FLIPPER_HEIGHT = 1.0f;
const float FLIPPER_WIDTH = 0.5f;
const float WALL_THICKNESS = 0.05f;
const float BALL_RADIUS = 0.025f;
const float BALL_DENSITY = 0.0001f;
const float BALL_FRICTION = 0.01f;
const float BALL_RESTITUTION = 0.9f;
const float FLIPPER_DENSITY = 0.0001f;
const float FLIPPER_FRICTION = 0.01f;
const float FLIPPER_RESTITUTION = 0.3f;
const float FLIPPER_REV_JOINT_LOWER_ANGLE = (float) 0.0f * b2_pi;
const float FLIPPER_REV_JOINT_UPPER_ANGLE = (float) 0.1f * b2_pi;
const float FLIPPER_REV_MOTOR_SPEED = (float) 1.5 * b2_pi; /* rad^-1 */
const float FLIPPER_REV_MOTOR_MAX_TORQUE = 5.0f;
/**
* Class used to simulate a pinball machine using Box2D
*/
class PinballSimulation{
private:
//The Box2D world where all the things take place
b2Vec2 gravity;
b2World world;
//The playing field
b2BodyDef playingFieldDef;
b2Body* playingFieldBody;
b2PolygonShape playingFieldPolygon;
//The ball used to play the game
b2BodyDef ballDef;
b2Body* ballBody;
b2CircleShape ballSphere;
b2FixtureDef ballFixtureDef;
//The flipper on the left hand side
b2BodyDef flipperLeftDef;
b2Body* flipperLeftBody;
b2PolygonShape flipperLeftTriangle;
b2FixtureDef flipperLeftFixtureDef;
b2RevoluteJointDef flipperLeftRevJointDef;
b2RevoluteJoint* flipperLeftRevJoint;
//The flipper on the right hand side
b2BodyDef flipperRightDef;
b2Body* flipperRightBody;
b2PolygonShape flipperRightTriangle;
b2FixtureDef flipperRightFixtureDef;
b2RevoluteJointDef flipperRightRevJointDef;
b2RevoluteJoint* flipperRightRevJoint;
public:
/**
* Inits the world and all of the needed objects
*/
PinballSimulation() : gravity(GRAVITY_X, GRAVITY_Y), world(this->gravity){
/* Initializes a world with gravity pulling downwards */
/* Sets the position of the boundaries. Remember: The origin (0|0) is the top left corner! */
this->playingFieldDef.position.Set((WALL_THICKNESS/2), (WALL_THICKNESS/2));
/* Define polygon shape of the playing field */
b2Vec2 playingFieldVertices[PLAYINGFIELD_VERTEX_NUMBER];
playingFieldVertices[0].Set(0, FLIPPER_HEIGHT / 8);
playingFieldVertices[1].Set((std::sin(b2_pi/20)*FLIPPER_HEIGHT/8), (FLIPPER_HEIGHT / 8) - (std::cos(b2_pi/20)*FLIPPER_HEIGHT / 8) );
playingFieldVertices[2].Set((std::sin(2 * b2_pi / 20)*FLIPPER_HEIGHT / 8), (FLIPPER_HEIGHT / 8) - (std::cos(2 * b2_pi / 20)*FLIPPER_HEIGHT / 8));
playingFieldVertices[3].Set((std::sin(3 * b2_pi / 20)*FLIPPER_HEIGHT / 8), (FLIPPER_HEIGHT / 8) - (std::cos(3 * b2_pi / 20)*FLIPPER_HEIGHT / 8));
playingFieldVertices[4].Set((std::sin(4 * b2_pi / 20)*FLIPPER_HEIGHT / 8), (FLIPPER_HEIGHT / 8) - (std::cos(4 * b2_pi / 20)*FLIPPER_HEIGHT / 8));
playingFieldVertices[5].Set((std::sin(5 * b2_pi / 20)*FLIPPER_HEIGHT / 8), (FLIPPER_HEIGHT / 8) - (std::cos(5 * b2_pi / 20)*FLIPPER_HEIGHT / 8));
playingFieldVertices[6].Set((std::sin(6 * b2_pi / 20)*FLIPPER_HEIGHT / 8), (FLIPPER_HEIGHT / 8) - (std::cos(6 * b2_pi / 20)*FLIPPER_HEIGHT / 8));
playingFieldVertices[7].Set((std::sin(7 * b2_pi / 20)*FLIPPER_HEIGHT / 8), (FLIPPER_HEIGHT / 8) - (std::cos(7 * b2_pi / 20)*FLIPPER_HEIGHT / 8));
playingFieldVertices[8].Set((std::sin(8 * b2_pi / 20)*FLIPPER_HEIGHT / 8), (FLIPPER_HEIGHT / 8) - (std::cos(8 * b2_pi / 20)*FLIPPER_HEIGHT / 8));
playingFieldVertices[9].Set((std::sin(9 * b2_pi / 20)*FLIPPER_HEIGHT / 8), (FLIPPER_HEIGHT / 8) - (std::cos(9 * b2_pi / 20)*FLIPPER_HEIGHT / 8));
playingFieldPolygon.Set(playingFieldVertices, PLAYINGFIELD_VERTEX_NUMBER);
/* Adds the boundaries to the world */
this->playingFieldBody = world.CreateBody(&this->playingFieldDef);
playingFieldDef
/* Creates fixtures for the boundaries, set the density to 0 because they're static anyway */
playingFieldBody->CreateFixture(&this->playingFieldPolygon, 0.0f);
/* Add 2 flippers */
flipperLeftDef.type = b2_dynamicBody;
flipperRightDef.type = b2_dynamicBody;
flipperLeftDef.position.Set(WALL_THICKNESS, (3*FLIPPER_HEIGHT/4));
flipperRightDef.position.Set(FLIPPER_WIDTH-WALL_THICKNESS, (3*FLIPPER_HEIGHT/4));
/* Triangle */
b2Vec2 leftFlipperVertices[3];
leftFlipperVertices[0].Set(0.0f, 0.0f);
leftFlipperVertices[1].Set(0.0f, 0.05f);
leftFlipperVertices[2].Set(0.15f, 0.05f);
flipperLeftTriangle.Set(leftFlipperVertices, 3);
/* Triangle */
b2Vec2 rightFlipperVertices[3];
rightFlipperVertices[0].Set(0.0f, 0.0f);
rightFlipperVertices[1].Set(0.0f, 0.05f);
rightFlipperVertices[2].Set(-0.15f, 0.05f);
flipperRightTriangle.Set(rightFlipperVertices, 3);
flipperLeftBody = world.CreateBody(&this->flipperLeftDef);
flipperRightBody = world.CreateBody(&this->flipperRightDef);
this->flipperLeftFixtureDef.shape = &this->flipperLeftTriangle;
this->flipperRightFixtureDef.shape = &this->flipperRightTriangle;
this->flipperLeftFixtureDef.density = this->flipperRightFixtureDef.density = FLIPPER_DENSITY;
this->flipperLeftFixtureDef.friction = this->flipperRightFixtureDef.friction = FLIPPER_FRICTION;
this->flipperLeftFixtureDef.restitution = this->flipperRightFixtureDef.restitution = FLIPPER_RESTITUTION;
this->flipperLeftBody->CreateFixture(&this->flipperLeftFixtureDef);
this->flipperRightBody->CreateFixture(&this->flipperRightFixtureDef);
/* Connect the flippers to the walls with a joint */
flipperLeftRevJointDef.bodyA = playingFieldBody;
flipperLeftRevJointDef.bodyB = flipperLeftBody;
flipperRightRevJointDef.bodyA = playingFieldBody;
flipperRightRevJointDef.bodyB = flipperRightBody;
flipperLeftRevJointDef.localAnchorA = b2Vec2((WALL_THICKNESS/2), 0.0f);
flipperLeftRevJointDef.localAnchorB = b2Vec2(0.0f, 0.0f);
flipperRightRevJointDef.localAnchorA = b2Vec2((-WALL_THICKNESS/2), 0.0f);
flipperRightRevJointDef.localAnchorB = b2Vec2(0.0f, 0.0f);
flipperLeftRevJointDef.collideConnected = flipperRightRevJointDef.collideConnected = false;
flipperLeftRevJointDef.lowerAngle = -1 * FLIPPER_REV_JOINT_UPPER_ANGLE;
flipperLeftRevJointDef.upperAngle = FLIPPER_REV_JOINT_LOWER_ANGLE;
flipperRightRevJointDef.lowerAngle = FLIPPER_REV_JOINT_LOWER_ANGLE;
flipperRightRevJointDef.upperAngle = FLIPPER_REV_JOINT_UPPER_ANGLE;
flipperLeftRevJointDef.enableLimit = flipperRightRevJointDef.enableLimit = true;
flipperLeftRevJointDef.maxMotorTorque = flipperRightRevJointDef.maxMotorTorque = FLIPPER_REV_MOTOR_MAX_TORQUE;
flipperLeftRevJointDef.enableMotor = flipperRightRevJointDef.enableMotor = false; /* Not enabled by default */
flipperLeftRevJointDef.motorSpeed = -1 * FLIPPER_REV_MOTOR_SPEED;
flipperRightRevJointDef.motorSpeed = FLIPPER_REV_MOTOR_SPEED;
flipperLeftRevJoint = (b2RevoluteJoint*)this->world.CreateJoint(&flipperLeftRevJointDef);
flipperRightRevJoint = (b2RevoluteJoint*)this->world.CreateJoint(&flipperRightRevJointDef);
/* Init playing ball */
ballDef.type = b2_dynamicBody;
ballDef.position.Set((FLIPPER_WIDTH/2), (FLIPPER_HEIGHT/2));
ballBody = world.CreateBody(&this->ballDef);
this->ballSphere.m_p.Set(0.0f, 0.0f);
this->ballSphere.m_radius = BALL_RADIUS;
this->ballFixtureDef.shape = &this->ballSphere;
this->ballFixtureDef.density = BALL_DENSITY;
this->ballFixtureDef.friction = BALL_FRICTION;
this->ballFixtureDef.restitution = BALL_RESTITUTION;
this->ballBody->CreateFixture(&this->ballFixtureDef);
}
/**
* Steps a specific value forward in time
* @param time_step float32 The amount of time to step
* @return void
*/
void step(const float32 &time_step){
world.Step(time_step, VELOCITY_ITERATIONS, POSITION_ITERATIONS);
}
/**
* Sets the DebugDraw renderer of the Box2D world
* @param draw b2Draw A pointer to a class implementing the b2Draw functions
* @return void
*/
void setRenderer(b2Draw* draw){
this->world.SetDebugDraw( draw );
}
/**
* Renders the scene by calling the DrawDebugData function inside the Box2D world,
* which calls back to the initially set b2Draw class
* @return void
*/
void render(){
this->world.DrawDebugData();
}
/**
* Activates the left hand flipper. Will stay active until disableLeftFlipper() is called
* @return void
*/
void enableLeftFlipper(){
flipperLeftRevJoint->EnableMotor(true);
}
/**
* Deactivates the left hand flipper. Gravity will do it's job again
* @return void
*/
void disableLeftFlipper(){
flipperLeftRevJoint->EnableMotor(false);
}
/**
* Activates the right hand flipper. Will stay active until disableLeftFlipper() is called
* @return void
*/
void enableRightFlipper(){
flipperRightRevJoint->EnableMotor(true);
}
/**
* Deactivates the right hand flipper. Gravity will do it's job again
* @return void
*/
void disableRightFlipper(){
flipperRightRevJoint->EnableMotor(false);
}
/**
* Prints debugging information about the playing ball
* @return void
*/
void debugPlayingBall(){
b2Vec2 position = this->ballBody->GetPosition();
float32 angle = this->ballBody->GetAngle();
printf("%4.2f %4.2f %4.2f\n", position.x, position.y, angle);
}
State getCurrentState(){
return State(Ball(this->ballBody->GetPosition(), this->ballBody->GetLinearVelocity()));
}
class s{
};
};
#endif /* PINBALL_BOT_SIMULATION */
<|endoftext|> |
<commit_before>#include "common.h"
#include <iostream>
#include <boost/math/special_functions/binomial.hpp>
// probability of equality of two calls of the SAME reference position
double p_equal_calls = 0.0;
// probability of 'sequenced position' which represents the probability of a read
// starting at a given position of the reference
double p_read_start = 0.0;
void initProbabilities() {
// convenience variables
double p_err = Options::opts.pe;
double q_err = 1.0 - p_err;
// init p_equal_calls
p_equal_calls = q_err * q_err + (1.0 / 3.0) * ( p_err * p_err );
// init p_read_start
p_read_start = (double)Options::opts.M / (double)Options::opts.N;
}
void clearProbabilities() {
}
/**
* Compute
* \sum_{s}{I(A,B,s)4^s}
*/
double overlappingStringsSum(const std::string & s1, const std::string& s2) {
size_t m = Options::opts.m;
double sum = 0.0;
for (size_t s = 1; s <= m-1; ++s) {
size_t indicator_ab = (prefixSuffixHammingDistance(s2,s1,s) == 0) ? 1 : 0;
size_t indicator_ba = (prefixSuffixHammingDistance(s1,s2,s) == 0) ? 1 : 0;
sum += pow(4,s) * ( indicator_ab + indicator_ba );
}
size_t indic_m = (prefixSuffixHammingDistance(s2,s1,m) == 0) ? 1 : 0;
sum += indic_m * pow(4,m);
return sum;
}
/**
* Computes probability of a random overlap of 's' bases with an hamming distance dh
*/
double randomReadsOverlapProbNoErr(const std::string& s1, const std::string& s2, size_t s) {
size_t dh_for_s = prefixSuffixHammingDistance(s1,s2,s);
if (dh_for_s != 0) {
return 0;
}
double olap_p = overlappingStringsSum(s1,s2) + (double)Options::opts.N - 2 * (double)Options::opts.m + 1.0;
return ( pow(4,s) / ( olap_p) ) ;
}
<commit_msg>Added probability for reads generation<commit_after>#include "common.h"
#include <iostream>
#include <boost/math/special_functions/binomial.hpp>
// probability of equality of two calls of the SAME reference position
double p_equal_calls = 0.0;
// probability of 'sequenced position' which represents the probability of a read
// starting at a given position of the reference
double p_read_start = 0.0;
void initProbabilities() {
// convenience variables
double p_err = Options::opts.pe;
double q_err = 1.0 - p_err;
// init p_equal_calls
p_equal_calls = q_err * q_err + (1.0 / 3.0) * ( p_err * p_err );
// init p_read_start
p_read_start = (double)Options::opts.M / (double)Options::opts.N;
}
void clearProbabilities() {
}
double probabilityReads(const std::string& s1, const std::string& s2, size_t d) {
// probability of D = d distance between reads
double p_s = p_read_start * pow(1.0 - p_read_start, d);
// no overlap
if (d >= Options::opts.m) {
return pow(4,2*Options::opts.m) * p_s;
}
size_t dh = prefixSuffixHammingDistance(s1,s2,Options::opts.m - d);
// probability of dh unequal bases on the common part
double p_err = pow(p_equal_calls, (Options::opts.m - d - dh)) * pow(1.0 - p_equal_calls, dh) ;
// probability of indipendent parts
double p_ind = pow(4,2*d);
return p_s * p_err * p_ind;
}
/**
* Compute
* \sum_{s}{I(A,B,s)4^s}
*/
double overlappingStringsSum(const std::string & s1, const std::string& s2) {
size_t m = Options::opts.m;
double sum = 0.0;
for (size_t s = 1; s <= m-1; ++s) {
size_t indicator_ab = (prefixSuffixHammingDistance(s2,s1,s) == 0) ? 1 : 0;
size_t indicator_ba = (prefixSuffixHammingDistance(s1,s2,s) == 0) ? 1 : 0;
sum += pow(4,s) * ( indicator_ab + indicator_ba );
}
size_t indic_m = (prefixSuffixHammingDistance(s2,s1,m) == 0) ? 1 : 0;
sum += indic_m * pow(4,m);
return sum;
}
/**
* Computes probability of a random overlap of 's' bases with an hamming distance dh
*/
double randomReadsOverlapProbNoErr(const std::string& s1, const std::string& s2, size_t s) {
size_t dh_for_s = prefixSuffixHammingDistance(s1,s2,s);
if (dh_for_s != 0) {
return 0;
}
double olap_p = overlappingStringsSum(s1,s2) + (double)Options::opts.N - 2 * (double)Options::opts.m + 1.0;
return ( pow(4,s) / ( olap_p) ) ;
}
<|endoftext|> |
<commit_before>/*
*
* Copyright 2015, Google Inc.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following disclaimer
* in the documentation and/or other materials provided with the
* distribution.
* * Neither the name of Google Inc. nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
*/
#include <cassert>
#include <forward_list>
#include <functional>
#include <memory>
#include <mutex>
#include <string>
#include <thread>
#include <vector>
#include <sstream>
#include <grpc/grpc.h>
#include <grpc/support/histogram.h>
#include <grpc/support/log.h>
#include <gflags/gflags.h>
#include <grpc++/async_unary_call.h>
#include <grpc++/client_context.h>
#include <grpc++/status.h>
#include <grpc++/stream.h>
#include "test/cpp/util/create_test_channel.h"
#include "test/cpp/qps/qpstest.grpc.pb.h"
#include "test/cpp/qps/timer.h"
#include "test/cpp/qps/client.h"
namespace grpc {
namespace testing {
typedef std::forward_list<grpc_time> deadline_list;
class ClientRpcContext {
public:
ClientRpcContext() {}
virtual ~ClientRpcContext() {}
// next state, return false if done. Collect stats when appropriate
virtual bool RunNextState(bool, Histogram* hist) = 0;
virtual void StartNewClone() = 0;
static void* tag(ClientRpcContext* c) { return reinterpret_cast<void*>(c); }
static ClientRpcContext* detag(void* t) {
return reinterpret_cast<ClientRpcContext*>(t);
}
deadline_list::iterator deadline_posn() const {return deadline_posn_;}
void set_deadline_posn(deadline_list::iterator&& it) {deadline_posn_ = it;}
virtual void Start() = 0;
private:
deadline_list::iterator deadline_posn_;
};
template <class RequestType, class ResponseType>
class ClientRpcContextUnaryImpl : public ClientRpcContext {
public:
ClientRpcContextUnaryImpl(
TestService::Stub* stub, const RequestType& req,
std::function<
std::unique_ptr<grpc::ClientAsyncResponseReader<ResponseType>>(
TestService::Stub*, grpc::ClientContext*, const RequestType&)>
start_req,
std::function<void(grpc::Status, ResponseType*)> on_done)
: context_(),
stub_(stub),
req_(req),
response_(),
next_state_(&ClientRpcContextUnaryImpl::RespDone),
callback_(on_done),
start_req_(start_req) {
}
void Start() GRPC_OVERRIDE {
start_ = Timer::Now();
response_reader_ = start_req_(stub_, &context_, req_);
response_reader_->Finish(&response_, &status_, ClientRpcContext::tag(this));
}
~ClientRpcContextUnaryImpl() GRPC_OVERRIDE {}
bool RunNextState(bool ok, Histogram* hist) GRPC_OVERRIDE {
bool ret = (this->*next_state_)(ok);
if (!ret) {
hist->Add((Timer::Now() - start_) * 1e9);
}
return ret;
}
void StartNewClone() GRPC_OVERRIDE {
new ClientRpcContextUnaryImpl(stub_, req_, start_req_, callback_);
}
private:
bool RespDone(bool) {
next_state_ = &ClientRpcContextUnaryImpl::DoCallBack;
return false;
}
bool DoCallBack(bool) {
callback_(status_, &response_);
return false;
}
grpc::ClientContext context_;
TestService::Stub* stub_;
RequestType req_;
ResponseType response_;
bool (ClientRpcContextUnaryImpl::*next_state_)(bool);
std::function<void(grpc::Status, ResponseType*)> callback_;
std::function<std::unique_ptr<grpc::ClientAsyncResponseReader<ResponseType>>(
TestService::Stub*, grpc::ClientContext*, const RequestType&)> start_req_;
grpc::Status status_;
double start_;
std::unique_ptr<grpc::ClientAsyncResponseReader<ResponseType>>
response_reader_;
};
class AsyncClient : public Client {
public:
explicit AsyncClient(const ClientConfig& config,
std::function<ClientRpcContext*(CompletionQueue*, TestService::Stub*,
const SimpleRequest&)> setup_ctx) :
Client(config), channel_rpc_lock_(config.client_channels()) {
for (int i = 0; i < config.async_client_threads(); i++) {
cli_cqs_.emplace_back(new CompletionQueue);
if (!closed_loop_) {
rpc_deadlines_.emplace_back();
next_channel_.push_back(i % channel_count_);
issue_allowed_.push_back(true);
grpc_time next_issue;
NextIssueTime(i, &next_issue);
next_issue_.push_back(next_issue);
}
}
if (!closed_loop_) {
for (auto channel = channels_.begin(); channel != channels_.end();
channel++) {
rpcs_outstanding_.push_back(0);
}
}
int t = 0;
for (int i = 0; i < config.outstanding_rpcs_per_channel(); i++) {
for (auto channel = channels_.begin(); channel != channels_.end();
channel++) {
auto* cq = cli_cqs_[t].get();
t = (t + 1) % cli_cqs_.size();
ClientRpcContext *ctx = setup_ctx(cq, channel->get_stub(), request_);
if (closed_loop_) {
// only relevant for closed_loop unary, but harmless for
// closed_loop streaming
ctx->Start();
}
}
}
}
virtual ~AsyncClient() {
for (auto cq = cli_cqs_.begin(); cq != cli_cqs_.end(); cq++) {
(*cq)->Shutdown();
void* got_tag;
bool ok;
while ((*cq)->Next(&got_tag, &ok)) {
delete ClientRpcContext::detag(got_tag);
}
}
}
bool ThreadFunc(Histogram* histogram,
size_t thread_idx) GRPC_OVERRIDE GRPC_FINAL {
void* got_tag;
bool ok;
grpc_time deadline, short_deadline;
if (closed_loop_) {
deadline = grpc_time_source::now() + std::chrono::seconds(1);
short_deadline = deadline;
} else {
deadline = *(rpc_deadlines_[thread_idx].begin());
short_deadline = issue_allowed_[thread_idx] ?
next_issue_[thread_idx] : deadline;
}
bool got_event;
switch (cli_cqs_[thread_idx]->AsyncNext(&got_tag, &ok, short_deadline)) {
case CompletionQueue::SHUTDOWN: return false;
case CompletionQueue::TIMEOUT:
got_event = false;
break;
case CompletionQueue::GOT_EVENT:
got_event = true;
break;
}
if (grpc_time_source::now() > deadline) {
// we have missed some 1-second deadline, which is too much gpr_log(GPR_INFO, "Missed an RPC deadline, giving up");
return false;
}
if (got_event) {
ClientRpcContext* ctx = ClientRpcContext::detag(got_tag);
if (ctx->RunNextState(ok, histogram) == false) {
// call the callback and then delete it
rpc_deadlines_[thread_idx].erase_after(ctx->deadline_posn());
ctx->RunNextState(ok, histogram);
ctx->StartNewClone();
delete ctx;
}
issue_allowed_[thread_idx] = true; // may be ok now even if it hadn't been
}
if (issue_allowed_[thread_idx] &&
grpc_time_source::now() >= next_issue_[thread_idx]) {
// Attempt to issue
bool issued = false;
for (int num_attempts = 0; num_attempts < channel_count_ && !issued;
num_attempts++, next_channel_[thread_idx] = (next_channel_[thread_idx]+1)%channel_count_) {
std::lock_guard<std::mutex>
g(channel_rpc_lock_[next_channel_[thread_idx]]);
if (rpcs_outstanding_[next_channel_[thread_idx]] < max_outstanding_per_channel_) {
// do the work to issue
rpcs_outstanding_[next_channel_[thread_idx]]++;
issued = true;
}
}
if (!issued)
issue_allowed_[thread_idx] = false;
}
return true;
}
private:
std::vector<std::unique_ptr<CompletionQueue>> cli_cqs_;
std::vector<deadline_list> rpc_deadlines_; // per thread deadlines
std::vector<int> next_channel_; // per thread round-robin channel ctr
std::vector<bool> issue_allowed_; // may this thread attempt to issue
std::vector<grpc_time> next_issue_; // when should it issue?
std::vector<std::mutex> channel_rpc_lock_;
std::vector<int> rpcs_outstanding_; // per-channel vector
int max_outstanding_per_channel_;
int channel_count_;
};
class AsyncUnaryClient GRPC_FINAL : public AsyncClient {
public:
explicit AsyncUnaryClient(const ClientConfig& config)
: AsyncClient(config, SetupCtx) {
StartThreads(config.async_client_threads());
}
~AsyncUnaryClient() GRPC_OVERRIDE { EndThreads(); }
private:
static ClientRpcContext *SetupCtx(CompletionQueue* cq, TestService::Stub* stub,
const SimpleRequest& req) {
auto check_done = [](grpc::Status s, SimpleResponse* response) {};
auto start_req = [cq](TestService::Stub* stub, grpc::ClientContext* ctx,
const SimpleRequest& request) {
return stub->AsyncUnaryCall(ctx, request, cq);
};
return new ClientRpcContextUnaryImpl<SimpleRequest, SimpleResponse>(
stub, req, start_req, check_done);
}
};
template <class RequestType, class ResponseType>
class ClientRpcContextStreamingImpl : public ClientRpcContext {
public:
ClientRpcContextStreamingImpl(
TestService::Stub* stub, const RequestType& req,
std::function<std::unique_ptr<
grpc::ClientAsyncReaderWriter<RequestType, ResponseType>>(
TestService::Stub*, grpc::ClientContext*, void*)> start_req,
std::function<void(grpc::Status, ResponseType*)> on_done)
: context_(),
stub_(stub),
req_(req),
response_(),
next_state_(&ClientRpcContextStreamingImpl::ReqSent),
callback_(on_done),
start_req_(start_req),
start_(Timer::Now()),
stream_(start_req_(stub_, &context_, ClientRpcContext::tag(this))) {}
~ClientRpcContextStreamingImpl() GRPC_OVERRIDE {}
bool RunNextState(bool ok, Histogram* hist) GRPC_OVERRIDE {
return (this->*next_state_)(ok, hist);
}
void StartNewClone() GRPC_OVERRIDE {
new ClientRpcContextStreamingImpl(stub_, req_, start_req_, callback_);
}
void Start() GRPC_OVERRIDE {}
private:
bool ReqSent(bool ok, Histogram*) { return StartWrite(ok); }
bool StartWrite(bool ok) {
if (!ok) {
return (false);
}
start_ = Timer::Now();
next_state_ = &ClientRpcContextStreamingImpl::WriteDone;
stream_->Write(req_, ClientRpcContext::tag(this));
return true;
}
bool WriteDone(bool ok, Histogram*) {
if (!ok) {
return (false);
}
next_state_ = &ClientRpcContextStreamingImpl::ReadDone;
stream_->Read(&response_, ClientRpcContext::tag(this));
return true;
}
bool ReadDone(bool ok, Histogram* hist) {
hist->Add((Timer::Now() - start_) * 1e9);
return StartWrite(ok);
}
grpc::ClientContext context_;
TestService::Stub* stub_;
RequestType req_;
ResponseType response_;
bool (ClientRpcContextStreamingImpl::*next_state_)(bool, Histogram*);
std::function<void(grpc::Status, ResponseType*)> callback_;
std::function<
std::unique_ptr<grpc::ClientAsyncReaderWriter<RequestType, ResponseType>>(
TestService::Stub*, grpc::ClientContext*, void*)> start_req_;
grpc::Status status_;
double start_;
std::unique_ptr<grpc::ClientAsyncReaderWriter<RequestType, ResponseType>>
stream_;
};
class AsyncStreamingClient GRPC_FINAL : public AsyncClient {
public:
explicit AsyncStreamingClient(const ClientConfig& config)
: AsyncClient(config, SetupCtx) {
StartThreads(config.async_client_threads());
}
~AsyncStreamingClient() GRPC_OVERRIDE { EndThreads(); }
private:
static ClientRpcContext *SetupCtx(CompletionQueue* cq, TestService::Stub* stub,
const SimpleRequest& req) {
auto check_done = [](grpc::Status s, SimpleResponse* response) {};
auto start_req = [cq](TestService::Stub* stub, grpc::ClientContext* ctx,
void* tag) {
auto stream = stub->AsyncStreamingCall(ctx, cq, tag);
return stream;
};
return new ClientRpcContextStreamingImpl<SimpleRequest, SimpleResponse>(
stub, req, start_req, check_done);
}
};
std::unique_ptr<Client> CreateAsyncUnaryClient(const ClientConfig& args) {
return std::unique_ptr<Client>(new AsyncUnaryClient(args));
}
std::unique_ptr<Client> CreateAsyncStreamingClient(const ClientConfig& args) {
return std::unique_ptr<Client>(new AsyncStreamingClient(args));
}
} // namespace testing
} // namespace grpc
<commit_msg>Invoke LoadTest setup<commit_after>/*
*
* Copyright 2015, Google Inc.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following disclaimer
* in the documentation and/or other materials provided with the
* distribution.
* * Neither the name of Google Inc. nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
*/
#include <cassert>
#include <forward_list>
#include <functional>
#include <memory>
#include <mutex>
#include <string>
#include <thread>
#include <vector>
#include <sstream>
#include <grpc/grpc.h>
#include <grpc/support/histogram.h>
#include <grpc/support/log.h>
#include <gflags/gflags.h>
#include <grpc++/async_unary_call.h>
#include <grpc++/client_context.h>
#include <grpc++/status.h>
#include <grpc++/stream.h>
#include "test/cpp/util/create_test_channel.h"
#include "test/cpp/qps/qpstest.grpc.pb.h"
#include "test/cpp/qps/timer.h"
#include "test/cpp/qps/client.h"
namespace grpc {
namespace testing {
typedef std::forward_list<grpc_time> deadline_list;
class ClientRpcContext {
public:
ClientRpcContext() {}
virtual ~ClientRpcContext() {}
// next state, return false if done. Collect stats when appropriate
virtual bool RunNextState(bool, Histogram* hist) = 0;
virtual void StartNewClone() = 0;
static void* tag(ClientRpcContext* c) { return reinterpret_cast<void*>(c); }
static ClientRpcContext* detag(void* t) {
return reinterpret_cast<ClientRpcContext*>(t);
}
deadline_list::iterator deadline_posn() const {return deadline_posn_;}
void set_deadline_posn(deadline_list::iterator&& it) {deadline_posn_ = it;}
virtual void Start() = 0;
private:
deadline_list::iterator deadline_posn_;
};
template <class RequestType, class ResponseType>
class ClientRpcContextUnaryImpl : public ClientRpcContext {
public:
ClientRpcContextUnaryImpl(
TestService::Stub* stub, const RequestType& req,
std::function<
std::unique_ptr<grpc::ClientAsyncResponseReader<ResponseType>>(
TestService::Stub*, grpc::ClientContext*, const RequestType&)>
start_req,
std::function<void(grpc::Status, ResponseType*)> on_done)
: context_(),
stub_(stub),
req_(req),
response_(),
next_state_(&ClientRpcContextUnaryImpl::RespDone),
callback_(on_done),
start_req_(start_req) {
}
void Start() GRPC_OVERRIDE {
start_ = Timer::Now();
response_reader_ = start_req_(stub_, &context_, req_);
response_reader_->Finish(&response_, &status_, ClientRpcContext::tag(this));
}
~ClientRpcContextUnaryImpl() GRPC_OVERRIDE {}
bool RunNextState(bool ok, Histogram* hist) GRPC_OVERRIDE {
bool ret = (this->*next_state_)(ok);
if (!ret) {
hist->Add((Timer::Now() - start_) * 1e9);
}
return ret;
}
void StartNewClone() GRPC_OVERRIDE {
new ClientRpcContextUnaryImpl(stub_, req_, start_req_, callback_);
}
private:
bool RespDone(bool) {
next_state_ = &ClientRpcContextUnaryImpl::DoCallBack;
return false;
}
bool DoCallBack(bool) {
callback_(status_, &response_);
return false;
}
grpc::ClientContext context_;
TestService::Stub* stub_;
RequestType req_;
ResponseType response_;
bool (ClientRpcContextUnaryImpl::*next_state_)(bool);
std::function<void(grpc::Status, ResponseType*)> callback_;
std::function<std::unique_ptr<grpc::ClientAsyncResponseReader<ResponseType>>(
TestService::Stub*, grpc::ClientContext*, const RequestType&)> start_req_;
grpc::Status status_;
double start_;
std::unique_ptr<grpc::ClientAsyncResponseReader<ResponseType>>
response_reader_;
};
class AsyncClient : public Client {
public:
explicit AsyncClient(const ClientConfig& config,
std::function<ClientRpcContext*(CompletionQueue*, TestService::Stub*,
const SimpleRequest&)> setup_ctx) :
Client(config), channel_rpc_lock_(config.client_channels()) {
SetupLoadTest(config, num_threads_);
for (int i = 0; i < config.async_client_threads(); i++) {
cli_cqs_.emplace_back(new CompletionQueue);
if (!closed_loop_) {
rpc_deadlines_.emplace_back();
next_channel_.push_back(i % channel_count_);
issue_allowed_.push_back(true);
grpc_time next_issue;
NextIssueTime(i, &next_issue);
next_issue_.push_back(next_issue);
}
}
if (!closed_loop_) {
for (auto channel = channels_.begin(); channel != channels_.end();
channel++) {
rpcs_outstanding_.push_back(0);
}
}
int t = 0;
for (int i = 0; i < config.outstanding_rpcs_per_channel(); i++) {
for (auto channel = channels_.begin(); channel != channels_.end();
channel++) {
auto* cq = cli_cqs_[t].get();
t = (t + 1) % cli_cqs_.size();
ClientRpcContext *ctx = setup_ctx(cq, channel->get_stub(), request_);
if (closed_loop_) {
// only relevant for closed_loop unary, but harmless for
// closed_loop streaming
ctx->Start();
}
}
}
}
virtual ~AsyncClient() {
for (auto cq = cli_cqs_.begin(); cq != cli_cqs_.end(); cq++) {
(*cq)->Shutdown();
void* got_tag;
bool ok;
while ((*cq)->Next(&got_tag, &ok)) {
delete ClientRpcContext::detag(got_tag);
}
}
}
bool ThreadFunc(Histogram* histogram,
size_t thread_idx) GRPC_OVERRIDE GRPC_FINAL {
void* got_tag;
bool ok;
grpc_time deadline, short_deadline;
if (closed_loop_) {
deadline = grpc_time_source::now() + std::chrono::seconds(1);
short_deadline = deadline;
} else {
deadline = *(rpc_deadlines_[thread_idx].begin());
short_deadline = issue_allowed_[thread_idx] ?
next_issue_[thread_idx] : deadline;
}
bool got_event;
switch (cli_cqs_[thread_idx]->AsyncNext(&got_tag, &ok, short_deadline)) {
case CompletionQueue::SHUTDOWN: return false;
case CompletionQueue::TIMEOUT:
got_event = false;
break;
case CompletionQueue::GOT_EVENT:
got_event = true;
break;
}
if (grpc_time_source::now() > deadline) {
// we have missed some 1-second deadline, which is too much gpr_log(GPR_INFO, "Missed an RPC deadline, giving up");
return false;
}
if (got_event) {
ClientRpcContext* ctx = ClientRpcContext::detag(got_tag);
if (ctx->RunNextState(ok, histogram) == false) {
// call the callback and then delete it
rpc_deadlines_[thread_idx].erase_after(ctx->deadline_posn());
ctx->RunNextState(ok, histogram);
ctx->StartNewClone();
delete ctx;
}
issue_allowed_[thread_idx] = true; // may be ok now even if it hadn't been
}
if (issue_allowed_[thread_idx] &&
grpc_time_source::now() >= next_issue_[thread_idx]) {
// Attempt to issue
bool issued = false;
for (int num_attempts = 0; num_attempts < channel_count_ && !issued;
num_attempts++, next_channel_[thread_idx] = (next_channel_[thread_idx]+1)%channel_count_) {
std::lock_guard<std::mutex>
g(channel_rpc_lock_[next_channel_[thread_idx]]);
if (rpcs_outstanding_[next_channel_[thread_idx]] < max_outstanding_per_channel_) {
// do the work to issue
rpcs_outstanding_[next_channel_[thread_idx]]++;
issued = true;
}
}
if (!issued)
issue_allowed_[thread_idx] = false;
}
return true;
}
private:
std::vector<std::unique_ptr<CompletionQueue>> cli_cqs_;
std::vector<deadline_list> rpc_deadlines_; // per thread deadlines
std::vector<int> next_channel_; // per thread round-robin channel ctr
std::vector<bool> issue_allowed_; // may this thread attempt to issue
std::vector<grpc_time> next_issue_; // when should it issue?
std::vector<std::mutex> channel_rpc_lock_;
std::vector<int> rpcs_outstanding_; // per-channel vector
int max_outstanding_per_channel_;
int channel_count_;
};
class AsyncUnaryClient GRPC_FINAL : public AsyncClient {
public:
explicit AsyncUnaryClient(const ClientConfig& config)
: AsyncClient(config, SetupCtx) {
StartThreads(config.async_client_threads());
}
~AsyncUnaryClient() GRPC_OVERRIDE { EndThreads(); }
private:
static ClientRpcContext *SetupCtx(CompletionQueue* cq, TestService::Stub* stub,
const SimpleRequest& req) {
auto check_done = [](grpc::Status s, SimpleResponse* response) {};
auto start_req = [cq](TestService::Stub* stub, grpc::ClientContext* ctx,
const SimpleRequest& request) {
return stub->AsyncUnaryCall(ctx, request, cq);
};
return new ClientRpcContextUnaryImpl<SimpleRequest, SimpleResponse>(
stub, req, start_req, check_done);
}
};
template <class RequestType, class ResponseType>
class ClientRpcContextStreamingImpl : public ClientRpcContext {
public:
ClientRpcContextStreamingImpl(
TestService::Stub* stub, const RequestType& req,
std::function<std::unique_ptr<
grpc::ClientAsyncReaderWriter<RequestType, ResponseType>>(
TestService::Stub*, grpc::ClientContext*, void*)> start_req,
std::function<void(grpc::Status, ResponseType*)> on_done)
: context_(),
stub_(stub),
req_(req),
response_(),
next_state_(&ClientRpcContextStreamingImpl::ReqSent),
callback_(on_done),
start_req_(start_req),
start_(Timer::Now()),
stream_(start_req_(stub_, &context_, ClientRpcContext::tag(this))) {}
~ClientRpcContextStreamingImpl() GRPC_OVERRIDE {}
bool RunNextState(bool ok, Histogram* hist) GRPC_OVERRIDE {
return (this->*next_state_)(ok, hist);
}
void StartNewClone() GRPC_OVERRIDE {
new ClientRpcContextStreamingImpl(stub_, req_, start_req_, callback_);
}
void Start() GRPC_OVERRIDE {}
private:
bool ReqSent(bool ok, Histogram*) { return StartWrite(ok); }
bool StartWrite(bool ok) {
if (!ok) {
return (false);
}
start_ = Timer::Now();
next_state_ = &ClientRpcContextStreamingImpl::WriteDone;
stream_->Write(req_, ClientRpcContext::tag(this));
return true;
}
bool WriteDone(bool ok, Histogram*) {
if (!ok) {
return (false);
}
next_state_ = &ClientRpcContextStreamingImpl::ReadDone;
stream_->Read(&response_, ClientRpcContext::tag(this));
return true;
}
bool ReadDone(bool ok, Histogram* hist) {
hist->Add((Timer::Now() - start_) * 1e9);
return StartWrite(ok);
}
grpc::ClientContext context_;
TestService::Stub* stub_;
RequestType req_;
ResponseType response_;
bool (ClientRpcContextStreamingImpl::*next_state_)(bool, Histogram*);
std::function<void(grpc::Status, ResponseType*)> callback_;
std::function<
std::unique_ptr<grpc::ClientAsyncReaderWriter<RequestType, ResponseType>>(
TestService::Stub*, grpc::ClientContext*, void*)> start_req_;
grpc::Status status_;
double start_;
std::unique_ptr<grpc::ClientAsyncReaderWriter<RequestType, ResponseType>>
stream_;
};
class AsyncStreamingClient GRPC_FINAL : public AsyncClient {
public:
explicit AsyncStreamingClient(const ClientConfig& config)
: AsyncClient(config, SetupCtx) {
StartThreads(config.async_client_threads());
}
~AsyncStreamingClient() GRPC_OVERRIDE { EndThreads(); }
private:
static ClientRpcContext *SetupCtx(CompletionQueue* cq, TestService::Stub* stub,
const SimpleRequest& req) {
auto check_done = [](grpc::Status s, SimpleResponse* response) {};
auto start_req = [cq](TestService::Stub* stub, grpc::ClientContext* ctx,
void* tag) {
auto stream = stub->AsyncStreamingCall(ctx, cq, tag);
return stream;
};
return new ClientRpcContextStreamingImpl<SimpleRequest, SimpleResponse>(
stub, req, start_req, check_done);
}
};
std::unique_ptr<Client> CreateAsyncUnaryClient(const ClientConfig& args) {
return std::unique_ptr<Client>(new AsyncUnaryClient(args));
}
std::unique_ptr<Client> CreateAsyncStreamingClient(const ClientConfig& args) {
return std::unique_ptr<Client>(new AsyncStreamingClient(args));
}
} // namespace testing
} // namespace grpc
<|endoftext|> |
<commit_before>/**
* TEM.cpp
* main program for running DVM-DOS-TEM
*
* It runs at 3 run-mods:
* (1) site-specific
* (2) regional - time series
* (3) regional - spatially (not yet available)
*
* Authors: Shuhua Yi - the original codes
* Fengming Yuan - re-designing and re-coding for (1) easily code managing;
* (2) java interface developing for calibration;
* (3) stand-alone application of TEM (java-c++)
* (4) inputs/outputs using netcdf format, have to be modified
* to fix memory-leaks
* (5) fix the snow/soil thermal/hydraulic algorithms
* (6) DVM coupled
* Tobey Carman - modifications and maintenance
* 1) update application entry point with boost command line arg. handling.
*
* Affilation: Spatial Ecology Lab, University of Alaska Fairbanks
*
* started: 11/01/2010
* last modified: 09/18/2012
*/
#include <string>
#include <iostream>
#include <fstream>
#include <sstream>
#include <ctime>
#include <cstdlib>
#include <exception>
#include <map>
#include <boost/signals2.hpp>
#include <boost/asio/signal_set.hpp>
#include <boost/thread.hpp>
#include "ArgHandler.h"
#include "TEMLogger.h"
#include "assembler/Runner.h"
BOOST_LOG_INLINE_GLOBAL_LOGGER_INIT(my_general_logger, severity_channel_logger_t) {
return severity_channel_logger_t(keywords::channel = "GENER");
}
BOOST_LOG_INLINE_GLOBAL_LOGGER_INIT(my_cal_logger, severity_channel_logger_t) {
return severity_channel_logger_t(keywords::channel = "CALIB");
}
void handler(const boost::system::error_code& error, int signal_number) {
if (!error) {
cout << "Caught a signal!!\n";
exit(-1);
}
}
void tbc_runner(){
std::cout << "jUST STARTING THE WORKER...\n";
boost::posix_time::seconds workTime(10);
boost::this_thread::sleep(workTime);
std::cout << "WORKER DONE SLEEPING!! thread done, moving on.....\n";
}
void stop_calibration(const boost::system::error_code& error,
int signal_number){
std::cout << "Now what? I caught a sigint: " << signal_number << std::endl;
std::cout << "SLEEPING!...\n";
boost::posix_time::seconds workTime(10);
boost::this_thread::sleep(workTime);
}
void calibration_worker_thread(/*ArgHandler* const args ? */){
// get handles for each of global loggers...
severity_channel_logger_t& glg = my_general_logger::get();
severity_channel_logger_t& clg = my_cal_logger::get();
BOOST_LOG_SEV(glg, info) << "Starting Calibration Worker Thread.";
BOOST_LOG_SEV(glg, info) << "This should start the model in x,y,z mode and crunch numbers....";
BOOST_LOG_SEV(glg, info) << "To simulate that, I am sleeping for 10 seconds...";
boost::posix_time::seconds workTime(10);
boost::this_thread::sleep(workTime);
BOOST_LOG_SEV(glg, info) << "Done working. This thread is finished.";
}
ArgHandler* args = new ArgHandler();
int main(int argc, char* argv[]){
args->parse(argc, argv);
if (args->getHelp()){
args->showHelp();
return 0;
}
args->verify();
std::cout << "Setting up Logging...\n";
setup_console_log_sink();
set_log_severity_level(args->getLogLevel());
// get handles for each of global loggers...
severity_channel_logger_t& glg = my_general_logger::get();
severity_channel_logger_t& clg = my_cal_logger::get();
if (args->getCalibrationMode() == "on") {
BOOST_LOG_SEV(glg, info) << "Running in Calibration Mode";
BOOST_LOG_SEV(glg, info) << "Making an io_service.";
boost::asio::io_service io_service;
BOOST_LOG_SEV(glg, info) << "Defining a signal set that the io_service will listen for.";
boost::asio::signal_set signals(io_service, SIGINT, SIGTERM);
// ??? stops service ???.
// signals.async_wait(boost::bind(
// &boost::asio::io_service::stop, &io_service));
BOOST_LOG_SEV(glg, info) << "Define a callback that will run when the service "
<< "delivers one of the defined signals.";
signals.async_wait(&stop_calibration);
// this is going to go off and sleep for 10 secs...
BOOST_LOG_SEV(glg, info) << "Start a worker thread to run tem.";
boost::thread workerThread(&calibration_worker_thread); // need to figure out how to pass args to this..
BOOST_LOG_SEV(glg, info) << "Run the io_service in the main thread, waiting "
<< "asynchronously for a signal to be captured/handled...";
io_service.run();
BOOST_LOG_SEV(glg, info) << "Exited from io_service.run().";
//workerThread.join();
} else {
BOOST_LOG_SEV(glg, info) << "Running in extrapolation mode.";
setvbuf(stdout, NULL, _IONBF, 0);
setvbuf(stderr, NULL, _IONBF, 0);
if (args->getMode() == "siterun") {
time_t stime;
time_t etime;
stime=time(0);
BOOST_LOG_SEV(glg, info) << "Running dvm-dos-tem in siterun mode. Start @ "
<< ctime(&stime);
string controlfile = args->getCtrlfile();
string chtid = args->getChtid();
Runner siter;
siter.chtid = atoi(chtid.c_str());
siter.initInput(controlfile, "siter");
siter.initOutput();
siter.setupData();
siter.setupIDs();
siter.runmode1();
etime=time(0);
} else if (args->getMode() == "regnrun") {
time_t stime;
time_t etime;
stime=time(0);
BOOST_LOG_SEV(glg, info) << "Running dvm-dos-tem in regional mode. Start @ "
<< ctime(&stime);
string controlfile = args->getCtrlfile();
string runmode = args->getRegrunmode();
Runner regner;
regner.initInput(controlfile, runmode);
regner.initOutput();
regner.setupData();
regner.setupIDs();
if (runmode.compare("regner1")==0) {
BOOST_LOG_SEV(glg, debug) << "Running in regner1...(runmode2)";
regner.runmode2();
} else if (runmode.compare("regner2")==0){
BOOST_LOG_SEV(glg, debug) << "Running in regner2...(runmode3)";
regner.runmode3();
} else {
BOOST_LOG_SEV(glg, fatal) << "Invalid runmode...quitting.";
exit(-1);
}
etime = time(0);
BOOST_LOG_SEV(glg, info) << "Done running dvm-dos-tem regionally "
<< "(" << ctime(&etime) << ").";
BOOST_LOG_SEV(glg, info) << "total seconds: " << difftime(etime, stime);
}
return 0;
}
};
<commit_msg>Seems like a deadend. but it compiles and runs.<commit_after>/**
* TEM.cpp
* main program for running DVM-DOS-TEM
*
* It runs at 3 run-mods:
* (1) site-specific
* (2) regional - time series
* (3) regional - spatially (not yet available)
*
* Authors: Shuhua Yi - the original codes
* Fengming Yuan - re-designing and re-coding for (1) easily code managing;
* (2) java interface developing for calibration;
* (3) stand-alone application of TEM (java-c++)
* (4) inputs/outputs using netcdf format, have to be modified
* to fix memory-leaks
* (5) fix the snow/soil thermal/hydraulic algorithms
* (6) DVM coupled
* Tobey Carman - modifications and maintenance
* 1) update application entry point with boost command line arg. handling.
*
* Affilation: Spatial Ecology Lab, University of Alaska Fairbanks
*
* started: 11/01/2010
* last modified: 09/18/2012
*/
#include <string>
#include <iostream>
#include <fstream>
#include <sstream>
#include <ctime>
#include <cstdlib>
#include <exception>
#include <map>
#include <boost/signals2.hpp>
#include <boost/asio/signal_set.hpp>
#include <boost/thread.hpp>
#include <boost/thread/condition_variable.hpp>
#include <boost/thread/mutex.hpp>
#include <boost/shared_ptr.hpp>
#include <boost/bind.hpp>
#include <boost/asio.hpp>
#include "ArgHandler.h"
#include "TEMLogger.h"
#include "assembler/Runner.h"
BOOST_LOG_INLINE_GLOBAL_LOGGER_INIT(my_general_logger, severity_channel_logger_t) {
return severity_channel_logger_t(keywords::channel = "GENER");
}
BOOST_LOG_INLINE_GLOBAL_LOGGER_INIT(my_cal_logger, severity_channel_logger_t) {
return severity_channel_logger_t(keywords::channel = "CALIB");
}
boost::condition_variable cond;
bool pause_calibration = false;
boost::mutex mtex1;
//void calibration_ui_worker_thread() {
// severity_channel_logger_t& clg = my_cal_logger::get();
// BOOST_LOG_SEV(clg, info) << "Starting Calibration UI Worker Thread.";
// std::string input;
// if (std::getline(std::cin, input)) {
// std::cerr << "input [" << input.size() << "] '" << input << "'\n";
// } else {
// std::cerr << "getline() was unable to read a string from std::cin\n";
// }
//}
/** The signal handler that will pause the calibration on CTRL-C */
void stop_calibration(const boost::system::error_code& error,
/*int signal_number,*/
boost::shared_ptr< boost::asio::io_service > io_service){
severity_channel_logger_t& clg = my_cal_logger::get();
BOOST_LOG_SEV(clg, info) << "Caught signal number: " ;//<< signal_number;
BOOST_LOG_SEV(clg, info) << "Lock the mutex and set condition variable to true...";
boost::lock_guard<boost::mutex> lock(mtex1);
pause_calibration = true;
BOOST_LOG_SEV(clg, info) << "call the notify function for the condition variable...";
cond.notify_one();
//BOOST_LOG_SEV(clg, info) << "?? Remap signal handler so that next ctrl-C quits.";
//BOOST_LOG_SEV(clg, info) << "Pausing calibration while user modified values...";
// stop the service
// reset the service
// add a restart handler to the serivce
// run the service.
// std::string input;
// //while (input != "c" || input != "r") {
// if (std::getline(std::cin, input)) {
// std::cerr << "input [" << input.size() << "] '" << input << "'\n";
// } else {
// std::cerr << "getline() was unable to read a string from std::cin\n";
// }
//}
// switch (input) {
// case "c": // continue
// case "r": // reload values
// default: // ?? not sure how to get here w/ loop
// }
// BOOST_LOG_SEV(clg, info) << "Making another io_service used to quit completely.";
// boost::asio::io_service io_service_quitter;
// BOOST_LOG_SEV(clg, info) << "Defining a signal set that the io_service will listen for.";
// boost::asio::signal_set signals(io_service_quitter, SIGINT, SIGTERM);
//
// BOOST_LOG_SEV(clg, info) << "Define a callback that will run when the service "
// << "delivers one of the defined signals.";
// signals.async_wait(boost::bind(
// &boost::asio::io_service::stop, &io_service_quitter));
// BOOST_LOG_SEV(clg, info) << "start interactive input session?";
// // this is going to go off and sleep for 10 secs...
// BOOST_LOG_SEV(clg, info) << "Start a worker handle the user input.";
// boost::thread workerThread(&calibration_ui_worker_thread); // need to figure out how to pass args to this..
// BOOST_LOG_SEV(clg, info) << "Run the io_service_quitter in the calibratioin "
// << "worker thread, waiting asynchronously for a "
// << "signal to be captured/handled...";
// io_service_quitter.run();
}
/** A seperate thread to run the model. */
void calibration_worker_thread( boost::shared_ptr< boost::asio::io_service > io_service
/*ArgHandler* const args ? */){
// get handles for each of global loggers
severity_channel_logger_t& clg = my_cal_logger::get();
BOOST_LOG_SEV(clg, info) << "Starting Calibration Worker Thread.";
BOOST_LOG_SEV(clg, info) << "This should start the model in some mode, depending "
<< "on command line args and and crunch numbers....";
BOOST_LOG_SEV(clg, info) << "To simulate that I will loop over "
<< "cohorts, years, months with brief pause in each.";
for(int cohort = 0; cohort < 1; cohort++){
for(int yr = 0; yr < 100; ++yr){
BOOST_LOG_SEV(clg, info) << "Ask central io service if there has been a signal?";
BOOST_LOG_SEV(clg, info) << "If so, post a collect_userin handler to the service";
boost::unique_lock<boost::mutex> lock(mtex1);
while(!pause_calibration){
cond.wait(lock);
// boost::system::error_code ec;
//
// int number_handlers_run;
// number_handlers_run = io_service->poll_one(ec);
// BOOST_LOG_SEV(clg, info) << number_handlers_run << " handlers were run. Error code: " << ec;
for(int m = 0; m < 12; ++m) {
int sleeptime = 1;
BOOST_LOG_SEV(clg, info) << "(cht, yr, m):" << "(" << cohort <<", "<< yr <<", "<< m << ") "
<< "Thinking for " << sleeptime << " seconds...";
boost::posix_time::seconds workTime(sleeptime);
boost::this_thread::sleep(workTime);
} // end month loop
} // end while !pause loop
} // end yr loop
} // end cht loop
BOOST_LOG_SEV(clg, info) << "Done working. This worker thread is finished.";
}
ArgHandler* args = new ArgHandler();
int main(int argc, char* argv[]){
args->parse(argc, argv);
if (args->getHelp()){
args->showHelp();
return 0;
}
args->verify();
std::cout << "Setting up Logging...\n";
setup_console_log_sink();
set_log_severity_level(args->getLogLevel());
// get handles for each of global loggers...
severity_channel_logger_t& glg = my_general_logger::get();
severity_channel_logger_t& clg = my_cal_logger::get();
if (args->getCalibrationMode() == "on") {
BOOST_LOG_SEV(glg, info) << "Running in Calibration Mode";
BOOST_LOG_SEV(glg, info) << "Make shared pointers to an io_service and some work.";
boost::shared_ptr< boost::asio::io_service > io_service(
new boost::asio::io_service
);
boost::shared_ptr< boost::asio::io_service::work > work(
new boost::asio::io_service::work( *io_service )
);
//BOOST_LOG_SEV(glg, info) << "Make a condition variable for 'pause_calibration' and set it to false.";
BOOST_LOG_SEV(glg, info) << "Defining a signal set that the io_service will listen for.";
boost::asio::signal_set signals(*io_service, SIGINT, SIGTERM);
BOOST_LOG_SEV(glg, info) << "Define a callback that will run when the service "
<< "delivers of the defined signals This callback needs "
<< "to be able to 1) stop the worker thread 2) block until a) user input is ok or "
<< "b) another signal is recieved, in which case exit. In case (a), then "
<< "choose what to do based on user input.";
signals.async_wait( boost::bind(stop_calibration,
boost::asio::placeholders::error, io_service) ); // need to pass the io_service here...
BOOST_LOG_SEV(glg, info) << "Start a worker thread to run tem, passing in the pointer to the io_service.";
boost::thread workerThread( boost::bind(calibration_worker_thread, io_service) );
BOOST_LOG_SEV(glg, info) << "Run the io_service event loop in the main thread, waiting "
<< "for a signal to be captured/handled...";
io_service->run();
BOOST_LOG_SEV(glg, info) << "Exited from io_service.run()... "
<< "all handlers have been run and there is no more work.";
//BOOST_LOG_SEV(glg, info) << "Now join the workerThread to make sure it is finished, before exiting.";
//workerThread.join();
//BOOST_LOG_SEV(glg, info) << "Now join the workerThread to make sure it is finished, before exiting.";
//io_service->stop()
} else {
BOOST_LOG_SEV(glg, info) << "Running in extrapolation mode.";
setvbuf(stdout, NULL, _IONBF, 0);
setvbuf(stderr, NULL, _IONBF, 0);
if (args->getMode() == "siterun") {
time_t stime;
time_t etime;
stime=time(0);
BOOST_LOG_SEV(glg, info) << "Running dvm-dos-tem in siterun mode. Start @ "
<< ctime(&stime);
string controlfile = args->getCtrlfile();
string chtid = args->getChtid();
Runner siter;
siter.chtid = atoi(chtid.c_str());
siter.initInput(controlfile, "siter");
siter.initOutput();
siter.setupData();
siter.setupIDs();
siter.runmode1();
etime=time(0);
} else if (args->getMode() == "regnrun") {
time_t stime;
time_t etime;
stime=time(0);
BOOST_LOG_SEV(glg, info) << "Running dvm-dos-tem in regional mode. Start @ "
<< ctime(&stime);
string controlfile = args->getCtrlfile();
string runmode = args->getRegrunmode();
Runner regner;
regner.initInput(controlfile, runmode);
regner.initOutput();
regner.setupData();
regner.setupIDs();
if (runmode.compare("regner1")==0) {
BOOST_LOG_SEV(glg, debug) << "Running in regner1...(runmode2)";
regner.runmode2();
} else if (runmode.compare("regner2")==0){
BOOST_LOG_SEV(glg, debug) << "Running in regner2...(runmode3)";
regner.runmode3();
} else {
BOOST_LOG_SEV(glg, fatal) << "Invalid runmode...quitting.";
exit(-1);
}
etime = time(0);
BOOST_LOG_SEV(glg, info) << "Done running dvm-dos-tem regionally "
<< "(" << ctime(&etime) << ").";
BOOST_LOG_SEV(glg, info) << "total seconds: " << difftime(etime, stime);
}
return 0;
}
};
<|endoftext|> |
<commit_before>#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "oamlCommon.h"
#define SWAP16(x) (((x) & 0xff) << 8 | ((x) & 0xff00) >> 8)
#define SWAP32(x) (((x) & 0xff) << 24 | ((x) & 0xff00) << 8 | ((x) & 0xff0000) >> 8 | ((x) >> 24) & 0xff)
enum {
AIFF_ID = 0x46464941,
FORM_ID = 0x4D524F46,
COMM_ID = 0x4D4D4F43,
SSND_ID = 0x444E5353
};
typedef struct {
int id;
unsigned int size;
} aifHeader;
typedef struct {
int id;
unsigned int size;
int aiff;
} formHeader;
typedef struct {
unsigned int offset;
unsigned int blockSize;
} ssndHeader;
typedef struct {
unsigned short channels;
unsigned int sampleFrames;
unsigned short sampleSize;
unsigned char sampleRate80[10];
} __attribute__((packed)) commHeader;
aifFile::aifFile() {
fd = NULL;
channels = 0;
samplesPerSec = 0;
bitsPerSample = 0;
totalSamples = 0;
chunkSize = 0;
status = 0;
}
aifFile::~aifFile() {
if (fd != NULL) {
Close();
}
}
int aifFile::Open(const char *filename) {
ASSERT(filename != NULL);
if (fd != NULL) {
Close();
}
fd = fopen(filename, "rb");
if (fd == NULL) {
return -1;
}
while (status < 2) {
if (ReadChunk() == -1) {
return -1;
}
}
return 0;
}
int aifFile::ReadChunk() {
if (fd == NULL)
return -1;
// Read the common header for all aif chunks
aifHeader header;
if (fread(&header, 1, sizeof(aifHeader), fd) != sizeof(aifHeader)) {
fclose(fd);
fd = NULL;
return -1;
}
switch (header.id) {
case FORM_ID:
int aifId;
if (fread(&aifId, 1, sizeof(int), fd) != sizeof(int))
return -1;
// Check aifId signature for valid file
if (aifId != AIFF_ID)
return -1;
break;
case COMM_ID:
commHeader comm;
if (fread(&comm, 1, sizeof(commHeader), fd) != sizeof(commHeader))
return -1;
channels = SWAP16(comm.channels);
samplesPerSec = 44100;
bitsPerSample = SWAP16(comm.sampleSize);
status = 1;
break;
case SSND_ID:
ssndHeader ssnd;
if (fread(&ssnd, 1, sizeof(ssndHeader), fd) != sizeof(ssndHeader))
return -1;
if (ssnd.offset) {
fseek(fd, SWAP32(ssnd.offset), SEEK_CUR);
}
chunkSize = SWAP32(header.size) - 8;
totalSamples = chunkSize / (bitsPerSample/8);
status = 2;
break;
default:
fseek(fd, SWAP32(header.size), SEEK_CUR);
break;
}
return 0;
}
int aifFile::Read(ByteBuffer *buffer, int size) {
unsigned char buf[4096];
if (fd == NULL)
return -1;
int bytesRead = 0;
while (size > 0) {
// Are we inside a data chunk?
if (status == 2) {
// Let's keep reading data!
int bytes = size < 4096 ? size : 4096;
if (chunkSize < bytes)
bytes = chunkSize;
int ret = fread(buf, 1, bytes, fd);
if (ret == 0) {
status = 3;
break;
} else {
chunkSize-= ret;
if (bitsPerSample == 16) {
for (int i=0; i<ret; i+= 2) {
unsigned char tmp;
tmp = buf[i+0];
buf[i+0] = buf[i+1];
buf[i+1] = tmp;
}
}
buffer->putBytes(buf, ret);
bytesRead+= ret;
size-= ret;
}
} else {
if (ReadChunk() == -1)
return -1;
}
}
return bytesRead;
}
void aifFile::WriteToFile(const char *filename, ByteBuffer *buffer, int channels, unsigned int sampleRate, int bytesPerSample) {
}
void aifFile::Close() {
if (fd != NULL) {
fclose(fd);
fd = NULL;
}
}
<commit_msg>Improvements on aif code, added support for 24bit files<commit_after>#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>
#include "oamlCommon.h"
#define SWAP16(x) (((x) & 0xff) << 8 | ((x) & 0xff00) >> 8)
#define SWAP32(x) (((x) & 0xff) << 24 | ((x) & 0xff00) << 8 | ((x) & 0xff0000) >> 8 | ((x) >> 24) & 0xff)
enum {
AIFF_ID = 0x46464941,
FORM_ID = 0x4D524F46,
COMM_ID = 0x4D4D4F43,
SSND_ID = 0x444E5353
};
#ifdef _MSC_VER
#pragma pack(push,1)
#endif
typedef struct {
int id;
unsigned int size;
} __attribute__((packed)) aifHeader;
typedef struct {
int id;
unsigned int size;
int aiff;
} __attribute__((packed)) formHeader;
typedef struct {
unsigned int offset;
unsigned int blockSize;
} __attribute__((packed)) ssndHeader;
typedef struct {
unsigned short channels;
unsigned int sampleFrames;
unsigned short sampleSize;
unsigned char sampleRate80[10];
} __attribute__((packed)) commHeader;
#ifdef _MSC_VER
#pragma pack(pop)
#endif
aifFile::aifFile() {
fd = NULL;
channels = 0;
samplesPerSec = 0;
bitsPerSample = 0;
totalSamples = 0;
chunkSize = 0;
status = 0;
}
aifFile::~aifFile() {
if (fd != NULL) {
Close();
}
}
int aifFile::Open(const char *filename) {
ASSERT(filename != NULL);
if (fd != NULL) {
Close();
}
fd = fopen(filename, "rb");
if (fd == NULL) {
return -1;
}
while (status < 2) {
if (ReadChunk() == -1) {
return -1;
}
}
return 0;
}
/*
* C O N V E R T F R O M I E E E E X T E N D E D
*/
/*
* Copyright (C) 1988-1991 Apple Computer, Inc.
* All rights reserved.
*
* Machine-independent I/O routines for IEEE floating-point numbers.
*
* NaN's and infinities are converted to HUGE_VAL or HUGE, which
* happens to be infinity on IEEE machines. Unfortunately, it is
* impossible to preserve NaN's in a machine-independent way.
* Infinities are, however, preserved on IEEE machines.
*
* These routines have been tested on the following machines:
* Apple Macintosh, MPW 3.1 C compiler
* Apple Macintosh, THINK C compiler
* Silicon Graphics IRIS, MIPS compiler
* Cray X/MP and Y/MP
* Digital Equipment VAX
*
*
* Implemented by Malcolm Slaney and Ken Turkowski.
*
* Malcolm Slaney contributions during 1988-1990 include big- and little-
* endian file I/O, conversion to and from Motorola's extended 80-bit
* floating-point format, and conversions to and from IEEE single-
* precision floating-point format.
*
* In 1991, Ken Turkowski implemented the conversions to and from
* IEEE double-precision format, added more precision to the extended
* conversions, and accommodated conversions involving +/- infinity,
* NaN's, and denormalized numbers.
*/
#ifndef HUGE_VAL
# define HUGE_VAL HUGE
#endif /*HUGE_VAL*/
# define UnsignedToFloat(u) (((double)((long)(u - 2147483647L - 1))) + 2147483648.0)
/****************************************************************
* Extended precision IEEE floating-point conversion routine.
****************************************************************/
double ConvertFromIeeeExtended(unsigned char *bytes) {
double f;
int expon;
unsigned long hiMant, loMant;
expon = ((bytes[0] & 0x7F) << 8) | (bytes[1] & 0xFF);
hiMant = ((unsigned long)(bytes[2] & 0xFF) << 24)
| ((unsigned long)(bytes[3] & 0xFF) << 16)
| ((unsigned long)(bytes[4] & 0xFF) << 8)
| ((unsigned long)(bytes[5] & 0xFF));
loMant = ((unsigned long)(bytes[6] & 0xFF) << 24)
| ((unsigned long)(bytes[7] & 0xFF) << 16)
| ((unsigned long)(bytes[8] & 0xFF) << 8)
| ((unsigned long)(bytes[9] & 0xFF));
if (expon == 0 && hiMant == 0 && loMant == 0) {
f = 0;
} else {
if (expon == 0x7FFF) { /* Infinity or NaN */
f = HUGE_VAL;
} else {
expon -= 16383;
f = ldexp(UnsignedToFloat(hiMant), expon-=31);
f += ldexp(UnsignedToFloat(loMant), expon-=32);
}
}
if (bytes[0] & 0x80)
return -f;
else
return f;
}
int aifFile::ReadChunk() {
if (fd == NULL)
return -1;
// Read the common header for all aif chunks
aifHeader header;
if (fread(&header, 1, sizeof(aifHeader), fd) != sizeof(aifHeader)) {
fclose(fd);
fd = NULL;
return -1;
}
switch (header.id) {
case FORM_ID:
int aifId;
if (fread(&aifId, 1, sizeof(int), fd) != sizeof(int))
return -1;
// Check aifId signature for valid file
if (aifId != AIFF_ID)
return -1;
break;
case COMM_ID:
commHeader comm;
if (fread(&comm, 1, sizeof(commHeader), fd) != sizeof(commHeader))
return -1;
channels = SWAP16(comm.channels);
samplesPerSec = (int)ConvertFromIeeeExtended(comm.sampleRate80);
bitsPerSample = SWAP16(comm.sampleSize);
status = 1;
break;
case SSND_ID:
ssndHeader ssnd;
if (fread(&ssnd, 1, sizeof(ssndHeader), fd) != sizeof(ssndHeader))
return -1;
if (ssnd.offset) {
fseek(fd, SWAP32(ssnd.offset), SEEK_CUR);
}
chunkSize = SWAP32(header.size) - 8;
totalSamples = chunkSize / (bitsPerSample/8);
status = 2;
break;
default:
fseek(fd, SWAP32(header.size), SEEK_CUR);
break;
}
return 0;
}
int aifFile::Read(ByteBuffer *buffer, int size) {
int bufSize = 4096*GetBytesPerSample();
unsigned char buf[4096*4];
if (fd == NULL)
return -1;
int bytesRead = 0;
while (size > 0) {
// Are we inside a ssnd chunk?
if (status == 2) {
// Let's keep reading data!
int bytes = size < bufSize ? size : bufSize;
if (chunkSize < bytes)
bytes = chunkSize;
int ret = fread(buf, 1, bytes, fd);
if (ret == 0) {
status = 3;
break;
} else {
chunkSize-= ret;
if (bitsPerSample == 16) {
unsigned short *sbuf = (unsigned short *)buf;
for (int i=0; i<ret; i+= 2) {
sbuf[i] = SWAP16(sbuf[i]);
}
} else
if (bitsPerSample == 24) {
for (int i=0; i<ret; i+= 3) {
unsigned char tmp;
tmp = buf[i+0];
buf[i+0] = buf[i+2];
buf[i+2] = tmp;
}
}
buffer->putBytes(buf, ret);
bytesRead+= ret;
size-= ret;
}
} else {
if (ReadChunk() == -1)
return -1;
}
}
return bytesRead;
}
void aifFile::WriteToFile(const char *filename, ByteBuffer *buffer, int channels, unsigned int sampleRate, int bytesPerSample) {
}
void aifFile::Close() {
if (fd != NULL) {
fclose(fd);
fd = NULL;
}
}
<|endoftext|> |
<commit_before>/*
Copyright (c) 2008-2014, Arvid Norberg
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in
the documentation and/or other materials provided with the distribution.
* Neither the name of the author nor the names of its
contributors may be used to endorse or promote products derived
from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
*/
#include "test.hpp"
#include "setup_transfer.hpp"
#include "web_seed_suite.hpp"
#include "libtorrent/create_torrent.hpp"
using namespace libtorrent;
const int proxy = libtorrent::proxy_settings::none;
//static unsigned char random_byte()
//{ return std::rand() & 0xff; }
int test_main()
{
using namespace libtorrent;
error_code ec;
file_storage fs;
int piece_size = 0x4000;
char random_data[16000];
std::generate(random_data, random_data + sizeof(random_data), random_byte);
file f("test_file", file::write_only, ec);
if (ec)
{
fprintf(stderr, "failed to create file \"test_file\": (%d) %s\n"
, ec.value(), ec.message().c_str());
return 1;
}
file::iovec_t b = { random_data, size_t(16000)};
f.writev(0, &b, 1, ec);
fs.add_file("test_file", 16000);
int port = start_web_server();
// generate a torrent with pad files to make sure they
// are not requested web seeds
libtorrent::create_torrent t(fs, piece_size, 0x4000);
char tmp[512];
snprintf(tmp, sizeof(tmp), "http://127.0.0.1:%d/redirect", port);
t.add_url_seed(tmp);
// calculate the hash for all pieces
set_piece_hashes(t, ".", ec);
if (ec)
{
fprintf(stderr, "error creating hashes for test torrent: %s\n"
, ec.message().c_str());
TEST_CHECK(false);
return 0;
}
std::vector<char> buf;
bencode(std::back_inserter(buf), t.generate());
boost::intrusive_ptr<torrent_info> torrent_file(new torrent_info(&buf[0]
, buf.size(), ec));
{
session ses(fingerprint(" ", 0,0,0,0), 0);
session_settings settings;
settings.max_queued_disk_bytes = 256 * 1024;
ses.set_settings(settings);
ses.set_alert_mask(~(alert::progress_notification | alert::stats_notification));
// disable keep-alive because otherwise the test will choke on seeing
// the disconnect (from the redirect)
test_transfer(ses, torrent_file, 0, 0, "http", true, false, false, false);
}
stop_web_server();
return 0;
}
<commit_msg>fix warning<commit_after>/*
Copyright (c) 2008-2014, Arvid Norberg
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in
the documentation and/or other materials provided with the distribution.
* Neither the name of the author nor the names of its
contributors may be used to endorse or promote products derived
from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
*/
#include "test.hpp"
#include "setup_transfer.hpp"
#include "web_seed_suite.hpp"
#include "libtorrent/create_torrent.hpp"
using namespace libtorrent;
int test_main()
{
using namespace libtorrent;
error_code ec;
file_storage fs;
int piece_size = 0x4000;
char random_data[16000];
std::generate(random_data, random_data + sizeof(random_data), random_byte);
file f("test_file", file::write_only, ec);
if (ec)
{
fprintf(stderr, "failed to create file \"test_file\": (%d) %s\n"
, ec.value(), ec.message().c_str());
return 1;
}
file::iovec_t b = { random_data, size_t(16000)};
f.writev(0, &b, 1, ec);
fs.add_file("test_file", 16000);
int port = start_web_server();
// generate a torrent with pad files to make sure they
// are not requested web seeds
libtorrent::create_torrent t(fs, piece_size, 0x4000);
char tmp[512];
snprintf(tmp, sizeof(tmp), "http://127.0.0.1:%d/redirect", port);
t.add_url_seed(tmp);
// calculate the hash for all pieces
set_piece_hashes(t, ".", ec);
if (ec)
{
fprintf(stderr, "error creating hashes for test torrent: %s\n"
, ec.message().c_str());
TEST_CHECK(false);
return 0;
}
std::vector<char> buf;
bencode(std::back_inserter(buf), t.generate());
boost::intrusive_ptr<torrent_info> torrent_file(new torrent_info(&buf[0]
, buf.size(), ec));
{
session ses(fingerprint(" ", 0,0,0,0), 0);
session_settings settings;
settings.max_queued_disk_bytes = 256 * 1024;
ses.set_settings(settings);
ses.set_alert_mask(~(alert::progress_notification | alert::stats_notification));
// disable keep-alive because otherwise the test will choke on seeing
// the disconnect (from the redirect)
test_transfer(ses, torrent_file, 0, 0, "http", true, false, false, false);
}
stop_web_server();
return 0;
}
<|endoftext|> |
<commit_before>
// -todo: make sizeBytes() static function
// -todo: make swapIdxPair function
// -todo: copy in CncrBlkLst from simdb
// todo: take out version from CncrLst
// todo: transition CncrLst to be without any stack variables - just use the functions and pass them addresses?
// todo: make default constructor
// todo: make constructor that takes a capacity
// todo: make allocation function
// todo: fill out BlkMeta struct
// todo: make put()
// todo: make operator[]
// todo: make operator()
// todo: make del()
#pragma once
#if !defined(__FLAT_LOCKFREE_MAP_HEADER_GUARD_HPP__)
#include <cstdint>
#include <atomic>
struct flf_map
{
class CncrLst
{
// Copied from simdb 2017.10.25
// Internally this is an array of indices that makes a linked list
// Externally indices can be gotten atomically and given back atomically
// | This is used to get free indices one at a time, and give back in-use indices one at a time
// Uses the first 8 bytes that would normally store sizeBytes as the 64 bits of memory for the Head structure
// Aligns the head on a 64 bytes boundary with the rest of the memory on a separate 64 byte boudary. This puts them on separate cache lines which should eliminate false sharing between cores when atomicallyaccessing the Head union (which will happen quite a bit)
public:
//using u32 = uint32_t;
//using u64 = uint64_t;
//using au64 = std::atomic<u64>;
using ListVec = lava_vec<u32>;
//union Head
//{
// struct { u32 ver; u32 idx; }; // ver is version, idx is index
// u64 asInt;
//};
union Head
{
u8 dblCachePad[128];
u32 idx; // idx is index
};
static const u32 LIST_END = 0xFFFFFFFF;
static const u32 NXT_VER_SPECIAL = 0xFFFFFFFF;
private:
//ListVec s_lv;
//au64* s_h;
public:
//static u64 sizeBytes(u32 size) { return ListVec::sizeBytes(size) + 128; } // an extra 128 bytes so that Head can be placed
static u64 sizeBytes(u32 size) { return sizeof(u32) + 128; } // an extra 128 bytes so that Head can be placed
static u32 incVersion(u32 v) { return v==NXT_VER_SPECIAL? 1 : v+1; }
CncrLst(){}
CncrLst(void* addr, void* headAddr, u32 size, bool owner=true) // this constructor is for when the memory is owned an needs to be initialized
{ // separate out initialization and let it be done explicitly in the simdb constructor?
u64 addrRem = (u64)headAddr % 64;
u64 alignAddr = (u64)headAddr + (64-addrRem);
assert( alignAddr % 64 == 0 );
au64* hd = (au64*)alignAddr;
u32* lstAddr = (u32*)((u64)alignAddr+64);
//new (&s_lv) ListVec(listAddr, size, owner);
// give the list initial values here
//u32* lstAddr =
//if(owner){
for(u32 i=0; i<(size-1); ++i){ lstAddr[i] = i+1; }
lstAddr[size-1] = LIST_END;
//((Head*)s_h)->idx = 0;
//((Head*)s_h)->ver = 0;
//}
}
u32 nxt() // moves forward in the list and return the previous index
{
Head curHead, nxtHead;
curHead.asInt = s_h->load();
do{
if(curHead.idx==LIST_END){return LIST_END;}
nxtHead.idx = s_lv[curHead.idx];
nxtHead.ver = curHead.ver==NXT_VER_SPECIAL? 1 : curHead.ver+1;
}while( !s_h->compare_exchange_strong(curHead.asInt, nxtHead.asInt) );
return curHead.idx;
}
u32 free(u32 idx) // not thread safe when reading from the list, but it doesn't matter because you shouldn't be reading while freeing anyway, since the CncrHsh will already have the index taken out and the free will only be triggered after the last reader has read from it
{
Head curHead, nxtHead; u32 retIdx;
curHead.asInt = s_h->load();
do{
retIdx = s_lv[idx] = curHead.idx;
nxtHead.idx = idx;
nxtHead.ver = curHead.ver + 1;
}while( !s_h->compare_exchange_strong(curHead.asInt, nxtHead.asInt) );
return retIdx;
}
u32 free(u32 st, u32 en) // not thread safe when reading from the list, but it doesn't matter because you shouldn't be reading while freeing anyway, since the CncrHsh will already have the index taken out and the free will only be triggered after the last reader has read from it
{
Head curHead, nxtHead; u32 retIdx;
curHead.asInt = s_h->load();
do{
retIdx = s_lv[en] = curHead.idx;
nxtHead.idx = st;
nxtHead.ver = curHead.ver + 1;
}while( !s_h->compare_exchange_strong(curHead.asInt, nxtHead.asInt) );
return retIdx;
}
auto count() const -> u32 { return ((Head*)s_h)->ver; }
auto idx() const -> u32
{
Head h;
h.asInt = s_h->load();
return h.idx;
}
auto list() -> ListVec const* { return &s_lv; } // not thread safe
u32 lnkCnt() // not thread safe
{
u32 cnt = 0;
u32 curIdx = idx();
while( curIdx != LIST_END ){
curIdx = s_lv[curIdx];
++cnt;
}
return cnt;
}
auto head() -> Head* { return (Head*)s_h; }
};
using u8 = uint8_t;
using u32 = uint32_t;
using u64 = uint64_t;
using au32 = std::atomic<uint32_t>;
using au64 = std::atomic<uint64_t>;
using Key = u64;
using Value = u64;
using Hash = std::hash<Key>;
using LstIdx = u32;
static const u32 EMPTY = 0x00FFFFFF; // max value of 2^24 to set all 24 bits of the value index
static const u32 DELETED = 0x00FFFFFE; // one less than the max value above
static const u32 SPECIAL_VALUE_START = DELETED; // comparing to this is more clear than comparing to DELETED
static const u32 LIST_END = 0xFFFFFFFF;
//static const u32 NXT_VER_SPECIAL = 0xFFFFFFFF;
struct Idx {
u32 readers : 8;
u32 val_idx : 24;
};
union IdxPair {
struct { Idx first; Idx second; };
u64 asInt;
};
struct Header {
// first 8 bytes - two 1 bytes characters that should equal 'lm' for lockless map
u64 typeChar1 : 8;
u64 typeChar2 : 8;
u64 sizeBytes : 48;
// next 8 bytes keep track of the size of the values and number inserted - from that and the sizeBytes, capacity can be inferred
u64 size : 32; // this could be only 24 bits since that is the max index
u64 valSizeBytes : 32;
// next 4 bytes is the current block list
u32 curBlk;
};
struct BlkMeta {
};
u8* m_mem = nullptr; // single pointer is all that ends up on the stack
void make_list(void* addr, u32* head, u32 size) // this constructor is for when the memory is owned an needs to be initialized
{ // separate out initialization and let it be done explicitly in the simdb constructor?
u32* lstAddr = (u32*)addr;
for(u32 i=0; i<(size-1); ++i){ lstAddr[i] = i+1; }
lstAddr[size-1] = LIST_END;
}
u32 nxt(au32* head, u32* lst) // moves forward in the list and return the previous index
{
u32 curHead, nxtHead;
curHead = head->load();
do{
if(curHead==LIST_END){return LIST_END;}
nxtHead = lst[curHead];
}while( !head->compare_exchange_strong(curHead, nxtHead) );
return curHead;
}
u32 free(au32* head, u32* lst, u32 idx) // not thread safe when reading from the list, but it doesn't matter because you shouldn't be reading while freeing anyway, since the CncrHsh will already have the index taken out and the free will only be triggered after the last reader has read from it
{
u32 curHead, nxtHead, retIdx;
curHead = head->load();
do{
retIdx = lst[idx] = curHead;
nxtHead = idx;
}while( !head->compare_exchange_strong(curHead, nxtHead) );
return retIdx;
}
u32 free(au32* head, u32* lst, u32 st, u32 en) // not thread safe when reading from the list, but it doesn't matter because you shouldn't be reading while freeing anyway, since the CncrHsh will already have the index taken out and the free will only be triggered after the last reader has read from it
{ // todo: possibly take this out, there might not be an oportunity to free a linked list of indices instead of a single index
u32 curHead, nxtHead, retIdx;
curHead = head->load();
do{
retIdx = lst[en] = curHead;
nxtHead = st;
}while( !head->compare_exchange_strong(curHead, nxtHead) );
return retIdx;
}
//u32 count(au32* head) const { return ((Header*)head)->cap; }
u64 slotByteOffset(u64 idx){ return sizeof(Header) + idx*sizeof(IdxPair); }
Idx* slotPtr(u64 idx){ return (Idx*)(m_mem + slotByteOffset(idx)); }
bool incReaders(void* oldIp, IdxPair* newIp = nullptr)
{
au64* atmIncPtr = (au64*)(oldIp);
Idx idxs[2];
u64 oldVal, newVal;
do{
oldVal = atmIncPtr->load(std::memory_order::memory_order_seq_cst); // get the value of both Idx structs atomically
*((u64*)(idxs)) = oldVal; // default memory order for now
if(idxs[0].val_idx < SPECIAL_VALUE_START &&
idxs[1].val_idx < SPECIAL_VALUE_START ){
idxs[0].readers += 1; // increment the reader values if neithe of the indices have special values like EMPTY or DELETED
idxs[1].readers += 1;
}else{
return false;
}
newVal = *((u64*)(idxs));
}while( atmIncPtr->compare_exchange_strong(oldVal, newVal) ); // store it back if the pair of indices hasn't changed - this is not an ABA problem because we aren't relying on the values at these indices yet, we are just incrementing the readers so that 1. the data is not deleted at these indices and 2. the indices themselves can't be reused until we decrement the readers
if(newIp) newIp->asInt = newVal;
return true; // the readers were successfully incremented, but we need to return the indices that were swapped since we read them atomically
}
bool swapIdxPair(IdxPair* ip, IdxPair* prevIp = nullptr)
{
using namespace std;
au64* aip = (au64*)ip;
IdxPair oldIp;
oldIp.asInt = aip->load();
IdxPair nxtIp;
nxtIp.first = oldIp.second;
nxtIp.second = oldIp.first;
bool ok = aip->compare_exchange_strong( oldIp.asInt, nxtIp.asInt, std::memory_order_seq_cst);
if(prevIp){ *prevIp = oldIp; }
return ok;
}
u64 hashKey(Key const& k)
{
return Hash()(k); // instances a hash function object and calls operator()
}
static u64 sizeBytes(u64 capacity)
{
u64 szPerCap = sizeof(BlkMeta) + sizeof(Idx) + sizeof(Key) + sizeof(Value) + sizeof(LstIdx);
return sizeof(Header) + capacity*szPerCap;
}
};
#endif
//
//nxtHead.ver = curHead.ver + 1;
//au32* head =
//nxtHead.ver = curHead.ver==NXT_VER_SPECIAL? 1 : curHead.ver+1;
//nxtIp.asInt = aip->load();
//Idx tmp = nxtIp.first;
//bool incTwoIdxReaders(u64 idx, IdxPair* newIp = nullptr)
//bool incIdxPairReaders(u64 idx, IdxPair* newIp = nullptr)
//
// u8* firstIdxPtr =
// Idx* idxPtr = (Idx*)(m_mem + idx*sizeof(Idx)); // it is crucial and fundamental that sizeof(Idx) needs to be 4 bytes so that two of them can be swapped even if unaligned, but this should be more correct and clear
//au64* atmIncPtr = (au64*)(m_mem + idx*sizeof(Idx)); // it is crucial and fundamental that sizeof(Idx) needs to be 4 bytes so that two of them can be swapped even if unaligned, but this should be more correct and clear
//IdxPair ip;
//ip.asInt = newVal;
<commit_msg>further functions from CncrList rounded out<commit_after>
// -todo: make sizeBytes() static function
// -todo: make swapIdxPair function
// -todo: copy in CncrBlkLst from simdb
// todo: take out version from CncrLst
// todo: transition CncrLst to be without any stack variables - just use the functions and pass them addresses?
// todo: make default constructor
// todo: make constructor that takes a capacity
// todo: make allocation function
// todo: fill out BlkMeta struct
// todo: make put()
// todo: make operator[]
// todo: make operator()
// todo: make del()
#pragma once
#if !defined(__FLAT_LOCKFREE_MAP_HEADER_GUARD_HPP__)
#include <cstdint>
#include <atomic>
struct flf_map
{
using u8 = uint8_t;
using u32 = uint32_t;
using u64 = uint64_t;
using au32 = std::atomic<uint32_t>;
using au64 = std::atomic<uint64_t>;
using Key = u64;
using Value = u64;
using Hash = std::hash<Key>;
using LstIdx = u32;
static const u32 EMPTY = 0x00FFFFFF; // max value of 2^24 to set all 24 bits of the value index
static const u32 DELETED = 0x00FFFFFE; // one less than the max value above
static const u32 SPECIAL_VALUE_START = DELETED; // comparing to this is more clear than comparing to DELETED
static const u32 LIST_END = 0xFFFFFFFF;
//static const u32 NXT_VER_SPECIAL = 0xFFFFFFFF;
struct Idx {
u32 readers : 8;
u32 val_idx : 24;
};
union IdxPair {
struct { Idx first; Idx second; };
u64 asInt;
};
union LstHead
{
u32 idx;
u32 count;
};
struct Header {
// first 8 bytes - two 1 bytes characters that should equal 'lm' for lockless map
u64 typeChar1 : 8;
u64 typeChar2 : 8;
u64 sizeBytes : 48;
// next 8 bytes keep track of the size of the values and number inserted - from that and the sizeBytes, capacity can be inferred
u64 size : 32; // this could be only 24 bits since that is the max index
u64 valSizeBytes : 32;
// next 4 bytes is the current block list
u32 lstHd; // lstHd is list head
};
struct BlkMeta {
};
u8* m_mem = nullptr; // single pointer is all that ends up on the stack
// concurrent list functions
void make_list(void* addr, u32* head, u32 size) // this constructor is for when the memory is owned an needs to be initialized
{ // separate out initialization and let it be done explicitly in the simdb constructor?
u32* lstAddr = (u32*)addr;
for(u32 i=0; i<(size-1); ++i){ lstAddr[i] = i+1; }
lstAddr[size-1] = LIST_END;
}
u32 nxt(au32* head, u32* lst) // moves forward in the list and return the previous index
{
u32 curHead, nxtHead;
curHead = head->load();
do{
if(curHead==LIST_END){return LIST_END;}
nxtHead = lst[curHead];
}while( !head->compare_exchange_strong(curHead, nxtHead) );
return curHead;
}
u32 free(au32* head, u32* lst, u32 idx) // not thread safe when reading from the list, but it doesn't matter because you shouldn't be reading while freeing anyway, since the CncrHsh will already have the index taken out and the free will only be triggered after the last reader has read from it
{
u32 curHead, nxtHead, retIdx;
curHead = head->load();
do{
retIdx = lst[idx] = curHead;
nxtHead = idx;
}while( !head->compare_exchange_strong(curHead, nxtHead) );
return retIdx;
}
u32 free(au32* head, u32* lst, u32 st, u32 en) // not thread safe when reading from the list, but it doesn't matter because you shouldn't be reading while freeing anyway, since the CncrHsh will already have the index taken out and the free will only be triggered after the last reader has read from it
{ // todo: possibly take this out, there might not be an oportunity to free a linked list of indices instead of a single index
u32 curHead, nxtHead, retIdx;
curHead = head->load();
do{
retIdx = lst[en] = curHead;
nxtHead = st;
}while( !head->compare_exchange_strong(curHead, nxtHead) );
return retIdx;
}
u32 idx(au32* head) const { return head->load(); }
u32* head(){ return &(((Header*)m_mem)->lstHd); }
//u32 count(au32* head) const { return ((Header*)head)->cap; }
u64 slotByteOffset(u64 idx){ return sizeof(Header) + idx*sizeof(IdxPair); }
Idx* slotPtr(u64 idx){ return (Idx*)(m_mem + slotByteOffset(idx)); }
bool incReaders(void* oldIp, IdxPair* newIp = nullptr)
{
au64* atmIncPtr = (au64*)(oldIp);
Idx idxs[2];
u64 oldVal, newVal;
do{
oldVal = atmIncPtr->load(std::memory_order::memory_order_seq_cst); // get the value of both Idx structs atomically
*((u64*)(idxs)) = oldVal; // default memory order for now
if(idxs[0].val_idx < SPECIAL_VALUE_START &&
idxs[1].val_idx < SPECIAL_VALUE_START ){
idxs[0].readers += 1; // increment the reader values if neithe of the indices have special values like EMPTY or DELETED
idxs[1].readers += 1;
}else{
return false;
}
newVal = *((u64*)(idxs));
}while( atmIncPtr->compare_exchange_strong(oldVal, newVal) ); // store it back if the pair of indices hasn't changed - this is not an ABA problem because we aren't relying on the values at these indices yet, we are just incrementing the readers so that 1. the data is not deleted at these indices and 2. the indices themselves can't be reused until we decrement the readers
if(newIp) newIp->asInt = newVal;
return true; // the readers were successfully incremented, but we need to return the indices that were swapped since we read them atomically
}
bool swapIdxPair(IdxPair* ip, IdxPair* prevIp = nullptr)
{
using namespace std;
au64* aip = (au64*)ip;
IdxPair oldIp;
oldIp.asInt = aip->load();
IdxPair nxtIp;
nxtIp.first = oldIp.second;
nxtIp.second = oldIp.first;
bool ok = aip->compare_exchange_strong( oldIp.asInt, nxtIp.asInt, std::memory_order_seq_cst);
if(prevIp){ *prevIp = oldIp; }
return ok;
}
u64 hashKey(Key const& k)
{
return Hash()(k); // instances a hash function object and calls operator()
}
static u64 sizeBytes(u64 capacity)
{
u64 szPerCap = sizeof(BlkMeta) + sizeof(Idx) + sizeof(Key) + sizeof(Value) + sizeof(LstIdx);
return sizeof(Header) + capacity*szPerCap;
}
};
#endif
//class CncrLst
//{
// // Copied from simdb 2017.10.25
// // Internally this is an array of indices that makes a linked list
// // Externally indices can be gotten atomically and given back atomically
// // | This is used to get free indices one at a time, and give back in-use indices one at a time
// // Uses the first 8 bytes that would normally store sizeBytes as the 64 bits of memory for the Head structure
// // Aligns the head on a 64 bytes boundary with the rest of the memory on a separate 64 byte boudary. This puts them on separate cache lines which should eliminate false sharing between cores when atomicallyaccessing the Head union (which will happen quite a bit)
//public:
// //using u32 = uint32_t;
// //using u64 = uint64_t;
// //using au64 = std::atomic<u64>;
// using ListVec = lava_vec<u32>;
//
// //union Head
// //{
// // struct { u32 ver; u32 idx; }; // ver is version, idx is index
// // u64 asInt;
// //};
// union Head
// {
// u8 dblCachePad[128];
// u32 idx; // idx is index
// };
//
// static const u32 LIST_END = 0xFFFFFFFF;
// static const u32 NXT_VER_SPECIAL = 0xFFFFFFFF;
//
//private:
// //ListVec s_lv;
// //au64* s_h;
//
//public:
// //static u64 sizeBytes(u32 size) { return ListVec::sizeBytes(size) + 128; } // an extra 128 bytes so that Head can be placed
// static u64 sizeBytes(u32 size) { return sizeof(u32) + 128; } // an extra 128 bytes so that Head can be placed
// static u32 incVersion(u32 v) { return v==NXT_VER_SPECIAL? 1 : v+1; }
//
// CncrLst(){}
// CncrLst(void* addr, void* headAddr, u32 size, bool owner=true) // this constructor is for when the memory is owned an needs to be initialized
// { // separate out initialization and let it be done explicitly in the simdb constructor?
// u64 addrRem = (u64)headAddr % 64;
// u64 alignAddr = (u64)headAddr + (64-addrRem);
// assert( alignAddr % 64 == 0 );
// au64* hd = (au64*)alignAddr;
// u32* lstAddr = (u32*)((u64)alignAddr+64);
// //new (&s_lv) ListVec(listAddr, size, owner);
//
// // give the list initial values here
// //u32* lstAddr =
// //if(owner){
// for(u32 i=0; i<(size-1); ++i){ lstAddr[i] = i+1; }
// lstAddr[size-1] = LIST_END;
//
// //((Head*)s_h)->idx = 0;
// //((Head*)s_h)->ver = 0;
// //}
// }
//
// u32 nxt() // moves forward in the list and return the previous index
// {
// Head curHead, nxtHead;
// curHead.asInt = s_h->load();
// do{
// if(curHead.idx==LIST_END){return LIST_END;}
//
// nxtHead.idx = s_lv[curHead.idx];
// nxtHead.ver = curHead.ver==NXT_VER_SPECIAL? 1 : curHead.ver+1;
// }while( !s_h->compare_exchange_strong(curHead.asInt, nxtHead.asInt) );
//
// return curHead.idx;
// }
// u32 free(u32 idx) // not thread safe when reading from the list, but it doesn't matter because you shouldn't be reading while freeing anyway, since the CncrHsh will already have the index taken out and the free will only be triggered after the last reader has read from it
// {
// Head curHead, nxtHead; u32 retIdx;
// curHead.asInt = s_h->load();
// do{
// retIdx = s_lv[idx] = curHead.idx;
// nxtHead.idx = idx;
// nxtHead.ver = curHead.ver + 1;
// }while( !s_h->compare_exchange_strong(curHead.asInt, nxtHead.asInt) );
//
// return retIdx;
// }
// u32 free(u32 st, u32 en) // not thread safe when reading from the list, but it doesn't matter because you shouldn't be reading while freeing anyway, since the CncrHsh will already have the index taken out and the free will only be triggered after the last reader has read from it
// {
// Head curHead, nxtHead; u32 retIdx;
// curHead.asInt = s_h->load();
// do{
// retIdx = s_lv[en] = curHead.idx;
// nxtHead.idx = st;
// nxtHead.ver = curHead.ver + 1;
// }while( !s_h->compare_exchange_strong(curHead.asInt, nxtHead.asInt) );
//
// return retIdx;
// }
// auto count() const -> u32 { return ((Head*)s_h)->ver; }
// auto idx() const -> u32
// {
// Head h;
// h.asInt = s_h->load();
// return h.idx;
// }
// auto list() -> ListVec const* { return &s_lv; } // not thread safe
// u32 lnkCnt() // not thread safe
// {
// u32 cnt = 0;
// u32 curIdx = idx();
// while( curIdx != LIST_END ){
// curIdx = s_lv[curIdx];
// ++cnt;
// }
// return cnt;
// }
// auto head() -> Head* { return (Head*)s_h; }
//};
//auto list() -> ListVec const* { return &s_lv; } // not thread safe
//u32 lnkCnt() // not thread safe
//{
// u32 cnt = 0;
// u32 curIdx = idx();
// while( curIdx != LIST_END ){
// curIdx = s_lv[curIdx];
// ++cnt;
// }
// return cnt;
//}
//
//nxtHead.ver = curHead.ver + 1;
//au32* head =
//nxtHead.ver = curHead.ver==NXT_VER_SPECIAL? 1 : curHead.ver+1;
//nxtIp.asInt = aip->load();
//Idx tmp = nxtIp.first;
//bool incTwoIdxReaders(u64 idx, IdxPair* newIp = nullptr)
//bool incIdxPairReaders(u64 idx, IdxPair* newIp = nullptr)
//
// u8* firstIdxPtr =
// Idx* idxPtr = (Idx*)(m_mem + idx*sizeof(Idx)); // it is crucial and fundamental that sizeof(Idx) needs to be 4 bytes so that two of them can be swapped even if unaligned, but this should be more correct and clear
//au64* atmIncPtr = (au64*)(m_mem + idx*sizeof(Idx)); // it is crucial and fundamental that sizeof(Idx) needs to be 4 bytes so that two of them can be swapped even if unaligned, but this should be more correct and clear
//IdxPair ip;
//ip.asInt = newVal;
<|endoftext|> |
<commit_before>//
// Copyright (c) 2011 Kim Walisch, <kim.walisch@gmail.com>.
// All rights reserved.
//
// This file is part of primesieve.
// Homepage: http://primesieve.googlecode.com
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following
// disclaimer in the documentation and/or other materials provided
// with the distribution.
// * Neither the name of the author nor the names of its
// contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
// FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
// COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
// INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
// HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
// STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
// OF THE POSSIBILITY OF SUCH DAMAGE.
#include "EratMedium.h"
#include "SieveOfEratosthenes.h"
#include "EratBase.h"
#include "WheelFactorization.h"
#include "defs.h"
#include <stdexcept>
#include <algorithm>
#include <list>
EratMedium::EratMedium(const SieveOfEratosthenes& soe) :
EratBase<Modulo210Wheel_t> (soe)
{
// conditions that assert multipleIndex < 2^23 in sieve()
static_assert(defs::ERATMEDIUM_FACTOR <= 6, "defs::ERATMEDIUM_FACTOR <= 6");
if (soe.getSieveSize() > (1U << 22))
throw std::overflow_error(
"EratMedium: sieveSize must be <= 2^22, 4096 kilobytes.");
uint32_t sqrtStop = soe.getSquareRoot();
uint32_t max = soe.getSieveSize() * defs::ERATMEDIUM_FACTOR;
uint32_t limit = std::min(sqrtStop, max);
this->setLimit(limit);
}
/**
* Implementation of the segmented sieve of Eratosthenes with wheel
* factorization optimized for medium sieving primes that have a few
* multiples per segment.
* This implementation uses a sieve array with 30 numbers per byte and
* a modulo 210 wheel that skips multiples of 2, 3, 5 and 7.
* @see SieveOfEratosthenes::crossOffMultiples()
*/
void EratMedium::sieve(uint8_t* sieve, uint32_t sieveSize)
{
// The integer multiplication and wheel(...)-> lookup table are this
// algorithm's bottlenecks, out-of-order optimization: 2 sieving
// primes are processed per loop iteration to break the dependency
// chain and reduce data hazards in the CPU's pipeline
for (BucketList_t::iterator bucket = buckets_.begin(); bucket != buckets_.end(); ++bucket) {
WheelPrime* wPrime = bucket->begin();
WheelPrime* end = bucket->end();
for (; wPrime + 2 <= end; wPrime += 2) {
uint32_t multipleIndex0 = wPrime[0].getMultipleIndex();
uint32_t wheelIndex0 = wPrime[0].getWheelIndex();
uint32_t sievingPrime0 = wPrime[0].getSievingPrime();
uint32_t multipleIndex1 = wPrime[1].getMultipleIndex();
uint32_t wheelIndex1 = wPrime[1].getWheelIndex();
uint32_t sievingPrime1 = wPrime[1].getSievingPrime();
while (multipleIndex0 < sieveSize &&
multipleIndex1 < sieveSize) {
sieve[multipleIndex0] &= wheel(wheelIndex0)->unsetBit;
multipleIndex0 += wheel(wheelIndex0)->nextMultipleFactor * sievingPrime0;
multipleIndex0 += wheel(wheelIndex0)->correct;
wheelIndex0 += wheel(wheelIndex0)->next;
sieve[multipleIndex1] &= wheel(wheelIndex1)->unsetBit;
multipleIndex1 += wheel(wheelIndex1)->nextMultipleFactor * sievingPrime1;
multipleIndex1 += wheel(wheelIndex1)->correct;
wheelIndex1 += wheel(wheelIndex1)->next;
}
while (multipleIndex0 < sieveSize) {
sieve[multipleIndex0] &= wheel(wheelIndex0)->unsetBit;
multipleIndex0 += wheel(wheelIndex0)->nextMultipleFactor * sievingPrime0;
multipleIndex0 += wheel(wheelIndex0)->correct;
wheelIndex0 += wheel(wheelIndex0)->next;
}
while (multipleIndex1 < sieveSize) {
sieve[multipleIndex1] &= wheel(wheelIndex1)->unsetBit;
multipleIndex1 += wheel(wheelIndex1)->nextMultipleFactor * sievingPrime1;
multipleIndex1 += wheel(wheelIndex1)->correct;
wheelIndex1 += wheel(wheelIndex1)->next;
}
multipleIndex0 -= sieveSize;
multipleIndex1 -= sieveSize;
wPrime[0].setIndexes(multipleIndex0, wheelIndex0);
wPrime[1].setIndexes(multipleIndex1, wheelIndex1);
}
if (wPrime != end) {
uint32_t multipleIndex = wPrime->getMultipleIndex();
uint32_t wheelIndex = wPrime->getWheelIndex();
uint32_t sievingPrime = wPrime->getSievingPrime();
while (multipleIndex < sieveSize) {
sieve[multipleIndex] &= wheel(wheelIndex)->unsetBit;
multipleIndex += wheel(wheelIndex)->nextMultipleFactor * sievingPrime;
multipleIndex += wheel(wheelIndex)->correct;
wheelIndex += wheel(wheelIndex)->next;
}
multipleIndex -= sieveSize;
wPrime->setIndexes(multipleIndex, wheelIndex);
}
}
}
<commit_msg>comment<commit_after>//
// Copyright (c) 2012 Kim Walisch, <kim.walisch@gmail.com>.
// All rights reserved.
//
// This file is part of primesieve.
// Homepage: http://primesieve.googlecode.com
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following
// disclaimer in the documentation and/or other materials provided
// with the distribution.
// * Neither the name of the author nor the names of its
// contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
// FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
// COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
// INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
// HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
// STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
// OF THE POSSIBILITY OF SUCH DAMAGE.
#include "EratMedium.h"
#include "SieveOfEratosthenes.h"
#include "EratBase.h"
#include "WheelFactorization.h"
#include "defs.h"
#include <stdexcept>
#include <algorithm>
#include <list>
EratMedium::EratMedium(const SieveOfEratosthenes& soe) :
EratBase<Modulo210Wheel_t> (soe)
{
// conditions that assert multipleIndex < 2^23 in sieve()
static_assert(defs::ERATMEDIUM_FACTOR <= 6, "defs::ERATMEDIUM_FACTOR <= 6");
if (soe.getSieveSize() > (1U << 22))
throw std::overflow_error(
"EratMedium: sieveSize must be <= 2^22, 4096 kilobytes.");
uint32_t sqrtStop = soe.getSquareRoot();
uint32_t max = soe.getSieveSize() * defs::ERATMEDIUM_FACTOR;
uint32_t limit = std::min(sqrtStop, max);
this->setLimit(limit);
}
/**
* Implementation of the segmented sieve of Eratosthenes with wheel
* factorization optimized for medium sieving primes that have a few
* multiples per segment.
* This implementation uses a sieve array with 30 numbers per byte and
* a modulo 210 wheel that skips multiples of 2, 3, 5 and 7.
* @see SieveOfEratosthenes::crossOffMultiples()
*/
void EratMedium::sieve(uint8_t* sieve, uint32_t sieveSize)
{
// The integer multiplication and wheel(...)-> lookup table are this
// algorithm's bottlenecks. For out-of-order CPUs the algorithm
// can be sped up by processing 2 sieving primes per loop iteration,
// this breaks the dependency chain and reduces pipeline stalls
for (BucketList_t::iterator bucket = buckets_.begin(); bucket != buckets_.end(); ++bucket) {
WheelPrime* wPrime = bucket->begin();
WheelPrime* end = bucket->end();
for (; wPrime + 2 <= end; wPrime += 2) {
uint32_t multipleIndex0 = wPrime[0].getMultipleIndex();
uint32_t wheelIndex0 = wPrime[0].getWheelIndex();
uint32_t sievingPrime0 = wPrime[0].getSievingPrime();
uint32_t multipleIndex1 = wPrime[1].getMultipleIndex();
uint32_t wheelIndex1 = wPrime[1].getWheelIndex();
uint32_t sievingPrime1 = wPrime[1].getSievingPrime();
while (multipleIndex0 < sieveSize &&
multipleIndex1 < sieveSize) {
sieve[multipleIndex0] &= wheel(wheelIndex0)->unsetBit;
multipleIndex0 += wheel(wheelIndex0)->nextMultipleFactor * sievingPrime0;
multipleIndex0 += wheel(wheelIndex0)->correct;
wheelIndex0 += wheel(wheelIndex0)->next;
sieve[multipleIndex1] &= wheel(wheelIndex1)->unsetBit;
multipleIndex1 += wheel(wheelIndex1)->nextMultipleFactor * sievingPrime1;
multipleIndex1 += wheel(wheelIndex1)->correct;
wheelIndex1 += wheel(wheelIndex1)->next;
}
while (multipleIndex0 < sieveSize) {
sieve[multipleIndex0] &= wheel(wheelIndex0)->unsetBit;
multipleIndex0 += wheel(wheelIndex0)->nextMultipleFactor * sievingPrime0;
multipleIndex0 += wheel(wheelIndex0)->correct;
wheelIndex0 += wheel(wheelIndex0)->next;
}
while (multipleIndex1 < sieveSize) {
sieve[multipleIndex1] &= wheel(wheelIndex1)->unsetBit;
multipleIndex1 += wheel(wheelIndex1)->nextMultipleFactor * sievingPrime1;
multipleIndex1 += wheel(wheelIndex1)->correct;
wheelIndex1 += wheel(wheelIndex1)->next;
}
multipleIndex0 -= sieveSize;
multipleIndex1 -= sieveSize;
wPrime[0].setIndexes(multipleIndex0, wheelIndex0);
wPrime[1].setIndexes(multipleIndex1, wheelIndex1);
}
if (wPrime != end) {
uint32_t multipleIndex = wPrime->getMultipleIndex();
uint32_t wheelIndex = wPrime->getWheelIndex();
uint32_t sievingPrime = wPrime->getSievingPrime();
while (multipleIndex < sieveSize) {
sieve[multipleIndex] &= wheel(wheelIndex)->unsetBit;
multipleIndex += wheel(wheelIndex)->nextMultipleFactor * sievingPrime;
multipleIndex += wheel(wheelIndex)->correct;
wheelIndex += wheel(wheelIndex)->next;
}
multipleIndex -= sieveSize;
wPrime->setIndexes(multipleIndex, wheelIndex);
}
}
}
<|endoftext|> |
<commit_before>#include <imgui_utils/icons_font_awesome_5.h>
#include <babylon/babylon_imgui/run_scene_with_inspector.h>
#include <imgui_utils/app_runner/imgui_runner.h>
#include <babylon/GL/framebuffer_canvas.h>
#include <babylon/core/logging.h>
#include <babylon/samples/samples_index.h>
#ifdef _WIN32
#include <windows.h>
#endif
namespace BABYLON
{
namespace impl
{
const int INSPECTOR_WIDTH = 400;
class BabylonInspectorApp {
public:
BabylonInspectorApp();
void RunApp(
std::shared_ptr<BABYLON::IRenderableScene> initialScene,
const SceneWithInspectorOptions & options
);
private:
enum class ViewState
{
Scene3d,
CodeEditor,
SampleBrowser,
};
static std::map<BabylonInspectorApp::ViewState, std::string> ViewStateLabels;
void initScene();
bool render(); // renders the GUI. Returns true when exit required
void setRenderableScene(std::shared_ptr<BABYLON::IRenderableScene> scene);
// Saves a screenshot after few frames (eeturns true when done)
bool saveScreenshot();
private:
void handleLoopSamples();
struct AppContext
{
std::unique_ptr<BABYLON::ImGuiSceneWidget> _sceneWidget;
BABYLON::Inspector _inspector;
BABYLON::SamplesBrowser _sampleListComponent;
ViewState _viewState = ViewState::Scene3d;
int _frameCounter = 0;
SceneWithInspectorOptions _options;
struct
{
bool flagLoop = false;
size_t currentIdx = 0;
std::vector<std::string> samplesToLoop;
} _loopSamples;
};
AppContext _appContext;
ImGuiUtils::CodeEditor _codeEditor;
}; // end of class BabylonInspectorApp
namespace
{
template<typename EnumType>
bool ShowTabBarEnum(const std::map<EnumType, std::string> & enumNames, EnumType * value)
{
bool changed = false;
for (const auto & kv : enumNames)
{
bool selected = (*value == kv.first);
if (selected)
ImGui::PushStyleColor(ImGuiCol_Button, ImVec4(0.3f, 0.3f, 0.6f, 1.f));
if (ImGui::Button(kv.second.c_str()))
{
if (*value != kv.first)
{
*value = kv.first;
changed = true;
}
}
if (selected)
ImGui::PopStyleColor();
ImGui::SameLine();
}
//ImGui::NewLine();
//ImGui::Separator();
return changed;
}
}
std::map<BabylonInspectorApp::ViewState, std::string> BabylonInspectorApp::ViewStateLabels = {
{ BabylonInspectorApp::ViewState::Scene3d, ICON_FA_CUBE " 3D Scene"},
{ BabylonInspectorApp::ViewState::CodeEditor, ICON_FA_EDIT " Code Editor"},
{ BabylonInspectorApp::ViewState::SampleBrowser, ICON_FA_PALETTE " Browse samples"},
};
bool BabylonInspectorApp::render()
{
bool shallExit = false;
_appContext._inspector.render(false, INSPECTOR_WIDTH);
ImGui::SameLine();
ImGui::BeginGroup();
ImGui::Text("%s", _appContext._sceneWidget->getRenderableScene()->getName());
ImGui::SameLine(0., 100.);
ShowTabBarEnum(ViewStateLabels, &_appContext._viewState);
ImGui::SameLine(0.f, 150.f);
if (ImGui::Button(ICON_FA_DOOR_OPEN "Exit"))
shallExit = true;
ImGui::Separator();
if (_appContext._viewState == ViewState::Scene3d)
_appContext._sceneWidget->render();
if (_appContext._viewState == ViewState::CodeEditor)
_codeEditor.render();
else if (_appContext._viewState == ViewState::SampleBrowser)
_appContext._sampleListComponent.render();
ImGui::EndGroup();
handleLoopSamples();
if (_appContext._options._flagScreenshotOneSampleAndExit)
return saveScreenshot();
else
return shallExit;
}
void BabylonInspectorApp::setRenderableScene(std::shared_ptr<BABYLON::IRenderableScene> scene)
{
_appContext._inspector.setScene(nullptr);
_appContext._sceneWidget->setRenderableScene(scene);
_appContext._inspector.setScene(_appContext._sceneWidget->getScene());
_appContext._viewState = ViewState::Scene3d;
}
bool BabylonInspectorApp::saveScreenshot()
{
_appContext._frameCounter++;
if (_appContext._frameCounter < 30)
return false;
int imageWidth = 200;
int jpgQuality = 75;
this->_appContext._sceneWidget->getCanvas()->saveScreenshotJpg((_appContext._options._sceneName + ".jpg").c_str(),
jpgQuality, imageWidth);
return true;
}
void BabylonInspectorApp::handleLoopSamples()
{
static BABYLON::Samples::SamplesIndex samplesIndex;
if (!_appContext._loopSamples.flagLoop)
return;
static int frame_counter = 0;
const int max_frames = 60;
if (frame_counter > max_frames)
{
std::string sampleName = _appContext._loopSamples.samplesToLoop[_appContext._loopSamples.currentIdx];
BABYLON_LOG_ERROR("LoopSample", sampleName);
auto scene = samplesIndex.createRenderableScene(sampleName, nullptr);
this->setRenderableScene(scene);
if (_appContext._loopSamples.currentIdx < _appContext._loopSamples.samplesToLoop.size() - 2)
_appContext._loopSamples.currentIdx++;
else
_appContext._loopSamples.flagLoop = false;
frame_counter = 0;
}
else
frame_counter++;
}
BabylonInspectorApp::BabylonInspectorApp()
{
}
void BabylonInspectorApp::RunApp(
std::shared_ptr<BABYLON::IRenderableScene> initialScene,
const SceneWithInspectorOptions & options)
{
_appContext._options = options;
std::function<bool(void)> showGuiLambda = [this]() -> bool {
return this->render();
};
auto initSceneLambda = [&]() {
this->initScene();
this->setRenderableScene(initialScene);
};
ImGuiUtils::ImGuiRunner::RunGui(showGuiLambda, _appContext._options._appWindowParams, initSceneLambda);
}
void BabylonInspectorApp::initScene()
{
_appContext._sampleListComponent.OnNewRenderableScene = [&](std::shared_ptr<IRenderableScene> scene) {
this->setRenderableScene(scene);
};
_appContext._sampleListComponent.OnEditFiles = [&](const std::vector<std::string> & files) {
_codeEditor.setFiles(files);
_appContext._viewState = ViewState::CodeEditor;
};
_appContext._sampleListComponent.OnLoopSamples = [&](const std::vector<std::string> & samples) {
_appContext._loopSamples.flagLoop = true;
_appContext._loopSamples.samplesToLoop = samples;
_appContext._loopSamples.currentIdx = 0;
_appContext._viewState = ViewState::Scene3d;
};
ImVec2 sceneSize = ImGui::GetIO().DisplaySize;
sceneSize.x -= INSPECTOR_WIDTH;
sceneSize.y -= 60;
_appContext._sceneWidget = std::make_unique<BABYLON::ImGuiSceneWidget>(sceneSize);
}
} // namespace impl
// public API
void runSceneWithInspector(
std::shared_ptr<BABYLON::IRenderableScene> scene,
SceneWithInspectorOptions options /* = SceneWithInspectorOptions() */
)
{
BABYLON::impl::BabylonInspectorApp app;
app.RunApp(scene, options);
}
} // namespace BABYLON
<commit_msg>run_scene_with_inspector : group internal class BabylonInspectorApp<commit_after>#include <imgui_utils/icons_font_awesome_5.h>
#include <babylon/babylon_imgui/run_scene_with_inspector.h>
#include <imgui_utils/app_runner/imgui_runner.h>
#include <babylon/GL/framebuffer_canvas.h>
#include <babylon/core/logging.h>
#include <babylon/samples/samples_index.h>
#ifdef _WIN32
#include <windows.h>
#endif
namespace
{
template<typename EnumType>
bool ShowTabBarEnum(const std::map<EnumType, std::string> & enumNames, EnumType * value)
{
bool changed = false;
for (const auto & kv : enumNames)
{
bool selected = (*value == kv.first);
if (selected)
ImGui::PushStyleColor(ImGuiCol_Button, ImVec4(0.3f, 0.3f, 0.6f, 1.f));
if (ImGui::Button(kv.second.c_str()))
{
if (*value != kv.first)
{
*value = kv.first;
changed = true;
}
}
if (selected)
ImGui::PopStyleColor();
ImGui::SameLine();
}
//ImGui::NewLine();
//ImGui::Separator();
return changed;
}
}
namespace BABYLON
{
namespace impl
{
const int INSPECTOR_WIDTH = 400;
class BabylonInspectorApp {
public:
BabylonInspectorApp() {}
void RunApp(
std::shared_ptr<BABYLON::IRenderableScene> initialScene,
const SceneWithInspectorOptions & options
)
{
_appContext._options = options;
std::function<bool(void)> showGuiLambda = [this]() -> bool {
return this->render();
};
auto initSceneLambda = [&]() {
this->initScene();
this->setRenderableScene(initialScene);
};
ImGuiUtils::ImGuiRunner::RunGui(showGuiLambda, _appContext._options._appWindowParams, initSceneLambda);
}
private:
enum class ViewState
{
Scene3d,
CodeEditor,
SampleBrowser,
};
static std::map<BabylonInspectorApp::ViewState, std::string> ViewStateLabels;
void initScene()
{
_appContext._sampleListComponent.OnNewRenderableScene = [&](std::shared_ptr<IRenderableScene> scene) {
this->setRenderableScene(scene);
};
_appContext._sampleListComponent.OnEditFiles = [&](const std::vector<std::string> & files) {
_codeEditor.setFiles(files);
_appContext._viewState = ViewState::CodeEditor;
};
_appContext._sampleListComponent.OnLoopSamples = [&](const std::vector<std::string> & samples) {
_appContext._loopSamples.flagLoop = true;
_appContext._loopSamples.samplesToLoop = samples;
_appContext._loopSamples.currentIdx = 0;
_appContext._viewState = ViewState::Scene3d;
};
ImVec2 sceneSize = ImGui::GetIO().DisplaySize;
sceneSize.x -= INSPECTOR_WIDTH;
sceneSize.y -= 60;
_appContext._sceneWidget = std::make_unique<BABYLON::ImGuiSceneWidget>(sceneSize);
}
bool render() // renders the GUI. Returns true when exit required
{
bool shallExit = false;
_appContext._inspector.render(false, INSPECTOR_WIDTH);
ImGui::SameLine();
ImGui::BeginGroup();
ImGui::Text("%s", _appContext._sceneWidget->getRenderableScene()->getName());
ImGui::SameLine(0., 100.);
ShowTabBarEnum(ViewStateLabels, &_appContext._viewState);
ImGui::SameLine(0.f, 150.f);
if (ImGui::Button(ICON_FA_DOOR_OPEN "Exit"))
shallExit = true;
ImGui::Separator();
if (_appContext._viewState == ViewState::Scene3d)
_appContext._sceneWidget->render();
if (_appContext._viewState == ViewState::CodeEditor)
_codeEditor.render();
else if (_appContext._viewState == ViewState::SampleBrowser)
_appContext._sampleListComponent.render();
ImGui::EndGroup();
handleLoopSamples();
if (_appContext._options._flagScreenshotOneSampleAndExit)
return saveScreenshot();
else
return shallExit;
}
void setRenderableScene(std::shared_ptr<BABYLON::IRenderableScene> scene)
{
_appContext._inspector.setScene(nullptr);
_appContext._sceneWidget->setRenderableScene(scene);
_appContext._inspector.setScene(_appContext._sceneWidget->getScene());
_appContext._viewState = ViewState::Scene3d;
}
// Saves a screenshot after few frames (eeturns true when done)
bool saveScreenshot()
{
_appContext._frameCounter++;
if (_appContext._frameCounter < 30)
return false;
int imageWidth = 200;
int jpgQuality = 75;
this->_appContext._sceneWidget->getCanvas()->saveScreenshotJpg((_appContext._options._sceneName + ".jpg").c_str(),
jpgQuality, imageWidth);
return true;
}
private:
void handleLoopSamples()
{
static BABYLON::Samples::SamplesIndex samplesIndex;
if (!_appContext._loopSamples.flagLoop)
return;
static int frame_counter = 0;
const int max_frames = 60;
if (frame_counter > max_frames)
{
std::string sampleName = _appContext._loopSamples.samplesToLoop[_appContext._loopSamples.currentIdx];
BABYLON_LOG_ERROR("LoopSample", sampleName);
auto scene = samplesIndex.createRenderableScene(sampleName, nullptr);
this->setRenderableScene(scene);
if (_appContext._loopSamples.currentIdx < _appContext._loopSamples.samplesToLoop.size() - 2)
_appContext._loopSamples.currentIdx++;
else
_appContext._loopSamples.flagLoop = false;
frame_counter = 0;
}
else
frame_counter++;
}
struct AppContext
{
std::unique_ptr<BABYLON::ImGuiSceneWidget> _sceneWidget;
BABYLON::Inspector _inspector;
BABYLON::SamplesBrowser _sampleListComponent;
ViewState _viewState = ViewState::Scene3d;
int _frameCounter = 0;
SceneWithInspectorOptions _options;
struct
{
bool flagLoop = false;
size_t currentIdx = 0;
std::vector<std::string> samplesToLoop;
} _loopSamples;
};
AppContext _appContext;
ImGuiUtils::CodeEditor _codeEditor;
}; // end of class BabylonInspectorApp
std::map<BabylonInspectorApp::ViewState, std::string> BabylonInspectorApp::ViewStateLabels = {
{ BabylonInspectorApp::ViewState::Scene3d, ICON_FA_CUBE " 3D Scene"},
{ BabylonInspectorApp::ViewState::CodeEditor, ICON_FA_EDIT " Code Editor"},
{ BabylonInspectorApp::ViewState::SampleBrowser, ICON_FA_PALETTE " Browse samples"},
};
} // namespace impl
// public API
void runSceneWithInspector(
std::shared_ptr<BABYLON::IRenderableScene> scene,
SceneWithInspectorOptions options /* = SceneWithInspectorOptions() */
)
{
BABYLON::impl::BabylonInspectorApp app;
app.RunApp(scene, options);
}
} // namespace BABYLON
<|endoftext|> |
<commit_before>/* Copyright (c) 2014, Fengping Bao <jamol@live.com>
*
* Permission to use, copy, modify, and/or distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
* ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
* ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
* OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*/
#ifdef KUMA_HAS_OPENSSL
#include "kmconf.h"
#if defined(KUMA_OS_WIN)
# include <Ws2tcpip.h>
# include <windows.h>
# include <time.h>
#elif defined(KUMA_OS_LINUX)
# include <string.h>
# include <pthread.h>
# include <unistd.h>
# include <fcntl.h>
# include <sys/types.h>
# include <sys/stat.h>
# include <sys/time.h>
# include <sys/socket.h>
# include <netdb.h>
# include <arpa/inet.h>
# include <netinet/tcp.h>
# include <netinet/in.h>
#elif defined(KUMA_OS_MAC)
# include <string.h>
# include <pthread.h>
# include <unistd.h>
# include <sys/types.h>
# include <sys/socket.h>
# include <sys/ioctl.h>
# include <sys/fcntl.h>
# include <sys/time.h>
# include <sys/uio.h>
# include <netinet/tcp.h>
# include <netinet/in.h>
# include <arpa/inet.h>
# include <netdb.h>
# include <ifaddrs.h>
#else
# error "UNSUPPORTED OS"
#endif
#include "SslHandler.h"
#include "util/kmtrace.h"
using namespace kuma;
SslHandler::SslHandler()
: fd_(INVALID_FD)
, ssl_(NULL)
, state_(SSL_NONE)
, is_server_(false)
{
}
SslHandler::~SslHandler()
{
cleanup();
}
const char* SslHandler::getObjKey()
{
return "SslHandler";
}
void SslHandler::cleanup()
{
if(ssl_) {
SSL_shutdown(ssl_);
SSL_free(ssl_);
ssl_ = NULL;
}
setState(SSL_NONE);
}
int SslHandler::attachFd(SOCKET_FD fd, SslRole ssl_role)
{
cleanup();
is_server_ = ssl_role == AS_SERVER;
fd_ = fd;
SSL_CTX* ctx = NULL;
if(is_server_) {
ctx = OpenSslLib::getServerContext();
} else {
ctx = OpenSslLib::getClientContext();
}
if(NULL == ctx) {
KUMA_ERRXTRACE("attachFd, CTX is NULL");
return KUMA_ERROR_SSL_FAILED;
}
ssl_ = SSL_new(ctx);
if(NULL == ssl_) {
KUMA_ERRXTRACE("attachFd, SSL_new failed");
return KUMA_ERROR_SSL_FAILED;
}
int ret = SSL_set_fd(ssl_, fd_);
if(0 == ret) {
KUMA_ERRXTRACE("attachFd, SSL_set_fd failed, err="<<ERR_reason_error_string(ERR_get_error()));
SSL_free(ssl_);
ssl_ = NULL;
return KUMA_ERROR_SSL_FAILED;
}
return KUMA_ERROR_NOERR;
}
int SslHandler::attachSsl(SSL* ssl)
{
cleanup();
ssl_ = ssl;
if (ssl_) {
setState(SSL_SUCCESS);
}
return KUMA_ERROR_NOERR;
}
int SslHandler::detachSsl(SSL* &ssl)
{
ssl = ssl_;
ssl_ = nullptr;
return KUMA_ERROR_NOERR;
}
SslHandler::SslState SslHandler::sslConnect()
{
if(NULL == ssl_) {
KUMA_ERRXTRACE("sslConnect, ssl_ is NULL");
return SSL_ERROR;
}
int ret = SSL_connect(ssl_);
int ssl_err = SSL_get_error (ssl_, ret);
switch (ssl_err)
{
case SSL_ERROR_NONE:
return SSL_SUCCESS;
case SSL_ERROR_WANT_WRITE:
case SSL_ERROR_WANT_READ:
return SSL_HANDSHAKE;
default:
{
const char* err_str = ERR_reason_error_string(ERR_get_error());
KUMA_ERRXTRACE("sslConnect, error, fd="<<fd_
<<", ssl_status="<<ret
<<", ssl_err="<<ssl_err
<<", os_err="<<getLastError()
<<", err_msg="<<(err_str?err_str:""));
SSL_free(ssl_);
ssl_ = NULL;
return SSL_ERROR;
}
}
return SSL_HANDSHAKE;
}
SslHandler::SslState SslHandler::sslAccept()
{
if(NULL == ssl_) {
KUMA_ERRXTRACE("sslAccept, ssl_ is NULL");
return SSL_ERROR;
}
int ret = SSL_accept(ssl_);
int ssl_err = SSL_get_error(ssl_, ret);
switch (ssl_err)
{
case SSL_ERROR_NONE:
return SSL_SUCCESS;
case SSL_ERROR_WANT_WRITE:
case SSL_ERROR_WANT_READ:
return SSL_HANDSHAKE;
default:
{
const char* err_str = ERR_reason_error_string(ERR_get_error());
KUMA_ERRXTRACE("sslAccept, error, fd="<<fd_
<<", ssl_status="<<ret
<<", ssl_err="<<ssl_err
<<", os_err="<<getLastError()
<<", err_msg="<<(err_str?err_str:""));
SSL_free(ssl_);
ssl_ = NULL;
return SSL_ERROR;
}
}
return SSL_HANDSHAKE;
}
int SslHandler::send(const uint8_t* data, uint32_t size)
{
if(NULL == ssl_) {
KUMA_ERRXTRACE("send, ssl is NULL");
return -1;
}
int ret = SSL_write(ssl_, data, size);
int ssl_err = SSL_get_error(ssl_, ret);
switch (ssl_err)
{
case SSL_ERROR_NONE:
break;
case SSL_ERROR_WANT_READ:
case SSL_ERROR_WANT_WRITE:
ret = 0;
break;
default:
{
const char* err_str = ERR_reason_error_string(ERR_get_error());
KUMA_ERRXTRACE( "send, SSL_write failed, fd="<<fd_
<<", ssl_status="<<ret
<<", ssl_err="<<ssl_err
<<", errno="<<getLastError()
<<", err_msg="<<(err_str?err_str:""));
ret = -1;
break;
}
}
if(ret < 0) {
cleanup();
}
//KUMA_INFOXTRACE("send, ret: "<<ret<<", len: "<<len);
return ret;
}
int SslHandler::send(const iovec* iovs, uint32_t count)
{
uint32_t bytes_sent = 0;
for (uint32_t i=0; i < count; ++i) {
int ret = SslHandler::send((const uint8_t*)iovs[i].iov_base, uint32_t(iovs[i].iov_len));
if(ret < 0) {
return ret;
} else {
bytes_sent += ret;
if(ret < iovs[i].iov_len) {
break;
}
}
}
return bytes_sent;
}
int SslHandler::receive(uint8_t* data, uint32_t size)
{
if(NULL == ssl_) {
KUMA_ERRXTRACE("receive, ssl is NULL");
return -1;
}
int ret = SSL_read(ssl_, data, size);
int ssl_err = SSL_get_error(ssl_, ret);
switch (ssl_err)
{
case SSL_ERROR_NONE:
break;
case SSL_ERROR_WANT_READ:
case SSL_ERROR_WANT_WRITE:
ret = 0;
break;
default:
{
const char* err_str = ERR_reason_error_string(ERR_get_error());
KUMA_ERRXTRACE("receive, SSL_read failed, fd="<<fd_
<<", ssl_status="<<ret
<<", ssl_err="<<ssl_err
<<", os_err="<<getLastError()
<<", err_msg="<<(err_str?err_str:""));
ret = -1;
break;
}
}
if(ret < 0) {
cleanup();
}
//KUMA_INFOXTRACE("receive, ret: "<<ret);
return ret;
}
int SslHandler::close()
{
cleanup();
return KUMA_ERROR_NOERR;
}
SslHandler::SslState SslHandler::doSslHandshake()
{
SslState state = SSL_HANDSHAKE;
if(is_server_) {
state = sslAccept();
} else {
state = sslConnect();
}
setState(state);
if(SSL_ERROR == state) {
cleanup();
}
return state;
}
#endif // KUMA_HAS_OPENSSL
<commit_msg>call ERR_clear_error before calling SSL_xxx<commit_after>/* Copyright (c) 2014, Fengping Bao <jamol@live.com>
*
* Permission to use, copy, modify, and/or distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
* ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
* ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
* OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*/
#ifdef KUMA_HAS_OPENSSL
#include "kmconf.h"
#if defined(KUMA_OS_WIN)
# include <Ws2tcpip.h>
# include <windows.h>
# include <time.h>
#elif defined(KUMA_OS_LINUX)
# include <string.h>
# include <pthread.h>
# include <unistd.h>
# include <fcntl.h>
# include <sys/types.h>
# include <sys/stat.h>
# include <sys/time.h>
# include <sys/socket.h>
# include <netdb.h>
# include <arpa/inet.h>
# include <netinet/tcp.h>
# include <netinet/in.h>
#elif defined(KUMA_OS_MAC)
# include <string.h>
# include <pthread.h>
# include <unistd.h>
# include <sys/types.h>
# include <sys/socket.h>
# include <sys/ioctl.h>
# include <sys/fcntl.h>
# include <sys/time.h>
# include <sys/uio.h>
# include <netinet/tcp.h>
# include <netinet/in.h>
# include <arpa/inet.h>
# include <netdb.h>
# include <ifaddrs.h>
#else
# error "UNSUPPORTED OS"
#endif
#include "SslHandler.h"
#include "util/kmtrace.h"
using namespace kuma;
SslHandler::SslHandler()
: fd_(INVALID_FD)
, ssl_(NULL)
, state_(SSL_NONE)
, is_server_(false)
{
}
SslHandler::~SslHandler()
{
cleanup();
}
const char* SslHandler::getObjKey()
{
return "SslHandler";
}
void SslHandler::cleanup()
{
if(ssl_) {
SSL_shutdown(ssl_);
SSL_free(ssl_);
ssl_ = NULL;
}
setState(SSL_NONE);
}
int SslHandler::attachFd(SOCKET_FD fd, SslRole ssl_role)
{
cleanup();
is_server_ = ssl_role == AS_SERVER;
fd_ = fd;
SSL_CTX* ctx = NULL;
if(is_server_) {
ctx = OpenSslLib::getServerContext();
} else {
ctx = OpenSslLib::getClientContext();
}
if(NULL == ctx) {
KUMA_ERRXTRACE("attachFd, CTX is NULL");
return KUMA_ERROR_SSL_FAILED;
}
ssl_ = SSL_new(ctx);
if(NULL == ssl_) {
KUMA_ERRXTRACE("attachFd, SSL_new failed");
return KUMA_ERROR_SSL_FAILED;
}
int ret = SSL_set_fd(ssl_, fd_);
if(0 == ret) {
KUMA_ERRXTRACE("attachFd, SSL_set_fd failed, err="<<ERR_reason_error_string(ERR_get_error()));
SSL_free(ssl_);
ssl_ = NULL;
return KUMA_ERROR_SSL_FAILED;
}
return KUMA_ERROR_NOERR;
}
int SslHandler::attachSsl(SSL* ssl)
{
cleanup();
ssl_ = ssl;
if (ssl_) {
setState(SSL_SUCCESS);
}
return KUMA_ERROR_NOERR;
}
int SslHandler::detachSsl(SSL* &ssl)
{
ssl = ssl_;
ssl_ = nullptr;
return KUMA_ERROR_NOERR;
}
SslHandler::SslState SslHandler::sslConnect()
{
if(NULL == ssl_) {
KUMA_ERRXTRACE("sslConnect, ssl_ is NULL");
return SSL_ERROR;
}
ERR_clear_error();
int ret = SSL_connect(ssl_);
int ssl_err = SSL_get_error (ssl_, ret);
switch (ssl_err)
{
case SSL_ERROR_NONE:
return SSL_SUCCESS;
case SSL_ERROR_WANT_WRITE:
case SSL_ERROR_WANT_READ:
return SSL_HANDSHAKE;
default:
{
const char* err_str = ERR_reason_error_string(ERR_get_error());
KUMA_ERRXTRACE("sslConnect, error, fd="<<fd_
<<", ssl_status="<<ret
<<", ssl_err="<<ssl_err
<<", os_err="<<getLastError()
<<", err_msg="<<(err_str?err_str:""));
SSL_free(ssl_);
ssl_ = NULL;
return SSL_ERROR;
}
}
return SSL_HANDSHAKE;
}
SslHandler::SslState SslHandler::sslAccept()
{
if(NULL == ssl_) {
KUMA_ERRXTRACE("sslAccept, ssl_ is NULL");
return SSL_ERROR;
}
ERR_clear_error();
int ret = SSL_accept(ssl_);
int ssl_err = SSL_get_error(ssl_, ret);
switch (ssl_err)
{
case SSL_ERROR_NONE:
return SSL_SUCCESS;
case SSL_ERROR_WANT_WRITE:
case SSL_ERROR_WANT_READ:
return SSL_HANDSHAKE;
default:
{
const char* err_str = ERR_reason_error_string(ERR_get_error());
KUMA_ERRXTRACE("sslAccept, error, fd="<<fd_
<<", ssl_status="<<ret
<<", ssl_err="<<ssl_err
<<", os_err="<<getLastError()
<<", err_msg="<<(err_str?err_str:""));
SSL_free(ssl_);
ssl_ = NULL;
return SSL_ERROR;
}
}
return SSL_HANDSHAKE;
}
int SslHandler::send(const uint8_t* data, uint32_t size)
{
if(NULL == ssl_) {
KUMA_ERRXTRACE("send, ssl is NULL");
return -1;
}
ERR_clear_error();
int ret = SSL_write(ssl_, data, size);
int ssl_err = SSL_get_error(ssl_, ret);
switch (ssl_err)
{
case SSL_ERROR_NONE:
break;
case SSL_ERROR_WANT_READ:
case SSL_ERROR_WANT_WRITE:
ret = 0;
break;
default:
{
const char* err_str = ERR_reason_error_string(ERR_get_error());
KUMA_ERRXTRACE( "send, SSL_write failed, fd="<<fd_
<<", ssl_status="<<ret
<<", ssl_err="<<ssl_err
<<", errno="<<getLastError()
<<", err_msg="<<(err_str?err_str:""));
ret = -1;
break;
}
}
if(ret < 0) {
cleanup();
}
//KUMA_INFOXTRACE("send, ret: "<<ret<<", len: "<<len);
return ret;
}
int SslHandler::send(const iovec* iovs, uint32_t count)
{
uint32_t bytes_sent = 0;
for (uint32_t i=0; i < count; ++i) {
int ret = SslHandler::send((const uint8_t*)iovs[i].iov_base, uint32_t(iovs[i].iov_len));
if(ret < 0) {
return ret;
} else {
bytes_sent += ret;
if(ret < iovs[i].iov_len) {
break;
}
}
}
return bytes_sent;
}
int SslHandler::receive(uint8_t* data, uint32_t size)
{
if(NULL == ssl_) {
KUMA_ERRXTRACE("receive, ssl is NULL");
return -1;
}
ERR_clear_error();
int ret = SSL_read(ssl_, data, size);
int ssl_err = SSL_get_error(ssl_, ret);
switch (ssl_err)
{
case SSL_ERROR_NONE:
break;
case SSL_ERROR_WANT_READ:
case SSL_ERROR_WANT_WRITE:
ret = 0;
break;
default:
{
const char* err_str = ERR_reason_error_string(ERR_get_error());
KUMA_ERRXTRACE("receive, SSL_read failed, fd="<<fd_
<<", ssl_status="<<ret
<<", ssl_err="<<ssl_err
<<", os_err="<<getLastError()
<<", err_msg="<<(err_str?err_str:""));
ret = -1;
break;
}
}
if(ret < 0) {
cleanup();
}
//KUMA_INFOXTRACE("receive, ret: "<<ret);
return ret;
}
int SslHandler::close()
{
cleanup();
return KUMA_ERROR_NOERR;
}
SslHandler::SslState SslHandler::doSslHandshake()
{
SslState state = SSL_HANDSHAKE;
if(is_server_) {
state = sslAccept();
} else {
state = sslConnect();
}
setState(state);
if(SSL_ERROR == state) {
cleanup();
}
return state;
}
#endif // KUMA_HAS_OPENSSL
<|endoftext|> |
<commit_before>/*
* stream_iterator.cc
* Copyright 2014-2015 John Lawson
*
* 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 "stream_iterator.h"
#include <iostream> /* Need iostream for std::cin. */
#include "equiv_quiver_matrix.h"
namespace cluster {
template<class T>
StreamIterator<T>::StreamIterator()
: has_next_(false),
str_(),
input_(&std::cin, NullDeleter()) {}
template<class T>
StreamIterator<T>::StreamIterator(std::istream& stream)
: input_(&stream, NullDeleter()) {
has_next_ = std::getline(*input_, str_);
}
template<class T>
std::shared_ptr<T> StreamIterator<T>::next() {
std::shared_ptr<T> result = std::make_shared<T>(str_);
do {
has_next_ = std::getline(*input_, str_);
} while (has_next_ && str_[0] != '{');
return std::move(result);
}
template<class T>
bool StreamIterator<T>::has_next() {
return has_next_;
}
template class StreamIterator<IntMatrix>;
template class StreamIterator<QuiverMatrix>;
template class StreamIterator<EquivQuiverMatrix>;
}
<commit_msg>Adds static cast to bool required for explicit operator (new GCC).<commit_after>/*
* stream_iterator.cc
* Copyright 2014-2015 John Lawson
*
* 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 "stream_iterator.h"
#include <iostream> /* Need iostream for std::cin. */
#include "equiv_quiver_matrix.h"
namespace cluster {
template<class T>
StreamIterator<T>::StreamIterator()
: has_next_(false),
str_(),
input_(&std::cin, NullDeleter()) {}
template<class T>
StreamIterator<T>::StreamIterator(std::istream& stream)
: input_(&stream, NullDeleter()) {
has_next_ = static_cast<bool>(std::getline(*input_, str_));
}
template<class T>
std::shared_ptr<T> StreamIterator<T>::next() {
std::shared_ptr<T> result = std::make_shared<T>(str_);
do {
has_next_ = static_cast<bool>(std::getline(*input_, str_));
} while (has_next_ && str_[0] != '{');
return std::move(result);
}
template<class T>
bool StreamIterator<T>::has_next() {
return has_next_;
}
template class StreamIterator<IntMatrix>;
template class StreamIterator<QuiverMatrix>;
template class StreamIterator<EquivQuiverMatrix>;
}
<|endoftext|> |
<commit_before>#pragma once
#include <cassert>
#include <fstream>
#include <cstring>
#include <string>
/**
* This namespace defines wrappers for std::ifstream, std::ofstream, and
* std::fstream objects. The wrappers perform the following steps:
* - check the open modes make sense
* - check that the call to open() is successful
* - (for input streams) check that the opened file is peek-able
* - turn on the badbit in the exception mask
*/
namespace strict_fstream
{
// Workaround for broken musl implementation
// Since musl insists that they are perfectly compatible, ironically enough,
// they don't have a __musl__ or similar. But __NEED_size_t is defined in their
// relevant header (and not in working implementations), so we can use that.
#ifdef __NEED_size_t
#define BROKEN_GNU_STRERROR_R
#warning "Working around broken strerror_r() implementation in musl, remove when musl is fixed"
#endif
// Non-gnu variants of strerror_* don't necessarily null-terminate if
// truncating, so we have to do things manually.
inline std::string &trim_to_null(std::string &buff)
{
const std::string::size_type pos = buff.find('\0');
if (pos == std::string::npos) {
buff += " [...]"; // it has been truncated
} else {
buff.resize(pos);
}
return buff;
}
/// Overload of error-reporting function, to enable use with VS.
/// Ref: http://stackoverflow.com/a/901316/717706
static std::string strerror()
{
std::string buff(256, '\0');
#ifdef _WIN32
if (strerror_s(buff.data(), buff.size(), errno) != 0) {
return trim_to_null(buff);
} else {
return "Unknown error";
}
#elif ((_POSIX_C_SOURCE >= 200112L || _XOPEN_SOURCE >= 600 || defined(__APPLE__)) && ! _GNU_SOURCE) || defined(BROKEN_GNU_STRERROR_R)
// XSI-compliant strerror_r()
if (strerror_r(errno, buff.data(), buff.size()) == 0) {
return trim_to_null(buff);
} else {
return "Unknown error";
}
#else
// GNU-specific strerror_r()
char * p = strerror_r(errno, &buff[0], buff.size());
return std::string(p, std::strlen(p));
#endif
}
/// Exception class thrown by failed operations.
class Exception
: public std::exception
{
public:
Exception(const std::string& msg) : _msg(msg) {}
const char * what() const noexcept { return _msg.c_str(); }
private:
std::string _msg;
}; // class Exception
namespace detail
{
struct static_method_holder
{
static std::string mode_to_string(std::ios_base::openmode mode)
{
static const int n_modes = 6;
static const std::ios_base::openmode mode_val_v[n_modes] =
{
std::ios_base::in,
std::ios_base::out,
std::ios_base::app,
std::ios_base::ate,
std::ios_base::trunc,
std::ios_base::binary
};
static const char * mode_name_v[n_modes] =
{
"in",
"out",
"app",
"ate",
"trunc",
"binary"
};
std::string res;
for (int i = 0; i < n_modes; ++i)
{
if (mode & mode_val_v[i])
{
res += (! res.empty()? "|" : "");
res += mode_name_v[i];
}
}
if (res.empty()) res = "none";
return res;
}
static void check_mode(const std::string& filename, std::ios_base::openmode mode)
{
if ((mode & std::ios_base::trunc) && ! (mode & std::ios_base::out))
{
throw Exception(std::string("strict_fstream: open('") + filename + "'): mode error: trunc and not out");
}
else if ((mode & std::ios_base::app) && ! (mode & std::ios_base::out))
{
throw Exception(std::string("strict_fstream: open('") + filename + "'): mode error: app and not out");
}
else if ((mode & std::ios_base::trunc) && (mode & std::ios_base::app))
{
throw Exception(std::string("strict_fstream: open('") + filename + "'): mode error: trunc and app");
}
}
static void check_open(std::ios * s_p, const std::string& filename, std::ios_base::openmode mode)
{
if (s_p->fail())
{
throw Exception(std::string("strict_fstream: open('")
+ filename + "'," + mode_to_string(mode) + "): open failed: "
+ strerror());
}
}
static void check_peek(std::istream * is_p, const std::string& filename, std::ios_base::openmode mode)
{
bool peek_failed = true;
try
{
is_p->peek();
peek_failed = is_p->fail();
}
catch (const std::ios_base::failure &) {}
if (peek_failed)
{
throw Exception(std::string("strict_fstream: open('")
+ filename + "'," + mode_to_string(mode) + "): peek failed: "
+ strerror());
}
is_p->clear();
}
}; // struct static_method_holder
} // namespace detail
class ifstream
: public std::ifstream
{
public:
ifstream() = default;
ifstream(const std::string& filename, std::ios_base::openmode mode = std::ios_base::in)
{
open(filename, mode);
}
void open(const std::string& filename, std::ios_base::openmode mode = std::ios_base::in)
{
mode |= std::ios_base::in;
exceptions(std::ios_base::badbit);
detail::static_method_holder::check_mode(filename, mode);
std::ifstream::open(filename, mode);
detail::static_method_holder::check_open(this, filename, mode);
detail::static_method_holder::check_peek(this, filename, mode);
}
}; // class ifstream
class ofstream
: public std::ofstream
{
public:
ofstream() = default;
ofstream(const std::string& filename, std::ios_base::openmode mode = std::ios_base::out)
{
open(filename, mode);
}
void open(const std::string& filename, std::ios_base::openmode mode = std::ios_base::out)
{
mode |= std::ios_base::out;
exceptions(std::ios_base::badbit);
detail::static_method_holder::check_mode(filename, mode);
std::ofstream::open(filename, mode);
detail::static_method_holder::check_open(this, filename, mode);
}
}; // class ofstream
class fstream
: public std::fstream
{
public:
fstream() = default;
fstream(const std::string& filename, std::ios_base::openmode mode = std::ios_base::in)
{
open(filename, mode);
}
void open(const std::string& filename, std::ios_base::openmode mode = std::ios_base::in)
{
if (! (mode & std::ios_base::out)) mode |= std::ios_base::in;
exceptions(std::ios_base::badbit);
detail::static_method_holder::check_mode(filename, mode);
std::fstream::open(filename, mode);
detail::static_method_holder::check_open(this, filename, mode);
detail::static_method_holder::check_peek(this, filename, mode);
}
}; // class fstream
} // namespace strict_fstream
<commit_msg>seems like there actually is a semi-standard for this<commit_after>#pragma once
#include <cassert>
#include <fstream>
#include <cstring>
#include <string>
/**
* This namespace defines wrappers for std::ifstream, std::ofstream, and
* std::fstream objects. The wrappers perform the following steps:
* - check the open modes make sense
* - check that the call to open() is successful
* - (for input streams) check that the opened file is peek-able
* - turn on the badbit in the exception mask
*/
namespace strict_fstream
{
// Help people out a bit, it seems like this is a common recommenation since
// musl breaks all over the place.
#if defined(__NEED_size_t) && !defined(__MUSL__)
#warning "It seems to be recommended to patch in a define for __MUSL__ if you use musl globally: https://www.openwall.com/lists/musl/2013/02/10/5"
#define __MUSL__
#endif
// Workaround for broken musl implementation
// Since musl insists that they are perfectly compatible, ironically enough,
// they don't officially have a __musl__ or similar. But __NEED_size_t is defined in their
// relevant header (and not in working implementations), so we can use that.
#ifdef __MUSL__
#define BROKEN_GNU_STRERROR_R
#warning "Working around broken strerror_r() implementation in musl, remove when musl is fixed"
#endif
// Non-gnu variants of strerror_* don't necessarily null-terminate if
// truncating, so we have to do things manually.
inline std::string &trim_to_null(std::string &buff)
{
const std::string::size_type pos = buff.find('\0');
if (pos == std::string::npos) {
buff += " [...]"; // it has been truncated
} else {
buff.resize(pos);
}
return buff;
}
/// Overload of error-reporting function, to enable use with VS.
/// Ref: http://stackoverflow.com/a/901316/717706
static std::string strerror()
{
std::string buff(256, '\0');
#ifdef _WIN32
if (strerror_s(buff.data(), buff.size(), errno) != 0) {
return trim_to_null(buff);
} else {
return "Unknown error";
}
#elif ((_POSIX_C_SOURCE >= 200112L || _XOPEN_SOURCE >= 600 || defined(__APPLE__)) && ! _GNU_SOURCE) || defined(BROKEN_GNU_STRERROR_R)
// XSI-compliant strerror_r()
if (strerror_r(errno, buff.data(), buff.size()) == 0) {
return trim_to_null(buff);
} else {
return "Unknown error";
}
#else
// GNU-specific strerror_r()
char * p = strerror_r(errno, &buff[0], buff.size());
return std::string(p, std::strlen(p));
#endif
}
/// Exception class thrown by failed operations.
class Exception
: public std::exception
{
public:
Exception(const std::string& msg) : _msg(msg) {}
const char * what() const noexcept { return _msg.c_str(); }
private:
std::string _msg;
}; // class Exception
namespace detail
{
struct static_method_holder
{
static std::string mode_to_string(std::ios_base::openmode mode)
{
static const int n_modes = 6;
static const std::ios_base::openmode mode_val_v[n_modes] =
{
std::ios_base::in,
std::ios_base::out,
std::ios_base::app,
std::ios_base::ate,
std::ios_base::trunc,
std::ios_base::binary
};
static const char * mode_name_v[n_modes] =
{
"in",
"out",
"app",
"ate",
"trunc",
"binary"
};
std::string res;
for (int i = 0; i < n_modes; ++i)
{
if (mode & mode_val_v[i])
{
res += (! res.empty()? "|" : "");
res += mode_name_v[i];
}
}
if (res.empty()) res = "none";
return res;
}
static void check_mode(const std::string& filename, std::ios_base::openmode mode)
{
if ((mode & std::ios_base::trunc) && ! (mode & std::ios_base::out))
{
throw Exception(std::string("strict_fstream: open('") + filename + "'): mode error: trunc and not out");
}
else if ((mode & std::ios_base::app) && ! (mode & std::ios_base::out))
{
throw Exception(std::string("strict_fstream: open('") + filename + "'): mode error: app and not out");
}
else if ((mode & std::ios_base::trunc) && (mode & std::ios_base::app))
{
throw Exception(std::string("strict_fstream: open('") + filename + "'): mode error: trunc and app");
}
}
static void check_open(std::ios * s_p, const std::string& filename, std::ios_base::openmode mode)
{
if (s_p->fail())
{
throw Exception(std::string("strict_fstream: open('")
+ filename + "'," + mode_to_string(mode) + "): open failed: "
+ strerror());
}
}
static void check_peek(std::istream * is_p, const std::string& filename, std::ios_base::openmode mode)
{
bool peek_failed = true;
try
{
is_p->peek();
peek_failed = is_p->fail();
}
catch (const std::ios_base::failure &) {}
if (peek_failed)
{
throw Exception(std::string("strict_fstream: open('")
+ filename + "'," + mode_to_string(mode) + "): peek failed: "
+ strerror());
}
is_p->clear();
}
}; // struct static_method_holder
} // namespace detail
class ifstream
: public std::ifstream
{
public:
ifstream() = default;
ifstream(const std::string& filename, std::ios_base::openmode mode = std::ios_base::in)
{
open(filename, mode);
}
void open(const std::string& filename, std::ios_base::openmode mode = std::ios_base::in)
{
mode |= std::ios_base::in;
exceptions(std::ios_base::badbit);
detail::static_method_holder::check_mode(filename, mode);
std::ifstream::open(filename, mode);
detail::static_method_holder::check_open(this, filename, mode);
detail::static_method_holder::check_peek(this, filename, mode);
}
}; // class ifstream
class ofstream
: public std::ofstream
{
public:
ofstream() = default;
ofstream(const std::string& filename, std::ios_base::openmode mode = std::ios_base::out)
{
open(filename, mode);
}
void open(const std::string& filename, std::ios_base::openmode mode = std::ios_base::out)
{
mode |= std::ios_base::out;
exceptions(std::ios_base::badbit);
detail::static_method_holder::check_mode(filename, mode);
std::ofstream::open(filename, mode);
detail::static_method_holder::check_open(this, filename, mode);
}
}; // class ofstream
class fstream
: public std::fstream
{
public:
fstream() = default;
fstream(const std::string& filename, std::ios_base::openmode mode = std::ios_base::in)
{
open(filename, mode);
}
void open(const std::string& filename, std::ios_base::openmode mode = std::ios_base::in)
{
if (! (mode & std::ios_base::out)) mode |= std::ios_base::in;
exceptions(std::ios_base::badbit);
detail::static_method_holder::check_mode(filename, mode);
std::fstream::open(filename, mode);
detail::static_method_holder::check_open(this, filename, mode);
detail::static_method_holder::check_peek(this, filename, mode);
}
}; // class fstream
} // namespace strict_fstream
<|endoftext|> |
<commit_before>//
// Copyright (C) 2005-2007 SIPez LLC
// Licensed to SIPfoundry under a Contributor Agreement.
//
// Copyright (C) 2005-2007 SIPfoundry Inc.
// Licensed by SIPfoundry under the LGPL license.
//
// $$
//////////////////////////////////////////////////////////////////////////////
// Author: Dan Petrie (dpetrie AT SIPez DOT com)
#include <cppunit/extensions/HelperMacros.h>
#include <cppunit/TestCase.h>
#include <mi/CpMediaInterfaceFactory.h>
#include <mi/CpMediaInterfaceFactoryFactory.h>
#include <mi/CpMediaInterface.h>
#include <os/OsTask.h>
#include <utl/UtlSList.h>
#include <utl/UtlInt.h>
#include <mp/MprFromFile.h>
#ifdef RTL_ENABLED
# include <rtl_macro.h>
RTL_DECLARE
#else
# define RTL_START(x)
# define RTL_BLOCK(x)
# define RTL_EVENT(x,y)
# define RTL_WRITE(x)
# define RTL_STOP
#endif
class StoreSignalNotification : public OsNotification
{
public:
StoreSignalNotification() {}
virtual ~StoreSignalNotification() {}
OsStatus signal(const intptr_t eventData)
{
//printf("Hit event %d\n", eventData);
UtlInt* pED = new UtlInt(eventData);
return (mEDataList.insert(pED) == pED) ?
OS_SUCCESS : OS_FAILED;
}
OsStatus popLastEvent(int& evtData)
{
OsStatus stat = OS_NOT_FOUND;
UtlInt* lastEData = (UtlInt*)mEDataList.get();
if(lastEData != NULL)
{
evtData = lastEData->getValue();
delete lastEData;
stat = OS_SUCCESS;
}
return stat;
}
// Data (public now)
UtlSList mEDataList;
private:
};
// Unittest for CpPhoneMediaInterface
class PlayAudioOldNotificationTest : public CppUnit::TestCase
{
CPPUNIT_TEST_SUITE(PlayAudioOldNotificationTest);
CPPUNIT_TEST(testRecordPlayback);
CPPUNIT_TEST_SUITE_END();
public:
CpMediaInterfaceFactory* mpMediaFactory;
PlayAudioOldNotificationTest()
{
};
virtual void setUp()
{
enableConsoleOutput(0);
mpMediaFactory = sipXmediaFactoryFactory(NULL);
}
virtual void tearDown()
{
sipxDestroyMediaFactoryFactory();
mpMediaFactory = NULL;
}
void testRecordPlayback()
{
RTL_START(4500000);
CPPUNIT_ASSERT(mpMediaFactory);
SdpCodecFactory* codecFactory = new SdpCodecFactory();
CPPUNIT_ASSERT(codecFactory);
int numCodecs;
SdpCodec** codecArray = NULL;
codecFactory->getCodecs(numCodecs, codecArray);
UtlString localRtpInterfaceAddress("127.0.0.1");
UtlString locale;
int tosOptions = 0;
UtlString stunServerAddress;
int stunOptions = 0;
int stunKeepAlivePeriodSecs = 25;
UtlString turnServerAddress;
int turnPort = 0 ;
UtlString turnUser;
UtlString turnPassword;
int turnKeepAlivePeriodSecs = 25;
bool enableIce = false ;
//enableConsoleOutput(1);
CpMediaInterface* mediaInterface =
mpMediaFactory->createMediaInterface(NULL, // public mapped RTP IP address
localRtpInterfaceAddress,
numCodecs,
codecArray,
locale,
tosOptions,
stunServerAddress,
stunOptions,
stunKeepAlivePeriodSecs,
turnServerAddress,
turnPort,
turnUser,
turnPassword,
turnKeepAlivePeriodSecs,
enableIce);
// Properties specific to a connection
int connectionId = -1;
CPPUNIT_ASSERT(mediaInterface->createConnection(connectionId, NULL) == OS_SUCCESS);
CPPUNIT_ASSERT(connectionId > 0);
mediaInterface->giveFocus() ;
int taskId;
OsTask::getCurrentTaskId(taskId);
// Record the entire "call" - all connections.
mediaInterface->recordChannelAudio(-1, "testRecordPlayback_call_recording.wav");
StoreSignalNotification playAudNote;
unsigned i;
for (i=0; i< 100; i++)
{
printf("Play record_prompt.wav taskId: %d\n",taskId);
mediaInterface->playAudio("short.wav",
false, //repeat
true, // local
false, //remote
false,
100,
&playAudNote);
OsTask::delay(250);
//enableConsoleOutput(0);
// Check via old OsNotification mechanism if the file finished playing.
// We should have 3 notifications:
// PLAYING(2), PLAY_STOPPED(1), PLAY_FINISHED(0)
// Check this.
printf("loopcnt %d: %d event(s) on play event queue: ", i, playAudNote.mEDataList.entries());
CPPUNIT_ASSERT_EQUAL(size_t(3), playAudNote.mEDataList.entries());
int evtData = -1;
CPPUNIT_ASSERT_EQUAL(OS_SUCCESS, playAudNote.popLastEvent(evtData));
CPPUNIT_ASSERT_EQUAL(int(MprFromFile::PLAYING), evtData);
printf("PLAYING, ");
evtData = -1;
CPPUNIT_ASSERT_EQUAL(OS_SUCCESS, playAudNote.popLastEvent(evtData));
CPPUNIT_ASSERT_EQUAL(int(MprFromFile::PLAY_STOPPED), evtData);
printf("PLAY_STOPPED, ");
evtData = -1;
CPPUNIT_ASSERT_EQUAL(OS_SUCCESS, playAudNote.popLastEvent(evtData));
CPPUNIT_ASSERT_EQUAL(int(MprFromFile::PLAY_FINISHED), evtData);
printf("PLAY_FINISHED\n");
mediaInterface->stopAudio() ;
}
mediaInterface->startTone(0, true, false) ;
OsTask::delay(100) ;
mediaInterface->stopTone() ;
OsTask::delay(100) ;
RTL_WRITE("testRecordPlayback.rtl");
RTL_STOP;
// Stop recording the "call" -- all connections.
mediaInterface->stopRecordChannelAudio(-1);
mediaInterface->deleteConnection(connectionId) ;
// delete codecs set
for ( numCodecs--; numCodecs>=0; numCodecs--)
{
delete codecArray[numCodecs];
}
delete[] codecArray;
delete codecFactory ;
// delete interface
mediaInterface->release();
}
};
CPPUNIT_TEST_SUITE_REGISTRATION(PlayAudioOldNotificationTest);
<commit_msg>Fix compilation bug in PlayAudioOldNotificationTest caused by change in codec loading method.<commit_after>//
// Copyright (C) 2005-2007 SIPez LLC
// Licensed to SIPfoundry under a Contributor Agreement.
//
// Copyright (C) 2005-2007 SIPfoundry Inc.
// Licensed by SIPfoundry under the LGPL license.
//
// $$
//////////////////////////////////////////////////////////////////////////////
// Author: Dan Petrie (dpetrie AT SIPez DOT com)
#include <cppunit/extensions/HelperMacros.h>
#include <cppunit/TestCase.h>
#include <mi/CpMediaInterfaceFactory.h>
#include <mi/CpMediaInterfaceFactoryFactory.h>
#include <mi/CpMediaInterface.h>
#include <os/OsTask.h>
#include <utl/UtlSList.h>
#include <utl/UtlInt.h>
#include <mp/MprFromFile.h>
#ifdef RTL_ENABLED
# include <rtl_macro.h>
RTL_DECLARE
#else
# define RTL_START(x)
# define RTL_BLOCK(x)
# define RTL_EVENT(x,y)
# define RTL_WRITE(x)
# define RTL_STOP
#endif
class StoreSignalNotification : public OsNotification
{
public:
StoreSignalNotification() {}
virtual ~StoreSignalNotification() {}
OsStatus signal(const intptr_t eventData)
{
//printf("Hit event %d\n", eventData);
UtlInt* pED = new UtlInt(eventData);
return (mEDataList.insert(pED) == pED) ?
OS_SUCCESS : OS_FAILED;
}
OsStatus popLastEvent(int& evtData)
{
OsStatus stat = OS_NOT_FOUND;
UtlInt* lastEData = (UtlInt*)mEDataList.get();
if(lastEData != NULL)
{
evtData = lastEData->getValue();
delete lastEData;
stat = OS_SUCCESS;
}
return stat;
}
// Data (public now)
UtlSList mEDataList;
private:
};
// Unittest for CpPhoneMediaInterface
class PlayAudioOldNotificationTest : public CppUnit::TestCase
{
CPPUNIT_TEST_SUITE(PlayAudioOldNotificationTest);
CPPUNIT_TEST(testRecordPlayback);
CPPUNIT_TEST_SUITE_END();
public:
CpMediaInterfaceFactory* mpMediaFactory;
PlayAudioOldNotificationTest()
{
};
virtual void setUp()
{
enableConsoleOutput(0);
mpMediaFactory = sipXmediaFactoryFactory(NULL);
}
virtual void tearDown()
{
sipxDestroyMediaFactoryFactory();
mpMediaFactory = NULL;
}
void testRecordPlayback()
{
RTL_START(4500000);
CPPUNIT_ASSERT(mpMediaFactory);
SdpCodecList* codecFactory = new SdpCodecList();
CPPUNIT_ASSERT(codecFactory);
int numCodecs;
SdpCodec** codecArray = NULL;
codecFactory->getCodecs(numCodecs, codecArray);
UtlString localRtpInterfaceAddress("127.0.0.1");
UtlString locale;
int tosOptions = 0;
UtlString stunServerAddress;
int stunOptions = 0;
int stunKeepAlivePeriodSecs = 25;
UtlString turnServerAddress;
int turnPort = 0 ;
UtlString turnUser;
UtlString turnPassword;
int turnKeepAlivePeriodSecs = 25;
bool enableIce = false ;
//enableConsoleOutput(1);
CpMediaInterface* mediaInterface =
mpMediaFactory->createMediaInterface(NULL, // public mapped RTP IP address
localRtpInterfaceAddress,
numCodecs,
codecArray,
locale,
tosOptions,
stunServerAddress,
stunOptions,
stunKeepAlivePeriodSecs,
turnServerAddress,
turnPort,
turnUser,
turnPassword,
turnKeepAlivePeriodSecs,
enableIce);
// Properties specific to a connection
int connectionId = -1;
CPPUNIT_ASSERT(mediaInterface->createConnection(connectionId, NULL) == OS_SUCCESS);
CPPUNIT_ASSERT(connectionId > 0);
mediaInterface->giveFocus() ;
int taskId;
OsTask::getCurrentTaskId(taskId);
// Record the entire "call" - all connections.
mediaInterface->recordChannelAudio(-1, "testRecordPlayback_call_recording.wav");
StoreSignalNotification playAudNote;
unsigned i;
for (i=0; i< 100; i++)
{
printf("Play record_prompt.wav taskId: %d\n",taskId);
mediaInterface->playAudio("short.wav",
false, //repeat
true, // local
false, //remote
false,
100,
&playAudNote);
OsTask::delay(250);
//enableConsoleOutput(0);
// Check via old OsNotification mechanism if the file finished playing.
// We should have 3 notifications:
// PLAYING(2), PLAY_STOPPED(1), PLAY_FINISHED(0)
// Check this.
printf("loopcnt %d: %d event(s) on play event queue: ", i, playAudNote.mEDataList.entries());
CPPUNIT_ASSERT_EQUAL(size_t(3), playAudNote.mEDataList.entries());
int evtData = -1;
CPPUNIT_ASSERT_EQUAL(OS_SUCCESS, playAudNote.popLastEvent(evtData));
CPPUNIT_ASSERT_EQUAL(int(MprFromFile::PLAYING), evtData);
printf("PLAYING, ");
evtData = -1;
CPPUNIT_ASSERT_EQUAL(OS_SUCCESS, playAudNote.popLastEvent(evtData));
CPPUNIT_ASSERT_EQUAL(int(MprFromFile::PLAY_STOPPED), evtData);
printf("PLAY_STOPPED, ");
evtData = -1;
CPPUNIT_ASSERT_EQUAL(OS_SUCCESS, playAudNote.popLastEvent(evtData));
CPPUNIT_ASSERT_EQUAL(int(MprFromFile::PLAY_FINISHED), evtData);
printf("PLAY_FINISHED\n");
mediaInterface->stopAudio() ;
}
mediaInterface->startTone(0, true, false) ;
OsTask::delay(100) ;
mediaInterface->stopTone() ;
OsTask::delay(100) ;
RTL_WRITE("testRecordPlayback.rtl");
RTL_STOP;
// Stop recording the "call" -- all connections.
mediaInterface->stopRecordChannelAudio(-1);
mediaInterface->deleteConnection(connectionId) ;
// delete codecs set
for ( numCodecs--; numCodecs>=0; numCodecs--)
{
delete codecArray[numCodecs];
}
delete[] codecArray;
delete codecFactory ;
// delete interface
mediaInterface->release();
}
};
CPPUNIT_TEST_SUITE_REGISTRATION(PlayAudioOldNotificationTest);
<|endoftext|> |
<commit_before>/*
The rapidradio project
rapidradio command line tool
Author: Michal Okulski, the rapidradio team
Website: www.rapidradio.pl
Email: michal@rapidradio.pl
Inspired by AVR's RFM70 libraries.
------------------------------------------------------------------------------------
The MIT License (MIT)
Copyright (c) 2015 Michal Okulski (micas.pro)
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
------------------------------------------------------------------------------------
*/
#include <errno.h>
#include "rapidradio.h"
#include <cstring>
#include <iostream>
#include <vector>
#include <signal.h>
#include <stdio.h>
#include <utility>
#include <cstddef>
using namespace std;
using namespace rapidradio;
const uint8_t transmissionEndToken[] = {0xb3, 0x67, 0x2b, 0x26, 0xa2, 0x33, 0x43, 0x25, 0x80, 0x50, 0x80, 0xd5, 0x6e, 0xad, 0x94, 0x85,
0x0c, 0xec, 0xf8, 0x0f, 0x57, 0x8c, 0x48, 0xda, 0x95, 0x2d, 0x09, 0xbf, 0xc0, 0x04, 0xd5, 0x40};
sig_atomic_t signaled = 0;
static volatile bool _irq = false;
void irq (void)
{
fprintf(stderr, "IRQ!\n");
_irq = true;
}
void my_handler (int param)
{
signaled = 1;
}
struct Packet
{
uint32_t senderAddress;
uint32_t targetAddress;
uint32_t sensorId;
uint8_t dataLength;
uint8_t data[19];
};
struct Settings
{
uint8_t channel;
uint32_t targetAddress;
bool listen;
bool discard;
vector<pair<uint8_t, uint8_t> > registers;
bool ack;
bool verbose;
string byteSpecifier;
bool newlineAfterPacket;
bool packetNumbering;
};
bool parseParams(const int argc, const char **argv, Settings &settings)
{
settings.channel = 0;
settings.targetAddress = 0xCCCD1102UL;
settings.listen = false;
settings.discard = false;
settings.ack = true;
settings.verbose = false;
settings.byteSpecifier = "%c";
settings.newlineAfterPacket = false;
settings.packetNumbering = true;
for (int i=1; i<argc; i++)
{
if (argv[i] == string("-l"))
{
settings.listen = true;
}
else if (string(argv[i]).substr(0, 3) == "-a=")
{
string sadr = string(argv[i]).substr(3);
uint32_t adr = 0xCCCD1102UL;
if (sscanf(sadr.c_str(), "%x", &adr))
{
settings.targetAddress = adr;
}
}
else if (argv[i] == string("-i"))
{
settings.packetNumbering = false;
}
else if (string(argv[i]).substr(0, 3) == "-c=")
{
string schannel = string(argv[i]).substr(3);
int channel = 0;
if (sscanf(schannel.c_str(), "%i", &channel))
{
if (channel < 0) channel = 0;
if (channel > 83) channel = 83;
settings.channel = (uint8_t)channel;
}
}
else if (argv[i] == string("-nack"))
{
settings.ack = false;
}
else if (argv[i] == string("-ld"))
{
settings.listen = true;
settings.discard = true;
}
else if (argv[i] == string("-v"))
{
settings.verbose = true;
}
else if (argv[i] == string("-x"))
{
settings.byteSpecifier = "%.2X ";
}
else if (argv[i] == string("-n"))
{
settings.newlineAfterPacket = true;
}
else if (argv[i] == string("-?") || argv[i] == string("--help"))
{
return false;
}
else if (strlen(argv[i]) > 2 && argv[i][0] == '-' && argv[i][1] == 'r')
{
string cmd(argv[i] + 2);
size_t j = cmd.find('=');
if (j != string::npos)
{
string reg = cmd.substr(0, j);
string val = cmd.substr(j + 1);
int ireg, ival;
if (sscanf(reg.c_str(), "%i", &ireg) && sscanf(val.c_str(), "%i", &ival))
{
settings.registers.push_back(make_pair((uint8_t)ireg, (uint8_t)ival));
}
}
}
else
{
printf("Unknown parameter: %s\n", argv[i]);
return false;
}
}
return true;
}
void usage()
{
printf("rapidradio command-line tool\n\n");
printf("Usage:\n");
printf("sudo ./rapidradio [-l] [-ld] [-v] [-x] [-n] [-i] [-a=4_byte_hex_address] [-c=channel] [-nack] [-rN=1_byte_value]\n\n");
printf("-l\t\t\tListen mode - rapidradio will listen for incomming packets send to address specified by -a and channel set by -c.\n");
printf("-ld\t\t\tListen mode with discarded output - rapidradio will just print a dot '.' every ~10KiB received.\n");
printf("-v\t\t\tVerbose output.\n");
printf("-x\t\t\tPrint received bytes as 2-character hex - useful when debugging or sniffing received radio packets.\n");
printf("-n\t\t\tPrint a newline after each received packet. Useful together with the -x option.\n");
printf("-i\t\t\tIgnore packet number byte. Use for real raw transmissions.\n");
printf("-a=address\t\tIt's a 4-byte hex address of target device (when sending) or this device address (when listening). Example: -a=123456AB\n");
printf("-c=channel\t\tRadio channel number, a value from range: 1 to 83.\n");
printf("-nack\t\t\tDon't expect ACKs when sending. Speeds up transmission but gives no guarantee that all packets reach the target device.\n");
printf("-rN=value\t\tManual setting for particular RFM's register. E.g. usage: to change auto-retry behavior to just 2 retries and 4ms interval use: -r4=242 which means: put 242 (decimal) value into the RFM's register no. 4 (decimal).\n");
printf("\n");
}
void listen(Settings &settings)
{
if (settings.verbose) fprintf(stderr, "Listening...\n");
startListening(settings.channel, settings.targetAddress);
int32_t packetCount = -1;
uint8_t packetNumber = 0;
bool stop = false;
while (!signaled && !stop)
{
// active wait for IRQ signal - it's faster than any user level interrupt implementation... ;(
while (bcm2835_gpio_lev(IRQ) != LOW && !signaled)
{
delayMicroseconds(1);
}
_irq = false;
if (signaled) break;
uint8_t buff[32];
uint8_t length = 0;
// process all packets (if any)
// 'while' loop instead of just 'if' statement because the RFM7x can buffer up to 3 received packets
while (received(buff, length) && length)
{
++packetCount;
if (!settings.discard)
{
// check if the packet is the end transmission indicator
bool isEndPacket = true;
for(uint8_t i=0; i<length; i++)
{
if (buff[i] != transmissionEndToken[i])
{
isEndPacket = false;
break;
}
}
if (isEndPacket)
{
if (settings.verbose) fprintf(stderr, "Received transmission end packet.\n");
stop = true;
break;
}
if (settings.packetNumbering)
{
// check packet number if packets are missing
if (buff[0] > packetNumber)
{
if (settings.verbose) fprintf(stderr, "Missing packet(s). Got packet %u, expected %u\n", buff[0], packetNumber);
packetNumber = buff[0];
}
// check packet number to discard duplicated packets (rare, but possible when ACK is used)
else if (buff[0] < packetNumber)
{
if (settings.verbose) fprintf(stderr, "Duplicated packet %u, expected %u\n", buff[0], packetNumber);
packetCount--;
continue;
}
}
// skip first byte
for(uint8_t i = settings.packetNumbering ? 1 : 0; i<length; i++)
{
printf(settings.byteSpecifier.c_str(), buff[i]);
}
if (settings.newlineAfterPacket)
{
printf("\n");
}
packetNumber++;
}
// print dot '.' every ~10 KiB
if (settings.discard && (packetCount % 330U) == 0)
{
fprintf(stderr, ".");
}
}
}
}
void transmit(Settings &settings)
{
freopen(NULL, "rb", stdin);
uint32_t totalSent = 0;
vector<uint8_t> input;
while (!feof(stdin))
{
uint8_t buff[1024];
size_t read = fread(buff, 1, 1024, stdin);
input.insert(input.end(), buff, buff + read);
totalSent += (uint32_t)read;
}
if (settings.verbose) fprintf(stderr, "Read %uB (%uKiB, %uMiB) from input.\n", input.size(), input.size()/1024U, input.size()/(1024U*1024U));
TransmitResult result = send(settings.channel, settings.targetAddress, input.begin(), input.end(), settings.ack, settings.packetNumbering, 0);
if (result.status != Success)
{
fprintf(stderr, "An error occured while sending! (%u)\n", (int)result.status);
}
if (result.status == Success)
{
totalSent = result.bytesSent;
// send transmission end special packet
result = send(settings.channel, settings.targetAddress, transmissionEndToken, sizeof(transmissionEndToken), settings.ack);
if (result.status != Success)
{
fprintf(stderr, "An error occured while sending last packet! (%u)\n", (int)result.status);
}
}
if (settings.verbose) fprintf(stderr, "Sent %uB (%uKiB, %uMiB)\n", totalSent, totalSent/1024U, totalSent/(1024U*1024U));
}
int main(const int argc, const char **argv)
{
Settings settings;
if (!parseParams(argc, argv, settings))
{
usage();
return 1;
}
void (*prev_handler)(int);
prev_handler = signal (SIGINT, my_handler);
if (!bcm2835_init())
{
fprintf(stderr, "BCM2835 library init failed.\n");
return 1;
}
if (!init())
{
fprintf(stderr, "rapidradio init failed.\n");
return 1;
}
// use custom RFM7x register settings (if any)
for (size_t i=0;i<settings.registers.size();i++)
{
if (settings.verbose) fprintf(stderr, "REG%u = %.2X\n", settings.registers[i].first, settings.registers[i].second);
writeRegVal(RFM7x_CMD_WRITE_REG | settings.registers[i].first, settings.registers[i].second);
}
if (settings.verbose) fprintf(stderr, "Address = %.8X\nChannel = %u\nPacket numbering %s\n", settings.targetAddress, settings.channel, settings.packetNumbering ? "enabled" : "disabled");
turnOn();
if (settings.listen)
{
listen(settings);
}
else
{
transmit(settings);
}
turnOff();
bcm2835_spi_end();
bcm2835_close();
return 0;
}
<commit_msg>Changed default channel number and default address<commit_after>/*
The rapidradio project
rapidradio command line tool
Author: Michal Okulski, the rapidradio team
Website: www.rapidradio.pl
Email: michal@rapidradio.pl
Inspired by AVR's RFM70 libraries.
------------------------------------------------------------------------------------
The MIT License (MIT)
Copyright (c) 2015 Michal Okulski (micas.pro)
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
------------------------------------------------------------------------------------
*/
#include <errno.h>
#include "rapidradio.h"
#include <cstring>
#include <iostream>
#include <vector>
#include <signal.h>
#include <stdio.h>
#include <utility>
#include <cstddef>
using namespace std;
using namespace rapidradio;
const uint8_t transmissionEndToken[] = {0xb3, 0x67, 0x2b, 0x26, 0xa2, 0x33, 0x43, 0x25, 0x80, 0x50, 0x80, 0xd5, 0x6e, 0xad, 0x94, 0x85,
0x0c, 0xec, 0xf8, 0x0f, 0x57, 0x8c, 0x48, 0xda, 0x95, 0x2d, 0x09, 0xbf, 0xc0, 0x04, 0xd5, 0x40};
sig_atomic_t signaled = 0;
static volatile bool _irq = false;
void irq (void)
{
fprintf(stderr, "IRQ!\n");
_irq = true;
}
void my_handler (int param)
{
signaled = 1;
}
struct Packet
{
uint32_t senderAddress;
uint32_t targetAddress;
uint32_t sensorId;
uint8_t dataLength;
uint8_t data[19];
};
struct Settings
{
uint8_t channel;
uint32_t targetAddress;
bool listen;
bool discard;
vector<pair<uint8_t, uint8_t> > registers;
bool ack;
bool verbose;
string byteSpecifier;
bool newlineAfterPacket;
bool packetNumbering;
};
bool parseParams(const int argc, const char **argv, Settings &settings)
{
settings.channel = 55;
settings.targetAddress = 0xAABB0001UL;
settings.listen = false;
settings.discard = false;
settings.ack = true;
settings.verbose = false;
settings.byteSpecifier = "%c";
settings.newlineAfterPacket = false;
settings.packetNumbering = true;
for (int i=1; i<argc; i++)
{
if (argv[i] == string("-l"))
{
settings.listen = true;
}
else if (string(argv[i]).substr(0, 3) == "-a=")
{
string sadr = string(argv[i]).substr(3);
uint32_t adr = 0xCCCD1102UL;
if (sscanf(sadr.c_str(), "%x", &adr))
{
settings.targetAddress = adr;
}
}
else if (argv[i] == string("-i"))
{
settings.packetNumbering = false;
}
else if (string(argv[i]).substr(0, 3) == "-c=")
{
string schannel = string(argv[i]).substr(3);
int channel = 0;
if (sscanf(schannel.c_str(), "%i", &channel))
{
if (channel < 0) channel = 0;
if (channel > 83) channel = 83;
settings.channel = (uint8_t)channel;
}
}
else if (argv[i] == string("-nack"))
{
settings.ack = false;
}
else if (argv[i] == string("-ld"))
{
settings.listen = true;
settings.discard = true;
}
else if (argv[i] == string("-v"))
{
settings.verbose = true;
}
else if (argv[i] == string("-x"))
{
settings.byteSpecifier = "%.2X ";
}
else if (argv[i] == string("-n"))
{
settings.newlineAfterPacket = true;
}
else if (argv[i] == string("-?") || argv[i] == string("--help"))
{
return false;
}
else if (strlen(argv[i]) > 2 && argv[i][0] == '-' && argv[i][1] == 'r')
{
string cmd(argv[i] + 2);
size_t j = cmd.find('=');
if (j != string::npos)
{
string reg = cmd.substr(0, j);
string val = cmd.substr(j + 1);
int ireg, ival;
if (sscanf(reg.c_str(), "%i", &ireg) && sscanf(val.c_str(), "%i", &ival))
{
settings.registers.push_back(make_pair((uint8_t)ireg, (uint8_t)ival));
}
}
}
else
{
printf("Unknown parameter: %s\n", argv[i]);
return false;
}
}
return true;
}
void usage()
{
printf("rapidradio command-line tool\n\n");
printf("Usage:\n");
printf("sudo ./rapidradio [-l] [-ld] [-v] [-x] [-n] [-i] [-a=4_byte_hex_address] [-c=channel] [-nack] [-rN=1_byte_value]\n\n");
printf("-l\t\t\tListen mode - rapidradio will listen for incomming packets send to address specified by -a and channel set by -c.\n");
printf("-ld\t\t\tListen mode with discarded output - rapidradio will just print a dot '.' every ~10KiB received.\n");
printf("-v\t\t\tVerbose output.\n");
printf("-x\t\t\tPrint received bytes as 2-character hex - useful when debugging or sniffing received radio packets.\n");
printf("-n\t\t\tPrint a newline after each received packet. Useful together with the -x option.\n");
printf("-i\t\t\tIgnore packet number byte. Use for real raw transmissions.\n");
printf("-a=address\t\tIt's a 4-byte hex address of target device (when sending) or this device address (when listening). Example: -a=123456AB\n");
printf("-c=channel\t\tRadio channel number, a value from range: 1 to 83.\n");
printf("-nack\t\t\tDon't expect ACKs when sending. Speeds up transmission but gives no guarantee that all packets reach the target device.\n");
printf("-rN=value\t\tManual setting for particular RFM's register. E.g. usage: to change auto-retry behavior to just 2 retries and 4ms interval use: -r4=242 which means: put 242 (decimal) value into the RFM's register no. 4 (decimal).\n");
printf("\n");
}
void listen(Settings &settings)
{
if (settings.verbose) fprintf(stderr, "Listening...\n");
startListening(settings.channel, settings.targetAddress);
int32_t packetCount = -1;
uint8_t packetNumber = 0;
bool stop = false;
while (!signaled && !stop)
{
// active wait for IRQ signal - it's faster than any user level interrupt implementation... ;(
while (bcm2835_gpio_lev(IRQ) != LOW && !signaled)
{
delayMicroseconds(1);
}
_irq = false;
if (signaled) break;
uint8_t buff[32];
uint8_t length = 0;
// process all packets (if any)
// 'while' loop instead of just 'if' statement because the RFM7x can buffer up to 3 received packets
while (received(buff, length) && length)
{
++packetCount;
if (!settings.discard)
{
// check if the packet is the end transmission indicator
bool isEndPacket = true;
for(uint8_t i=0; i<length; i++)
{
if (buff[i] != transmissionEndToken[i])
{
isEndPacket = false;
break;
}
}
if (isEndPacket)
{
if (settings.verbose) fprintf(stderr, "Received transmission end packet.\n");
stop = true;
break;
}
if (settings.packetNumbering)
{
// check packet number if packets are missing
if (buff[0] > packetNumber)
{
if (settings.verbose) fprintf(stderr, "Missing packet(s). Got packet %u, expected %u\n", buff[0], packetNumber);
packetNumber = buff[0];
}
// check packet number to discard duplicated packets (rare, but possible when ACK is used)
else if (buff[0] < packetNumber)
{
if (settings.verbose) fprintf(stderr, "Duplicated packet %u, expected %u\n", buff[0], packetNumber);
packetCount--;
continue;
}
}
// skip first byte
for(uint8_t i = settings.packetNumbering ? 1 : 0; i<length; i++)
{
printf(settings.byteSpecifier.c_str(), buff[i]);
}
if (settings.newlineAfterPacket)
{
printf("\n");
}
packetNumber++;
}
// print dot '.' every ~10 KiB
if (settings.discard && (packetCount % 330U) == 0)
{
fprintf(stderr, ".");
}
}
}
}
void transmit(Settings &settings)
{
freopen(NULL, "rb", stdin);
uint32_t totalSent = 0;
vector<uint8_t> input;
while (!feof(stdin))
{
uint8_t buff[1024];
size_t read = fread(buff, 1, 1024, stdin);
input.insert(input.end(), buff, buff + read);
totalSent += (uint32_t)read;
}
if (settings.verbose) fprintf(stderr, "Read %uB (%uKiB, %uMiB) from input.\n", input.size(), input.size()/1024U, input.size()/(1024U*1024U));
TransmitResult result = send(settings.channel, settings.targetAddress, input.begin(), input.end(), settings.ack, settings.packetNumbering, 0);
if (result.status != Success)
{
fprintf(stderr, "An error occured while sending! (%u)\n", (int)result.status);
}
if (result.status == Success)
{
totalSent = result.bytesSent;
// send transmission end special packet
result = send(settings.channel, settings.targetAddress, transmissionEndToken, sizeof(transmissionEndToken), settings.ack);
if (result.status != Success)
{
fprintf(stderr, "An error occured while sending last packet! (%u)\n", (int)result.status);
}
}
if (settings.verbose) fprintf(stderr, "Sent %uB (%uKiB, %uMiB)\n", totalSent, totalSent/1024U, totalSent/(1024U*1024U));
}
int main(const int argc, const char **argv)
{
Settings settings;
if (!parseParams(argc, argv, settings))
{
usage();
return 1;
}
void (*prev_handler)(int);
prev_handler = signal (SIGINT, my_handler);
if (!bcm2835_init())
{
fprintf(stderr, "BCM2835 library init failed.\n");
return 1;
}
if (!init())
{
fprintf(stderr, "rapidradio init failed.\n");
return 1;
}
// use custom RFM7x register settings (if any)
for (size_t i=0;i<settings.registers.size();i++)
{
if (settings.verbose) fprintf(stderr, "REG%u = %.2X\n", settings.registers[i].first, settings.registers[i].second);
writeRegVal(RFM7x_CMD_WRITE_REG | settings.registers[i].first, settings.registers[i].second);
}
if (settings.verbose) fprintf(stderr, "Address = %.8X\nChannel = %u\nPacket numbering %s\n", settings.targetAddress, settings.channel, settings.packetNumbering ? "enabled" : "disabled");
turnOn();
if (settings.listen)
{
listen(settings);
}
else
{
transmit(settings);
}
turnOff();
bcm2835_spi_end();
bcm2835_close();
return 0;
}
<|endoftext|> |
<commit_before>/*
* Copyright (c) 2007, Michael Feathers, James Grenning and Bas Vodde
* 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 <organization> 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 EARLIER MENTIONED AUTHORS ``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 <copyright holder> 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 "TestHarness.h"
#include "MockTestOutput.h"
#include "MemoryLeakWarningPlugin.h"
#include "GenericTest.h"
static char* arrayToLeak1;
static char* arrayToLeak2;
static long* nonArrayToLeak;
TEST_GROUP(MemoryLeakWarningTest)
{
MemoryLeakWarningPlugin* memPlugin;
MemoryLeakWarning* prevMemWarning;
GenericTestFixture* fixture;
TEST_SETUP()
{
fixture = new GenericTestFixture();
prevMemWarning = MemoryLeakWarning::_latest;
memPlugin = new MemoryLeakWarningPlugin;
fixture->registry->installPlugin(memPlugin);
arrayToLeak1 = 0;
arrayToLeak2 = 0;
nonArrayToLeak = 0;
}
TEST_TEARDOWN()
{
delete fixture;
delete memPlugin;
MemoryLeakWarning::_latest = prevMemWarning;
if (arrayToLeak1) delete [] arrayToLeak1;
if (arrayToLeak2) delete [] arrayToLeak2;
if (nonArrayToLeak) delete nonArrayToLeak;
}
};
void _testExpectOneLeak()
{
EXPECT_N_LEAKS(1);
arrayToLeak1 = new char[100];
}
TEST(MemoryLeakWarningTest, Ignore1)
{
fixture->setTestFunction(_testExpectOneLeak);
fixture->runAllTests();
LONGS_EQUAL(0, fixture->getFailureCount());
}
void _testTwoLeaks()
{
arrayToLeak2 = new char[10];
nonArrayToLeak = new long;
}
TEST(MemoryLeakWarningTest, TwoLeaks)
{
fixture->setTestFunction(_testTwoLeaks);
fixture->runAllTests();
LONGS_EQUAL(1, fixture->getFailureCount());
}
void _testIgnore2()
{
EXPECT_N_LEAKS(2);
arrayToLeak2 = new char[10];
nonArrayToLeak = new long;
}
TEST(MemoryLeakWarningTest, Ignore2)
{
fixture->setTestFunction(_testIgnore2);
fixture->runAllTests();
LONGS_EQUAL(0, fixture->getFailureCount());
}
<commit_msg>Slightly different interface<commit_after>/*
* Copyright (c) 2007, Michael Feathers, James Grenning and Bas Vodde
* 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 <organization> 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 EARLIER MENTIONED AUTHORS ``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 <copyright holder> 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 "TestHarness.h"
#include "MockTestOutput.h"
#include "MemoryLeakWarningPlugin.h"
#include "GenericTest.h"
static char* arrayToLeak1;
static char* arrayToLeak2;
static long* nonArrayToLeak;
TEST_GROUP(MemoryLeakWarningTest)
{
MemoryLeakWarningPlugin* memPlugin;
MemoryLeakWarning* prevMemWarning;
GenericTestFixture* fixture;
TEST_SETUP()
{
fixture = new GenericTestFixture();
prevMemWarning = MemoryLeakWarning::GetLatest();
memPlugin = new MemoryLeakWarningPlugin;
fixture->registry->installPlugin(memPlugin);
arrayToLeak1 = 0;
arrayToLeak2 = 0;
nonArrayToLeak = 0;
}
TEST_TEARDOWN()
{
delete fixture;
delete memPlugin;
MemoryLeakWarning::SetLatest(prevMemWarning);
if (arrayToLeak1) delete [] arrayToLeak1;
if (arrayToLeak2) delete [] arrayToLeak2;
if (nonArrayToLeak) delete nonArrayToLeak;
}
};
void _testExpectOneLeak()
{
EXPECT_N_LEAKS(1);
arrayToLeak1 = new char[100];
}
TEST(MemoryLeakWarningTest, Ignore1)
{
fixture->setTestFunction(_testExpectOneLeak);
fixture->runAllTests();
LONGS_EQUAL(0, fixture->getFailureCount());
}
void _testTwoLeaks()
{
arrayToLeak2 = new char[10];
nonArrayToLeak = new long;
}
TEST(MemoryLeakWarningTest, TwoLeaks)
{
fixture->setTestFunction(_testTwoLeaks);
fixture->runAllTests();
LONGS_EQUAL(1, fixture->getFailureCount());
}
void _testIgnore2()
{
EXPECT_N_LEAKS(2);
arrayToLeak2 = new char[10];
nonArrayToLeak = new long;
}
TEST(MemoryLeakWarningTest, Ignore2)
{
fixture->setTestFunction(_testIgnore2);
fixture->runAllTests();
LONGS_EQUAL(0, fixture->getFailureCount());
}
<|endoftext|> |
<commit_before>#include <fstream>
#include "system.hpp"
namespace System {
bool Printer_Base::uni_special(char ch) {
return (ch & 0xc0) == 0x80;
}
int Printer_Base::uni_strlen(const char *word) {
int len = 0;
for(; *word; word++) {
if(!uni_special(*word)) {
len++;
}
}
return len;
}
int Printer_Base::uni_strlen(const std::string &word) {
return uni_strlen(word.c_str());
}
int Printer_Base::strlen(const char *word) {
int len = 0;
bool escape = false, bracket = false;
for(; *word; word++) {
char ch = *word;
if(!uni_special(ch)) {
if(bracket) {
if(ch == 'm') {
bracket = escape = false;
}
} else if(escape) {
if(ch == '[') {
bracket = true;
}
} else if(ch == '\e') {
escape = true;
} else {
len++;
}
}
}
return len;
}
std::string Printer_Base::repeat(int w, char c) {
std::ostringstream oss;
oss << std::setw(w) << std::setfill(c);
return oss.str();
}
template<typename T>
std::string Printer_Base::stringify(const T &t) {
std::ostringstream oss;
oss << t;
return oss.str();
}
/*template<typename T1, typename T2, typename... TN>
std::string Printer_Base::stringify(const T1 &t1,
const T2 &t2, const TN &... tn) {
return stringify(t1) + " " + stringify(t2, tn...);
}
int Printer_Base::split(std::string const& line,
std::vector<std::string> &words) {
int wc = 0;
std::string word;
std::istringstream iss(line);
while(iss >> word) {
words.emplace_back(word);
wc++;
}
return wc;
}*/
}
<commit_msg>Removed stringify<commit_after>#include <fstream>
#include "system.hpp"
namespace System {
bool Printer_Base::uni_special(char ch) {
return (ch & 0xc0) == 0x80;
}
int Printer_Base::uni_strlen(const char *word) {
int len = 0;
for(; *word; word++) {
if(!uni_special(*word)) {
len++;
}
}
return len;
}
int Printer_Base::uni_strlen(const std::string &word) {
return uni_strlen(word.c_str());
}
int Printer_Base::strlen(const char *word) {
int len = 0;
bool escape = false, bracket = false;
for(; *word; word++) {
char ch = *word;
if(!uni_special(ch)) {
if(bracket) {
if(ch == 'm') {
bracket = escape = false;
}
} else if(escape) {
if(ch == '[') {
bracket = true;
}
} else if(ch == '\e') {
escape = true;
} else {
len++;
}
}
}
return len;
}
std::string Printer_Base::repeat(int w, char c) {
std::ostringstream oss;
oss << std::setw(w) << std::setfill(c);
return oss.str();
}
/*template<typename T>
std::string Printer_Base::stringify(const T &t) {
std::ostringstream oss;
oss << t;
return oss.str();
}
template<typename T1, typename T2, typename... TN>
std::string Printer_Base::stringify(const T1 &t1,
const T2 &t2, const TN &... tn) {
return stringify(t1) + " " + stringify(t2, tn...);
}
int Printer_Base::split(std::string const& line,
std::vector<std::string> &words) {
int wc = 0;
std::string word;
std::istringstream iss(line);
while(iss >> word) {
words.emplace_back(word);
wc++;
}
return wc;
}*/
}
<|endoftext|> |
<commit_before>/*
* Copyright (c) 2007, Michael Feathers, James Grenning and Bas Vodde
* 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 <organization> 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 EARLIER MENTIONED AUTHORS ``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 <copyright holder> 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 "CppUTest/TestHarness.h"
#include "CppUTest/TestRegistry.h"
#include "CppUTest/TestOutput.h"
#include "CppUTest/MemoryLeakWarningPlugin.h"
#include "CppUTest/MemoryLeakDetector.h"
#include "CppUTest/MemoryLeakAllocator.h"
#include "CppUTest/TestTestingFixture.h"
static char* leak1;
static long* leak2;
class DummyReporter: public MemoryLeakFailure
{
public:
virtual ~DummyReporter()
{
}
virtual void fail(char* /*fail_string*/)
{
}
};
static MemoryLeakDetector* detector;
static MemoryLeakWarningPlugin* memPlugin;
static DummyReporter dummy;
static MemoryLeakAllocator* allocator;
TEST_GROUP(MemoryLeakWarningTest)
{
TestTestingFixture* fixture;
void setup()
{
fixture = new TestTestingFixture();
detector = new MemoryLeakDetector();
allocator = new StandardNewAllocator;
detector->init(&dummy);
memPlugin = new MemoryLeakWarningPlugin("TestMemoryLeakWarningPlugin", detector);
fixture->registry_->installPlugin(memPlugin);
memPlugin->enable();
leak1 = 0;
leak2 = 0;
}
void teardown()
{
detector->deallocMemory(allocator, leak1);
detector->deallocMemory(allocator, leak2);
delete fixture;
delete memPlugin;
delete detector;
delete allocator;
}
};
void _testTwoLeaks()
{
leak1 = detector->allocMemory(allocator, 10);
;
leak2 = (long*) detector->allocMemory(allocator, 4);
}
TEST(MemoryLeakWarningTest, TwoLeaks)
{
fixture->setTestFunction(_testTwoLeaks);
fixture->runAllTests();
LONGS_EQUAL(1, fixture->getFailureCount());
fixture->assertPrintContains("Total number of leaks: 2");
}
void _testIgnore2()
{
memPlugin->expectLeaksInTest(2);
leak1 = detector->allocMemory(allocator, 10);
leak2 = (long*) detector->allocMemory(allocator, 4);
}
TEST(MemoryLeakWarningTest, Ignore2)
{
fixture->setTestFunction(_testIgnore2);
fixture->runAllTests();
LONGS_EQUAL(0, fixture->getFailureCount());
}
static void _failAndLeakMemory()
{
leak1 = detector->allocMemory(allocator, 10);
FAIL("");
}
TEST(MemoryLeakWarningTest, FailingTestDoesNotReportMemoryLeaks)
{
fixture->setTestFunction(_failAndLeakMemory);
fixture->runAllTests();
LONGS_EQUAL(1, fixture->getFailureCount());
}
<commit_msg><commit_after>/*
* Copyright (c) 2007, Michael Feathers, James Grenning and Bas Vodde
* 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 <organization> 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 EARLIER MENTIONED AUTHORS ``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 <copyright holder> 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 "CppUTest/TestHarness.h"
#include "CppUTest/TestRegistry.h"
#include "CppUTest/TestOutput.h"
#include "CppUTest/MemoryLeakWarningPlugin.h"
#include "CppUTest/MemoryLeakDetector.h"
#include "CppUTest/MemoryLeakAllocator.h"
#include "CppUTest/TestTestingFixture.h"
static char* leak1;
static long* leak2;
class DummyReporter: public MemoryLeakFailure
{
public:
virtual ~DummyReporter()
{
}
virtual void fail(char* /*fail_string*/)
{
}
};
static MemoryLeakDetector* detector;
static MemoryLeakWarningPlugin* memPlugin;
static DummyReporter dummy;
static MemoryLeakAllocator* allocator;
TEST_GROUP(MemoryLeakWarningTest)
{
TestTestingFixture* fixture;
void setup()
{
fixture = new TestTestingFixture();
detector = new MemoryLeakDetector();
allocator = new StandardNewAllocator;
detector->init(&dummy);
memPlugin = new MemoryLeakWarningPlugin("TestMemoryLeakWarningPlugin", detector);
fixture->registry_->installPlugin(memPlugin);
memPlugin->enable();
leak1 = 0;
leak2 = 0;
}
void teardown()
{
detector->deallocMemory(allocator, leak1);
detector->deallocMemory(allocator, leak2);
delete fixture;
delete memPlugin;
delete detector;
delete allocator;
}
};
void _testTwoLeaks()
{
leak1 = detector->allocMemory(allocator, 10);
leak2 = (long*) detector->allocMemory(allocator, 4);
}
TEST(MemoryLeakWarningTest, TwoLeaks)
{
fixture->setTestFunction(_testTwoLeaks);
fixture->runAllTests();
LONGS_EQUAL(1, fixture->getFailureCount());
fixture->assertPrintContains("Total number of leaks: 2");
}
void _testIgnore2()
{
memPlugin->expectLeaksInTest(2);
leak1 = detector->allocMemory(allocator, 10);
leak2 = (long*) detector->allocMemory(allocator, 4);
}
TEST(MemoryLeakWarningTest, Ignore2)
{
fixture->setTestFunction(_testIgnore2);
fixture->runAllTests();
LONGS_EQUAL(0, fixture->getFailureCount());
}
static void _failAndLeakMemory()
{
leak1 = detector->allocMemory(allocator, 10);
FAIL("");
}
TEST(MemoryLeakWarningTest, FailingTestDoesNotReportMemoryLeaks)
{
fixture->setTestFunction(_failAndLeakMemory);
fixture->runAllTests();
LONGS_EQUAL(1, fixture->getFailureCount());
}
<|endoftext|> |
<commit_before>/*
* The Apache Software License, Version 1.1
*
* Copyright (c) 1999-2000 The Apache Software Foundation. All rights
* reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* 3. The end-user documentation included with the redistribution,
* if any, must include the following acknowledgment:
* "This product includes software developed by the
* Apache Software Foundation (http://www.apache.org/)."
* Alternately, this acknowledgment may appear in the software itself,
* if and wherever such third-party acknowledgments normally appear.
*
* 4. The names "Xerces" and "Apache Software Foundation" must
* not be used to endorse or promote products derived from this
* software without prior written permission. For written
* permission, please contact apache\@apache.org.
*
* 5. Products derived from this software may not be called "Apache",
* nor may "Apache" appear in their name, without prior written
* permission of the Apache Software Foundation.
*
* THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED 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 APACHE SOFTWARE FOUNDATION OR
* ITS 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.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation, and was
* originally based on software copyright (c) 1999, International
* Business Machines, Inc., http://www.ibm.com . For more information
* on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*/
/*
* $Log$
* Revision 1.7 2000/03/02 19:55:46 roddey
* This checkin includes many changes done while waiting for the
* 1.1.0 code to be finished. I can't list them all here, but a list is
* available elsewhere.
*
* Revision 1.6 2000/02/06 07:48:36 rahulj
* Year 2K copyright swat.
*
* Revision 1.5 2000/01/26 19:35:57 roddey
* When the /Debug output format is used, it will spit out source offset
* data as well now.
*
* Revision 1.4 2000/01/21 23:58:06 roddey
* Initial move away from util streams was bad. Wide char APIs didn't allow enough
* control to do canonical output, so changed to use std short char APIs.
*
* Revision 1.2 2000/01/12 00:29:49 roddey
* Changes for the new URL and InputSource changes.
*
* Revision 1.1.1.1 1999/11/09 01:02:14 twl
* Initial checkin
*
* Revision 1.3 1999/11/08 20:42:25 rahul
* Swat for adding in Product name and CVS comment log variable.
*
*/
// ---------------------------------------------------------------------------
// Includes
// ---------------------------------------------------------------------------
#include <util/PlatformUtils.hpp>
#include <util/XMLString.hpp>
#include <util/XMLURL.hpp>
#include <internal/XMLScanner.hpp>
#include <validators/DTD/DTDValidator.hpp>
#include "ParserTest.hpp"
// ---------------------------------------------------------------------------
// Program entry point
// ---------------------------------------------------------------------------
int main(int argC, char** argV)
{
// Init the XML platform
try
{
XMLPlatformUtils::Initialize();
}
catch(const XMLException& toCatch)
{
cout << "Error during platform init! Message:\n"
<< StrX(toCatch.getMessage()) << endl;
return 1;
}
//
// Create our test parser object. This guy implements the internal event
// APIs and is plugged into the scanner.
//
TestParser parserTest;
// Figure out the parameters
bool doValidation = false;
bool doNamespaces = false;
bool keepGoing = false;
XMLCh* urlPath = 0;
for (int index = 1; index < argC; index++)
{
if (!XMLString::compareIString(argV[index], "/Debug"))
parserTest.setOutputType(OutputType_Debug);
else if (!XMLString::compareIString(argV[index], "/Validate"))
doValidation = true;
else if (!XMLString::compareIString(argV[index], "/Namespaces"))
{
doNamespaces = true;
parserTest.setDoNamespaces(true);
}
else if (!XMLString::compareIString(argV[index], "/XML"))
parserTest.setOutputType(OutputType_XML);
else if (!XMLString::compareIString(argV[index], "/IntDTD"))
parserTest.setShowIntDTD(true);
else if (!XMLString::compareIString(argV[index], "/ShowWarnings"))
parserTest.setShowWarnings(true);
else if (!XMLString::compareIString(argV[index], "/ShowErrLoc"))
parserTest.setShowErrLoc(true);
else if (!XMLString::compareIString(argV[index], "/JCCanon"))
parserTest.setOutputType(OutputType_JCCanon);
else if (!XMLString::compareIString(argV[index], "/SunCanon"))
parserTest.setOutputType(OutputType_SunCanon);
else if (!XMLString::compareIString(argV[index], "/KeepGoing"))
keepGoing = true;
else if (!XMLString::compareNIString(argV[index], "/URL=", 5))
urlPath = XMLString::transcode(&argV[index][5]);
else
cout << "Unknown parameter: " << argV[index] << endl;
}
// We have to have a URL to work on
if (!urlPath)
{
cout << "A URL must be provided, /URL=xxxx" << endl;
return 1;
}
//
// Create a validator of the correct type so that we can install it
// on the scanner.
//
// <TBD> Later, when Schema validators exist, we'll have a parameter
// to select one or the other
//
XMLValidator* validator = 0;
DTDValidator* dtdVal = new DTDValidator(&parserTest);
dtdVal->setDocTypeHandler(&parserTest);
validator = dtdVal;
// And now create the scanner and give it all the handlers
XMLScanner scanner
(
&parserTest
, 0
, &parserTest
, validator
);
// Set the scanner flags that we were told to
scanner.setDoValidation(doValidation);
scanner.setDoNamespaces(doNamespaces);
scanner.setExitOnFirstFatal(!keepGoing);
// Tell the parser about the scanner
parserTest.setScanner(&scanner);
try
{
scanner.scanDocument(urlPath);
}
catch(const XMLException& toCatch)
{
cout << "Exception during scan:\n "
<< StrX(toCatch.getMessage())
<< endl;
}
// And call the termination method
XMLPlatformUtils::Terminate();
return 0;
}
// ---------------------------------------------------------------------------
// StrX: Private helper methods
// ---------------------------------------------------------------------------
void StrX::transcode(const XMLCh* const toTranscode, const unsigned int len)
{
// Short circuit if its a null pointer
if (!toTranscode || (!toTranscode[0]))
{
fLocalForm = new char[1];
fLocalForm[0] = 0;
return;
}
// See if our XMLCh and wchar_t as the same on this platform
const bool isSameSize = (sizeof(XMLCh) == sizeof(wchar_t));
//
// Get the actual number of chars. If the passed len is zero, its null
// terminated. Else we have to use the len.
//
wchar_t realLen = (wchar_t)len;
if (!realLen)
{
//
// We cannot just assume we can use wcslen() because we don't know
// if our XMLCh is the same as wchar_t on this platform.
//
const XMLCh* tmpPtr = toTranscode;
while (*(tmpPtr++))
realLen++;
}
//
// If either the passed length was non-zero or our char sizes are not
// same, we have to use a temp buffer. Since this is common in these
// samples, we just do it anyway.
//
wchar_t* tmpSource = new wchar_t[realLen + 1];
if (isSameSize)
{
memcpy(tmpSource, toTranscode, realLen * sizeof(wchar_t));
}
else
{
for (unsigned int index = 0; index < realLen; index++)
tmpSource[index] = (wchar_t)toTranscode[index];
}
tmpSource[realLen] = 0;
// See now many chars we need to transcode this guy
const unsigned int targetLen = ::wcstombs(0, tmpSource, 0);
// Allocate out storage member
fLocalForm = new char[targetLen + 1];
//
// And transcode our temp source buffer to the local buffer. Cap it
// off since the converter won't do it (because the null is beyond
// where the target will fill up.)
//
::wcstombs(fLocalForm, tmpSource, targetLen);
fLocalForm[targetLen] = 0;
// Don't forget to delete our temp buffer
delete [] tmpSource;
}
<commit_msg>'Do nothing' comment change to test my ability to commit from home.<commit_after>/*
* The Apache Software License, Version 1.1
*
* Copyright (c) 1999-2000 The Apache Software Foundation. All rights
* reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* 3. The end-user documentation included with the redistribution,
* if any, must include the following acknowledgment:
* "This product includes software developed by the
* Apache Software Foundation (http://www.apache.org/)."
* Alternately, this acknowledgment may appear in the software itself,
* if and wherever such third-party acknowledgments normally appear.
*
* 4. The names "Xerces" and "Apache Software Foundation" must
* not be used to endorse or promote products derived from this
* software without prior written permission. For written
* permission, please contact apache\@apache.org.
*
* 5. Products derived from this software may not be called "Apache",
* nor may "Apache" appear in their name, without prior written
* permission of the Apache Software Foundation.
*
* THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED 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 APACHE SOFTWARE FOUNDATION OR
* ITS 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.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation, and was
* originally based on software copyright (c) 1999, International
* Business Machines, Inc., http://www.ibm.com . For more information
* on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*/
/*
* $Log$
* Revision 1.8 2000/06/22 04:20:59 roddey
* 'Do nothing' comment change to test my ability to commit
* from home.
*
* Revision 1.7 2000/03/02 19:55:46 roddey
* This checkin includes many changes done while waiting for the
* 1.1.0 code to be finished. I can't list them all here, but a list is
* available elsewhere.
*
* Revision 1.6 2000/02/06 07:48:36 rahulj
* Year 2K copyright swat.
*
* Revision 1.5 2000/01/26 19:35:57 roddey
* When the /Debug output format is used, it will spit out source offset
* data as well now.
*
* Revision 1.4 2000/01/21 23:58:06 roddey
* Initial move away from util streams was bad. Wide char APIs didn't allow enough
* control to do canonical output, so changed to use std short char APIs.
*
* Revision 1.2 2000/01/12 00:29:49 roddey
* Changes for the new URL and InputSource changes.
*
* Revision 1.1.1.1 1999/11/09 01:02:14 twl
* Initial checkin
*
* Revision 1.3 1999/11/08 20:42:25 rahul
* Swat for adding in Product name and CVS comment log variable.
*
*/
// ---------------------------------------------------------------------------
// Includes
// ---------------------------------------------------------------------------
#include <util/PlatformUtils.hpp>
#include <util/XMLString.hpp>
#include <util/XMLURL.hpp>
#include <internal/XMLScanner.hpp>
#include <validators/DTD/DTDValidator.hpp>
#include "ParserTest.hpp"
// ---------------------------------------------------------------------------
// Program entry point
// ---------------------------------------------------------------------------
int main(int argC, char** argV)
{
// Init the XML platform
try
{
XMLPlatformUtils::Initialize();
}
catch(const XMLException& toCatch)
{
cout << "Error during platform init! Message:\n"
<< StrX(toCatch.getMessage()) << endl;
return 1;
}
//
// Create our test parser object. This object implements the internal
// event APIs and is plugged into the scanner.
//
TestParser parserTest;
// Figure out the parameters
bool doValidation = false;
bool doNamespaces = false;
bool keepGoing = false;
XMLCh* urlPath = 0;
for (int index = 1; index < argC; index++)
{
if (!XMLString::compareIString(argV[index], "/Debug"))
parserTest.setOutputType(OutputType_Debug);
else if (!XMLString::compareIString(argV[index], "/Validate"))
doValidation = true;
else if (!XMLString::compareIString(argV[index], "/Namespaces"))
{
doNamespaces = true;
parserTest.setDoNamespaces(true);
}
else if (!XMLString::compareIString(argV[index], "/XML"))
parserTest.setOutputType(OutputType_XML);
else if (!XMLString::compareIString(argV[index], "/IntDTD"))
parserTest.setShowIntDTD(true);
else if (!XMLString::compareIString(argV[index], "/ShowWarnings"))
parserTest.setShowWarnings(true);
else if (!XMLString::compareIString(argV[index], "/ShowErrLoc"))
parserTest.setShowErrLoc(true);
else if (!XMLString::compareIString(argV[index], "/JCCanon"))
parserTest.setOutputType(OutputType_JCCanon);
else if (!XMLString::compareIString(argV[index], "/SunCanon"))
parserTest.setOutputType(OutputType_SunCanon);
else if (!XMLString::compareIString(argV[index], "/KeepGoing"))
keepGoing = true;
else if (!XMLString::compareNIString(argV[index], "/URL=", 5))
urlPath = XMLString::transcode(&argV[index][5]);
else
cout << "Unknown parameter: " << argV[index] << endl;
}
// We have to have a URL to work on
if (!urlPath)
{
cout << "A URL must be provided, /URL=xxxx" << endl;
return 1;
}
//
// Create a validator of the correct type so that we can install it
// on the scanner.
//
// <TBD> Later, when Schema validators exist, we'll have a parameter
// to select one or the other
//
XMLValidator* validator = 0;
DTDValidator* dtdVal = new DTDValidator(&parserTest);
dtdVal->setDocTypeHandler(&parserTest);
validator = dtdVal;
// And now create the scanner and give it all the handlers
XMLScanner scanner
(
&parserTest
, 0
, &parserTest
, validator
);
// Set the scanner flags that we were told to
scanner.setDoValidation(doValidation);
scanner.setDoNamespaces(doNamespaces);
scanner.setExitOnFirstFatal(!keepGoing);
// Tell the parser about the scanner
parserTest.setScanner(&scanner);
try
{
scanner.scanDocument(urlPath);
}
catch(const XMLException& toCatch)
{
cout << "Exception during scan:\n "
<< StrX(toCatch.getMessage())
<< endl;
}
// And call the termination method
XMLPlatformUtils::Terminate();
return 0;
}
// ---------------------------------------------------------------------------
// StrX: Private helper methods
// ---------------------------------------------------------------------------
void StrX::transcode(const XMLCh* const toTranscode, const unsigned int len)
{
// Short circuit if its a null pointer
if (!toTranscode || (!toTranscode[0]))
{
fLocalForm = new char[1];
fLocalForm[0] = 0;
return;
}
// See if our XMLCh and wchar_t as the same on this platform
const bool isSameSize = (sizeof(XMLCh) == sizeof(wchar_t));
//
// Get the actual number of chars. If the passed len is zero, its null
// terminated. Else we have to use the len.
//
wchar_t realLen = (wchar_t)len;
if (!realLen)
{
//
// We cannot just assume we can use wcslen() because we don't know
// if our XMLCh is the same as wchar_t on this platform.
//
const XMLCh* tmpPtr = toTranscode;
while (*(tmpPtr++))
realLen++;
}
//
// If either the passed length was non-zero or our char sizes are not
// same, we have to use a temp buffer. Since this is common in these
// samples, we just do it anyway.
//
wchar_t* tmpSource = new wchar_t[realLen + 1];
if (isSameSize)
{
memcpy(tmpSource, toTranscode, realLen * sizeof(wchar_t));
}
else
{
for (unsigned int index = 0; index < realLen; index++)
tmpSource[index] = (wchar_t)toTranscode[index];
}
tmpSource[realLen] = 0;
// See now many chars we need to transcode this guy
const unsigned int targetLen = ::wcstombs(0, tmpSource, 0);
// Allocate out storage member
fLocalForm = new char[targetLen + 1];
//
// And transcode our temp source buffer to the local buffer. Cap it
// off since the converter won't do it (because the null is beyond
// where the target will fill up.)
//
::wcstombs(fLocalForm, tmpSource, targetLen);
fLocalForm[targetLen] = 0;
// Don't forget to delete our temp buffer
delete [] tmpSource;
}
<|endoftext|> |
<commit_before>// Copyright (c) 2011-2016 The Bitcoin Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
// Unit tests for denial-of-service detection/prevention code
#include "chainparams.h"
#include "keystore.h"
#include "net.h"
#include "net_processing.h"
#include "pow.h"
#include "script/sign.h"
#include "serialize.h"
#include "util.h"
#include "validation.h"
#include "test/test_bitcoin.h"
#include <stdint.h>
#include <boost/assign/list_of.hpp> // for 'map_list_of()'
#include <boost/date_time/posix_time/posix_time_types.hpp>
#include <boost/foreach.hpp>
#include <boost/test/unit_test.hpp>
// Tests these internal-to-net_processing.cpp methods:
extern bool AddOrphanTx(const CTransactionRef& tx, NodeId peer);
extern void EraseOrphansFor(NodeId peer);
extern unsigned int LimitOrphanTxSize(unsigned int nMaxOrphans);
struct COrphanTx {
CTransactionRef tx;
NodeId fromPeer;
int64_t nTimeExpire;
};
extern std::map<uint256, COrphanTx> mapOrphanTransactions;
CService ip(uint32_t i)
{
struct in_addr s;
s.s_addr = i;
return CService(CNetAddr(s), Params().GetDefaultPort());
}
static NodeId id = 0;
BOOST_FIXTURE_TEST_SUITE(DoS_tests, TestingSetup)
BOOST_AUTO_TEST_CASE(DoS_banning)
{
std::atomic<bool> interruptDummy(false);
connman->ClearBanned();
CAddress addr1(ip(0xa0b0c001), NODE_NONE);
CNode dummyNode1(id++, NODE_NETWORK, 0, INVALID_SOCKET, addr1, 0, 0, "", true);
dummyNode1.SetSendVersion(PROTOCOL_VERSION);
GetNodeSignals().InitializeNode(&dummyNode1, *connman);
dummyNode1.nVersion = 1;
dummyNode1.fSuccessfullyConnected = true;
Misbehaving(dummyNode1.GetId(), 100); // Should get banned
SendMessages(&dummyNode1, *connman, interruptDummy);
BOOST_CHECK(connman->IsBanned(addr1));
BOOST_CHECK(!connman->IsBanned(ip(0xa0b0c001|0x0000ff00))); // Different IP, not banned
CAddress addr2(ip(0xa0b0c002), NODE_NONE);
CNode dummyNode2(id++, NODE_NETWORK, 0, INVALID_SOCKET, addr2, 1, 1, "", true);
dummyNode2.SetSendVersion(PROTOCOL_VERSION);
GetNodeSignals().InitializeNode(&dummyNode2, *connman);
dummyNode2.nVersion = 1;
dummyNode2.fSuccessfullyConnected = true;
Misbehaving(dummyNode2.GetId(), 50);
SendMessages(&dummyNode2, *connman, interruptDummy);
BOOST_CHECK(!connman->IsBanned(addr2)); // 2 not banned yet...
BOOST_CHECK(connman->IsBanned(addr1)); // ... but 1 still should be
Misbehaving(dummyNode2.GetId(), 50);
SendMessages(&dummyNode2, *connman, interruptDummy);
BOOST_CHECK(connman->IsBanned(addr2));
}
BOOST_AUTO_TEST_CASE(DoS_banscore)
{
std::atomic<bool> interruptDummy(false);
connman->ClearBanned();
ForceSetArg("-banscore", "111"); // because 11 is my favorite number
CAddress addr1(ip(0xa0b0c001), NODE_NONE);
CNode dummyNode1(id++, NODE_NETWORK, 0, INVALID_SOCKET, addr1, 3, 1, "", true);
dummyNode1.SetSendVersion(PROTOCOL_VERSION);
GetNodeSignals().InitializeNode(&dummyNode1, *connman);
dummyNode1.nVersion = 1;
dummyNode1.fSuccessfullyConnected = true;
Misbehaving(dummyNode1.GetId(), 100);
SendMessages(&dummyNode1, *connman, interruptDummy);
BOOST_CHECK(!connman->IsBanned(addr1));
Misbehaving(dummyNode1.GetId(), 10);
SendMessages(&dummyNode1, *connman, interruptDummy);
BOOST_CHECK(!connman->IsBanned(addr1));
Misbehaving(dummyNode1.GetId(), 1);
SendMessages(&dummyNode1, *connman, interruptDummy);
BOOST_CHECK(connman->IsBanned(addr1));
ForceSetArg("-banscore", std::to_string(DEFAULT_BANSCORE_THRESHOLD));
}
BOOST_AUTO_TEST_CASE(DoS_bantime)
{
std::atomic<bool> interruptDummy(false);
connman->ClearBanned();
int64_t nStartTime = GetTime();
SetMockTime(nStartTime); // Overrides future calls to GetTime()
CAddress addr(ip(0xa0b0c001), NODE_NONE);
CNode dummyNode(id++, NODE_NETWORK, 0, INVALID_SOCKET, addr, 4, 4, "", true);
dummyNode.SetSendVersion(PROTOCOL_VERSION);
GetNodeSignals().InitializeNode(&dummyNode, *connman);
dummyNode.nVersion = 1;
dummyNode.fSuccessfullyConnected = true;
Misbehaving(dummyNode.GetId(), 100);
SendMessages(&dummyNode, *connman, interruptDummy);
BOOST_CHECK(connman->IsBanned(addr));
SetMockTime(nStartTime+60*60);
BOOST_CHECK(connman->IsBanned(addr));
SetMockTime(nStartTime+60*60*24+1);
BOOST_CHECK(!connman->IsBanned(addr));
}
CTransactionRef RandomOrphan()
{
std::map<uint256, COrphanTx>::iterator it;
it = mapOrphanTransactions.lower_bound(GetRandHash());
if (it == mapOrphanTransactions.end())
it = mapOrphanTransactions.begin();
return it->second.tx;
}
BOOST_AUTO_TEST_CASE(DoS_mapOrphans)
{
CKey key;
key.MakeNewKey(true);
CBasicKeyStore keystore;
keystore.AddKey(key);
// 50 orphan transactions:
for (int i = 0; i < 50; i++)
{
CMutableTransaction tx;
tx.vin.resize(1);
tx.vin[0].prevout.n = 0;
tx.vin[0].prevout.hash = GetRandHash();
tx.vin[0].scriptSig << OP_1;
tx.vout.resize(1);
tx.vout[0].nValue = 1*CENT;
tx.vout[0].scriptPubKey = GetScriptForDestination(key.GetPubKey().GetID());
AddOrphanTx(MakeTransactionRef(tx), i);
}
// ... and 50 that depend on other orphans:
for (int i = 0; i < 50; i++)
{
CTransactionRef txPrev = RandomOrphan();
CMutableTransaction tx;
tx.vin.resize(1);
tx.vin[0].prevout.n = 0;
tx.vin[0].prevout.hash = txPrev->GetId();
tx.vout.resize(1);
tx.vout[0].nValue = 1*CENT;
tx.vout[0].scriptPubKey = GetScriptForDestination(key.GetPubKey().GetID());
SignSignature(keystore, *txPrev, tx, 0, SIGHASH_ALL);
AddOrphanTx(MakeTransactionRef(tx), i);
}
// This really-big orphan should be ignored:
for (int i = 0; i < 10; i++)
{
CTransactionRef txPrev = RandomOrphan();
CMutableTransaction tx;
tx.vout.resize(1);
tx.vout[0].nValue = 1*CENT;
tx.vout[0].scriptPubKey = GetScriptForDestination(key.GetPubKey().GetID());
tx.vin.resize(2777);
for (unsigned int j = 0; j < tx.vin.size(); j++)
{
tx.vin[j].prevout.n = j;
tx.vin[j].prevout.hash = txPrev->GetId();
}
SignSignature(keystore, *txPrev, tx, 0, SIGHASH_ALL);
// Re-use same signature for other inputs
// (they don't have to be valid for this test)
for (unsigned int j = 1; j < tx.vin.size(); j++)
tx.vin[j].scriptSig = tx.vin[0].scriptSig;
BOOST_CHECK(!AddOrphanTx(MakeTransactionRef(tx), i));
}
// Test EraseOrphansFor:
for (NodeId i = 0; i < 3; i++)
{
size_t sizeBefore = mapOrphanTransactions.size();
EraseOrphansFor(i);
BOOST_CHECK(mapOrphanTransactions.size() < sizeBefore);
}
// Test LimitOrphanTxSize() function:
LimitOrphanTxSize(40);
BOOST_CHECK(mapOrphanTransactions.size() <= 40);
LimitOrphanTxSize(10);
BOOST_CHECK(mapOrphanTransactions.size() <= 10);
LimitOrphanTxSize(0);
BOOST_CHECK(mapOrphanTransactions.empty());
}
BOOST_AUTO_TEST_SUITE_END()
<commit_msg>Format DoS_tests.cpp<commit_after>// Copyright (c) 2011-2016 The Bitcoin Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
// Unit tests for denial-of-service detection/prevention code
#include "chainparams.h"
#include "keystore.h"
#include "net.h"
#include "net_processing.h"
#include "pow.h"
#include "script/sign.h"
#include "serialize.h"
#include "util.h"
#include "validation.h"
#include "test/test_bitcoin.h"
#include <stdint.h>
#include <boost/assign/list_of.hpp> // for 'map_list_of()'
#include <boost/date_time/posix_time/posix_time_types.hpp>
#include <boost/foreach.hpp>
#include <boost/test/unit_test.hpp>
// Tests these internal-to-net_processing.cpp methods:
extern bool AddOrphanTx(const CTransactionRef &tx, NodeId peer);
extern void EraseOrphansFor(NodeId peer);
extern unsigned int LimitOrphanTxSize(unsigned int nMaxOrphans);
struct COrphanTx {
CTransactionRef tx;
NodeId fromPeer;
int64_t nTimeExpire;
};
extern std::map<uint256, COrphanTx> mapOrphanTransactions;
CService ip(uint32_t i) {
struct in_addr s;
s.s_addr = i;
return CService(CNetAddr(s), Params().GetDefaultPort());
}
static NodeId id = 0;
BOOST_FIXTURE_TEST_SUITE(DoS_tests, TestingSetup)
BOOST_AUTO_TEST_CASE(DoS_banning) {
std::atomic<bool> interruptDummy(false);
connman->ClearBanned();
CAddress addr1(ip(0xa0b0c001), NODE_NONE);
CNode dummyNode1(id++, NODE_NETWORK, 0, INVALID_SOCKET, addr1, 0, 0, "",
true);
dummyNode1.SetSendVersion(PROTOCOL_VERSION);
GetNodeSignals().InitializeNode(&dummyNode1, *connman);
dummyNode1.nVersion = 1;
dummyNode1.fSuccessfullyConnected = true;
// Should get banned.
Misbehaving(dummyNode1.GetId(), 100);
SendMessages(&dummyNode1, *connman, interruptDummy);
BOOST_CHECK(connman->IsBanned(addr1));
// Different IP, not banned.
BOOST_CHECK(!connman->IsBanned(ip(0xa0b0c001 | 0x0000ff00)));
CAddress addr2(ip(0xa0b0c002), NODE_NONE);
CNode dummyNode2(id++, NODE_NETWORK, 0, INVALID_SOCKET, addr2, 1, 1, "",
true);
dummyNode2.SetSendVersion(PROTOCOL_VERSION);
GetNodeSignals().InitializeNode(&dummyNode2, *connman);
dummyNode2.nVersion = 1;
dummyNode2.fSuccessfullyConnected = true;
Misbehaving(dummyNode2.GetId(), 50);
SendMessages(&dummyNode2, *connman, interruptDummy);
// 2 not banned yet...
BOOST_CHECK(!connman->IsBanned(addr2));
// ... but 1 still should be.
BOOST_CHECK(connman->IsBanned(addr1));
Misbehaving(dummyNode2.GetId(), 50);
SendMessages(&dummyNode2, *connman, interruptDummy);
BOOST_CHECK(connman->IsBanned(addr2));
}
BOOST_AUTO_TEST_CASE(DoS_banscore) {
std::atomic<bool> interruptDummy(false);
connman->ClearBanned();
// because 11 is my favorite number.
ForceSetArg("-banscore", "111");
CAddress addr1(ip(0xa0b0c001), NODE_NONE);
CNode dummyNode1(id++, NODE_NETWORK, 0, INVALID_SOCKET, addr1, 3, 1, "",
true);
dummyNode1.SetSendVersion(PROTOCOL_VERSION);
GetNodeSignals().InitializeNode(&dummyNode1, *connman);
dummyNode1.nVersion = 1;
dummyNode1.fSuccessfullyConnected = true;
Misbehaving(dummyNode1.GetId(), 100);
SendMessages(&dummyNode1, *connman, interruptDummy);
BOOST_CHECK(!connman->IsBanned(addr1));
Misbehaving(dummyNode1.GetId(), 10);
SendMessages(&dummyNode1, *connman, interruptDummy);
BOOST_CHECK(!connman->IsBanned(addr1));
Misbehaving(dummyNode1.GetId(), 1);
SendMessages(&dummyNode1, *connman, interruptDummy);
BOOST_CHECK(connman->IsBanned(addr1));
ForceSetArg("-banscore", std::to_string(DEFAULT_BANSCORE_THRESHOLD));
}
BOOST_AUTO_TEST_CASE(DoS_bantime) {
std::atomic<bool> interruptDummy(false);
connman->ClearBanned();
int64_t nStartTime = GetTime();
// Overrides future calls to GetTime()
SetMockTime(nStartTime);
CAddress addr(ip(0xa0b0c001), NODE_NONE);
CNode dummyNode(id++, NODE_NETWORK, 0, INVALID_SOCKET, addr, 4, 4, "",
true);
dummyNode.SetSendVersion(PROTOCOL_VERSION);
GetNodeSignals().InitializeNode(&dummyNode, *connman);
dummyNode.nVersion = 1;
dummyNode.fSuccessfullyConnected = true;
Misbehaving(dummyNode.GetId(), 100);
SendMessages(&dummyNode, *connman, interruptDummy);
BOOST_CHECK(connman->IsBanned(addr));
SetMockTime(nStartTime + 60 * 60);
BOOST_CHECK(connman->IsBanned(addr));
SetMockTime(nStartTime + 60 * 60 * 24 + 1);
BOOST_CHECK(!connman->IsBanned(addr));
}
CTransactionRef RandomOrphan() {
std::map<uint256, COrphanTx>::iterator it;
it = mapOrphanTransactions.lower_bound(GetRandHash());
if (it == mapOrphanTransactions.end()) it = mapOrphanTransactions.begin();
return it->second.tx;
}
BOOST_AUTO_TEST_CASE(DoS_mapOrphans) {
CKey key;
key.MakeNewKey(true);
CBasicKeyStore keystore;
keystore.AddKey(key);
// 50 orphan transactions:
for (int i = 0; i < 50; i++) {
CMutableTransaction tx;
tx.vin.resize(1);
tx.vin[0].prevout.n = 0;
tx.vin[0].prevout.hash = GetRandHash();
tx.vin[0].scriptSig << OP_1;
tx.vout.resize(1);
tx.vout[0].nValue = 1 * CENT;
tx.vout[0].scriptPubKey =
GetScriptForDestination(key.GetPubKey().GetID());
AddOrphanTx(MakeTransactionRef(tx), i);
}
// ... and 50 that depend on other orphans:
for (int i = 0; i < 50; i++) {
CTransactionRef txPrev = RandomOrphan();
CMutableTransaction tx;
tx.vin.resize(1);
tx.vin[0].prevout.n = 0;
tx.vin[0].prevout.hash = txPrev->GetId();
tx.vout.resize(1);
tx.vout[0].nValue = 1 * CENT;
tx.vout[0].scriptPubKey =
GetScriptForDestination(key.GetPubKey().GetID());
SignSignature(keystore, *txPrev, tx, 0, SIGHASH_ALL);
AddOrphanTx(MakeTransactionRef(tx), i);
}
// This really-big orphan should be ignored:
for (int i = 0; i < 10; i++) {
CTransactionRef txPrev = RandomOrphan();
CMutableTransaction tx;
tx.vout.resize(1);
tx.vout[0].nValue = 1 * CENT;
tx.vout[0].scriptPubKey =
GetScriptForDestination(key.GetPubKey().GetID());
tx.vin.resize(2777);
for (unsigned int j = 0; j < tx.vin.size(); j++) {
tx.vin[j].prevout.n = j;
tx.vin[j].prevout.hash = txPrev->GetId();
}
SignSignature(keystore, *txPrev, tx, 0, SIGHASH_ALL);
// Re-use same signature for other inputs
// (they don't have to be valid for this test)
for (unsigned int j = 1; j < tx.vin.size(); j++)
tx.vin[j].scriptSig = tx.vin[0].scriptSig;
BOOST_CHECK(!AddOrphanTx(MakeTransactionRef(tx), i));
}
// Test EraseOrphansFor:
for (NodeId i = 0; i < 3; i++) {
size_t sizeBefore = mapOrphanTransactions.size();
EraseOrphansFor(i);
BOOST_CHECK(mapOrphanTransactions.size() < sizeBefore);
}
// Test LimitOrphanTxSize() function:
LimitOrphanTxSize(40);
BOOST_CHECK(mapOrphanTransactions.size() <= 40);
LimitOrphanTxSize(10);
BOOST_CHECK(mapOrphanTransactions.size() <= 10);
LimitOrphanTxSize(0);
BOOST_CHECK(mapOrphanTransactions.empty());
}
BOOST_AUTO_TEST_SUITE_END()
<|endoftext|> |
<commit_before>// Copyright (c) 2015 The Bitcoin Core developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "chain.h"
#include "chainparams.h"
#include "pow.h"
#include "random.h"
#include "util.h"
#include "test/test_bitcoin.h"
#include <boost/test/unit_test.hpp>
using namespace std;
BOOST_FIXTURE_TEST_SUITE(pow_tests, BasicTestingSetup)
/* Test calculation of next difficulty target with no constraints applying */
BOOST_AUTO_TEST_CASE(get_next_work)
{
SelectParams(CBaseChainParams::MAIN);
const Consensus::Params& params = Params().GetConsensus();
int64_t nLastRetargetTime = 1435312481; // Block #1209599
CBlockIndex pindexLast;
pindexLast.nHeight = 1229759;
pindexLast.nTime = 1435797007; // Block #1229759
pindexLast.nBits = 0x1b0d6191;
BOOST_CHECK_EQUAL(CalculateNextWorkRequired(&pindexLast, nLastRetargetTime, params), 0x1d00d86a);
}
/* Test the constraint on the upper bound for next work */
BOOST_AUTO_TEST_CASE(get_next_work_pow_limit)
{
SelectParams(CBaseChainParams::MAIN);
const Consensus::Params& params = Params().GetConsensus();
int64_t nLastRetargetTime = 1401043267; // Block #0
CBlockIndex pindexLast;
pindexLast.nHeight = 2015;
pindexLast.nTime = 1405610669; // Block #2015
pindexLast.nBits = 0x1e01ffff;
BOOST_CHECK_EQUAL(CalculateNextWorkRequired(&pindexLast, nLastRetargetTime, params),0x1e01ffff;
}
/* Test the constraint on the lower bound for actual time taken */
BOOST_AUTO_TEST_CASE(get_next_work_lower_limit_actual)
{
SelectParams(CBaseChainParams::MAIN);
const Consensus::Params& params = Params().GetConsensus();
int64_t nLastRetargetTime = 1279008237; // Block #66528
CBlockIndex pindexLast;
pindexLast.nHeight = 68543;
pindexLast.nTime = 1279297671; // Block #68543
pindexLast.nBits = 0x1c05a3f4;
BOOST_CHECK_EQUAL(CalculateNextWorkRequired(&pindexLast, nLastRetargetTime, params), 0x1c0168fd);
}
/* Test the constraint on the upper bound for actual time taken */
BOOST_AUTO_TEST_CASE(get_next_work_upper_limit_actual)
{
SelectParams(CBaseChainParams::MAIN);
const Consensus::Params& params = Params().GetConsensus();
int64_t nLastRetargetTime = 1263163443; // NOTE: Not an actual block time
CBlockIndex pindexLast;
pindexLast.nHeight = 46367;
pindexLast.nTime = 1269211443; // Block #46367
pindexLast.nBits = 0x1c387f6f;
BOOST_CHECK_EQUAL(CalculateNextWorkRequired(&pindexLast, nLastRetargetTime, params), 0x1d00e1fd);
}
BOOST_AUTO_TEST_CASE(GetBlockProofEquivalentTime_test)
{
SelectParams(CBaseChainParams::MAIN);
const Consensus::Params& params = Params().GetConsensus();
std::vector<CBlockIndex> blocks(10000);
for (int i = 0; i < 10000; i++) {
blocks[i].pprev = i ? &blocks[i - 1] : NULL;
blocks[i].nHeight = i;
blocks[i].nTime = 1269211443 + i * params.nPowTargetSpacing;
blocks[i].nBits = 0x207fffff; /* target 0x7fffff000... */
blocks[i].nChainWork = i ? blocks[i - 1].nChainWork + GetBlockProof(blocks[i - 1]) : arith_uint256(0);
}
for (int j = 0; j < 1000; j++) {
CBlockIndex *p1 = &blocks[GetRand(10000)];
CBlockIndex *p2 = &blocks[GetRand(10000)];
CBlockIndex *p3 = &blocks[GetRand(10000)];
int64_t tdiff = GetBlockProofEquivalentTime(*p1, *p2, *p3, params);
BOOST_CHECK_EQUAL(tdiff, p1->GetBlockTime() - p2->GetBlockTime());
}
}
BOOST_AUTO_TEST_SUITE_END()
<commit_msg>get_next_work BOOST fix<commit_after>// Copyright (c) 2015 The Bitcoin Core developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "chain.h"
#include "chainparams.h"
#include "pow.h"
#include "random.h"
#include "util.h"
#include "test/test_bitcoin.h"
#include <boost/test/unit_test.hpp>
using namespace std;
BOOST_FIXTURE_TEST_SUITE(pow_tests, BasicTestingSetup)
/* Test calculation of next difficulty target with no constraints applying */
BOOST_AUTO_TEST_CASE(get_next_work)
{
SelectParams(CBaseChainParams::MAIN);
const Consensus::Params& params = Params().GetConsensus();
int64_t nLastRetargetTime = 1435312481; // Block #1209599
CBlockIndex pindexLast;
pindexLast.nHeight = 1229759;
pindexLast.nTime = 1435797007; // Block #1229759
pindexLast.nBits = 0x1b0d6191;
BOOST_CHECK_EQUAL(CalculateNextWorkRequired(&pindexLast, nLastRetargetTime, params), 0x1d00d86a);
}
/* Test the constraint on the upper bound for next work */
BOOST_AUTO_TEST_CASE(get_next_work_pow_limit)
{
SelectParams(CBaseChainParams::MAIN);
const Consensus::Params& params = Params().GetConsensus();
int64_t nLastRetargetTime = 1401043267; // Block #0
CBlockIndex pindexLast;
pindexLast.nHeight = 2015;
pindexLast.nTime = 1405610669; // Block #2015
pindexLast.nBits = 0x1e01ffff;
BOOST_CHECK_EQUAL(CalculateNextWorkRequired(&pindexLast, nLastRetargetTime, params), 0x1e01ffff);
}
/* Test the constraint on the lower bound for actual time taken */
BOOST_AUTO_TEST_CASE(get_next_work_lower_limit_actual)
{
SelectParams(CBaseChainParams::MAIN);
const Consensus::Params& params = Params().GetConsensus();
int64_t nLastRetargetTime = 1279008237; // Block #66528
CBlockIndex pindexLast;
pindexLast.nHeight = 68543;
pindexLast.nTime = 1279297671; // Block #68543
pindexLast.nBits = 0x1c05a3f4;
BOOST_CHECK_EQUAL(CalculateNextWorkRequired(&pindexLast, nLastRetargetTime, params), 0x1c0168fd);
}
/* Test the constraint on the upper bound for actual time taken */
BOOST_AUTO_TEST_CASE(get_next_work_upper_limit_actual)
{
SelectParams(CBaseChainParams::MAIN);
const Consensus::Params& params = Params().GetConsensus();
int64_t nLastRetargetTime = 1263163443; // NOTE: Not an actual block time
CBlockIndex pindexLast;
pindexLast.nHeight = 46367;
pindexLast.nTime = 1269211443; // Block #46367
pindexLast.nBits = 0x1c387f6f;
BOOST_CHECK_EQUAL(CalculateNextWorkRequired(&pindexLast, nLastRetargetTime, params), 0x1d00e1fd);
}
BOOST_AUTO_TEST_CASE(GetBlockProofEquivalentTime_test)
{
SelectParams(CBaseChainParams::MAIN);
const Consensus::Params& params = Params().GetConsensus();
std::vector<CBlockIndex> blocks(10000);
for (int i = 0; i < 10000; i++) {
blocks[i].pprev = i ? &blocks[i - 1] : NULL;
blocks[i].nHeight = i;
blocks[i].nTime = 1269211443 + i * params.nPowTargetSpacing;
blocks[i].nBits = 0x207fffff; /* target 0x7fffff000... */
blocks[i].nChainWork = i ? blocks[i - 1].nChainWork + GetBlockProof(blocks[i - 1]) : arith_uint256(0);
}
for (int j = 0; j < 1000; j++) {
CBlockIndex *p1 = &blocks[GetRand(10000)];
CBlockIndex *p2 = &blocks[GetRand(10000)];
CBlockIndex *p3 = &blocks[GetRand(10000)];
int64_t tdiff = GetBlockProofEquivalentTime(*p1, *p2, *p3, params);
BOOST_CHECK_EQUAL(tdiff, p1->GetBlockTime() - p2->GetBlockTime());
}
}
BOOST_AUTO_TEST_SUITE_END()
<|endoftext|> |
<commit_before>#include <QTest>
#include <QtCore>
#include <QHostInfo>
#include <tglobal.h>
#include <stdio.h>
static QByteArray randomString()
{
QByteArray data;
data.reserve(128);
#if QT_VERSION >= 0x040700
data.append(QByteArray::number(QDateTime::currentMSecsSinceEpoch()));
#else
QDateTime now = QDateTime::currentDateTime();
data.append(QByteArray::number(now.toTime_t()));
data.append(QByteArray::number(now.time().msec()));
#endif
data.append(QHostInfo::localHostName());
data.append(QByteArray::number(QCoreApplication::applicationPid()));
data.append(QByteArray::number((qulonglong)QThread::currentThread()));
data.append(QByteArray::number((qulonglong)qApp));
data.append(QByteArray::number(Tf::randXor128()));
return QCryptographicHash::hash(data, QCryptographicHash::Sha1).toHex();
}
static QByteArray randomString(int length)
{
static char ch[] = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
const int num = strlen(ch) - 1;
QByteArray ret;
ret.reserve(length);
for (int i = 0; i < length; ++i) {
ret += ch[Tf::random(num)];
}
return ret;
}
class Thread : public QThread
{
void run()
{
for (;;) {
Tf::randXor128();
yieldCurrentThread();
}
}
};
class TestRand : public QObject
{
Q_OBJECT
private slots:
void random_data();
void random();
void bench_data();
void bench();
void randomstring1();
void randomstring2();
};
void TestRand::random_data()
{
QTest::addColumn<int>("seed");
QTest::newRow("1") << 1;
QTest::newRow("2") << 10;
QTest::newRow("3") << 100;
}
void TestRand::random()
{
QFETCH(int, seed);
Tf::srandXor128(seed);
for (int i = 0; i < 10; ++i)
printf("rand: %u\n", Tf::randXor128());
}
void TestRand::bench_data()
{
Tf::srandXor128(1222);
for (int i = 0; i < 1000; ++i) {
(new Thread)->start();
}
Tf::msleep(100);
}
void TestRand::bench()
{
QBENCHMARK {
Tf::randXor128();
}
}
void TestRand::randomstring1()
{
QBENCHMARK {
randomString();
}
}
void TestRand::randomstring2()
{
QBENCHMARK {
randomString(20);
}
}
QTEST_APPLESS_MAIN(TestRand)
#include "main.moc"
/*
rand: 3656013425
rand: 503675675
rand: 4013738704
rand: 4013743934
rand: 1693336950
rand: 1359361875
rand: 1483021801
rand: 1370094836
rand: 1199228482
rand: 665247057
rand: 3656013434
rand: 503675664
rand: 4013738715
rand: 4013721446
rand: 1693336957
rand: 1359376139
rand: 1483021794
rand: 1399432767
rand: 1169867906
rand: 665224457
rand: 3656013332
rand: 503675774
rand: 4013738677
rand: 4013945878
rand: 1693336851
rand: 1359289467
rand: 1483021708
rand: 1223347666
rand: 1580916481
rand: 665187961
*/
<commit_msg>updated a test case of rand.<commit_after>#include <QTest>
#include <QtCore>
#include <QHostInfo>
#include <tglobal.h>
#include <stdio.h>
static QByteArray randomString()
{
QByteArray data;
data.reserve(128);
#if QT_VERSION >= 0x040700
data.append(QByteArray::number(QDateTime::currentMSecsSinceEpoch()));
#else
QDateTime now = QDateTime::currentDateTime();
data.append(QByteArray::number(now.toTime_t()));
data.append(QByteArray::number(now.time().msec()));
#endif
data.append(QHostInfo::localHostName());
data.append(QByteArray::number(QCoreApplication::applicationPid()));
data.append(QByteArray::number((qulonglong)QThread::currentThread()));
data.append(QByteArray::number((qulonglong)qApp));
data.append(QByteArray::number(Tf::randXor128()));
return QCryptographicHash::hash(data, QCryptographicHash::Sha1).toHex();
}
static QByteArray randomString(int length)
{
static char ch[] = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
const int num = strlen(ch) - 1;
QByteArray ret;
ret.reserve(length);
for (int i = 0; i < length; ++i) {
ret += ch[Tf::random(num)];
}
return ret;
}
class Thread : public QThread
{
void run()
{
for (;;) {
for (int i = 0; i < 20; ++i) {
Tf::randXor128();
}
QThread::yieldCurrentThread();
}
}
};
class TestRand : public QObject
{
Q_OBJECT
private slots:
void random_data();
void random();
void bench_data();
void bench();
void randomstring1();
void randomstring2();
};
void TestRand::random_data()
{
QTest::addColumn<int>("seed");
QTest::newRow("1") << 1;
QTest::newRow("2") << 10;
QTest::newRow("3") << 100;
}
void TestRand::random()
{
QFETCH(int, seed);
Tf::srandXor128(seed);
for (int i = 0; i < 10; ++i)
printf("rand: %u\n", Tf::randXor128());
}
void TestRand::bench_data()
{
Tf::srandXor128(1222);
for (int i = 0; i < 400; ++i) {
(new Thread)->start();
}
Tf::msleep(100);
}
void TestRand::bench()
{
QBENCHMARK {
Tf::randXor128();
}
}
void TestRand::randomstring1()
{
QBENCHMARK {
randomString();
}
}
void TestRand::randomstring2()
{
QBENCHMARK {
randomString(20);
}
}
QTEST_APPLESS_MAIN(TestRand)
#include "main.moc"
/*
rand: 3656013425
rand: 503675675
rand: 4013738704
rand: 4013743934
rand: 1693336950
rand: 1359361875
rand: 1483021801
rand: 1370094836
rand: 1199228482
rand: 665247057
rand: 3656013434
rand: 503675664
rand: 4013738715
rand: 4013721446
rand: 1693336957
rand: 1359376139
rand: 1483021794
rand: 1399432767
rand: 1169867906
rand: 665224457
rand: 3656013332
rand: 503675774
rand: 4013738677
rand: 4013945878
rand: 1693336851
rand: 1359289467
rand: 1483021708
rand: 1223347666
rand: 1580916481
rand: 665187961
*/
<|endoftext|> |
<commit_before>// @(#)root/core/meta:$Id$
// Author: Paul Russo 30/07/2012
/*************************************************************************
* Copyright (C) 1995-2000, Rene Brun and Fons Rademakers. *
* All rights reserved. *
* *
* For the licensing terms see $ROOTSYS/LICENSE. *
* For the list of contributors see $ROOTSYS/README/CREDITS. *
*************************************************************************/
//////////////////////////////////////////////////////////////////////////
// //
// TClingMethodInfo //
// //
// Emulation of the CINT MethodInfo class. //
// //
// The CINT C++ interpreter provides an interface to metadata about //
// a function through the MethodInfo class. This class provides the //
// same functionality, using an interface as close as possible to //
// MethodInfo but the typedef metadata comes from the Clang C++ //
// compiler, not CINT. //
// //
//////////////////////////////////////////////////////////////////////////
#include "TClingMethodInfo.h"
#include "TClingCallFunc.h"
#include "TClingClassInfo.h"
#include "TClingMethodArgInfo.h"
#include "Property.h"
#include "TClingProperty.h"
#include "TClingTypeInfo.h"
#include "TMetaUtils.h"
#include "cling/Interpreter/Interpreter.h"
#include "clang/AST/ASTContext.h"
#include "clang/AST/Decl.h"
#include "clang/AST/DeclCXX.h"
#include "clang/AST/Mangle.h"
#include "clang/AST/PrettyPrinter.h"
#include "clang/AST/Type.h"
#include "clang/Basic/IdentifierTable.h"
#include "llvm/Support/Casting.h"
#include "llvm/Support/raw_ostream.h"
#include "llvm/ADT/OwningPtr.h"
#include <string>
using namespace clang;
TClingMethodInfo::TClingMethodInfo(cling::Interpreter *interp,
TClingClassInfo *ci)
: fInterp(interp), fFirstTime(true), fContextIdx(0U), fTitle(""),
fSingleDecl(0)
{
if (!ci || !ci->IsValid()) {
return;
}
clang::DeclContext *dc =
llvm::cast<clang::DeclContext>(const_cast<clang::Decl*>(ci->GetDecl()));
dc->collectAllContexts(fContexts);
fIter = dc->decls_begin();
InternalNext();
fFirstTime = true;
}
TClingMethodInfo::TClingMethodInfo(cling::Interpreter *interp,
const clang::FunctionDecl *FD)
: fInterp(interp), fFirstTime(true), fContextIdx(0U), fTitle(""),
fSingleDecl(FD)
{
}
const clang::FunctionDecl *TClingMethodInfo::GetMethodDecl() const
{
if (!IsValid()) {
return 0;
}
if (fSingleDecl)
return fSingleDecl;
return llvm::dyn_cast<clang::FunctionDecl>(*fIter);
}
void TClingMethodInfo::CreateSignature(TString &signature) const
{
signature = "(";
if (!IsValid()) {
signature += ")";
return;
}
TClingMethodArgInfo arg(fInterp, this);
int idx = 0;
while (arg.Next()) {
if (idx) {
signature += ", ";
}
signature += arg.Type()->Name();
if (arg.Name() && strlen(arg.Name())) {
signature += " ";
signature += arg.Name();
}
if (arg.DefaultValue()) {
signature += " = ";
signature += arg.DefaultValue();
}
++idx;
}
signature += ")";
}
void TClingMethodInfo::Init(const clang::FunctionDecl *decl)
{
fContexts.clear();
fFirstTime = true;
fContextIdx = 0U;
fIter = clang::DeclContext::decl_iterator();
if (!decl) {
return;
}
clang::DeclContext *DC =
const_cast<clang::DeclContext *>(decl->getDeclContext());
DC = DC->getPrimaryContext();
DC->collectAllContexts(fContexts);
fIter = DC->decls_begin();
while (InternalNext()) {
if (*fIter == decl || *fIter == decl->getCanonicalDecl()) {
fFirstTime = true;
break;
}
}
}
void *TClingMethodInfo::InterfaceMethod() const
{
if (!IsValid()) {
return 0;
}
TClingCallFunc cf(fInterp);
cf.SetFunc(this);
return cf.InterfaceMethod();
}
bool TClingMethodInfo::IsValid() const
{
return fSingleDecl ? fSingleDecl : *fIter;
}
int TClingMethodInfo::NArg() const
{
if (!IsValid()) {
return -1;
}
const clang::FunctionDecl *fd = GetMethodDecl();
unsigned num_params = fd->getNumParams();
// Truncate cast to fit cint interface.
return static_cast<int>(num_params);
}
int TClingMethodInfo::NDefaultArg() const
{
if (!IsValid()) {
return -1;
}
const clang::FunctionDecl *fd = GetMethodDecl();
unsigned num_params = fd->getNumParams();
unsigned min_args = fd->getMinRequiredArguments();
unsigned defaulted_params = num_params - min_args;
// Truncate cast to fit cint interface.
return static_cast<int>(defaulted_params);
}
int TClingMethodInfo::InternalNext()
{
assert(!fSingleDecl && "This is not an iterator!");
if (!*fIter) {
// Iterator is already invalid.
return 0;
}
while (true) {
// Advance to the next decl.
if (fFirstTime) {
// The cint semantics are weird.
fFirstTime = false;
}
else {
++fIter;
}
// Fix it if we have gone past the end of the current decl context.
while (!*fIter) {
++fContextIdx;
if (fContextIdx >= fContexts.size()) {
// Iterator is now invalid.
return 0;
}
clang::DeclContext *dc = fContexts[fContextIdx];
fIter = dc->decls_begin();
if (*fIter) {
// Good, a non-empty context.
break;
}
}
// Return if this decl is a function or method.
if (llvm::isa<clang::FunctionDecl>(*fIter)) {
// Iterator is now valid.
return 1;
}
}
}
int TClingMethodInfo::Next()
{
return InternalNext();
}
long TClingMethodInfo::Property() const
{
if (!IsValid()) {
return 0L;
}
long property = 0L;
property |= G__BIT_ISCOMPILED;
const clang::FunctionDecl *fd = GetMethodDecl();
switch (fd->getAccess()) {
case clang::AS_public:
property |= G__BIT_ISPUBLIC;
break;
case clang::AS_protected:
property |= G__BIT_ISPROTECTED;
break;
case clang::AS_private:
property |= G__BIT_ISPRIVATE;
break;
case clang::AS_none:
// IMPOSSIBLE
break;
default:
// IMPOSSIBLE
break;
}
if (fd->getStorageClass() == clang::SC_Static) {
property |= G__BIT_ISSTATIC;
}
clang::QualType qt = fd->getResultType().getCanonicalType();
if (qt.isConstQualified()) {
property |= G__BIT_ISCONSTANT;
}
while (1) {
if (qt->isArrayType()) {
qt = llvm::cast<clang::ArrayType>(qt)->getElementType();
continue;
}
else if (qt->isReferenceType()) {
property |= G__BIT_ISREFERENCE;
qt = llvm::cast<clang::ReferenceType>(qt)->getPointeeType();
continue;
}
else if (qt->isPointerType()) {
property |= G__BIT_ISPOINTER;
if (qt.isConstQualified()) {
property |= G__BIT_ISPCONSTANT;
}
qt = llvm::cast<clang::PointerType>(qt)->getPointeeType();
continue;
}
else if (qt->isMemberPointerType()) {
qt = llvm::cast<clang::MemberPointerType>(qt)->getPointeeType();
continue;
}
break;
}
if (qt.isConstQualified()) {
property |= G__BIT_ISCONSTANT;
}
if (const clang::CXXMethodDecl *md =
llvm::dyn_cast<clang::CXXMethodDecl>(fd)) {
if (md->getTypeQualifiers() & clang::Qualifiers::Const) {
property |= G__BIT_ISCONSTANT | G__BIT_ISMETHCONSTANT;
}
if (md->isVirtual()) {
property |= G__BIT_ISVIRTUAL;
}
if (md->isPure()) {
property |= G__BIT_ISPUREVIRTUAL;
}
if (const clang::CXXConstructorDecl *cd =
llvm::dyn_cast<clang::CXXConstructorDecl>(md)) {
if (cd->isExplicit()) {
property |= G__BIT_ISEXPLICIT;
}
}
else if (const clang::CXXConversionDecl *cd =
llvm::dyn_cast<clang::CXXConversionDecl>(md)) {
if (cd->isExplicit()) {
property |= G__BIT_ISEXPLICIT;
}
}
}
return property;
}
TClingTypeInfo *TClingMethodInfo::Type() const
{
static TClingTypeInfo ti(fInterp);
ti.Init(clang::QualType());
if (!IsValid()) {
return &ti;
}
clang::QualType qt = GetMethodDecl()->getResultType();
ti.Init(qt);
return &ti;
}
const char *TClingMethodInfo::GetMangledName() const
{
if (!IsValid()) {
return 0;
}
const char *fname = 0;
static std::string mangled_name;
mangled_name.clear();
llvm::raw_string_ostream os(mangled_name);
llvm::OwningPtr<clang::MangleContext> mangle(GetMethodDecl()->getASTContext().
createMangleContext());
const clang::NamedDecl *nd = GetMethodDecl();
if (!nd) {
return 0;
}
if (!mangle->shouldMangleDeclName(nd)) {
clang::IdentifierInfo *ii = nd->getIdentifier();
fname = ii->getNameStart();
}
else {
if (const clang::CXXConstructorDecl *d =
llvm::dyn_cast<clang::CXXConstructorDecl>(nd)) {
//Ctor_Complete, // Complete object ctor
//Ctor_Base, // Base object ctor
//Ctor_CompleteAllocating // Complete object allocating ctor (unused)
mangle->mangleCXXCtor(d, clang::Ctor_Complete, os);
}
else if (const clang::CXXDestructorDecl *d =
llvm::dyn_cast<clang::CXXDestructorDecl>(nd)) {
//Dtor_Deleting, // Deleting dtor
//Dtor_Complete, // Complete object dtor
//Dtor_Base // Base object dtor
mangle->mangleCXXDtor(d, clang::Dtor_Deleting, os);
}
else {
mangle->mangleName(nd, os);
}
os.flush();
fname = mangled_name.c_str();
}
return fname;
}
const char *TClingMethodInfo::GetPrototype() const
{
if (!IsValid()) {
return 0;
}
static std::string buf;
buf.clear();
buf += Type()->Name();
buf += ' ';
std::string name;
clang::PrintingPolicy policy(GetMethodDecl()->getASTContext().getPrintingPolicy());
const clang::NamedDecl *nd = GetMethodDecl();
nd->getNameForDiagnostic(name, policy, /*Qualified=*/true);
buf += name;
buf += '(';
TClingMethodArgInfo arg(fInterp, this);
int idx = 0;
while (arg.Next()) {
if (idx) {
buf += ", ";
}
buf += arg.Type()->Name();
if (arg.Name() && strlen(arg.Name())) {
buf += ' ';
buf += arg.Name();
}
if (arg.DefaultValue()) {
buf += " = ";
buf += arg.DefaultValue();
}
++idx;
}
buf += ')';
return buf.c_str();
}
const char *TClingMethodInfo::Name() const
{
if (!IsValid()) {
return 0;
}
static std::string buf;
buf.clear();
clang::PrintingPolicy policy(GetMethodDecl()->getASTContext().getPrintingPolicy());
GetMethodDecl()->getNameForDiagnostic(buf, policy, /*Qualified=*/false);
return buf.c_str();
}
const char *TClingMethodInfo::TypeName() const
{
if (!IsValid()) {
// FIXME: Cint does not check!
return 0;
}
return Type()->Name();
}
const char *TClingMethodInfo::Title()
{
if (!IsValid()) {
return 0;
}
//NOTE: We can't use it as a cache due to the "thoughtful" self iterator
//if (fTitle.size())
// return fTitle.c_str();
// Try to get the comment either from the annotation or the header file if present
// Iterate over the redeclarations, we can have muliple definitions in the
// redecl chain (came from merging of pcms).
if (const FunctionDecl *FD = llvm::dyn_cast<FunctionDecl>(GetMethodDecl())) {
if ( (FD = ROOT::TMetaUtils::GetAnnotatedRedeclarable(FD)) ) {
if (AnnotateAttr *A = FD->getAttr<AnnotateAttr>()) {
fTitle = A->getAnnotation().str();
return fTitle.c_str();
}
}
}
// Try to get the comment from the header file if present
fTitle = ROOT::TMetaUtils::GetComment(*GetMethodDecl()).str();
return fTitle.c_str();
}
<commit_msg>No longer set the iterator in TClingMethodInfo::Init that takes a decl<commit_after>// @(#)root/core/meta:$Id$
// Author: Paul Russo 30/07/2012
/*************************************************************************
* Copyright (C) 1995-2000, Rene Brun and Fons Rademakers. *
* All rights reserved. *
* *
* For the licensing terms see $ROOTSYS/LICENSE. *
* For the list of contributors see $ROOTSYS/README/CREDITS. *
*************************************************************************/
//////////////////////////////////////////////////////////////////////////
// //
// TClingMethodInfo //
// //
// Emulation of the CINT MethodInfo class. //
// //
// The CINT C++ interpreter provides an interface to metadata about //
// a function through the MethodInfo class. This class provides the //
// same functionality, using an interface as close as possible to //
// MethodInfo but the typedef metadata comes from the Clang C++ //
// compiler, not CINT. //
// //
//////////////////////////////////////////////////////////////////////////
#include "TClingMethodInfo.h"
#include "TClingCallFunc.h"
#include "TClingClassInfo.h"
#include "TClingMethodArgInfo.h"
#include "Property.h"
#include "TClingProperty.h"
#include "TClingTypeInfo.h"
#include "TMetaUtils.h"
#include "cling/Interpreter/Interpreter.h"
#include "clang/AST/ASTContext.h"
#include "clang/AST/Decl.h"
#include "clang/AST/DeclCXX.h"
#include "clang/AST/Mangle.h"
#include "clang/AST/PrettyPrinter.h"
#include "clang/AST/Type.h"
#include "clang/Basic/IdentifierTable.h"
#include "llvm/Support/Casting.h"
#include "llvm/Support/raw_ostream.h"
#include "llvm/ADT/OwningPtr.h"
#include <string>
using namespace clang;
TClingMethodInfo::TClingMethodInfo(cling::Interpreter *interp,
TClingClassInfo *ci)
: fInterp(interp), fFirstTime(true), fContextIdx(0U), fTitle(""),
fSingleDecl(0)
{
if (!ci || !ci->IsValid()) {
return;
}
clang::DeclContext *dc =
llvm::cast<clang::DeclContext>(const_cast<clang::Decl*>(ci->GetDecl()));
dc->collectAllContexts(fContexts);
fIter = dc->decls_begin();
InternalNext();
fFirstTime = true;
}
TClingMethodInfo::TClingMethodInfo(cling::Interpreter *interp,
const clang::FunctionDecl *FD)
: fInterp(interp), fFirstTime(true), fContextIdx(0U), fTitle(""),
fSingleDecl(FD)
{
}
const clang::FunctionDecl *TClingMethodInfo::GetMethodDecl() const
{
if (!IsValid()) {
return 0;
}
if (fSingleDecl)
return fSingleDecl;
return llvm::dyn_cast<clang::FunctionDecl>(*fIter);
}
void TClingMethodInfo::CreateSignature(TString &signature) const
{
signature = "(";
if (!IsValid()) {
signature += ")";
return;
}
TClingMethodArgInfo arg(fInterp, this);
int idx = 0;
while (arg.Next()) {
if (idx) {
signature += ", ";
}
signature += arg.Type()->Name();
if (arg.Name() && strlen(arg.Name())) {
signature += " ";
signature += arg.Name();
}
if (arg.DefaultValue()) {
signature += " = ";
signature += arg.DefaultValue();
}
++idx;
}
signature += ")";
}
void TClingMethodInfo::Init(const clang::FunctionDecl *decl)
{
fContexts.clear();
fFirstTime = true;
fContextIdx = 0U;
fIter = clang::DeclContext::decl_iterator();
fSingleDecl = decl;
}
void *TClingMethodInfo::InterfaceMethod() const
{
if (!IsValid()) {
return 0;
}
TClingCallFunc cf(fInterp);
cf.SetFunc(this);
return cf.InterfaceMethod();
}
bool TClingMethodInfo::IsValid() const
{
return fSingleDecl ? fSingleDecl : *fIter;
}
int TClingMethodInfo::NArg() const
{
if (!IsValid()) {
return -1;
}
const clang::FunctionDecl *fd = GetMethodDecl();
unsigned num_params = fd->getNumParams();
// Truncate cast to fit cint interface.
return static_cast<int>(num_params);
}
int TClingMethodInfo::NDefaultArg() const
{
if (!IsValid()) {
return -1;
}
const clang::FunctionDecl *fd = GetMethodDecl();
unsigned num_params = fd->getNumParams();
unsigned min_args = fd->getMinRequiredArguments();
unsigned defaulted_params = num_params - min_args;
// Truncate cast to fit cint interface.
return static_cast<int>(defaulted_params);
}
int TClingMethodInfo::InternalNext()
{
assert(!fSingleDecl && "This is not an iterator!");
if (!*fIter) {
// Iterator is already invalid.
return 0;
}
while (true) {
// Advance to the next decl.
if (fFirstTime) {
// The cint semantics are weird.
fFirstTime = false;
}
else {
++fIter;
}
// Fix it if we have gone past the end of the current decl context.
while (!*fIter) {
++fContextIdx;
if (fContextIdx >= fContexts.size()) {
// Iterator is now invalid.
return 0;
}
clang::DeclContext *dc = fContexts[fContextIdx];
fIter = dc->decls_begin();
if (*fIter) {
// Good, a non-empty context.
break;
}
}
// Return if this decl is a function or method.
if (llvm::isa<clang::FunctionDecl>(*fIter)) {
// Iterator is now valid.
return 1;
}
}
}
int TClingMethodInfo::Next()
{
return InternalNext();
}
long TClingMethodInfo::Property() const
{
if (!IsValid()) {
return 0L;
}
long property = 0L;
property |= G__BIT_ISCOMPILED;
const clang::FunctionDecl *fd = GetMethodDecl();
switch (fd->getAccess()) {
case clang::AS_public:
property |= G__BIT_ISPUBLIC;
break;
case clang::AS_protected:
property |= G__BIT_ISPROTECTED;
break;
case clang::AS_private:
property |= G__BIT_ISPRIVATE;
break;
case clang::AS_none:
// IMPOSSIBLE
break;
default:
// IMPOSSIBLE
break;
}
if (fd->getStorageClass() == clang::SC_Static) {
property |= G__BIT_ISSTATIC;
}
clang::QualType qt = fd->getResultType().getCanonicalType();
if (qt.isConstQualified()) {
property |= G__BIT_ISCONSTANT;
}
while (1) {
if (qt->isArrayType()) {
qt = llvm::cast<clang::ArrayType>(qt)->getElementType();
continue;
}
else if (qt->isReferenceType()) {
property |= G__BIT_ISREFERENCE;
qt = llvm::cast<clang::ReferenceType>(qt)->getPointeeType();
continue;
}
else if (qt->isPointerType()) {
property |= G__BIT_ISPOINTER;
if (qt.isConstQualified()) {
property |= G__BIT_ISPCONSTANT;
}
qt = llvm::cast<clang::PointerType>(qt)->getPointeeType();
continue;
}
else if (qt->isMemberPointerType()) {
qt = llvm::cast<clang::MemberPointerType>(qt)->getPointeeType();
continue;
}
break;
}
if (qt.isConstQualified()) {
property |= G__BIT_ISCONSTANT;
}
if (const clang::CXXMethodDecl *md =
llvm::dyn_cast<clang::CXXMethodDecl>(fd)) {
if (md->getTypeQualifiers() & clang::Qualifiers::Const) {
property |= G__BIT_ISCONSTANT | G__BIT_ISMETHCONSTANT;
}
if (md->isVirtual()) {
property |= G__BIT_ISVIRTUAL;
}
if (md->isPure()) {
property |= G__BIT_ISPUREVIRTUAL;
}
if (const clang::CXXConstructorDecl *cd =
llvm::dyn_cast<clang::CXXConstructorDecl>(md)) {
if (cd->isExplicit()) {
property |= G__BIT_ISEXPLICIT;
}
}
else if (const clang::CXXConversionDecl *cd =
llvm::dyn_cast<clang::CXXConversionDecl>(md)) {
if (cd->isExplicit()) {
property |= G__BIT_ISEXPLICIT;
}
}
}
return property;
}
TClingTypeInfo *TClingMethodInfo::Type() const
{
static TClingTypeInfo ti(fInterp);
ti.Init(clang::QualType());
if (!IsValid()) {
return &ti;
}
clang::QualType qt = GetMethodDecl()->getResultType();
ti.Init(qt);
return &ti;
}
const char *TClingMethodInfo::GetMangledName() const
{
if (!IsValid()) {
return 0;
}
const char *fname = 0;
static std::string mangled_name;
mangled_name.clear();
llvm::raw_string_ostream os(mangled_name);
llvm::OwningPtr<clang::MangleContext> mangle(GetMethodDecl()->getASTContext().
createMangleContext());
const clang::NamedDecl *nd = GetMethodDecl();
if (!nd) {
return 0;
}
if (!mangle->shouldMangleDeclName(nd)) {
clang::IdentifierInfo *ii = nd->getIdentifier();
fname = ii->getNameStart();
}
else {
if (const clang::CXXConstructorDecl *d =
llvm::dyn_cast<clang::CXXConstructorDecl>(nd)) {
//Ctor_Complete, // Complete object ctor
//Ctor_Base, // Base object ctor
//Ctor_CompleteAllocating // Complete object allocating ctor (unused)
mangle->mangleCXXCtor(d, clang::Ctor_Complete, os);
}
else if (const clang::CXXDestructorDecl *d =
llvm::dyn_cast<clang::CXXDestructorDecl>(nd)) {
//Dtor_Deleting, // Deleting dtor
//Dtor_Complete, // Complete object dtor
//Dtor_Base // Base object dtor
mangle->mangleCXXDtor(d, clang::Dtor_Deleting, os);
}
else {
mangle->mangleName(nd, os);
}
os.flush();
fname = mangled_name.c_str();
}
return fname;
}
const char *TClingMethodInfo::GetPrototype() const
{
if (!IsValid()) {
return 0;
}
static std::string buf;
buf.clear();
buf += Type()->Name();
buf += ' ';
std::string name;
clang::PrintingPolicy policy(GetMethodDecl()->getASTContext().getPrintingPolicy());
const clang::NamedDecl *nd = GetMethodDecl();
nd->getNameForDiagnostic(name, policy, /*Qualified=*/true);
buf += name;
buf += '(';
TClingMethodArgInfo arg(fInterp, this);
int idx = 0;
while (arg.Next()) {
if (idx) {
buf += ", ";
}
buf += arg.Type()->Name();
if (arg.Name() && strlen(arg.Name())) {
buf += ' ';
buf += arg.Name();
}
if (arg.DefaultValue()) {
buf += " = ";
buf += arg.DefaultValue();
}
++idx;
}
buf += ')';
return buf.c_str();
}
const char *TClingMethodInfo::Name() const
{
if (!IsValid()) {
return 0;
}
static std::string buf;
buf.clear();
clang::PrintingPolicy policy(GetMethodDecl()->getASTContext().getPrintingPolicy());
GetMethodDecl()->getNameForDiagnostic(buf, policy, /*Qualified=*/false);
return buf.c_str();
}
const char *TClingMethodInfo::TypeName() const
{
if (!IsValid()) {
// FIXME: Cint does not check!
return 0;
}
return Type()->Name();
}
const char *TClingMethodInfo::Title()
{
if (!IsValid()) {
return 0;
}
//NOTE: We can't use it as a cache due to the "thoughtful" self iterator
//if (fTitle.size())
// return fTitle.c_str();
// Try to get the comment either from the annotation or the header file if present
// Iterate over the redeclarations, we can have muliple definitions in the
// redecl chain (came from merging of pcms).
if (const FunctionDecl *FD = llvm::dyn_cast<FunctionDecl>(GetMethodDecl())) {
if ( (FD = ROOT::TMetaUtils::GetAnnotatedRedeclarable(FD)) ) {
if (AnnotateAttr *A = FD->getAttr<AnnotateAttr>()) {
fTitle = A->getAnnotation().str();
return fTitle.c_str();
}
}
}
// Try to get the comment from the header file if present
fTitle = ROOT::TMetaUtils::GetComment(*GetMethodDecl()).str();
return fTitle.c_str();
}
<|endoftext|> |
<commit_before>/*****************************************************************************
*
* This file is part of Mapnik (c++ mapping toolkit)
*
* Copyright (C) 2015 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
*
*****************************************************************************/
#include <mapnik/text/text_line.hpp>
#include <mapnik/text/glyph_info.hpp>
#include <mapnik/text/text_properties.hpp>
namespace mapnik {
text_line::text_line(unsigned first_char, unsigned last_char)
: glyphs_(),
line_height_(0.0),
max_char_height_(0.0),
width_(0.0),
glyphs_width_(0.0),
first_char_(first_char),
last_char_(last_char),
first_line_(false),
space_count_(0)
{}
text_line::text_line(text_line && rhs)
: glyphs_(std::move(rhs.glyphs_)),
line_height_(std::move(rhs.line_height_)),
max_char_height_(std::move(rhs.max_char_height_)),
width_(std::move(rhs.width_)),
glyphs_width_(std::move(rhs.glyphs_width_)),
first_char_(std::move(rhs.first_char_)),
last_char_(std::move(rhs.last_char_)),
first_line_(std::move(rhs.first_line_)),
space_count_(std::move(rhs.space_count_)) {}
void text_line::add_glyph(glyph_info && glyph, double scale_factor_)
{
line_height_ = std::max(line_height_, glyph.line_height() + glyph.format->line_spacing);
double advance = glyph.advance();
if (glyphs_.empty())
{
width_ = advance;
glyphs_width_ = advance;
space_count_ = 0;
}
else if (advance > 0)
{
// Only add character spacing if the character is not a zero-width part of a cluster.
width_ += advance + glyphs_.back().format->character_spacing * scale_factor_;
glyphs_width_ += advance;
space_count_++;
}
glyphs_.emplace_back(std::move(glyph));
}
void text_line::reserve(glyph_vector::size_type length)
{
glyphs_.reserve(length);
}
text_line::const_iterator text_line::begin() const
{
return glyphs_.begin();
}
text_line::const_iterator text_line::end() const
{
return glyphs_.end();
}
double text_line::height() const
{
if (first_line_) return max_char_height_;
return line_height_;
}
void text_line::update_max_char_height(double max_char_height)
{
max_char_height_ = std::max(max_char_height_, max_char_height);
}
void text_line::set_first_line(bool first_line)
{
first_line_ = first_line;
}
unsigned text_line::first_char() const
{
return first_char_;
}
unsigned text_line::last_char() const
{
return last_char_;
}
unsigned text_line::size() const
{
return glyphs_.size();
}
} // end namespace mapnik
<commit_msg>apply scale factor to line spacing<commit_after>/*****************************************************************************
*
* This file is part of Mapnik (c++ mapping toolkit)
*
* Copyright (C) 2015 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
*
*****************************************************************************/
#include <mapnik/text/text_line.hpp>
#include <mapnik/text/glyph_info.hpp>
#include <mapnik/text/text_properties.hpp>
namespace mapnik {
text_line::text_line(unsigned first_char, unsigned last_char)
: glyphs_(),
line_height_(0.0),
max_char_height_(0.0),
width_(0.0),
glyphs_width_(0.0),
first_char_(first_char),
last_char_(last_char),
first_line_(false),
space_count_(0)
{}
text_line::text_line(text_line && rhs)
: glyphs_(std::move(rhs.glyphs_)),
line_height_(std::move(rhs.line_height_)),
max_char_height_(std::move(rhs.max_char_height_)),
width_(std::move(rhs.width_)),
glyphs_width_(std::move(rhs.glyphs_width_)),
first_char_(std::move(rhs.first_char_)),
last_char_(std::move(rhs.last_char_)),
first_line_(std::move(rhs.first_line_)),
space_count_(std::move(rhs.space_count_)) {}
void text_line::add_glyph(glyph_info && glyph, double scale_factor_)
{
line_height_ = std::max(line_height_, glyph.line_height() + glyph.format->line_spacing * scale_factor_);
double advance = glyph.advance();
if (glyphs_.empty())
{
width_ = advance;
glyphs_width_ = advance;
space_count_ = 0;
}
else if (advance > 0)
{
// Only add character spacing if the character is not a zero-width part of a cluster.
width_ += advance + glyphs_.back().format->character_spacing * scale_factor_;
glyphs_width_ += advance;
space_count_++;
}
glyphs_.emplace_back(std::move(glyph));
}
void text_line::reserve(glyph_vector::size_type length)
{
glyphs_.reserve(length);
}
text_line::const_iterator text_line::begin() const
{
return glyphs_.begin();
}
text_line::const_iterator text_line::end() const
{
return glyphs_.end();
}
double text_line::height() const
{
if (first_line_) return max_char_height_;
return line_height_;
}
void text_line::update_max_char_height(double max_char_height)
{
max_char_height_ = std::max(max_char_height_, max_char_height);
}
void text_line::set_first_line(bool first_line)
{
first_line_ = first_line;
}
unsigned text_line::first_char() const
{
return first_char_;
}
unsigned text_line::last_char() const
{
return last_char_;
}
unsigned text_line::size() const
{
return glyphs_.size();
}
} // end namespace mapnik
<|endoftext|> |
<commit_before>#include <common-ee.h>
#include <kernel.h>
#include <string.h>
#define INIT_PRIO 0x40
#define STACK_SIZE 0x8000
char nullThreadStack[STACK_SIZE] __attribute__ ((aligned(16)));
void nullThreadProc(u32) {
//Do nothing
}
char sleepingThreadStack[STACK_SIZE] __attribute__ ((aligned(16)));
void sleepingThreadProc(u32) {
SleepThread();
}
char waitingThreadStack[STACK_SIZE] __attribute__ ((aligned(16)));
void waitingThreadProc(u32) {
ee_sema_t dummySemaInfo;
dummySemaInfo.init_count = 0;
dummySemaInfo.max_count = 1;
dummySemaInfo.option = 0;
u32 dummySema = CreateSema(&dummySemaInfo);
WaitSema(dummySema);
}
int createTestThread(void *entry, int prio, void *stack, u32 stackSize) {
ee_thread_t threadParam;
memset(&threadParam, 0, sizeof(ee_thread_t));
threadParam.func = entry;
threadParam.initial_priority = prio;
threadParam.stack = stack;
threadParam.stack_size = stackSize;
return CreateThread(&threadParam);
}
void printThreadStatus(int threadId) {
ee_thread_status_t threadStat;
memset(&threadStat, 0, sizeof(ee_thread_status_t));
int result = ReferThreadStatus(threadId, &threadStat);
if(result >= 0)
{
schedf("succeeded -> result: %02x, init prio: %02x current prio: %02x, status: %02x\n",
result, threadStat.initial_priority, threadStat.current_priority, threadStat.status);
}
else
{
schedf("failed -> result: %d\n");
}
}
int main(int argc, char **argv) {
printf("-- TEST BEGIN\n");
{
schedf("self thread:\n");
schedf(" stat (with tid 0): ");
printThreadStatus(0);
schedf(" stat (with current tid): ");
printThreadStatus(GetThreadId());
flushschedf();
}
{
schedf("low prio thread:\n");
int threadId = createTestThread((void*)&nullThreadProc, INIT_PRIO + 0x10, nullThreadStack, STACK_SIZE);
schedf(" stat before start: ");
printThreadStatus(threadId);
StartThread(threadId, 0);
schedf(" stat after start: ");
printThreadStatus(threadId);
SuspendThread(threadId);
schedf(" stat after suspend: ");
printThreadStatus(threadId);
ResumeThread(threadId);
schedf(" stat after resume: ");
printThreadStatus(threadId);
TerminateThread(threadId);
schedf(" stat after terminate: ");
printThreadStatus(threadId);
DeleteThread(threadId);
flushschedf();
}
{
schedf("sleeping thread:\n");
int threadId = createTestThread((void*)&sleepingThreadProc, INIT_PRIO - 0x10, sleepingThreadStack, STACK_SIZE);
StartThread(threadId, 0);
schedf(" stat after start: ");
printThreadStatus(threadId);
SuspendThread(threadId);
schedf(" stat after suspend: ");
printThreadStatus(threadId);
ResumeThread(threadId);
schedf(" stat after resume: ");
printThreadStatus(threadId);
TerminateThread(threadId);
DeleteThread(threadId);
flushschedf();
}
//Waiting thread
{
schedf("waiting thread:\n");
int threadId = createTestThread((void*)&waitingThreadProc, INIT_PRIO - 0x10, waitingThreadStack, STACK_SIZE);
StartThread(threadId, 0);
schedf(" stat after start: ");
printThreadStatus(threadId);
SuspendThread(threadId);
schedf(" stat after suspend: ");
printThreadStatus(threadId);
ResumeThread(threadId);
schedf(" stat after resume: ");
printThreadStatus(threadId);
TerminateThread(threadId);
DeleteThread(threadId);
flushschedf();
}
//Various corner cases
{
//Add thread stat from spr_ram
schedf("thread stat with invalid tid: ");
printThreadStatus(~0);
int result = ReferThreadStatus(0, NULL);
schedf("self thread stat with null struct: %02x\n", result);
flushschedf();
}
printf("-- TEST END\n");
return 0;
}
<commit_msg>Fixed printThreadStatus function.<commit_after>#include <common-ee.h>
#include <kernel.h>
#include <string.h>
#define INIT_PRIO 0x40
#define STACK_SIZE 0x8000
char nullThreadStack[STACK_SIZE] __attribute__ ((aligned(16)));
void nullThreadProc(u32) {
//Do nothing
}
char sleepingThreadStack[STACK_SIZE] __attribute__ ((aligned(16)));
void sleepingThreadProc(u32) {
SleepThread();
}
char waitingThreadStack[STACK_SIZE] __attribute__ ((aligned(16)));
void waitingThreadProc(u32) {
ee_sema_t dummySemaInfo;
dummySemaInfo.init_count = 0;
dummySemaInfo.max_count = 1;
dummySemaInfo.option = 0;
u32 dummySema = CreateSema(&dummySemaInfo);
WaitSema(dummySema);
}
int createTestThread(void *entry, int prio, void *stack, u32 stackSize) {
ee_thread_t threadParam;
memset(&threadParam, 0, sizeof(ee_thread_t));
threadParam.func = entry;
threadParam.initial_priority = prio;
threadParam.stack = stack;
threadParam.stack_size = stackSize;
return CreateThread(&threadParam);
}
void printThreadStatus(int threadId) {
ee_thread_status_t threadStat;
memset(&threadStat, 0, sizeof(ee_thread_status_t));
int result = ReferThreadStatus(threadId, &threadStat);
if(result >= 0) {
schedf("succeeded -> result: %02x, init prio: %02x current prio: %02x, status: %02x\n",
result, threadStat.initial_priority, threadStat.current_priority, threadStat.status);
} else {
schedf("failed -> result: %d\n", result);
}
}
int main(int argc, char **argv) {
printf("-- TEST BEGIN\n");
{
schedf("self thread:\n");
schedf(" stat (with tid 0): ");
printThreadStatus(0);
schedf(" stat (with current tid): ");
printThreadStatus(GetThreadId());
flushschedf();
}
{
schedf("low prio thread:\n");
int threadId = createTestThread((void*)&nullThreadProc, INIT_PRIO + 0x10, nullThreadStack, STACK_SIZE);
schedf(" stat before start: ");
printThreadStatus(threadId);
StartThread(threadId, 0);
schedf(" stat after start: ");
printThreadStatus(threadId);
SuspendThread(threadId);
schedf(" stat after suspend: ");
printThreadStatus(threadId);
ResumeThread(threadId);
schedf(" stat after resume: ");
printThreadStatus(threadId);
TerminateThread(threadId);
schedf(" stat after terminate: ");
printThreadStatus(threadId);
DeleteThread(threadId);
flushschedf();
}
{
schedf("sleeping thread:\n");
int threadId = createTestThread((void*)&sleepingThreadProc, INIT_PRIO - 0x10, sleepingThreadStack, STACK_SIZE);
StartThread(threadId, 0);
schedf(" stat after start: ");
printThreadStatus(threadId);
SuspendThread(threadId);
schedf(" stat after suspend: ");
printThreadStatus(threadId);
ResumeThread(threadId);
schedf(" stat after resume: ");
printThreadStatus(threadId);
TerminateThread(threadId);
DeleteThread(threadId);
flushschedf();
}
//Waiting thread
{
schedf("waiting thread:\n");
int threadId = createTestThread((void*)&waitingThreadProc, INIT_PRIO - 0x10, waitingThreadStack, STACK_SIZE);
StartThread(threadId, 0);
schedf(" stat after start: ");
printThreadStatus(threadId);
SuspendThread(threadId);
schedf(" stat after suspend: ");
printThreadStatus(threadId);
ResumeThread(threadId);
schedf(" stat after resume: ");
printThreadStatus(threadId);
TerminateThread(threadId);
DeleteThread(threadId);
flushschedf();
}
//Various corner cases
{
//Add thread stat from spr_ram
schedf("thread stat with invalid tid: ");
printThreadStatus(~0);
int result = ReferThreadStatus(0, NULL);
schedf("self thread stat with null struct: %02x\n", result);
flushschedf();
}
printf("-- TEST END\n");
return 0;
}
<|endoftext|> |
<commit_before>//Copyright (c) 2018 Ultimaker B.V.
//CuraEngine is released under the terms of the AGPLv3 or higher.
#include <cmath> //For M_PI.
#include "SettingsTest.h"
#include "../src/settings/FlowTempGraph.h"
#include "../src/settings/types/LayerIndex.h"
#include "../src/settings/types/AngleRadians.h"
#include "../src/settings/types/AngleDegrees.h"
#include "../src/settings/types/Temperature.h"
#include "../src/settings/types/Velocity.h"
#include "../src/settings/types/Ratio.h"
#include "../src/settings/types/Duration.h"
#include "../src/utils/floatpoint.h"
namespace cura
{
CPPUNIT_TEST_SUITE_REGISTRATION(SettingsTest);
void SettingsTest::addSettingStringTest()
{
const std::string setting_value("The human body contains enough bones to make an entire skeleton.");
settings.add("test_setting", setting_value);
CPPUNIT_ASSERT_EQUAL(setting_value, settings.get<std::string>("test_setting"));
}
void SettingsTest::addSettingIntTest()
{
settings.add("test_setting", "42");
CPPUNIT_ASSERT_EQUAL(int(42), settings.get<int>("test_setting"));
settings.add("test_setting", "-1");
CPPUNIT_ASSERT_EQUAL(int(-1), settings.get<int>("test_setting"));
}
void SettingsTest::addSettingDoubleTest()
{
settings.add("test_setting", "1234567.890");
CPPUNIT_ASSERT_EQUAL(double(1234567.89), settings.get<double>("test_setting"));
}
void SettingsTest::addSettingSizeTTest()
{
settings.add("test_setting", "666");
CPPUNIT_ASSERT_EQUAL(size_t(666), settings.get<size_t>("test_setting"));
}
void SettingsTest::addSettingUnsignedIntTest()
{
settings.add("test_setting", "69");
CPPUNIT_ASSERT_EQUAL(unsigned(69), settings.get<unsigned int>("test_setting"));
}
void SettingsTest::addSettingBoolTest()
{
settings.add("test_setting", "true");
CPPUNIT_ASSERT_EQUAL(true, settings.get<bool>("test_setting"));
settings.add("test_setting", "on");
CPPUNIT_ASSERT_EQUAL(true, settings.get<bool>("test_setting"));
settings.add("test_setting", "yes");
CPPUNIT_ASSERT_EQUAL(true, settings.get<bool>("test_setting"));
settings.add("test_setting", "True");
CPPUNIT_ASSERT_EQUAL(true, settings.get<bool>("test_setting"));
settings.add("test_setting", "50");
CPPUNIT_ASSERT_EQUAL(true, settings.get<bool>("test_setting"));
settings.add("test_setting", "0");
CPPUNIT_ASSERT_EQUAL_MESSAGE("0 should cast to false.",
false, settings.get<bool>("test_setting"));
settings.add("test_setting", "false");
CPPUNIT_ASSERT_EQUAL(false, settings.get<bool>("test_setting"));
settings.add("test_setting", "False");
CPPUNIT_ASSERT_EQUAL(false, settings.get<bool>("test_setting"));
}
void SettingsTest::addSettingExtruderTrainTest()
{
// TODO: Do it when the implementation is done.
CPPUNIT_ASSERT_MESSAGE("TODO: The value of the 'ExtruderTrain' setting is not the same as the expected value!",
false);
}
void SettingsTest::addSettingLayerIndexTest()
{
settings.add("test_setting", "-4");
CPPUNIT_ASSERT_EQUAL_MESSAGE("LayerIndex settings start counting from 0, so subtract one.",
LayerIndex(-5), settings.get<LayerIndex>("test_setting"));
}
void SettingsTest::addSettingCoordTTest()
{
settings.add("test_setting", "8589934.592"); //2^33 microns, so this MUST be a 64-bit integer! (Or at least 33-bit, but those don't exist.)
CPPUNIT_ASSERT_EQUAL_MESSAGE("Coordinates must be entered in the setting as millimetres, but are converted to micrometres.",
coord_t(8589934592), settings.get<coord_t>("test_setting"));
}
void SettingsTest::addSettingAngleRadiansTest()
{
settings.add("test_setting", "180");
CPPUNIT_ASSERT_DOUBLES_EQUAL_MESSAGE("180 degrees is 1 pi radians.",
AngleRadians(M_PI), settings.get<AngleRadians>("test_setting"), DELTA);
settings.add("test_setting", "810");
CPPUNIT_ASSERT_DOUBLES_EQUAL_MESSAGE("810 degrees in clock arithmetic is 90 degrees, which is 0.5 pi radians.",
AngleRadians(M_PI / 2.0), settings.get<AngleRadians>("test_setting"), DELTA);
}
void SettingsTest::addSettingAngleDegreesTest()
{
settings.add("test_setting", "4442.4");
CPPUNIT_ASSERT_DOUBLES_EQUAL_MESSAGE("4442.4 in clock arithmetic is 360 degrees.",
AngleDegrees(122.4), settings.get<AngleDegrees>("test_setting"), DELTA);
}
void SettingsTest::addSettingTemperatureTest()
{
settings.add("test_setting", "245.5");
CPPUNIT_ASSERT_DOUBLES_EQUAL(Temperature(245.5), settings.get<Temperature>("test_setting"), DELTA);
}
void SettingsTest::addSettingVelocityTest()
{
settings.add("test_setting", "12.345");
CPPUNIT_ASSERT_DOUBLES_EQUAL(Velocity(12.345), settings.get<Velocity>("test_setting"), DELTA);
settings.add("test_setting", "-78");
CPPUNIT_ASSERT_DOUBLES_EQUAL(Velocity(-78), settings.get<Velocity>("test_setting"), DELTA);
}
void SettingsTest::addSettingRatioTest()
{
settings.add("test_setting", "1.618");
CPPUNIT_ASSERT_DOUBLES_EQUAL_MESSAGE("With ratios, the input is interpreted in percentages.",
Ratio(0.01618), settings.get<Ratio>("test_setting"), DELTA);
}
void SettingsTest::addSettingDurationTest()
{
settings.add("test_setting", "1234.5678");
CPPUNIT_ASSERT_DOUBLES_EQUAL(Duration(1234.5678), settings.get<Duration>("test_setting"), DELTA);
settings.add("test_setting", "-1234.5678");
CPPUNIT_ASSERT_DOUBLES_EQUAL(Duration(0), settings.get<Duration>("test_setting"), DELTA);
}
void SettingsTest::addSettingFlowTempGraphTest()
{
settings.add("test_setting", "[[1.50, 10.1],[ 25.1,40.4 ], [26.5,75], [50 , 100.10]]"); //Try various spacing and radixes.
const FlowTempGraph flow_temp_graph = settings.get<FlowTempGraph>("test_setting");
double stored_temperature = flow_temp_graph.getTemp(30.5, 200.0, true);
CPPUNIT_ASSERT_DOUBLES_EQUAL(75.0 + (100.10 - 75.0) * (30.5 - 26.5) / (50.0 - 26.5), stored_temperature, DELTA);
stored_temperature = flow_temp_graph.getTemp(1, 200.0, true);
CPPUNIT_ASSERT_DOUBLES_EQUAL(10.1, stored_temperature, DELTA); //Flow too low - Return lower temperature in the graph.
stored_temperature = flow_temp_graph.getTemp(80, 200.0, true);
CPPUNIT_ASSERT_DOUBLES_EQUAL(100.1, stored_temperature, DELTA); //Flow too high - Return higher temperature in the graph.
stored_temperature = flow_temp_graph.getTemp(30.5, 200.0, false);
CPPUNIT_ASSERT_DOUBLES_EQUAL(200.0, stored_temperature, DELTA);
}
void SettingsTest::addSettingFMatrix3x3Test()
{
settings.add("test_setting", "[[1.0, 2.0, 3.3],[ 2 , 3.0 , 1.0],[3.0 ,1.0,2.0 ]]"); //Try various spacing and radixes.
FMatrix3x3 flow_matrix = settings.get<FMatrix3x3>("test_setting");
CPPUNIT_ASSERT_DOUBLES_EQUAL(1.0, flow_matrix.m[0][0], DELTA);
CPPUNIT_ASSERT_DOUBLES_EQUAL(2.0, flow_matrix.m[0][1], DELTA);
CPPUNIT_ASSERT_DOUBLES_EQUAL(3.3, flow_matrix.m[0][2], DELTA);
CPPUNIT_ASSERT_DOUBLES_EQUAL(2.0, flow_matrix.m[1][0], DELTA);
CPPUNIT_ASSERT_DOUBLES_EQUAL(3.0, flow_matrix.m[1][1], DELTA);
CPPUNIT_ASSERT_DOUBLES_EQUAL(1.0, flow_matrix.m[1][2], DELTA);
CPPUNIT_ASSERT_DOUBLES_EQUAL(3.0, flow_matrix.m[2][0], DELTA);
CPPUNIT_ASSERT_DOUBLES_EQUAL(1.0, flow_matrix.m[2][1], DELTA);
CPPUNIT_ASSERT_DOUBLES_EQUAL(2.0, flow_matrix.m[2][2], DELTA);
}
void SettingsTest::addSettingVectorTest()
{
settings.add("test_setting", "[0, 1, 1,2, 3 , 5, 8,13]");
std::vector<int> vector_int = settings.get<std::vector<int>>("test_setting");
std::vector<int> ground_truth = {0, 1, 1, 2, 3, 5, 8, 13};
CPPUNIT_ASSERT_EQUAL(ground_truth.size(), vector_int.size());
for (size_t i = 0; i < ground_truth.size(); i++)
{
CPPUNIT_ASSERT_EQUAL(ground_truth[i], vector_int[i]);
}
}
void SettingsTest::overwriteSettingTest()
{
settings.add("test_setting", "P");
settings.add("test_setting", "NP");
CPPUNIT_ASSERT_MESSAGE("When overriding a setting, the original value was not changed.",
settings.get<std::string>("test_setting") != std::string("P"));
CPPUNIT_ASSERT_EQUAL(std::string("NP"), settings.get<std::string>("test_setting"));
}
}
<commit_msg>Flip axes when checking float matrix<commit_after>//Copyright (c) 2018 Ultimaker B.V.
//CuraEngine is released under the terms of the AGPLv3 or higher.
#include <cmath> //For M_PI.
#include "SettingsTest.h"
#include "../src/settings/FlowTempGraph.h"
#include "../src/settings/types/LayerIndex.h"
#include "../src/settings/types/AngleRadians.h"
#include "../src/settings/types/AngleDegrees.h"
#include "../src/settings/types/Temperature.h"
#include "../src/settings/types/Velocity.h"
#include "../src/settings/types/Ratio.h"
#include "../src/settings/types/Duration.h"
#include "../src/utils/floatpoint.h"
namespace cura
{
CPPUNIT_TEST_SUITE_REGISTRATION(SettingsTest);
void SettingsTest::addSettingStringTest()
{
const std::string setting_value("The human body contains enough bones to make an entire skeleton.");
settings.add("test_setting", setting_value);
CPPUNIT_ASSERT_EQUAL(setting_value, settings.get<std::string>("test_setting"));
}
void SettingsTest::addSettingIntTest()
{
settings.add("test_setting", "42");
CPPUNIT_ASSERT_EQUAL(int(42), settings.get<int>("test_setting"));
settings.add("test_setting", "-1");
CPPUNIT_ASSERT_EQUAL(int(-1), settings.get<int>("test_setting"));
}
void SettingsTest::addSettingDoubleTest()
{
settings.add("test_setting", "1234567.890");
CPPUNIT_ASSERT_EQUAL(double(1234567.89), settings.get<double>("test_setting"));
}
void SettingsTest::addSettingSizeTTest()
{
settings.add("test_setting", "666");
CPPUNIT_ASSERT_EQUAL(size_t(666), settings.get<size_t>("test_setting"));
}
void SettingsTest::addSettingUnsignedIntTest()
{
settings.add("test_setting", "69");
CPPUNIT_ASSERT_EQUAL(unsigned(69), settings.get<unsigned int>("test_setting"));
}
void SettingsTest::addSettingBoolTest()
{
settings.add("test_setting", "true");
CPPUNIT_ASSERT_EQUAL(true, settings.get<bool>("test_setting"));
settings.add("test_setting", "on");
CPPUNIT_ASSERT_EQUAL(true, settings.get<bool>("test_setting"));
settings.add("test_setting", "yes");
CPPUNIT_ASSERT_EQUAL(true, settings.get<bool>("test_setting"));
settings.add("test_setting", "True");
CPPUNIT_ASSERT_EQUAL(true, settings.get<bool>("test_setting"));
settings.add("test_setting", "50");
CPPUNIT_ASSERT_EQUAL(true, settings.get<bool>("test_setting"));
settings.add("test_setting", "0");
CPPUNIT_ASSERT_EQUAL_MESSAGE("0 should cast to false.",
false, settings.get<bool>("test_setting"));
settings.add("test_setting", "false");
CPPUNIT_ASSERT_EQUAL(false, settings.get<bool>("test_setting"));
settings.add("test_setting", "False");
CPPUNIT_ASSERT_EQUAL(false, settings.get<bool>("test_setting"));
}
void SettingsTest::addSettingExtruderTrainTest()
{
// TODO: Do it when the implementation is done.
CPPUNIT_ASSERT_MESSAGE("TODO: The value of the 'ExtruderTrain' setting is not the same as the expected value!",
false);
}
void SettingsTest::addSettingLayerIndexTest()
{
settings.add("test_setting", "-4");
CPPUNIT_ASSERT_EQUAL_MESSAGE("LayerIndex settings start counting from 0, so subtract one.",
LayerIndex(-5), settings.get<LayerIndex>("test_setting"));
}
void SettingsTest::addSettingCoordTTest()
{
settings.add("test_setting", "8589934.592"); //2^33 microns, so this MUST be a 64-bit integer! (Or at least 33-bit, but those don't exist.)
CPPUNIT_ASSERT_EQUAL_MESSAGE("Coordinates must be entered in the setting as millimetres, but are converted to micrometres.",
coord_t(8589934592), settings.get<coord_t>("test_setting"));
}
void SettingsTest::addSettingAngleRadiansTest()
{
settings.add("test_setting", "180");
CPPUNIT_ASSERT_DOUBLES_EQUAL_MESSAGE("180 degrees is 1 pi radians.",
AngleRadians(M_PI), settings.get<AngleRadians>("test_setting"), DELTA);
settings.add("test_setting", "810");
CPPUNIT_ASSERT_DOUBLES_EQUAL_MESSAGE("810 degrees in clock arithmetic is 90 degrees, which is 0.5 pi radians.",
AngleRadians(M_PI / 2.0), settings.get<AngleRadians>("test_setting"), DELTA);
}
void SettingsTest::addSettingAngleDegreesTest()
{
settings.add("test_setting", "4442.4");
CPPUNIT_ASSERT_DOUBLES_EQUAL_MESSAGE("4442.4 in clock arithmetic is 360 degrees.",
AngleDegrees(122.4), settings.get<AngleDegrees>("test_setting"), DELTA);
}
void SettingsTest::addSettingTemperatureTest()
{
settings.add("test_setting", "245.5");
CPPUNIT_ASSERT_DOUBLES_EQUAL(Temperature(245.5), settings.get<Temperature>("test_setting"), DELTA);
}
void SettingsTest::addSettingVelocityTest()
{
settings.add("test_setting", "12.345");
CPPUNIT_ASSERT_DOUBLES_EQUAL(Velocity(12.345), settings.get<Velocity>("test_setting"), DELTA);
settings.add("test_setting", "-78");
CPPUNIT_ASSERT_DOUBLES_EQUAL(Velocity(-78), settings.get<Velocity>("test_setting"), DELTA);
}
void SettingsTest::addSettingRatioTest()
{
settings.add("test_setting", "1.618");
CPPUNIT_ASSERT_DOUBLES_EQUAL_MESSAGE("With ratios, the input is interpreted in percentages.",
Ratio(0.01618), settings.get<Ratio>("test_setting"), DELTA);
}
void SettingsTest::addSettingDurationTest()
{
settings.add("test_setting", "1234.5678");
CPPUNIT_ASSERT_DOUBLES_EQUAL(Duration(1234.5678), settings.get<Duration>("test_setting"), DELTA);
settings.add("test_setting", "-1234.5678");
CPPUNIT_ASSERT_DOUBLES_EQUAL(Duration(0), settings.get<Duration>("test_setting"), DELTA);
}
void SettingsTest::addSettingFlowTempGraphTest()
{
settings.add("test_setting", "[[1.50, 10.1],[ 25.1,40.4 ], [26.5,75], [50 , 100.10]]"); //Try various spacing and radixes.
const FlowTempGraph flow_temp_graph = settings.get<FlowTempGraph>("test_setting");
double stored_temperature = flow_temp_graph.getTemp(30.5, 200.0, true);
CPPUNIT_ASSERT_DOUBLES_EQUAL(75.0 + (100.10 - 75.0) * (30.5 - 26.5) / (50.0 - 26.5), stored_temperature, DELTA);
stored_temperature = flow_temp_graph.getTemp(1, 200.0, true);
CPPUNIT_ASSERT_DOUBLES_EQUAL(10.1, stored_temperature, DELTA); //Flow too low - Return lower temperature in the graph.
stored_temperature = flow_temp_graph.getTemp(80, 200.0, true);
CPPUNIT_ASSERT_DOUBLES_EQUAL(100.1, stored_temperature, DELTA); //Flow too high - Return higher temperature in the graph.
stored_temperature = flow_temp_graph.getTemp(30.5, 200.0, false);
CPPUNIT_ASSERT_DOUBLES_EQUAL(200.0, stored_temperature, DELTA);
}
void SettingsTest::addSettingFMatrix3x3Test()
{
settings.add("test_setting", "[[1.0, 2.0, 3.3],[ 2 , 3.0 , 1.0],[3.0 ,1.0,2.0 ]]"); //Try various spacing and radixes.
FMatrix3x3 float_matrix = settings.get<FMatrix3x3>("test_setting");
CPPUNIT_ASSERT_DOUBLES_EQUAL(1.0, float_matrix.m[0][0], DELTA);
CPPUNIT_ASSERT_DOUBLES_EQUAL(2.0, float_matrix.m[1][0], DELTA);
CPPUNIT_ASSERT_DOUBLES_EQUAL(3.3, float_matrix.m[2][0], DELTA);
CPPUNIT_ASSERT_DOUBLES_EQUAL(2.0, float_matrix.m[0][1], DELTA);
CPPUNIT_ASSERT_DOUBLES_EQUAL(3.0, float_matrix.m[1][1], DELTA);
CPPUNIT_ASSERT_DOUBLES_EQUAL(1.0, float_matrix.m[2][1], DELTA);
CPPUNIT_ASSERT_DOUBLES_EQUAL(3.0, float_matrix.m[0][2], DELTA);
CPPUNIT_ASSERT_DOUBLES_EQUAL(1.0, float_matrix.m[1][2], DELTA);
CPPUNIT_ASSERT_DOUBLES_EQUAL(2.0, float_matrix.m[2][2], DELTA);
}
void SettingsTest::addSettingVectorTest()
{
settings.add("test_setting", "[0, 1, 1,2, 3 , 5, 8,13]");
std::vector<int> vector_int = settings.get<std::vector<int>>("test_setting");
std::vector<int> ground_truth = {0, 1, 1, 2, 3, 5, 8, 13};
CPPUNIT_ASSERT_EQUAL(ground_truth.size(), vector_int.size());
for (size_t i = 0; i < ground_truth.size(); i++)
{
CPPUNIT_ASSERT_EQUAL(ground_truth[i], vector_int[i]);
}
}
void SettingsTest::overwriteSettingTest()
{
settings.add("test_setting", "P");
settings.add("test_setting", "NP");
CPPUNIT_ASSERT_MESSAGE("When overriding a setting, the original value was not changed.",
settings.get<std::string>("test_setting") != std::string("P"));
CPPUNIT_ASSERT_EQUAL(std::string("NP"), settings.get<std::string>("test_setting"));
}
}
<|endoftext|> |
<commit_before><commit_msg>i mean. basics<commit_after>namespace dfg {
class DFG {
public DFG() {
}
public ~DGF() {
}
}
private vector<ptree> jsons;
}
<|endoftext|> |
<commit_before>/* Copyright (c) 2010-2012, Delft University of Technology
* 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 Delft University of Technology 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 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.
*
* Changelog
* YYMMDD Author Comment
* 110519 F.M. Engelen Creation of code.
* 110628 K. Kumar Minor comment and layout modifications.
* 110701 K. Kumar Updated unit tests to check relative error;
* Updated file path.
* 110718 F.M. Engelen Took out falacy in test (only checking the norm) and
* added ItoE and EtoI transformation.
* 110726 K. Kumar Minor modifications; updated relative error
* wrt to norm.
* 110808 F.M. Engelen Updated with better tests, changed test for vertical frame.
* 120529 E.A.G. Heeren Boostified unit tests.
* 120614 P. Musegaas Removed unneccessary using statements and normalizations.
*
* References
*
* The reference frame definitions/abbreviations can be found in the file
* referenceFrameTransformations.h.
*
*/
#define BOOST_TEST_MAIN
#include <boost/test/unit_test.hpp>
#include <Eigen/Core>
#include <TudatCore/Basics/testMacros.h>
#include <TudatCore/Astrodynamics/BasicAstrodynamics/unitConversions.h>
#include "Tudat/Astrodynamics/ReferenceFrames/referenceFrameTransformations.h"
namespace tudat
{
namespace unit_tests
{
BOOST_AUTO_TEST_SUITE( test_reference_frame_transformations )
// Summary of tests.
// Test 1: Test inertial to rotating planetocentric frame transformation.
// Test 2: Check whether the transformed matrix of Test 1 is also correct.
// Test 3: Same test as Test 1 for the transformation quaternion.
// Test 4: Same test as Test 2 for the transformation quaternion.
// Test 5: Test airspeed-based aerodynamic to body frame transformation.
// Test 6: Test planetocentric to local vertical frame transformation quaternion.
// Test 7: Check whether the transformed matrix of Test 6 is also correct.
// Test inertial to rotating planetocentric frame transformations.
BOOST_AUTO_TEST_CASE( testRotatingPlanetocentricFrameTransformations )
{
// Using declarations.
using std::atan2;
using std::cos;
using std::sin;
using std::pow;
using std::sqrt;
using tudat::unit_conversions::convertDegreesToRadians;
// Test 1: Test Inertial to rotating planetocentric frame transformation.
{
// Initialize initial location vector in inertial frame.
Eigen::Vector3d startLocation;
startLocation( 0 ) = 4.0;
startLocation( 1 ) = 1.0;
startLocation( 2 ) = 5.0;
double horizontalStartLocationSize = sqrt( pow( startLocation( 0 ), 2.0 )
+ pow( startLocation( 1 ), 2.0 ) );
// Declare and initialize angle between vector and XR-axis.
double startAngle = atan2( startLocation( 1 ), startLocation( 0 ) );
// Rotate by 10 degrees around the positive Z-axis
double angleInTime = convertDegreesToRadians( 10.0 );
// Declare and initialize the angle between the XI- and XR-axis.
double endAngle = startAngle - angleInTime;
// Declare the expected location of the point in the planetocentric reference frame.
Eigen::Vector3d expectedLocation;
expectedLocation( 0 ) = horizontalStartLocationSize * cos( endAngle );
expectedLocation( 1 ) = horizontalStartLocationSize * sin( endAngle );
expectedLocation( 2 ) = startLocation( 2 );
// Compute location of the point in the rotating frame subject to the transformation matrix.
Eigen::Vector3d transformedLocation;
transformedLocation = reference_frames::
getInertialToPlanetocentricFrameTransformationMatrix( angleInTime ) * startLocation;
// Check whether both vectors are equal within tolerances.
TUDAT_CHECK_MATRIX_CLOSE_FRACTION( transformedLocation, expectedLocation,
std::numeric_limits< double >::epsilon( ) );
}
// Test 2: Check whether the transformed matrix of Test 1 is also correct.
// Compute the error in the calculation.
{
// Initialize initial location vector in inertial frame.
Eigen::Vector3d startLocation;
startLocation( 0 ) = 4.0;
startLocation( 1 ) = 1.0;
startLocation( 2 ) = 5.0;
// Rotate by 10 degrees around the positive Z-axis
double angleInTime = convertDegreesToRadians( 10.0 );
// Compute location of the point in the rotating frame subject to the transformation matrix.
Eigen::Vector3d transformedLocation;
transformedLocation = tudat::reference_frames::
getRotatingPlanetocentricToInertialFrameTransformationMatrix( angleInTime ) *
tudat::reference_frames::
getInertialToPlanetocentricFrameTransformationMatrix( angleInTime )
* startLocation;
// Check whether both vectors are equal within tolerances.
TUDAT_CHECK_MATRIX_CLOSE_FRACTION( transformedLocation, startLocation,
std::numeric_limits< double >::epsilon( ) );
}
}
BOOST_AUTO_TEST_CASE( testRotatingPlanetocentricFrameTransformationQuaternion )
{
// Using declarations.
using std::atan2;
using std::cos;
using std::sin;
using std::pow;
using std::sqrt;
using tudat::unit_conversions::convertDegreesToRadians;
// Test 3: Same test as Test 1 for the transformation quaternion.
// Compute location of the point in the Rotating frame subject to the transformation matrix.
{
// Initialize initial location vector in inertial frame.
Eigen::Vector3d startLocation;
startLocation( 0 ) = 4.0;
startLocation( 1 ) = 1.0;
startLocation( 2 ) = 5.0;
double horizontalStartLocationSize = sqrt( pow( startLocation( 0 ), 2.0 )
+ pow( startLocation( 1 ), 2.0 ) );
// Declare and initialize angle between vector and XR-axis.
double startAngle = atan2( startLocation( 1 ), startLocation( 0 ) );
// Rotate by 10 degrees around the positive Z-axis
double angleInTime = convertDegreesToRadians( 10.0 );
// Declare and initialize the angle between the XI- and XR-axis.
double endAngle = startAngle - angleInTime;
// Declare the expected location of the point in the planetocentric reference frame.
Eigen::Vector3d expectedLocation;
expectedLocation( 0 ) = horizontalStartLocationSize * cos( endAngle );
expectedLocation( 1 ) = horizontalStartLocationSize * sin( endAngle );
expectedLocation( 2 ) = startLocation( 2 );
// Compute location of the point in the rotating frame subject to the transformation matrix.
Eigen::Vector3d transformedLocation;
transformedLocation = reference_frames::
getInertialToPlanetocentricFrameTransformationQuaternion( angleInTime )
* startLocation;
// Check whether both vectors are equal within tolerances.
TUDAT_CHECK_MATRIX_CLOSE_FRACTION( transformedLocation, expectedLocation,
std::numeric_limits< double >::epsilon( ) );
}
// Test 4: Same test as Test 2 for the transformation quaternion.
// Compute the error in the calculation.
{
// Initialize initial location vector in inertial frame.
Eigen::Vector3d startLocation;
startLocation( 0 ) = 4.0;
startLocation( 1 ) = 1.0;
startLocation( 2 ) = 5.0;
// Rotate by 10 degrees around the positive Z-axis
double angleInTime = convertDegreesToRadians( 10.0 );
// Compute location of the point in the rotating frame subject to the transformation matrix.
Eigen::Vector3d transformedLocation;
transformedLocation = reference_frames::
getRotatingPlanetocentricToInertialFrameTransformationQuaternion( angleInTime ) *
reference_frames::
getInertialToPlanetocentricFrameTransformationQuaternion( angleInTime )
* startLocation;
// Check whether both vectors are equal within tolerances.
TUDAT_CHECK_MATRIX_CLOSE_FRACTION( transformedLocation, startLocation,
std::numeric_limits< double >::epsilon( ) );
}
}
BOOST_AUTO_TEST_CASE( testAirspeedBasedAerodynamicToBodyFrameTransformation )
{
// Using declarations.
using std::atan2;
using std::cos;
using tudat::unit_conversions::convertDegreesToRadians;
// Test 5: Test airspeed-Based Aerodynamic to body frame transformation.
// Declare and initialize the start location and angles.
{
// Initialize initial location vector in inertial frame.
Eigen::Vector3d startLocation;
startLocation( 0 ) = -10.0;
startLocation( 1 ) = 0.0;
startLocation( 2 ) = 0.0;
double angleOfAttack = convertDegreesToRadians( 45.0 );
double angleOfSideslip = convertDegreesToRadians( 60.0 );;
// Compute expected location.
// As there is only an angle of attack, the following simplified equations can be used.
Eigen::Vector3d expectedLocation;
expectedLocation( 0 ) = startLocation( 0 ) * cos( angleOfSideslip ) * cos( angleOfAttack );
expectedLocation( 1 ) = startLocation( 0 ) * sin( angleOfSideslip );
expectedLocation( 2 ) = startLocation( 0 ) * cos( angleOfSideslip ) * sin( angleOfAttack );
// Compute location of the point in the rotating frame subject to the transformation matrix.
Eigen::Vector3d transformedLocation;
transformedLocation = reference_frames::
getAirspeedBasedAerodynamicToBodyFrameTransformationMatrix( angleOfAttack,
angleOfSideslip )
* startLocation;
// Check whether both vectors are equal within tolerances.
TUDAT_CHECK_MATRIX_CLOSE_FRACTION( transformedLocation, expectedLocation, 1.0e-14 );
}
}
BOOST_AUTO_TEST_CASE( testRotatingPlanetocentricToLocalVerticalFrameTransformationQuaternion )
{
// Using declarations.
using std::atan2;
using std::cos;
using std::sin;
using tudat::unit_conversions::convertDegreesToRadians;
// Test 6: Test Rotating planetocentric to local vertical frame transformation quaternion.
{
// Initialize initial location vector.
Eigen::Vector3d startLocation;
startLocation( 0 ) = 10.0;
startLocation( 1 ) = 5.0;
startLocation( 2 ) = 2.0;
// Declare rotation angle for planet and set to 90 degrees.
double longitude = convertDegreesToRadians( 60.0 );
// Declare latitude and set to 45 degrees.
double latitude = convertDegreesToRadians( 20.0 );
// Declare the expected location of the point in the planet reference frame.
Eigen::Vector3d expectedLocation;
expectedLocation( 0 ) = -cos( longitude ) * sin( latitude ) * startLocation( 0 ) -
sin( longitude ) * sin( latitude ) * startLocation( 1 ) +
cos( latitude ) * startLocation( 2 );
expectedLocation( 1 ) = -sin( longitude ) * startLocation( 0 ) +
cos( longitude ) * startLocation( 1 ) +
0.0;
expectedLocation( 2 ) = -cos( longitude ) * cos( latitude ) * startLocation( 0 ) -
sin( longitude ) * cos( latitude ) * startLocation( 1 ) -
sin( latitude ) * startLocation( 2 );
// Compute location of the point in the rotating frame subject to the transformation matrix.
Eigen::Vector3d transformedLocation;
transformedLocation = reference_frames::
getRotatingPlanetocentricToLocalVerticalFrameTransformationQuaternion( longitude,
latitude )
* startLocation;
// Check whether both vectors are equal within tolerances.
TUDAT_CHECK_MATRIX_CLOSE_FRACTION( transformedLocation, expectedLocation, 1.0e-14 );
}
// Test 7: Check whether the transformed matrix of Test 6 is also correct.
// Compute the error in the calculation.
{
// Initialize initial location vector.
Eigen::Vector3d startLocation;
startLocation( 0 ) = 10.0;
startLocation( 1 ) = 5.0;
startLocation( 2 ) = 2.0;
// Declare rotation angle for planet and set to 90 degrees.
double longitude = convertDegreesToRadians( 60.0 );
// Declare latitude and set to 45 degrees.
double latitude = convertDegreesToRadians( 20.0 );
// Compute location of the point in the rotating frame subject to the transformation matrix.
Eigen::Vector3d transformedLocation;
transformedLocation = reference_frames::
getLocalVerticalToRotatingPlanetocentricFrameTransformationQuaternion( longitude,
latitude )
* reference_frames::
getRotatingPlanetocentricToLocalVerticalFrameTransformationQuaternion( longitude,
latitude )
* startLocation;
// Check whether both vectors are equal within tolerances.
TUDAT_CHECK_MATRIX_CLOSE_FRACTION( transformedLocation, startLocation, 1.0e-14 );
}
}
BOOST_AUTO_TEST_SUITE_END( )
} //namespace unit_tests
} //namespace tudat
<commit_msg>Repository management wiki test: rollback to r472 (issue #499)<commit_after>/* Copyright (c) 2010-2012, Delft University of Technology
* 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 Delft University of Technology 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 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.
*
* Changelog
* YYMMDD Author Comment
* 110519 F.M. Engelen Creation of code.
* 110628 K. Kumar Minor comment and layout modifications.
* 110701 K. Kumar Updated unit tests to check relative error;
* Updated file path.
* 110718 F.M. Engelen Took out falacy in test (only checking the norm) and
* added ItoE and EtoI transformation.
* 110726 K. Kumar Minor modifications; updated relative error
* wrt to norm.
* 110808 F.M. Engelen Updated with better tests, changed test for vertical frame.
* 120529 E.A.G. Heeren Boostified unit tests.
* 120614 P. Musegaas Removed unneccessary using statements and normalizations.
*
* References
*
* The reference frame definitions/abbreviations can be found in the file
* referenceFrameTransformations.h.
*
*/
#define BOOST_TEST_MAIN
#include <boost/test/unit_test.hpp>
#include <Eigen/Core>
#include <TudatCore/Basics/testMacros.h>
#include <TudatCore/Astrodynamics/BasicAstrodynamics/unitConversions.h>
#include "Tudat/Astrodynamics/ReferenceFrames/referenceFrameTransformations.h"
namespace tudat
{
namespace unit_tests
{
BOOST_AUTO_TEST_SUITE( test_reference_frame_transformations )
// Summary of tests.
// Test 1: Test inertial to rotating planetocentric frame transformation.
// Test 2: Check whether the transformed matrix of Test 1 is also correct.
// Test 3: Same test as Test 1 for the transformation quaternion.
// Test 4: Same test as Test 2 for the transformation quaternion.
// Test 5: Test airspeed-based aerodynamic to body frame transformation.
// Test 6: Test planetocentric to local vertical frame transformation quaternion.
// Test 7: Check whether the transformed matrix of Test 6 is also correct.
// Test inertial to rotating planetocentric frame transformations.
BOOST_AUTO_TEST_CASE( testRotatingPlanetocentricFrameTransformations )
{
// Using declarations.
using std::atan2;
using std::cos;
using std::sin;
using std::pow;
using std::sqrt;
using tudat::unit_conversions::convertDegreesToRadians;
// Test 1: Test Inertial to rotating planetocentric frame transformation.
{
// Initialize initial location vector in inertial frame.
Eigen::Vector3d startLocation;
startLocation( 0 ) = 4.0;
startLocation( 1 ) = 1.0;
startLocation( 2 ) = 5.0;
double horizontalStartLocationSize = sqrt( pow( startLocation( 0 ), 2.0 )
+ pow( startLocation( 1 ), 2.0 ) );
// Declare and initialize angle between vector and XR-axis.
double startAngle = atan2( startLocation( 1 ), startLocation( 0 ) );
// Rotate by 10 degrees around the positive Z-axis
double angleInTime = convertDegreesToRadians( 10.0 );
// Declare and initialize the angle between the XI- and XR-axis.
double endAngle = startAngle - angleInTime;
// Declare the expected location of the point in the planetocentric reference frame.
Eigen::Vector3d expectedLocation;
expectedLocation( 0 ) = horizontalStartLocationSize * cos( endAngle );
expectedLocation( 1 ) = horizontalStartLocationSize * sin( endAngle );
expectedLocation( 2 ) = startLocation( 2 );
// Compute location of the point in the rotating frame subject to the transformation matrix.
Eigen::Vector3d transformedLocation;
transformedLocation = reference_frames::
getInertialToPlanetocentricFrameTransformationMatrix( angleInTime ) * startLocation;
// Check whether both vectors are equal within tolerances.
TUDAT_CHECK_MATRIX_CLOSE_FRACTION( transformedLocation, expectedLocation,
std::numeric_limits< double >::epsilon( ) );
}
// Test 2: Check whether the transformed matrix of Test 1 is also correct.
// Compute the error in the calculation.
{
// Initialize initial location vector in inertial frame.
Eigen::Vector3d startLocation;
startLocation( 0 ) = 4.0;
startLocation( 1 ) = 1.0;
startLocation( 2 ) = 5.0;
// Rotate by 10 degrees around the positive Z-axis
double angleInTime = convertDegreesToRadians( 10.0 );
// Compute location of the point in the rotating frame subject to the transformation matrix.
Eigen::Vector3d transformedLocation;
transformedLocation = tudat::reference_frames::
getRotatingPlanetocentricToInertialFrameTransformationMatrix( angleInTime ) *
tudat::reference_frames::
getInertialToPlanetocentricFrameTransformationMatrix( angleInTime )
* startLocation;
// Check whether both vectors are equal within tolerances.
TUDAT_CHECK_MATRIX_CLOSE_FRACTION( transformedLocation, startLocation,
std::numeric_limits< double >::epsilon( ) );
}
}
BOOST_AUTO_TEST_CASE( testRotatingPlanetocentricFrameTransformationQuaternion )
{
// Using declarations.
using std::atan2;
using std::cos;
using std::sin;
using std::pow;
using std::sqrt;
using tudat::unit_conversions::convertDegreesToRadians;
// Test 3: Same test as Test 1 for the transformation quaternion.
// Compute location of the point in the Rotating frame subject to the transformation matrix.
{
// Initialize initial location vector in inertial frame.
Eigen::Vector3d startLocation;
startLocation( 0 ) = 4.0;
startLocation( 1 ) = 1.0;
startLocation( 2 ) = 5.0;
double horizontalStartLocationSize = sqrt( pow( startLocation( 0 ), 2.0 )
+ pow( startLocation( 1 ), 2.0 ) );
// Declare and initialize angle between vector and XR-axis.
double startAngle = atan2( startLocation( 1 ), startLocation( 0 ) );
// Rotate by 10 degrees around the positive Z-axis
double angleInTime = convertDegreesToRadians( 10.0 );
// Declare and initialize the angle between the XI- and XR-axis.
double endAngle = startAngle - angleInTime;
// Declare the expected location of the point in the planetocentric reference frame.
Eigen::Vector3d expectedLocation;
expectedLocation( 0 ) = horizontalStartLocationSize * cos( endAngle );
expectedLocation( 1 ) = horizontalStartLocationSize * sin( endAngle );
expectedLocation( 2 ) = startLocation( 2 );
// Compute location of the point in the rotating frame subject to the transformation matrix.
Eigen::Vector3d transformedLocation;
transformedLocation = reference_frames::
getInertialToPlanetocentricFrameTransformationQuaternion( angleInTime )
* startLocation;
// Check whether both vectors are equal within tolerances.
TUDAT_CHECK_MATRIX_CLOSE_FRACTION( transformedLocation, expectedLocation,
std::numeric_limits< double >::epsilon( ) );
}
// Test 4: Same test as Test 2 for the transformation quaternion.
// Compute the error in the calculation.
{
// Initialize initial location vector in inertial frame.
Eigen::Vector3d startLocation;
startLocation( 0 ) = 4.0;
startLocation( 1 ) = 1.0;
startLocation( 2 ) = 5.0;
// Rotate by 10 degrees around the positive Z-axis
double angleInTime = convertDegreesToRadians( 10.0 );
// Compute location of the point in the rotating frame subject to the transformation matrix.
Eigen::Vector3d transformedLocation;
transformedLocation = reference_frames::
getRotatingPlanetocentricToInertialFrameTransformationQuaternion( angleInTime ) *
reference_frames::
getInertialToPlanetocentricFrameTransformationQuaternion( angleInTime )
* startLocation;
// Check whether both vectors are equal within tolerances.
TUDAT_CHECK_MATRIX_CLOSE_FRACTION( transformedLocation, startLocation,
std::numeric_limits< double >::epsilon( ) );
}
}
BOOST_AUTO_TEST_CASE( testAirspeedBasedAerodynamicToBodyFrameTransformation )
{
// Using declarations.
using std::atan2;
using std::cos;
using tudat::unit_conversions::convertDegreesToRadians;
// Test 5: Test airspeed-Based Aerodynamic to body frame transformation.
// Declare and initialize the start location and angles.
{
// Initialize initial location vector in inertial frame.
Eigen::Vector3d startLocation;
startLocation( 0 ) = -10.0;
startLocation( 1 ) = 0.0;
startLocation( 2 ) = 0.0;
double angleOfAttack = convertDegreesToRadians( 45.0 );
double angleOfSideslip = convertDegreesToRadians( 60.0 );;
// Compute expected location.
// As there is only an angle of attack, the following simplified equations can be used.
Eigen::Vector3d expectedLocation;
expectedLocation( 0 ) = startLocation( 0 ) * cos( angleOfSideslip ) * cos( angleOfAttack );
expectedLocation( 1 ) = startLocation( 0 ) * sin( angleOfSideslip );
expectedLocation( 2 ) = startLocation( 0 ) * cos( angleOfSideslip ) * sin( angleOfAttack );
// Compute location of the point in the rotating frame subject to the transformation matrix.
Eigen::Vector3d transformedLocation;
transformedLocation = reference_frames::
getAirspeedBasedAerodynamicToBodyFrameTransformationMatrix( angleOfAttack,
angleOfSideslip )
* startLocation;
// Check whether both vectors are equal within tolerances.
TUDAT_CHECK_MATRIX_CLOSE_FRACTION( transformedLocation, expectedLocation, 1.0e-14 );
}
}
BOOST_AUTO_TEST_CASE( testRotatingPlanetocentricToLocalVerticalFrameTransformationQuaternion )
{
// Using declarations.
using std::atan2;
using std::cos;
using std::sin;
using tudat::unit_conversions::convertDegreesToRadians;
// Test 6: Test Rotating planetocentric to local vertical frame transformation quaternion.
{
// Initialize initial location vector.
Eigen::Vector3d startLocation;
startLocation( 0 ) = 10.0;
startLocation( 1 ) = 5.0;
startLocation( 2 ) = 2.0;
// Declare rotation angle for planet and set to 90 degrees.
double longitude = convertDegreesToRadians( 60.0 );
// Declare latitude and set to 45 degrees.
double latitude = convertDegreesToRadians( 20.0 );
// Declare the expected location of the point in the planet reference frame.
Eigen::Vector3d expectedLocation;
expectedLocation( 0 ) = -cos( longitude ) * sin( latitude ) * startLocation( 0 ) -
sin( longitude ) * sin( latitude ) * startLocation( 1 ) +
cos( latitude ) * startLocation( 2 );
expectedLocation( 1 ) = -sin( longitude ) * startLocation( 0 ) +
cos( longitude ) * startLocation( 1 ) +
0.0;
expectedLocation( 2 ) = -cos( longitude ) * cos( latitude ) * startLocation( 0 ) -
sin( longitude ) * cos( latitude ) * startLocation( 1 ) -
sin( latitude ) * startLocation( 2 );
// Compute location of the point in the rotating frame subject to the transformation matrix.
Eigen::Vector3d transformedLocation;
transformedLocation = reference_frames::
getRotatingPlanetocentricToLocalVerticalFrameTransformationQuaternion( longitude,
latitude )
* startLocation;
// Check whether both vectors are equal within tolerances.
TUDAT_CHECK_MATRIX_CLOSE_FRACTION( transformedLocation, expectedLocation, 1.0e-14 );
}
// Test 7: Check whether the transformed matrix of Test 6 is also correct.
// Compute the error in the calculation.
{
// Initialize initial location vector.
Eigen::Vector3d startLocation;
startLocation( 0 ) = 10.0;
startLocation( 1 ) = 5.0;
startLocation( 2 ) = 2.0;
// Declare rotation angle for planet and set to 90 degrees.
double longitude = convertDegreesToRadians( 60.0 );
// Declare latitude and set to 45 degrees.
double latitude = convertDegreesToRadians( 20.0 );
// Compute location of the point in the rotating frame subject to the transformation matrix.
Eigen::Vector3d transformedLocation;
transformedLocation = reference_frames::
getLocalVerticalToRotatingPlanetocentricFrameTransformationQuaternion( longitude,
latitude )
* reference_frames::
getRotatingPlanetocentricToLocalVerticalFrameTransformationQuaternion( longitude,
latitude )
* startLocation;
// Check whether both vectors are equal within tolerances.
TUDAT_CHECK_MATRIX_CLOSE_FRACTION( transformedLocation, startLocation, 1.0e-14 );
}
}
BOOST_AUTO_TEST_SUITE_END( )
} //namespace unit_tests
} //namespace tudat
<|endoftext|> |
<commit_before>/*
* Copyright 2008-2009 NVIDIA Corporation
*
* 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.
*/
/*! \file gather.inl
* \brief Inline file for gather.h
*/
#pragma once
#include <thrust/iterator/iterator_traits.h>
#include <thrust/detail/device/cuda/vectorize.h>
#include <thrust/detail/device/dereference.h>
namespace thrust
{
namespace detail
{
namespace device
{
namespace detail
{
//////////////
// Functors //
//////////////
template <typename ForwardIterator, typename InputIterator, typename RandomAccessIterator>
struct gather_functor
{
ForwardIterator first;
InputIterator map;
RandomAccessIterator input;
gather_functor(ForwardIterator _first, InputIterator _map, RandomAccessIterator _input)
: first(_first), map(_map), input(_input) {}
template <typename IntegerType>
__device__
void operator()(const IntegerType& i)
{
//output[i] = input[map[i]];
thrust::detail::device::dereference(first, i) = thrust::detail::device::dereference(input, thrust::detail::device::dereference(map, i));
}
}; // end gather_functor
template <typename ForwardIterator, typename InputIterator1, typename InputIterator2, typename RandomAccessIterator, typename Predicate>
struct gather_if_functor
{
ForwardIterator first;
InputIterator1 map;
InputIterator2 stencil;
RandomAccessIterator input;
Predicate pred;
gather_if_functor(ForwardIterator _first, InputIterator1 _map, InputIterator2 _stencil, RandomAccessIterator _input, Predicate _pred)
: first(_first), map(_map), stencil(_stencil), input(_input), pred(_pred) {}
template <typename IntegerType>
__device__
void operator()(const IntegerType& i)
{
//if(pred(stencil[i])
// output[i] = input[map[i]];
if(pred(thrust::detail::device::dereference(stencil, i)))
thrust::detail::device::dereference(first, i) = thrust::detail::device::dereference(input, thrust::detail::device::dereference(map, i));
}
}; // end gather_functor
} // end detail
template<typename ForwardIterator,
typename InputIterator,
typename RandomAccessIterator>
void gather(ForwardIterator first,
ForwardIterator last,
InputIterator map,
RandomAccessIterator input)
{
detail::gather_functor<ForwardIterator, InputIterator, RandomAccessIterator> func(first, map, input);
thrust::detail::device::cuda::vectorize(last - first, func);
} // end gather()
template<typename ForwardIterator,
typename InputIterator1,
typename InputIterator2,
typename RandomAccessIterator,
typename Predicate>
void gather_if(ForwardIterator first,
ForwardIterator last,
InputIterator1 map,
InputIterator2 stencil,
RandomAccessIterator input,
Predicate pred)
{
detail::gather_if_functor<ForwardIterator, InputIterator1, InputIterator2, RandomAccessIterator, Predicate> func(first, map, stencil, input, pred);
thrust::detail::device::cuda::vectorize(last - first, func);
} // end gather_if()
} // end namespace device
} // end namespace detail
} // end namespace thrust
<commit_msg>Implement device gather with device for_each.<commit_after>/*
* Copyright 2008-2009 NVIDIA Corporation
*
* 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.
*/
/*! \file gather.inl
* \brief Inline file for gather.h
*/
#pragma once
#include <thrust/detail/device/for_each.h>
#include <thrust/detail/device/dereference.h>
#include <thrust/distance.h>
namespace thrust
{
namespace detail
{
namespace device
{
namespace detail
{
template <typename RandomAccessIterator>
struct gather_functor
{
RandomAccessIterator input;
gather_functor(RandomAccessIterator _input)
: input(_input) {}
template <typename Tuple>
__device__
void operator()(Tuple t)
{
thrust::get<0>(t) = thrust::detail::device::dereference(input, thrust::get<1>(t));
}
}; // end gather_functor
template <typename RandomAccessIterator, typename Predicate>
struct gather_if_functor
{
RandomAccessIterator input;
Predicate pred;
gather_if_functor(RandomAccessIterator _input, Predicate _pred)
: input(_input), pred(_pred) {}
template <typename Tuple>
__device__
void operator()(Tuple t)
{
if(pred(thrust::get<2>(t)))
thrust::get<0>(t) = thrust::detail::device::dereference(input, thrust::get<1>(t));
}
}; // end gather_functor
} // end detail
template<typename ForwardIterator,
typename InputIterator,
typename RandomAccessIterator>
void gather(ForwardIterator first,
ForwardIterator last,
InputIterator map,
RandomAccessIterator input)
{
detail::gather_functor<RandomAccessIterator> func(input);
thrust::detail::device::for_each(thrust::make_zip_iterator(thrust::make_tuple(first, map)),
thrust::make_zip_iterator(thrust::make_tuple(last, map + thrust::distance(first, last))),
func);
} // end gather()
template<typename ForwardIterator,
typename InputIterator1,
typename InputIterator2,
typename RandomAccessIterator,
typename Predicate>
void gather_if(ForwardIterator first,
ForwardIterator last,
InputIterator1 map,
InputIterator2 stencil,
RandomAccessIterator input,
Predicate pred)
{
detail::gather_if_functor<RandomAccessIterator, Predicate> func(input, pred);
thrust::detail::device::for_each(thrust::make_zip_iterator(thrust::make_tuple(first, map, stencil)),
thrust::make_zip_iterator(thrust::make_tuple(last, map + thrust::distance(first, last), stencil + thrust::distance(first, last))),
func);
} // end gather_if()
} // end namespace device
} // end namespace detail
} // end namespace thrust
<|endoftext|> |
<commit_before>#include <cstdio>
#include <vector>
#include <stack>
#include <algorithm>
#include <memory>
namespace Frogs
{
enum class Frog { None, Brown, Green };
enum class Step { None, JumpLeft, LeapLeft, JumpRight, LeapRight };
class State
{
std::vector<Frog> lilies;
int count, blankPos;
Step movement;
public:
State(): count(0), blankPos(-1), movement(Step::None)
{
}
State(int count): lilies(2 * count + 1), count(count), blankPos(count), movement(Step::None)
{
for (int i = 0; i < count; ++i)
{
lilies[i] = Frog::Brown;
lilies[2 * count - i] = Frog::Green;
}
lilies[blankPos] = Frog::None;
}
Step GetMovement() const { return movement; }
bool operator==(const State& other) const
{
return count == other.count && lilies == other.lilies && blankPos == other.blankPos && movement == other.movement;
}
bool IsStuckJumpLeft() const { return blankPos >= (int)lilies.size() - 1 || lilies[blankPos + 1] != Frog::Green; }
bool IsStuckLeapLeft() const { return blankPos >= (int)lilies.size() - 2 || lilies[blankPos + 2] != Frog::Green; }
bool IsStuckJumpRight() const { return blankPos < 1 || lilies[blankPos - 1] != Frog::Brown; }
bool IsStuckLeapRight() const { return blankPos < 2 || lilies[blankPos - 2] != Frog::Brown; }
bool WasTargetReached() const
{
for (int i = 0; i < count; ++i)
if (lilies[i] != Frog::Green || lilies[2 * count - i] != Frog::Brown)
return false;
return lilies[count] == Frog::None;
}
std::shared_ptr<State> Move(Step movement) const
{
bool canMove = false;
auto moved = std::make_shared<State>(*this);
moved->movement = movement;
switch (movement)
{
case Step::JumpLeft:
if (!moved->IsStuckJumpLeft())
{
moved->lilies[moved->blankPos] = Frog::Green;
moved->blankPos++;
canMove = true;
}
break;
case Step::LeapLeft:
if (!moved->IsStuckLeapLeft())
{
moved->lilies[moved->blankPos] = Frog::Green;
moved->blankPos += 2;
canMove = true;
}
break;
case Step::JumpRight:
if (!moved->IsStuckJumpRight())
{
moved->lilies[moved->blankPos] = Frog::Brown;
moved->blankPos--;
canMove = true;
}
break;
case Step::LeapRight:
if (!moved->IsStuckLeapRight())
{
moved->lilies[moved->blankPos] = Frog::Brown;
moved->blankPos -= 2;
canMove = true;
}
break;
default:
break;
}
if (canMove)
moved->lilies[moved->blankPos] = Frog::None;
return canMove ? moved : nullptr;
}
void Print() const
{
for (const auto& frog: lilies)
switch (frog)
{
case Frog::Brown:
printf(">");
break;
case Frog::Green:
printf("<");
break;
case Frog::None:
printf("_");
break;
}
printf("\n");
}
};
}
int main()
{
int count;
scanf("%u", &count);
if (count < 0)
return 1;
std::vector<std::shared_ptr<Frogs::State> > visited;
std::stack<std::shared_ptr<Frogs::State> > trace;
std::stack<Frogs::Step> movements;
trace.push(std::make_shared<Frogs::State>(count));
while (!trace.empty() && !trace.top()->WasTargetReached())
{
auto state = trace.top();
trace.pop();
auto move = [&](Frogs::Step movement)
{
auto newState = state->Move(movement);
if (newState)
trace.push(newState);
};
while (!movements.empty() && state && state->IsStuckJumpLeft() && state->IsStuckLeapLeft() && state->IsStuckJumpRight() && state->IsStuckLeapRight())
movements.pop();
if (!state)
continue;
if (visited.crend() == std::find(visited.crbegin(), visited.crend(), state))
{
visited.push_back(state);
movements.push(state->GetMovement());
move(Frogs::Step::JumpLeft);
move(Frogs::Step::LeapLeft);
move(Frogs::Step::JumpRight);
move(Frogs::Step::LeapRight);
state->Print();
}
}
if (!trace.empty())
trace.top()->Print();
return 0;
}
<commit_msg>frogs: dropped the movements stack as it is unnecessary<commit_after>#include <cstdio>
#include <vector>
#include <stack>
#include <algorithm>
#include <memory>
namespace Frogs
{
enum class Frog { None, Brown, Green };
enum class Step { None, JumpLeft, LeapLeft, JumpRight, LeapRight };
class State
{
std::vector<Frog> lilies;
int count, blankPos;
Step movement;
public:
State(): count(0), blankPos(-1), movement(Step::None)
{
}
State(int count): lilies(2 * count + 1), count(count), blankPos(count), movement(Step::None)
{
for (int i = 0; i < count; ++i)
{
lilies[i] = Frog::Brown;
lilies[2 * count - i] = Frog::Green;
}
lilies[blankPos] = Frog::None;
}
Step GetMovement() const { return movement; }
bool operator==(const State& other) const
{
return count == other.count && lilies == other.lilies && blankPos == other.blankPos && movement == other.movement;
}
bool IsStuckJumpLeft() const { return blankPos >= (int)lilies.size() - 1 || lilies[blankPos + 1] != Frog::Green; }
bool IsStuckLeapLeft() const { return blankPos >= (int)lilies.size() - 2 || lilies[blankPos + 2] != Frog::Green; }
bool IsStuckJumpRight() const { return blankPos < 1 || lilies[blankPos - 1] != Frog::Brown; }
bool IsStuckLeapRight() const { return blankPos < 2 || lilies[blankPos - 2] != Frog::Brown; }
bool WasTargetReached() const
{
for (int i = 0; i < count; ++i)
if (lilies[i] != Frog::Green || lilies[2 * count - i] != Frog::Brown)
return false;
return lilies[count] == Frog::None;
}
std::shared_ptr<State> Move(Step movement) const
{
bool canMove = false;
auto moved = std::make_shared<State>(*this);
moved->movement = movement;
switch (movement)
{
case Step::JumpLeft:
if (!moved->IsStuckJumpLeft())
{
moved->lilies[moved->blankPos] = Frog::Green;
moved->blankPos++;
canMove = true;
}
break;
case Step::LeapLeft:
if (!moved->IsStuckLeapLeft())
{
moved->lilies[moved->blankPos] = Frog::Green;
moved->blankPos += 2;
canMove = true;
}
break;
case Step::JumpRight:
if (!moved->IsStuckJumpRight())
{
moved->lilies[moved->blankPos] = Frog::Brown;
moved->blankPos--;
canMove = true;
}
break;
case Step::LeapRight:
if (!moved->IsStuckLeapRight())
{
moved->lilies[moved->blankPos] = Frog::Brown;
moved->blankPos -= 2;
canMove = true;
}
break;
default:
break;
}
if (canMove)
moved->lilies[moved->blankPos] = Frog::None;
return canMove ? moved : nullptr;
}
void Print() const
{
for (const auto& frog: lilies)
switch (frog)
{
case Frog::Brown:
printf(">");
break;
case Frog::Green:
printf("<");
break;
case Frog::None:
printf("_");
break;
}
printf("\n");
}
};
}
int main()
{
int count;
scanf("%u", &count);
if (count < 0)
return 1;
std::vector<std::shared_ptr<Frogs::State> > visited;
std::stack<std::shared_ptr<Frogs::State> > trace;
trace.push(std::make_shared<Frogs::State>(count));
while (!trace.empty() && !trace.top()->WasTargetReached())
{
auto state = trace.top();
trace.pop();
auto move = [&](Frogs::Step movement)
{
auto newState = state->Move(movement);
if (newState)
trace.push(newState);
};
if (!state)
continue;
if (visited.crend() == std::find(visited.crbegin(), visited.crend(), state))
{
visited.push_back(state);
move(Frogs::Step::JumpLeft);
move(Frogs::Step::LeapLeft);
move(Frogs::Step::JumpRight);
move(Frogs::Step::LeapRight);
state->Print();
}
}
if (!trace.empty())
trace.top()->Print();
return 0;
}
<|endoftext|> |
<commit_before>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*
* This file is part of the LibreOffice project.
*
* 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/.
*/
#include <sal/config.h>
#include <test/bootstrapfixture.hxx>
#include <test/unoapi_test.hxx>
#include <rtl/strbuf.hxx>
#include <osl/file.hxx>
#include <com/sun/star/frame/Desktop.hpp>
#include <com/sun/star/lang/XComponent.hpp>
#include <com/sun/star/frame/XStorable.hpp>
#include <com/sun/star/document/XEmbeddedScripts.hpp>
#include <com/sun/star/script/XStorageBasedLibraryContainer.hpp>
#include <com/sun/star/script/XLibraryContainer.hpp>
#include <com/sun/star/util/XModifiable.hpp>
#include <com/sun/star/container/XHierarchicalNameAccess.hpp>
#include <com/sun/star/io/XStream.hpp>
#include <com/sun/star/io/XInputStream.hpp>
#include <sfx2/app.hxx>
#include <sfx2/docfilt.hxx>
#include <sfx2/docfile.hxx>
#include <sfx2/objsh.hxx>
#include <sfx2/sfxmodelfactory.hxx>
#include <svl/intitem.hxx>
#include <comphelper/processfactory.hxx>
#include <basic/sbxdef.hxx>
using namespace ::com::sun::star;
using namespace ::com::sun::star::uno;
class DialogSaveTest : public UnoApiTest
{
public:
DialogSaveTest();
void test();
CPPUNIT_TEST_SUITE(DialogSaveTest);
// Should we disable this test on MOX and WNT?
// #if !defined(MACOSX) && !defined(WNT)
CPPUNIT_TEST(test);
// #endif
CPPUNIT_TEST_SUITE_END();
};
DialogSaveTest::DialogSaveTest()
: UnoApiTest("/dbaccess/qa/extras/testdocuments")
{
}
void DialogSaveTest::test()
{
OUString aFileName;
aFileName = getURLFromWorkdir("CppunitTest/testDialogSave.odb");
{
uno::Reference< lang::XComponent > xComponent = loadFromDesktop(aFileName);
CPPUNIT_ASSERT(xComponent.is());
uno::Reference< frame::XStorable > xDocStorable(xComponent, UNO_QUERY_THROW);
CPPUNIT_ASSERT(xDocStorable.is());
uno::Reference< document::XEmbeddedScripts > xDocScr(xComponent, UNO_QUERY_THROW);
CPPUNIT_ASSERT(xDocScr.is());
uno::Reference< script::XStorageBasedLibraryContainer > xStorBasLib(xDocScr->getBasicLibraries());
CPPUNIT_ASSERT(xStorBasLib.is());
uno::Reference< script::XLibraryContainer > xBasLib(xStorBasLib, UNO_QUERY_THROW);
CPPUNIT_ASSERT(xBasLib.is());
uno::Reference< script::XStorageBasedLibraryContainer > xStorDlgLib(xDocScr->getDialogLibraries());
CPPUNIT_ASSERT(xStorDlgLib.is());
uno::Reference< script::XLibraryContainer > xDlgLib(xStorDlgLib, UNO_QUERY_THROW);
CPPUNIT_ASSERT(xDlgLib.is());
xBasLib->loadLibrary("Standard");
CPPUNIT_ASSERT(xBasLib->isLibraryLoaded("Standard"));
// the whole point of this test is to test the "save" operation
// when the Basic library is loaded, but not the Dialog library
CPPUNIT_ASSERT(!xDlgLib->isLibraryLoaded("Standard"));
// make some change to enable a save
// uno::Reference< document::XDocumentPropertiesSupplier > xDocPropSuppl(xComponent, UNO_QUERY_THROW);
// CPPUNIT_ASSERT(xDocPropSuppl.is());
// uno::Reference< document::XDocumentPropertiesSupplier > xDocProps(xDocPropSuppl->getDocumentProperties());
// CPPUNIT_ASSERT(xDocProps.is());
// xDocProps.setTitle(xDocProps.getTitle() + " suffix");
uno::Reference< util::XModifiable > xDocMod(xComponent, UNO_QUERY_THROW);
CPPUNIT_ASSERT(xDocMod.is());
xDocMod->setModified(sal_True);
// now save; the code path to exercise in this test is the "store to same location"
// do *not* change to store(As|To|URL)!
xDocStorable->store();
// close
uno::Reference< util::XCloseable > xDocCloseable(xComponent, UNO_QUERY_THROW);
CPPUNIT_ASSERT(xDocCloseable.is());
//xDocCloseable->close(false);
// All our uno::References are (should?) be invalid now -> let them go out of scope
}
{
uno::Sequence<uno::Any> args(1);
args[0] <<= aFileName;
Reference<container::XHierarchicalNameAccess> xHNA(getMultiServiceFactory()->createInstanceWithArguments("com.sun.star.packages.Package", args), UNO_QUERY_THROW);
CPPUNIT_ASSERT(xHNA.is());
Reference< beans::XPropertySet > xPS(xHNA->getByHierarchicalName("Dialogs/Standard/Dialog1.xml"), UNO_QUERY_THROW);
CPPUNIT_ASSERT(xPS.is());
sal_Int64 nSize = 0;
CPPUNIT_ASSERT(xPS->getPropertyValue("Size") >>= nSize);
CPPUNIT_ASSERT(nSize != 0);
}
}
CPPUNIT_TEST_SUITE_REGISTRATION(DialogSaveTest);
CPPUNIT_PLUGIN_IMPLEMENT();
/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
<commit_msg>Prevent SolarMutex deadlock in unit test<commit_after>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*
* This file is part of the LibreOffice project.
*
* 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/.
*/
#include <sal/config.h>
#include <test/bootstrapfixture.hxx>
#include <test/unoapi_test.hxx>
#include <rtl/strbuf.hxx>
#include <osl/file.hxx>
#include <com/sun/star/frame/Desktop.hpp>
#include <com/sun/star/lang/XComponent.hpp>
#include <com/sun/star/frame/XStorable.hpp>
#include <com/sun/star/document/XEmbeddedScripts.hpp>
#include <com/sun/star/script/XStorageBasedLibraryContainer.hpp>
#include <com/sun/star/script/XLibraryContainer.hpp>
#include <com/sun/star/util/XModifiable.hpp>
#include <com/sun/star/container/XHierarchicalNameAccess.hpp>
#include <com/sun/star/io/XStream.hpp>
#include <com/sun/star/io/XInputStream.hpp>
#include <sfx2/app.hxx>
#include <sfx2/docfilt.hxx>
#include <sfx2/docfile.hxx>
#include <sfx2/objsh.hxx>
#include <sfx2/sfxmodelfactory.hxx>
#include <svl/intitem.hxx>
#include <comphelper/processfactory.hxx>
#include <basic/sbxdef.hxx>
using namespace ::com::sun::star;
using namespace ::com::sun::star::uno;
class DialogSaveTest : public UnoApiTest
{
public:
DialogSaveTest();
void test();
CPPUNIT_TEST_SUITE(DialogSaveTest);
// Should we disable this test on MOX and WNT?
// #if !defined(MACOSX) && !defined(WNT)
CPPUNIT_TEST(test);
// #endif
CPPUNIT_TEST_SUITE_END();
};
DialogSaveTest::DialogSaveTest()
: UnoApiTest("/dbaccess/qa/extras/testdocuments")
{
}
void DialogSaveTest::test()
{
// UnoApiTest::setUp (via InitVCL) puts each test under a locked SolarMutex,
// but at least the below xDocCloseable->close call could lead to a deadlock
// then, and it looks like none of the code here requires the SolarMutex to
// be locked anyway:
SolarMutexReleaser rel;
OUString aFileName;
aFileName = getURLFromWorkdir("CppunitTest/testDialogSave.odb");
{
uno::Reference< lang::XComponent > xComponent = loadFromDesktop(aFileName);
CPPUNIT_ASSERT(xComponent.is());
uno::Reference< frame::XStorable > xDocStorable(xComponent, UNO_QUERY_THROW);
CPPUNIT_ASSERT(xDocStorable.is());
uno::Reference< document::XEmbeddedScripts > xDocScr(xComponent, UNO_QUERY_THROW);
CPPUNIT_ASSERT(xDocScr.is());
uno::Reference< script::XStorageBasedLibraryContainer > xStorBasLib(xDocScr->getBasicLibraries());
CPPUNIT_ASSERT(xStorBasLib.is());
uno::Reference< script::XLibraryContainer > xBasLib(xStorBasLib, UNO_QUERY_THROW);
CPPUNIT_ASSERT(xBasLib.is());
uno::Reference< script::XStorageBasedLibraryContainer > xStorDlgLib(xDocScr->getDialogLibraries());
CPPUNIT_ASSERT(xStorDlgLib.is());
uno::Reference< script::XLibraryContainer > xDlgLib(xStorDlgLib, UNO_QUERY_THROW);
CPPUNIT_ASSERT(xDlgLib.is());
xBasLib->loadLibrary("Standard");
CPPUNIT_ASSERT(xBasLib->isLibraryLoaded("Standard"));
// the whole point of this test is to test the "save" operation
// when the Basic library is loaded, but not the Dialog library
CPPUNIT_ASSERT(!xDlgLib->isLibraryLoaded("Standard"));
// make some change to enable a save
// uno::Reference< document::XDocumentPropertiesSupplier > xDocPropSuppl(xComponent, UNO_QUERY_THROW);
// CPPUNIT_ASSERT(xDocPropSuppl.is());
// uno::Reference< document::XDocumentPropertiesSupplier > xDocProps(xDocPropSuppl->getDocumentProperties());
// CPPUNIT_ASSERT(xDocProps.is());
// xDocProps.setTitle(xDocProps.getTitle() + " suffix");
uno::Reference< util::XModifiable > xDocMod(xComponent, UNO_QUERY_THROW);
CPPUNIT_ASSERT(xDocMod.is());
xDocMod->setModified(sal_True);
// now save; the code path to exercise in this test is the "store to same location"
// do *not* change to store(As|To|URL)!
xDocStorable->store();
// close
uno::Reference< util::XCloseable > xDocCloseable(xComponent, UNO_QUERY_THROW);
CPPUNIT_ASSERT(xDocCloseable.is());
xDocCloseable->close(false);
// All our uno::References are (should?) be invalid now -> let them go out of scope
}
{
uno::Sequence<uno::Any> args(1);
args[0] <<= aFileName;
Reference<container::XHierarchicalNameAccess> xHNA(getMultiServiceFactory()->createInstanceWithArguments("com.sun.star.packages.Package", args), UNO_QUERY_THROW);
CPPUNIT_ASSERT(xHNA.is());
Reference< beans::XPropertySet > xPS(xHNA->getByHierarchicalName("Dialogs/Standard/Dialog1.xml"), UNO_QUERY_THROW);
CPPUNIT_ASSERT(xPS.is());
sal_Int64 nSize = 0;
CPPUNIT_ASSERT(xPS->getPropertyValue("Size") >>= nSize);
CPPUNIT_ASSERT(nSize != 0);
}
}
CPPUNIT_TEST_SUITE_REGISTRATION(DialogSaveTest);
CPPUNIT_PLUGIN_IMPLEMENT();
/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
<|endoftext|> |
<commit_before>#include <cassert>
#include <fstream>
#include <iostream>
#include <strstream>
#include <util/PlatformUtils.hpp>
#include <PlatformSupport/DOMStringHelper.hpp>
#include <DOMSupport/DOMSupportDefault.hpp>
#include <XPath/XObjectFactoryDefault.hpp>
#include <XPath/XPathSupportDefault.hpp>
#include <XPath/XPathFactoryDefault.hpp>
#include <XSLT/StylesheetConstructionContextDefault.hpp>
#include <XSLT/StylesheetExecutionContextDefault.hpp>
#include <XSLT/StylesheetRoot.hpp>
#include <XSLT/XSLTEngineImpl.hpp>
#include <XSLT/XSLTInputSource.hpp>
#include <XSLT/XSLTProcessorEnvSupportDefault.hpp>
#include <XSLT/XSLTResultTarget.hpp>
#include <XercesParserLiaison/XercesParserLiaison.hpp>
#include <XercesPlatformSupport/TextFileOutputStream.hpp>
#include <XercesPlatformSupport/XercesDOMPrintWriter.hpp>
int
main(
int argc,
const char* /* argv */[])
{
#if !defined(XALAN_NO_NAMESPACES)
using std::cerr;
using std::endl;
using std::ifstream;
using std::ios_base;
using std::ostrstream;
using std::string;
#endif
if (argc != 1)
{
cerr << "Usage: CompileStylesheet"
<< endl
<< endl;
}
else
{
try
{
// Call the static initializers...
XMLPlatformUtils::Initialize();
XSLTEngineImpl::Initialize();
// Create the support objects that are necessary for running the processor...
DOMSupportDefault theDOMSupport;
XercesParserLiaison theParserLiaison(theDOMSupport);
XPathSupportDefault theXPathSupport(theDOMSupport);
XSLTProcessorEnvSupportDefault theXSLTProcessorEnvSupport;
XObjectFactoryDefault theXObjectFactory(
theXSLTProcessorEnvSupport,
theXPathSupport);
XPathFactoryDefault theXPathFactory;
// Create a processor...
XSLTEngineImpl theProcessor(
theParserLiaison,
theXPathSupport,
theXSLTProcessorEnvSupport,
theXObjectFactory,
theXPathFactory);
// Connect the processor to the support object...
theXSLTProcessorEnvSupport.setProcessor(&theProcessor);
// Create separate factory support objects so the stylesheet's
// factory-created XObject and XPath instances are independent
// from processor's.
XObjectFactoryDefault theStylesheetXObjectFactory(
theXSLTProcessorEnvSupport,
theXPathSupport);
XPathFactoryDefault theStylesheetXPathFactory;
// Create a stylesheet construction context, using the
// stylesheet's factory support objects.
StylesheetConstructionContextDefault theConstructionContext(
theProcessor,
theXSLTProcessorEnvSupport,
theStylesheetXObjectFactory,
theStylesheetXPathFactory);
// The execution context uses the same factory support objects as
// the processor, since those objects have the same lifetime as
// other objects created as a result of the execution.
StylesheetExecutionContextDefault theExecutionContext(
theProcessor,
theXSLTProcessorEnvSupport,
theXPathSupport,
theXObjectFactory);
// Our input files. The assumption is that the executable will be run
// from same directory as the input files.
const XalanDOMString theXMLFileName("foo.xml");
const XalanDOMString theXSLFileName("foo.xsl");
// Our stylesheet input source...
XSLTInputSource theStylesheetSource(c_wstr(theXSLFileName));
// Ask the processor to create a StylesheetRoot for the specified
// input XSL. This is the compiled stylesheet. We don't have to
// delete it, since it is owned by the StylesheetConstructionContext
// instance.
StylesheetRoot* const theStylesheetRoot =
theProcessor.processStylesheet(
theStylesheetSource,
theConstructionContext);
assert(theStylesheetRoot != 0);
for (unsigned int i = 0; i < 10; i++)
{
theExecutionContext.setStylesheetRoot(theStylesheetRoot);
// Generate the input and output file names.
ostrstream theFormatterIn, theFormatterOut;
theFormatterIn << "foo" << i + 1 << ".xml" << '\0';
theFormatterOut << "foo" << i + 1 << ".out" << '\0';
//Generate the XML input and output objects.
XSLTInputSource theInputSource(theFormatterIn.str());
XSLTResultTarget theResultTarget(theFormatterOut.str());
// Unfreeze the ostrstreams, so the memory is returned...
theFormatterIn.freeze(false);
theFormatterOut.freeze(false);
// Do the tranformation...
theProcessor.process(
theInputSource,
theResultTarget,
theExecutionContext);
// Reset the processor and the execution context
// so we can perform the next transformation.
theProcessor.reset();
theExecutionContext.reset();
}
}
catch(...)
{
cerr << "Exception caught!!!"
<< endl
<< endl;
}
}
return 0;
}
<commit_msg>Added terminator function calls, and reset call on the parser liaison.<commit_after>#include <cassert>
#include <fstream>
#include <iostream>
#include <strstream>
#include <util/PlatformUtils.hpp>
#include <PlatformSupport/DOMStringHelper.hpp>
#include <DOMSupport/DOMSupportDefault.hpp>
#include <XPath/XObjectFactoryDefault.hpp>
#include <XPath/XPathSupportDefault.hpp>
#include <XPath/XPathFactoryDefault.hpp>
#include <XSLT/StylesheetConstructionContextDefault.hpp>
#include <XSLT/StylesheetExecutionContextDefault.hpp>
#include <XSLT/StylesheetRoot.hpp>
#include <XSLT/XSLTEngineImpl.hpp>
#include <XSLT/XSLTInputSource.hpp>
#include <XSLT/XSLTProcessorEnvSupportDefault.hpp>
#include <XSLT/XSLTResultTarget.hpp>
#include <XercesParserLiaison/XercesParserLiaison.hpp>
#include <XercesPlatformSupport/TextFileOutputStream.hpp>
#include <XercesPlatformSupport/XercesDOMPrintWriter.hpp>
int
main(
int argc,
const char* /* argv */[])
{
#if !defined(XALAN_NO_NAMESPACES)
using std::cerr;
using std::endl;
using std::ifstream;
using std::ios_base;
using std::ostrstream;
using std::string;
#endif
if (argc != 1)
{
cerr << "Usage: CompileStylesheet"
<< endl
<< endl;
}
else
{
try
{
// Call the static initializers...
XMLPlatformUtils::Initialize();
XSLTEngineImpl::Initialize();
// Create the support objects that are necessary for running the processor...
DOMSupportDefault theDOMSupport;
XercesParserLiaison theParserLiaison(theDOMSupport);
XPathSupportDefault theXPathSupport(theDOMSupport);
XSLTProcessorEnvSupportDefault theXSLTProcessorEnvSupport;
XObjectFactoryDefault theXObjectFactory(
theXSLTProcessorEnvSupport,
theXPathSupport);
XPathFactoryDefault theXPathFactory;
// Create a processor...
XSLTEngineImpl theProcessor(
theParserLiaison,
theXPathSupport,
theXSLTProcessorEnvSupport,
theXObjectFactory,
theXPathFactory);
// Connect the processor to the support object...
theXSLTProcessorEnvSupport.setProcessor(&theProcessor);
// Create separate factory support objects so the stylesheet's
// factory-created XObject and XPath instances are independent
// from processor's.
XObjectFactoryDefault theStylesheetXObjectFactory(
theXSLTProcessorEnvSupport,
theXPathSupport);
XPathFactoryDefault theStylesheetXPathFactory;
// Create a stylesheet construction context, using the
// stylesheet's factory support objects.
StylesheetConstructionContextDefault theConstructionContext(
theProcessor,
theXSLTProcessorEnvSupport,
theStylesheetXObjectFactory,
theStylesheetXPathFactory);
// The execution context uses the same factory support objects as
// the processor, since those objects have the same lifetime as
// other objects created as a result of the execution.
StylesheetExecutionContextDefault theExecutionContext(
theProcessor,
theXSLTProcessorEnvSupport,
theXPathSupport,
theXObjectFactory);
// Our input files. The assumption is that the executable will be run
// from same directory as the input files.
const XalanDOMString theXMLFileName("foo.xml");
const XalanDOMString theXSLFileName("foo.xsl");
// Our stylesheet input source...
XSLTInputSource theStylesheetSource(c_wstr(theXSLFileName));
// Ask the processor to create a StylesheetRoot for the specified
// input XSL. This is the compiled stylesheet. We don't have to
// delete it, since it is owned by the StylesheetConstructionContext
// instance.
StylesheetRoot* const theStylesheetRoot =
theProcessor.processStylesheet(
theStylesheetSource,
theConstructionContext);
assert(theStylesheetRoot != 0);
for (unsigned int i = 0; i < 10; i++)
{
theExecutionContext.setStylesheetRoot(theStylesheetRoot);
// Generate the input and output file names.
ostrstream theFormatterIn, theFormatterOut;
theFormatterIn << "foo" << i + 1 << ".xml" << '\0';
theFormatterOut << "foo" << i + 1 << ".out" << '\0';
//Generate the XML input and output objects.
XSLTInputSource theInputSource(theFormatterIn.str());
XSLTResultTarget theResultTarget(theFormatterOut.str());
// Unfreeze the ostrstreams, so the memory is returned...
theFormatterIn.freeze(false);
theFormatterOut.freeze(false);
// Do the tranformation...
theProcessor.process(
theInputSource,
theResultTarget,
theExecutionContext);
// Reset the processor and the execution context
// so we can perform the next transformation.
// Reset the parser liaison to clear out the
// source document we just transformed.
theProcessor.reset();
theExecutionContext.reset();
theParserLiaison.reset();
}
// Call the static terminators...
XMLPlatformUtils::Terminate();
XSLTEngineImpl::Terminate();
}
catch(...)
{
cerr << "Exception caught!!!"
<< endl
<< endl;
}
}
return 0;
}
<|endoftext|> |
<commit_before>#include <iostream>
#include <fstream>
#include <functional>
#include <typeinfo>
#include <time.h>
#include <cstdio>
#include <vector>
#include <time.h>
#define SEQAN_DEBUG
#define SEQAN_TEST
#include <seqan/file.h>
#include <seqan/modifier.h>
using namespace std;
using namespace seqan;
//////////////////////////////////////////////////////////////////////////////
// custom functor (Caesar chiffre)
template <typename InType, typename Result = InType>
struct CaesarChiffre : public unary_function<InType,Result>
{
InType delta;
CaesarChiffre():delta(1) {}
CaesarChiffre(InType _delta) {
if (_delta < 0)
delta = ('z' - 'a' + 1) - (-_delta) % ('z' - 'a' + 1);
else
delta = _delta;
}
inline Result operator()(InType x) const {
if (('a' <= x) && (x <= 'z')) return (x - 'a' + delta) % ('z' - 'a' + 1) + 'a';
if (('A' <= x) && (x <= 'Z')) return (x - 'A' + delta) % ('Z' - 'A' + 1) + 'A';
return x;
}
};
SEQAN_DEFINE_TEST(test_modifier_view_iterator) {
String<char> origin = "Vjku ku qwt qtkikpcn uvtkpi";
//____________________________________________________________________________
// Test1 - no modification (default)
{
typedef ModifiedIterator< Iterator<String<char>, Rooted>::Type > TModIterDefault;
TModIterDefault it, itEnd(end(origin));
setContainer(it, container(itEnd)); // test setContainer
cout << "*** Iterator Test: Caesar chiffre ***" << endl;
cout << "chiffre: ";
it = begin(origin);
while (it != itEnd) {
cout << *it;
++it;
}
cout << endl;
}
//____________________________________________________________________________
// Test2 - Caesar chiffre
{
typedef CaesarChiffre<char> TEncode;
typedef ModifiedIterator< Iterator<String<char>, Rooted>::Type, ModView<TEncode> > TModIterCaesar;
TEncode encode(-2);
TModIterCaesar it(encode), itEnd(end(origin));
setContainer(it, container(itEnd)); // test setContainer
cout << "original: ";
it = begin(origin);
while (it != itEnd) {
cout << *it;
it = it + 1;
}
cout << endl << endl;
}
}
SEQAN_DEFINE_TEST(test_modifier_view_string) {
String<char> origin = "This is our original string";
//____________________________________________________________________________
// Test1 - no modification (default)
typedef ModifiedString< String<char> > TModStringDefault;
TModStringDefault nomod(origin);
cout << "*** Test1/2: Caesar chiffre ***" << endl;
cout << "origin: " << nomod << endl;
//____________________________________________________________________________
// Test2 - Caesar chiffre
typedef CaesarChiffre<char> TEncode;
typedef ModifiedString< String<char>, ModView<TEncode> > TModStringCaesar;
TEncode encode(2);
TModStringCaesar chiffre(origin);
assignModViewFunctor(chiffre, encode);
cout << "chiffre: " << chiffre << endl << endl;
//____________________________________________________________________________
// Test3 - upcase/lowcase
typedef ModifiedString< String<char>, ModView< FunctorUpcase<char> > > TModStringUp;
typedef ModifiedString< String<char>, ModView< FunctorLowcase<char> > > TModStringLow;
TModStringUp up(origin);
TModStringLow low(origin);
cout << "*** Test3: upcase/lowcase ***" << endl;
cout << "upcase: " << up << endl;
cout << "lowcase: " << low << endl << endl;
//____________________________________________________________________________
// Test4 - alphabet conversion
String<char> originDNA = "acgtnACGTN";
typedef ModifiedString< String<char>, ModView< FunctorConvert<char, Dna5> > > TModStringDNA;
TModStringDNA dna(originDNA);
cout << "*** Test4: alphabet conversion ***" << endl;
cout << "origin: " << originDNA << endl;
cout << "Dna5: " << dna << endl << endl;
//____________________________________________________________________________
// Test5 - nested modifiers
typedef CaesarChiffre<char> TEncode;
typedef ModifiedString<
// ModifiedString<
ModifiedString<
String<char>,
ModView<TEncode>
>,
ModView<TEncode>
// >,
// ModView<TEncode>
> TModStringNested;
TModStringNested nested(origin);
TEncode enc2(2), enc3(-2), enc_5(-5);
assignModViewFunctor(nested, enc2);
assignModViewFunctor(host(nested), enc3);
// assignModViewFunctor(host(host(nested)), enc_5);
cout << (int) (begin(nested)).data_cargo.func.delta << " ";
cout << (int) host((begin(nested))).data_cargo.func.delta << " ";
// cout << (int) host(host(nested)).data_cargo.func.delta << " ";
cout << "*** Test5: nested modifiers ***" << endl;
cout << "nested: " << nested << endl << endl;
}
SEQAN_DEFINE_TEST(test_modifier_reverse_string) {
String<char> origin = "A man, a plan, a canal-Panama";
//____________________________________________________________________________
// Test1 - reverse string
typedef ModifiedString< String<char>, ModReverse> TModString;
TModString reverse(origin);
cout << "*** Test1: Reverse String ***" << endl;
cout << "origin: " << origin << endl;
cout << "reverse: " << reverse << endl << endl;
//____________________________________________________________________________
// Test2 - complement string
DnaString dna = "attacgg";
cout << "*** Test2: DNA symmetry ***" << endl;
cout << "origin: " << dna << endl;
cout << "reverse: " << DnaStringReverse(dna) << endl;
cout << "complement: " << DnaStringComplement(dna) << endl;
cout << "reverse complement: " << DnaStringReverseComplement(dna) << endl << endl;
//____________________________________________________________________________
// Test3 - in-place conversions
DnaString dna2 = dna;
cout << "*** Test3: in-place conversions ***" << endl;
cout << "origin: " << dna2 << endl;
reverseInPlace(dna2);
cout << "reverse: " << dna2 << endl;
dna2 = dna;
complementInPlace(dna2);
cout << "complement: " << dna2 << endl;
dna2 = dna;
reverseComplementInPlace(dna2);
cout << "reverse complement: " << dna2 << endl << endl;
}
//____________________________________________________________________________
//////////////////////////////////////////////////////////////////////////////
SEQAN_DEFINE_TEST(test_modifier_alphabet_modifier) {
typedef ModifiedAlphabet<Dna, ModExpand<'-'> > TDnaGap;
typedef String<TDnaGap> TString;
TString str = "aCgT-AcGt";
cout << str << endl;
SEQAN_TASSERT(str == "aCgT-AcGt");
SEQAN_TASSERT(str == "AcGt-aCgT");
}
//////////////////////////////////////////////////////////////////////////////
SEQAN_BEGIN_TESTSUITE(test_modifier) {
SEQAN_CALL_TEST(test_modifier_view_string);
SEQAN_CALL_TEST(test_modifier_view_iterator);
SEQAN_CALL_TEST(test_modifier_reverse_string);
SEQAN_CALL_TEST(test_modifier_alphabet_modifier);
SEQAN_VERIFY_CHECKPOINTS("projects/library/seqan/modifier/modifier_alphabet.h");
SEQAN_VERIFY_CHECKPOINTS("projects/library/seqan/modifier/modifier_alphabet_expansion.h");
SEQAN_VERIFY_CHECKPOINTS("projects/library/seqan/modifier/modifier_functors.h");
SEQAN_VERIFY_CHECKPOINTS("projects/library/seqan/modifier/modifier_generated_forwards.h");
SEQAN_VERIFY_CHECKPOINTS("projects/library/seqan/modifier/modifier_iterator.h");
SEQAN_VERIFY_CHECKPOINTS("projects/library/seqan/modifier/modifier_reverse.h");
SEQAN_VERIFY_CHECKPOINTS("projects/library/seqan/modifier/modifier_shortcuts.h");
SEQAN_VERIFY_CHECKPOINTS("projects/library/seqan/modifier/modifier_string.h");
SEQAN_VERIFY_CHECKPOINTS("projects/library/seqan/modifier/modifier_view.h");
}
SEQAN_END_TESTSUITE
<commit_msg>Tests for modifier_alphabet.h -- commenting out other tests for now.<commit_after>#include <iostream>
#include <fstream>
#include <functional>
#include <typeinfo>
#include <time.h>
#include <cstdio>
#include <vector>
#include <time.h>
#define SEQAN_DEBUG
#define SEQAN_TEST
#include <seqan/file.h>
#include <seqan/modifier.h>
#include "test_modifier_alphabet.h"
using namespace std;
using namespace seqan;
//////////////////////////////////////////////////////////////////////////////
// custom functor (Caesar chiffre)
template <typename InType, typename Result = InType>
struct CaesarChiffre : public unary_function<InType,Result>
{
InType delta;
CaesarChiffre():delta(1) {}
CaesarChiffre(InType _delta) {
if (_delta < 0)
delta = ('z' - 'a' + 1) - (-_delta) % ('z' - 'a' + 1);
else
delta = _delta;
}
inline Result operator()(InType x) const {
if (('a' <= x) && (x <= 'z')) return (x - 'a' + delta) % ('z' - 'a' + 1) + 'a';
if (('A' <= x) && (x <= 'Z')) return (x - 'A' + delta) % ('Z' - 'A' + 1) + 'A';
return x;
}
};
SEQAN_DEFINE_TEST(test_modifier_view_iterator) {
String<char> origin = "Vjku ku qwt qtkikpcn uvtkpi";
//____________________________________________________________________________
// Test1 - no modification (default)
{
typedef ModifiedIterator< Iterator<String<char>, Rooted>::Type > TModIterDefault;
TModIterDefault it, itEnd(end(origin));
setContainer(it, container(itEnd)); // test setContainer
cout << "*** Iterator Test: Caesar chiffre ***" << endl;
cout << "chiffre: ";
it = begin(origin);
while (it != itEnd) {
cout << *it;
++it;
}
cout << endl;
}
//____________________________________________________________________________
// Test2 - Caesar chiffre
{
typedef CaesarChiffre<char> TEncode;
typedef ModifiedIterator< Iterator<String<char>, Rooted>::Type, ModView<TEncode> > TModIterCaesar;
TEncode encode(-2);
TModIterCaesar it(encode), itEnd(end(origin));
setContainer(it, container(itEnd)); // test setContainer
cout << "original: ";
it = begin(origin);
while (it != itEnd) {
cout << *it;
it = it + 1;
}
cout << endl << endl;
}
}
SEQAN_DEFINE_TEST(test_modifier_view_string) {
String<char> origin = "This is our original string";
//____________________________________________________________________________
// Test1 - no modification (default)
typedef ModifiedString< String<char> > TModStringDefault;
TModStringDefault nomod(origin);
cout << "*** Test1/2: Caesar chiffre ***" << endl;
cout << "origin: " << nomod << endl;
//____________________________________________________________________________
// Test2 - Caesar chiffre
typedef CaesarChiffre<char> TEncode;
typedef ModifiedString< String<char>, ModView<TEncode> > TModStringCaesar;
TEncode encode(2);
TModStringCaesar chiffre(origin);
assignModViewFunctor(chiffre, encode);
cout << "chiffre: " << chiffre << endl << endl;
//____________________________________________________________________________
// Test3 - upcase/lowcase
typedef ModifiedString< String<char>, ModView< FunctorUpcase<char> > > TModStringUp;
typedef ModifiedString< String<char>, ModView< FunctorLowcase<char> > > TModStringLow;
TModStringUp up(origin);
TModStringLow low(origin);
cout << "*** Test3: upcase/lowcase ***" << endl;
cout << "upcase: " << up << endl;
cout << "lowcase: " << low << endl << endl;
//____________________________________________________________________________
// Test4 - alphabet conversion
String<char> originDNA = "acgtnACGTN";
typedef ModifiedString< String<char>, ModView< FunctorConvert<char, Dna5> > > TModStringDNA;
TModStringDNA dna(originDNA);
cout << "*** Test4: alphabet conversion ***" << endl;
cout << "origin: " << originDNA << endl;
cout << "Dna5: " << dna << endl << endl;
//____________________________________________________________________________
// Test5 - nested modifiers
typedef CaesarChiffre<char> TEncode;
typedef ModifiedString<
// ModifiedString<
ModifiedString<
String<char>,
ModView<TEncode>
>,
ModView<TEncode>
// >,
// ModView<TEncode>
> TModStringNested;
TModStringNested nested(origin);
TEncode enc2(2), enc3(-2), enc_5(-5);
assignModViewFunctor(nested, enc2);
assignModViewFunctor(host(nested), enc3);
// assignModViewFunctor(host(host(nested)), enc_5);
cout << (int) (begin(nested)).data_cargo.func.delta << " ";
cout << (int) host((begin(nested))).data_cargo.func.delta << " ";
// cout << (int) host(host(nested)).data_cargo.func.delta << " ";
cout << "*** Test5: nested modifiers ***" << endl;
cout << "nested: " << nested << endl << endl;
}
SEQAN_DEFINE_TEST(test_modifier_reverse_string) {
String<char> origin = "A man, a plan, a canal-Panama";
//____________________________________________________________________________
// Test1 - reverse string
typedef ModifiedString< String<char>, ModReverse> TModString;
TModString reverse(origin);
cout << "*** Test1: Reverse String ***" << endl;
cout << "origin: " << origin << endl;
cout << "reverse: " << reverse << endl << endl;
//____________________________________________________________________________
// Test2 - complement string
DnaString dna = "attacgg";
cout << "*** Test2: DNA symmetry ***" << endl;
cout << "origin: " << dna << endl;
cout << "reverse: " << DnaStringReverse(dna) << endl;
cout << "complement: " << DnaStringComplement(dna) << endl;
cout << "reverse complement: " << DnaStringReverseComplement(dna) << endl << endl;
//____________________________________________________________________________
// Test3 - in-place conversions
DnaString dna2 = dna;
cout << "*** Test3: in-place conversions ***" << endl;
cout << "origin: " << dna2 << endl;
reverseInPlace(dna2);
cout << "reverse: " << dna2 << endl;
dna2 = dna;
complementInPlace(dna2);
cout << "complement: " << dna2 << endl;
dna2 = dna;
reverseComplementInPlace(dna2);
cout << "reverse complement: " << dna2 << endl << endl;
}
//____________________________________________________________________________
SEQAN_DEFINE_TEST(test_modifier_alphabet_modifier) {
typedef ModifiedAlphabet<Dna, ModExpand<'-'> > TDnaGap;
typedef String<TDnaGap> TString;
TString str = "aCgT-AcGt";
cout << str << endl;
SEQAN_TASSERT(str == "aCgT-AcGt");
SEQAN_TASSERT(str == "AcGt-aCgT");
}
SEQAN_BEGIN_TESTSUITE(test_modifier) {
// Tests for modifier_alphabet.h.
SEQAN_CALL_TEST(test_modifier_alphabet_size_metafunctions);
SEQAN_CALL_TEST(test_modifier_alphabet_convert);
SEQAN_CALL_TEST(test_modifier_alphabet_ord_value);
SEQAN_CALL_TEST(test_modifier_alphabet_operator_eq);
SEQAN_CALL_TEST(test_modifier_alphabet_operator_neq);
SEQAN_CALL_TEST(test_modifier_alphabet_operator_lt);
SEQAN_CALL_TEST(test_modifier_alphabet_operator_gt);
SEQAN_CALL_TEST(test_modifier_alphabet_operator_leq);
SEQAN_CALL_TEST(test_modifier_alphabet_operator_geq);
/*
SEQAN_CALL_TEST(test_modifier_view_string);
SEQAN_CALL_TEST(test_modifier_view_iterator);
SEQAN_CALL_TEST(test_modifier_reverse_string);
SEQAN_CALL_TEST(test_modifier_alphabet_modifier);
*/
SEQAN_VERIFY_CHECKPOINTS("projects/library/seqan/modifier/modifier_alphabet.h");
/*
SEQAN_VERIFY_CHECKPOINTS("projects/library/seqan/modifier/modifier_alphabet_expansion.h");
SEQAN_VERIFY_CHECKPOINTS("projects/library/seqan/modifier/modifier_functors.h");
SEQAN_VERIFY_CHECKPOINTS("projects/library/seqan/modifier/modifier_generated_forwards.h");
SEQAN_VERIFY_CHECKPOINTS("projects/library/seqan/modifier/modifier_iterator.h");
SEQAN_VERIFY_CHECKPOINTS("projects/library/seqan/modifier/modifier_reverse.h");
SEQAN_VERIFY_CHECKPOINTS("projects/library/seqan/modifier/modifier_shortcuts.h");
SEQAN_VERIFY_CHECKPOINTS("projects/library/seqan/modifier/modifier_string.h");
SEQAN_VERIFY_CHECKPOINTS("projects/library/seqan/modifier/modifier_view.h");
*/
}
SEQAN_END_TESTSUITE
<|endoftext|> |
<commit_before>/*
* Copyright (C) 2017-2018 Nagisa Sekiguchi
*
* 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 <sys/wait.h>
#include <algorithm>
#include <cerrno>
#include <csignal>
#include "vm.h"
#include "logger.h"
namespace ydsh {
Proc Proc::fork(DSState &st, pid_t pgid, bool foreground) {
SignalGuard guard;
pid_t pid = ::fork();
if(pid == 0) { // child process
if(st.isJobControl()) {
setpgid(0, pgid);
if(foreground) {
tcsetpgrp(STDIN_FILENO, getpgid(0));
}
setJobControlSignalSetting(st, false);
}
// clear queued signal
DSState::pendingSigIndex = 1;
DSState::pendingSigSet.clear();
unsetFlag(DSState::eventDesc, DSState::VM_EVENT_SIGNAL | DSState::VM_EVENT_MASK);
// clear JobTable entries
st.jobTable.detachAll();
// clear termination hook
st.setGlobal(getTermHookIndex(st), DSValue::createInvalid());
// update PID, PPID
st.setGlobal(toIndex(BuiltinVarOffset::PID), DSValue::create<Int_Object>(st.symbolTable.get(TYPE::Int32), getpid()));
st.setGlobal(toIndex(BuiltinVarOffset::PPID), DSValue::create<Int_Object>(st.symbolTable.get(TYPE::Int32), getppid()));
} else if(pid > 0) {
if(st.isJobControl()) {
setpgid(pid, pgid);
if(foreground) {
tcsetpgrp(STDIN_FILENO, getpgid(pid));
}
}
}
return Proc(pid);
}
void tryToForeground(const DSState &st) {
if(st.isForeground()) {
tcsetpgrp(STDIN_FILENO, getpgid(0));
}
}
// ##################
// ## Proc ##
// ##################
static int toOption(Proc::WaitOp op) {
int option = 0;
switch(op) {
case Proc::BLOCKING:
break;
case Proc::BLOCK_UNTRACED:
option = WUNTRACED;
break;
case Proc::NONBLOCKING:
option = WUNTRACED | WCONTINUED | WNOHANG;
break;
}
return option;
}
#ifdef USE_LOGGING
static const char *toString(Proc::WaitOp op) {
const char *str = nullptr;
switch(op) {
#define GEN_STR(OP) case Proc::OP: str = #OP; break;
EACH_WAIT_OP(GEN_STR)
#undef GEN_STR
}
return str;
}
#endif
int Proc::wait(WaitOp op) {
if(this->state() != TERMINATED) {
int status = 0;
int ret = waitpid(this->pid_, &status, toOption(op));
if(ret == -1) {
fatal_perror("");
}
// dump waitpid result
LOG_L(DUMP_WAIT, [&](std::ostream &stream) {
stream << "opt: " << toString(op) << std::endl;
stream << "pid: " << this->pid() << ", before state: "
<< (this->state() == Proc::RUNNING ? "RUNNING" : "STOPPED") << std::endl;
stream << "ret: " << ret << std::endl;
if(ret > 0) {
stream << "after state: ";
if(WIFEXITED(status)) {
stream << "TERMINATED" << std::endl
<< "kind: EXITED, status: " << WEXITSTATUS(status);
} else if(WIFSIGNALED(status)) {
int sigNum = WTERMSIG(status);
stream << "TERMINATED" << std::endl
<< "kind: SIGNALED, status: " << getSignalName(sigNum) << "(" << sigNum << ")";
} else if(WIFSTOPPED(status)) {
int sigNum = WSTOPSIG(status);
stream << "STOPPED" << std::endl
<< "kind: STOPPED, status: " << getSignalName(sigNum) << "(" << sigNum << ")";
} else if(WIFCONTINUED(status)) {
stream << "RUNNING" << std::endl << "kind: CONTINUED";
}
stream << std::endl;
}
});
if(ret > 0) {
// update status
if(WIFEXITED(status)) {
this->state_ = TERMINATED;
this->exitStatus_ = WEXITSTATUS(status);
} else if(WIFSIGNALED(status)) {
int sigNum = WTERMSIG(status);
bool hasCoreDump = false;
this->state_ = TERMINATED;
this->exitStatus_ = sigNum + 128;
#ifdef WCOREDUMP
if(WCOREDUMP(status)) {
hasCoreDump = true;
}
#endif
fprintf(stderr, "%s%s\n", strsignal(sigNum), hasCoreDump ? " (core dump)" : "");
fflush(stderr);
} else if(WIFSTOPPED(status)) {
this->state_ = STOPPED;
this->exitStatus_ = WSTOPSIG(status) + 128;
} else if(WIFCONTINUED(status)) {
this->state_ = RUNNING;
}
if(this->state_ == TERMINATED) {
this->pid_ = -1;
}
}
}
return this->exitStatus_;
}
// #####################
// ## JobImpl ##
// #####################
bool JobImpl::restoreStdin() {
if(this->oldStdin > -1 && this->hasOwnership()) {
dup2(this->oldStdin, STDIN_FILENO);
close(this->oldStdin);
return true;
}
return false;
}
void JobImpl::send(int sigNum) const {
if(!this->available()) {
return;
}
pid_t pid = this->getPid(0);
if(pid == getpgid(pid)) {
kill(-pid, sigNum);
return;
}
for(unsigned int i = 0; i < this->procSize; i++) {
pid = this->getPid(i);
if(pid > 0) {
kill(pid, sigNum);
}
}
}
int JobImpl::wait(Proc::WaitOp op) {
if(!hasOwnership()) {
return -1;
}
if(!this->available()) {
return this->procs[this->procSize - 1].exitStatus();
}
unsigned int terminateCount = 0;
unsigned int lastStatus = 0;
for(unsigned int i = 0; i < this->procSize; i++) {
auto &proc = this->procs[i];
lastStatus = proc.wait(op);
if(proc.state() == Proc::TERMINATED) {
terminateCount++;
}
}
if(terminateCount == this->procSize) {
this->running = false;
}
return lastStatus;
}
// ######################
// ## JobTable ##
// ######################
void JobTable::attach(Job job, bool disowned) {
if(job->jobID() != 0) {
return;
}
if(disowned) {
this->entries.push_back(std::move(job));
return;
}
auto ret = this->findEmptyEntry();
this->entries.insert(this->beginJob() + ret, job);
job->jobID_ = ret + 1;
this->latestEntry = std::move(job);
this->jobSize++;
}
Job JobTable::detach(unsigned int jobId, bool remove) {
auto iter = this->findEntryIter(jobId);
if(iter == this->endJob()) {
return nullptr;
}
auto job = *iter;
this->detachByIter(iter);
if(!remove) {
this->entries.push_back(job);
}
return job;
}
JobTable::EntryIter JobTable::detachByIter(ConstEntryIter iter) {
if(iter != this->entries.end()) {
/**
* convert const_iterator -> iterator
*/
auto actual = this->entries.begin() + (iter - this->entries.cbegin());
Job job = *actual;
if(job->jobID() > 0) {
this->jobSize--;
}
job->jobID_ = 0;
/**
* in C++11, vector::erase accepts const_iterator.
* but in libstdc++ 4.8, vector::erase(const_iterator) is not implemented.
*/
auto next = this->entries.erase(actual);
// change latest entry
if(this->latestEntry == job) {
this->latestEntry = nullptr;
if(!this->entries.empty()) {
this->latestEntry = this->entries[this->jobSize - 1];
}
}
return next;
}
return this->entries.end();
}
void JobTable::updateStatus() {
for(auto begin = this->entries.begin(); begin != this->entries.end();) {
(*begin)->wait(Proc::NONBLOCKING);
if((*begin)->available()) {
++begin;
} else {
begin = this->detachByIter(begin);
}
}
}
unsigned int JobTable::findEmptyEntry() const {
unsigned int firstIndex = 0;
unsigned int dist = this->jobSize;
while(dist > 0) {
unsigned int hafDist = dist / 2;
unsigned int midIndex = hafDist + firstIndex;
if(entries[midIndex]->jobID() == midIndex + 1) {
firstIndex = midIndex + 1;
dist = dist - hafDist - 1;
} else {
dist = hafDist;
}
}
return firstIndex;
}
struct Comparator {
bool operator()(const Job &x, unsigned int y) const {
return x->jobID() < y;
}
bool operator()(unsigned int x, const Job &y) const {
return x < y->jobID();
}
};
JobTable::ConstEntryIter JobTable::findEntryIter(unsigned int jobId) const {
if(jobId > 0) {
auto iter = std::lower_bound(this->beginJob(), this->endJob(), jobId, Comparator());
if(iter != this->endJob() && (*iter)->jobID_ == jobId) {
return iter;
}
}
return this->endJob();
}
} // namespace ydsh<commit_msg>fix coredump message<commit_after>/*
* Copyright (C) 2017-2018 Nagisa Sekiguchi
*
* 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 <sys/wait.h>
#include <algorithm>
#include <cerrno>
#include <csignal>
#include "vm.h"
#include "logger.h"
namespace ydsh {
Proc Proc::fork(DSState &st, pid_t pgid, bool foreground) {
SignalGuard guard;
pid_t pid = ::fork();
if(pid == 0) { // child process
if(st.isJobControl()) {
setpgid(0, pgid);
if(foreground) {
tcsetpgrp(STDIN_FILENO, getpgid(0));
}
setJobControlSignalSetting(st, false);
}
// clear queued signal
DSState::pendingSigIndex = 1;
DSState::pendingSigSet.clear();
unsetFlag(DSState::eventDesc, DSState::VM_EVENT_SIGNAL | DSState::VM_EVENT_MASK);
// clear JobTable entries
st.jobTable.detachAll();
// clear termination hook
st.setGlobal(getTermHookIndex(st), DSValue::createInvalid());
// update PID, PPID
st.setGlobal(toIndex(BuiltinVarOffset::PID), DSValue::create<Int_Object>(st.symbolTable.get(TYPE::Int32), getpid()));
st.setGlobal(toIndex(BuiltinVarOffset::PPID), DSValue::create<Int_Object>(st.symbolTable.get(TYPE::Int32), getppid()));
} else if(pid > 0) {
if(st.isJobControl()) {
setpgid(pid, pgid);
if(foreground) {
tcsetpgrp(STDIN_FILENO, getpgid(pid));
}
}
}
return Proc(pid);
}
void tryToForeground(const DSState &st) {
if(st.isForeground()) {
tcsetpgrp(STDIN_FILENO, getpgid(0));
}
}
// ##################
// ## Proc ##
// ##################
static int toOption(Proc::WaitOp op) {
int option = 0;
switch(op) {
case Proc::BLOCKING:
break;
case Proc::BLOCK_UNTRACED:
option = WUNTRACED;
break;
case Proc::NONBLOCKING:
option = WUNTRACED | WCONTINUED | WNOHANG;
break;
}
return option;
}
#ifdef USE_LOGGING
static const char *toString(Proc::WaitOp op) {
const char *str = nullptr;
switch(op) {
#define GEN_STR(OP) case Proc::OP: str = #OP; break;
EACH_WAIT_OP(GEN_STR)
#undef GEN_STR
}
return str;
}
#endif
int Proc::wait(WaitOp op) {
if(this->state() != TERMINATED) {
int status = 0;
int ret = waitpid(this->pid_, &status, toOption(op));
if(ret == -1) {
fatal_perror("");
}
// dump waitpid result
LOG_L(DUMP_WAIT, [&](std::ostream &stream) {
stream << "opt: " << toString(op) << std::endl;
stream << "pid: " << this->pid() << ", before state: "
<< (this->state() == Proc::RUNNING ? "RUNNING" : "STOPPED") << std::endl;
stream << "ret: " << ret << std::endl;
if(ret > 0) {
stream << "after state: ";
if(WIFEXITED(status)) {
stream << "TERMINATED" << std::endl
<< "kind: EXITED, status: " << WEXITSTATUS(status);
} else if(WIFSIGNALED(status)) {
int sigNum = WTERMSIG(status);
stream << "TERMINATED" << std::endl
<< "kind: SIGNALED, status: " << getSignalName(sigNum) << "(" << sigNum << ")";
} else if(WIFSTOPPED(status)) {
int sigNum = WSTOPSIG(status);
stream << "STOPPED" << std::endl
<< "kind: STOPPED, status: " << getSignalName(sigNum) << "(" << sigNum << ")";
} else if(WIFCONTINUED(status)) {
stream << "RUNNING" << std::endl << "kind: CONTINUED";
}
stream << std::endl;
}
});
if(ret > 0) {
// update status
if(WIFEXITED(status)) {
this->state_ = TERMINATED;
this->exitStatus_ = WEXITSTATUS(status);
} else if(WIFSIGNALED(status)) {
int sigNum = WTERMSIG(status);
bool hasCoreDump = false;
this->state_ = TERMINATED;
this->exitStatus_ = sigNum + 128;
#ifdef WCOREDUMP
if(WCOREDUMP(status)) {
hasCoreDump = true;
}
#endif
fprintf(stderr, "%s%s\n", strsignal(sigNum), hasCoreDump ? " (core dumped)" : "");
fflush(stderr);
} else if(WIFSTOPPED(status)) {
this->state_ = STOPPED;
this->exitStatus_ = WSTOPSIG(status) + 128;
} else if(WIFCONTINUED(status)) {
this->state_ = RUNNING;
}
if(this->state_ == TERMINATED) {
this->pid_ = -1;
}
}
}
return this->exitStatus_;
}
// #####################
// ## JobImpl ##
// #####################
bool JobImpl::restoreStdin() {
if(this->oldStdin > -1 && this->hasOwnership()) {
dup2(this->oldStdin, STDIN_FILENO);
close(this->oldStdin);
return true;
}
return false;
}
void JobImpl::send(int sigNum) const {
if(!this->available()) {
return;
}
pid_t pid = this->getPid(0);
if(pid == getpgid(pid)) {
kill(-pid, sigNum);
return;
}
for(unsigned int i = 0; i < this->procSize; i++) {
pid = this->getPid(i);
if(pid > 0) {
kill(pid, sigNum);
}
}
}
int JobImpl::wait(Proc::WaitOp op) {
if(!hasOwnership()) {
return -1;
}
if(!this->available()) {
return this->procs[this->procSize - 1].exitStatus();
}
unsigned int terminateCount = 0;
unsigned int lastStatus = 0;
for(unsigned int i = 0; i < this->procSize; i++) {
auto &proc = this->procs[i];
lastStatus = proc.wait(op);
if(proc.state() == Proc::TERMINATED) {
terminateCount++;
}
}
if(terminateCount == this->procSize) {
this->running = false;
}
return lastStatus;
}
// ######################
// ## JobTable ##
// ######################
void JobTable::attach(Job job, bool disowned) {
if(job->jobID() != 0) {
return;
}
if(disowned) {
this->entries.push_back(std::move(job));
return;
}
auto ret = this->findEmptyEntry();
this->entries.insert(this->beginJob() + ret, job);
job->jobID_ = ret + 1;
this->latestEntry = std::move(job);
this->jobSize++;
}
Job JobTable::detach(unsigned int jobId, bool remove) {
auto iter = this->findEntryIter(jobId);
if(iter == this->endJob()) {
return nullptr;
}
auto job = *iter;
this->detachByIter(iter);
if(!remove) {
this->entries.push_back(job);
}
return job;
}
JobTable::EntryIter JobTable::detachByIter(ConstEntryIter iter) {
if(iter != this->entries.end()) {
/**
* convert const_iterator -> iterator
*/
auto actual = this->entries.begin() + (iter - this->entries.cbegin());
Job job = *actual;
if(job->jobID() > 0) {
this->jobSize--;
}
job->jobID_ = 0;
/**
* in C++11, vector::erase accepts const_iterator.
* but in libstdc++ 4.8, vector::erase(const_iterator) is not implemented.
*/
auto next = this->entries.erase(actual);
// change latest entry
if(this->latestEntry == job) {
this->latestEntry = nullptr;
if(!this->entries.empty()) {
this->latestEntry = this->entries[this->jobSize - 1];
}
}
return next;
}
return this->entries.end();
}
void JobTable::updateStatus() {
for(auto begin = this->entries.begin(); begin != this->entries.end();) {
(*begin)->wait(Proc::NONBLOCKING);
if((*begin)->available()) {
++begin;
} else {
begin = this->detachByIter(begin);
}
}
}
unsigned int JobTable::findEmptyEntry() const {
unsigned int firstIndex = 0;
unsigned int dist = this->jobSize;
while(dist > 0) {
unsigned int hafDist = dist / 2;
unsigned int midIndex = hafDist + firstIndex;
if(entries[midIndex]->jobID() == midIndex + 1) {
firstIndex = midIndex + 1;
dist = dist - hafDist - 1;
} else {
dist = hafDist;
}
}
return firstIndex;
}
struct Comparator {
bool operator()(const Job &x, unsigned int y) const {
return x->jobID() < y;
}
bool operator()(unsigned int x, const Job &y) const {
return x < y->jobID();
}
};
JobTable::ConstEntryIter JobTable::findEntryIter(unsigned int jobId) const {
if(jobId > 0) {
auto iter = std::lower_bound(this->beginJob(), this->endJob(), jobId, Comparator());
if(iter != this->endJob() && (*iter)->jobID_ == jobId) {
return iter;
}
}
return this->endJob();
}
} // namespace ydsh<|endoftext|> |
<commit_before>#ifndef GENERIC_REV_HPP
# define GENERIC_REV_HPP
# pragma once
#include <iterator>
#include <utility>
namespace gnr
{
namespace detail
{
template <typename T>
class rev_impl
{
T ref_;
public:
template <typename U>
explicit rev_impl(U&& r) noexcept(noexcept(T(std::forward<U>(r)))) :
ref_(std::forward<U>(r))
{
}
template <typename U, std::size_t N>
explicit rev_impl(U(&&a)[N]) noexcept(
noexcept(std::move(std::begin(a), std::end(a), std::begin(ref_))))
{
std::move(std::begin(a), std::end(a), std::begin(ref_));
}
auto begin() noexcept(noexcept(std::rbegin(ref_)))
{
return std::rbegin(ref_);
}
auto end() noexcept(noexcept(std::rend(ref_)))
{
return std::rend(ref_);
}
};
}
template <typename T>
auto rev(T&& r) noexcept(noexcept(detail::rev_impl<T>(std::forward<T>(r)))) ->
decltype(std::begin(r),std::end(r),detail::rev_impl<T>(std::forward<T>(r)))
{
return detail::rev_impl<T>(std::forward<T>(r));
}
template <typename T, std::size_t N>
auto rev(T(&&a)[N]) noexcept(
noexcept(detail::rev_impl<T[N]>(std::move(a)))) ->
decltype(detail::rev_impl<T[N]>(std::move(a)))
{
return detail::rev_impl<T[N]>(std::move(a));
}
}
#endif // GENERIC_REV_HPP
<commit_msg>some fixes<commit_after>#ifndef GENERIC_REV_HPP
# define GENERIC_REV_HPP
# pragma once
#include <iterator>
#include <utility>
namespace gnr
{
namespace detail
{
template <typename T>
class rev_impl
{
T ref_;
public:
template <typename U>
explicit rev_impl(U&& r) noexcept(noexcept(T(std::forward<U>(r)))) :
ref_(std::forward<U>(r))
{
}
template <typename U, std::size_t N>
explicit rev_impl(U(&&a)[N]) noexcept(
noexcept(std::move(std::begin(a), std::end(a), std::begin(ref_))))
{
std::move(std::begin(a), std::end(a), std::begin(ref_));
}
auto begin() noexcept(noexcept(std::rbegin(ref_)))
{
return std::rbegin(ref_);
}
auto end() noexcept(noexcept(std::rend(ref_)))
{
return std::rend(ref_);
}
};
}
template <typename T>
auto rev(T&& r) noexcept(noexcept(detail::rev_impl<T>(std::forward<T>(r)))) ->
decltype(std::begin(r),std::end(r),detail::rev_impl<T>(std::forward<T>(r)))
{
return detail::rev_impl<T>(std::forward<T>(r));
}
template <typename T, std::size_t N>
auto rev(T(&&a)[N]) noexcept(
noexcept(detail::rev_impl<T[N]>(std::move(a)))) -> detail::rev_impl<T[N]>
{
return detail::rev_impl<T[N]>(std::move(a));
}
}
#endif // GENERIC_REV_HPP
<|endoftext|> |
<commit_before>/*
* Copyright 2016 The Imaging Source Europe GmbH
*
* 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 "CameraListHolder.h"
#include "DaemonClass.h"
#include "gige-daemon.h"
#include <csignal>
#include <cstring>
#include <iostream>
#include <stdio.h>
#include <sys/ipc.h>
#include <sys/msg.h>
#include <sys/shm.h>
#include <unistd.h>
DaemonClass daemon_instance(LOCK_FILE);
std::vector<struct tcam_device_info> get_camera_list()
{
key_t shmkey = ftok(LOCK_FILE, 'G');
key_t sem_key = ftok(LOCK_FILE, 'S');
int sem_id = tcam::semaphore_create(sem_key);
int shmid;
if ((shmid = shmget(shmkey, sizeof(struct tcam_gige_device_list), 0644 | IPC_CREAT)) == -1)
{
perror("shmget");
exit(1);
}
tcam::semaphore_lock(sem_id);
struct tcam_gige_device_list* d = (struct tcam_gige_device_list*)shmat(shmid, NULL, 0);
if (d == nullptr)
{
shmdt(d);
return std::vector<struct tcam_device_info>();
}
std::vector<struct tcam_device_info> ret;
ret.reserve(d->device_count);
for (unsigned int i = 0; i < d->device_count; ++i) { ret.push_back(d->devices[i]); }
shmdt(d);
tcam::semaphore_unlock(sem_id);
return ret;
}
void print_camera_list()
{
auto cam_list = get_camera_list();
for (const auto& c : cam_list) { std::cout << c.identifier << std::endl; }
}
void print_camera_list_long()
{
auto cam_list = get_camera_list();
for (const auto& c : cam_list)
{
std::cout << c.name << " - " << c.serial_number << " - " << c.identifier << std::endl;
}
}
void print_help(const char* prog_name)
{
std::cout << prog_name << " - GigE Indexing daemon\n"
<< "\n"
<< "Usage:\n"
<< "\t" << prog_name << " list \t - list camera names\n"
<< "\t" << prog_name << " list-long \t - list camera names, ip, mac\n"
<< "\t" << prog_name << " start \t - start daemon and fork\n"
<< "\t\t --no-fork \t - run daemon without forking\n"
<< "\t" << prog_name << " stop \t - stop daemon\n"
<< std::endl;
}
void signal_handler(int sig)
{
switch (sig)
{
case SIGHUP:
/* rehash the server */
break;
case SIGTERM:
case SIGINT:
/* finalize the server */
CameraListHolder::get_instance().stop();
daemon_instance.stop_daemon();
break;
default:
std::cout << "Received unhandled signal " << sig << std::endl;
break;
}
}
int main(int argc, char* argv[])
{
for (int i = 1; i < argc; ++i)
{
if (strcmp("list", argv[i]) == 0)
{
print_camera_list();
return 0;
}
else if (strcmp("list-long", argv[i]) == 0)
{
print_camera_list_long();
return 0;
}
else if (strcmp("start", argv[i]) == 0)
{
bool daemonize = true;
for (int j = 1; j < argc; ++j)
{
if (strcmp("--no-fork", argv[j]) == 0)
{
daemonize = false;
break;
}
}
int ret = daemon_instance.daemonize(&signal_handler, daemonize);
if (ret < 0)
{
std::cerr << "Daemon is already running!" << std::endl;
return 1;
}
if (ret > 0)
{
std::cout << "Started daemon. PID: " << ret << std::endl;
return 0;
}
std::vector<std::string> interfaces;
for (int x = (i + 1); x < argc; ++x)
{
if (strcmp("--no-fork", argv[x]) == 0)
{
continue;
}
interfaces.push_back(argv[x]);
}
// block signals in this thread and subsequently
// spawned threads
sigset_t sigset;
sigemptyset(&sigset);
sigaddset(&sigset, SIGINT);
sigaddset(&sigset, SIGTERM);
pthread_sigmask(SIG_BLOCK, &sigset, nullptr);
try
{
CameraListHolder::get_instance().set_interface_list(interfaces);
}
catch (std::runtime_error& e)
{
std::cerr << "Unable to start indexing: " << e.what() << std::endl;
return 1;
}
int signum = 0;
// wait until a signal is delivered:
sigwait(&sigset, &signum);
signal_handler(signum);
return 0;
}
else if (strcmp("stop", argv[i]) == 0)
{
if (daemon_instance.undaemonize())
{
std::cout << "Successfully stopped daemon." << std::endl;
return 0;
}
else
{
std::cout << "Could not stop daemon. " << strerror(errno) << std::endl;
return 1;
}
}
}
print_help(argv[0]);
return 0;
}
<commit_msg>tcam-gige-daemon: Add semaphore security checks<commit_after>/*
* Copyright 2016 The Imaging Source Europe GmbH
*
* 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 "CameraListHolder.h"
#include "DaemonClass.h"
#include "gige-daemon.h"
#include <csignal>
#include <cstring>
#include <iostream>
#include <stdio.h>
#include <sys/ipc.h>
#include <sys/msg.h>
#include <sys/shm.h>
#include <unistd.h>
DaemonClass daemon_instance(LOCK_FILE);
std::vector<struct tcam_device_info> get_camera_list()
{
key_t shmkey = ftok(LOCK_FILE, 'G');
key_t sem_key = ftok(LOCK_FILE, 'S');
if (sem_key < 0)
{
perror("Unable to get semaphore key.");
return {};
}
int sem_id = tcam::semaphore_create(sem_key);
if (sem_id < 0)
{
perror("Cannot create semaphore");
return {};
}
int shmid;
if ((shmid = shmget(shmkey, sizeof(struct tcam_gige_device_list), 0644 | IPC_CREAT)) == -1)
{
perror("shmget");
exit(1);
}
tcam::semaphore_lock(sem_id);
struct tcam_gige_device_list* d = (struct tcam_gige_device_list*)shmat(shmid, NULL, 0);
if (d == nullptr)
{
shmdt(d);
return std::vector<struct tcam_device_info>();
}
std::vector<struct tcam_device_info> ret;
ret.reserve(d->device_count);
for (unsigned int i = 0; i < d->device_count; ++i) { ret.push_back(d->devices[i]); }
shmdt(d);
tcam::semaphore_unlock(sem_id);
return ret;
}
void print_camera_list()
{
auto cam_list = get_camera_list();
for (const auto& c : cam_list) { std::cout << c.identifier << std::endl; }
}
void print_camera_list_long()
{
auto cam_list = get_camera_list();
for (const auto& c : cam_list)
{
std::cout << c.name << " - " << c.serial_number << " - " << c.identifier << std::endl;
}
}
void print_help(const char* prog_name)
{
std::cout << prog_name << " - GigE Indexing daemon\n"
<< "\n"
<< "Usage:\n"
<< "\t" << prog_name << " list \t - list camera names\n"
<< "\t" << prog_name << " list-long \t - list camera names, ip, mac\n"
<< "\t" << prog_name << " start \t - start daemon and fork\n"
<< "\t\t --no-fork \t - run daemon without forking\n"
<< "\t" << prog_name << " stop \t - stop daemon\n"
<< std::endl;
}
void signal_handler(int sig)
{
switch (sig)
{
case SIGHUP:
/* rehash the server */
break;
case SIGTERM:
case SIGINT:
/* finalize the server */
CameraListHolder::get_instance().stop();
daemon_instance.stop_daemon();
break;
default:
std::cout << "Received unhandled signal " << sig << std::endl;
break;
}
}
int main(int argc, char* argv[])
{
for (int i = 1; i < argc; ++i)
{
if (strcmp("list", argv[i]) == 0)
{
print_camera_list();
return 0;
}
else if (strcmp("list-long", argv[i]) == 0)
{
print_camera_list_long();
return 0;
}
else if (strcmp("start", argv[i]) == 0)
{
bool daemonize = true;
for (int j = 1; j < argc; ++j)
{
if (strcmp("--no-fork", argv[j]) == 0)
{
daemonize = false;
break;
}
}
int ret = daemon_instance.daemonize(&signal_handler, daemonize);
if (ret < 0)
{
std::cerr << "Daemon is already running!" << std::endl;
return 1;
}
if (ret > 0)
{
std::cout << "Started daemon. PID: " << ret << std::endl;
return 0;
}
std::vector<std::string> interfaces;
for (int x = (i + 1); x < argc; ++x)
{
if (strcmp("--no-fork", argv[x]) == 0)
{
continue;
}
interfaces.push_back(argv[x]);
}
// block signals in this thread and subsequently
// spawned threads
sigset_t sigset;
sigemptyset(&sigset);
sigaddset(&sigset, SIGINT);
sigaddset(&sigset, SIGTERM);
pthread_sigmask(SIG_BLOCK, &sigset, nullptr);
try
{
CameraListHolder::get_instance().set_interface_list(interfaces);
}
catch (std::runtime_error& e)
{
std::cerr << "Unable to start indexing: " << e.what() << std::endl;
return 1;
}
int signum = 0;
// wait until a signal is delivered:
sigwait(&sigset, &signum);
signal_handler(signum);
return 0;
}
else if (strcmp("stop", argv[i]) == 0)
{
if (daemon_instance.undaemonize())
{
std::cout << "Successfully stopped daemon." << std::endl;
return 0;
}
else
{
std::cout << "Could not stop daemon. " << strerror(errno) << std::endl;
return 1;
}
}
}
print_help(argv[0]);
return 0;
}
<|endoftext|> |
<commit_before>/*
This file is part of the ORK library.
Full copyright and license terms can be found in the LICENSE.txt file.
*/
#include"ork/ork.hpp"
#define ORK_STL_INC_FILE <fstream>
#include"ork/core/stl_include.inl"
#define ORK_STL_INC_FILE <iostream>
#include"ork/core/stl_include.inl"
#define ORK_STL_INC_FILE <mutex>
#include"ork/core/stl_include.inl"
#define ORK_STL_INC_FILE <sstream>
#include"ork/core/stl_include.inl"
#include"ork/memory.hpp"
namespace ork {
const ork::string debug_trace(ORK("debug_trace"));
const ork::string output_data(ORK("output_data"));
const ork::string&to_string(const log_channel val) {
switch(val) {
case log_channel::debug_trace:
return debug_trace;
case log_channel::output_data:
return output_data;
};
ORK_UNREACHABLE
}
log_channel string2log_channel(const ork::string&str) {
if(str == output_data) {
return log_channel::output_data;
}
if(str == output_data) {
return log_channel::output_data;
}
ORK_THROW(ORK("Invalid log_channel: ") << str);
}
const ork::string trace(ORK("trace"));
const ork::string debug(ORK("debug"));
const ork::string info(ORK("info"));
const ork::string warning(ORK("warning"));
const ork::string error(ORK("error"));
const ork::string fatal(ORK("fatal"));
const ork::string&to_string(const severity_level val) {
switch(val) {
case severity_level::trace:
return trace;
case severity_level::debug:
return debug;
case severity_level::info:
return info;
case severity_level::warning:
return warning;
case severity_level::error:
return error;
case severity_level::fatal:
return fatal;
};
ORK_UNREACHABLE
}
severity_level string2severity_level(const ork::string&str) {
if(str == trace) {
return severity_level::trace;
}
if(str == debug) {
return severity_level::debug;
}
if(str == info) {
return severity_level::info;
}
if(str == warning) {
return severity_level::warning;
}
if(str == error) {
return severity_level::error;
}
if(str == fatal) {
return severity_level::fatal;
}
ORK_THROW(ORK("Invalid severity_level: ") << str);
}
//This is little more than a synchronous wrapper around an o_stream
class log_stream {
public:
using stream_ptr = std::shared_ptr<o_stream>;
private:
stream_ptr _stream;
std::mutex _mutex;
public:
explicit log_stream(stream_ptr stream_) : _stream{stream_}, _mutex{} {}
~log_stream() {
flush();
}
ORK_NON_COPYABLE(log_stream)
public:
void log(const string&message) {
std::lock_guard<std::mutex>lock(_mutex);
*_stream << message;
}
void flush() {
_stream->flush();
}
};
class log_sink {
public:
using stream_ptr = std::shared_ptr<log_stream>;
private:
std::vector<stream_ptr>_streams = {};
bool _auto_flush = true;
public:
log_sink() {}
log_sink(const bool auto_flush) : _auto_flush{auto_flush} {}
public:
void insert(const stream_ptr&ptr) {
_streams.push_back(ptr);
}
void log(const string&message) {
for(auto&stream : _streams) {
stream->log(message);
if(_auto_flush) {
stream->flush();
}
}
}
void set_auto_flush(const bool auto_flush) {
_auto_flush = auto_flush;
}
void flush() {
for(auto&stream : _streams) {
stream->flush();
}
}
};
std::shared_ptr<log_stream>open_file_log_stream(const file::path&file_name) {
if(!file::ensure_directory(file_name)) {
ORK_THROW(ORK("Could not create directory : ") << file_name.ORK_GEN_STR())
}
of_stream* p_stream = new of_stream();
p_stream->open(file_name);//std::ios::app | std::ios::ate
if(p_stream->fail()) {
ORK_THROW(ORK("Error opening log : ") << file_name)
}
//p_stream->rdbuf()->pubsetbuf(0, 0);//Less performance, more likely to catch error messages
return std::shared_ptr<log_stream>(new log_stream(log_stream::stream_ptr(p_stream)));
}
//This is where our logging system falls short of a generic filter system; try to hide it somewhat in one place
class log_multiplexer {
private:
std::array<log_sink, severity_levels.size()>_severity_sinks = {};
log_sink _data_sink = {};
public:
log_multiplexer(const file::path&root_directory){
auto lout = log_sink::stream_ptr{new log_stream{log_stream::stream_ptr{&ORK_CLOG, singleton_deleter<o_stream>()}}};
auto lerr = log_sink::stream_ptr{new log_stream{log_stream::stream_ptr{&ORK_CERR, singleton_deleter<o_stream>()}}};
auto flog = open_file_log_stream(root_directory / ORK("trace.log"));
auto fdata = open_file_log_stream(root_directory / ORK("output.log"));
for(const auto sv : severity_levels) {
auto sink = _severity_sinks[static_cast<size_t>(sv)];
if(sv < severity_level::error) {
sink.insert(lout);
sink.set_auto_flush(true);
}
else {
sink.insert(lerr);
}
sink.insert(flog);
}
_data_sink.insert(lout);
_data_sink.insert(fdata);
}
public:
void log(const log_channel channel, const severity_level severity, const o_string_stream&stream) {
const string message = stream.str();
switch(channel) {
case log_channel::debug_trace:
log_severity(severity, message);
break;
case log_channel::output_data:
_data_sink.log(stream.str());
break;
default:
ORK_UNREACHABLE
};
}
void flush_all() {
for(auto&sink : _severity_sinks) {
sink.flush();
}
_data_sink.flush();
}
private:
void log_severity(const severity_level severity, const string&message) {
const bool do_it = ORK_DEBUG || severity > severity_level::debug;
if ORK_CONSTEXPR(do_it || true) {
_severity_sinks[static_cast<size_t>(severity)].log(message);
}
}
};
struct log_scope::impl {
public:
std::shared_ptr<log_multiplexer>multiplexer;
log_channel channel;
severity_level severity;
o_string_stream stream;
public:
impl(std::shared_ptr<log_multiplexer>&mp, const log_channel lc, const severity_level sv)
: multiplexer{mp}
, channel{lc}
, severity{sv}
, stream{}
{}
~impl() {
multiplexer->log(channel, severity, stream);
}
ORK_MOVE_ONLY(impl)
};
log_scope::log_scope(std::unique_ptr<impl>&&ptr) : _pimpl{ std::move(ptr) } {}
log_scope::~log_scope() {}
#define LOG_STREAM_OPERATOR(TYPE) \
log_scope& log_scope::operator<< (const TYPE val) {\
_pimpl->stream << val;\
return *this;\
}
LOG_STREAM_OPERATOR(bool)
LOG_STREAM_OPERATOR(short)
LOG_STREAM_OPERATOR(unsigned short)
LOG_STREAM_OPERATOR(int)
LOG_STREAM_OPERATOR(unsigned)
LOG_STREAM_OPERATOR(long)
LOG_STREAM_OPERATOR(unsigned long)
LOG_STREAM_OPERATOR(long long)
LOG_STREAM_OPERATOR(unsigned long long)
LOG_STREAM_OPERATOR(float)
LOG_STREAM_OPERATOR(double)
LOG_STREAM_OPERATOR(long double)
#undef LOG_STREAM_OPERATOR
#define LOG_STREAM_OPERATOR(TYPE) \
log_scope& log_scope::operator<< (const TYPE val) {\
_pimpl->stream << ORK_BYTE_2_STR(val);\
return *this;\
}
LOG_STREAM_OPERATOR(char)
LOG_STREAM_OPERATOR(char*)
LOG_STREAM_OPERATOR(bstring&)
#undef LOG_STREAM_OPERATOR
#define LOG_STREAM_OPERATOR(TYPE) \
log_scope& log_scope::operator<< (const TYPE val) {\
_pimpl->stream << ORK_WIDE_2_STR(val);\
return *this;\
}
LOG_STREAM_OPERATOR(wchar_t)
LOG_STREAM_OPERATOR(wchar_t*)
LOG_STREAM_OPERATOR(wstring&)
log_scope& log_scope::operator<< (const void* val) {
_pimpl->stream << val;
return *this;
}
log_scope& log_scope::operator<< (const std::streambuf* sb) {
_pimpl->stream << sb;
return *this;
}
log_scope& log_scope::operator<< (std::ostream& (*pf)(std::ostream&)) {
_pimpl->stream << pf;
return *this;
}
log_scope& log_scope::operator<< (std::ios& (*pf)(std::ios&)) {
_pimpl->stream << pf;
return *this;
}
log_scope& log_scope::operator<< (std::ios_base& (*pf)(std::ios_base&)) {
_pimpl->stream << pf;
return *this;
}
const string&to_formatted_string(const severity_level sv) {
static const std::array<const string, severity_levels.size()>strings = {{
ORK("TRACE")
, ORK("DEBUG")
, ORK("INFO ")
, ORK("WARN ")
, ORK("ERROR")
, ORK("FATAL")
}};
return strings[static_cast<size_t>(sv)];
}
struct logger::impl {
public:
file::path root_directory;
std::shared_ptr<log_multiplexer>multiplexer;
public:
impl(const file::path&directory)
: root_directory(directory)
, multiplexer{new log_multiplexer(directory)}
{}
void flush_all() {
multiplexer->flush_all();
}
};
logger::logger(const file::path&log_directory) : _pimpl(new impl(log_directory)) {}
logger::~logger() {}
const file::path& logger::root_directory() {
return _pimpl->root_directory;
}
log_scope logger::get_log_scope(
const string&file_
, const string&line_
, const string&function_
, const log_channel channel
, const severity_level severity)
{
const file::path fullpath(file_);
string file(fullpath.filename().ORK_GEN_STR());
file.resize(28, ORK(' '));
string line(line_);
line.resize(4, ORK(' '));
string function(function_);
function.resize(40, ORK(' '));
std::unique_ptr<log_scope::impl> ls_impl(new log_scope::impl(_pimpl->multiplexer, channel, severity));
log_scope scope(std::move(ls_impl));
//Output formatted context first
scope << ORK("[") << to_formatted_string(severity) << ORK("]:") << file << ORK("(") << line << ORK("):") << function << ORK("-- ");
//Finally, return the stream to the client
return std::move(scope);
}
void logger::flush_all() {
_pimpl->flush_all();
}
logger*_g_log = nullptr;
int make_global_log(const string&directory) {
static logger log(directory);
_g_log = &log;
return 0;
}
logger& get_global_log() {
return *_g_log;
}
}//namespace ork
<commit_msg>Fixed auto flush settings<commit_after>/*
This file is part of the ORK library.
Full copyright and license terms can be found in the LICENSE.txt file.
*/
#include"ork/ork.hpp"
#define ORK_STL_INC_FILE <fstream>
#include"ork/core/stl_include.inl"
#define ORK_STL_INC_FILE <iostream>
#include"ork/core/stl_include.inl"
#define ORK_STL_INC_FILE <mutex>
#include"ork/core/stl_include.inl"
#define ORK_STL_INC_FILE <sstream>
#include"ork/core/stl_include.inl"
#include"ork/memory.hpp"
namespace ork {
const ork::string debug_trace(ORK("debug_trace"));
const ork::string output_data(ORK("output_data"));
const ork::string&to_string(const log_channel val) {
switch(val) {
case log_channel::debug_trace:
return debug_trace;
case log_channel::output_data:
return output_data;
};
ORK_UNREACHABLE
}
log_channel string2log_channel(const ork::string&str) {
if(str == output_data) {
return log_channel::output_data;
}
if(str == output_data) {
return log_channel::output_data;
}
ORK_THROW(ORK("Invalid log_channel: ") << str);
}
const ork::string trace(ORK("trace"));
const ork::string debug(ORK("debug"));
const ork::string info(ORK("info"));
const ork::string warning(ORK("warning"));
const ork::string error(ORK("error"));
const ork::string fatal(ORK("fatal"));
const ork::string&to_string(const severity_level val) {
switch(val) {
case severity_level::trace:
return trace;
case severity_level::debug:
return debug;
case severity_level::info:
return info;
case severity_level::warning:
return warning;
case severity_level::error:
return error;
case severity_level::fatal:
return fatal;
};
ORK_UNREACHABLE
}
severity_level string2severity_level(const ork::string&str) {
if(str == trace) {
return severity_level::trace;
}
if(str == debug) {
return severity_level::debug;
}
if(str == info) {
return severity_level::info;
}
if(str == warning) {
return severity_level::warning;
}
if(str == error) {
return severity_level::error;
}
if(str == fatal) {
return severity_level::fatal;
}
ORK_THROW(ORK("Invalid severity_level: ") << str);
}
//This is little more than a synchronous wrapper around an o_stream
class log_stream {
public:
using stream_ptr = std::shared_ptr<o_stream>;
private:
stream_ptr _stream;
std::mutex _mutex;
public:
explicit log_stream(stream_ptr stream_) : _stream{stream_}, _mutex{} {}
~log_stream() {
flush();
}
ORK_NON_COPYABLE(log_stream)
public:
void log(const string&message) {
std::lock_guard<std::mutex>lock(_mutex);
*_stream << message;
}
void flush() {
_stream->flush();
}
};
class log_sink {
public:
using stream_ptr = std::shared_ptr<log_stream>;
private:
std::vector<stream_ptr>_streams = {};
bool _auto_flush = false;
public:
log_sink() {}
log_sink(const bool auto_flush) : _auto_flush{auto_flush} {}
public:
void insert(const stream_ptr&ptr) {
_streams.push_back(ptr);
}
void log(const string&message) {
for(auto&stream : _streams) {
stream->log(message);
if(_auto_flush) {
stream->flush();
}
}
}
void set_auto_flush(const bool auto_flush) {
_auto_flush = auto_flush;
}
void flush() {
for(auto&stream : _streams) {
stream->flush();
}
}
};
std::shared_ptr<log_stream>open_file_log_stream(const file::path&file_name) {
if(!file::ensure_directory(file_name)) {
ORK_THROW(ORK("Could not create directory : ") << file_name.ORK_GEN_STR())
}
of_stream* p_stream = new of_stream();
p_stream->open(file_name);//std::ios::app | std::ios::ate
if(p_stream->fail()) {
ORK_THROW(ORK("Error opening log : ") << file_name)
}
//p_stream->rdbuf()->pubsetbuf(0, 0);//Less performance, more likely to catch error messages
return std::shared_ptr<log_stream>(new log_stream(log_stream::stream_ptr(p_stream)));
}
//This is where our logging system falls short of a generic filter system; try to hide it somewhat in one place
class log_multiplexer {
private:
std::array<log_sink, severity_levels.size()>_severity_sinks = {};
log_sink _data_sink = {};
public:
log_multiplexer(const file::path&root_directory){
auto lout = log_sink::stream_ptr{new log_stream{log_stream::stream_ptr{&ORK_CLOG, singleton_deleter<o_stream>()}}};
auto lerr = log_sink::stream_ptr{new log_stream{log_stream::stream_ptr{&ORK_CERR, singleton_deleter<o_stream>()}}};
auto flog = open_file_log_stream(root_directory / ORK("trace.log"));
auto fdata = open_file_log_stream(root_directory / ORK("output.log"));
for(const auto sv : severity_levels) {
auto sink = _severity_sinks[static_cast<size_t>(sv)];
if(sv < severity_level::error) {
sink.insert(lout);
}
else {
sink.insert(lerr);
sink.set_auto_flush(true);
}
sink.insert(flog);
}
_data_sink.insert(lout);
_data_sink.insert(fdata);
}
public:
void log(const log_channel channel, const severity_level severity, const o_string_stream&stream) {
const string message = stream.str();
switch(channel) {
case log_channel::debug_trace:
log_severity(severity, message);
break;
case log_channel::output_data:
_data_sink.log(stream.str());
break;
default:
ORK_UNREACHABLE
};
}
void flush_all() {
for(auto&sink : _severity_sinks) {
sink.flush();
}
_data_sink.flush();
}
private:
void log_severity(const severity_level severity, const string&message) {
const bool do_it = ORK_DEBUG || severity > severity_level::debug;
if ORK_CONSTEXPR(do_it || true) {
_severity_sinks[static_cast<size_t>(severity)].log(message);
}
}
};
struct log_scope::impl {
public:
std::shared_ptr<log_multiplexer>multiplexer;
log_channel channel;
severity_level severity;
o_string_stream stream;
public:
impl(std::shared_ptr<log_multiplexer>&mp, const log_channel lc, const severity_level sv)
: multiplexer{mp}
, channel{lc}
, severity{sv}
, stream{}
{}
~impl() {
multiplexer->log(channel, severity, stream);
}
ORK_MOVE_ONLY(impl)
};
log_scope::log_scope(std::unique_ptr<impl>&&ptr) : _pimpl{ std::move(ptr) } {}
log_scope::~log_scope() {}
#define LOG_STREAM_OPERATOR(TYPE) \
log_scope& log_scope::operator<< (const TYPE val) {\
_pimpl->stream << val;\
return *this;\
}
LOG_STREAM_OPERATOR(bool)
LOG_STREAM_OPERATOR(short)
LOG_STREAM_OPERATOR(unsigned short)
LOG_STREAM_OPERATOR(int)
LOG_STREAM_OPERATOR(unsigned)
LOG_STREAM_OPERATOR(long)
LOG_STREAM_OPERATOR(unsigned long)
LOG_STREAM_OPERATOR(long long)
LOG_STREAM_OPERATOR(unsigned long long)
LOG_STREAM_OPERATOR(float)
LOG_STREAM_OPERATOR(double)
LOG_STREAM_OPERATOR(long double)
#undef LOG_STREAM_OPERATOR
#define LOG_STREAM_OPERATOR(TYPE) \
log_scope& log_scope::operator<< (const TYPE val) {\
_pimpl->stream << ORK_BYTE_2_STR(val);\
return *this;\
}
LOG_STREAM_OPERATOR(char)
LOG_STREAM_OPERATOR(char*)
LOG_STREAM_OPERATOR(bstring&)
#undef LOG_STREAM_OPERATOR
#define LOG_STREAM_OPERATOR(TYPE) \
log_scope& log_scope::operator<< (const TYPE val) {\
_pimpl->stream << ORK_WIDE_2_STR(val);\
return *this;\
}
LOG_STREAM_OPERATOR(wchar_t)
LOG_STREAM_OPERATOR(wchar_t*)
LOG_STREAM_OPERATOR(wstring&)
log_scope& log_scope::operator<< (const void* val) {
_pimpl->stream << val;
return *this;
}
log_scope& log_scope::operator<< (const std::streambuf* sb) {
_pimpl->stream << sb;
return *this;
}
log_scope& log_scope::operator<< (std::ostream& (*pf)(std::ostream&)) {
_pimpl->stream << pf;
return *this;
}
log_scope& log_scope::operator<< (std::ios& (*pf)(std::ios&)) {
_pimpl->stream << pf;
return *this;
}
log_scope& log_scope::operator<< (std::ios_base& (*pf)(std::ios_base&)) {
_pimpl->stream << pf;
return *this;
}
const string&to_formatted_string(const severity_level sv) {
static const std::array<const string, severity_levels.size()>strings = {{
ORK("TRACE")
, ORK("DEBUG")
, ORK("INFO ")
, ORK("WARN ")
, ORK("ERROR")
, ORK("FATAL")
}};
return strings[static_cast<size_t>(sv)];
}
struct logger::impl {
public:
file::path root_directory;
std::shared_ptr<log_multiplexer>multiplexer;
public:
impl(const file::path&directory)
: root_directory(directory)
, multiplexer{new log_multiplexer(directory)}
{}
void flush_all() {
multiplexer->flush_all();
}
};
logger::logger(const file::path&log_directory) : _pimpl(new impl(log_directory)) {}
logger::~logger() {}
const file::path& logger::root_directory() {
return _pimpl->root_directory;
}
log_scope logger::get_log_scope(
const string&file_
, const string&line_
, const string&function_
, const log_channel channel
, const severity_level severity)
{
const file::path fullpath(file_);
string file(fullpath.filename().ORK_GEN_STR());
file.resize(28, ORK(' '));
string line(line_);
line.resize(4, ORK(' '));
string function(function_);
function.resize(40, ORK(' '));
std::unique_ptr<log_scope::impl> ls_impl(new log_scope::impl(_pimpl->multiplexer, channel, severity));
log_scope scope(std::move(ls_impl));
//Output formatted context first
scope << ORK("[") << to_formatted_string(severity) << ORK("]:") << file << ORK("(") << line << ORK("):") << function << ORK("-- ");
//Finally, return the stream to the client
return std::move(scope);
}
void logger::flush_all() {
_pimpl->flush_all();
}
logger*_g_log = nullptr;
int make_global_log(const string&directory) {
static logger log(directory);
_g_log = &log;
return 0;
}
logger& get_global_log() {
return *_g_log;
}
}//namespace ork
<|endoftext|> |
<commit_before>#include "loom.hpp"
namespace loom
{
using ::distributions::sample_from_scores_overwrite;
Loom::Loom (
rng_t & rng,
const char * model_in,
const char * groups_in,
const char * assign_in) :
cross_cat_(model_in),
assignments_(cross_cat_.kinds.size()),
value_join_(cross_cat_),
factors_(cross_cat_.kinds.size()),
scores_()
{
LOOM_ASSERT(not cross_cat_.kinds.empty(), "no kinds, loom is empty");
if (groups_in) {
cross_cat_.mixture_load(groups_in, rng);
} else {
cross_cat_.mixture_init_empty(rng);
}
if (assign_in) {
assignments_.load(assign_in);
for (const auto & kind : cross_cat_.kinds) {
LOOM_ASSERT_LE(
assignments_.size(),
kind.mixture.clustering.sample_size());
}
}
}
//----------------------------------------------------------------------------
// High level operations
void Loom::dump (
const char * groups_out,
const char * assign_out)
{
if (groups_out) {
cross_cat_.mixture_dump(groups_out);
}
if (assign_out) {
assignments_.dump(assign_out);
}
}
void Loom::infer_single_pass (
rng_t & rng,
const char * rows_in,
const char * assign_out)
{
protobuf::InFile rows(rows_in);
protobuf::SparseRow row;
if (assign_out) {
protobuf::OutFile assignments(assign_out);
protobuf::Assignment assignment;
while (rows.try_read_stream(row)) {
add_row(rng, row, assignment);
assignments.write_stream(assignment);
}
} else {
while (rows.try_read_stream(row)) {
add_row_noassign(rng, row);
}
}
}
void Loom::infer_multi_pass (
rng_t & rng,
const char * rows_in,
double extra_passes)
{
protobuf::InFile rows_to_add(rows_in);
protobuf::InFile rows_to_remove(rows_in);
protobuf::SparseRow row;
// Set positions of both read heads.
if (assignments_.size()) {
// point rows_to_add at first unassigned row
const auto last_assigned_rowid = assignments_.rowids().back();
do {
rows_to_add.cyclic_read_stream(row);
} while (row.id() != last_assigned_rowid);
// point rows_to_remove at first assigned row
const auto first_assigned_rowid = assignments_.rowids().front();
do {
rows_to_remove.cyclic_read_stream(row);
} while (row.id() != first_assigned_rowid);
remove_row(rng, row);
}
AnnealingSchedule schedule(extra_passes);
while (true) {
if (schedule.next_action_is_add()) {
rows_to_add.cyclic_read_stream(row);
bool all_rows_assigned = not try_add_row(rng, row);
if (LOOM_UNLIKELY(all_rows_assigned)) {
break;
}
} else {
rows_to_remove.cyclic_read_stream(row);
remove_row(rng, row);
}
}
}
void Loom::predict (
rng_t & rng,
const char * queries_in,
const char * results_out)
{
protobuf::InFile query_stream(queries_in);
protobuf::OutFile result_stream(results_out);
protobuf::PreQL::Predict::Query query;
protobuf::PreQL::Predict::Result result;
while (query_stream.try_read_stream(query)) {
predict_row(rng, query, result);
result_stream.write_stream(result);
result_stream.flush();
}
}
//----------------------------------------------------------------------------
// Low level operations
inline void Loom::add_row_noassign (
rng_t & rng,
const protobuf::SparseRow & row)
{
cross_cat_.value_split(row.data(), factors_);
const size_t kind_count = cross_cat_.kinds.size();
for (size_t i = 0; i < kind_count; ++i) {
const auto & value = factors_[i];
auto & kind = cross_cat_.kinds[i];
const ProductModel & model = kind.model;
ProductModel::Mixture & mixture = kind.mixture;
mixture.score(model, value, scores_, rng);
size_t groupid = sample_from_scores_overwrite(rng, scores_);
mixture.add_value(model, groupid, value, rng);
}
}
inline void Loom::add_row (
rng_t & rng,
const protobuf::SparseRow & row,
protobuf::Assignment & assignment)
{
cross_cat_.value_split(row.data(), factors_);
assignment.set_rowid(row.id());
assignment.clear_groupids();
const size_t kind_count = cross_cat_.kinds.size();
for (size_t i = 0; i < kind_count; ++i) {
const auto & value = factors_[i];
auto & kind = cross_cat_.kinds[i];
const ProductModel & model = kind.model;
ProductModel::Mixture & mixture = kind.mixture;
mixture.score(model, value, scores_, rng);
size_t groupid = sample_from_scores_overwrite(rng, scores_);
mixture.add_value(model, groupid, value, rng);
assignment.add_groupids(groupid);
}
}
inline bool Loom::try_add_row (
rng_t & rng,
const protobuf::SparseRow & row)
{
bool already_added = not assignments_.rowids().try_push(row.id());
if (LOOM_UNLIKELY(already_added)) {
return false;
}
cross_cat_.value_split(row.data(), factors_);
const size_t kind_count = cross_cat_.kinds.size();
for (size_t i = 0; i < kind_count; ++i) {
const auto & value = factors_[i];
auto & kind = cross_cat_.kinds[i];
const ProductModel & model = kind.model;
ProductModel::Mixture & mixture = kind.mixture;
mixture.score(model, value, scores_, rng);
size_t groupid = sample_from_scores_overwrite(rng, scores_);
mixture.add_value(model, groupid, value, rng);
size_t global_groupid = mixture.id_tracker.packed_to_global(groupid);
assignments_.groupids(i).push(global_groupid);
}
return true;
}
inline void Loom::remove_row (
rng_t & rng,
const protobuf::SparseRow & row)
{
assignments_.rowids().pop();
cross_cat_.value_split(row.data(), factors_);
const size_t kind_count = cross_cat_.kinds.size();
for (size_t i = 0; i < kind_count; ++i) {
const auto & value = factors_[i];
auto & kind = cross_cat_.kinds[i];
const ProductModel & model = kind.model;
ProductModel::Mixture & mixture = kind.mixture;
auto global_groupid = assignments_.groupids(i).pop();
auto groupid = mixture.id_tracker.global_to_packed(global_groupid);
mixture.remove_value(model, groupid, value, rng);
}
}
inline void Loom::predict_row (
rng_t & rng,
const protobuf::PreQL::Predict::Query & query,
protobuf::PreQL::Predict::Result & result)
{
result.Clear();
result.set_id(query.id());
if (not cross_cat_.schema.is_valid(query.data())) {
result.set_error("invalid query data");
return;
}
if (query.data().observed_size() != query.to_predict_size()) {
result.set_error("observed size != to_predict size");
return;
}
const size_t sample_count = query.sample_count();
if (sample_count == 0) {
return;
}
cross_cat_.value_split(query.data(), factors_);
std::vector<std::vector<ProductModel::Value>> result_factors(1);
{
ProductModel::Value sample;
* sample.mutable_observed() = query.to_predict();
cross_cat_.value_resize(sample);
cross_cat_.value_split(sample, result_factors[0]);
result_factors.resize(sample_count, result_factors[0]);
}
const size_t kind_count = cross_cat_.kinds.size();
for (size_t i = 0; i < kind_count; ++i) {
if (protobuf::SparseValueSchema::total_size(result_factors[0][i])) {
const auto & value = factors_[i];
auto & kind = cross_cat_.kinds[i];
const ProductModel & model = kind.model;
ProductModel::Mixture & mixture = kind.mixture;
mixture.score(model, value, scores_, rng);
float total = distributions::scores_to_likelihoods(scores_);
distributions::vector_scale(
scores_.size(),
scores_.data(),
1.f / total);
const VectorFloat & probs = scores_;
for (auto & result_values : result_factors) {
mixture.sample_value(model, probs, result_values[i], rng);
}
}
}
for (const auto & result_values : result_factors) {
value_join_(* result.add_samples(), result_values);
}
}
} // namespace loom
<commit_msg>Factor out StreamInterval from Loom::infer_multipass<commit_after>#include "loom.hpp"
namespace loom
{
//----------------------------------------------------------------------------
// StreamInterval
class StreamInterval : noncopyable
{
public:
template<class RemoveRow>
StreamInterval (
const char * rows_in,
Assignments & assignments,
RemoveRow remove_row) :
unassigned_(rows_in),
assigned_(rows_in)
{
if (assignments.size()) {
protobuf::SparseRow row;
// point unassigned at first unassigned row
const auto last_assigned_rowid = assignments.rowids().back();
do {
read_unassigned(row);
} while (row.id() != last_assigned_rowid);
// point rows_assigned at first assigned row
const auto first_assigned_rowid = assignments.rowids().front();
do {
read_assigned(row);
} while (row.id() != first_assigned_rowid);
remove_row(row);
}
}
void read_unassigned (protobuf::SparseRow & row)
{
unassigned_.cyclic_read_stream(row);
}
void read_assigned (protobuf::SparseRow & row)
{
assigned_.cyclic_read_stream(row);
}
private:
protobuf::InFile unassigned_;
protobuf::InFile assigned_;
};
//----------------------------------------------------------------------------
// Loom
using ::distributions::sample_from_scores_overwrite;
Loom::Loom (
rng_t & rng,
const char * model_in,
const char * groups_in,
const char * assign_in) :
cross_cat_(model_in),
assignments_(cross_cat_.kinds.size()),
value_join_(cross_cat_),
factors_(cross_cat_.kinds.size()),
scores_()
{
LOOM_ASSERT(not cross_cat_.kinds.empty(), "no kinds, loom is empty");
if (groups_in) {
cross_cat_.mixture_load(groups_in, rng);
} else {
cross_cat_.mixture_init_empty(rng);
}
if (assign_in) {
assignments_.load(assign_in);
for (const auto & kind : cross_cat_.kinds) {
LOOM_ASSERT_LE(
assignments_.size(),
kind.mixture.clustering.sample_size());
}
}
}
//----------------------------------------------------------------------------
// High level operations
void Loom::dump (
const char * groups_out,
const char * assign_out)
{
if (groups_out) {
cross_cat_.mixture_dump(groups_out);
}
if (assign_out) {
assignments_.dump(assign_out);
}
}
void Loom::infer_single_pass (
rng_t & rng,
const char * rows_in,
const char * assign_out)
{
protobuf::InFile rows(rows_in);
protobuf::SparseRow row;
if (assign_out) {
protobuf::OutFile assignments(assign_out);
protobuf::Assignment assignment;
while (rows.try_read_stream(row)) {
add_row(rng, row, assignment);
assignments.write_stream(assignment);
}
} else {
while (rows.try_read_stream(row)) {
add_row_noassign(rng, row);
}
}
}
void Loom::infer_multi_pass (
rng_t & rng,
const char * rows_in,
double extra_passes)
{
auto _remove_row = [&](protobuf::SparseRow & row) { remove_row(rng, row); };
StreamInterval rows(rows_in, assignments_, _remove_row);
protobuf::SparseRow row;
AnnealingSchedule schedule(extra_passes);
while (true) {
if (schedule.next_action_is_add()) {
rows.read_unassigned(row);
bool all_rows_assigned = not try_add_row(rng, row);
if (LOOM_UNLIKELY(all_rows_assigned)) {
break;
}
} else {
rows.read_assigned(row);
remove_row(rng, row);
}
}
}
void Loom::predict (
rng_t & rng,
const char * queries_in,
const char * results_out)
{
protobuf::InFile query_stream(queries_in);
protobuf::OutFile result_stream(results_out);
protobuf::PreQL::Predict::Query query;
protobuf::PreQL::Predict::Result result;
while (query_stream.try_read_stream(query)) {
predict_row(rng, query, result);
result_stream.write_stream(result);
result_stream.flush();
}
}
//----------------------------------------------------------------------------
// Low level operations
inline void Loom::add_row_noassign (
rng_t & rng,
const protobuf::SparseRow & row)
{
cross_cat_.value_split(row.data(), factors_);
const size_t kind_count = cross_cat_.kinds.size();
for (size_t i = 0; i < kind_count; ++i) {
const auto & value = factors_[i];
auto & kind = cross_cat_.kinds[i];
const ProductModel & model = kind.model;
ProductModel::Mixture & mixture = kind.mixture;
mixture.score(model, value, scores_, rng);
size_t groupid = sample_from_scores_overwrite(rng, scores_);
mixture.add_value(model, groupid, value, rng);
}
}
inline void Loom::add_row (
rng_t & rng,
const protobuf::SparseRow & row,
protobuf::Assignment & assignment)
{
cross_cat_.value_split(row.data(), factors_);
assignment.set_rowid(row.id());
assignment.clear_groupids();
const size_t kind_count = cross_cat_.kinds.size();
for (size_t i = 0; i < kind_count; ++i) {
const auto & value = factors_[i];
auto & kind = cross_cat_.kinds[i];
const ProductModel & model = kind.model;
ProductModel::Mixture & mixture = kind.mixture;
mixture.score(model, value, scores_, rng);
size_t groupid = sample_from_scores_overwrite(rng, scores_);
mixture.add_value(model, groupid, value, rng);
assignment.add_groupids(groupid);
}
}
inline bool Loom::try_add_row (
rng_t & rng,
const protobuf::SparseRow & row)
{
bool already_added = not assignments_.rowids().try_push(row.id());
if (LOOM_UNLIKELY(already_added)) {
return false;
}
cross_cat_.value_split(row.data(), factors_);
const size_t kind_count = cross_cat_.kinds.size();
for (size_t i = 0; i < kind_count; ++i) {
const auto & value = factors_[i];
auto & kind = cross_cat_.kinds[i];
const ProductModel & model = kind.model;
ProductModel::Mixture & mixture = kind.mixture;
mixture.score(model, value, scores_, rng);
size_t groupid = sample_from_scores_overwrite(rng, scores_);
mixture.add_value(model, groupid, value, rng);
size_t global_groupid = mixture.id_tracker.packed_to_global(groupid);
assignments_.groupids(i).push(global_groupid);
}
return true;
}
inline void Loom::remove_row (
rng_t & rng,
const protobuf::SparseRow & row)
{
assignments_.rowids().pop();
cross_cat_.value_split(row.data(), factors_);
const size_t kind_count = cross_cat_.kinds.size();
for (size_t i = 0; i < kind_count; ++i) {
const auto & value = factors_[i];
auto & kind = cross_cat_.kinds[i];
const ProductModel & model = kind.model;
ProductModel::Mixture & mixture = kind.mixture;
auto global_groupid = assignments_.groupids(i).pop();
auto groupid = mixture.id_tracker.global_to_packed(global_groupid);
mixture.remove_value(model, groupid, value, rng);
}
}
inline void Loom::predict_row (
rng_t & rng,
const protobuf::PreQL::Predict::Query & query,
protobuf::PreQL::Predict::Result & result)
{
result.Clear();
result.set_id(query.id());
if (not cross_cat_.schema.is_valid(query.data())) {
result.set_error("invalid query data");
return;
}
if (query.data().observed_size() != query.to_predict_size()) {
result.set_error("observed size != to_predict size");
return;
}
const size_t sample_count = query.sample_count();
if (sample_count == 0) {
return;
}
cross_cat_.value_split(query.data(), factors_);
std::vector<std::vector<ProductModel::Value>> result_factors(1);
{
ProductModel::Value sample;
* sample.mutable_observed() = query.to_predict();
cross_cat_.value_resize(sample);
cross_cat_.value_split(sample, result_factors[0]);
result_factors.resize(sample_count, result_factors[0]);
}
const size_t kind_count = cross_cat_.kinds.size();
for (size_t i = 0; i < kind_count; ++i) {
if (protobuf::SparseValueSchema::total_size(result_factors[0][i])) {
const auto & value = factors_[i];
auto & kind = cross_cat_.kinds[i];
const ProductModel & model = kind.model;
ProductModel::Mixture & mixture = kind.mixture;
mixture.score(model, value, scores_, rng);
float total = distributions::scores_to_likelihoods(scores_);
distributions::vector_scale(
scores_.size(),
scores_.data(),
1.f / total);
const VectorFloat & probs = scores_;
for (auto & result_values : result_factors) {
mixture.sample_value(model, probs, result_values[i], rng);
}
}
}
for (const auto & result_values : result_factors) {
value_join_(* result.add_samples(), result_values);
}
}
} // namespace loom
<|endoftext|> |
<commit_before>// Simple UDP-to-HTTPS DNS Proxy
//
// (C) 2016 Aaron Drew
//
// Intended for use with Google's Public-DNS over HTTPS service
// (https://developers.google.com/speed/public-dns/docs/dns-over-https)
#include <arpa/inet.h>
#include <curl/curl.h>
#include <errno.h>
#include <grp.h>
#include <netdb.h>
#include <netinet/in.h>
#include <pwd.h>
#include <signal.h>
#include <stdio.h>
#include <stdint.h>
#include <stdlib.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <time.h>
#include <unistd.h>
#include <ares.h>
#include "dns_packet.h"
#include "options.h"
#include "logging.h"
using namespace std;
namespace {
sig_atomic_t gKeepRunning = 1;
// Quit gracefully on Ctrl-C
void SigHandler(int sig) {
if (sig == SIGINT) {
gKeepRunning = 0;
}
}
// rand() is used for tx_id selection in outgoing DNS requests.
// This is probably overkill but seed the PRNG with a decent
// source to minimize chance of sequence prediction.
static void prng_init() {
struct timeval time;
gettimeofday(&time, NULL);
srand(time.tv_sec);
srand(rand() + time.tv_usec);
}
// Called when c-ares has a DNS response or error for a lookup of
// dns.google.com.
void AresCallback(void *arg, int status, int timeouts,
struct hostent *hostent) {
if (status != ARES_SUCCESS) {
WLOG("DNS lookup failed: %d", status);
}
if (!hostent || hostent->h_length < 1) {
WLOG("No hosts.");
return;
}
char buf[128] = "dns.google.com:443:";
char *p = buf + strlen(buf);
int l = sizeof(buf) - strlen(buf);
ares_inet_ntop(AF_INET, hostent->h_addr_list[0], p, l);
DLOG("Received new IP '%s'", p);
// Update libcurl's resolv cache (we pass these cache injection entries in on
// every request)
curl_slist **p_client_resolv = (curl_slist**)arg;
curl_slist_free_all(*p_client_resolv);
*p_client_resolv = curl_slist_append(NULL, buf);
}
class Request {
public:
Request(uint16_t tx_id, const char *url,
sockaddr_in raddr, curl_slist *resolv) {
curl_ = curl_easy_init();
tx_id_ = tx_id;
buf_ = NULL;
len_ = 0;
raddr_ = raddr;
resolv_ = resolv;
CURLcode res;
if ((res = curl_easy_setopt(curl_, CURLOPT_RESOLVE, resolv_)) != CURLE_OK) {
FLOG("CURLOPT_RESOLV error: %s", curl_easy_strerror(res));
}
curl_easy_setopt(curl_, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_2_0);
curl_easy_setopt(curl_, CURLOPT_URL, url);
curl_easy_setopt(curl_, CURLOPT_WRITEFUNCTION, &WriteBuffer);
curl_easy_setopt(curl_, CURLOPT_WRITEDATA, (void *)this);
curl_easy_setopt(curl_, CURLOPT_TCP_KEEPALIVE, 1L);
curl_easy_setopt(curl_, CURLOPT_USERAGENT, "dns-to-https-proxy/0.1");
DLOG("Req %04x: %s", tx_id_, url);
}
CURL *easy_handle() { return curl_; }
void SendResponse(int listen_sock) {
if (buf_ == NULL) {
DLOG("No response received. Ignoring.");
return;
}
DNSPacket r;
if (!r.ReadJson(tx_id_, buf_)) {
WLOG("Failed to interpret JSON '%s'. Skipping.", buf_);
return;
}
char ret[4096];
int len = 0;
if (!r.WriteDNS(ret, ret + sizeof(ret), &len)) {
DLOG("Failed to write DNS response to buffer. Skipping.");
return;
}
if (len > 0) {
sendto(listen_sock, ret, len, 0, (sockaddr *)&raddr_, sizeof(raddr_));
}
DLOG("Resp %04x", tx_id_);
}
~Request() {
curl_easy_cleanup(curl_);
free(buf_);
}
private:
CURL *curl_;
uint16_t tx_id_;
char *buf_;
size_t len_;
sockaddr_in raddr_;
curl_slist *resolv_;
static size_t WriteBuffer(
void *contents, size_t size, size_t nmemb, void *userp) {
Request *req = (Request *)userp;
char *new_buf = (char *)realloc(req->buf_, req->len_ + size * nmemb + 1);
if(new_buf == NULL) {
ELOG("Out of memory!");
return 0;
}
req->buf_ = new_buf;
memcpy(&(req->buf_[req->len_]), contents, size * nmemb);
req->len_ += size * nmemb;
req->buf_[req->len_] = '\0';
return size * nmemb;
}
};
// Multiplexes three things, forever:
// 1. Listening socket for incoming DNS requests.
// 2. Outgoing sockets for HTTPS requests.
// 3. Outgoing socket for periodic DNS client query for dns.google.com.
void RunSelectLoop(const Options& opt, int listen_sock) {
CURLM *curlm = curl_multi_init();
curl_multi_setopt(curlm, CURLMOPT_PIPELINING, CURLPIPE_MULTIPLEX);
// Avoid C++ map, etc for symbol bloat.
// We don't bother sorting this, so O(n) cost in number of concurrent
// requests. I assume this won't hurt much.
Request* reqs[4096];
int num_reqs = 0;
// DNS client.
ares_channel ares;
if (ares_init(&ares) != ARES_SUCCESS) {
FLOG("Failed to init c-ares channel");
}
if (ares_set_servers_csv(ares, opt.bootstrap_dns) != ARES_SUCCESS) {
FLOG("Failed to set DNS servers to '%s'.", opt.bootstrap_dns);
}
// 60 seconds poll. Rely on c-ares to honor DNS TTL.
const time_t client_req_interval = 60;
time_t last_client_req_time = 0;
curl_slist *client_resolv = NULL;
while (gKeepRunning) {
fd_set rfd, wfd, efd;
int max_fd;
// If we need to, send off a DNS request.
if (last_client_req_time + client_req_interval < time(NULL)) {
DLOG("Sending DNS request for dns.google.com");
last_client_req_time = time(NULL);
ares_gethostbyname(ares, "dns.google.com", AF_INET,
&AresCallback, &client_resolv);
}
// Curl tells us how long select should wait.
long curl_timeo;
timeval timeout;
curl_multi_timeout(curlm, &curl_timeo);
if(curl_timeo < 0) curl_timeo = 1000;
timeout.tv_sec = curl_timeo / 1000;
timeout.tv_usec = (curl_timeo % 1000) * 1000;
FD_ZERO(&rfd); FD_ZERO(&wfd); FD_ZERO(&efd); max_fd = 0;
CURLMcode err;
if ((err = curl_multi_fdset(curlm, &rfd, &wfd, &efd, &max_fd)) != CURLM_OK) {
FLOG("CURL error: %s", curl_multi_strerror(err));
}
FD_SET(listen_sock, &rfd);
max_fd = max_fd > listen_sock ? max_fd : listen_sock;
int ares_max_fd = ares_fds(ares, &rfd, &wfd) - 1;
max_fd = max_fd > ares_max_fd ? max_fd : ares_max_fd;
int r = select(max_fd + 1, &rfd, &wfd, &efd, &timeout);
if (r < 0) continue; // Signal.
if (r == 0) continue; // Timeout.
// DNS request
if (FD_ISSET(listen_sock, &rfd)) {
unsigned char buf[1500]; // A whole MTU. We don't do TCP so any bigger is a waste.
sockaddr_in raddr;
socklen_t raddr_size = sizeof(raddr);
int len = recvfrom(listen_sock, buf, sizeof(buf), 0,
(sockaddr *)&raddr, &raddr_size);
if (len < 0) {
WLOG("recvfrom failed: %s", strerror(errno));
continue;
}
unsigned char *p = buf;
uint16_t tx_id = ntohs(*(uint16_t*)p); p += 2;
uint16_t flags = ntohs(*(uint16_t*)p); p += 2;
uint16_t num_q = ntohs(*(uint16_t*)p); p += 2;
uint16_t num_rr = ntohs(*(uint16_t*)p); p += 2;
uint16_t num_arr = ntohs(*(uint16_t*)p); p += 2;
uint16_t num_xrr = ntohs(*(uint16_t*)p); p += 2;
if (num_q != 1) {
DLOG("Malformed request received.");
continue;
};
char *domain_name;
long enc_len;
if (ares_expand_name(p, buf, len,
&domain_name, &enc_len) != ARES_SUCCESS) {
DLOG("Malformed request received.");
continue;
}
p += enc_len;
uint16_t type = ntohs(*(uint16_t*)p); p += 2;
bool cd_bit = flags & (1 << 4);
char *escaped_name = curl_escape(domain_name, strlen(domain_name));
ares_free_string(domain_name);
char url[1500] = {};
snprintf(url, sizeof(url)-1,
"https://dns.google.com/resolve?name=%s&type=%d%s",
escaped_name, type, cd_bit ? "&cd=true" : "");
curl_free(escaped_name);
Request *req = new Request(tx_id, url, raddr, client_resolv);
reqs[num_reqs++] = req;
curl_multi_add_handle(curlm, req->easy_handle());
}
// DNS response
ares_process(ares, &rfd, &wfd);
// CURL transfers
if (r >= 0) {
int running_https = 0;
if ((err = curl_multi_perform(curlm, &running_https)) != CURLM_OK) {
FLOG("CURL error: %s", curl_multi_strerror(err));
}
CURLMsg *m;
int msgq = 0;
while (m = curl_multi_info_read(curlm, &msgq)) {
if(m->msg == CURLMSG_DONE) {
for (int i = 0; i < num_reqs; i++) {
if (reqs[i]->easy_handle() == m->easy_handle) {
Request *req = reqs[i];
req->SendResponse(listen_sock);
reqs[i] = reqs[--num_reqs];
curl_multi_remove_handle(curlm, m->easy_handle);
delete req;
break;
}
}
}
}
}
}
WLOG("Shutting down.");
// Cancel all pending requests.
for (int i = 0; i < num_reqs; i++) {
curl_multi_remove_handle(curlm, reqs[i]->easy_handle());
delete reqs[i];
}
curl_multi_cleanup(curlm);
ares_destroy(ares);
curl_slist_free_all(client_resolv);
close(listen_sock);
}
} // namespace
int main(int argc, char *argv[]) {
prng_init();
struct Options opt;
options_init(&opt);
if (options_parse_args(&opt, argc, argv)) {
options_show_usage(argc, argv);
exit(1);
}
logging_init(opt.logfd, opt.loglevel);
ares_library_init(ARES_LIB_INIT_ALL);
curl_global_init(CURL_GLOBAL_DEFAULT);
sockaddr_in laddr, raddr;
memset(&laddr, 0, sizeof(laddr));
laddr.sin_family = AF_INET;
laddr.sin_port = htons(opt.listen_port);
laddr.sin_addr.s_addr = inet_addr(opt.listen_addr);
int sock = socket(AF_INET, SOCK_DGRAM, 0);
if (sock < 0) {
FLOG("Error creating socket");
}
if(bind(sock, (struct sockaddr*)&laddr, sizeof(laddr)) < 0) {
FLOG("Error binding %s:%d", opt.listen_addr, opt.listen_port);
}
ILOG("Listening on %s:%d", opt.listen_addr, opt.listen_port);
if (opt.daemonize) {
if (setgid(opt.gid)) FLOG("Failed to set gid.");
if (setuid(opt.uid)) FLOG("Failed to set uid.");
// Note: This is non-standard. If needed, see OpenSSH openbsd-compat/daemon.c
daemon(0, 0);
}
if (signal(SIGINT, SigHandler) == SIG_ERR) {
FLOG("Can't set signal handler.");
}
RunSelectLoop(opt, sock);
curl_global_cleanup();
ares_library_cleanup();
logging_cleanup();
options_cleanup(&opt);
return 0;
}
<commit_msg>Update main.cc<commit_after>// Simple UDP-to-HTTPS DNS Proxy
//
// (C) 2016 Aaron Drew
//
// Intended for use with Google's Public-DNS over HTTPS service
// (https://developers.google.com/speed/public-dns/docs/dns-over-https)
#include <arpa/inet.h>
#include <curl/curl.h>
#include <errno.h>
#include <grp.h>
#include <netdb.h>
#include <netinet/in.h>
#include <pwd.h>
#include <signal.h>
#include <stdio.h>
#include <stdint.h>
#include <stdlib.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <time.h>
#include <unistd.h>
#include <ares.h>
#include "dns_packet.h"
#include "options.h"
#include "logging.h"
static sig_atomic_t gKeepRunning = 1;
// Quit gracefully on Ctrl-C
static void SigHandler(int sig) {
if (sig == SIGINT) gKeepRunning = 0;
}
// rand() is used for tx_id selection in outgoing DNS requests.
// This is probably overkill but seed the PRNG with a decent
// source to minimize chance of sequence prediction.
static void prng_init() {
struct timeval time;
gettimeofday(&time, NULL);
srand(time.tv_sec);
srand(rand() + time.tv_usec);
}
// Called when c-ares has a DNS response or error for a lookup of
// dns.google.com.
void AresCallback(void *arg, int status, int timeouts,
struct hostent *hostent) {
if (status != ARES_SUCCESS) {
WLOG("DNS lookup failed: %d", status);
}
if (!hostent || hostent->h_length < 1) {
WLOG("No hosts.");
return;
}
char buf[128] = "dns.google.com:443:";
char *p = buf + strlen(buf);
int l = sizeof(buf) - strlen(buf);
ares_inet_ntop(AF_INET, hostent->h_addr_list[0], p, l);
DLOG("Received new IP '%s'", p);
// Update libcurl's resolv cache (we pass these cache injection entries in on
// every request)
curl_slist **p_client_resolv = (curl_slist**)arg;
curl_slist_free_all(*p_client_resolv);
*p_client_resolv = curl_slist_append(NULL, buf);
}
class Request {
public:
Request(uint16_t tx_id, const char *url,
sockaddr_in raddr, curl_slist *resolv) {
curl_ = curl_easy_init();
tx_id_ = tx_id;
buf_ = NULL;
len_ = 0;
raddr_ = raddr;
resolv_ = resolv;
CURLcode res;
if ((res = curl_easy_setopt(curl_, CURLOPT_RESOLVE, resolv_)) != CURLE_OK) {
FLOG("CURLOPT_RESOLV error: %s", curl_easy_strerror(res));
}
curl_easy_setopt(curl_, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_2_0);
curl_easy_setopt(curl_, CURLOPT_URL, url);
curl_easy_setopt(curl_, CURLOPT_WRITEFUNCTION, &WriteBuffer);
curl_easy_setopt(curl_, CURLOPT_WRITEDATA, (void *)this);
curl_easy_setopt(curl_, CURLOPT_TCP_KEEPALIVE, 5L);
curl_easy_setopt(curl_, CURLOPT_USERAGENT, "dns-to-https-proxy/0.1");
DLOG("Req %04x: %s", tx_id_, url);
}
CURL *easy_handle() { return curl_; }
void SendResponse(int listen_sock) {
if (buf_ == NULL) {
DLOG("No response received. Ignoring.");
return;
}
DNSPacket r;
if (!r.ReadJson(tx_id_, buf_)) {
WLOG("Failed to interpret JSON '%s'. Skipping.", buf_);
return;
}
char ret[4096];
int len = 0;
if (!r.WriteDNS(ret, ret + sizeof(ret), &len)) {
DLOG("Failed to write DNS response to buffer. Skipping.");
return;
}
if (len > 0) {
sendto(listen_sock, ret, len, 0, (sockaddr *)&raddr_, sizeof(raddr_));
}
DLOG("Resp %04x", tx_id_);
}
~Request() {
curl_easy_cleanup(curl_);
free(buf_);
}
private:
CURL *curl_;
uint16_t tx_id_;
char *buf_;
size_t len_;
sockaddr_in raddr_;
curl_slist *resolv_;
static size_t WriteBuffer(
void *contents, size_t size, size_t nmemb, void *userp) {
Request *req = (Request *)userp;
char *new_buf = (char *)realloc(req->buf_, req->len_ + size * nmemb + 1);
if(new_buf == NULL) {
ELOG("Out of memory!");
return 0;
}
req->buf_ = new_buf;
memcpy(&(req->buf_[req->len_]), contents, size * nmemb);
req->len_ += size * nmemb;
req->buf_[req->len_] = '\0';
return size * nmemb;
}
};
// Multiplexes three things, forever:
// 1. Listening socket for incoming DNS requests.
// 2. Outgoing sockets for HTTPS requests.
// 3. Outgoing socket for periodic DNS client query for dns.google.com.
void RunSelectLoop(const Options& opt, int listen_sock) {
CURLM *curlm = curl_multi_init();
curl_multi_setopt(curlm, CURLMOPT_PIPELINING, CURLPIPE_MULTIPLEX);
// Avoid C++ map, etc for symbol bloat.
// We don't bother sorting this, so O(n) cost in number of concurrent
// requests. I assume this won't hurt much.
Request* reqs[4096];
int num_reqs = 0;
// DNS client.
ares_channel ares;
if (ares_init(&ares) != ARES_SUCCESS) {
FLOG("Failed to init c-ares channel");
}
if (ares_set_servers_csv(ares, opt.bootstrap_dns) != ARES_SUCCESS) {
FLOG("Failed to set DNS servers to '%s'.", opt.bootstrap_dns);
}
// 60 seconds poll. Rely on c-ares to honor DNS TTL.
const time_t client_req_interval = 60;
time_t last_client_req_time = 0;
curl_slist *client_resolv = NULL;
while (gKeepRunning) {
fd_set rfd, wfd, efd;
int max_fd;
// If we need to, send off a DNS request.
if (last_client_req_time + client_req_interval < time(NULL)) {
DLOG("Sending DNS request for dns.google.com");
last_client_req_time = time(NULL);
ares_gethostbyname(ares, "dns.google.com", AF_INET,
&AresCallback, &client_resolv);
}
// Curl tells us how long select should wait.
long curl_timeo;
timeval timeout;
curl_multi_timeout(curlm, &curl_timeo);
if(curl_timeo < 0) curl_timeo = 1000;
timeout.tv_sec = curl_timeo / 1000;
timeout.tv_usec = (curl_timeo % 1000) * 1000;
FD_ZERO(&rfd); FD_ZERO(&wfd); FD_ZERO(&efd); max_fd = 0;
CURLMcode err;
if ((err = curl_multi_fdset(curlm, &rfd, &wfd, &efd, &max_fd)) != CURLM_OK) {
FLOG("CURL error: %s", curl_multi_strerror(err));
}
FD_SET(listen_sock, &rfd);
max_fd = max_fd > listen_sock ? max_fd : listen_sock;
int ares_max_fd = ares_fds(ares, &rfd, &wfd) - 1;
max_fd = max_fd > ares_max_fd ? max_fd : ares_max_fd;
int r = select(max_fd + 1, &rfd, &wfd, &efd, &timeout);
if (r < 0) continue; // Signal.
if (r == 0) continue; // Timeout.
// DNS request
if (FD_ISSET(listen_sock, &rfd)) {
unsigned char buf[1500]; // A whole MTU. We don't do TCP so any bigger is a waste.
sockaddr_in raddr;
socklen_t raddr_size = sizeof(raddr);
int len = recvfrom(listen_sock, buf, sizeof(buf), 0,
(sockaddr *)&raddr, &raddr_size);
if (len < 0) {
WLOG("recvfrom failed: %s", strerror(errno));
continue;
}
unsigned char *p = buf;
uint16_t tx_id = ntohs(*(uint16_t*)p); p += 2;
uint16_t flags = ntohs(*(uint16_t*)p); p += 2;
uint16_t num_q = ntohs(*(uint16_t*)p); p += 2;
uint16_t num_rr = ntohs(*(uint16_t*)p); p += 2;
uint16_t num_arr = ntohs(*(uint16_t*)p); p += 2;
uint16_t num_xrr = ntohs(*(uint16_t*)p); p += 2;
if (num_q != 1) {
DLOG("Malformed request received.");
continue;
};
char *domain_name;
long enc_len;
if (ares_expand_name(p, buf, len,
&domain_name, &enc_len) != ARES_SUCCESS) {
DLOG("Malformed request received.");
continue;
}
p += enc_len;
uint16_t type = ntohs(*(uint16_t*)p); p += 2;
bool cd_bit = flags & (1 << 4);
char *escaped_name = curl_escape(domain_name, strlen(domain_name));
ares_free_string(domain_name);
char url[1500] = {};
snprintf(url, sizeof(url)-1,
"https://dns.google.com/resolve?name=%s&type=%d%s",
escaped_name, type, cd_bit ? "&cd=true" : "");
curl_free(escaped_name);
Request *req = new Request(tx_id, url, raddr, client_resolv);
reqs[num_reqs++] = req;
curl_multi_add_handle(curlm, req->easy_handle());
}
// DNS response
ares_process(ares, &rfd, &wfd);
// CURL transfers
if (r >= 0) {
int running_https = 0;
if ((err = curl_multi_perform(curlm, &running_https)) != CURLM_OK) {
FLOG("CURL error: %s", curl_multi_strerror(err));
}
CURLMsg *m;
int msgq = 0;
while (m = curl_multi_info_read(curlm, &msgq)) {
if(m->msg == CURLMSG_DONE) {
for (int i = 0; i < num_reqs; i++) {
if (reqs[i]->easy_handle() == m->easy_handle) {
Request *req = reqs[i];
req->SendResponse(listen_sock);
reqs[i] = reqs[--num_reqs];
curl_multi_remove_handle(curlm, m->easy_handle);
delete req;
break;
}
}
}
}
}
}
WLOG("Shutting down.");
// Cancel all pending requests.
for (int i = 0; i < num_reqs; i++) {
curl_multi_remove_handle(curlm, reqs[i]->easy_handle());
delete reqs[i];
}
curl_multi_cleanup(curlm);
ares_destroy(ares);
curl_slist_free_all(client_resolv);
close(listen_sock);
}
} // namespace
int main(int argc, char *argv[]) {
prng_init();
struct Options opt;
options_init(&opt);
if (options_parse_args(&opt, argc, argv)) {
options_show_usage(argc, argv);
exit(1);
}
logging_init(opt.logfd, opt.loglevel);
ares_library_init(ARES_LIB_INIT_ALL);
curl_global_init(CURL_GLOBAL_DEFAULT);
sockaddr_in laddr, raddr;
memset(&laddr, 0, sizeof(laddr));
laddr.sin_family = AF_INET;
laddr.sin_port = htons(opt.listen_port);
laddr.sin_addr.s_addr = inet_addr(opt.listen_addr);
int sock = socket(AF_INET, SOCK_DGRAM, 0);
if (sock < 0) {
FLOG("Error creating socket");
}
if(bind(sock, (struct sockaddr*)&laddr, sizeof(laddr)) < 0) {
FLOG("Error binding %s:%d", opt.listen_addr, opt.listen_port);
}
ILOG("Listening on %s:%d", opt.listen_addr, opt.listen_port);
if (opt.daemonize) {
if (setgid(opt.gid)) FLOG("Failed to set gid.");
if (setuid(opt.uid)) FLOG("Failed to set uid.");
// Note: This is non-standard. If needed, see OpenSSH openbsd-compat/daemon.c
daemon(0, 0);
}
if (signal(SIGINT, SigHandler) == SIG_ERR) {
FLOG("Can't set signal handler.");
}
RunSelectLoop(opt, sock);
curl_global_cleanup();
ares_library_cleanup();
logging_cleanup();
options_cleanup(&opt);
return 0;
}
<|endoftext|> |
<commit_before>
/*
* MIT License
*
* Copyright (c) 2017 Susanow
* Copyright (c) 2017 Hiroki SHIROKURA
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
#include <stdio.h>
#include <stdint.h>
#include <stddef.h>
#include <thread>
#include <ssn_nfvi.h>
#include <ssn_vnf_l2fwd1b.h>
#include <ssn_vnf_l2fwd2b.h>
#include <ssn_rest_api.h>
void user_operation_mock(ssn_nfvi* nfvi) try
{
#if 0
rte_mempool* mp = nfvi->get_mp();
nfvi->vnf_alloc_from_catalog("l2fwd1b", "vnf0");
nfvi->vnf_alloc_from_catalog("l2fwd1b", "vnf1");
nfvi->vnf_alloc_from_catalog("l2fwd2b", "l2fwd2b-vnf");
ssn_portalloc_tap_arg tap0arg = { mp, "tap0" };
nfvi->port_alloc_from_catalog("tap", "tap0", &tap0arg);
nfvi->find_port("tap0")->config_hw(4, 4);
ssn_portalloc_tap_arg tap1arg = { mp, "tap1" };
nfvi->port_alloc_from_catalog("tap", "tap1", &tap1arg);
nfvi->find_port("tap1")->config_hw(4, 4);
ssn_portalloc_virt_arg virt0arg = {};
nfvi->port_alloc_from_catalog("virt", "virt0", &virt0arg);
nfvi->find_port("virt0")->config_hw(4, 4);
ssn_portalloc_virt_arg virt1arg = {};
nfvi->port_alloc_from_catalog("virt", "virt1", &virt1arg);
nfvi->find_port("virt1")->config_hw(4, 4);
// ssn_portalloc_pci_arg pci0arg = { mp, "0000:01:00.0" };
// nfvi->port_alloc_from_catalog("pci", "pci0", &pci0arg);
// nfvi->find_port("pci0")->config_hw(4, 4);
//
// ssn_portalloc_pci_arg pci1arg = { mp, "0000:01:00.1" };
// nfvi->port_alloc_from_catalog("pci", "pci1", &pci1arg);
// nfvi->find_port("pci1")->config_hw(4, 4);
/* vnf0 */
{
auto* vnf = nfvi->find_vnf("vnf0");
auto* port0 = nfvi->find_port("tap0");
auto* port1 = nfvi->find_port("tap1");
vnf->attach_port(0, port0);
vnf->attach_port(1, port1);
vnf->set_coremask(0, 0b00000100);
vnf->deploy();
}
/* l2fwd2b-vnf */
{
// auto* vnf = nfvi->find_vnf("l2fwd2b-vnf");
// auto* port0 = nfvi->find_port("pci0");
// auto* port1 = nfvi->find_port("pci1");
// vnf->attach_port(0, port0);
// vnf->attach_port(1, port1);
// vnf->set_coremask(0, 0b00010000);
// vnf->set_coremask(1, 0b00100000);
}
#endif
} catch (std::exception& e) { printf("throwed: %s \n", e.what()); }
void contoll(ssn_nfvi* nfvi)
{
while (true) {
printf("ssn> ");
fflush(stdout);
std::string line;
std::getline(std::cin, line);
if (line == "quit") break;
else if (line == "dump") nfvi->debug_dump(stdout);
}
nfvi->stop();
}
int main(int argc, char** argv)
{
ssn_nfvi nfvi(argc, argv);
nfvi.vnf_register_to_catalog("l2fwd1b", ssn_vnfalloc_l2fwd1b);
nfvi.vnf_register_to_catalog("l2fwd2b", ssn_vnfalloc_l2fwd2b);
nfvi.port_register_to_catalog("pci" , ssn_portalloc_pci );
nfvi.port_register_to_catalog("tap" , ssn_portalloc_tap );
nfvi.port_register_to_catalog("virt", ssn_portalloc_virt);
user_operation_mock(&nfvi);
std::thread tt(contoll, &nfvi);
nfvi.run(8888);
tt.join();
printf("bye...\n");
}
<commit_msg>userop: update<commit_after>
/*
* MIT License
*
* Copyright (c) 2017 Susanow
* Copyright (c) 2017 Hiroki SHIROKURA
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
#include <stdio.h>
#include <stdint.h>
#include <stddef.h>
#include <thread>
#include <ssn_nfvi.h>
#include <ssn_vnf_l2fwd1b.h>
#include <ssn_vnf_l2fwd2b.h>
#include <ssn_rest_api.h>
void user_operation_mock(ssn_nfvi* nfvi) try
{
rte_mempool* mp = nfvi->get_mp();
nfvi->vnf_alloc_from_catalog("l2fwd1b", "vnf0");
nfvi->vnf_alloc_from_catalog("l2fwd1b", "vnf1");
ssn_portalloc_tap_arg tap0arg = { mp, "tap0" };
nfvi->port_alloc_from_catalog("tap", "tap0", &tap0arg);
nfvi->find_port("tap0")->config_hw(4, 4);
ssn_portalloc_tap_arg tap1arg = { mp, "tap1" };
nfvi->port_alloc_from_catalog("tap", "tap1", &tap1arg);
nfvi->find_port("tap1")->config_hw(4, 4);
ssn_portalloc_virt_arg virt0arg = {};
nfvi->port_alloc_from_catalog("virt", "virt0", &virt0arg);
nfvi->find_port("virt0")->config_hw(4, 4);
ssn_portalloc_virt_arg virt1arg = {};
nfvi->port_alloc_from_catalog("virt", "virt1", &virt1arg);
nfvi->find_port("virt1")->config_hw(4, 4);
#if 0
rte_mempool* mp = nfvi->get_mp();
nfvi->vnf_alloc_from_catalog("l2fwd2b", "l2fwd2b-vnf");
ssn_portalloc_tap_arg tap0arg = { mp, "tap0" };
nfvi->port_alloc_from_catalog("tap", "tap0", &tap0arg);
nfvi->find_port("tap0")->config_hw(4, 4);
ssn_portalloc_tap_arg tap1arg = { mp, "tap1" };
nfvi->port_alloc_from_catalog("tap", "tap1", &tap1arg);
nfvi->find_port("tap1")->config_hw(4, 4);
ssn_portalloc_virt_arg virt0arg = {};
nfvi->port_alloc_from_catalog("virt", "virt0", &virt0arg);
nfvi->find_port("virt0")->config_hw(4, 4);
ssn_portalloc_virt_arg virt1arg = {};
nfvi->port_alloc_from_catalog("virt", "virt1", &virt1arg);
nfvi->find_port("virt1")->config_hw(4, 4);
// ssn_portalloc_pci_arg pci0arg = { mp, "0000:01:00.0" };
// nfvi->port_alloc_from_catalog("pci", "pci0", &pci0arg);
// nfvi->find_port("pci0")->config_hw(4, 4);
//
// ssn_portalloc_pci_arg pci1arg = { mp, "0000:01:00.1" };
// nfvi->port_alloc_from_catalog("pci", "pci1", &pci1arg);
// nfvi->find_port("pci1")->config_hw(4, 4);
/* vnf0 */
{
auto* vnf = nfvi->find_vnf("vnf0");
auto* port0 = nfvi->find_port("tap0");
auto* port1 = nfvi->find_port("tap1");
vnf->attach_port(0, port0);
vnf->attach_port(1, port1);
vnf->set_coremask(0, 0b00000100);
vnf->deploy();
}
/* l2fwd2b-vnf */
{
// auto* vnf = nfvi->find_vnf("l2fwd2b-vnf");
// auto* port0 = nfvi->find_port("pci0");
// auto* port1 = nfvi->find_port("pci1");
// vnf->attach_port(0, port0);
// vnf->attach_port(1, port1);
// vnf->set_coremask(0, 0b00010000);
// vnf->set_coremask(1, 0b00100000);
}
#endif
} catch (std::exception& e) { printf("throwed: %s \n", e.what()); }
void contoll(ssn_nfvi* nfvi)
{
while (true) {
printf("ssn> ");
fflush(stdout);
std::string line;
std::getline(std::cin, line);
if (line == "quit") break;
else if (line == "dump") nfvi->debug_dump(stdout);
}
nfvi->stop();
}
int main(int argc, char** argv)
{
ssn_nfvi nfvi(argc, argv);
nfvi.vnf_register_to_catalog("l2fwd1b", ssn_vnfalloc_l2fwd1b);
nfvi.vnf_register_to_catalog("l2fwd2b", ssn_vnfalloc_l2fwd2b);
nfvi.port_register_to_catalog("pci" , ssn_portalloc_pci );
nfvi.port_register_to_catalog("tap" , ssn_portalloc_tap );
nfvi.port_register_to_catalog("virt", ssn_portalloc_virt);
user_operation_mock(&nfvi);
std::thread tt(contoll, &nfvi);
nfvi.run(8888);
tt.join();
printf("bye...\n");
}
<|endoftext|> |
<commit_before>#include <getopt.h>
#include <iostream>
#include <fstream>
#include "error_handling.h"
#include "game.h"
#include "command.h"
#include "io.h"
#include "score.h"
#include "misc.h"
#include "level_rooms.h"
#include "player.h"
#include "options.h"
#include "os.h"
#include "move.h"
#include "rogue.h"
#include "wizard.h"
using namespace std;
// Parse command-line arguments
static void
parse_args(int argc, char* const* argv, bool& restore, string& save_path, string& whoami)
{
string const game_version = "Misty Mountains v2.0-alpha2 - Based on Rogue5.4.4";
int option_index = 0;
struct option const long_options[] = {
{"no-colors", no_argument, 0, 'c'},
{"escdelay", optional_argument, 0, 'E'},
{"flush", no_argument, 0, 'f'},
{"hide-floor",no_argument, 0, 'F'},
{"no-jump", no_argument, 0, 'j'},
{"name", required_argument, 0, 'n'},
{"passgo", no_argument, 0, 'p'},
{"restore", optional_argument, 0, 'r'},
{"score", no_argument, 0, 's'},
{"seed", required_argument, 0, 'S'},
{"wizard", no_argument, 0, 'W'},
{"help", no_argument, 0, '0'},
{"dicerolls", no_argument, 0, 1 },
{"version", no_argument, 0, '1'},
{0, 0, 0, 0 }
};
// Global default options
ESCDELAY = 0;
// Set seed and dungeon number
os_rand_seed = static_cast<unsigned>(time(nullptr) + getpid());
for (;;)
{
int c = getopt_long(argc, argv, "cE::fjn:pr::sS:W",
long_options, &option_index);
if (c == -1)
break;
switch (c)
{
case 'c': use_colors = false; break;
case 'E': ESCDELAY = optarg == nullptr ? 64 : atoi(optarg); break;
case 'f': fight_flush = true; break;
case 'j': jump = false; break;
case 'n': if (optarg != nullptr) {
whoami = optarg;
} break;
case 'p': passgo = true; break;
case 'r': {
restore = true;
if (optarg != nullptr) {
save_path = optarg;
}
} break;
case 's': score_show_and_exit(0, -1, 0); // does not return
case 'W': wizard = true; break;
case 'S': if (wizard && optarg != nullptr) {
os_rand_seed = static_cast<unsigned>(stoul(optarg));
} break;
case 1: if (wizard) {
wizard_dicerolls = true;
} break;
case '0':
cout << "Usage: " << argv[0] << " [OPTIONS] [FILE]\n"
<< "Run Rogue14 with selected options or a savefile\n\n"
<< " -c, --no-colors remove colors from the game\n"
<< " -E, --escdelay=[NUM] set escdelay in ms. Not setting this\n"
<< " defaults to 0. If you do not give a NUM\n"
<< " argument, it's set to 64 (old standard)\n"
<< " -f, --flush flush typeahead during battle\n"
<< " -j, --no-jump draw each player step separately\n"
<< " -n, --name=NAME set highscore name\n"
<< " -p, --passgo follow the turnings in passageways\n"
<< " -r, --restore restore game instead of creating a new\n"
<< " -s, --score display the highscore and exit\n"
<< " -W, --wizard run the game in debug-mode\n"
<< " --dicerolls (wizard) show all dice rolls\n"
<< " -S, --seed=NUMBER (wizard) set map seed to NUMBER\n"
<< " --help display this help and exit\n"
<< " --version display game version and exit\n\n"
<< game_version
<< endl;
exit(0);
case '1':
cout << game_version << endl;
exit(0);
default:
cerr << "Try '" << argv[0] << " --help' for more information\n";
exit(1);
}
}
if (optind < argc)
{
cerr << "Try '" << argv[0] << " --help' for more information\n";
exit(1);
}
}
/** main:
* The main program, of course */
int
main(int argc, char** argv)
{
/* Open scoreboard, so we can modify the score later */
score_open();
bool restore = false;
string save_path;
string whoami;
/* Parse args and then init new (or old) game */
parse_args(argc, argv, restore, save_path, whoami);
if (whoami.empty()) {
whoami = os_whoami();
}
if (save_path.empty()) {
save_path = os_homedir() + ".misty_mountain.save";
}
Game* game = nullptr;
if (restore) {
ifstream savefile(save_path);
if (!savefile) {
cerr << save_path + ": " + strerror(errno) + "\n";
return 1;
}
game = new Game(savefile);
savefile.close();
remove(save_path.c_str());
} else {
game = new Game(whoami, save_path);
}
if (game != nullptr) {
return game->run();
}
return 0;
}
<commit_msg>change to dev version<commit_after>#include <getopt.h>
#include <iostream>
#include <fstream>
#include "error_handling.h"
#include "game.h"
#include "command.h"
#include "io.h"
#include "score.h"
#include "misc.h"
#include "level_rooms.h"
#include "player.h"
#include "options.h"
#include "os.h"
#include "move.h"
#include "rogue.h"
#include "wizard.h"
using namespace std;
// Parse command-line arguments
static void
parse_args(int argc, char* const* argv, bool& restore, string& save_path, string& whoami)
{
string const game_version = "Misty Mountains v2.0-alpha2-dev - Based on Rogue5.4.4";
int option_index = 0;
struct option const long_options[] = {
{"no-colors", no_argument, 0, 'c'},
{"escdelay", optional_argument, 0, 'E'},
{"flush", no_argument, 0, 'f'},
{"hide-floor",no_argument, 0, 'F'},
{"no-jump", no_argument, 0, 'j'},
{"name", required_argument, 0, 'n'},
{"passgo", no_argument, 0, 'p'},
{"restore", optional_argument, 0, 'r'},
{"score", no_argument, 0, 's'},
{"seed", required_argument, 0, 'S'},
{"wizard", no_argument, 0, 'W'},
{"help", no_argument, 0, '0'},
{"dicerolls", no_argument, 0, 1 },
{"version", no_argument, 0, '1'},
{0, 0, 0, 0 }
};
// Global default options
ESCDELAY = 0;
// Set seed and dungeon number
os_rand_seed = static_cast<unsigned>(time(nullptr) + getpid());
for (;;)
{
int c = getopt_long(argc, argv, "cE::fjn:pr::sS:W",
long_options, &option_index);
if (c == -1)
break;
switch (c)
{
case 'c': use_colors = false; break;
case 'E': ESCDELAY = optarg == nullptr ? 64 : atoi(optarg); break;
case 'f': fight_flush = true; break;
case 'j': jump = false; break;
case 'n': if (optarg != nullptr) {
whoami = optarg;
} break;
case 'p': passgo = true; break;
case 'r': {
restore = true;
if (optarg != nullptr) {
save_path = optarg;
}
} break;
case 's': score_show_and_exit(0, -1, 0); // does not return
case 'W': wizard = true; break;
case 'S': if (wizard && optarg != nullptr) {
os_rand_seed = static_cast<unsigned>(stoul(optarg));
} break;
case 1: if (wizard) {
wizard_dicerolls = true;
} break;
case '0':
cout << "Usage: " << argv[0] << " [OPTIONS] [FILE]\n"
<< "Run Rogue14 with selected options or a savefile\n\n"
<< " -c, --no-colors remove colors from the game\n"
<< " -E, --escdelay=[NUM] set escdelay in ms. Not setting this\n"
<< " defaults to 0. If you do not give a NUM\n"
<< " argument, it's set to 64 (old standard)\n"
<< " -f, --flush flush typeahead during battle\n"
<< " -j, --no-jump draw each player step separately\n"
<< " -n, --name=NAME set highscore name\n"
<< " -p, --passgo follow the turnings in passageways\n"
<< " -r, --restore restore game instead of creating a new\n"
<< " -s, --score display the highscore and exit\n"
<< " -W, --wizard run the game in debug-mode\n"
<< " --dicerolls (wizard) show all dice rolls\n"
<< " -S, --seed=NUMBER (wizard) set map seed to NUMBER\n"
<< " --help display this help and exit\n"
<< " --version display game version and exit\n\n"
<< game_version
<< endl;
exit(0);
case '1':
cout << game_version << endl;
exit(0);
default:
cerr << "Try '" << argv[0] << " --help' for more information\n";
exit(1);
}
}
if (optind < argc)
{
cerr << "Try '" << argv[0] << " --help' for more information\n";
exit(1);
}
}
/** main:
* The main program, of course */
int
main(int argc, char** argv)
{
/* Open scoreboard, so we can modify the score later */
score_open();
bool restore = false;
string save_path;
string whoami;
/* Parse args and then init new (or old) game */
parse_args(argc, argv, restore, save_path, whoami);
if (whoami.empty()) {
whoami = os_whoami();
}
if (save_path.empty()) {
save_path = os_homedir() + ".misty_mountain.save";
}
Game* game = nullptr;
if (restore) {
ifstream savefile(save_path);
if (!savefile) {
cerr << save_path + ": " + strerror(errno) + "\n";
return 1;
}
game = new Game(savefile);
savefile.close();
remove(save_path.c_str());
} else {
game = new Game(whoami, save_path);
}
if (game != nullptr) {
return game->run();
}
return 0;
}
<|endoftext|> |
<commit_before>// main.cc for Fluxbox Window manager
// Copyright (c) 2001 - 2003 Henrik Kinnunen (fluxgen at users.sourceforge.net)
// and 2003 Simon Bowden (rathnor at users.sourceforge.net)
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the "Software"),
// to deal in the Software without restriction, including without limitation
// the rights to use, copy, modify, merge, publish, distribute, sublicense,
// and/or sell copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
// THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
// $Id: main.cc,v 1.25 2003/12/09 08:48:08 rathnor Exp $
#include "fluxbox.hh"
#include "I18n.hh"
#include "version.h"
#include "defaults.hh"
#include "FbTk/Theme.hh"
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif // HAVE_CONFIG_H
//use GNU extensions
#ifndef _GNU_SOURCE
#define _GNU_SOURCE
#endif // _GNU_SOURCE
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <iostream>
#include <fstream>
#include <stdexcept>
#include <typeinfo>
using namespace std;
void showInfo(ostream &ostr) {
ostr<<"Fluxbox version: "<<__fluxbox_version<<endl;
ostr<<"Compiled: "<<__DATE__<<" "<<__TIME__<<endl;
ostr<<"Compiler: ";
#ifdef __GNUG__
ostr<<"GCC";
#else
ostr<<"Unknown";
#endif
ostr<<endl<<"Compiler version: "<<__VERSION__<<endl;
ostr<<endl<<"Defaults:"<<endl;
ostr<<" menu: "<<DEFAULTMENU<<endl;
ostr<<" style: "<<DEFAULTSTYLE<<endl;
ostr<<" keys: "<<DEFAULTKEYSFILE<<endl;
ostr<<" init: "<<DEFAULT_INITFILE<<endl;
const char NOT[] = "-";
ostr<<endl<<"Compiled options ("<<NOT<<" => disabled): "<<endl<<
#ifndef DEBUG
NOT<<
#endif // DEBUG
"DEBUG"<<endl<<
#ifndef SLIT
NOT<<
#endif // SLIT
"SLIT"<<endl<<
#ifndef USE_TOOLBAR
NOT<<
#endif // USE_TOOLBAR
"TOOLBAR"<<endl<<
#ifndef HAVE_XPM
NOT<<
#endif // HAVE_XPM
"XPM"<<endl<<
#ifndef USE_GNOME
NOT<<
#endif // USE_GNOME
"GNOME"<<endl<<
#ifndef KDE
NOT<<
#endif // KDE
"KDE"<<endl<<
#ifndef USE_NEWWMSPEC
NOT<<
#endif // USE_NEWWMSPEC
"EWMH"<<endl<<
#ifndef REMEMBER
NOT<<
#endif // REMEMBER
"REMEMBER"<<endl<<
#ifndef SHAPE
NOT<<
#endif // SHAPE
"SHAPE"<<endl<<
#ifndef USE_XFT
NOT<<
#endif // USE_XFT
"XFT"<<endl<<
#ifndef USE_XMB
NOT<<
#endif // USE_XMB
"XMB"<<endl<<
#ifndef XINERAMA
NOT<<
#endif // XINERAMA
"XINERAMA"<<endl<<
#ifndef HAVE_XRENDER
NOT<<
#endif // HAVE_XRENDER
"RENDER"<<endl<<
endl;
}
int main(int argc, char **argv) {
std::string session_display = "";
std::string rc_file;
std::string log_filename;
NLSInit("fluxbox.cat");
I18n &i18n = *I18n::instance();
int i;
for (i = 1; i < argc; ++i) {
if (! strcmp(argv[i], "-rc")) {
// look for alternative rc file to use
if ((++i) >= argc) {
fprintf(stderr,
i18n.getMessage(FBNLS::mainSet, FBNLS::mainRCRequiresArg,
"error: '-rc' requires and argument\n"));
exit(1);
}
rc_file = argv[i];
} else if (! strcmp(argv[i], "-display")) {
// check for -display option... to run on a display other than the one
// set by the environment variable DISPLAY
if ((++i) >= argc) {
fprintf(stderr,
i18n.getMessage(FBNLS::mainSet, FBNLS::mainDISPLAYRequiresArg,
"error: '-display' requires an argument\n"));
exit(1);
}
session_display = argv[i];
std::string display_env = "DISPLAY=" + session_display;
if (putenv(const_cast<char *>(display_env.c_str()))) {
fprintf(stderr,
i18n.
getMessage(FBNLS::mainSet, FBNLS::mainWarnDisplaySet,
"warning: couldn't set environment variable 'DISPLAY'\n"));
perror("putenv()");
}
} else if (strcmp(argv[i], "-version") == 0 || strcmp(argv[i], "-v") == 0) {
// print current version string
cout<<"Fluxbox "<<__fluxbox_version<<" : (c) 2001-2003 Henrik Kinnunen "<<endl<<endl;
exit(0);
} else if (strcmp(argv[i], "-log") == 0 ) {
if (i + 1 >= argc) {
cerr<<"error: '-log' needs an argument"<<endl;
exit(1);
}
log_filename = argv[++i];
} else if (strcmp(argv[i], "-help") == 0 || strcmp(argv[i], "-h") == 0) {
// print program usage and command line options
printf(i18n.
getMessage(FBNLS::mainSet, FBNLS::mainUsage,
"Fluxbox %s : (c) %s Henrik Kinnunen\n"
"Website: http://www.fluxbox.org/ \n\n"
" -display <string>\t\tuse display connection.\n"
" -rc <string>\t\t\tuse alternate resource file.\n"
" -version\t\t\tdisplay version and exit.\n"
" -info\t\t\t\tdisplay some useful information.\n"
"\t-log <filename>\t\t\tlog output to file.\n"
" -help\t\t\t\tdisplay this help text and exit.\n\n"),
__fluxbox_version, "2001-2003");
exit(0);
} else if (strcmp(argv[i], "-info") == 0 || strcmp(argv[i], "-i") == 0) {
showInfo(cout);
exit(0);
} else if (strcmp(argv[i], "-verbose") == 0) {
FbTk::ThemeManager::instance().setVerbose(true);
}
}
#ifdef __EMX__
_chdir2(getenv("X11ROOT"));
#endif // __EMX__
std::auto_ptr<Fluxbox> fluxbox;
int exitcode=EXIT_FAILURE;
streambuf *outbuf = 0;
streambuf *errbuf = 0;
ofstream log_file(log_filename.c_str());
// setup log file
if (log_file) {
cerr<<"Loggin to: "<<log_filename<<endl;
log_file<<"------------------------------------------"<<endl;
log_file<<"Logfile: "<<log_filename<<endl;
showInfo(log_file);
log_file<<"------------------------------------------"<<endl;
// setup log to use cout and cerr stream
outbuf = cout.rdbuf(log_file.rdbuf());
errbuf = cerr.rdbuf(log_file.rdbuf());
}
try {
fluxbox.reset(new Fluxbox(argc, argv, session_display.c_str(), rc_file.c_str()));
fluxbox->eventLoop();
exitcode = EXIT_SUCCESS;
} catch (std::out_of_range &oor) {
cerr<<"Fluxbox: Out of range: "<<oor.what()<<endl;
} catch (std::runtime_error &re) {
cerr<<"Fluxbox: Runtime error: "<<re.what()<<endl;
} catch (std::bad_cast &bc) {
cerr<<"Fluxbox: Bad cast: "<<bc.what()<<endl;
} catch (std::bad_alloc &ba) {
cerr<<"Fluxbox: Bad Alloc: "<<ba.what()<<endl;
} catch (std::exception &e) {
cerr<<"Fluxbox: Standard exception: "<<e.what()<<endl;
} catch (std::string error_str) {
cerr<<"Error: "<<error_str<<endl;
} catch (...) {
cerr<<"Fluxbox: Unknown error."<<endl;
abort();
}
// restore cout and cin streams
if (outbuf != 0)
cout.rdbuf(outbuf);
if (errbuf != 0)
cerr.rdbuf(errbuf);
return exitcode;
}
<commit_msg>destroy fluxbox<commit_after>// main.cc for Fluxbox Window manager
// Copyright (c) 2001 - 2003 Henrik Kinnunen (fluxgen at users.sourceforge.net)
// and 2003 Simon Bowden (rathnor at users.sourceforge.net)
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the "Software"),
// to deal in the Software without restriction, including without limitation
// the rights to use, copy, modify, merge, publish, distribute, sublicense,
// and/or sell copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
// THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
// $Id: main.cc,v 1.26 2004/01/11 13:12:02 fluxgen Exp $
#include "fluxbox.hh"
#include "I18n.hh"
#include "version.h"
#include "defaults.hh"
#include "FbTk/Theme.hh"
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif // HAVE_CONFIG_H
//use GNU extensions
#ifndef _GNU_SOURCE
#define _GNU_SOURCE
#endif // _GNU_SOURCE
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <iostream>
#include <fstream>
#include <stdexcept>
#include <typeinfo>
using namespace std;
void showInfo(ostream &ostr) {
ostr<<"Fluxbox version: "<<__fluxbox_version<<endl;
ostr<<"Compiled: "<<__DATE__<<" "<<__TIME__<<endl;
ostr<<"Compiler: ";
#ifdef __GNUG__
ostr<<"GCC";
#else
ostr<<"Unknown";
#endif
ostr<<endl<<"Compiler version: "<<__VERSION__<<endl;
ostr<<endl<<"Defaults:"<<endl;
ostr<<" menu: "<<DEFAULTMENU<<endl;
ostr<<" style: "<<DEFAULTSTYLE<<endl;
ostr<<" keys: "<<DEFAULTKEYSFILE<<endl;
ostr<<" init: "<<DEFAULT_INITFILE<<endl;
const char NOT[] = "-";
ostr<<endl<<"Compiled options ("<<NOT<<" => disabled): "<<endl<<
#ifndef DEBUG
NOT<<
#endif // DEBUG
"DEBUG"<<endl<<
#ifndef SLIT
NOT<<
#endif // SLIT
"SLIT"<<endl<<
#ifndef USE_TOOLBAR
NOT<<
#endif // USE_TOOLBAR
"TOOLBAR"<<endl<<
#ifndef HAVE_XPM
NOT<<
#endif // HAVE_XPM
"XPM"<<endl<<
#ifndef USE_GNOME
NOT<<
#endif // USE_GNOME
"GNOME"<<endl<<
#ifndef KDE
NOT<<
#endif // KDE
"KDE"<<endl<<
#ifndef USE_NEWWMSPEC
NOT<<
#endif // USE_NEWWMSPEC
"EWMH"<<endl<<
#ifndef REMEMBER
NOT<<
#endif // REMEMBER
"REMEMBER"<<endl<<
#ifndef SHAPE
NOT<<
#endif // SHAPE
"SHAPE"<<endl<<
#ifndef USE_XFT
NOT<<
#endif // USE_XFT
"XFT"<<endl<<
#ifndef USE_XMB
NOT<<
#endif // USE_XMB
"XMB"<<endl<<
#ifndef XINERAMA
NOT<<
#endif // XINERAMA
"XINERAMA"<<endl<<
#ifndef HAVE_XRENDER
NOT<<
#endif // HAVE_XRENDER
"RENDER"<<endl<<
endl;
}
int main(int argc, char **argv) {
std::string session_display = "";
std::string rc_file;
std::string log_filename;
NLSInit("fluxbox.cat");
I18n &i18n = *I18n::instance();
int i;
for (i = 1; i < argc; ++i) {
if (! strcmp(argv[i], "-rc")) {
// look for alternative rc file to use
if ((++i) >= argc) {
fprintf(stderr,
i18n.getMessage(FBNLS::mainSet, FBNLS::mainRCRequiresArg,
"error: '-rc' requires and argument\n"));
exit(1);
}
rc_file = argv[i];
} else if (! strcmp(argv[i], "-display")) {
// check for -display option... to run on a display other than the one
// set by the environment variable DISPLAY
if ((++i) >= argc) {
fprintf(stderr,
i18n.getMessage(FBNLS::mainSet, FBNLS::mainDISPLAYRequiresArg,
"error: '-display' requires an argument\n"));
exit(1);
}
session_display = argv[i];
std::string display_env = "DISPLAY=" + session_display;
if (putenv(const_cast<char *>(display_env.c_str()))) {
fprintf(stderr,
i18n.
getMessage(FBNLS::mainSet, FBNLS::mainWarnDisplaySet,
"warning: couldn't set environment variable 'DISPLAY'\n"));
perror("putenv()");
}
} else if (strcmp(argv[i], "-version") == 0 || strcmp(argv[i], "-v") == 0) {
// print current version string
cout<<"Fluxbox "<<__fluxbox_version<<" : (c) 2001-2003 Henrik Kinnunen "<<endl<<endl;
exit(0);
} else if (strcmp(argv[i], "-log") == 0 ) {
if (i + 1 >= argc) {
cerr<<"error: '-log' needs an argument"<<endl;
exit(1);
}
log_filename = argv[++i];
} else if (strcmp(argv[i], "-help") == 0 || strcmp(argv[i], "-h") == 0) {
// print program usage and command line options
printf(i18n.
getMessage(FBNLS::mainSet, FBNLS::mainUsage,
"Fluxbox %s : (c) %s Henrik Kinnunen\n"
"Website: http://www.fluxbox.org/ \n\n"
" -display <string>\t\tuse display connection.\n"
" -rc <string>\t\t\tuse alternate resource file.\n"
" -version\t\t\tdisplay version and exit.\n"
" -info\t\t\t\tdisplay some useful information.\n"
"\t-log <filename>\t\t\tlog output to file.\n"
" -help\t\t\t\tdisplay this help text and exit.\n\n"),
__fluxbox_version, "2001-2003");
exit(0);
} else if (strcmp(argv[i], "-info") == 0 || strcmp(argv[i], "-i") == 0) {
showInfo(cout);
exit(0);
} else if (strcmp(argv[i], "-verbose") == 0) {
FbTk::ThemeManager::instance().setVerbose(true);
}
}
#ifdef __EMX__
_chdir2(getenv("X11ROOT"));
#endif // __EMX__
std::auto_ptr<Fluxbox> fluxbox;
int exitcode=EXIT_FAILURE;
streambuf *outbuf = 0;
streambuf *errbuf = 0;
ofstream log_file(log_filename.c_str());
// setup log file
if (log_file) {
cerr<<"Loggin to: "<<log_filename<<endl;
log_file<<"------------------------------------------"<<endl;
log_file<<"Logfile: "<<log_filename<<endl;
showInfo(log_file);
log_file<<"------------------------------------------"<<endl;
// setup log to use cout and cerr stream
outbuf = cout.rdbuf(log_file.rdbuf());
errbuf = cerr.rdbuf(log_file.rdbuf());
}
try {
fluxbox.reset(new Fluxbox(argc, argv, session_display.c_str(), rc_file.c_str()));
fluxbox->eventLoop();
exitcode = EXIT_SUCCESS;
} catch (std::out_of_range &oor) {
cerr<<"Fluxbox: Out of range: "<<oor.what()<<endl;
} catch (std::runtime_error &re) {
cerr<<"Fluxbox: Runtime error: "<<re.what()<<endl;
} catch (std::bad_cast &bc) {
cerr<<"Fluxbox: Bad cast: "<<bc.what()<<endl;
} catch (std::bad_alloc &ba) {
cerr<<"Fluxbox: Bad Alloc: "<<ba.what()<<endl;
} catch (std::exception &e) {
cerr<<"Fluxbox: Standard exception: "<<e.what()<<endl;
} catch (std::string error_str) {
cerr<<"Error: "<<error_str<<endl;
} catch (...) {
cerr<<"Fluxbox: Unknown error."<<endl;
abort();
}
// destroy fluxbox
fluxbox.reset(0);
// restore cout and cin streams
if (outbuf != 0)
cout.rdbuf(outbuf);
if (errbuf != 0)
cerr.rdbuf(errbuf);
return exitcode;
}
<|endoftext|> |
<commit_before>/*****************************************************************************
*
* This file is part of Mapnik (c++ mapping toolkit)
*
* Copyright (C) 2006 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
*
*****************************************************************************/
//$Id: map.cpp 17 2005-03-08 23:58:43Z pavlenko $,
#include <mapnik/style.hpp>
#include <mapnik/datasource.hpp>
#include <mapnik/layer.hpp>
#include <mapnik/map.hpp>
namespace mapnik
{
Map::Map()
: width_(400),
height_(400),
srid_(-1) {}
Map::Map(int width,int height,int srid)
: width_(width),
height_(height),
srid_(srid),
background_(Color(255,255,255)) {}
Map::Map(const Map& rhs)
: width_(rhs.width_),
height_(rhs.height_),
srid_(rhs.srid_),
background_(rhs.background_),
styles_(rhs.styles_),
layers_(rhs.layers_),
currentExtent_(rhs.currentExtent_) {}
Map& Map::operator=(const Map& rhs)
{
if (this==&rhs) return *this;
width_=rhs.width_;
height_=rhs.height_;
srid_=rhs.srid_;
background_=rhs.background_;
styles_=rhs.styles_;
layers_=rhs.layers_;
return *this;
}
Map::style_iterator Map::begin_styles() const
{
return styles_.begin();
}
Map::style_iterator Map::end_styles() const
{
return styles_.end();
}
bool Map::insert_style(std::string const& name,feature_type_style const& style)
{
return styles_.insert(make_pair(name,style)).second;
}
void Map::remove_style(std::string const& name)
{
styles_.erase(name);
}
feature_type_style const& Map::find_style(std::string const& name) const
{
std::map<std::string,feature_type_style>::const_iterator itr=styles_.find(name);
if (itr!=styles_.end())
return itr->second;
static feature_type_style default_style;
return default_style;
}
size_t Map::layerCount() const
{
return layers_.size();
}
void Map::addLayer(const Layer& l)
{
layers_.push_back(l);
}
void Map::removeLayer(size_t index)
{
layers_.erase(layers_.begin()+index);
}
const Layer& Map::getLayer(size_t index) const
{
return layers_[index];
}
Layer& Map::getLayer(size_t index)
{
return layers_[index];
}
std::vector<Layer> const& Map::layers() const
{
return layers_;
}
unsigned Map::getWidth() const
{
return width_;
}
unsigned Map::getHeight() const
{
return height_;
}
void Map::setWidth(unsigned width)
{
if (width >= MIN_MAPSIZE && width <= MAX_MAPSIZE)
{
width_=width;
fixAspectRatio();
}
}
void Map::setHeight(unsigned height)
{
if (height >= MIN_MAPSIZE && height <= MAX_MAPSIZE)
{
height_=height;
fixAspectRatio();
}
}
void Map::resize(unsigned width,unsigned height)
{
if (width >= MIN_MAPSIZE && width <= MAX_MAPSIZE &&
height >= MIN_MAPSIZE && height <= MAX_MAPSIZE)
{
width_=width;
height_=height;
fixAspectRatio();
}
}
int Map::srid() const
{
return srid_;
}
void Map::setBackground(const Color& c)
{
background_=c;
}
const Color& Map::getBackground() const
{
return background_;
}
void Map::zoom(double factor)
{
coord2d center = currentExtent_.center();
double w = factor * currentExtent_.width();
double h = factor * currentExtent_.height();
currentExtent_ = Envelope<double>(center.x - 0.5 * w, center.y - 0.5 * h,
center.x + 0.5 * w, center.y + 0.5 * h);
fixAspectRatio();
}
void Map::zoom_all()
{
std::vector<Layer>::const_iterator itr = layers_.begin();
Envelope<double> ext;
bool first = true;
while (itr != layers_.end())
{
if (first)
{
ext = itr->envelope();
first = false;
}
else
{
ext.expand_to_include(itr->envelope());
}
++itr;
}
zoomToBox(ext);
}
void Map::zoomToBox(const Envelope<double> &box)
{
currentExtent_=box;
fixAspectRatio();
}
void Map::fixAspectRatio()
{
double ratio1 = (double) width_ / (double) height_;
double ratio2 = currentExtent_.width() / currentExtent_.height();
if (ratio2 > ratio1)
{
currentExtent_.height(currentExtent_.width() / ratio1);
}
else if (ratio2 < ratio1)
{
currentExtent_.width(currentExtent_.height() * ratio1);
}
}
const Envelope<double>& Map::getCurrentExtent() const
{
return currentExtent_;
}
void Map::pan(int x,int y)
{
int dx = x - int(0.5 * width_);
int dy = int(0.5 * height_) - y;
double s = width_/currentExtent_.width();
double minx = currentExtent_.minx() + dx/s;
double maxx = currentExtent_.maxx() + dx/s;
double miny = currentExtent_.miny() + dy/s;
double maxy = currentExtent_.maxy() + dy/s;
currentExtent_.init(minx,miny,maxx,maxy);
}
void Map::pan_and_zoom(int x,int y,double factor)
{
pan(x,y);
zoom(factor);
}
double Map::scale() const
{
if (width_>0)
return currentExtent_.width()/width_;
return currentExtent_.width();
}
Map::~Map() {}
}
<commit_msg>added remove_all <commit_after>/*****************************************************************************
*
* This file is part of Mapnik (c++ mapping toolkit)
*
* Copyright (C) 2006 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
*
*****************************************************************************/
//$Id: map.cpp 17 2005-03-08 23:58:43Z pavlenko $,
#include <mapnik/style.hpp>
#include <mapnik/datasource.hpp>
#include <mapnik/layer.hpp>
#include <mapnik/map.hpp>
namespace mapnik
{
Map::Map()
: width_(400),
height_(400),
srid_(-1) {}
Map::Map(int width,int height,int srid)
: width_(width),
height_(height),
srid_(srid),
background_(Color(255,255,255)) {}
Map::Map(const Map& rhs)
: width_(rhs.width_),
height_(rhs.height_),
srid_(rhs.srid_),
background_(rhs.background_),
styles_(rhs.styles_),
layers_(rhs.layers_),
currentExtent_(rhs.currentExtent_) {}
Map& Map::operator=(const Map& rhs)
{
if (this==&rhs) return *this;
width_=rhs.width_;
height_=rhs.height_;
srid_=rhs.srid_;
background_=rhs.background_;
styles_=rhs.styles_;
layers_=rhs.layers_;
return *this;
}
Map::style_iterator Map::begin_styles() const
{
return styles_.begin();
}
Map::style_iterator Map::end_styles() const
{
return styles_.end();
}
bool Map::insert_style(std::string const& name,feature_type_style const& style)
{
return styles_.insert(make_pair(name,style)).second;
}
void Map::remove_style(std::string const& name)
{
styles_.erase(name);
}
feature_type_style const& Map::find_style(std::string const& name) const
{
std::map<std::string,feature_type_style>::const_iterator itr
= styles_.find(name);
if (itr!=styles_.end())
return itr->second;
static feature_type_style default_style;
return default_style;
}
size_t Map::layerCount() const
{
return layers_.size();
}
void Map::addLayer(const Layer& l)
{
layers_.push_back(l);
}
void Map::removeLayer(size_t index)
{
layers_.erase(layers_.begin()+index);
}
void Map::remove_all()
{
layers_.clear();
}
const Layer& Map::getLayer(size_t index) const
{
return layers_[index];
}
Layer& Map::getLayer(size_t index)
{
return layers_[index];
}
std::vector<Layer> const& Map::layers() const
{
return layers_;
}
unsigned Map::getWidth() const
{
return width_;
}
unsigned Map::getHeight() const
{
return height_;
}
void Map::setWidth(unsigned width)
{
if (width >= MIN_MAPSIZE && width <= MAX_MAPSIZE)
{
width_=width;
fixAspectRatio();
}
}
void Map::setHeight(unsigned height)
{
if (height >= MIN_MAPSIZE && height <= MAX_MAPSIZE)
{
height_=height;
fixAspectRatio();
}
}
void Map::resize(unsigned width,unsigned height)
{
if (width >= MIN_MAPSIZE && width <= MAX_MAPSIZE &&
height >= MIN_MAPSIZE && height <= MAX_MAPSIZE)
{
width_=width;
height_=height;
fixAspectRatio();
}
}
int Map::srid() const
{
return srid_;
}
void Map::setBackground(const Color& c)
{
background_=c;
}
const Color& Map::getBackground() const
{
return background_;
}
void Map::zoom(double factor)
{
coord2d center = currentExtent_.center();
double w = factor * currentExtent_.width();
double h = factor * currentExtent_.height();
currentExtent_ = Envelope<double>(center.x - 0.5 * w, center.y - 0.5 * h,
center.x + 0.5 * w, center.y + 0.5 * h);
fixAspectRatio();
}
void Map::zoom_all()
{
std::vector<Layer>::const_iterator itr = layers_.begin();
Envelope<double> ext;
bool first = true;
while (itr != layers_.end())
{
if (first)
{
ext = itr->envelope();
first = false;
}
else
{
ext.expand_to_include(itr->envelope());
}
++itr;
}
zoomToBox(ext);
}
void Map::zoomToBox(const Envelope<double> &box)
{
currentExtent_=box;
fixAspectRatio();
}
void Map::fixAspectRatio()
{
double ratio1 = (double) width_ / (double) height_;
double ratio2 = currentExtent_.width() / currentExtent_.height();
if (ratio2 > ratio1)
{
currentExtent_.height(currentExtent_.width() / ratio1);
}
else if (ratio2 < ratio1)
{
currentExtent_.width(currentExtent_.height() * ratio1);
}
}
const Envelope<double>& Map::getCurrentExtent() const
{
return currentExtent_;
}
void Map::pan(int x,int y)
{
int dx = x - int(0.5 * width_);
int dy = int(0.5 * height_) - y;
double s = width_/currentExtent_.width();
double minx = currentExtent_.minx() + dx/s;
double maxx = currentExtent_.maxx() + dx/s;
double miny = currentExtent_.miny() + dy/s;
double maxy = currentExtent_.maxy() + dy/s;
currentExtent_.init(minx,miny,maxx,maxy);
}
void Map::pan_and_zoom(int x,int y,double factor)
{
pan(x,y);
zoom(factor);
}
double Map::scale() const
{
if (width_>0)
return currentExtent_.width()/width_;
return currentExtent_.width();
}
Map::~Map() {}
}
<|endoftext|> |
<commit_before>//===--------------------------- new.cpp ----------------------------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
#include <stdlib.h>
#include <cxxabi.h>
#include "new"
#if __APPLE__
// On Darwin, there are two STL shared libraries and a lower level ABI
// shared libray. The global holding the current new handler is
// in the ABI library and named __cxa_new_handler.
#define __new_handler __cxxabiapple::__cxa_new_handler
#else
static std::new_handler __new_handler;
#endif
// Implement all new and delete operators as weak definitions
// in this shared library, so that they can be overriden by programs
// that define non-weak copies of the functions.
__attribute__((__weak__, __visibility__("default")))
void *
operator new(std::size_t size) throw (std::bad_alloc)
{
if (size == 0)
size = 1;
void* p;
while ((p = ::malloc(size)) == 0)
{
// If malloc fails and there is a new_handler,
// call it to try free up memory.
if (__new_handler)
__new_handler();
else
throw std::bad_alloc();
}
return p;
}
__attribute__((__weak__, __visibility__("default")))
void*
operator new(size_t size, const std::nothrow_t&) throw()
{
void* p = 0;
try
{
p = ::operator new(size);
}
catch (...)
{
}
return p;
}
__attribute__((__weak__, __visibility__("default")))
void*
operator new[](size_t size) throw (std::bad_alloc)
{
return ::operator new(size);
}
__attribute__((__weak__, __visibility__("default")))
void*
operator new[](size_t size, const std::nothrow_t& nothrow) throw()
{
void* p = 0;
try
{
p = ::operator new[](size);
}
catch (...)
{
}
return p;
}
__attribute__((__weak__, __visibility__("default")))
void
operator delete(void* ptr) throw ()
{
if (ptr)
::free(ptr);
}
__attribute__((__weak__, __visibility__("default")))
void
operator delete(void* ptr, const std::nothrow_t&) throw ()
{
::operator delete(ptr);
}
__attribute__((__weak__, __visibility__("default")))
void
operator delete[] (void* ptr) throw ()
{
::operator delete (ptr);
}
__attribute__((__weak__, __visibility__("default")))
void
operator delete[] (void* ptr, const std::nothrow_t&) throw ()
{
::operator delete[](ptr);
}
namespace std
{
bad_alloc::bad_alloc() throw()
{
}
bad_alloc::~bad_alloc() throw()
{
}
const char*
bad_alloc::what() const throw()
{
return "std::bad_alloc";
}
bad_array_new_length::bad_array_new_length() throw()
{
}
bad_array_new_length::~bad_array_new_length() throw()
{
}
const char*
bad_array_new_length::what() const throw()
{
return "bad_array_new_length";
}
void
__throw_bad_alloc()
{
throw bad_alloc();
}
} // std
<commit_msg>Add set_new_handler and nothrow implementations<commit_after>//===--------------------------- new.cpp ----------------------------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
#include <stdlib.h>
#include <cxxabi.h>
#include "new"
#if __APPLE__
// On Darwin, there are two STL shared libraries and a lower level ABI
// shared libray. The global holding the current new handler is
// in the ABI library and named __cxa_new_handler.
#define __new_handler __cxxabiapple::__cxa_new_handler
#else
static std::new_handler __new_handler;
#endif
// Implement all new and delete operators as weak definitions
// in this shared library, so that they can be overriden by programs
// that define non-weak copies of the functions.
__attribute__((__weak__, __visibility__("default")))
void *
operator new(std::size_t size) throw (std::bad_alloc)
{
if (size == 0)
size = 1;
void* p;
while ((p = ::malloc(size)) == 0)
{
// If malloc fails and there is a new_handler,
// call it to try free up memory.
if (__new_handler)
__new_handler();
else
throw std::bad_alloc();
}
return p;
}
__attribute__((__weak__, __visibility__("default")))
void*
operator new(size_t size, const std::nothrow_t&) throw()
{
void* p = 0;
try
{
p = ::operator new(size);
}
catch (...)
{
}
return p;
}
__attribute__((__weak__, __visibility__("default")))
void*
operator new[](size_t size) throw (std::bad_alloc)
{
return ::operator new(size);
}
__attribute__((__weak__, __visibility__("default")))
void*
operator new[](size_t size, const std::nothrow_t& nothrow) throw()
{
void* p = 0;
try
{
p = ::operator new[](size);
}
catch (...)
{
}
return p;
}
__attribute__((__weak__, __visibility__("default")))
void
operator delete(void* ptr) throw ()
{
if (ptr)
::free(ptr);
}
__attribute__((__weak__, __visibility__("default")))
void
operator delete(void* ptr, const std::nothrow_t&) throw ()
{
::operator delete(ptr);
}
__attribute__((__weak__, __visibility__("default")))
void
operator delete[] (void* ptr) throw ()
{
::operator delete (ptr);
}
__attribute__((__weak__, __visibility__("default")))
void
operator delete[] (void* ptr, const std::nothrow_t&) throw ()
{
::operator delete[](ptr);
}
namespace std
{
const nothrow_t nothrow = {};
new_handler
set_new_handler(new_handler handler) throw()
{
new_handler r = __new_handler;
__new_handler = handler;
return r;
}
bad_alloc::bad_alloc() throw()
{
}
bad_alloc::~bad_alloc() throw()
{
}
const char*
bad_alloc::what() const throw()
{
return "std::bad_alloc";
}
bad_array_new_length::bad_array_new_length() throw()
{
}
bad_array_new_length::~bad_array_new_length() throw()
{
}
const char*
bad_array_new_length::what() const throw()
{
return "bad_array_new_length";
}
void
__throw_bad_alloc()
{
throw bad_alloc();
}
} // std
<|endoftext|> |
<commit_before>#include <sys/time.h>
#ifdef WIN32
#include <winsock2.h>
#else
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <netdb.h>
#endif
#ifndef WIN32
#include <unistd.h>
#endif
#include "netbase.h"
extern int GetRandInt(int nMax);
/*
* NTP uses two fixed point formats. The first (l_fp) is the "long"
* format and is 64 bits long with the decimal between bits 31 and 32.
* This is used for time stamps in the NTP packet header (in network
* byte order) and for internal computations of offsets (in local host
* byte order). We use the same structure for both signed and unsigned
* values, which is a big hack but saves rewriting all the operators
* twice. Just to confuse this, we also sometimes just carry the
* fractional part in calculations, in both signed and unsigned forms.
* Anyway, an l_fp looks like:
*
* 0 1 2 3
* 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
* | Integral Part |
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
* | Fractional Part |
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
* REF http://www.eecis.udel.edu/~mills/database/rfc/rfc2030.txt
*/
typedef struct {
union {
uint32_t Xl_ui;
int32_t Xl_i;
} Ul_i;
union {
uint32_t Xl_uf;
int32_t Xl_f;
} Ul_f;
} l_fp;
inline void Ntp2Unix(uint32_t &n, time_t &u)
{
// Ntp's time scale starts in 1900, Unix in 1970.
u = n - 0x83aa7e80; // 2208988800 1970 - 1900 in seconds
}
inline void HTONL_FP(l_fp *h, l_fp *n)
{
(n)->Ul_i.Xl_ui = htonl((h)->Ul_i.Xl_ui);
(n)->Ul_f.Xl_uf = htonl((h)->Ul_f.Xl_uf);
}
inline void ntohl_fp(l_fp *n, l_fp *h)
{
(h)->Ul_i.Xl_ui = ntohl((n)->Ul_i.Xl_ui);
(h)->Ul_f.Xl_uf = ntohl((n)->Ul_f.Xl_uf);
}
struct pkt {
uint8_t li_vn_mode; /* leap indicator, version and mode */
uint8_t stratum; /* peer stratum */
uint8_t ppoll; /* peer poll interval */
int8_t precision; /* peer clock precision */
uint32_t rootdelay; /* distance to primary clock */
uint32_t rootdispersion; /* clock dispersion */
uint32_t refid; /* reference clock ID */
l_fp ref; /* time peer clock was last updated */
l_fp org; /* originate time stamp */
l_fp rec; /* receive time stamp */
l_fp xmt; /* transmit time stamp */
uint32_t exten[1]; /* misused */
uint8_t mac[5 * sizeof(uint32_t)]; /* mac */
};
int nServersCount = 65;
std::string NtpServers[65] = {
// Microsoft
"time.windows.com",
// Google
"time1.google.com",
"time2.google.com",
// Russian Federation
"ntp.ix.ru",
"0.ru.pool.ntp.org",
"1.ru.pool.ntp.org",
"2.ru.pool.ntp.org",
"3.ru.pool.ntp.org",
"ntp1.stratum2.ru",
"ntp2.stratum2.ru",
"ntp3.stratum2.ru",
"ntp4.stratum2.ru",
"ntp5.stratum2.ru",
"ntp6.stratum2.ru",
"ntp7.stratum2.ru",
"ntp1.stratum1.ru",
"ntp2.stratum1.ru",
"ntp3.stratum1.ru",
"ntp4.stratum1.ru",
"ntp1.vniiftri.ru",
"ntp2.vniiftri.ru",
"ntp3.vniiftri.ru",
"ntp4.vniiftri.ru",
"ntp21.vniiftri.ru",
"ntp1.niiftri.irkutsk.ru",
"ntp2.niiftri.irkutsk.ru",
"vniiftri.khv.ru",
"vniiftri2.khv.ru",
// United States
"nist1-pa.ustiming.org",
"time-a.nist.gov ",
"time-b.nist.gov ",
"time-c.nist.gov ",
"time-d.nist.gov ",
"nist1-macon.macon.ga.us",
"nist.netservicesgroup.com",
"nisttime.carsoncity.k12.mi.us",
"nist1-lnk.binary.net",
"wwv.nist.gov",
"time-a.timefreq.bldrdoc.gov",
"time-b.timefreq.bldrdoc.gov",
"time-c.timefreq.bldrdoc.gov",
"time.nist.gov",
"utcnist.colorado.edu",
"utcnist2.colorado.edu",
"ntp-nist.ldsbc.net",
"nist1-lv.ustiming.org",
"time-nw.nist.gov",
"nist-time-server.eoni.com",
"nist-time-server.eoni.com",
"ntp1.bu.edu",
"ntp2.bu.edu",
"ntp3.bu.edu",
// South Africa
"ntp1.meraka.csir.co.za",
"ntp.is.co.za",
"ntp2.is.co.za",
"igubu.saix.net",
"ntp1.neology.co.za",
"ntp2.neology.co.za",
"tick.meraka.csir.co.za",
"tock.meraka.csir.co.za",
"ntp.time.org.za",
"ntp1.meraka.csir.co.za",
"ntp2.meraka.csir.co.za",
// Italy
"ntp1.inrim.it",
"ntp2.inrim.it",
// ... To be continued
};
#ifdef WIN32
bool InitWithRandom(SOCKET &sockfd, int &servlen, struct sockaddr *pcliaddr)
#else
bool InitWithRandom(int &sockfd, socklen_t &servlen, struct sockaddr *pcliaddr)
#endif
{
int nAttempt = 0;
while(nAttempt < 100)
{
sockfd = -1;
nAttempt++;
int nServerNum = GetRandInt(nServersCount);
std::vector<CNetAddr> vIP;
bool fRet = LookupHost(NtpServers[nServerNum].c_str(), vIP, 10, true);
if (!fRet)
continue;
struct sockaddr_in servaddr;
servaddr.sin_family = AF_INET;
servaddr.sin_port = htons(123);
bool found = false;
for(unsigned int i = 0; i < vIP.size(); i++)
{
if ((found = vIP[i].GetInAddr(&servaddr.sin_addr)))
{
break;
}
}
if (!found)
continue;
sockfd = socket(AF_INET, SOCK_DGRAM, 0);
if (sockfd == -1)
continue; // socket initialization error
if (connect(sockfd, (struct sockaddr *) &servaddr, sizeof(servaddr)) == -1 )
{
continue; // "connection" error
}
*pcliaddr = *((struct sockaddr *) &servaddr);
servlen = sizeof(servaddr);
return true;
}
return false;
}
#ifdef WIN32
bool InitWithHost(std::string &strHostName, SOCKET &sockfd, int &servlen, struct sockaddr *pcliaddr)
#else
bool InitWithHost(std::string &strHostName, int &sockfd, socklen_t &servlen, struct sockaddr *pcliaddr)
#endif
{
sockfd = -1;
std::vector<CNetAddr> vIP;
bool fRet = LookupHost(strHostName.c_str(), vIP, 10, true);
if (!fRet)
return false;
struct sockaddr_in servaddr;
servaddr.sin_family = AF_INET;
servaddr.sin_port = htons(123);
bool found = false;
for(unsigned int i = 0; i < vIP.size(); i++)
{
if ((found = vIP[i].GetInAddr(&servaddr.sin_addr)))
{
break;
}
}
if (!found)
return false;
sockfd = socket(AF_INET, SOCK_DGRAM, 0);
if (sockfd == -1)
return false; // socket initialization error
if (connect(sockfd, (struct sockaddr *) &servaddr, sizeof(servaddr)) == -1 )
{
return false; // "connection" error
}
*pcliaddr = *((struct sockaddr *) &servaddr);
servlen = sizeof(servaddr);
return true;
}
#ifdef WIN32
int64_t DoReq(SOCKET sockfd, int servlen, struct sockaddr cliaddr)
#else
int64_t DoReq(int sockfd, socklen_t servlen, struct sockaddr cliaddr)
#endif
{
struct pkt *msg = new pkt;
struct pkt *prt = new pkt;
msg->li_vn_mode=227;
msg->stratum=0;
msg->ppoll=4;
msg->precision=0;
msg->rootdelay=0;
msg->rootdispersion=0;
msg->ref.Ul_i.Xl_i=0;
msg->ref.Ul_f.Xl_f=0;
msg->org.Ul_i.Xl_i=0;
msg->org.Ul_f.Xl_f=0;
msg->rec.Ul_i.Xl_i=0;
msg->rec.Ul_f.Xl_f=0;
msg->xmt.Ul_i.Xl_i=0;
msg->xmt.Ul_f.Xl_f=0;
int len=48;
sendto(sockfd, (char *) msg, len, 0, &cliaddr, servlen);
int n = recvfrom(sockfd, (char *) msg, len, 0, NULL, NULL);
ntohl_fp(&msg->rec, &prt->rec);
ntohl_fp(&msg->xmt, &prt->xmt);
time_t seconds_receive;
time_t seconds_transmit;
Ntp2Unix(prt->rec.Ul_i.Xl_ui, seconds_receive);
Ntp2Unix(prt->xmt.Ul_i.Xl_ui, seconds_transmit);
delete msg;
delete prt;
return (seconds_receive + seconds_transmit) / 2;
}
int64_t NtpGetTime()
{
struct sockaddr cliaddr;
#ifdef WIN32
SOCKET sockfd;
int servlen;
#else
int sockfd;
socklen_t servlen;
#endif
if (!InitWithRandom(sockfd, servlen, &cliaddr))
return -1;
int64_t nTime = DoReq(sockfd, servlen, cliaddr);
#ifdef WIN32
closesocket(sockfd);
#else
close(sockfd);
#endif
return nTime;
}
int64_t NtpGetTime(std::string &strHostName)
{
struct sockaddr cliaddr;
#ifdef WIN32
SOCKET sockfd;
int servlen;
#else
int sockfd;
socklen_t servlen;
#endif
if (!InitWithHost(strHostName, sockfd, servlen, &cliaddr))
return -1;
int64_t nTime = DoReq(sockfd, servlen, cliaddr);
#ifdef WIN32
closesocket(sockfd);
#else
close(sockfd);
#endif
return nTime;
}
<commit_msg>compat.h definitions should work well.<commit_after>#include <sys/time.h>
#ifdef WIN32
#include <winsock2.h>
#else
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <netdb.h>
#endif
#ifndef WIN32
#include <unistd.h>
#endif
#include "netbase.h"
extern int GetRandInt(int nMax);
/*
* NTP uses two fixed point formats. The first (l_fp) is the "long"
* format and is 64 bits long with the decimal between bits 31 and 32.
* This is used for time stamps in the NTP packet header (in network
* byte order) and for internal computations of offsets (in local host
* byte order). We use the same structure for both signed and unsigned
* values, which is a big hack but saves rewriting all the operators
* twice. Just to confuse this, we also sometimes just carry the
* fractional part in calculations, in both signed and unsigned forms.
* Anyway, an l_fp looks like:
*
* 0 1 2 3
* 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
* | Integral Part |
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
* | Fractional Part |
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
* REF http://www.eecis.udel.edu/~mills/database/rfc/rfc2030.txt
*/
typedef struct {
union {
uint32_t Xl_ui;
int32_t Xl_i;
} Ul_i;
union {
uint32_t Xl_uf;
int32_t Xl_f;
} Ul_f;
} l_fp;
inline void Ntp2Unix(uint32_t &n, time_t &u)
{
// Ntp's time scale starts in 1900, Unix in 1970.
u = n - 0x83aa7e80; // 2208988800 1970 - 1900 in seconds
}
inline void HTONL_FP(l_fp *h, l_fp *n)
{
(n)->Ul_i.Xl_ui = htonl((h)->Ul_i.Xl_ui);
(n)->Ul_f.Xl_uf = htonl((h)->Ul_f.Xl_uf);
}
inline void ntohl_fp(l_fp *n, l_fp *h)
{
(h)->Ul_i.Xl_ui = ntohl((n)->Ul_i.Xl_ui);
(h)->Ul_f.Xl_uf = ntohl((n)->Ul_f.Xl_uf);
}
struct pkt {
uint8_t li_vn_mode; /* leap indicator, version and mode */
uint8_t stratum; /* peer stratum */
uint8_t ppoll; /* peer poll interval */
int8_t precision; /* peer clock precision */
uint32_t rootdelay; /* distance to primary clock */
uint32_t rootdispersion; /* clock dispersion */
uint32_t refid; /* reference clock ID */
l_fp ref; /* time peer clock was last updated */
l_fp org; /* originate time stamp */
l_fp rec; /* receive time stamp */
l_fp xmt; /* transmit time stamp */
uint32_t exten[1]; /* misused */
uint8_t mac[5 * sizeof(uint32_t)]; /* mac */
};
int nServersCount = 65;
std::string NtpServers[65] = {
// Microsoft
"time.windows.com",
// Google
"time1.google.com",
"time2.google.com",
// Russian Federation
"ntp.ix.ru",
"0.ru.pool.ntp.org",
"1.ru.pool.ntp.org",
"2.ru.pool.ntp.org",
"3.ru.pool.ntp.org",
"ntp1.stratum2.ru",
"ntp2.stratum2.ru",
"ntp3.stratum2.ru",
"ntp4.stratum2.ru",
"ntp5.stratum2.ru",
"ntp6.stratum2.ru",
"ntp7.stratum2.ru",
"ntp1.stratum1.ru",
"ntp2.stratum1.ru",
"ntp3.stratum1.ru",
"ntp4.stratum1.ru",
"ntp1.vniiftri.ru",
"ntp2.vniiftri.ru",
"ntp3.vniiftri.ru",
"ntp4.vniiftri.ru",
"ntp21.vniiftri.ru",
"ntp1.niiftri.irkutsk.ru",
"ntp2.niiftri.irkutsk.ru",
"vniiftri.khv.ru",
"vniiftri2.khv.ru",
// United States
"nist1-pa.ustiming.org",
"time-a.nist.gov ",
"time-b.nist.gov ",
"time-c.nist.gov ",
"time-d.nist.gov ",
"nist1-macon.macon.ga.us",
"nist.netservicesgroup.com",
"nisttime.carsoncity.k12.mi.us",
"nist1-lnk.binary.net",
"wwv.nist.gov",
"time-a.timefreq.bldrdoc.gov",
"time-b.timefreq.bldrdoc.gov",
"time-c.timefreq.bldrdoc.gov",
"time.nist.gov",
"utcnist.colorado.edu",
"utcnist2.colorado.edu",
"ntp-nist.ldsbc.net",
"nist1-lv.ustiming.org",
"time-nw.nist.gov",
"nist-time-server.eoni.com",
"nist-time-server.eoni.com",
"ntp1.bu.edu",
"ntp2.bu.edu",
"ntp3.bu.edu",
// South Africa
"ntp1.meraka.csir.co.za",
"ntp.is.co.za",
"ntp2.is.co.za",
"igubu.saix.net",
"ntp1.neology.co.za",
"ntp2.neology.co.za",
"tick.meraka.csir.co.za",
"tock.meraka.csir.co.za",
"ntp.time.org.za",
"ntp1.meraka.csir.co.za",
"ntp2.meraka.csir.co.za",
// Italy
"ntp1.inrim.it",
"ntp2.inrim.it",
// ... To be continued
};
bool InitWithRandom(SOCKET &sockfd, socklen_t &servlen, struct sockaddr *pcliaddr)
{
int nAttempt = 0;
while(nAttempt < 100)
{
sockfd = -1;
nAttempt++;
int nServerNum = GetRandInt(nServersCount);
std::vector<CNetAddr> vIP;
bool fRet = LookupHost(NtpServers[nServerNum].c_str(), vIP, 10, true);
if (!fRet)
continue;
struct sockaddr_in servaddr;
servaddr.sin_family = AF_INET;
servaddr.sin_port = htons(123);
bool found = false;
for(unsigned int i = 0; i < vIP.size(); i++)
{
if ((found = vIP[i].GetInAddr(&servaddr.sin_addr)))
{
break;
}
}
if (!found)
continue;
sockfd = socket(AF_INET, SOCK_DGRAM, 0);
if (sockfd == INVALID_SOCKET)
continue; // socket initialization error
if (connect(sockfd, (struct sockaddr *) &servaddr, sizeof(servaddr)) == -1 )
{
continue; // "connection" error
}
*pcliaddr = *((struct sockaddr *) &servaddr);
servlen = sizeof(servaddr);
return true;
}
return false;
}
bool InitWithHost(std::string &strHostName, SOCKET &sockfd, socklen_t &servlen, struct sockaddr *pcliaddr)
{
sockfd = -1;
std::vector<CNetAddr> vIP;
bool fRet = LookupHost(strHostName.c_str(), vIP, 10, true);
if (!fRet)
return false;
struct sockaddr_in servaddr;
servaddr.sin_family = AF_INET;
servaddr.sin_port = htons(123);
bool found = false;
for(unsigned int i = 0; i < vIP.size(); i++)
{
if ((found = vIP[i].GetInAddr(&servaddr.sin_addr)))
{
break;
}
}
if (!found)
return false;
sockfd = socket(AF_INET, SOCK_DGRAM, 0);
if (sockfd == INVALID_SOCKET)
return false; // socket initialization error
if (connect(sockfd, (struct sockaddr *) &servaddr, sizeof(servaddr)) == -1 )
{
return false; // "connection" error
}
*pcliaddr = *((struct sockaddr *) &servaddr);
servlen = sizeof(servaddr);
return true;
}
int64_t DoReq(SOCKET sockfd, socklen_t servlen, struct sockaddr cliaddr)
{
struct pkt *msg = new pkt;
struct pkt *prt = new pkt;
msg->li_vn_mode=227;
msg->stratum=0;
msg->ppoll=4;
msg->precision=0;
msg->rootdelay=0;
msg->rootdispersion=0;
msg->ref.Ul_i.Xl_i=0;
msg->ref.Ul_f.Xl_f=0;
msg->org.Ul_i.Xl_i=0;
msg->org.Ul_f.Xl_f=0;
msg->rec.Ul_i.Xl_i=0;
msg->rec.Ul_f.Xl_f=0;
msg->xmt.Ul_i.Xl_i=0;
msg->xmt.Ul_f.Xl_f=0;
int len=48;
sendto(sockfd, (char *) msg, len, 0, &cliaddr, servlen);
int n = recvfrom(sockfd, (char *) msg, len, 0, NULL, NULL);
ntohl_fp(&msg->rec, &prt->rec);
ntohl_fp(&msg->xmt, &prt->xmt);
time_t seconds_receive;
time_t seconds_transmit;
Ntp2Unix(prt->rec.Ul_i.Xl_ui, seconds_receive);
Ntp2Unix(prt->xmt.Ul_i.Xl_ui, seconds_transmit);
delete msg;
delete prt;
return (seconds_receive + seconds_transmit) / 2;
}
int64_t NtpGetTime()
{
struct sockaddr cliaddr;
SOCKET sockfd;
socklen_t servlen;
if (!InitWithRandom(sockfd, servlen, &cliaddr))
return -1;
int64_t nTime = DoReq(sockfd, servlen, cliaddr);
closesocket(sockfd);
return nTime;
}
int64_t NtpGetTime(std::string &strHostName)
{
struct sockaddr cliaddr;
SOCKET sockfd;
socklen_t servlen;
if (!InitWithHost(strHostName, sockfd, servlen, &cliaddr))
return -1;
int64_t nTime = DoReq(sockfd, servlen, cliaddr);
closesocket(sockfd);
return nTime;
}
<|endoftext|> |
<commit_before>///
/// @file phi.cpp
/// @brief The PhiCache class calculates the partial sieve function
/// (a.k.a. Legendre-sum) using the recursive formula:
/// phi(x, a) = phi(x, a - 1) - phi(x / primes[a], a - 1).
/// phi(x, a) counts the numbers <= x that are not divisible by
/// any of the first a primes. The algorithm used is an
/// optimized version of the algorithm described in Tomás
/// Oliveira e Silva's paper [1]. I have added 5 optimizations
/// to my implementation which significantly speed up the
/// calculation:
///
/// * Cache results of phi(x, a)
/// * Calculate phi(x, a) using formula [2] if a <= 6
/// * Calculate phi(x, a) using pi(x) lookup table
/// * Calculate all phi(x, a) = 1 upfront
/// * Stop recursion at c instead of 1
///
/// [1] Tomás Oliveira e Silva, Computing pi(x): the combinatorial
/// method, Revista do DETUA, vol. 4, no. 6, March 2006, p. 761.
/// http://sweet.ua.pt/tos/bib/5.4.pdf
/// [2] phi(x, a) = (x / pp) * φ(pp) + phi(x % pp, a)
/// with pp = 2 * 3 * ... * prime[a]
///
/// Copyright (C) 2016 Kim Walisch, <kim.walisch@gmail.com>
///
/// This file is distributed under the BSD License. See the COPYING
/// file in the top level directory.
///
#include <PiTable.hpp>
#include <primecount-internal.hpp>
#include <primecount.hpp>
#include <generate.hpp>
#include <pmath.hpp>
#include <PhiTiny.hpp>
#include <fast_div.hpp>
#include <min_max.hpp>
#include <stdint.h>
#include <algorithm>
#include <vector>
#include <limits>
#ifdef _OPENMP
#include <omp.h>
#endif
using namespace std;
using namespace primecount;
namespace {
class PhiCache
{
public:
PhiCache(vector<int32_t>& primes,
PiTable& pi) :
primes_(primes),
pi_(pi),
bytes_(0)
{
size_t max_size = CACHE_A_LIMIT + 1;
size_t size = min(primes.size(), max_size);
cache_.resize(size);
}
/// Calculate phi(x, a) using the recursive formula:
/// phi(x, a) = phi(x, a - 1) - phi(x / primes_[a], a - 1)
///
template <int SIGN>
int64_t phi(int64_t x, int64_t a)
{
int64_t sum = 0;
if (x <= primes_[a])
sum = SIGN;
else if (is_phi_tiny(a))
sum = phi_tiny(x, a) * SIGN;
else if (is_phi_by_pix(x, a))
sum = (pi_[x] - a + 1) * SIGN;
else
{
int64_t sqrtx = isqrt(x);
int64_t pi_sqrtx = a;
if (sqrtx < pi_.size() && sqrtx < primes_[a])
pi_sqrtx = pi_[sqrtx];
// Move out of the loop the calculations where phi(x2, a2) = 1
// phi(x, a) = 1 if primes_[a] >= x
// x2 = x / primes_[a2 + 1]
// phi(x2, a2) = 1 if primes_[a2] >= x / primes_[a2 + 1]
// phi(x2, a2) = 1 if primes_[a2] >= sqrt(x)
// phi(x2, a2) = 1 if a2 >= pi(sqrt(x))
// \sum_{a2 = pi(sqrt(x))}^{a - 1} phi(x2, a2) = a - pi(sqrt(x))
//
sum = (a - pi_sqrtx) * -SIGN;
// phi(x, c) = phi(x, 1) - \sum_{a2 = 1}^{c - 1} phi(x / primes_[a2 + 1], a2)
int64_t c = min(PhiTiny::max_a(), pi_sqrtx);
sum += phi_tiny(x, c) * SIGN;
for (int64_t a2 = c; a2 < pi_sqrtx; a2++)
{
int64_t x2 = fast_div(x, primes_[a2 + 1]);
if (is_cached(x2, a2))
sum += cache_[a2][x2] * -SIGN;
else
sum += phi<-SIGN>(x2, a2);
}
}
if (write_to_cache(x, a))
cache_[a][x] = (uint16_t) (sum * SIGN);
return sum;
}
private:
enum
{
/// Cache phi(x, a) results if a <= CACHE_A_LIMIT
CACHE_A_LIMIT = 500,
/// Keep the cache size below CACHE_BYTES_LIMIT per thread
CACHE_BYTES_LIMIT = 16 << 20
};
vector<vector<uint16_t> > cache_;
vector<int32_t>& primes_;
PiTable& pi_;
int64_t bytes_;
int64_t cache_size(int64_t a) const
{
return (int64_t) cache_[a].size();
}
bool is_phi_by_pix(int64_t x, int64_t a) const
{
return x < pi_.size() &&
x < isquare(primes_[a + 1]);
}
bool is_cached(int64_t x, int64_t a) const
{
return a <= CACHE_A_LIMIT &&
x < cache_size(a) &&
cache_[a][x] != 0;
}
bool write_to_cache(int64_t x, int64_t a)
{
if (a > CACHE_A_LIMIT ||
x > numeric_limits<uint16_t>::max())
return false;
// we need to increase cache size
if (x >= cache_size(a))
{
if (bytes_ > CACHE_BYTES_LIMIT)
return false;
bytes_ += (x + 1 - cache_size(a)) * 2;
cache_[a].resize(x + 1, 0);
}
return true;
}
};
} // namespace
namespace primecount {
/// Partial sieve function (a.k.a. Legendre-sum).
/// phi(x, a) counts the numbers <= x that are not divisible
/// by any of the first a primes.
///
int64_t phi(int64_t x, int64_t a, int threads)
{
if (x < 1) return 0;
if (a > x) return 1;
if (a < 1) return x;
print("");
print("=== phi(x, a) ===");
print("Count the numbers <= x coprime to the first a primes");
double time = get_wtime();
int64_t sum = 0;
if (is_phi_tiny(a))
sum = phi_tiny(x, a);
else
{
vector<int32_t> primes = generate_n_primes(a);
if (primes.at(a) >= x)
sum = 1;
else
{
// use a large pi(x) lookup table for speed
int64_t sqrtx = isqrt(x);
PiTable pi(max(sqrtx, primes[a]));
PhiCache cache(primes, pi);
int64_t pi_sqrtx = min(pi[sqrtx], a);
sum = x - a + pi_sqrtx;
int64_t p14 = ipow((int64_t) 10, 14);
int64_t thread_threshold = p14 / primes[a];
threads = ideal_num_threads(threads, x, thread_threshold);
// this loop scales only up to about 8 CPU cores
threads = min(8, threads);
#pragma omp parallel for schedule(dynamic, 16) \
num_threads(threads) firstprivate(cache) reduction(+: sum)
for (int64_t a2 = 0; a2 < pi_sqrtx; a2++)
sum += cache.phi<-1>(x / primes[a2 + 1], a2);
}
}
print("phi", sum, time);
return sum;
}
} // namespace
<commit_msg>Refactor<commit_after>///
/// @file phi.cpp
/// @brief The PhiCache class calculates the partial sieve function
/// (a.k.a. Legendre-sum) using the recursive formula:
/// phi(x, a) = phi(x, a - 1) - phi(x / primes[a], a - 1).
/// phi(x, a) counts the numbers <= x that are not divisible by
/// any of the first a primes. The algorithm used is an
/// optimized version of the algorithm described in Tomás
/// Oliveira e Silva's paper [1]. I have added 5 optimizations
/// to my implementation which significantly speed up the
/// calculation:
///
/// * Cache results of phi(x, a)
/// * Calculate phi(x, a) using formula [2] if a <= 6
/// * Calculate phi(x, a) using pi(x) lookup table
/// * Calculate all phi(x, a) = 1 upfront
/// * Stop recursion at c instead of 1
///
/// [1] Tomás Oliveira e Silva, Computing pi(x): the combinatorial
/// method, Revista do DETUA, vol. 4, no. 6, March 2006, p. 761.
/// http://sweet.ua.pt/tos/bib/5.4.pdf
/// [2] phi(x, a) = (x / pp) * φ(pp) + phi(x % pp, a)
/// with pp = 2 * 3 * ... * prime[a]
///
/// Copyright (C) 2016 Kim Walisch, <kim.walisch@gmail.com>
///
/// This file is distributed under the BSD License. See the COPYING
/// file in the top level directory.
///
#include <PiTable.hpp>
#include <primecount-internal.hpp>
#include <primecount.hpp>
#include <generate.hpp>
#include <pmath.hpp>
#include <PhiTiny.hpp>
#include <fast_div.hpp>
#include <min_max.hpp>
#include <stdint.h>
#include <algorithm>
#include <vector>
#include <limits>
#ifdef _OPENMP
#include <omp.h>
#endif
using namespace std;
using namespace primecount;
namespace {
class PhiCache
{
public:
PhiCache(vector<int32_t>& primes,
PiTable& pi) :
primes_(primes),
pi_(pi),
bytes_(0)
{
size_t max_size = MAX_A + 1;
size_t size = min(primes.size(), max_size);
cache_.resize(size);
}
/// Calculate phi(x, a) using the recursive formula:
/// phi(x, a) = phi(x, a - 1) - phi(x / primes_[a], a - 1)
///
template <int SIGN>
int64_t phi(int64_t x, int64_t a)
{
int64_t sum = 0;
if (x <= primes_[a])
sum = SIGN;
else if (is_phi_tiny(a))
sum = phi_tiny(x, a) * SIGN;
else if (is_phi_by_pix(x, a))
sum = (pi_[x] - a + 1) * SIGN;
else
{
int64_t sqrtx = isqrt(x);
int64_t pi_sqrtx = a;
if (sqrtx < pi_.size() && sqrtx < primes_[a])
pi_sqrtx = pi_[sqrtx];
// Move out of the loop the calculations where phi(x2, a2) = 1
// phi(x, a) = 1 if primes_[a] >= x
// x2 = x / primes_[a2 + 1]
// phi(x2, a2) = 1 if primes_[a2] >= x / primes_[a2 + 1]
// phi(x2, a2) = 1 if primes_[a2] >= sqrt(x)
// phi(x2, a2) = 1 if a2 >= pi(sqrt(x))
// \sum_{a2 = pi(sqrt(x))}^{a - 1} phi(x2, a2) = a - pi(sqrt(x))
//
sum = (a - pi_sqrtx) * -SIGN;
// phi(x, c) = phi(x, 1) - \sum_{a2 = 1}^{c - 1} phi(x / primes_[a2 + 1], a2)
int64_t c = min(PhiTiny::max_a(), pi_sqrtx);
sum += phi_tiny(x, c) * SIGN;
for (int64_t a2 = c; a2 < pi_sqrtx; a2++)
{
int64_t x2 = fast_div(x, primes_[a2 + 1]);
if (is_cached(x2, a2))
sum += cache_[a2][x2] * -SIGN;
else
sum += phi<-SIGN>(x2, a2);
}
}
if (write_to_cache(x, a))
cache_[a][x] = (uint16_t) (sum * SIGN);
return sum;
}
private:
enum
{
/// Cache phi(x, a) results if a <= MAX_A
MAX_A = 500,
/// Keep the cache size below MAX_BYTES per thread
MAX_BYTES = 16 << 20
};
vector<vector<uint16_t> > cache_;
vector<int32_t>& primes_;
PiTable& pi_;
int64_t bytes_;
int64_t cache_size(int64_t a) const
{
return (int64_t) cache_[a].size();
}
bool is_phi_by_pix(int64_t x, int64_t a) const
{
return x < pi_.size() &&
x < isquare(primes_[a + 1]);
}
bool is_cached(int64_t x, int64_t a) const
{
return a <= MAX_A &&
x < cache_size(a) &&
cache_[a][x] != 0;
}
bool write_to_cache(int64_t x, int64_t a)
{
if (a > MAX_A ||
x > numeric_limits<uint16_t>::max())
return false;
// we need to increase cache size
if (x >= cache_size(a))
{
if (bytes_ > MAX_BYTES)
return false;
bytes_ += (x + 1 - cache_size(a)) * 2;
cache_[a].resize(x + 1, 0);
}
return true;
}
};
} // namespace
namespace primecount {
/// Partial sieve function (a.k.a. Legendre-sum).
/// phi(x, a) counts the numbers <= x that are not divisible
/// by any of the first a primes.
///
int64_t phi(int64_t x, int64_t a, int threads)
{
if (x < 1) return 0;
if (a > x) return 1;
if (a < 1) return x;
print("");
print("=== phi(x, a) ===");
print("Count the numbers <= x coprime to the first a primes");
double time = get_wtime();
int64_t sum = 0;
if (is_phi_tiny(a))
sum = phi_tiny(x, a);
else
{
vector<int32_t> primes = generate_n_primes(a);
if (primes.at(a) >= x)
sum = 1;
else
{
// use a large pi(x) lookup table for speed
int64_t sqrtx = isqrt(x);
PiTable pi(max(sqrtx, primes[a]));
PhiCache cache(primes, pi);
int64_t pi_sqrtx = min(pi[sqrtx], a);
sum = x - a + pi_sqrtx;
int64_t p14 = ipow((int64_t) 10, 14);
int64_t thread_threshold = p14 / primes[a];
threads = ideal_num_threads(threads, x, thread_threshold);
// this loop scales only up to about 8 CPU cores
threads = min(8, threads);
#pragma omp parallel for schedule(dynamic, 16) \
num_threads(threads) firstprivate(cache) reduction(+: sum)
for (int64_t a2 = 0; a2 < pi_sqrtx; a2++)
sum += cache.phi<-1>(x / primes[a2 + 1], a2);
}
}
print("phi", sum, time);
return sum;
}
} // namespace
<|endoftext|> |
<commit_before>// Copyright (c) 2009-2010 Satoshi Nakamoto
// Copyright (c) 2009-2016 The Bitcoin Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "pow.h"
#include "arith_uint256.h"
#include "chain.h"
#include "primitives/block.h"
#include "uint256.h"
#include "util.h"
unsigned int GetNextWorkRequired(const CBlockIndex* pindexLast, const CBlockHeader *pblock, const Consensus::Params& params)
{
unsigned int nProofOfWorkLimit = UintToArith256(params.powLimit).GetCompact();
// Genesis block
if (pindexLast == NULL)
return nProofOfWorkLimit;
// Only change once per difficulty adjustment interval
if ((pindexLast->nHeight+1) % params.DifficultyAdjustmentInterval() != 0)
{
if (params.fPowAllowMinDifficultyBlocks)
{
// Special difficulty rule for testnet:
// If the new block's timestamp is more than 2* 10 minutes
// then allow mining of a min-difficulty block.
if (pblock->GetBlockTime() > pindexLast->GetBlockTime() + params.nPowTargetSpacing*2)
return nProofOfWorkLimit;
else
{
// Return the last non-special-min-difficulty-rules-block
const CBlockIndex* pindex = pindexLast;
while (pindex->pprev && pindex->nHeight % params.DifficultyAdjustmentInterval() != 0 && pindex->nBits == nProofOfWorkLimit)
pindex = pindex->pprev;
return pindex->nBits;
}
}
return pindexLast->nBits;
}
// Go back by what we want to be 14 days worth of blocks
int nHeightFirst = pindexLast->nHeight - (params.DifficultyAdjustmentInterval()-1);
assert(nHeightFirst >= 0);
const CBlockIndex* pindexFirst = pindexLast->GetAncestor(nHeightFirst);
assert(pindexFirst);
return CalculateNextWorkRequired(pindexLast, pindexFirst->GetBlockTime(), params);
}
unsigned int CalculateNextWorkRequired(const CBlockIndex* pindexLast, int64_t nFirstBlockTime, const Consensus::Params& params)
{
if (params.fPowNoRetargeting)
return pindexLast->nBits;
// Limit adjustment step
int64_t nActualTimespan = pindexLast->GetBlockTime() - nFirstBlockTime;
if (nActualTimespan < params.nPowTargetTimespan/4)
nActualTimespan = params.nPowTargetTimespan/4;
if (nActualTimespan > params.nPowTargetTimespan*4)
nActualTimespan = params.nPowTargetTimespan*4;
// Retarget
const arith_uint256 bnPowLimit = UintToArith256(params.powLimit);
arith_uint256 bnNew;
bnNew.SetCompact(pindexLast->nBits);
bnNew *= nActualTimespan;
bnNew /= params.nPowTargetTimespan;
if (bnNew > bnPowLimit)
bnNew = bnPowLimit;
return bnNew.GetCompact();
}
bool CheckProofOfWork(uint256 hash, unsigned int nBits, const Consensus::Params& params)
{
bool fNegative;
bool fOverflow;
arith_uint256 bnTarget;
bnTarget.SetCompact(nBits, &fNegative, &fOverflow);
// Check range
if (fNegative || bnTarget == 0 || fOverflow || bnTarget > UintToArith256(params.powLimit))
return false;
// Check proof of work matches claimed amount
if (UintToArith256(hash) > bnTarget)
return false;
return true;
}
<commit_msg>Litecoin: Fix zeitgeist2 attack thanks to Lolcust and ArtForz. This fixes an issue where a 51% attack can change difficulty at will. Go back the full period unless it's the first retarget after genesis.<commit_after>// Copyright (c) 2009-2010 Satoshi Nakamoto
// Copyright (c) 2009-2016 The Bitcoin Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "pow.h"
#include "arith_uint256.h"
#include "chain.h"
#include "primitives/block.h"
#include "uint256.h"
#include "util.h"
unsigned int GetNextWorkRequired(const CBlockIndex* pindexLast, const CBlockHeader *pblock, const Consensus::Params& params)
{
unsigned int nProofOfWorkLimit = UintToArith256(params.powLimit).GetCompact();
// Genesis block
if (pindexLast == NULL)
return nProofOfWorkLimit;
// Only change once per difficulty adjustment interval
if ((pindexLast->nHeight+1) % params.DifficultyAdjustmentInterval() != 0)
{
if (params.fPowAllowMinDifficultyBlocks)
{
// Special difficulty rule for testnet:
// If the new block's timestamp is more than 2* 10 minutes
// then allow mining of a min-difficulty block.
if (pblock->GetBlockTime() > pindexLast->GetBlockTime() + params.nPowTargetSpacing*2)
return nProofOfWorkLimit;
else
{
// Return the last non-special-min-difficulty-rules-block
const CBlockIndex* pindex = pindexLast;
while (pindex->pprev && pindex->nHeight % params.DifficultyAdjustmentInterval() != 0 && pindex->nBits == nProofOfWorkLimit)
pindex = pindex->pprev;
return pindex->nBits;
}
}
return pindexLast->nBits;
}
// Litecoin: This fixes an issue where a 51% attack can change difficulty at will.
// Go back the full period unless it's the first retarget after genesis. Code courtesy of Art Forz
int blockstogoback = params.DifficultyAdjustmentInterval()-1;
if ((pindexLast->nHeight+1) != params.DifficultyAdjustmentInterval())
blockstogoback = params.DifficultyAdjustmentInterval();
// Go back by what we want to be 14 days worth of blocks
int nHeightFirst = pindexLast->nHeight - blockstogoback;
assert(nHeightFirst >= 0);
const CBlockIndex* pindexFirst = pindexLast->GetAncestor(nHeightFirst);
assert(pindexFirst);
return CalculateNextWorkRequired(pindexLast, pindexFirst->GetBlockTime(), params);
}
unsigned int CalculateNextWorkRequired(const CBlockIndex* pindexLast, int64_t nFirstBlockTime, const Consensus::Params& params)
{
if (params.fPowNoRetargeting)
return pindexLast->nBits;
// Limit adjustment step
int64_t nActualTimespan = pindexLast->GetBlockTime() - nFirstBlockTime;
if (nActualTimespan < params.nPowTargetTimespan/4)
nActualTimespan = params.nPowTargetTimespan/4;
if (nActualTimespan > params.nPowTargetTimespan*4)
nActualTimespan = params.nPowTargetTimespan*4;
// Retarget
const arith_uint256 bnPowLimit = UintToArith256(params.powLimit);
arith_uint256 bnNew;
bnNew.SetCompact(pindexLast->nBits);
bnNew *= nActualTimespan;
bnNew /= params.nPowTargetTimespan;
if (bnNew > bnPowLimit)
bnNew = bnPowLimit;
return bnNew.GetCompact();
}
bool CheckProofOfWork(uint256 hash, unsigned int nBits, const Consensus::Params& params)
{
bool fNegative;
bool fOverflow;
arith_uint256 bnTarget;
bnTarget.SetCompact(nBits, &fNegative, &fOverflow);
// Check range
if (fNegative || bnTarget == 0 || fOverflow || bnTarget > UintToArith256(params.powLimit))
return false;
// Check proof of work matches claimed amount
if (UintToArith256(hash) > bnTarget)
return false;
return true;
}
<|endoftext|> |
<commit_before>// Copyright (c) 2009-2010 Satoshi Nakamoto
// Copyright (c) 2009-2014 The Bitcoin Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "pow.h"
#include "arith_uint256.h"
#include "chain.h"
#include "chainparams.h"
#include "crypto/equihash.h"
#include "primitives/block.h"
#include "streams.h"
#include "uint256.h"
#include "util.h"
#include "sodium.h"
unsigned int GetNextWorkRequired(const CBlockIndex* pindexLast, const CBlockHeader *pblock, const Consensus::Params& params)
{
unsigned int nProofOfWorkLimit = UintToArith256(params.powLimit).GetCompact();
// Genesis block
if (pindexLast == NULL)
return nProofOfWorkLimit;
const CBlockIndex* pindexBits = pindexLast;
{
if (params.fPowAllowMinDifficultyBlocks)
{
// Special difficulty rule for testnet:
// If the new block's timestamp is more than 2* 2.5 minutes
// then allow mining of a min-difficulty block.
if (pblock->GetBlockTime() > pindexLast->GetBlockTime() + params.nPowTargetSpacing*2)
return nProofOfWorkLimit;
else {
// Get the last non-min-difficulty (or at worst the genesis difficulty)
while (pindexBits->pprev && pindexBits->nBits == nProofOfWorkLimit)
pindexBits = pindexBits->pprev;
}
}
}
// Find the first block in the averaging interval
const CBlockIndex* pindexFirst = pindexLast;
for (int i = 0; pindexFirst && i < params.nPowAveragingWindow; i++) {
pindexFirst = pindexFirst->pprev;
}
// Check we have enough blocks
if (pindexFirst == NULL)
return nProofOfWorkLimit;
return CalculateNextWorkRequired(pindexBits->nBits, pindexLast->GetMedianTimePast(), pindexFirst->GetMedianTimePast(), params);
}
unsigned int CalculateNextWorkRequired(const CBlockIndex* pindexLast, int64_t nFirstBlockTime, const Consensus::Params& params)
{
return CalculateNextWorkRequired(pindexLast->nBits, pindexLast->GetMedianTimePast(), nFirstBlockTime, params);
}
unsigned int CalculateNextWorkRequired(uint32_t nBits, int64_t nLastBlockTime, int64_t nFirstBlockTime, const Consensus::Params& params)
{
// Limit adjustment step
// Use medians to prevent time-warp attacks
int64_t nActualTimespan = nLastBlockTime - nFirstBlockTime;
LogPrint("pow", " nActualTimespan = %d before dampening\n", nActualTimespan);
nActualTimespan = params.AveragingWindowTimespan() + (nActualTimespan - params.AveragingWindowTimespan())/4;
LogPrint("pow", " nActualTimespan = %d before bounds\n", nActualTimespan);
if (nActualTimespan < params.MinActualTimespan())
nActualTimespan = params.MinActualTimespan();
if (nActualTimespan > params.MaxActualTimespan())
nActualTimespan = params.MaxActualTimespan();
// Retarget
const arith_uint256 bnPowLimit = UintToArith256(params.powLimit);
arith_uint256 bnNew;
arith_uint256 bnOld;
bnNew.SetCompact(nBits);
bnOld = bnNew;
bnNew /= params.AveragingWindowTimespan();
bnNew *= nActualTimespan;
if (bnNew > bnPowLimit)
bnNew = bnPowLimit;
/// debug print
LogPrint("pow", "GetNextWorkRequired RETARGET\n");
LogPrint("pow", "params.AveragingWindowTimespan() = %d nActualTimespan = %d\n", params.AveragingWindowTimespan(), nActualTimespan);
LogPrint("pow", "Before: %08x %s\n", nBits, bnOld.ToString());
LogPrint("pow", "After: %08x %s\n", bnNew.GetCompact(), bnNew.ToString());
return bnNew.GetCompact();
}
bool CheckEquihashSolution(const CBlockHeader *pblock, const CChainParams& params)
{
unsigned int n = params.EquihashN();
unsigned int k = params.EquihashK();
// Hash state
crypto_generichash_blake2b_state state;
EhInitialiseState(n, k, state);
// I = the block header minus nonce and solution.
CEquihashInput I{*pblock};
// I||V
CDataStream ss(SER_NETWORK, PROTOCOL_VERSION);
ss << I;
ss << pblock->nNonce;
// H(I||V||...
crypto_generichash_blake2b_update(&state, (unsigned char*)&ss[0], ss.size());
bool isValid;
EhIsValidSolution(n, k, state, pblock->nSolution, isValid);
if (!isValid)
return error("CheckEquihashSolution(): invalid solution");
return true;
}
bool CheckProofOfWork(uint256 hash, unsigned int nBits, const Consensus::Params& params)
{
bool fNegative;
bool fOverflow;
arith_uint256 bnTarget;
bnTarget.SetCompact(nBits, &fNegative, &fOverflow);
// Check range
if (fNegative || bnTarget == 0 || fOverflow || bnTarget > UintToArith256(params.powLimit))
return error("CheckProofOfWork(): nBits below minimum work");
// Check proof of work matches claimed amount
if (UintToArith256(hash) > bnTarget)
return error("CheckProofOfWork(): hash doesn't match nBits");
return true;
}
arith_uint256 GetBlockProof(const CBlockIndex& block)
{
arith_uint256 bnTarget;
bool fNegative;
bool fOverflow;
bnTarget.SetCompact(block.nBits, &fNegative, &fOverflow);
if (fNegative || fOverflow || bnTarget == 0)
return 0;
// We need to compute 2**256 / (bnTarget+1), but we can't represent 2**256
// as it's too large for a arith_uint256. However, as 2**256 is at least as large
// as bnTarget+1, it is equal to ((2**256 - bnTarget - 1) / (bnTarget+1)) + 1,
// or ~bnTarget / (nTarget+1) + 1.
return (~bnTarget / (bnTarget + 1)) + 1;
}
int64_t GetBlockProofEquivalentTime(const CBlockIndex& to, const CBlockIndex& from, const CBlockIndex& tip, const Consensus::Params& params)
{
arith_uint256 r;
int sign = 1;
if (to.nChainWork > from.nChainWork) {
r = to.nChainWork - from.nChainWork;
} else {
r = from.nChainWork - to.nChainWork;
sign = -1;
}
r = r * arith_uint256(params.nPowTargetSpacing) / GetBlockProof(tip);
if (r.bits() > 63) {
return sign * std::numeric_limits<int64_t>::max();
}
return sign * r.GetLow64();
}
<commit_msg>Hardfork to the previous testnet difficulty adjustment behaviour at block 43400<commit_after>// Copyright (c) 2009-2010 Satoshi Nakamoto
// Copyright (c) 2009-2014 The Bitcoin Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "pow.h"
#include "arith_uint256.h"
#include "chain.h"
#include "chainparams.h"
#include "crypto/equihash.h"
#include "primitives/block.h"
#include "streams.h"
#include "uint256.h"
#include "util.h"
#include "sodium.h"
unsigned int GetNextWorkRequired(const CBlockIndex* pindexLast, const CBlockHeader *pblock, const Consensus::Params& params)
{
unsigned int nProofOfWorkLimit = UintToArith256(params.powLimit).GetCompact();
// Genesis block
if (pindexLast == NULL)
return nProofOfWorkLimit;
const CBlockIndex* pindexBits = pindexLast;
{
if (params.fPowAllowMinDifficultyBlocks)
{
// Special difficulty rule for testnet:
// If the new block's timestamp is more than 2* 2.5 minutes
// then allow mining of a min-difficulty block.
if (pblock->GetBlockTime() > pindexLast->GetBlockTime() + params.nPowTargetSpacing*2)
return nProofOfWorkLimit;
else if (pindexLast->nHeight >= 43400) { // TODO remove hardfork at next chain reset
// Get the last non-min-difficulty (or at worst the genesis difficulty)
while (pindexBits->pprev && pindexBits->nBits == nProofOfWorkLimit)
pindexBits = pindexBits->pprev;
}
}
}
// Find the first block in the averaging interval
const CBlockIndex* pindexFirst = pindexLast;
for (int i = 0; pindexFirst && i < params.nPowAveragingWindow; i++) {
pindexFirst = pindexFirst->pprev;
}
// Check we have enough blocks
if (pindexFirst == NULL)
return nProofOfWorkLimit;
return CalculateNextWorkRequired(pindexBits->nBits, pindexLast->GetMedianTimePast(), pindexFirst->GetMedianTimePast(), params);
}
unsigned int CalculateNextWorkRequired(const CBlockIndex* pindexLast, int64_t nFirstBlockTime, const Consensus::Params& params)
{
return CalculateNextWorkRequired(pindexLast->nBits, pindexLast->GetMedianTimePast(), nFirstBlockTime, params);
}
unsigned int CalculateNextWorkRequired(uint32_t nBits, int64_t nLastBlockTime, int64_t nFirstBlockTime, const Consensus::Params& params)
{
// Limit adjustment step
// Use medians to prevent time-warp attacks
int64_t nActualTimespan = nLastBlockTime - nFirstBlockTime;
LogPrint("pow", " nActualTimespan = %d before dampening\n", nActualTimespan);
nActualTimespan = params.AveragingWindowTimespan() + (nActualTimespan - params.AveragingWindowTimespan())/4;
LogPrint("pow", " nActualTimespan = %d before bounds\n", nActualTimespan);
if (nActualTimespan < params.MinActualTimespan())
nActualTimespan = params.MinActualTimespan();
if (nActualTimespan > params.MaxActualTimespan())
nActualTimespan = params.MaxActualTimespan();
// Retarget
const arith_uint256 bnPowLimit = UintToArith256(params.powLimit);
arith_uint256 bnNew;
arith_uint256 bnOld;
bnNew.SetCompact(nBits);
bnOld = bnNew;
bnNew /= params.AveragingWindowTimespan();
bnNew *= nActualTimespan;
if (bnNew > bnPowLimit)
bnNew = bnPowLimit;
/// debug print
LogPrint("pow", "GetNextWorkRequired RETARGET\n");
LogPrint("pow", "params.AveragingWindowTimespan() = %d nActualTimespan = %d\n", params.AveragingWindowTimespan(), nActualTimespan);
LogPrint("pow", "Before: %08x %s\n", nBits, bnOld.ToString());
LogPrint("pow", "After: %08x %s\n", bnNew.GetCompact(), bnNew.ToString());
return bnNew.GetCompact();
}
bool CheckEquihashSolution(const CBlockHeader *pblock, const CChainParams& params)
{
unsigned int n = params.EquihashN();
unsigned int k = params.EquihashK();
// Hash state
crypto_generichash_blake2b_state state;
EhInitialiseState(n, k, state);
// I = the block header minus nonce and solution.
CEquihashInput I{*pblock};
// I||V
CDataStream ss(SER_NETWORK, PROTOCOL_VERSION);
ss << I;
ss << pblock->nNonce;
// H(I||V||...
crypto_generichash_blake2b_update(&state, (unsigned char*)&ss[0], ss.size());
bool isValid;
EhIsValidSolution(n, k, state, pblock->nSolution, isValid);
if (!isValid)
return error("CheckEquihashSolution(): invalid solution");
return true;
}
bool CheckProofOfWork(uint256 hash, unsigned int nBits, const Consensus::Params& params)
{
bool fNegative;
bool fOverflow;
arith_uint256 bnTarget;
bnTarget.SetCompact(nBits, &fNegative, &fOverflow);
// Check range
if (fNegative || bnTarget == 0 || fOverflow || bnTarget > UintToArith256(params.powLimit))
return error("CheckProofOfWork(): nBits below minimum work");
// Check proof of work matches claimed amount
if (UintToArith256(hash) > bnTarget)
return error("CheckProofOfWork(): hash doesn't match nBits");
return true;
}
arith_uint256 GetBlockProof(const CBlockIndex& block)
{
arith_uint256 bnTarget;
bool fNegative;
bool fOverflow;
bnTarget.SetCompact(block.nBits, &fNegative, &fOverflow);
if (fNegative || fOverflow || bnTarget == 0)
return 0;
// We need to compute 2**256 / (bnTarget+1), but we can't represent 2**256
// as it's too large for a arith_uint256. However, as 2**256 is at least as large
// as bnTarget+1, it is equal to ((2**256 - bnTarget - 1) / (bnTarget+1)) + 1,
// or ~bnTarget / (nTarget+1) + 1.
return (~bnTarget / (bnTarget + 1)) + 1;
}
int64_t GetBlockProofEquivalentTime(const CBlockIndex& to, const CBlockIndex& from, const CBlockIndex& tip, const Consensus::Params& params)
{
arith_uint256 r;
int sign = 1;
if (to.nChainWork > from.nChainWork) {
r = to.nChainWork - from.nChainWork;
} else {
r = from.nChainWork - to.nChainWork;
sign = -1;
}
r = r * arith_uint256(params.nPowTargetSpacing) / GetBlockProof(tip);
if (r.bits() > 63) {
return sign * std::numeric_limits<int64_t>::max();
}
return sign * r.GetLow64();
}
<|endoftext|> |
<commit_before>#include "ski.h"
class SkiTerm {
public:
SkiTerm() { }
SkiTerm(const QChar& c) { ch = c; }
virtual ~SkiTerm() { }
virtual QString toHof() const { return QString(ch); }
virtual bool isWellFormed() const { return !ch.isNull(); }
QChar ch;
};
class SkiSubTerm : public SkiTerm {
public:
SkiSubTerm()
: SkiTerm('A'),
m_subTerm(0),
m_closed(false) { }
virtual ~SkiSubTerm()
{
qDeleteAll(m_terms);
delete m_subTerm;
m_subTerm = 0;
}
virtual QString toHof() const
{
QString a('A');
QTextStream stream(&a);
stream << QString(m_terms.count() - 2, 'A');
foreach (SkiTerm* t, m_terms)
stream << t->toHof();
stream.flush();
return a;
}
virtual bool isWellFormed() const
{
return m_closed && m_terms.count() >= 2 && !m_subTerm;
}
bool isClosed() const
{
return m_closed;
}
void addTerm(SkiTerm* term)
{
if (m_subTerm)
m_subTerm->addTerm(term);
else if (term->ch == 'A')
m_subTerm = static_cast<SkiSubTerm*>(term);
else
m_terms.append(term);
}
void close()
{
if (m_subTerm)
m_subTerm->close();
else
m_closed = true;
if (m_subTerm && m_subTerm->m_closed) {
m_terms.append(m_subTerm);
m_subTerm = 0;
}
}
private:
QList<SkiTerm*> m_terms;
SkiSubTerm* m_subTerm;
bool m_closed;
};
QString Ski::fromSki(const QString& string)
{
SkiSubTerm* subTerm = 0;
QList<SkiTerm*> terms;
for (int x = 0; x < string.length(); x++) {
SkiTerm* term = 0;
QChar ch = string.at(x);
switch (ch.unicode()) {
case '(': term = new SkiSubTerm; break;
case ')':
{
subTerm->close();
if (subTerm->isClosed()) {
terms.append(subTerm);
subTerm = 0;
}
continue;
}
case 'S':
case 's': term = new SkiTerm('S'); break;
case 'K':
case 'k': term = new SkiTerm('K'); break;
case 'I':
case 'i': term = new SkiTerm('I'); break;
default:
QString error = QString("Error: from ski to hof! ch=`%1`").arg(ch);
Q_ASSERT_X(false, "translate", qPrintable(error));
return error;
};
if (terms.isEmpty() && !subTerm && term->ch != 'A') {
terms.append(term);
continue;
}
if (!subTerm && term->ch == 'A') {
subTerm = static_cast<SkiSubTerm*>(term);
continue;
}
Q_ASSERT(subTerm);
subTerm->addTerm(term);
}
if (subTerm)
terms.append(subTerm); // wasn't closed properly
bool error = false;
QString hof;
QTextStream stream(&hof);
foreach (SkiTerm* t, terms) {
Q_ASSERT(t);
error = !t->isWellFormed() ? true : error;
stream << t->toHof();
}
stream.flush();
if (error) {
QString error = QString("Error: from ski to hof: program is not well formed! program=`%1`").arg(hof);
Q_ASSERT_X(false, "translate", qPrintable(error));
return error;
}
qDeleteAll(terms); // cleanup
return hof;
}
<commit_msg>Simplify the logic in ski translator and fix bug.<commit_after>#include "ski.h"
class SkiTerm {
public:
SkiTerm() { }
SkiTerm(const QChar& c) { ch = c; }
virtual ~SkiTerm() { }
virtual QString toHof() const { return QString(ch); }
virtual bool isWellFormed() const { return !ch.isNull(); }
QChar ch;
};
class SkiSubTerm : public SkiTerm {
public:
SkiSubTerm()
: SkiTerm('A'),
m_subTerm(0),
m_closed(false) { }
virtual ~SkiSubTerm()
{
qDeleteAll(m_terms);
delete m_subTerm;
m_subTerm = 0;
}
virtual QString toHof() const
{
QString a('A');
QTextStream stream(&a);
stream << QString(m_terms.count() - 2, 'A');
foreach (SkiTerm* t, m_terms)
stream << t->toHof();
stream.flush();
return a;
}
virtual bool isWellFormed() const
{
return m_closed && m_terms.count() >= 2 && !m_subTerm;
}
bool isClosed() const
{
return m_closed;
}
void addTerm(SkiTerm* term)
{
if (m_subTerm)
m_subTerm->addTerm(term);
else if (term->ch == 'A')
m_subTerm = static_cast<SkiSubTerm*>(term);
else
m_terms.append(term);
}
void close()
{
if (m_subTerm)
m_subTerm->close();
else
m_closed = true;
if (m_subTerm && m_subTerm->m_closed) {
m_terms.append(m_subTerm);
m_subTerm = 0;
}
}
private:
QList<SkiTerm*> m_terms;
SkiSubTerm* m_subTerm;
bool m_closed;
};
QString Ski::fromSki(const QString& string)
{
SkiSubTerm* subTerm = 0;
QList<SkiTerm*> terms;
for (int x = 0; x < string.length(); x++) {
SkiTerm* term = 0;
QChar ch = string.at(x);
switch (ch.unicode()) {
case '(': term = new SkiSubTerm; break;
case ')':
{
subTerm->close();
if (subTerm->isClosed()) {
terms.append(subTerm);
subTerm = 0;
}
continue;
}
case 'S':
case 's': term = new SkiTerm('S'); break;
case 'K':
case 'k': term = new SkiTerm('K'); break;
case 'I':
case 'i': term = new SkiTerm('I'); break;
default:
QString error = QString("Error: from ski to hof! ch=`%1`").arg(ch);
Q_ASSERT_X(false, "translate", qPrintable(error));
return error;
};
if (subTerm)
subTerm->addTerm(term);
else if (term->ch == 'A')
subTerm = static_cast<SkiSubTerm*>(term);
else
terms.append(term);
}
if (subTerm)
terms.append(subTerm); // wasn't closed properly
bool error = false;
QString hof;
QTextStream stream(&hof);
foreach (SkiTerm* t, terms) {
Q_ASSERT(t);
error = !t->isWellFormed() ? true : error;
stream << t->toHof();
}
stream.flush();
if (error) {
QString error = QString("Error: from ski to hof: program is not well formed! program=`%1`").arg(hof);
Q_ASSERT_X(false, "translate", qPrintable(error));
return error;
}
qDeleteAll(terms); // cleanup
return hof;
}
<|endoftext|> |
<commit_before>#include <uri>
#include <regex>
#include <iostream>
using namespace uri;
///////////////////////////////////////////////////////////////////////////////
URI::URI(const char* uri)
: URI{std::string{uri}}
{}
///////////////////////////////////////////////////////////////////////////////
URI::URI(const std::string& uri)
: port_{}
{
parse(uri);
}
///////////////////////////////////////////////////////////////////////////////
const std::string& URI::scheme() const {
return scheme_;
}
///////////////////////////////////////////////////////////////////////////////
const std::string& URI::userinfo() const {
return userinfo_;
}
///////////////////////////////////////////////////////////////////////////////
const std::string& URI::host() const {
return host_;
}
///////////////////////////////////////////////////////////////////////////////
const std::string& URI::port_str() const {
return port_str_;
}
///////////////////////////////////////////////////////////////////////////////
uint16_t URI::port() const noexcept {
if (not port_) {
port_ = port_str_.begin ? static_cast<uint16_t>(std::stoi(port_str())) : 0;
}
return port_;
}
///////////////////////////////////////////////////////////////////////////////
const std::string& URI::path() const {
static std::string path;
if (path.empty()) {
path = uri_str_.substr(path_.begin, path_.end);
}
return path;
}
///////////////////////////////////////////////////////////////////////////////
const std::string& URI::query() const {
static std::string query;
if (query.empty()){
query = uri_str_.substr(query_.begin, query_.end);
}
return query;
}
///////////////////////////////////////////////////////////////////////////////
const std::string& URI::fragment() const {
static std::string fragment;
if (fragment.empty()) {
fragment = uri_str_.substr(fragment_.begin, fragment_.end);
}
return fragment;
}
///////////////////////////////////////////////////////////////////////////////
const std::string& URI::query(const std::string& key) {
static std::string no_entry_value;
auto target = queries_.find(key);
return (target not_eq queries_.end()) ? target->second : no_entry_value;
}
///////////////////////////////////////////////////////////////////////////////
std::string URI::to_string() const{
return uri_str_;
}
///////////////////////////////////////////////////////////////////////////////
URI::operator std::string () const {
return uri_str_;
}
///////////////////////////////////////////////////////////////////////////////
void URI::parse(const std::string& uri) {
static const std::regex uri_pattern_matcher
{
"^([a-zA-z]+[\\w\\+\\-\\.]+)?(\\://)?" //< scheme
"(([^:@]+)(\\:([^@]+))?@)?" //< username && password
"([^/:?#]+)?(\\:(\\d+))?" //< hostname && port
"([^?#]+)" //< path
"(\\?([^#]*))?" //< query
"(#(.*))?$" //< fragment
};
static std::smatch uri_parts;
if (std::regex_match(uri, uri_parts, uri_pattern_matcher)) {
path_ = Span_t(uri_parts.position(10), uri_parts.length(10));
scheme_ = uri_parts.length(1) ? Span_t(uri_parts.position(1), uri_parts.length(1)) : zero_span_;
userinfo_ = uri_parts.length(3) ? Span_t(uri_parts.position(3), uri_parts.length(3)) : zero_span_;
host_ = uri_parts.length(7) ? Span_t(uri_parts.position(7), uri_parts.length(7)) : zero_span_;
port_str_ = uri_parts.length(9) ? Span_t(uri_parts.position(9), uri_parts.length(9)) : zero_span_;
query_ = uri_parts.length(11) ? Span_t(uri_parts.position(11), uri_parts.length(11)) : zero_span_;
fragment_ = uri_parts.length(13) ? Span_t(uri_parts.position(13), uri_parts.length(13)) : zero_span_;
}
}
///////////////////////////////////////////////////////////////////////////////
void URI::load_queries() {
static const std::regex queries_tokenizer {"[^?=&]+"};
auto& queries = query();
auto position = std::sregex_iterator(queries.begin(), queries.end(), queries_tokenizer);
auto end = std::sregex_iterator();
while (position not_eq end) {
auto key = (*position).str();
if ((++position) not_eq end) {
queries_[key] = (*position++).str();
} else {
queries_[key];
}
}
}
///////////////////////////////////////////////////////////////////////////////
std::ostream& uri::operator<< (std::ostream& out, const URI& uri) {
return out << uri.to_string();
}
<commit_msg>Refactored URI::port()<commit_after>#include <uri>
#include <regex>
#include <iostream>
using namespace uri;
///////////////////////////////////////////////////////////////////////////////
URI::URI(const char* uri)
: URI{std::string{uri}}
{}
///////////////////////////////////////////////////////////////////////////////
URI::URI(const std::string& uri)
: port_{}
{
parse(uri);
}
///////////////////////////////////////////////////////////////////////////////
const std::string& URI::scheme() const {
return scheme_;
}
///////////////////////////////////////////////////////////////////////////////
const std::string& URI::userinfo() const {
return userinfo_;
}
///////////////////////////////////////////////////////////////////////////////
const std::string& URI::host() const {
return host_;
}
///////////////////////////////////////////////////////////////////////////////
const std::string& URI::port_str() const {
return port_str_;
}
///////////////////////////////////////////////////////////////////////////////
uint16_t URI::port() const noexcept {
if (not port_) {
port_ = (not port_str_.empty()) ? static_cast<uint16_t>(std::stoi(port_str_)) : 0;
}
return port_;
}
///////////////////////////////////////////////////////////////////////////////
const std::string& URI::path() const {
static std::string path;
if (path.empty()) {
path = uri_str_.substr(path_.begin, path_.end);
}
return path;
}
///////////////////////////////////////////////////////////////////////////////
const std::string& URI::query() const {
static std::string query;
if (query.empty()){
query = uri_str_.substr(query_.begin, query_.end);
}
return query;
}
///////////////////////////////////////////////////////////////////////////////
const std::string& URI::fragment() const {
static std::string fragment;
if (fragment.empty()) {
fragment = uri_str_.substr(fragment_.begin, fragment_.end);
}
return fragment;
}
///////////////////////////////////////////////////////////////////////////////
const std::string& URI::query(const std::string& key) {
static std::string no_entry_value;
auto target = queries_.find(key);
return (target not_eq queries_.end()) ? target->second : no_entry_value;
}
///////////////////////////////////////////////////////////////////////////////
std::string URI::to_string() const{
return uri_str_;
}
///////////////////////////////////////////////////////////////////////////////
URI::operator std::string () const {
return uri_str_;
}
///////////////////////////////////////////////////////////////////////////////
void URI::parse(const std::string& uri) {
static const std::regex uri_pattern_matcher
{
"^([a-zA-z]+[\\w\\+\\-\\.]+)?(\\://)?" //< scheme
"(([^:@]+)(\\:([^@]+))?@)?" //< username && password
"([^/:?#]+)?(\\:(\\d+))?" //< hostname && port
"([^?#]+)" //< path
"(\\?([^#]*))?" //< query
"(#(.*))?$" //< fragment
};
static std::smatch uri_parts;
if (std::regex_match(uri, uri_parts, uri_pattern_matcher)) {
path_ = Span_t(uri_parts.position(10), uri_parts.length(10));
scheme_ = uri_parts.length(1) ? Span_t(uri_parts.position(1), uri_parts.length(1)) : zero_span_;
userinfo_ = uri_parts.length(3) ? Span_t(uri_parts.position(3), uri_parts.length(3)) : zero_span_;
host_ = uri_parts.length(7) ? Span_t(uri_parts.position(7), uri_parts.length(7)) : zero_span_;
port_str_ = uri_parts.length(9) ? Span_t(uri_parts.position(9), uri_parts.length(9)) : zero_span_;
query_ = uri_parts.length(11) ? Span_t(uri_parts.position(11), uri_parts.length(11)) : zero_span_;
fragment_ = uri_parts.length(13) ? Span_t(uri_parts.position(13), uri_parts.length(13)) : zero_span_;
}
}
///////////////////////////////////////////////////////////////////////////////
void URI::load_queries() {
static const std::regex queries_tokenizer {"[^?=&]+"};
auto& queries = query();
auto position = std::sregex_iterator(queries.begin(), queries.end(), queries_tokenizer);
auto end = std::sregex_iterator();
while (position not_eq end) {
auto key = (*position).str();
if ((++position) not_eq end) {
queries_[key] = (*position++).str();
} else {
queries_[key];
}
}
}
///////////////////////////////////////////////////////////////////////////////
std::ostream& uri::operator<< (std::ostream& out, const URI& uri) {
return out << uri.to_string();
}
<|endoftext|> |
<commit_before>
#include "uri.h"
#include <algorithm>
#include <iomanip>
#include <sstream>
#include <stdexcept>
#include <string>
#include <type_traits>
using namespace std;
namespace coda {
namespace net {
namespace helper {
#ifdef URIPARSER_FOUND
static std::string fromRange(const UriTextRangeA &rng) {
if (rng.first && rng.afterLast) {
return std::string(rng.first, rng.afterLast);
} else {
return std::string();
}
}
static std::string fromList(UriPathSegmentA *xs, const std::string &delim) {
UriPathSegmentStructA *head(xs);
std::string accum;
uri::uri(const std::string &uri, const std::string &defaultScheme) : uri_(uri) {
isValid_ = parse(uri, defaultScheme);
}
while (head) {
accum += delim + fromRange(head->text);
head = head->next;
}
return accum;
}
#endif
char from_hex(char ch) { return isdigit(ch) ? ch - '0' : tolower(ch) - 'a' + 10; }
} // namespace helper
uri::uri() noexcept : isValid_(false) {}
uri::uri(const std::string &uri, const std::string &defaultScheme) : uri_(uri) {
isValid_ = parse(uri, defaultScheme);
}
std::string uri::to_string() const noexcept { return uri_; }
uri::operator std::string() const noexcept { return uri_; }
std::string uri::full_path() const {
std::string temp = path();
if (!query().empty()) {
temp += '?';
temp += query_;
}
if (!fragment().empty()) {
temp += '#';
temp += fragment();
}
return temp;
}
bool uri::parse(const std::string &uri_s, const std::string &defaultScheme) {
static const string prot_end("://");
if (uri_s.empty()) {
return false;
}
string::const_iterator pos_i = search(uri_s.begin(), uri_s.end(), prot_end.begin(), prot_end.end());
#ifdef URIPARSER_FOUND
UriUriA uri;
UriParserStateA state;
state.uri = &uri;
std::string url;
// ensure we always have a scheme
if (pos_i == uri_s.end()) {
url.append(defaultScheme).append(prot_end).append(uri_s);
} else {
url = uri_s;
}
bool rval = uriParseUriA(&state, url.c_str()) == URI_SUCCESS;
if (rval) {
scheme_ = helper::fromRange(uri.scheme);
auto userInfo = helper::fromRange(uri.userInfo);
if (!userInfo.empty()) {
user_ = userInfo.substr(0, userInfo.find(':'));
password_ = userInfo.substr(userInfo.find(':') + 1);
}
host_ = helper::fromRange(uri.hostText);
port_ = helper::fromRange(uri.portText);
path_ = helper::fromList(uri.pathHead, "/");
query_ = helper::fromRange(uri.query);
fragment_ = helper::fromRange(uri.fragment);
}
uriFreeUriMembersA(&uri);
return rval;
#else
// do the manual implementation from stack overflow
// with some mods for the port
if (pos_i == uri_s.end()) {
if (defaultScheme.empty()) {
return false;
} else {
scheme_ = defaultScheme;
pos_i = uri_s.begin();
}
} else {
scheme_.reserve(distance(uri_s.begin(), pos_i));
transform(uri_s.begin(), pos_i, back_inserter(scheme_),
[](unsigned char c) { return tolower(c); }); // protocol is icase
advance(pos_i, prot_end.length());
}
string::const_iterator user_i = find(pos_i, uri_s.end(), '@');
string::const_iterator path_i;
if (user_i != uri_s.end()) {
string::const_iterator pwd_i = find(pos_i, user_i, ':');
if (pwd_i != user_i) {
password_.assign(pwd_i, user_i);
user_.assign(pos_i, pwd_i);
} else {
user_.assign(pos_i, user_i);
}
pos_i = user_i + 1;
}
path_i = find(pos_i, uri_s.end(), '/');
string::const_iterator port_i = find(pos_i, path_i, ':');
string::const_iterator host_end;
if (port_i != uri_s.end()) {
port_.assign(*port_i == ':' ? (port_i + 1) : port_i, path_i);
host_end = port_i;
} else {
host_end = path_i;
}
host_.reserve(distance(pos_i, host_end));
transform(pos_i, host_end, back_inserter(host_), [](unsigned char c) { return tolower(c); });
string::const_iterator query_i = find(path_i, uri_s.end(), '?');
path_.assign(*path_i == '/' ? (path_i + 1) : path_i, query_i);
if (query_i != uri_s.end()) ++query_i;
string::const_iterator frag_i = find(query_i, uri_s.end(), '#');
query_.assign(query_i, frag_i);
if (frag_i != uri_s.end()) {
fragment_.assign(frag_i, uri_s.end());
}
return true;
#endif
}
uri::~uri() noexcept {}
bool uri::is_valid() const noexcept { return isValid_; }
std::string uri::scheme() const noexcept { return scheme_; }
std::string uri::username() const noexcept { return user_; }
std::string uri::password() const noexcept { return password_; }
std::string uri::host() const noexcept { return host_; }
std::string uri::port() const noexcept { return port_; }
std::string uri::host_with_port() const {
std::string hostname = host();
if (!port().empty()) {
return hostname + ":" + port();
}
return hostname;
}
std::string uri::path() const noexcept { return path_; }
std::string uri::query() const noexcept { return query_; }
std::string uri::fragment() const noexcept { return fragment_; }
std::string uri::encode(const std::string &value) {
// TODO: test. Grabbed from stack overflow
ostringstream escaped;
escaped.fill('0');
escaped << hex;
for (string::const_iterator i = value.begin(), n = value.end(); i != n; ++i) {
string::value_type c = (*i);
// Keep alphanumeric and other accepted characters intact
if (isalnum(c) || c == '-' || c == '_' || c == '.' || c == '~') {
escaped << c;
continue;
}
// Any other characters are percent-encoded
escaped << uppercase;
escaped << '%' << setw(2) << int((unsigned char)c);
escaped << nouppercase;
}
return escaped.str();
}
std::string uri::decode(const std::string &value) {
// TODO: test. grabbed from stack overflow
char h;
ostringstream escaped;
escaped.fill('0');
for (auto i = value.begin(), n = value.end(); i != n; ++i) {
string::value_type c = (*i);
if (c == '%') {
if (i[1] && i[2]) {
h = helper::from_hex(i[1]) << 4 | helper::from_hex(i[2]);
escaped << h;
i += 2;
}
} else if (c == '+') {
escaped << ' ';
} else {
escaped << c;
}
}
return escaped.str();
}
} // namespace net
} // namespace coda
<commit_msg>Fix merge compile err<commit_after>
#include "uri.h"
#include <algorithm>
#include <iomanip>
#include <sstream>
#include <stdexcept>
#include <string>
#include <type_traits>
using namespace std;
namespace coda {
namespace net {
namespace helper {
#ifdef URIPARSER_FOUND
static std::string fromRange(const UriTextRangeA &rng) {
if (rng.first && rng.afterLast) {
return std::string(rng.first, rng.afterLast);
} else {
return std::string();
}
}
static std::string fromList(UriPathSegmentA *xs, const std::string &delim) {
UriPathSegmentStructA *head(xs);
std::string accum;
while (head) {
accum += delim + fromRange(head->text);
head = head->next;
}
return accum;
}
#endif
char from_hex(char ch) { return isdigit(ch) ? ch - '0' : tolower(ch) - 'a' + 10; }
} // namespace helper
uri::uri() noexcept : isValid_(false) {}
uri::uri(const std::string &uri, const std::string &defaultScheme) : uri_(uri) {
isValid_ = parse(uri, defaultScheme);
}
std::string uri::to_string() const noexcept { return uri_; }
uri::operator std::string() const noexcept { return uri_; }
std::string uri::full_path() const {
std::string temp = path();
if (!query().empty()) {
temp += '?';
temp += query_;
}
if (!fragment().empty()) {
temp += '#';
temp += fragment();
}
return temp;
}
bool uri::parse(const std::string &uri_s, const std::string &defaultScheme) {
static const string prot_end("://");
if (uri_s.empty()) {
return false;
}
string::const_iterator pos_i = search(uri_s.begin(), uri_s.end(), prot_end.begin(), prot_end.end());
#ifdef URIPARSER_FOUND
UriUriA uri;
UriParserStateA state;
state.uri = &uri;
std::string url;
// ensure we always have a scheme
if (pos_i == uri_s.end()) {
url.append(defaultScheme).append(prot_end).append(uri_s);
} else {
url = uri_s;
}
bool rval = uriParseUriA(&state, url.c_str()) == URI_SUCCESS;
if (rval) {
scheme_ = helper::fromRange(uri.scheme);
auto userInfo = helper::fromRange(uri.userInfo);
if (!userInfo.empty()) {
user_ = userInfo.substr(0, userInfo.find(':'));
password_ = userInfo.substr(userInfo.find(':') + 1);
}
host_ = helper::fromRange(uri.hostText);
port_ = helper::fromRange(uri.portText);
path_ = helper::fromList(uri.pathHead, "/");
query_ = helper::fromRange(uri.query);
fragment_ = helper::fromRange(uri.fragment);
}
uriFreeUriMembersA(&uri);
return rval;
#else
// do the manual implementation from stack overflow
// with some mods for the port
if (pos_i == uri_s.end()) {
if (defaultScheme.empty()) {
return false;
} else {
scheme_ = defaultScheme;
pos_i = uri_s.begin();
}
} else {
scheme_.reserve(distance(uri_s.begin(), pos_i));
transform(uri_s.begin(), pos_i, back_inserter(scheme_),
[](unsigned char c) { return tolower(c); }); // protocol is icase
advance(pos_i, prot_end.length());
}
string::const_iterator user_i = find(pos_i, uri_s.end(), '@');
string::const_iterator path_i;
if (user_i != uri_s.end()) {
string::const_iterator pwd_i = find(pos_i, user_i, ':');
if (pwd_i != user_i) {
password_.assign(pwd_i, user_i);
user_.assign(pos_i, pwd_i);
} else {
user_.assign(pos_i, user_i);
}
pos_i = user_i + 1;
}
path_i = find(pos_i, uri_s.end(), '/');
string::const_iterator port_i = find(pos_i, path_i, ':');
string::const_iterator host_end;
if (port_i != uri_s.end()) {
port_.assign(*port_i == ':' ? (port_i + 1) : port_i, path_i);
host_end = port_i;
} else {
host_end = path_i;
}
host_.reserve(distance(pos_i, host_end));
transform(pos_i, host_end, back_inserter(host_), [](unsigned char c) { return tolower(c); });
string::const_iterator query_i = find(path_i, uri_s.end(), '?');
path_.assign(*path_i == '/' ? (path_i + 1) : path_i, query_i);
if (query_i != uri_s.end()) ++query_i;
string::const_iterator frag_i = find(query_i, uri_s.end(), '#');
query_.assign(query_i, frag_i);
if (frag_i != uri_s.end()) {
fragment_.assign(frag_i, uri_s.end());
}
return true;
#endif
}
uri::~uri() noexcept {}
bool uri::is_valid() const noexcept { return isValid_; }
std::string uri::scheme() const noexcept { return scheme_; }
std::string uri::username() const noexcept { return user_; }
std::string uri::password() const noexcept { return password_; }
std::string uri::host() const noexcept { return host_; }
std::string uri::port() const noexcept { return port_; }
std::string uri::host_with_port() const {
std::string hostname = host();
if (!port().empty()) {
return hostname + ":" + port();
}
return hostname;
}
std::string uri::path() const noexcept { return path_; }
std::string uri::query() const noexcept { return query_; }
std::string uri::fragment() const noexcept { return fragment_; }
std::string uri::encode(const std::string &value) {
// TODO: test. Grabbed from stack overflow
ostringstream escaped;
escaped.fill('0');
escaped << hex;
for (string::const_iterator i = value.begin(), n = value.end(); i != n; ++i) {
string::value_type c = (*i);
// Keep alphanumeric and other accepted characters intact
if (isalnum(c) || c == '-' || c == '_' || c == '.' || c == '~') {
escaped << c;
continue;
}
// Any other characters are percent-encoded
escaped << uppercase;
escaped << '%' << setw(2) << int((unsigned char)c);
escaped << nouppercase;
}
return escaped.str();
}
std::string uri::decode(const std::string &value) {
// TODO: test. grabbed from stack overflow
char h;
ostringstream escaped;
escaped.fill('0');
for (auto i = value.begin(), n = value.end(); i != n; ++i) {
string::value_type c = (*i);
if (c == '%') {
if (i[1] && i[2]) {
h = helper::from_hex(i[1]) << 4 | helper::from_hex(i[2]);
escaped << h;
i += 2;
}
} else if (c == '+') {
escaped << ' ';
} else {
escaped << c;
}
}
return escaped.str();
}
} // namespace net
} // namespace coda
<|endoftext|> |
<commit_before>// Copyright 2011 Google Inc. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include "util.h"
#ifdef _WIN32
#include <windows.h>
#include <io.h>
#endif
#include <errno.h>
#include <fcntl.h>
#include <stdarg.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/stat.h>
#include <sys/types.h>
#ifndef _WIN32
#include <sys/time.h>
#endif
#include <vector>
#ifdef _WIN32
#include <direct.h> // _mkdir
#endif
#include "edit_distance.h"
#include "metrics.h"
void Fatal(const char* msg, ...) {
va_list ap;
fprintf(stderr, "ninja: FATAL: ");
va_start(ap, msg);
vfprintf(stderr, msg, ap);
va_end(ap);
fprintf(stderr, "\n");
#ifdef _WIN32
// On Windows, some tools may inject extra threads.
// exit() may block on locks held by those threads, so forcibly exit.
fflush(stderr);
fflush(stdout);
ExitProcess(1);
#else
exit(1);
#endif
}
void Warning(const char* msg, ...) {
va_list ap;
fprintf(stderr, "ninja: WARNING: ");
va_start(ap, msg);
vfprintf(stderr, msg, ap);
va_end(ap);
fprintf(stderr, "\n");
}
void Error(const char* msg, ...) {
va_list ap;
fprintf(stderr, "ninja: ERROR: ");
va_start(ap, msg);
vfprintf(stderr, msg, ap);
va_end(ap);
fprintf(stderr, "\n");
}
bool CanonicalizePath(string* path, string* err) {
METRIC_RECORD("canonicalize str");
int len = path->size();
char* str = 0;
if (len > 0)
str = &(*path)[0];
if (!CanonicalizePath(str, &len, err))
return false;
path->resize(len);
return true;
}
bool CanonicalizePath(char* path, int* len, string* err) {
// WARNING: this function is performance-critical; please benchmark
// any changes you make to it.
METRIC_RECORD("canonicalize path");
if (*len == 0) {
*err = "empty path";
return false;
}
const int kMaxPathComponents = 30;
char* components[kMaxPathComponents];
int component_count = 0;
char* start = path;
char* dst = start;
const char* src = start;
const char* end = start + *len;
if (*src == '/') {
++src;
++dst;
}
while (src < end) {
if (*src == '.') {
if (src[1] == '/' || src + 1 == end) {
// '.' component; eliminate.
src += 2;
continue;
} else if (src[1] == '.' && (src[2] == '/' || src + 2 == end)) {
// '..' component. Back up if possible.
if (component_count > 0) {
dst = components[component_count - 1];
src += 3;
--component_count;
} else {
*dst++ = *src++;
*dst++ = *src++;
*dst++ = *src++;
}
continue;
}
}
if (*src == '/') {
src++;
continue;
}
if (component_count == kMaxPathComponents)
Fatal("path has too many components");
components[component_count] = dst;
++component_count;
const char* sep = (const char*)memchr(src, '/', end - src);
if (sep == NULL)
sep = end;
while (src <= sep) {
*dst++ = *src++;
}
src = sep + 1;
}
if (dst == start) {
*err = "path canonicalizes to the empty path";
return false;
}
*len = dst - start - 1;
return true;
}
int MakeDir(const string& path) {
#ifdef _WIN32
return _mkdir(path.c_str());
#else
return mkdir(path.c_str(), 0777);
#endif
}
int ReadFile(const string& path, string* contents, string* err) {
FILE* f = fopen(path.c_str(), "r");
if (!f) {
err->assign(strerror(errno));
return -errno;
}
char buf[64 << 10];
size_t len;
while ((len = fread(buf, 1, sizeof(buf), f)) > 0) {
contents->append(buf, len);
}
if (ferror(f)) {
err->assign(strerror(errno)); // XXX errno?
contents->clear();
fclose(f);
return -errno;
}
fclose(f);
return 0;
}
void SetCloseOnExec(int fd) {
#ifndef _WIN32
int flags = fcntl(fd, F_GETFD);
if (flags < 0) {
perror("fcntl(F_GETFD)");
} else {
if (fcntl(fd, F_SETFD, flags | FD_CLOEXEC) < 0)
perror("fcntl(F_SETFD)");
}
#else
HANDLE hd = (HANDLE) _get_osfhandle(fd);
if (! SetHandleInformation(hd, HANDLE_FLAG_INHERIT, 0)) {
fprintf(stderr, "SetHandleInformation(): %s", GetLastErrorString().c_str());
}
#endif // ! _WIN32
}
int64_t GetTimeMillis() {
#ifdef _WIN32
// GetTickCount64 is only available on Vista or later.
return GetTickCount();
#else
timeval now;
gettimeofday(&now, NULL);
return ((int64_t)now.tv_sec * 1000) + (now.tv_usec / 1000);
#endif
}
const char* SpellcheckStringV(const string& text,
const vector<const char*>& words) {
const bool kAllowReplacements = true;
const int kMaxValidEditDistance = 3;
int min_distance = kMaxValidEditDistance + 1;
const char* result = NULL;
for (vector<const char*>::const_iterator i = words.begin();
i != words.end(); ++i) {
int distance = EditDistance(*i, text, kAllowReplacements,
kMaxValidEditDistance);
if (distance < min_distance) {
min_distance = distance;
result = *i;
}
}
return result;
}
const char* SpellcheckString(const string& text, ...) {
va_list ap;
va_start(ap, text);
vector<const char*> words;
const char* word;
while ((word = va_arg(ap, const char*)))
words.push_back(word);
return SpellcheckStringV(text, words);
}
#ifdef _WIN32
string GetLastErrorString() {
DWORD err = GetLastError();
char* msg_buf;
FormatMessageA(
FORMAT_MESSAGE_ALLOCATE_BUFFER |
FORMAT_MESSAGE_FROM_SYSTEM |
FORMAT_MESSAGE_IGNORE_INSERTS,
NULL,
err,
MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
(char*)&msg_buf,
0,
NULL);
string msg = msg_buf;
LocalFree(msg_buf);
return msg;
}
#endif
static bool islatinalpha(int c) {
// isalpha() is locale-dependent.
return (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z');
}
string StripAnsiEscapeCodes(const string& in) {
string stripped;
stripped.reserve(in.size());
for (size_t i = 0; i < in.size(); ++i) {
if (in[i] != '\33') {
// Not an escape code.
stripped.push_back(in[i]);
continue;
}
// Only strip CSIs for now.
if (i + 1 >= in.size()) break;
if (in[i + 1] != '[') continue; // Not a CSI.
i += 2;
// Skip everything up to and including the next [a-zA-Z].
while (i < in.size() && !islatinalpha(in[i]))
++i;
}
return stripped;
}
#ifdef _WIN32
static double GetLoadAverage_win32()
{
// TODO(nicolas.despres@gmail.com): Find a way to implement it on Windows.
return -0.0f;
}
#else
static double GetLoadAverage_unix()
{
double loadavg[3] = { 0.0f, 0.0f, 0.0f };
if (getloadavg(loadavg, 3) < 0)
{
// Maybe we should return an error here or the availability of
// getloadavg(3) should be checked when ninja is configured.
return -0.0f;
}
return loadavg[0];
}
#endif // _WIN32
double GetLoadAverage()
{
#ifdef _WIN32
return GetLoadAverage_win32();
#else
return GetLoadAverage_unix();
#endif // _WIN32
}
<commit_msg>Don't walk path components twice. Speeds up CanonicalizePath() 115ms (285ms -> 170ms).<commit_after>// Copyright 2011 Google Inc. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include "util.h"
#ifdef _WIN32
#include <windows.h>
#include <io.h>
#endif
#include <errno.h>
#include <fcntl.h>
#include <stdarg.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/stat.h>
#include <sys/types.h>
#ifndef _WIN32
#include <sys/time.h>
#endif
#include <vector>
#ifdef _WIN32
#include <direct.h> // _mkdir
#endif
#include "edit_distance.h"
#include "metrics.h"
void Fatal(const char* msg, ...) {
va_list ap;
fprintf(stderr, "ninja: FATAL: ");
va_start(ap, msg);
vfprintf(stderr, msg, ap);
va_end(ap);
fprintf(stderr, "\n");
#ifdef _WIN32
// On Windows, some tools may inject extra threads.
// exit() may block on locks held by those threads, so forcibly exit.
fflush(stderr);
fflush(stdout);
ExitProcess(1);
#else
exit(1);
#endif
}
void Warning(const char* msg, ...) {
va_list ap;
fprintf(stderr, "ninja: WARNING: ");
va_start(ap, msg);
vfprintf(stderr, msg, ap);
va_end(ap);
fprintf(stderr, "\n");
}
void Error(const char* msg, ...) {
va_list ap;
fprintf(stderr, "ninja: ERROR: ");
va_start(ap, msg);
vfprintf(stderr, msg, ap);
va_end(ap);
fprintf(stderr, "\n");
}
bool CanonicalizePath(string* path, string* err) {
METRIC_RECORD("canonicalize str");
int len = path->size();
char* str = 0;
if (len > 0)
str = &(*path)[0];
if (!CanonicalizePath(str, &len, err))
return false;
path->resize(len);
return true;
}
bool CanonicalizePath(char* path, int* len, string* err) {
// WARNING: this function is performance-critical; please benchmark
// any changes you make to it.
METRIC_RECORD("canonicalize path");
if (*len == 0) {
*err = "empty path";
return false;
}
const int kMaxPathComponents = 30;
char* components[kMaxPathComponents];
int component_count = 0;
char* start = path;
char* dst = start;
const char* src = start;
const char* end = start + *len;
if (*src == '/') {
++src;
++dst;
}
while (src < end) {
if (*src == '.') {
if (src[1] == '/' || src + 1 == end) {
// '.' component; eliminate.
src += 2;
continue;
} else if (src[1] == '.' && (src[2] == '/' || src + 2 == end)) {
// '..' component. Back up if possible.
if (component_count > 0) {
dst = components[component_count - 1];
src += 3;
--component_count;
} else {
*dst++ = *src++;
*dst++ = *src++;
*dst++ = *src++;
}
continue;
}
}
if (*src == '/') {
src++;
continue;
}
if (component_count == kMaxPathComponents)
Fatal("path has too many components");
components[component_count] = dst;
++component_count;
while (*src != '/' && src != end)
*dst++ = *src++;
*dst++ = *src++; // Copy '/' or final \0 character as well.
}
if (dst == start) {
*err = "path canonicalizes to the empty path";
return false;
}
*len = dst - start - 1;
return true;
}
int MakeDir(const string& path) {
#ifdef _WIN32
return _mkdir(path.c_str());
#else
return mkdir(path.c_str(), 0777);
#endif
}
int ReadFile(const string& path, string* contents, string* err) {
FILE* f = fopen(path.c_str(), "r");
if (!f) {
err->assign(strerror(errno));
return -errno;
}
char buf[64 << 10];
size_t len;
while ((len = fread(buf, 1, sizeof(buf), f)) > 0) {
contents->append(buf, len);
}
if (ferror(f)) {
err->assign(strerror(errno)); // XXX errno?
contents->clear();
fclose(f);
return -errno;
}
fclose(f);
return 0;
}
void SetCloseOnExec(int fd) {
#ifndef _WIN32
int flags = fcntl(fd, F_GETFD);
if (flags < 0) {
perror("fcntl(F_GETFD)");
} else {
if (fcntl(fd, F_SETFD, flags | FD_CLOEXEC) < 0)
perror("fcntl(F_SETFD)");
}
#else
HANDLE hd = (HANDLE) _get_osfhandle(fd);
if (! SetHandleInformation(hd, HANDLE_FLAG_INHERIT, 0)) {
fprintf(stderr, "SetHandleInformation(): %s", GetLastErrorString().c_str());
}
#endif // ! _WIN32
}
int64_t GetTimeMillis() {
#ifdef _WIN32
// GetTickCount64 is only available on Vista or later.
return GetTickCount();
#else
timeval now;
gettimeofday(&now, NULL);
return ((int64_t)now.tv_sec * 1000) + (now.tv_usec / 1000);
#endif
}
const char* SpellcheckStringV(const string& text,
const vector<const char*>& words) {
const bool kAllowReplacements = true;
const int kMaxValidEditDistance = 3;
int min_distance = kMaxValidEditDistance + 1;
const char* result = NULL;
for (vector<const char*>::const_iterator i = words.begin();
i != words.end(); ++i) {
int distance = EditDistance(*i, text, kAllowReplacements,
kMaxValidEditDistance);
if (distance < min_distance) {
min_distance = distance;
result = *i;
}
}
return result;
}
const char* SpellcheckString(const string& text, ...) {
va_list ap;
va_start(ap, text);
vector<const char*> words;
const char* word;
while ((word = va_arg(ap, const char*)))
words.push_back(word);
return SpellcheckStringV(text, words);
}
#ifdef _WIN32
string GetLastErrorString() {
DWORD err = GetLastError();
char* msg_buf;
FormatMessageA(
FORMAT_MESSAGE_ALLOCATE_BUFFER |
FORMAT_MESSAGE_FROM_SYSTEM |
FORMAT_MESSAGE_IGNORE_INSERTS,
NULL,
err,
MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
(char*)&msg_buf,
0,
NULL);
string msg = msg_buf;
LocalFree(msg_buf);
return msg;
}
#endif
static bool islatinalpha(int c) {
// isalpha() is locale-dependent.
return (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z');
}
string StripAnsiEscapeCodes(const string& in) {
string stripped;
stripped.reserve(in.size());
for (size_t i = 0; i < in.size(); ++i) {
if (in[i] != '\33') {
// Not an escape code.
stripped.push_back(in[i]);
continue;
}
// Only strip CSIs for now.
if (i + 1 >= in.size()) break;
if (in[i + 1] != '[') continue; // Not a CSI.
i += 2;
// Skip everything up to and including the next [a-zA-Z].
while (i < in.size() && !islatinalpha(in[i]))
++i;
}
return stripped;
}
#ifdef _WIN32
static double GetLoadAverage_win32()
{
// TODO(nicolas.despres@gmail.com): Find a way to implement it on Windows.
return -0.0f;
}
#else
static double GetLoadAverage_unix()
{
double loadavg[3] = { 0.0f, 0.0f, 0.0f };
if (getloadavg(loadavg, 3) < 0)
{
// Maybe we should return an error here or the availability of
// getloadavg(3) should be checked when ninja is configured.
return -0.0f;
}
return loadavg[0];
}
#endif // _WIN32
double GetLoadAverage()
{
#ifdef _WIN32
return GetLoadAverage_win32();
#else
return GetLoadAverage_unix();
#endif // _WIN32
}
<|endoftext|> |
<commit_before>/*****************************************************************************
*
* This file is part of Mapnik (c++ mapping toolkit)
*
* Copyright (C) 2006 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
*
*****************************************************************************/
//$Id: wkb.cpp 19 2005-03-22 13:53:27Z pavlenko $
#include <mapnik/global.hpp>
#include <mapnik/wkb.hpp>
#include <mapnik/geom_util.hpp>
#include <mapnik/feature.hpp>
// boost
#include <boost/utility.hpp>
#include <boost/detail/endian.hpp>
namespace mapnik
{
struct wkb_reader : boost::noncopyable
{
private:
enum wkbByteOrder {
wkbXDR=0,
wkbNDR=1
};
const char* wkb_;
unsigned size_;
unsigned pos_;
wkbByteOrder byteOrder_;
bool needSwap_;
wkbFormat format_;
public:
enum wkbGeometryType {
wkbPoint=1,
wkbLineString=2,
wkbPolygon=3,
wkbMultiPoint=4,
wkbMultiLineString=5,
wkbMultiPolygon=6,
wkbGeometryCollection=7
};
wkb_reader(const char* wkb,unsigned size,wkbFormat format)
: wkb_(wkb),
size_(size),
pos_(0),
format_(format)
{
switch (format_)
{
case wkbSpatiaLite:
byteOrder_ = (wkbByteOrder) wkb_[1];
pos_ = 39;
break;
case wkbGeneric:
default:
byteOrder_ = (wkbByteOrder) wkb_[0];
pos_ = 1;
break;
}
#ifndef MAPNIK_BIG_ENDIAN
needSwap_=byteOrder_?wkbXDR:wkbNDR;
#else
needSwap_=byteOrder_?wkbNDR:wkbXDR;
#endif
}
~wkb_reader() {}
void read_multi(Feature & feature)
{
int type=read_integer();
switch (type)
{
case wkbPoint:
read_point(feature);
break;
case wkbLineString:
read_linestring(feature);
break;
case wkbPolygon:
read_polygon(feature);
break;
case wkbMultiPoint:
read_multipoint(feature);
break;
case wkbMultiLineString:
read_multilinestring(feature);
break;
case wkbMultiPolygon:
read_multipolygon(feature);
break;
case wkbGeometryCollection:
break;
default:
break;
}
}
void read(Feature & feature)
{
int type=read_integer();
switch (type)
{
case wkbPoint:
read_point(feature);
break;
case wkbLineString:
read_linestring(feature);
break;
case wkbPolygon:
read_polygon(feature);
break;
case wkbMultiPoint:
read_multipoint_2(feature);
break;
case wkbMultiLineString:
read_multilinestring_2(feature);
break;
case wkbMultiPolygon:
read_multipolygon_2(feature);
break;
case wkbGeometryCollection:
break;
default:
break;
}
}
private:
int read_integer()
{
boost::int32_t n;
if (needSwap_)
{
read_int32_xdr(wkb_+pos_,n);
}
else
{
read_int32_ndr(wkb_+pos_,n);
}
pos_+=4;
return n;
}
double read_double()
{
double d;
if (needSwap_)
{
read_double_xdr(wkb_ + pos_, d);
}
else
{
read_double_ndr(wkb_ + pos_, d);
}
pos_+=8;
return d;
}
void read_coords(CoordinateArray& ar)
{
int size=sizeof(coord<double,2>)*ar.size();
if (!needSwap_)
{
std::memcpy(&ar[0],wkb_+pos_,size);
pos_+=size;
}
else
{
for (unsigned i=0;i<ar.size();++i)
{
read_double_xdr(wkb_ + pos_,ar[i].x);
read_double_xdr(wkb_ + pos_ + 8,ar[i].y);
pos_ += 16;
}
}
}
void read_point(Feature & feature)
{
geometry2d * pt = new point<vertex2d>;
double x = read_double();
double y = read_double();
pt->move_to(x,y);
feature.add_geometry(pt);
}
void read_multipoint(Feature & feature)
{
int num_points = read_integer();
for (int i=0;i<num_points;++i)
{
pos_+=5;
read_point(feature);
}
}
void read_multipoint_2(Feature & feature)
{
geometry2d * pt = new point<vertex2d>;
int num_points = read_integer();
for (int i=0;i<num_points;++i)
{
pos_+=5;
double x = read_double();
double y = read_double();
pt->move_to(x,y);
}
feature.add_geometry(pt);
}
void read_linestring(Feature & feature)
{
geometry2d * line = new line_string<vertex2d>;
int num_points=read_integer();
CoordinateArray ar(num_points);
read_coords(ar);
line->set_capacity(num_points);
line->move_to(ar[0].x,ar[0].y);
for (int i=1;i<num_points;++i)
{
line->line_to(ar[i].x,ar[i].y);
}
feature.add_geometry(line);
}
void read_multilinestring(Feature & feature)
{
int num_lines=read_integer();
for (int i=0;i<num_lines;++i)
{
pos_+=5;
read_linestring(feature);
}
}
void read_multilinestring_2(Feature & feature)
{
geometry2d * line = new line_string<vertex2d>;
int num_lines=read_integer();
unsigned capacity = 0;
for (int i=0;i<num_lines;++i)
{
pos_+=5;
int num_points=read_integer();
capacity+=num_points;
CoordinateArray ar(num_points);
read_coords(ar);
line->set_capacity(capacity);
line->move_to(ar[0].x,ar[0].y);
for (int i=1;i<num_points;++i)
{
line->line_to(ar[i].x,ar[i].y);
}
}
feature.add_geometry(line);
}
void read_polygon(Feature & feature)
{
geometry2d * poly = new polygon<vertex2d>;
int num_rings=read_integer();
unsigned capacity = 0;
for (int i=0;i<num_rings;++i)
{
int num_points=read_integer();
capacity+=num_points;
CoordinateArray ar(num_points);
read_coords(ar);
poly->set_capacity(capacity);
poly->move_to(ar[0].x,ar[0].y);
for (int j=1;j<num_points;++j)
{
poly->line_to(ar[j].x,ar[j].y);
}
}
feature.add_geometry(poly);
}
void read_multipolygon(Feature & feature)
{
int num_polys=read_integer();
for (int i=0;i<num_polys;++i)
{
pos_+=5;
read_polygon(feature);
}
}
void read_multipolygon_2(Feature & feature)
{
geometry2d * poly = new polygon<vertex2d>;
int num_polys=read_integer();
unsigned capacity = 0;
for (int i=0;i<num_polys;++i)
{
pos_+=5;
int num_rings=read_integer();
for (int i=0;i<num_rings;++i)
{
int num_points=read_integer();
capacity += num_points;
CoordinateArray ar(num_points);
read_coords(ar);
poly->set_capacity(capacity);
poly->move_to(ar[0].x,ar[0].y);
for (int j=1;j<num_points;++j)
{
poly->line_to(ar[j].x,ar[j].y);
}
poly->line_to(ar[0].x,ar[0].y);
}
}
feature.add_geometry(poly);
}
};
void geometry_utils::from_wkb (Feature & feature,
const char* wkb,
unsigned size,
bool multiple_geometries,
wkbFormat format)
{
wkb_reader reader(wkb,size,format);
if (multiple_geometries)
return reader.read_multi(feature);
else
return reader.read(feature);
}
}
<commit_msg>remove unneeded header<commit_after>/*****************************************************************************
*
* This file is part of Mapnik (c++ mapping toolkit)
*
* Copyright (C) 2006 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
*
*****************************************************************************/
//$Id: wkb.cpp 19 2005-03-22 13:53:27Z pavlenko $
#include <mapnik/global.hpp>
#include <mapnik/wkb.hpp>
#include <mapnik/geom_util.hpp>
#include <mapnik/feature.hpp>
// boost
#include <boost/utility.hpp>
namespace mapnik
{
struct wkb_reader : boost::noncopyable
{
private:
enum wkbByteOrder {
wkbXDR=0,
wkbNDR=1
};
const char* wkb_;
unsigned size_;
unsigned pos_;
wkbByteOrder byteOrder_;
bool needSwap_;
wkbFormat format_;
public:
enum wkbGeometryType {
wkbPoint=1,
wkbLineString=2,
wkbPolygon=3,
wkbMultiPoint=4,
wkbMultiLineString=5,
wkbMultiPolygon=6,
wkbGeometryCollection=7
};
wkb_reader(const char* wkb,unsigned size,wkbFormat format)
: wkb_(wkb),
size_(size),
pos_(0),
format_(format)
{
switch (format_)
{
case wkbSpatiaLite:
byteOrder_ = (wkbByteOrder) wkb_[1];
pos_ = 39;
break;
case wkbGeneric:
default:
byteOrder_ = (wkbByteOrder) wkb_[0];
pos_ = 1;
break;
}
#ifndef MAPNIK_BIG_ENDIAN
needSwap_=byteOrder_?wkbXDR:wkbNDR;
#else
needSwap_=byteOrder_?wkbNDR:wkbXDR;
#endif
}
~wkb_reader() {}
void read_multi(Feature & feature)
{
int type=read_integer();
switch (type)
{
case wkbPoint:
read_point(feature);
break;
case wkbLineString:
read_linestring(feature);
break;
case wkbPolygon:
read_polygon(feature);
break;
case wkbMultiPoint:
read_multipoint(feature);
break;
case wkbMultiLineString:
read_multilinestring(feature);
break;
case wkbMultiPolygon:
read_multipolygon(feature);
break;
case wkbGeometryCollection:
break;
default:
break;
}
}
void read(Feature & feature)
{
int type=read_integer();
switch (type)
{
case wkbPoint:
read_point(feature);
break;
case wkbLineString:
read_linestring(feature);
break;
case wkbPolygon:
read_polygon(feature);
break;
case wkbMultiPoint:
read_multipoint_2(feature);
break;
case wkbMultiLineString:
read_multilinestring_2(feature);
break;
case wkbMultiPolygon:
read_multipolygon_2(feature);
break;
case wkbGeometryCollection:
break;
default:
break;
}
}
private:
int read_integer()
{
boost::int32_t n;
if (needSwap_)
{
read_int32_xdr(wkb_+pos_,n);
}
else
{
read_int32_ndr(wkb_+pos_,n);
}
pos_+=4;
return n;
}
double read_double()
{
double d;
if (needSwap_)
{
read_double_xdr(wkb_ + pos_, d);
}
else
{
read_double_ndr(wkb_ + pos_, d);
}
pos_+=8;
return d;
}
void read_coords(CoordinateArray& ar)
{
int size=sizeof(coord<double,2>)*ar.size();
if (!needSwap_)
{
std::memcpy(&ar[0],wkb_+pos_,size);
pos_+=size;
}
else
{
for (unsigned i=0;i<ar.size();++i)
{
read_double_xdr(wkb_ + pos_,ar[i].x);
read_double_xdr(wkb_ + pos_ + 8,ar[i].y);
pos_ += 16;
}
}
}
void read_point(Feature & feature)
{
geometry2d * pt = new point<vertex2d>;
double x = read_double();
double y = read_double();
pt->move_to(x,y);
feature.add_geometry(pt);
}
void read_multipoint(Feature & feature)
{
int num_points = read_integer();
for (int i=0;i<num_points;++i)
{
pos_+=5;
read_point(feature);
}
}
void read_multipoint_2(Feature & feature)
{
geometry2d * pt = new point<vertex2d>;
int num_points = read_integer();
for (int i=0;i<num_points;++i)
{
pos_+=5;
double x = read_double();
double y = read_double();
pt->move_to(x,y);
}
feature.add_geometry(pt);
}
void read_linestring(Feature & feature)
{
geometry2d * line = new line_string<vertex2d>;
int num_points=read_integer();
CoordinateArray ar(num_points);
read_coords(ar);
line->set_capacity(num_points);
line->move_to(ar[0].x,ar[0].y);
for (int i=1;i<num_points;++i)
{
line->line_to(ar[i].x,ar[i].y);
}
feature.add_geometry(line);
}
void read_multilinestring(Feature & feature)
{
int num_lines=read_integer();
for (int i=0;i<num_lines;++i)
{
pos_+=5;
read_linestring(feature);
}
}
void read_multilinestring_2(Feature & feature)
{
geometry2d * line = new line_string<vertex2d>;
int num_lines=read_integer();
unsigned capacity = 0;
for (int i=0;i<num_lines;++i)
{
pos_+=5;
int num_points=read_integer();
capacity+=num_points;
CoordinateArray ar(num_points);
read_coords(ar);
line->set_capacity(capacity);
line->move_to(ar[0].x,ar[0].y);
for (int i=1;i<num_points;++i)
{
line->line_to(ar[i].x,ar[i].y);
}
}
feature.add_geometry(line);
}
void read_polygon(Feature & feature)
{
geometry2d * poly = new polygon<vertex2d>;
int num_rings=read_integer();
unsigned capacity = 0;
for (int i=0;i<num_rings;++i)
{
int num_points=read_integer();
capacity+=num_points;
CoordinateArray ar(num_points);
read_coords(ar);
poly->set_capacity(capacity);
poly->move_to(ar[0].x,ar[0].y);
for (int j=1;j<num_points;++j)
{
poly->line_to(ar[j].x,ar[j].y);
}
}
feature.add_geometry(poly);
}
void read_multipolygon(Feature & feature)
{
int num_polys=read_integer();
for (int i=0;i<num_polys;++i)
{
pos_+=5;
read_polygon(feature);
}
}
void read_multipolygon_2(Feature & feature)
{
geometry2d * poly = new polygon<vertex2d>;
int num_polys=read_integer();
unsigned capacity = 0;
for (int i=0;i<num_polys;++i)
{
pos_+=5;
int num_rings=read_integer();
for (int i=0;i<num_rings;++i)
{
int num_points=read_integer();
capacity += num_points;
CoordinateArray ar(num_points);
read_coords(ar);
poly->set_capacity(capacity);
poly->move_to(ar[0].x,ar[0].y);
for (int j=1;j<num_points;++j)
{
poly->line_to(ar[j].x,ar[j].y);
}
poly->line_to(ar[0].x,ar[0].y);
}
}
feature.add_geometry(poly);
}
};
void geometry_utils::from_wkb (Feature & feature,
const char* wkb,
unsigned size,
bool multiple_geometries,
wkbFormat format)
{
wkb_reader reader(wkb,size,format);
if (multiple_geometries)
return reader.read_multi(feature);
else
return reader.read(feature);
}
}
<|endoftext|> |
<commit_before>#include"xml.hpp"
Xml::Xml(){
}
bool Xml::open(const QString filename){
if(!QFile::exists(filename)) return false;
this->filename = filename;
return true;
}
bool Xml::save(){
return true;
}
<commit_msg>xmlパースのopen部分を書いた<commit_after>#include"xml.hpp"
Xml::Xml(){
}
bool Xml::open(const QString filename){
if(!QFile::exists(filename)) return false;
this->filename = filename;
QDomDocument doc;
QString error;int errorline;int errorColmun;
QString rootTagName = "MCSwitch_Env";
QFile f(this->filename);
if(f.open(QIODevice::ReadOnly)){
//fail to open file.
return false;
}
if(!doc.setContent(&f,true,&error,&errorline,&errorColmun)){
//fail to set content.
return false;
}
QDomElement root = doc.documentElement();
if(root.tagName().toStdString() != rootTagName){
return false;
}
QDomNode node = root.firstChild();
while(!node.isNull()){
if(node.toElement().tagName().toStdString() == "name"){
}
else if(node.toElement().tagName().toStdString() == "version"){
}
else if(node.toElement().tagName().toStdString() == "mods"){
}
else if(node.toElement().tagName().toStdString() == "comment"){
}
else{
}
}
return true;
}
bool Xml::save(){
return true;
}
<|endoftext|> |
<commit_before>//
// Capture.cpp : Capture events to a window.
//
#include "stdafx.h"
#include "Capture.h"
#include "vtdata/vtLog.h"
// Class statics
std::map <void*, Capture*> Capture::registry;
Capture::Capture(void* winId)
{
_ok = false;
_winId = winId;
registry.insert(std::pair<void*, Capture*>(_winId, this));
}
void Capture::init()
{
// install an event filter on the widget
_oldWndProc = (WNDPROC)SetWindowLong((HWND)_winId, GWL_WNDPROC, (LONG) s_wndProc);
_ok = true;
}
Capture::~Capture()
{
if(_ok)
SetWindowLong((HWND)_winId, GWL_WNDPROC, (LONG) _oldWndProc);
}
LRESULT CALLBACK Capture::s_wndProc(HWND hWnd, UINT uMsg,
WPARAM wParam, LPARAM lParam)
{
std::map <void*, Capture*>::iterator p;
p = registry.find( (void*)hWnd );
if( p == registry.end() )
return DefWindowProc( hWnd, uMsg, wParam, lParam );
else
return p->second->wndProc( hWnd, uMsg, wParam, lParam );
}
LRESULT CALLBACK Capture::wndProc(HWND hWnd, UINT iMsg,
WPARAM wParam, LPARAM lParam)
{
#if 1
VTLOG("Capture sees %3d (0x%04x)", iMsg, iMsg);
if (iMsg == WM_MOVE) VTLOG1(" (WM_MOVE)");
if (iMsg == WM_SETFOCUS) VTLOG1(" (WM_SETFOCUS)");
if (iMsg == WM_SETCURSOR) VTLOG1(" (WM_SETCURSOR)");
if (iMsg == WM_MOUSEMOVE) VTLOG1(" (WM_MOUSEMOVE)");
if (iMsg == WM_NCHITTEST) VTLOG1(" (WM_NCHITTEST)");
if (iMsg == WM_SHOWWINDOW) VTLOG1(" (WM_SHOWWINDOW)");
if (iMsg == WM_NCPAINT) VTLOG1(" (WM_NCPAINT)");
if (iMsg == WM_SIZE) VTLOG1(" (WM_SIZE)");
if (iMsg == WM_TIMER) VTLOG1(" (WM_TIMER)");
if (iMsg == WM_PAINT) VTLOG1(" (WM_PAINT)");
if (iMsg == WM_ERASEBKGND) VTLOG1(" (WM_ERASEBKGND)");
if (iMsg == WM_WINDOWPOSCHANGING) VTLOG1(" (WM_WINDOWPOSCHANGING)");
if (iMsg == WM_WINDOWPOSCHANGED) VTLOG1(" (WM_WINDOWPOSCHANGED)");
if (iMsg == WM_IME_SETCONTEXT) VTLOG1(" (WM_IME_SETCONTEXT)");
if (iMsg == WM_LBUTTONDOWN) VTLOG1(" (WM_LBUTTONDOWN)");
if (iMsg == WM_LBUTTONUP) VTLOG1(" (WM_LBUTTONUP)");
VTLOG1("\n");
#endif
int x = LOWORD( lParam );
int y = HIWORD( lParam );
UINT flags = static_cast<UINT>(wParam);
switch ( iMsg )
{
case WM_PAINT:
//VTLOG1("Capture sees WM_PAINT\n");
// try to validate the whole window so we don't keep getting PAINT msgs
//ValidateRect(hWnd, NULL);
//return 0;
// return DefWindowProc( hWnd, iMsg, wParam, lParam );
break;
//case WM_DRAW:
// VTLOG1("Capture sees WM_DRAW\n");
// break;
//case WM_IDLE:
// VTLOG1("Capture sees WM_IDLE\n");
// break;
case WM_TIMER:
//VTLOG1("Capture sees WM_TIMER\n");
break;
case WM_LBUTTONDOWN:
//VTLOG1("Capture sees WM_LBUTTONDOWN\n");
OnLButtonDown(flags, x, y);
break;
case WM_MBUTTONDOWN:
OnMButtonDown(flags, x, y);
break;
case WM_RBUTTONDOWN:
OnRButtonDown(flags, x, y);
break;
case WM_LBUTTONUP:
//VTLOG1("Capture sees WM_LBUTTONUP\n");
OnLButtonUp(flags, x, y);
break;
case WM_MBUTTONUP:
OnMButtonUp(flags, x, y);
break;
case WM_RBUTTONUP:
OnRButtonUp(flags, x, y);
break;
case WM_MOUSEMOVE:
if(x > 32768) x -= 65536;
if(y > 32768) y -= 65536;
OnMouseMove(flags, x, y);
break;
case WM_MOUSEWHEEL:
{
// VTLOG1("WM_MOUSEWHEEL\n");
short zDelta = HIWORD(wParam);
}
break;
// Many other potential events could be caught here.
case WM_NCLBUTTONUP:
case WM_NCMBUTTONUP:
case WM_NCRBUTTONUP:
//::ReleaseCapture();
break;
//case WM_LBUTTONDBLCLK:
//case WM_CONTEXTMENU:
//{
// // prevent the context menu from showing up, except when right clicking
// int x = LOWORD( lParam );
// int y = HIWORD( lParam );
// if( ( fabs(x() - (1.0f/w->width())*m->x()) < 1.e-3) && ( fabs(y() - (1.0f/w->height())*m->y()) < 1.e-3) )
// return false;
// else
// return true;
//}
//break;
default:
break;
}
return CallWindowProc(_oldWndProc, hWnd, iMsg, wParam, lParam);
}
<commit_msg>turned off some excessive logging<commit_after>//
// Capture.cpp : Capture events to a window.
//
#include "stdafx.h"
#include "Capture.h"
#include "vtdata/vtLog.h"
// Class statics
std::map <void*, Capture*> Capture::registry;
Capture::Capture(void* winId)
{
_ok = false;
_winId = winId;
registry.insert(std::pair<void*, Capture*>(_winId, this));
}
void Capture::init()
{
// install an event filter on the widget
_oldWndProc = (WNDPROC)SetWindowLong((HWND)_winId, GWL_WNDPROC, (LONG) s_wndProc);
_ok = true;
}
Capture::~Capture()
{
if(_ok)
SetWindowLong((HWND)_winId, GWL_WNDPROC, (LONG) _oldWndProc);
}
LRESULT CALLBACK Capture::s_wndProc(HWND hWnd, UINT uMsg,
WPARAM wParam, LPARAM lParam)
{
std::map <void*, Capture*>::iterator p;
p = registry.find( (void*)hWnd );
if( p == registry.end() )
return DefWindowProc( hWnd, uMsg, wParam, lParam );
else
return p->second->wndProc( hWnd, uMsg, wParam, lParam );
}
LRESULT CALLBACK Capture::wndProc(HWND hWnd, UINT iMsg,
WPARAM wParam, LPARAM lParam)
{
#if _DEBUG
VTLOG("Capture sees %3d (0x%04x)", iMsg, iMsg);
if (iMsg == WM_MOVE) VTLOG1(" (WM_MOVE)");
if (iMsg == WM_SETFOCUS) VTLOG1(" (WM_SETFOCUS)");
if (iMsg == WM_SETCURSOR) VTLOG1(" (WM_SETCURSOR)");
if (iMsg == WM_MOUSEMOVE) VTLOG1(" (WM_MOUSEMOVE)");
if (iMsg == WM_NCHITTEST) VTLOG1(" (WM_NCHITTEST)");
if (iMsg == WM_SHOWWINDOW) VTLOG1(" (WM_SHOWWINDOW)");
if (iMsg == WM_NCPAINT) VTLOG1(" (WM_NCPAINT)");
if (iMsg == WM_SIZE) VTLOG1(" (WM_SIZE)");
if (iMsg == WM_TIMER) VTLOG1(" (WM_TIMER)");
if (iMsg == WM_PAINT) VTLOG1(" (WM_PAINT)");
if (iMsg == WM_ERASEBKGND) VTLOG1(" (WM_ERASEBKGND)");
if (iMsg == WM_WINDOWPOSCHANGING) VTLOG1(" (WM_WINDOWPOSCHANGING)");
if (iMsg == WM_WINDOWPOSCHANGED) VTLOG1(" (WM_WINDOWPOSCHANGED)");
if (iMsg == WM_IME_SETCONTEXT) VTLOG1(" (WM_IME_SETCONTEXT)");
if (iMsg == WM_LBUTTONDOWN) VTLOG1(" (WM_LBUTTONDOWN)");
if (iMsg == WM_LBUTTONUP) VTLOG1(" (WM_LBUTTONUP)");
VTLOG1("\n");
#endif
int x = LOWORD( lParam );
int y = HIWORD( lParam );
UINT flags = static_cast<UINT>(wParam);
switch ( iMsg )
{
case WM_PAINT:
//VTLOG1("Capture sees WM_PAINT\n");
// try to validate the whole window so we don't keep getting PAINT msgs
//ValidateRect(hWnd, NULL);
//return 0;
// return DefWindowProc( hWnd, iMsg, wParam, lParam );
break;
//case WM_DRAW:
// VTLOG1("Capture sees WM_DRAW\n");
// break;
//case WM_IDLE:
// VTLOG1("Capture sees WM_IDLE\n");
// break;
case WM_TIMER:
//VTLOG1("Capture sees WM_TIMER\n");
break;
case WM_LBUTTONDOWN:
//VTLOG1("Capture sees WM_LBUTTONDOWN\n");
OnLButtonDown(flags, x, y);
break;
case WM_MBUTTONDOWN:
OnMButtonDown(flags, x, y);
break;
case WM_RBUTTONDOWN:
OnRButtonDown(flags, x, y);
break;
case WM_LBUTTONUP:
//VTLOG1("Capture sees WM_LBUTTONUP\n");
OnLButtonUp(flags, x, y);
break;
case WM_MBUTTONUP:
OnMButtonUp(flags, x, y);
break;
case WM_RBUTTONUP:
OnRButtonUp(flags, x, y);
break;
case WM_MOUSEMOVE:
if(x > 32768) x -= 65536;
if(y > 32768) y -= 65536;
OnMouseMove(flags, x, y);
break;
case WM_MOUSEWHEEL:
{
// VTLOG1("WM_MOUSEWHEEL\n");
short zDelta = HIWORD(wParam);
}
break;
// Many other potential events could be caught here.
case WM_NCLBUTTONUP:
case WM_NCMBUTTONUP:
case WM_NCRBUTTONUP:
//::ReleaseCapture();
break;
//case WM_LBUTTONDBLCLK:
//case WM_CONTEXTMENU:
//{
// // prevent the context menu from showing up, except when right clicking
// int x = LOWORD( lParam );
// int y = HIWORD( lParam );
// if( ( fabs(x() - (1.0f/w->width())*m->x()) < 1.e-3) && ( fabs(y() - (1.0f/w->height())*m->y()) < 1.e-3) )
// return false;
// else
// return true;
//}
//break;
default:
break;
}
return CallWindowProc(_oldWndProc, hWnd, iMsg, wParam, lParam);
}
<|endoftext|> |
<commit_before>#include <ros/ros.h>
#include "map_creator/WorkSpace.h"
#include "H5Cpp.h"
#include <hdf5.h>
using namespace H5;
using namespace std;
#define POSES_DATASETNAME "poses_dataset"
#define SPHERE_DATASETNAME "sphere_dataset"
#define POSE_GROUPNAME "/Poses"
#define SPHERE_GROUPNAME "/Spheres"
#define RANK_OUT 2
class loadHD5{
public:
void h5ToMultiMapPoses(const hid_t dataset, multimap<vector<double>, vector<double> >& PoseColFilter)
{
hsize_t dims_out[2], count[2], offset[2];
hid_t dataspace = H5Dget_space (dataset); /* dataspace handle */
int rank = H5Sget_simple_extent_ndims (dataspace);
herr_t status_n = H5Sget_simple_extent_dims (dataspace, dims_out, NULL);
herr_t status;
int chunk_size, chunk_itr;
if (dims_out[0]%10)
{
chunk_itr=11;
}
else
{
chunk_itr=10;
}
chunk_size=(dims_out[0]/10);
offset[0] = 0;
for(int it=0;it<chunk_itr;it++)
{
offset[1] = 0;
if ((dims_out[0]-(chunk_size*it))/chunk_size != 0){
count[0] = chunk_size;
offset[0] = chunk_size*it;
}
else{
count[0] = (dims_out[0]-(chunk_size*it));
offset[0] = count[0];
}
count[1] = 10;
double data_out[count[0]][count[1]];
status = H5Sselect_hyperslab (dataspace, H5S_SELECT_SET, offset, NULL,
count, NULL);
hsize_t dimsm[2];
dimsm[0] = count[0];
dimsm[1] = count[1];
hid_t memspace;
memspace = H5Screate_simple (RANK_OUT, dimsm, NULL);
status = H5Dread (dataset, H5T_NATIVE_DOUBLE, memspace, dataspace,
H5P_DEFAULT, data_out);
for(int i=0;i<count[0];i++){
vector<double> sphereCenter;
vector<double> Poses;
for(int j=0;j<3;j++)
{
sphereCenter.push_back(data_out[i][j]);
}
for(int k=3;k<10;k++)
{
Poses.push_back(data_out[i][k]);
}
PoseColFilter.insert(pair<vector<double>, vector<double> >(sphereCenter, Poses));
}
}
}
void h5ToMultiMapSpheres(const hid_t dataset, multimap<vector<double>, double >& SphereCol){
hsize_t dims_out[2], count[2], offset[2], dimsm[2];
hid_t dataspace = H5Dget_space (dataset); /* dataspace handle */
int rank = H5Sget_simple_extent_ndims (dataspace);
herr_t status_n = H5Sget_simple_extent_dims (dataspace, dims_out, NULL);
herr_t status;
offset[0] = 0;
offset[1] = 0;
count[0] = dims_out[0];
count[1] = 4;
double data_out[count[0]][count[1]];
status = H5Sselect_hyperslab (dataspace, H5S_SELECT_SET, offset, NULL,
count, NULL);
dimsm[0] = count[0];
dimsm[1] = count[1];
hid_t memspace;
memspace = H5Screate_simple (RANK_OUT, dimsm, NULL);
status = H5Dread (dataset, H5T_NATIVE_DOUBLE, memspace, dataspace,
H5P_DEFAULT, data_out);
for(int i=0;i<count[0];i++){
vector<double> sphereCenter;
double ri;
for(int j=0;j<3;j++)
{
sphereCenter.push_back(data_out[i][j]);
}
for(int k=3;k<4;k++)
{
ri = data_out[i][k];
}
SphereCol.insert(pair<vector<double>, double >(sphereCenter, ri));
}
}
};
int main(int argc, char **argv)
{
if (argc<2){
ROS_ERROR_STREAM("Please provide the name of the reachability map. If you have not created it yet, Please create the map by running the create reachability map launch file in map_creator");
return 1;
}
else{
ros::init(argc, argv, "workspace");
ros::NodeHandle n;
ros::Publisher workspace_pub = n.advertise<map_creator::WorkSpace>("reachability_map", 1);
ros::Rate loop_rate(10);
int count = 0;
time_t startit,finish;
time (&startit);
const char* FILE = argv[1];
hid_t file, poses_group, poses_dataset, sphere_group, sphere_dataset, attr;
file = H5Fopen (FILE, H5F_ACC_RDONLY, H5P_DEFAULT);
//Poses dataset
poses_group = H5Gopen (file, POSE_GROUPNAME, H5P_DEFAULT);
poses_dataset = H5Dopen (poses_group, POSES_DATASETNAME, H5P_DEFAULT);
multimap<vector<double>, vector<double> > PoseColFilter;
loadHD5 hd5;
hd5.h5ToMultiMapPoses(poses_dataset, PoseColFilter);
//Sphere dataset
sphere_group = H5Gopen (file, SPHERE_GROUPNAME, H5P_DEFAULT);
sphere_dataset = H5Dopen (sphere_group, SPHERE_DATASETNAME, H5P_DEFAULT);
multimap<vector<double>, double > SphereCol;
hd5.h5ToMultiMapSpheres(sphere_dataset, SphereCol);
//Resolution Attribute
float res;
attr = H5Aopen(sphere_dataset,"Resolution",H5P_DEFAULT);
herr_t ret = H5Aread(attr, H5T_NATIVE_FLOAT, &res);
//Closing resources
H5Aclose(attr);
H5Dclose(poses_dataset);
H5Dclose(sphere_dataset);
H5Gclose(poses_group);
H5Gclose(sphere_group);
H5Fclose(file);
//Creating messages
map_creator::WorkSpace ws;
ws.header.stamp = ros::Time::now();
ws.header.frame_id = "/base_link";
ws.resolution = res;
for (multimap<vector<double>, double >::iterator it = SphereCol.begin();it != SphereCol.end();++it){
map_creator::WsSphere wss;
wss.point.x = it->first[0];
wss.point.y = it->first[1];
wss.point.z = it->first[2];
wss.ri = it->second;
multimap<vector<double>, vector<double> >::iterator it1;
for(it1 = PoseColFilter.lower_bound(it->first); it1 !=PoseColFilter.upper_bound(it->first); ++it1){
geometry_msgs::Pose pp;
pp.position.x = it1->second[0];
pp.position.y = it1->second[1];
pp.position.z = it1->second[2];
pp.orientation.x = it1->second[3];
pp.orientation.y = it1->second[4];
pp.orientation.z = it1->second[5];
pp.orientation.w = it1->second[6];
wss.poses.push_back(pp);
}
ws.WsSpheres.push_back(wss);
}
while (ros::ok())
{
workspace_pub.publish(ws);
ros::spinOnce();
sleep(5);
++count;
}
}
return 0;
}
<commit_msg>Update load_reachability_map.cpp<commit_after>#include <ros/ros.h>
#include "map_creator/WorkSpace.h"
#include "H5Cpp.h"
#include <hdf5.h>
using namespace H5;
using namespace std;
#define POSES_DATASETNAME "poses_dataset"
#define SPHERE_DATASETNAME "sphere_dataset"
#define POSE_GROUPNAME "/Poses"
#define SPHERE_GROUPNAME "/Spheres"
#define RANK_OUT 2
class loadHD5{
public:
void h5ToMultiMapPoses(const hid_t dataset, multimap<vector<double>, vector<double> >& PoseColFilter)
{
hsize_t dims_out[2], count[2], offset[2];
hid_t dataspace = H5Dget_space (dataset); /* dataspace handle */
int rank = H5Sget_simple_extent_ndims (dataspace);
herr_t status_n = H5Sget_simple_extent_dims (dataspace, dims_out, NULL);
herr_t status;
int chunk_size, chunk_itr;
if (dims_out[0]%10)
{
chunk_itr=11;
}
else
{
chunk_itr=10;
}
chunk_size=(dims_out[0]/10);
offset[0] = 0;
for(int it=0;it<chunk_itr;it++)
{
offset[1] = 0;
if ((dims_out[0]-(chunk_size*it))/chunk_size != 0){
count[0] = chunk_size;
offset[0] = chunk_size*it;
}
else{
count[0] = (dims_out[0]-(chunk_size*it));
offset[0] = count[0];
}
count[1] = 10;
double data_out[count[0]][count[1]];
status = H5Sselect_hyperslab (dataspace, H5S_SELECT_SET, offset, NULL,
count, NULL);
hsize_t dimsm[2];
dimsm[0] = count[0];
dimsm[1] = count[1];
hid_t memspace;
memspace = H5Screate_simple (RANK_OUT, dimsm, NULL);
status = H5Dread (dataset, H5T_NATIVE_DOUBLE, memspace, dataspace,
H5P_DEFAULT, data_out);
for(int i=0;i<count[0];i++){
vector<double> sphereCenter;
vector<double> Poses;
for(int j=0;j<3;j++)
{
sphereCenter.push_back(data_out[i][j]);
}
for(int k=3;k<10;k++)
{
Poses.push_back(data_out[i][k]);
}
PoseColFilter.insert(pair<vector<double>, vector<double> >(sphereCenter, Poses));
}
}
}
void h5ToMultiMapSpheres(const hid_t dataset, multimap<vector<double>, double >& SphereCol){
hsize_t dims_out[2], count[2], offset[2], dimsm[2];
hid_t dataspace = H5Dget_space (dataset); /* dataspace handle */
int rank = H5Sget_simple_extent_ndims (dataspace);
herr_t status_n = H5Sget_simple_extent_dims (dataspace, dims_out, NULL);
herr_t status;
offset[0] = 0;
offset[1] = 0;
count[0] = dims_out[0];
count[1] = 4;
double data_out[count[0]][count[1]];
status = H5Sselect_hyperslab (dataspace, H5S_SELECT_SET, offset, NULL,
count, NULL);
dimsm[0] = count[0];
dimsm[1] = count[1];
hid_t memspace;
memspace = H5Screate_simple (RANK_OUT, dimsm, NULL);
status = H5Dread (dataset, H5T_NATIVE_DOUBLE, memspace, dataspace,
H5P_DEFAULT, data_out);
for(int i=0;i<count[0];i++){
vector<double> sphereCenter;
double ri;
for(int j=0;j<3;j++)
{
sphereCenter.push_back(data_out[i][j]);
}
for(int k=3;k<4;k++)
{
ri = data_out[i][k];
}
SphereCol.insert(pair<vector<double>, double >(sphereCenter, ri));
}
}
};
int main(int argc, char **argv)
{
if (argc<2){
ROS_ERROR_STREAM("Please provide the name of the reachability map. If you have not created it yet, Please create the map by running the create reachability map launch file in map_creator");
return 1;
}
else{
ros::init(argc, argv, "workspace");
ros::NodeHandle n;
//TODO: It can be published as a latched topic. So the whole message will be published just once and stay on the topic
ros::Publisher workspace_pub = n.advertise<map_creator::WorkSpace>("reachability_map", 1);
//bool latchOn = 1;
//ros::Publisher workspace_pub = n.advertise<map_creator::WorkSpace>("reachability_map", 1, latchOn);
ros::Rate loop_rate(10);
int count = 0;
time_t startit,finish;
time (&startit);
const char* FILE = argv[1];
hid_t file, poses_group, poses_dataset, sphere_group, sphere_dataset, attr;
file = H5Fopen (FILE, H5F_ACC_RDONLY, H5P_DEFAULT);
//Poses dataset
poses_group = H5Gopen (file, POSE_GROUPNAME, H5P_DEFAULT);
poses_dataset = H5Dopen (poses_group, POSES_DATASETNAME, H5P_DEFAULT);
multimap<vector<double>, vector<double> > PoseColFilter;
loadHD5 hd5;
hd5.h5ToMultiMapPoses(poses_dataset, PoseColFilter);
//Sphere dataset
sphere_group = H5Gopen (file, SPHERE_GROUPNAME, H5P_DEFAULT);
sphere_dataset = H5Dopen (sphere_group, SPHERE_DATASETNAME, H5P_DEFAULT);
multimap<vector<double>, double > SphereCol;
hd5.h5ToMultiMapSpheres(sphere_dataset, SphereCol);
//Resolution Attribute
float res;
attr = H5Aopen(sphere_dataset,"Resolution",H5P_DEFAULT);
herr_t ret = H5Aread(attr, H5T_NATIVE_FLOAT, &res);
//Closing resources
H5Aclose(attr);
H5Dclose(poses_dataset);
H5Dclose(sphere_dataset);
H5Gclose(poses_group);
H5Gclose(sphere_group);
H5Fclose(file);
//Creating messages
map_creator::WorkSpace ws;
ws.header.stamp = ros::Time::now();
ws.header.frame_id = "/base_link";
ws.resolution = res;
for (multimap<vector<double>, double >::iterator it = SphereCol.begin();it != SphereCol.end();++it){
map_creator::WsSphere wss;
wss.point.x = it->first[0];
wss.point.y = it->first[1];
wss.point.z = it->first[2];
wss.ri = it->second;
multimap<vector<double>, vector<double> >::iterator it1;
for(it1 = PoseColFilter.lower_bound(it->first); it1 !=PoseColFilter.upper_bound(it->first); ++it1){
geometry_msgs::Pose pp;
pp.position.x = it1->second[0];
pp.position.y = it1->second[1];
pp.position.z = it1->second[2];
pp.orientation.x = it1->second[3];
pp.orientation.y = it1->second[4];
pp.orientation.z = it1->second[5];
pp.orientation.w = it1->second[6];
wss.poses.push_back(pp);
}
ws.WsSpheres.push_back(wss);
}
while (ros::ok())
{
workspace_pub.publish(ws);
ros::spinOnce();
sleep(5);
++count;
}
}
return 0;
}
<|endoftext|> |
<commit_before>// @(#)root/gl:$Name: $:$Id: TRootOIViewer.cxx,v 1.2 2001/05/14 16:27:39 brun Exp $
// Author: Valery Fine & Fons Rademakers 5/10/2000 and 28/4/2001
/*************************************************************************
* Copyright (C) 1995-2001, Rene Brun and Fons Rademakers. *
* All rights reserved. *
* *
* For the licensing terms see $ROOTSYS/LICENSE. *
* For the list of contributors see $ROOTSYS/README/CREDITS. *
*************************************************************************/
//////////////////////////////////////////////////////////////////////////
// //
// TRootOIViewer //
// //
// This class creates a toplevel window and an OpenInventor //
// drawing area and context using the ROOT native GUI. //
// //
// Open Inventor can be downloaded from //
// ftp://oss.sgi.com/projects/inventor/download/ //
// //
// Free version of OpenGL API: //
// http://sourceforge.net/project/showfiles.php?group_id=3 //
// //
//////////////////////////////////////////////////////////////////////////
#include <Inventor/Xt/SoXt.h>
#include <Inventor/Xt/viewers/SoXtExaminerViewer.h>
#include <Inventor/actions/SoGetBoundingBoxAction.h>
#include <Inventor/nodes/SoSeparator.h>
#include <Inventor/nodes/SoCallback.h>
#include <Inventor/nodes/SoMaterial.h>
#include <Inventor/elements/SoCacheElement.h>
#include <X11/IntrinsicP.h>
#include "TRootOIViewer.h"
#include "TGClient.h"
#include "TGCanvas.h"
#include "TGMsgBox.h"
#include "TVirtualX.h"
#include "TROOT.h"
#include "TError.h"
#include "Buttons.h"
#include "TVirtualPad.h"
#include "TPadOpenGLView.h"
#include "TView.h"
#include "TVirtualGL.h"
#include "TColor.h"
#include "TSystem.h"
XtAppContext TRootOIViewer::fgAppContext = 0;
//______________________________________________________________________________
void InventorCallback(void *d, SoAction *action)
{
// OpenInventor call back function.
if (!d) return;
TRootOIViewer *currentViewer = (TRootOIViewer *)d;
if (currentViewer) {
if (action->isOfType(SoGLRenderAction::getClassTypeId())) {
SoCacheElement::invalidate(action->getState());
// gVirtualGL->SetRootLight(kFALSE);
glEnable(GL_COLOR_MATERIAL);
currentViewer->Paint("");
glDisable(GL_COLOR_MATERIAL);
} else if (action->isOfType(SoGetBoundingBoxAction::getClassTypeId())) {
// define the default range
Float_t minBound[3]={-1000,-1000,-1000};
Float_t maxBound[3]={ 1000, 1000, 1000};
// pick the "real" range provided by TPad object
currentViewer->GetGLView()->GetPad()->GetView()->GetRange(minBound,maxBound);
if (minBound[0] == maxBound[0])
SoCacheElement::invalidate(action->getState());
((SoGetBoundingBoxAction *)action)->
extendBy(SbBox3f(minBound[0],minBound[1],minBound[2]
,maxBound[0],maxBound[2],maxBound[2])
);
}
}
}
//////////////////////////////////////////////////////////////////////////
// //
// TSoXtEventHandler //
// //
// All X events that are not for any of the windows under the control //
// of the ROOT GUI are forwarded by this class to Xt. //
// //
//////////////////////////////////////////////////////////////////////////
class TSoXtEventHandler : public TGUnknownWindowHandler {
private:
TRootOIViewer *fViewer; // pointer back to viewer imp
public:
TSoXtEventHandler(TRootOIViewer *c) { fViewer = c; }
Bool_t HandleEvent(Event_t *)
{ return SoXt::dispatchEvent((XEvent *)gVirtualX->GetNativeEvent()); }
};
//////////////////////////////////////////////////////////////////////////
// //
// TXtTimerHandler //
// //
// Check every 100 ms if there is an Xt timer event to be processed. //
// This is the best we can do since there is no way to get access to //
// the Xt timer queue. //
// //
//////////////////////////////////////////////////////////////////////////
class TXtTimerHandler : public TTimer {
public:
TXtTimerHandler() : TTimer(100) { }
Bool_t Notify();
};
Bool_t TXtTimerHandler::Notify()
{
XtInputMask m = XtAppPending(TRootOIViewer::fgAppContext);
if ((m & XtIMTimer))
XtAppProcessEvent(TRootOIViewer::fgAppContext, XtIMTimer);
Reset();
return kTRUE;
}
//////////////////////////////////////////////////////////////////////////
// //
// TOIContainer //
// //
// Utility class used by TRootOIViewer. The TOIContainer is the frame //
// embedded in the TGCanvas widget. The OI graphics goes into this //
// frame. This class is used to enable input events on this graphics //
// frame and forward the events to the TRootOIViewer handlers. //
// //
//////////////////////////////////////////////////////////////////////////
class TOIContainer : public TGCompositeFrame {
private:
TRootOIViewer *fViewer; // pointer back to viewer imp
public:
TOIContainer(TRootOIViewer *c, Window_t id, const TGWindow *parent);
Bool_t HandleButton(Event_t *)
{ return SoXt::dispatchEvent((XEvent *)gVirtualX->GetNativeEvent()); }
Bool_t HandleConfigureNotify(Event_t *ev)
{ TGFrame::HandleConfigureNotify(ev);
return SoXt::dispatchEvent((XEvent *)gVirtualX->GetNativeEvent()); }
Bool_t HandleKey(Event_t *)
{ return SoXt::dispatchEvent((XEvent *)gVirtualX->GetNativeEvent()); }
Bool_t HandleMotion(Event_t *)
{ return SoXt::dispatchEvent((XEvent *)gVirtualX->GetNativeEvent()); }
Bool_t HandleExpose(Event_t *)
{ return SoXt::dispatchEvent((XEvent *)gVirtualX->GetNativeEvent()); }
};
//______________________________________________________________________________
TOIContainer::TOIContainer(TRootOIViewer *c, Window_t id, const TGWindow *p)
: TGCompositeFrame(gClient, id, p)
{
// Create a canvas container.
fViewer = c;
}
//ClassImp(TRootOIViewer)
//______________________________________________________________________________
TRootOIViewer::TRootOIViewer(TPadOpenGLView *pad, const char *title, UInt_t width, UInt_t height)
: TGMainFrame(gClient->GetRoot(), width, height)
{
// Create a ROOT OpenInventor viewer.
fGLView = pad;
CreateViewer(title);
Resize(width, height);
SetDrawList(0);
}
//______________________________________________________________________________
TRootOIViewer::TRootOIViewer(TPadOpenGLView *pad, const char *title, Int_t x, Int_t y, UInt_t width, UInt_t height)
: TGMainFrame(gClient->GetRoot(), width, height)
{
// Create a ROOT OpenInventor viewer.
fGLView = pad;
CreateViewer(title);
MoveResize(x, y, width, height);
SetWMPosition(x, y);
SetDrawList(0);
}
//______________________________________________________________________________
TRootOIViewer::~TRootOIViewer()
{
// Delete ROOT OpenInventor viewer.
SafeDelete(fInventorViewer);
DeleteContext();
fClient->RemoveUnknownWindowHandler(fSoXtHandler);
delete fSoXtHandler;
delete fXtTimerHandler;
delete fCanvasContainer;
delete fCanvasWindow;
delete fCanvasLayout;
}
//______________________________________________________________________________
void TRootOIViewer::CreateViewer(const char *title)
{
// Create the actual canvas.
fInventorViewer = 0;
fPaint = kTRUE;
fTopLevel = 0;
// Create canvas and canvas container to host the OpenInventor graphics
fCanvasWindow = new TGCanvas(this, GetWidth()+4, GetHeight()+4,
kSunkenFrame | kDoubleBorder);
InitXt();
if (!fTopLevel) {
fCanvasContainer = 0;
fCanvasLayout = 0;
return;
}
fCanvasContainer = new TOIContainer(this, XtWindow(fTopLevel),
fCanvasWindow->GetViewPort());
fCanvasWindow->SetContainer(fCanvasContainer);
fCanvasLayout = new TGLayoutHints(kLHintsExpandX | kLHintsExpandY);
AddFrame(fCanvasWindow, fCanvasLayout);
SoXt::init(fTopLevel);
fRootNode = new SoSeparator;
fRootNode->ref();
fGLNode = new SoSeparator;
fMaterial = new SoMaterial;
// fMaterial->shininess = 100.;
// fMaterial->ambientColor.setValue(0.9, 0.1, 0.0);
// fMaterial->diffuseColor.setValue(0.5,0.2,0.5);
// fMaterial->transparency = 0.8;
fRootCallback = new SoCallback;
fRootCallback->setCallback(InventorCallback, this);
fSoXtHandler = new TSoXtEventHandler(this);
fClient->AddUnknownWindowHandler(fSoXtHandler);
fXtTimerHandler = new TXtTimerHandler;
fXtTimerHandler->TurnOn();
fGLNode->addChild(fMaterial);
fGLNode->addChild(fRootCallback);
fRootNode->addChild(fGLNode);
SoInput viewDecor;
const char *fileDecor = "root.iv";
if (!gSystem->AccessPathName(fileDecor) && viewDecor.openFile(fileDecor)) {
SoSeparator *extraObjects = SoDB::readAll(&viewDecor);
if (extraObjects) {
fRootNode->addChild(extraObjects);
}
}
fInventorViewer = new SoXtExaminerViewer(fTopLevel);
fInventorViewer->setSceneGraph(fRootNode);
fInventorViewer->setTitle(title);
fInventorViewer->setSize(SbVec2s((short)GetWidth(), (short)GetHeight()));
// Pick the background color
TVirtualPad *thisPad = fGLView->GetPad();
if (thisPad) {
Color_t color = thisPad->GetFillColor();
TColor *background = gROOT->GetColor(color);
if (background) {
float rgb[3];
background->GetRGB(rgb[0],rgb[1],rgb[2]);
fInventorViewer->setBackgroundColor(SbColor(rgb));
}
}
fInventorViewer->show();
//SoXt::show(fTopLevel);
InitGLWindow();
// Misc
SetWindowName(title);
SetIconName(title);
SetClassHints("OIViewer", "OIViewer");
SetMWMHints(kMWMDecorAll, kMWMFuncAll, kMWMInputModeless);
MapSubwindows();
// we need to use GetDefaultSize() to initialize the layout algorithm...
Resize(GetDefaultSize());
Show();
}
//______________________________________________________________________________
void TRootOIViewer::InitXt()
{
// Initialize Xt.
fDpy = (Display *) gVirtualX->GetDisplay();
if (!fgAppContext) {
XtToolkitInitialize();
fgAppContext = XtCreateApplicationContext();
int argc = 0;
XtDisplayInitialize(fgAppContext, fDpy, 0, "Inventor", 0, 0, &argc, 0);
}
int xval, yval;
unsigned int wval, hval, border, depth;
Window root, wind = (Window) fCanvasWindow->GetViewPort()->GetId();
XGetGeometry(fDpy, wind, &root, &xval, &yval, &wval, &hval, &border, &depth);
//fTopLevel = XtAppCreateShell(0, "Inventor", applicationShellWidgetClass,
fTopLevel = XtAppCreateShell(0, "Inventor", topLevelShellWidgetClass,
fDpy, 0, 0);
// reparent fTopLevel into the ROOT GUI hierarchy
XtResizeWidget(fTopLevel, 100, 100, 0);
XtSetMappedWhenManaged(fTopLevel, False);
XtRealizeWidget(fTopLevel);
XSync(fDpy, False); // I want all windows to be created now
XReparentWindow(fDpy, XtWindow(fTopLevel), wind, xval, yval);
XtSetMappedWhenManaged(fTopLevel, True);
Arg reqargs[20];
Cardinal nargs = 0;
XtSetArg(reqargs[nargs], XtNx, xval); nargs++;
XtSetArg(reqargs[nargs], XtNy, yval); nargs++;
XtSetArg(reqargs[nargs], XtNwidth, wval); nargs++;
XtSetArg(reqargs[nargs], XtNheight, hval); nargs++;
//XtSetArg(reqargs[nargs], "mappedWhenManaged", False); nargs++;
XtSetValues(fTopLevel, reqargs, nargs);
XtRealizeWidget(fTopLevel);
}
//______________________________________________________________________________
void TRootOIViewer::InitGLWindow()
{
// Initialize GL window.
if (fInventorViewer) {
gVirtualGL->SetTrueColorMode();
}
}
//______________________________________________________________________________
void TRootOIViewer::DeleteGLWindow()
{
// X11 specific code to delete GL window.
// fGLWin is destroyed when parent is destroyed.
}
//______________________________________________________________________________
void TRootOIViewer::CloseWindow()
{
// In case window is closed via WM we get here.
delete fGLView; // this in turn will delete this object
fGLView = 0;
}
//______________________________________________________________________________
void TRootOIViewer::CreateContext()
{
// Create OpenGL context.
}
//______________________________________________________________________________
void TRootOIViewer::DeleteContext()
{
// Delete OpenGL context.
}
//______________________________________________________________________________
void TRootOIViewer::SwapBuffers()
{
// Swap two GL buffers
}
//______________________________________________________________________________
void TRootOIViewer::Paint(Option_t *)
{
// Paint scene.
MakeCurrent();
gVirtualGL->RunGLList(1+4);
}
//______________________________________________________________________________
void TRootOIViewer::MakeCurrent()
{
// Set this GL context the current one.
glXMakeCurrent(fInventorViewer->getDisplay(),
fInventorViewer->getNormalWindow(),
fInventorViewer->getNormalContext());
}
<commit_msg>From Philippe: This prevents a crash when starting an OpenInventor windows starting from a 1D canvas.<commit_after>// @(#)root/gl:$Name: $:$Id: TRootOIViewer.cxx,v 1.3 2003/08/29 10:42:18 rdm Exp $
// Author: Valery Fine & Fons Rademakers 5/10/2000 and 28/4/2001
/*************************************************************************
* Copyright (C) 1995-2001, Rene Brun and Fons Rademakers. *
* All rights reserved. *
* *
* For the licensing terms see $ROOTSYS/LICENSE. *
* For the list of contributors see $ROOTSYS/README/CREDITS. *
*************************************************************************/
//////////////////////////////////////////////////////////////////////////
// //
// TRootOIViewer //
// //
// This class creates a toplevel window and an OpenInventor //
// drawing area and context using the ROOT native GUI. //
// //
// Open Inventor can be downloaded from //
// ftp://oss.sgi.com/projects/inventor/download/ //
// //
// Free version of OpenGL API: //
// http://sourceforge.net/project/showfiles.php?group_id=3 //
// //
//////////////////////////////////////////////////////////////////////////
#include <Inventor/Xt/SoXt.h>
#include <Inventor/Xt/viewers/SoXtExaminerViewer.h>
#include <Inventor/actions/SoGetBoundingBoxAction.h>
#include <Inventor/nodes/SoSeparator.h>
#include <Inventor/nodes/SoCallback.h>
#include <Inventor/nodes/SoMaterial.h>
#include <Inventor/elements/SoCacheElement.h>
#include <X11/IntrinsicP.h>
#include "TRootOIViewer.h"
#include "TGClient.h"
#include "TGCanvas.h"
#include "TGMsgBox.h"
#include "TVirtualX.h"
#include "TROOT.h"
#include "TError.h"
#include "Buttons.h"
#include "TVirtualPad.h"
#include "TPadOpenGLView.h"
#include "TView.h"
#include "TVirtualGL.h"
#include "TColor.h"
#include "TSystem.h"
XtAppContext TRootOIViewer::fgAppContext = 0;
//______________________________________________________________________________
void InventorCallback(void *d, SoAction *action)
{
// OpenInventor call back function.
if (!d) return;
TRootOIViewer *currentViewer = (TRootOIViewer *)d;
if (currentViewer) {
if (action->isOfType(SoGLRenderAction::getClassTypeId())) {
SoCacheElement::invalidate(action->getState());
// gVirtualGL->SetRootLight(kFALSE);
glEnable(GL_COLOR_MATERIAL);
currentViewer->Paint("");
glDisable(GL_COLOR_MATERIAL);
} else if (action->isOfType(SoGetBoundingBoxAction::getClassTypeId())) {
// define the default range
Float_t minBound[3]={-1000,-1000,-1000};
Float_t maxBound[3]={ 1000, 1000, 1000};
// pick the "real" range provided by TPad object
TView *view = currentViewer->GetGLView()->GetPad()->GetView();
if (view) {
view->GetRange(minBound,maxBound);
if (minBound[0] == maxBound[0])
SoCacheElement::invalidate(action->getState());
}
((SoGetBoundingBoxAction *)action)->
extendBy(SbBox3f(minBound[0],minBound[1],minBound[2]
,maxBound[0],maxBound[2],maxBound[2])
);
}
}
}
//////////////////////////////////////////////////////////////////////////
// //
// TSoXtEventHandler //
// //
// All X events that are not for any of the windows under the control //
// of the ROOT GUI are forwarded by this class to Xt. //
// //
//////////////////////////////////////////////////////////////////////////
class TSoXtEventHandler : public TGUnknownWindowHandler {
private:
TRootOIViewer *fViewer; // pointer back to viewer imp
public:
TSoXtEventHandler(TRootOIViewer *c) { fViewer = c; }
Bool_t HandleEvent(Event_t *)
{ return SoXt::dispatchEvent((XEvent *)gVirtualX->GetNativeEvent()); }
};
//////////////////////////////////////////////////////////////////////////
// //
// TXtTimerHandler //
// //
// Check every 100 ms if there is an Xt timer event to be processed. //
// This is the best we can do since there is no way to get access to //
// the Xt timer queue. //
// //
//////////////////////////////////////////////////////////////////////////
class TXtTimerHandler : public TTimer {
public:
TXtTimerHandler() : TTimer(100) { }
Bool_t Notify();
};
Bool_t TXtTimerHandler::Notify()
{
XtInputMask m = XtAppPending(TRootOIViewer::fgAppContext);
if ((m & XtIMTimer))
XtAppProcessEvent(TRootOIViewer::fgAppContext, XtIMTimer);
Reset();
return kTRUE;
}
//////////////////////////////////////////////////////////////////////////
// //
// TOIContainer //
// //
// Utility class used by TRootOIViewer. The TOIContainer is the frame //
// embedded in the TGCanvas widget. The OI graphics goes into this //
// frame. This class is used to enable input events on this graphics //
// frame and forward the events to the TRootOIViewer handlers. //
// //
//////////////////////////////////////////////////////////////////////////
class TOIContainer : public TGCompositeFrame {
private:
TRootOIViewer *fViewer; // pointer back to viewer imp
public:
TOIContainer(TRootOIViewer *c, Window_t id, const TGWindow *parent);
Bool_t HandleButton(Event_t *)
{ return SoXt::dispatchEvent((XEvent *)gVirtualX->GetNativeEvent()); }
Bool_t HandleConfigureNotify(Event_t *ev)
{ TGFrame::HandleConfigureNotify(ev);
return SoXt::dispatchEvent((XEvent *)gVirtualX->GetNativeEvent()); }
Bool_t HandleKey(Event_t *)
{ return SoXt::dispatchEvent((XEvent *)gVirtualX->GetNativeEvent()); }
Bool_t HandleMotion(Event_t *)
{ return SoXt::dispatchEvent((XEvent *)gVirtualX->GetNativeEvent()); }
Bool_t HandleExpose(Event_t *)
{ return SoXt::dispatchEvent((XEvent *)gVirtualX->GetNativeEvent()); }
};
//______________________________________________________________________________
TOIContainer::TOIContainer(TRootOIViewer *c, Window_t id, const TGWindow *p)
: TGCompositeFrame(gClient, id, p)
{
// Create a canvas container.
fViewer = c;
}
//ClassImp(TRootOIViewer)
//______________________________________________________________________________
TRootOIViewer::TRootOIViewer(TPadOpenGLView *pad, const char *title, UInt_t width, UInt_t height)
: TGMainFrame(gClient->GetRoot(), width, height)
{
// Create a ROOT OpenInventor viewer.
fGLView = pad;
CreateViewer(title);
Resize(width, height);
SetDrawList(0);
}
//______________________________________________________________________________
TRootOIViewer::TRootOIViewer(TPadOpenGLView *pad, const char *title, Int_t x, Int_t y, UInt_t width, UInt_t height)
: TGMainFrame(gClient->GetRoot(), width, height)
{
// Create a ROOT OpenInventor viewer.
fGLView = pad;
CreateViewer(title);
MoveResize(x, y, width, height);
SetWMPosition(x, y);
SetDrawList(0);
}
//______________________________________________________________________________
TRootOIViewer::~TRootOIViewer()
{
// Delete ROOT OpenInventor viewer.
SafeDelete(fInventorViewer);
DeleteContext();
fClient->RemoveUnknownWindowHandler(fSoXtHandler);
delete fSoXtHandler;
delete fXtTimerHandler;
delete fCanvasContainer;
delete fCanvasWindow;
delete fCanvasLayout;
}
//______________________________________________________________________________
void TRootOIViewer::CreateViewer(const char *title)
{
// Create the actual canvas.
fInventorViewer = 0;
fPaint = kTRUE;
fTopLevel = 0;
// Create canvas and canvas container to host the OpenInventor graphics
fCanvasWindow = new TGCanvas(this, GetWidth()+4, GetHeight()+4,
kSunkenFrame | kDoubleBorder);
InitXt();
if (!fTopLevel) {
fCanvasContainer = 0;
fCanvasLayout = 0;
return;
}
fCanvasContainer = new TOIContainer(this, XtWindow(fTopLevel),
fCanvasWindow->GetViewPort());
fCanvasWindow->SetContainer(fCanvasContainer);
fCanvasLayout = new TGLayoutHints(kLHintsExpandX | kLHintsExpandY);
AddFrame(fCanvasWindow, fCanvasLayout);
SoXt::init(fTopLevel);
fRootNode = new SoSeparator;
fRootNode->ref();
fGLNode = new SoSeparator;
fMaterial = new SoMaterial;
// fMaterial->shininess = 100.;
// fMaterial->ambientColor.setValue(0.9, 0.1, 0.0);
// fMaterial->diffuseColor.setValue(0.5,0.2,0.5);
// fMaterial->transparency = 0.8;
fRootCallback = new SoCallback;
fRootCallback->setCallback(InventorCallback, this);
fSoXtHandler = new TSoXtEventHandler(this);
fClient->AddUnknownWindowHandler(fSoXtHandler);
fXtTimerHandler = new TXtTimerHandler;
fXtTimerHandler->TurnOn();
fGLNode->addChild(fMaterial);
fGLNode->addChild(fRootCallback);
fRootNode->addChild(fGLNode);
SoInput viewDecor;
const char *fileDecor = "root.iv";
if (!gSystem->AccessPathName(fileDecor) && viewDecor.openFile(fileDecor)) {
SoSeparator *extraObjects = SoDB::readAll(&viewDecor);
if (extraObjects) {
fRootNode->addChild(extraObjects);
}
}
fInventorViewer = new SoXtExaminerViewer(fTopLevel);
fInventorViewer->setSceneGraph(fRootNode);
fInventorViewer->setTitle(title);
fInventorViewer->setSize(SbVec2s((short)GetWidth(), (short)GetHeight()));
// Pick the background color
TVirtualPad *thisPad = fGLView->GetPad();
if (thisPad) {
Color_t color = thisPad->GetFillColor();
TColor *background = gROOT->GetColor(color);
if (background) {
float rgb[3];
background->GetRGB(rgb[0],rgb[1],rgb[2]);
fInventorViewer->setBackgroundColor(SbColor(rgb));
}
}
fInventorViewer->show();
//SoXt::show(fTopLevel);
InitGLWindow();
// Misc
SetWindowName(title);
SetIconName(title);
SetClassHints("OIViewer", "OIViewer");
SetMWMHints(kMWMDecorAll, kMWMFuncAll, kMWMInputModeless);
MapSubwindows();
// we need to use GetDefaultSize() to initialize the layout algorithm...
Resize(GetDefaultSize());
Show();
}
//______________________________________________________________________________
void TRootOIViewer::InitXt()
{
// Initialize Xt.
fDpy = (Display *) gVirtualX->GetDisplay();
if (!fgAppContext) {
XtToolkitInitialize();
fgAppContext = XtCreateApplicationContext();
int argc = 0;
XtDisplayInitialize(fgAppContext, fDpy, 0, "Inventor", 0, 0, &argc, 0);
}
int xval, yval;
unsigned int wval, hval, border, depth;
Window root, wind = (Window) fCanvasWindow->GetViewPort()->GetId();
XGetGeometry(fDpy, wind, &root, &xval, &yval, &wval, &hval, &border, &depth);
//fTopLevel = XtAppCreateShell(0, "Inventor", applicationShellWidgetClass,
fTopLevel = XtAppCreateShell(0, "Inventor", topLevelShellWidgetClass,
fDpy, 0, 0);
// reparent fTopLevel into the ROOT GUI hierarchy
XtResizeWidget(fTopLevel, 100, 100, 0);
XtSetMappedWhenManaged(fTopLevel, False);
XtRealizeWidget(fTopLevel);
XSync(fDpy, False); // I want all windows to be created now
XReparentWindow(fDpy, XtWindow(fTopLevel), wind, xval, yval);
XtSetMappedWhenManaged(fTopLevel, True);
Arg reqargs[20];
Cardinal nargs = 0;
XtSetArg(reqargs[nargs], XtNx, xval); nargs++;
XtSetArg(reqargs[nargs], XtNy, yval); nargs++;
XtSetArg(reqargs[nargs], XtNwidth, wval); nargs++;
XtSetArg(reqargs[nargs], XtNheight, hval); nargs++;
//XtSetArg(reqargs[nargs], "mappedWhenManaged", False); nargs++;
XtSetValues(fTopLevel, reqargs, nargs);
XtRealizeWidget(fTopLevel);
}
//______________________________________________________________________________
void TRootOIViewer::InitGLWindow()
{
// Initialize GL window.
if (fInventorViewer) {
gVirtualGL->SetTrueColorMode();
}
}
//______________________________________________________________________________
void TRootOIViewer::DeleteGLWindow()
{
// X11 specific code to delete GL window.
// fGLWin is destroyed when parent is destroyed.
}
//______________________________________________________________________________
void TRootOIViewer::CloseWindow()
{
// In case window is closed via WM we get here.
delete fGLView; // this in turn will delete this object
fGLView = 0;
}
//______________________________________________________________________________
void TRootOIViewer::CreateContext()
{
// Create OpenGL context.
}
//______________________________________________________________________________
void TRootOIViewer::DeleteContext()
{
// Delete OpenGL context.
}
//______________________________________________________________________________
void TRootOIViewer::SwapBuffers()
{
// Swap two GL buffers
}
//______________________________________________________________________________
void TRootOIViewer::Paint(Option_t *)
{
// Paint scene.
MakeCurrent();
gVirtualGL->RunGLList(1+4);
}
//______________________________________________________________________________
void TRootOIViewer::MakeCurrent()
{
// Set this GL context the current one.
glXMakeCurrent(fInventorViewer->getDisplay(),
fInventorViewer->getNormalWindow(),
fInventorViewer->getNormalContext());
}
<|endoftext|> |
<commit_before>#include <QtGui/QTransform>
#include <QtCore/QStringList>
#include "constants.h"
#include "worldModel.h"
#include "src/engine/items/wallItem.h"
#include "src/engine/items/colorFieldItem.h"
#include "src/engine/items/ellipseItem.h"
#include "src/engine/items/stylusItem.h"
using namespace twoDModel;
using namespace model;
#ifdef D2_MODEL_FRAMES_DEBUG
#include <QtWidgets/QGraphicsPathItem>
QGraphicsPathItem *debugPath = nullptr;
#endif
WorldModel::WorldModel()
{
}
int WorldModel::sonarReading(QPointF const &position, qreal direction) const
{
int maxSonarRangeCms = 255;
int minSonarRangeCms = 0;
int currentRangeInCm = (minSonarRangeCms + maxSonarRangeCms) / 2;
QPainterPath const wallPath = buildWallPath();
if (!checkSonarDistance(maxSonarRangeCms, position, direction, wallPath)) {
return maxSonarRangeCms;
}
for ( ; minSonarRangeCms < maxSonarRangeCms;
currentRangeInCm = (minSonarRangeCms + maxSonarRangeCms) / 2)
{
if (checkSonarDistance(currentRangeInCm, position, direction, wallPath)) {
maxSonarRangeCms = currentRangeInCm;
} else {
minSonarRangeCms = currentRangeInCm + 1;
}
}
return currentRangeInCm;
}
bool WorldModel::checkSonarDistance(int const distance, QPointF const &position
, qreal const direction, QPainterPath const &wallPath) const
{
QPainterPath const rayPath = sonarScanningRegion(position, direction, distance);
return rayPath.intersects(wallPath);
}
QPainterPath WorldModel::sonarScanningRegion(QPointF const &position, int range) const
{
return sonarScanningRegion(position, 0, range);
}
QPainterPath WorldModel::sonarScanningRegion(QPointF const &position, qreal direction, int range) const
{
qreal const rayWidthDegrees = 10.0;
qreal const rangeInPixels = range * pixelsInCm;
QPainterPath rayPath;
rayPath.arcTo(QRect(-rangeInPixels, -rangeInPixels
, 2 * rangeInPixels, 2 * rangeInPixels)
, -direction - rayWidthDegrees, 2 * rayWidthDegrees);
rayPath.closeSubpath();
QTransform const sensorPositionTransform = QTransform().translate(position.x(), position.y());
return sensorPositionTransform.map(rayPath);
}
bool WorldModel::checkCollision(QPainterPath const &path) const
{
#ifdef D2_MODEL_FRAMES_DEBUG
delete debugPath;
QPainterPath commonPath = buildWallPath();
commonPath.addPath(path);
debugPath = new QGraphicsPathItem(commonPath);
debugPath->setBrush(Qt::red);
debugPath->setPen(QPen(QColor(Qt::blue)));
q debugPath->setZValue(100);
QGraphicsScene * const scene = mWalls.isEmpty()
? (mColorFields.isEmpty() ? nullptr : mColorFields[0]->scene())
: mWalls[0]->scene();
if (scene) {
scene->addItem(debugPath);
scene->update();
}
#endif
return buildWallPath().intersects(path);
}
QList<items::WallItem *> const &WorldModel::walls() const
{
return mWalls;
}
void WorldModel::addWall(items::WallItem *wall)
{
mWalls.append(wall);
emit wallAdded(wall);
}
void WorldModel::removeWall(items::WallItem *wall)
{
mWalls.removeOne(wall);
emit itemRemoved(wall);
}
QList<items::ColorFieldItem *> const &WorldModel::colorFields() const
{
return mColorFields;
}
int WorldModel::wallsCount() const
{
return mWalls.count();
}
items::WallItem *WorldModel::wallAt(int index) const
{
return mWalls[index];
}
void WorldModel::addColorField(items::ColorFieldItem *colorField)
{
mColorFields.append(colorField);
emit colorItemAdded(colorField);
}
void WorldModel::removeColorField(items::ColorFieldItem *colorField)
{
mColorFields.removeOne(colorField);
emit itemRemoved(colorField);
}
void WorldModel::clear()
{
while (!mWalls.isEmpty()) {
removeWall(mWalls.last());
}
while (!mColorFields.isEmpty()) {
removeColorField(mColorFields.last());
}
clearRobotTrace();
}
void WorldModel::appendRobotTrace(QPen const &pen, QPointF const &begin, QPointF const &end)
{
if (pen.color() == QColor(Qt::transparent)) {
return;
}
QGraphicsLineItem * const traceItem = new QGraphicsLineItem(QLineF(begin, end));
traceItem->setPen(pen);
if (mRobotTrace.isEmpty()) {
emit robotTraceAppearedOrDisappeared(true);
}
mRobotTrace << traceItem;
emit otherItemAdded(traceItem);
}
void WorldModel::clearRobotTrace()
{
while (!mRobotTrace.isEmpty()) {
QGraphicsLineItem * const toRemove = mRobotTrace.first();
mRobotTrace.removeOne(toRemove);
emit itemRemoved(toRemove);
}
emit robotTraceAppearedOrDisappeared(false);
}
QPainterPath WorldModel::buildWallPath() const
{
/// @todo Maintain a cache for this.
QPainterPath wallPath;
for (items::WallItem *wall : mWalls) {
wallPath.addPath(wall->path());
}
return wallPath;
}
QDomElement WorldModel::serialize(QDomDocument &document, QPointF const &topLeftPicture) const
{
QDomElement result = document.createElement("world");
QDomElement trace = document.createElement("trace");
result.appendChild(trace);
for (QGraphicsLineItem *line : mRobotTrace) {
QDomElement traceSegment = document.createElement("segment");
traceSegment.setAttribute("x1", line->line().x1());
traceSegment.setAttribute("x2", line->line().x2());
traceSegment.setAttribute("y1", line->line().y1());
traceSegment.setAttribute("y2", line->line().y2());
traceSegment.setAttribute("color", line->pen().color().name());
traceSegment.setAttribute("width", line->pen().width());
trace.appendChild(traceSegment);
}
QDomElement walls = document.createElement("walls");
result.appendChild(walls);
for (items::WallItem * const wall : mWalls) {
QDomElement wallNode = wall->serialize(document, topLeftPicture.toPoint());
walls.appendChild(wallNode);
}
QDomElement colorFields = document.createElement("colorFields");
result.appendChild(colorFields);
for (items::ColorFieldItem *colorField : mColorFields) {
QDomElement colorFiedlNode = colorField->serialize(document, topLeftPicture.toPoint());
colorFields.appendChild(colorFiedlNode);
}
return result;
}
void WorldModel::deserialize(QDomElement const &element)
{
if (element.isNull()) {
/// @todo Report error
return;
}
clear();
QDomNodeList allTraces = element.elementsByTagName("trace");
for (int i = 0; i < allTraces.count(); ++i) {
QDomElement const trace = allTraces.at(i).toElement();
QDomNodeList segments = trace.elementsByTagName("segment");
for (int j = 0; j < segments.count(); ++j) {
QDomElement const segmentNode = segments.at(j).toElement();
QPointF const from(segmentNode.attribute("x1").toDouble(), segmentNode.attribute("y1").toDouble());
QPointF const to(segmentNode.attribute("x2").toDouble(), segmentNode.attribute("y2").toDouble());
QPen pen;
pen.setColor(QColor(segmentNode.attribute("color")));
pen.setWidth(segmentNode.attribute("width").toInt());
appendRobotTrace(pen, from, to);
}
}
QDomNodeList allWalls = element.elementsByTagName("walls");
for (int i = 0; i < allWalls.count(); ++i) {
QDomElement const wallsNode = allWalls.at(i).toElement();
QDomNodeList walls = wallsNode.elementsByTagName("wall");
for (int j = 0; j < walls.count(); ++j) {
QDomElement const wallNode = walls.at(j).toElement();
items::WallItem *wall = new items::WallItem(QPointF(0, 0), QPointF(0, 0));
wall->deserialize(wallNode);
addWall(wall);
}
}
QDomNodeList colorFields = element.elementsByTagName("colorFields");
for (int i = 0; i < colorFields.count(); ++i) {
QDomElement const colorFieldNode = colorFields.at(i).toElement();
QDomNodeList ellipses = colorFieldNode.elementsByTagName("ellipse");
for (int j = 0; j < ellipses.count(); ++j) {
QDomElement const ellipseNode = ellipses.at(j).toElement();
items::EllipseItem *ellipseItem = new items::EllipseItem(QPointF(0, 0), QPointF(0, 0));
ellipseItem->deserialize(ellipseNode);
addColorField(ellipseItem);
}
QDomNodeList lines = colorFieldNode.elementsByTagName("line");
for (int j = 0; j < lines.count(); ++j) {
QDomElement const lineNode = lines.at(j).toElement();
items::LineItem* lineItem = new items::LineItem(QPointF(0, 0), QPointF(0, 0));
lineItem->deserialize(lineNode);
addColorField(lineItem);
}
QDomNodeList styluses = colorFieldNode.elementsByTagName("stylus");
for (int j = 0; j < styluses.count(); ++j) {
QDomElement const stylusNode = styluses.at(j).toElement();
items::StylusItem *stylusItem = new items::StylusItem(0, 0);
stylusItem->deserialize(stylusNode);
addColorField(stylusItem);
}
}
}
<commit_msg>Removed extra character<commit_after>#include <QtGui/QTransform>
#include <QtCore/QStringList>
#include "constants.h"
#include "worldModel.h"
#include "src/engine/items/wallItem.h"
#include "src/engine/items/colorFieldItem.h"
#include "src/engine/items/ellipseItem.h"
#include "src/engine/items/stylusItem.h"
using namespace twoDModel;
using namespace model;
#ifdef D2_MODEL_FRAMES_DEBUG
#include <QtWidgets/QGraphicsPathItem>
QGraphicsPathItem *debugPath = nullptr;
#endif
WorldModel::WorldModel()
{
}
int WorldModel::sonarReading(QPointF const &position, qreal direction) const
{
int maxSonarRangeCms = 255;
int minSonarRangeCms = 0;
int currentRangeInCm = (minSonarRangeCms + maxSonarRangeCms) / 2;
QPainterPath const wallPath = buildWallPath();
if (!checkSonarDistance(maxSonarRangeCms, position, direction, wallPath)) {
return maxSonarRangeCms;
}
for ( ; minSonarRangeCms < maxSonarRangeCms;
currentRangeInCm = (minSonarRangeCms + maxSonarRangeCms) / 2)
{
if (checkSonarDistance(currentRangeInCm, position, direction, wallPath)) {
maxSonarRangeCms = currentRangeInCm;
} else {
minSonarRangeCms = currentRangeInCm + 1;
}
}
return currentRangeInCm;
}
bool WorldModel::checkSonarDistance(int const distance, QPointF const &position
, qreal const direction, QPainterPath const &wallPath) const
{
QPainterPath const rayPath = sonarScanningRegion(position, direction, distance);
return rayPath.intersects(wallPath);
}
QPainterPath WorldModel::sonarScanningRegion(QPointF const &position, int range) const
{
return sonarScanningRegion(position, 0, range);
}
QPainterPath WorldModel::sonarScanningRegion(QPointF const &position, qreal direction, int range) const
{
qreal const rayWidthDegrees = 10.0;
qreal const rangeInPixels = range * pixelsInCm;
QPainterPath rayPath;
rayPath.arcTo(QRect(-rangeInPixels, -rangeInPixels
, 2 * rangeInPixels, 2 * rangeInPixels)
, -direction - rayWidthDegrees, 2 * rayWidthDegrees);
rayPath.closeSubpath();
QTransform const sensorPositionTransform = QTransform().translate(position.x(), position.y());
return sensorPositionTransform.map(rayPath);
}
bool WorldModel::checkCollision(QPainterPath const &path) const
{
#ifdef D2_MODEL_FRAMES_DEBUG
delete debugPath;
QPainterPath commonPath = buildWallPath();
commonPath.addPath(path);
debugPath = new QGraphicsPathItem(commonPath);
debugPath->setBrush(Qt::red);
debugPath->setPen(QPen(QColor(Qt::blue)));
debugPath->setZValue(100);
QGraphicsScene * const scene = mWalls.isEmpty()
? (mColorFields.isEmpty() ? nullptr : mColorFields[0]->scene())
: mWalls[0]->scene();
if (scene) {
scene->addItem(debugPath);
scene->update();
}
#endif
return buildWallPath().intersects(path);
}
QList<items::WallItem *> const &WorldModel::walls() const
{
return mWalls;
}
void WorldModel::addWall(items::WallItem *wall)
{
mWalls.append(wall);
emit wallAdded(wall);
}
void WorldModel::removeWall(items::WallItem *wall)
{
mWalls.removeOne(wall);
emit itemRemoved(wall);
}
QList<items::ColorFieldItem *> const &WorldModel::colorFields() const
{
return mColorFields;
}
int WorldModel::wallsCount() const
{
return mWalls.count();
}
items::WallItem *WorldModel::wallAt(int index) const
{
return mWalls[index];
}
void WorldModel::addColorField(items::ColorFieldItem *colorField)
{
mColorFields.append(colorField);
emit colorItemAdded(colorField);
}
void WorldModel::removeColorField(items::ColorFieldItem *colorField)
{
mColorFields.removeOne(colorField);
emit itemRemoved(colorField);
}
void WorldModel::clear()
{
while (!mWalls.isEmpty()) {
removeWall(mWalls.last());
}
while (!mColorFields.isEmpty()) {
removeColorField(mColorFields.last());
}
clearRobotTrace();
}
void WorldModel::appendRobotTrace(QPen const &pen, QPointF const &begin, QPointF const &end)
{
if (pen.color() == QColor(Qt::transparent)) {
return;
}
QGraphicsLineItem * const traceItem = new QGraphicsLineItem(QLineF(begin, end));
traceItem->setPen(pen);
if (mRobotTrace.isEmpty()) {
emit robotTraceAppearedOrDisappeared(true);
}
mRobotTrace << traceItem;
emit otherItemAdded(traceItem);
}
void WorldModel::clearRobotTrace()
{
while (!mRobotTrace.isEmpty()) {
QGraphicsLineItem * const toRemove = mRobotTrace.first();
mRobotTrace.removeOne(toRemove);
emit itemRemoved(toRemove);
}
emit robotTraceAppearedOrDisappeared(false);
}
QPainterPath WorldModel::buildWallPath() const
{
/// @todo Maintain a cache for this.
QPainterPath wallPath;
for (items::WallItem *wall : mWalls) {
wallPath.addPath(wall->path());
}
return wallPath;
}
QDomElement WorldModel::serialize(QDomDocument &document, QPointF const &topLeftPicture) const
{
QDomElement result = document.createElement("world");
QDomElement trace = document.createElement("trace");
result.appendChild(trace);
for (QGraphicsLineItem *line : mRobotTrace) {
QDomElement traceSegment = document.createElement("segment");
traceSegment.setAttribute("x1", line->line().x1());
traceSegment.setAttribute("x2", line->line().x2());
traceSegment.setAttribute("y1", line->line().y1());
traceSegment.setAttribute("y2", line->line().y2());
traceSegment.setAttribute("color", line->pen().color().name());
traceSegment.setAttribute("width", line->pen().width());
trace.appendChild(traceSegment);
}
QDomElement walls = document.createElement("walls");
result.appendChild(walls);
for (items::WallItem * const wall : mWalls) {
QDomElement wallNode = wall->serialize(document, topLeftPicture.toPoint());
walls.appendChild(wallNode);
}
QDomElement colorFields = document.createElement("colorFields");
result.appendChild(colorFields);
for (items::ColorFieldItem *colorField : mColorFields) {
QDomElement colorFiedlNode = colorField->serialize(document, topLeftPicture.toPoint());
colorFields.appendChild(colorFiedlNode);
}
return result;
}
void WorldModel::deserialize(QDomElement const &element)
{
if (element.isNull()) {
/// @todo Report error
return;
}
clear();
QDomNodeList allTraces = element.elementsByTagName("trace");
for (int i = 0; i < allTraces.count(); ++i) {
QDomElement const trace = allTraces.at(i).toElement();
QDomNodeList segments = trace.elementsByTagName("segment");
for (int j = 0; j < segments.count(); ++j) {
QDomElement const segmentNode = segments.at(j).toElement();
QPointF const from(segmentNode.attribute("x1").toDouble(), segmentNode.attribute("y1").toDouble());
QPointF const to(segmentNode.attribute("x2").toDouble(), segmentNode.attribute("y2").toDouble());
QPen pen;
pen.setColor(QColor(segmentNode.attribute("color")));
pen.setWidth(segmentNode.attribute("width").toInt());
appendRobotTrace(pen, from, to);
}
}
QDomNodeList allWalls = element.elementsByTagName("walls");
for (int i = 0; i < allWalls.count(); ++i) {
QDomElement const wallsNode = allWalls.at(i).toElement();
QDomNodeList walls = wallsNode.elementsByTagName("wall");
for (int j = 0; j < walls.count(); ++j) {
QDomElement const wallNode = walls.at(j).toElement();
items::WallItem *wall = new items::WallItem(QPointF(0, 0), QPointF(0, 0));
wall->deserialize(wallNode);
addWall(wall);
}
}
QDomNodeList colorFields = element.elementsByTagName("colorFields");
for (int i = 0; i < colorFields.count(); ++i) {
QDomElement const colorFieldNode = colorFields.at(i).toElement();
QDomNodeList ellipses = colorFieldNode.elementsByTagName("ellipse");
for (int j = 0; j < ellipses.count(); ++j) {
QDomElement const ellipseNode = ellipses.at(j).toElement();
items::EllipseItem *ellipseItem = new items::EllipseItem(QPointF(0, 0), QPointF(0, 0));
ellipseItem->deserialize(ellipseNode);
addColorField(ellipseItem);
}
QDomNodeList lines = colorFieldNode.elementsByTagName("line");
for (int j = 0; j < lines.count(); ++j) {
QDomElement const lineNode = lines.at(j).toElement();
items::LineItem* lineItem = new items::LineItem(QPointF(0, 0), QPointF(0, 0));
lineItem->deserialize(lineNode);
addColorField(lineItem);
}
QDomNodeList styluses = colorFieldNode.elementsByTagName("stylus");
for (int j = 0; j < styluses.count(); ++j) {
QDomElement const stylusNode = styluses.at(j).toElement();
items::StylusItem *stylusItem = new items::StylusItem(0, 0);
stylusItem->deserialize(stylusNode);
addColorField(stylusItem);
}
}
}
<|endoftext|> |
<commit_before>
#include <atomic>
#include <iostream>
using namespace std;
struct DoubleWord {
uint64_t a;
uint64_t b;
};
int main() {
atomic<DoubleWord> dw1;
DoubleWord dw2{3, 4};
DoubleWord dw3{5, 6};
dw1 = DoubleWord{7, 8};
// This will compile using LOCK CMPXCHG8B
bool ret = dw1.compare_exchange_strong(dw2, dw3);
cout << "ret = " << ret << endl;
cout << "dw2.a, dw2.b = " << dw2.a << ", " << dw2.b << endl;
return 0;
}
<commit_msg>Adding NOP instruction into the code to see how g++ translates atomic operations<commit_after>
#include <atomic>
#include <iostream>
using namespace std;
struct DoubleWord {
uint64_t a;
uint64_t b;
};
int main() {
atomic<DoubleWord> dw1;
DoubleWord dw2{3, 4};
DoubleWord dw3{5, 6};
dw1 = DoubleWord{7, 8};
// This will compile using LOCK CMPXCHG8B
bool ret = dw1.compare_exchange_strong(dw2, dw3);
cout << "ret = " << ret << endl;
cout << "dw2.a, dw2.b = " << dw2.a << ", " << dw2.b << endl;
__asm ("nop; nop");
DoubleWord dw4 = dw1.load();
__asm ("nop; nop; nop");
cout << "dw4.a, dw4.b = " << dw4.a << ", " << dw4.b << endl;
return 0;
}
<|endoftext|> |
<commit_before>#include "kernel.h"
#include "raster.h"
#include "pixeliterator.h"
using namespace Ilwis;
bool PixelIterator::isValid() const {
return _isValid;
}
PixelIterator::PixelIterator() : _localOffset(0), _currentBlock(0), _step(0), _flow(fXYZ),_isValid(false),_positionid(0) {
}
PixelIterator::PixelIterator(IGridCoverage raster, const Box3D<>& box, double step) :
_raster(raster),
_box(box),
_localOffset(0),
_currentBlock(0),
_step(step),
_flow(fXYZ),
_isValid(false)
{
init();
}
PixelIterator::PixelIterator(const PixelIterator& iter) {
copy(iter);
}
inline PixelIterator::PixelIterator(quint64 posid ) :
_localOffset(0),
_currentBlock(0),
_step(0),
_flow(fXYZ),
_isValid(false),
_positionid(posid)
{
}
void PixelIterator::copy(const PixelIterator &iter) {
_raster = iter._raster;
if ( _raster.isValid()) // TODO beyond end marker(end()) dont have a valid raster, no problem just yet but it maybe needed in the future
_grid = _raster->_grid.data();
_box = iter._box;
_step = iter._step;
_isValid = iter._isValid;
_flow = iter._flow;
_positionid = iter._positionid;
_x = iter._x;
_y = iter._y;
_z = iter._z;
_endx = iter._endx;
_endy = iter._endy;
_endz = iter._endz;
_positionid = iter._positionid;
_endpositionid = iter._endpositionid;
_localOffset = iter._localOffset;
_currentBlock = iter._currentBlock;
}
void PixelIterator::init() {
const Size& sz = _raster->size();
if ( _box.isNull()) {
_box = Box3D<>(sz);
}
_box.ensure(sz);
_x = _box.min_corner().x();
_y = _box.min_corner().y();
_z = _box.min_corner().z();
_endx = _box.max_corner().x();
_endy = _box.max_corner().y();
_endz = _box.max_corner().z();
bool inside = contains(Pixel(_x,_y));
if ( inside) {
_grid = _raster->grid();
}
initPosition();
quint64 shift = _x + _y * 1e5 + (_z + 1) *1e10;
_endpositionid = _positionid + shift;
//_endpositionid = _endx + _endy * 1e5 + _endz*1e10 + _raster->id() * 1e13;
_isValid = inside;
_xChanged = _yChanged = _zChanged = false;
}
inline bool PixelIterator::moveXYZ(int n) {
_x += n * _step;
_localOffset += n;
_xChanged = true;
_yChanged = _zChanged = false;
if ( _x > _endx) {
++_y;
_x = _box.min_corner().x();
_yChanged = true;
_localOffset = _x + _y * _grid->size().xsize();
if ( (_y % _grid->maxLines()) == 0) {
++_currentBlock;
_localOffset = 0;
}
if ( _y > _endy) {
++_z;
++_currentBlock;
_zChanged = true;
_y = _box.min_corner().y();
_localOffset = 0;
if ( _z >= _endz) { // done with this iteration block
_positionid = _endpositionid;
return false;
}
}
}
return true;
}
inline bool PixelIterator::isAtEnd() const {
return _x == _box.max_corner().x() &&
_y == _box.max_corner().y() &&
_z == _box.max_corner().z();
}
Voxel PixelIterator::position() const
{
return Voxel(_x, _y, _z);
}
inline bool PixelIterator::move(int n) {
if (isAtEnd()) {
_positionid = _endpositionid;
return false;
}
bool ok;
if ( _flow == fXYZ) {
ok = moveXYZ(n);
}
else if ( _flow == fYXZ){
}
if (ok)
_positionid = calcPosId();
return ok;
}
PixelIterator& PixelIterator::operator=(const PixelIterator& iter) {
copy(iter);
return *this;
}
inline PixelIterator PixelIterator::operator++(int) {
PixelIterator temp(*this);
if(!move(1))
return end();
return temp;
}
inline PixelIterator PixelIterator::operator--(int) {
PixelIterator temp(*this);
move(-1);
return temp;
}
bool PixelIterator::operator==(const PixelIterator& iter) const{
return _positionid == iter._positionid;
}
bool PixelIterator::operator!=(const PixelIterator& iter) const{
return ! operator ==(iter);
}
PixelIterator PixelIterator::end() const {
return PixelIterator(_endpositionid);
}
void PixelIterator::setFlow(Flow flw) {
_flow = flw;
}
bool PixelIterator::contains(const Pixel& pix) {
return pix.x() >= _box.min_corner().x() &&
pix.x() < _box.max_corner().x() &&
pix.y() >= _box.min_corner().y() &&
pix.y() < _box.max_corner().y();
}
bool PixelIterator::xchanged() const {
return _xChanged;
}
bool PixelIterator::ychanged() const {
return _yChanged;
}
bool PixelIterator::zchanged() const {
return _zChanged;
}
void PixelIterator::initPosition() {
const Size& sz = _raster->size();
quint64 linearPos = _y * sz.xsize() + _x;
_currentBlock = _y / _grid->maxLines();
_localOffset = linearPos - _currentBlock * _grid->maxLines() * sz.xsize();
_currentBlock += _z * _grid->blocksPerBand();
_positionid = calcPosId();
}
<commit_msg>corrected some location stuff<commit_after>#include "kernel.h"
#include "raster.h"
#include "pixeliterator.h"
using namespace Ilwis;
bool PixelIterator::isValid() const {
return _isValid;
}
PixelIterator::PixelIterator() : _localOffset(0), _currentBlock(0), _step(0), _flow(fXYZ),_isValid(false),_positionid(0) {
}
PixelIterator::PixelIterator(IGridCoverage raster, const Box3D<>& box, double step) :
_raster(raster),
_box(box),
_localOffset(0),
_currentBlock(0),
_step(step),
_flow(fXYZ),
_isValid(false)
{
init();
}
PixelIterator::PixelIterator(const PixelIterator& iter) {
copy(iter);
}
inline PixelIterator::PixelIterator(quint64 posid ) :
_localOffset(0),
_currentBlock(0),
_step(0),
_flow(fXYZ),
_isValid(false),
_positionid(posid)
{
}
void PixelIterator::copy(const PixelIterator &iter) {
_raster = iter._raster;
if ( _raster.isValid()) // TODO beyond end marker(end()) dont have a valid raster, no problem just yet but it maybe needed in the future
_grid = _raster->_grid.data();
_box = iter._box;
_step = iter._step;
_isValid = iter._isValid;
_flow = iter._flow;
_positionid = iter._positionid;
_x = iter._x;
_y = iter._y;
_z = iter._z;
_endx = iter._endx;
_endy = iter._endy;
_endz = iter._endz;
_positionid = iter._positionid;
_endpositionid = iter._endpositionid;
_localOffset = iter._localOffset;
_currentBlock = iter._currentBlock;
}
void PixelIterator::init() {
const Size& sz = _raster->size();
if ( _box.isNull()) {
_box = Box3D<>(sz);
}
_box.ensure(sz);
_x = _box.min_corner().x();
_y = _box.min_corner().y();
_z = _box.min_corner().z();
_endx = _box.max_corner().x();
_endy = _box.max_corner().y();
_endz = _box.max_corner().z();
bool inside = contains(Pixel(_x,_y));
if ( inside) {
_grid = _raster->grid();
}
initPosition();
quint64 shift = _x + _y * 1e5 + (_z + 1) *1e10;
_endpositionid = _positionid + shift;
//_endpositionid = _endx + _endy * 1e5 + _endz*1e10 + _raster->id() * 1e13;
_isValid = inside;
_xChanged = _yChanged = _zChanged = false;
}
inline bool PixelIterator::moveXYZ(int n) {
_x += n * _step;
_localOffset += n;
_xChanged = true;
_yChanged = _zChanged = false;
if ( _x > _endx) {
++_y;
_x = _box.min_corner().x();
_yChanged = true;
qint32 ylocal = _y % _grid->maxLines();
_localOffset = _x + ylocal * _grid->size().xsize();
if ( ylocal == 0) {
++_currentBlock;
_localOffset = _x;
}
if ( _y > _endy) {
++_z;
++_currentBlock;
_zChanged = true;
_y = _box.min_corner().y();
_localOffset = _box.min_corner().x();
if ( _z >= _endz) { // done with this iteration block
_positionid = _endpositionid;
return false;
}
}
}
return true;
}
inline bool PixelIterator::isAtEnd() const {
return _x == _box.max_corner().x() &&
_y == _box.max_corner().y() &&
_z == _box.max_corner().z();
}
Voxel PixelIterator::position() const
{
return Voxel(_x, _y, _z);
}
inline bool PixelIterator::move(int n) {
if (isAtEnd()) {
_positionid = _endpositionid;
return false;
}
bool ok;
if ( _flow == fXYZ) {
ok = moveXYZ(n);
}
else if ( _flow == fYXZ){
}
if (ok)
_positionid = calcPosId();
return ok;
}
PixelIterator& PixelIterator::operator=(const PixelIterator& iter) {
copy(iter);
return *this;
}
inline PixelIterator PixelIterator::operator++(int) {
PixelIterator temp(*this);
if(!move(1))
return end();
return temp;
}
inline PixelIterator PixelIterator::operator--(int) {
PixelIterator temp(*this);
move(-1);
return temp;
}
bool PixelIterator::operator==(const PixelIterator& iter) const{
return _positionid == iter._positionid;
}
bool PixelIterator::operator!=(const PixelIterator& iter) const{
return ! operator ==(iter);
}
PixelIterator PixelIterator::end() const {
return PixelIterator(_endpositionid);
}
void PixelIterator::setFlow(Flow flw) {
_flow = flw;
}
bool PixelIterator::contains(const Pixel& pix) {
return pix.x() >= _box.min_corner().x() &&
pix.x() < _box.max_corner().x() &&
pix.y() >= _box.min_corner().y() &&
pix.y() < _box.max_corner().y();
}
bool PixelIterator::xchanged() const {
return _xChanged;
}
bool PixelIterator::ychanged() const {
return _yChanged;
}
bool PixelIterator::zchanged() const {
return _zChanged;
}
void PixelIterator::initPosition() {
const Size& sz = _raster->size();
quint64 linearPos = _y * sz.xsize() + _x;
_currentBlock = _y / _grid->maxLines();
_localOffset = linearPos - _currentBlock * _grid->maxLines() * sz.xsize();
_currentBlock += _z * _grid->blocksPerBand();
_positionid = calcPosId();
}
<|endoftext|> |
<commit_before>/*************************************************************************
*
* $RCSfile: writersvc.cxx,v $
*
* $Revision: 1.2 $
*
* last change: $Author: jb $ $Date: 2002-05-27 13:55:02 $
*
* 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: 2002 by Sun Microsystems, Inc.
*
* All Rights Reserved.
*
* Contributor(s): _______________________________________
*
*
************************************************************************/
#include "writersvc.hxx"
#ifndef CONFIGMGR_API_FACTORY_HXX_
#include "confapifactory.hxx"
#endif
#include <drafts/com/sun/star/configuration/backend/XLayerHandler.hpp>
#include <com/sun/star/lang/WrappedTargetRuntimeException.hpp>
// -----------------------------------------------------------------------------
namespace configmgr
{
// -----------------------------------------------------------------------------
namespace xml
{
// -----------------------------------------------------------------------------
namespace uno = ::com::sun::star::uno;
namespace lang = ::com::sun::star::lang;
namespace io = ::com::sun::star::io;
namespace sax = ::com::sun::star::xml::sax;
namespace backenduno = drafts::com::sun::star::configuration::backend;
// -----------------------------------------------------------------------------
template <class BackendInterface>
struct WriterServiceTraits;
// -----------------------------------------------------------------------------
static inline void clear(OUString & _rs) { _rs = OUString(); }
// -----------------------------------------------------------------------------
template <class BackendInterface>
WriterService<BackendInterface>::WriterService(CreationArg _xServiceFactory)
: m_xServiceFactory(_xServiceFactory)
, m_xWriter()
{
if (!m_xServiceFactory.is())
{
OUString sMessage( RTL_CONSTASCII_USTRINGPARAM("Configuration XML Writer: Unexpected NULL context"));
throw uno::RuntimeException(sMessage,NULL);
}
}
// -----------------------------------------------------------------------------
// XInitialization
template <class BackendInterface>
void SAL_CALL
WriterService<BackendInterface>::initialize( const uno::Sequence< uno::Any >& aArguments )
throw (uno::Exception, uno::RuntimeException)
{
switch(aArguments.getLength())
{
case 0:
{
break;
}
case 1:
{
if (aArguments[0] >>= m_xWriter)
break;
uno::Reference< io::XOutputStream > xStream;
if (aArguments[0] >>= xStream)
{
this->setOutputStream(xStream);
break;
}
OUString sMessage( RTL_CONSTASCII_USTRINGPARAM("Cannot use argument to initialize a Configuration XML Writer"
"- SAX XDocumentHandler or XOutputStream expected"));
throw lang::IllegalArgumentException(sMessage,*this,1);
}
default:
{
OUString sMessage( RTL_CONSTASCII_USTRINGPARAM("Too many arguments to initialize a Configuration Parser"));
throw lang::IllegalArgumentException(sMessage,*this,0);
}
}
}
// -----------------------------------------------------------------------------
template <class BackendInterface>
inline
ServiceInfoHelper WriterService<BackendInterface>::getServiceInfo()
{
return WriterServiceTraits<BackendInterface>::getServiceInfo();
}
// -----------------------------------------------------------------------------
// XServiceInfo
template <class BackendInterface>
::rtl::OUString SAL_CALL
WriterService<BackendInterface>::getImplementationName( )
throw (uno::RuntimeException)
{
return getServiceInfo().getImplementationName( );
}
// -----------------------------------------------------------------------------
template <class BackendInterface>
sal_Bool SAL_CALL
WriterService<BackendInterface>::supportsService( const ::rtl::OUString& ServiceName )
throw (uno::RuntimeException)
{
return getServiceInfo().supportsService( ServiceName );
}
// -----------------------------------------------------------------------------
template <class BackendInterface>
uno::Sequence< ::rtl::OUString > SAL_CALL
WriterService<BackendInterface>::getSupportedServiceNames( )
throw (uno::RuntimeException)
{
return getServiceInfo().getSupportedServiceNames( );
}
// -----------------------------------------------------------------------------
template <class BackendInterface>
void SAL_CALL
WriterService<BackendInterface>::setOutputStream( const uno::Reference< io::XOutputStream >& aStream )
throw (uno::RuntimeException)
{
uno::Reference< io::XActiveDataSource > xDS( m_xWriter, uno::UNO_QUERY );
if (xDS.is())
{
xDS->setOutputStream(aStream);
}
else
{
SaxHandler xNewHandler = this->createHandler();
xDS.set( xNewHandler, uno::UNO_QUERY );
if (!xDS.is())
{
OUString sMessage( RTL_CONSTASCII_USTRINGPARAM("Configuration XML Writer: Cannot set output stream to sax.Writer - missing interface XActiveDataSource."));
throw uno::RuntimeException(sMessage,*this);
}
xDS->setOutputStream(aStream);
m_xWriter = xNewHandler;
}
}
// -----------------------------------------------------------------------------
template <class BackendInterface>
uno::Reference< io::XOutputStream > SAL_CALL
WriterService<BackendInterface>::getOutputStream( )
throw (uno::RuntimeException)
{
uno::Reference< io::XActiveDataSource > xDS( m_xWriter, uno::UNO_QUERY );
return xDS.is()? xDS->getOutputStream() : uno::Reference< io::XOutputStream >();
}
// -----------------------------------------------------------------------------
template <class BackendInterface>
uno::Reference< sax::XDocumentHandler > WriterService<BackendInterface>::getWriteHandler()
throw (uno::RuntimeException)
{
if (!m_xWriter.is())
m_xWriter = this->createHandler();
return m_xWriter;
}
// -----------------------------------------------------------------------------
template <class BackendInterface>
uno::Reference< sax::XDocumentHandler > WriterService<BackendInterface>::createHandler() const
throw (uno::RuntimeException)
{
static rtl::OUString const k_sSaxWriterSvc( RTL_CONSTASCII_USTRINGPARAM("com.sun.star.xml.sax.Writer") );
return SaxHandler::query( getServiceFactory()->createInstance(k_sSaxWriterSvc) );
}
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
AsciiServiceName const aLayerWriterServices[] =
{
"com.sun.star.configuration.backend.xml.LayerWriter",
0
};
const ServiceInfo aLayerWriterSI =
{
"com.sun.star.comp.configuration.backend.xml.LayerWriter",
aLayerWriterServices
};
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
template <>
struct WriterServiceTraits< backenduno::XLayerHandler >
{
typedef backenduno::XLayerHandler Handler;
static ServiceInfo const * getServiceInfo()
{ return & aLayerWriterSI; }
};
// -----------------------------------------------------------------------------
const ServiceInfo* getLayerWriterServiceInfo()
{ return & aLayerWriterSI; }
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// instantiate here !
template class WriterService< backenduno::XLayerHandler >;
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
} // namespace
// -----------------------------------------------------------------------------
} // namespace
<commit_msg>#98489# Removed reference to static data from template for SunCC<commit_after>/*************************************************************************
*
* $RCSfile: writersvc.cxx,v $
*
* $Revision: 1.3 $
*
* last change: $Author: jb $ $Date: 2002-05-27 16:12:47 $
*
* 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: 2002 by Sun Microsystems, Inc.
*
* All Rights Reserved.
*
* Contributor(s): _______________________________________
*
*
************************************************************************/
#include "writersvc.hxx"
#ifndef CONFIGMGR_API_FACTORY_HXX_
#include "confapifactory.hxx"
#endif
#include <drafts/com/sun/star/configuration/backend/XLayerHandler.hpp>
#include <com/sun/star/lang/WrappedTargetRuntimeException.hpp>
// -----------------------------------------------------------------------------
namespace configmgr
{
// -----------------------------------------------------------------------------
namespace xml
{
// -----------------------------------------------------------------------------
namespace uno = ::com::sun::star::uno;
namespace lang = ::com::sun::star::lang;
namespace io = ::com::sun::star::io;
namespace sax = ::com::sun::star::xml::sax;
namespace backenduno = drafts::com::sun::star::configuration::backend;
// -----------------------------------------------------------------------------
template <class BackendInterface>
struct WriterServiceTraits;
// -----------------------------------------------------------------------------
static inline void clear(OUString & _rs) { _rs = OUString(); }
// -----------------------------------------------------------------------------
template <class BackendInterface>
WriterService<BackendInterface>::WriterService(CreationArg _xServiceFactory)
: m_xServiceFactory(_xServiceFactory)
, m_xWriter()
{
if (!m_xServiceFactory.is())
{
OUString sMessage( RTL_CONSTASCII_USTRINGPARAM("Configuration XML Writer: Unexpected NULL context"));
throw uno::RuntimeException(sMessage,NULL);
}
}
// -----------------------------------------------------------------------------
// XInitialization
template <class BackendInterface>
void SAL_CALL
WriterService<BackendInterface>::initialize( const uno::Sequence< uno::Any >& aArguments )
throw (uno::Exception, uno::RuntimeException)
{
switch(aArguments.getLength())
{
case 0:
{
break;
}
case 1:
{
if (aArguments[0] >>= m_xWriter)
break;
uno::Reference< io::XOutputStream > xStream;
if (aArguments[0] >>= xStream)
{
this->setOutputStream(xStream);
break;
}
OUString sMessage( RTL_CONSTASCII_USTRINGPARAM("Cannot use argument to initialize a Configuration XML Writer"
"- SAX XDocumentHandler or XOutputStream expected"));
throw lang::IllegalArgumentException(sMessage,*this,1);
}
default:
{
OUString sMessage( RTL_CONSTASCII_USTRINGPARAM("Too many arguments to initialize a Configuration Parser"));
throw lang::IllegalArgumentException(sMessage,*this,0);
}
}
}
// -----------------------------------------------------------------------------
template <class BackendInterface>
inline
ServiceInfoHelper WriterService<BackendInterface>::getServiceInfo()
{
return WriterServiceTraits<BackendInterface>::getServiceInfo();
}
// -----------------------------------------------------------------------------
// XServiceInfo
template <class BackendInterface>
::rtl::OUString SAL_CALL
WriterService<BackendInterface>::getImplementationName( )
throw (uno::RuntimeException)
{
return getServiceInfo().getImplementationName( );
}
// -----------------------------------------------------------------------------
template <class BackendInterface>
sal_Bool SAL_CALL
WriterService<BackendInterface>::supportsService( const ::rtl::OUString& ServiceName )
throw (uno::RuntimeException)
{
return getServiceInfo().supportsService( ServiceName );
}
// -----------------------------------------------------------------------------
template <class BackendInterface>
uno::Sequence< ::rtl::OUString > SAL_CALL
WriterService<BackendInterface>::getSupportedServiceNames( )
throw (uno::RuntimeException)
{
return getServiceInfo().getSupportedServiceNames( );
}
// -----------------------------------------------------------------------------
template <class BackendInterface>
void SAL_CALL
WriterService<BackendInterface>::setOutputStream( const uno::Reference< io::XOutputStream >& aStream )
throw (uno::RuntimeException)
{
uno::Reference< io::XActiveDataSource > xDS( m_xWriter, uno::UNO_QUERY );
if (xDS.is())
{
xDS->setOutputStream(aStream);
}
else
{
SaxHandler xNewHandler = this->createHandler();
xDS.set( xNewHandler, uno::UNO_QUERY );
if (!xDS.is())
{
OUString sMessage( RTL_CONSTASCII_USTRINGPARAM("Configuration XML Writer: Cannot set output stream to sax.Writer - missing interface XActiveDataSource."));
throw uno::RuntimeException(sMessage,*this);
}
xDS->setOutputStream(aStream);
m_xWriter = xNewHandler;
}
}
// -----------------------------------------------------------------------------
template <class BackendInterface>
uno::Reference< io::XOutputStream > SAL_CALL
WriterService<BackendInterface>::getOutputStream( )
throw (uno::RuntimeException)
{
uno::Reference< io::XActiveDataSource > xDS( m_xWriter, uno::UNO_QUERY );
return xDS.is()? xDS->getOutputStream() : uno::Reference< io::XOutputStream >();
}
// -----------------------------------------------------------------------------
template <class BackendInterface>
uno::Reference< sax::XDocumentHandler > WriterService<BackendInterface>::getWriteHandler()
throw (uno::RuntimeException)
{
if (!m_xWriter.is())
m_xWriter = this->createHandler();
return m_xWriter;
}
// -----------------------------------------------------------------------------
template <class BackendInterface>
uno::Reference< sax::XDocumentHandler > WriterService<BackendInterface>::createHandler() const
throw (uno::RuntimeException)
{
static rtl::OUString const k_sSaxWriterSvc( RTL_CONSTASCII_USTRINGPARAM("com.sun.star.xml.sax.Writer") );
return SaxHandler::query( getServiceFactory()->createInstance(k_sSaxWriterSvc) );
}
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
AsciiServiceName const aLayerWriterServices[] =
{
"com.sun.star.configuration.backend.xml.LayerWriter",
0
};
const ServiceInfo aLayerWriterSI =
{
"com.sun.star.comp.configuration.backend.xml.LayerWriter",
aLayerWriterServices
};
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
template <>
struct WriterServiceTraits< backenduno::XLayerHandler >
{
typedef backenduno::XLayerHandler Handler;
static ServiceInfo const * getServiceInfo()
{ return getLayerWriterServiceInfo(); }
};
// -----------------------------------------------------------------------------
const ServiceInfo* getLayerWriterServiceInfo()
{ return & aLayerWriterSI; }
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// instantiate here !
template class WriterService< backenduno::XLayerHandler >;
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
} // namespace
// -----------------------------------------------------------------------------
} // namespace
<|endoftext|> |
<commit_before>//**************************************************************************************************
//
// OSSIM Open Source Geospatial Data Processing Library
// See top level LICENSE.txt file for license information
//
//**************************************************************************************************
#include "ossimAtpTool.h"
#include <math.h>
#include "correlation/CorrelationAtpGenerator.h"
#include "descriptor/DescriptorAtpGenerator.h"
#include <ossim/base/ossimException.h>
#include <ossim/base/ossimGpt.h>
#include <ossim/base/ossimEcefPoint.h>
#include <ossim/base/ossimArgumentParser.h>
#include <ossim/base/ossimApplicationUsage.h>
#include <ossim/base/ossimKeywordNames.h>
#include <ossim/base/ossimException.h>
#include <ossim/base/ossimNotify.h>
#include <ossim/base/ossimException.h>
#include <cstdlib>
#include <iostream>
#include <memory>
#include <sstream>
using namespace std;
#define CINFO ossimNotify(ossimNotifyLevel_INFO)
#define CWARN ossimNotify(ossimNotifyLevel_WARN)
#define CFATAL ossimNotify(ossimNotifyLevel_FATAL)
namespace ATP
{
const char* ossimAtpTool::DESCRIPTION =
"Provides automatic tiepoint generation functionality. This tool uses JSON format to "
"communicate requests and results.";
ossimAtpTool::ossimAtpTool()
: m_outputStream (0),
m_verbose (false),
m_featureBased (true),
m_algorithm (ALGO_UNASSIGNED),
m_method (METHOD_UNASSIGNED)
{
}
ossimAtpTool::~ossimAtpTool()
{
}
void ossimAtpTool::setUsage(ossimArgumentParser& ap)
{
// Add global usage options. Don't include ossimChipProcUtil options as not appropriate.
ossimTool::setUsage(ap);
// Set the general usage:
ossimApplicationUsage* au = ap.getApplicationUsage();
ossimString usageString = ap.getApplicationName();
usageString += " atp [options] \n\n";
usageString +=
"Accesses automatic tiepoint generation functionality given JSON request on stdin (or input file if\n"
"-i specified). The response JSON is output to stdout unless -o option is specified.\n";
au->setCommandLineUsage(usageString);
// Set the command line options:
au->addCommandLineOption("--algorithms",
"List available auto-tie-point algorithms");
au->addCommandLineOption("-i <filename>",
"Reads request JSON from the input file specified instead of stdin.");
au->addCommandLineOption("-o <filename>",
"Outputs response JSON to the output file instead of stdout.");
au->addCommandLineOption("--parameters",
"List all ATP parameters with default values.");
au->addCommandLineOption("-v",
"Verbose. All non-response (debug) output to stdout is enabled.");
}
bool ossimAtpTool::initialize(ossimArgumentParser& ap)
{
string ts1;
ossimArgumentParser::ossimParameter sp1(ts1);
m_method = GENERATE;
if (!ossimTool::initialize(ap))
return false;
if (m_helpRequested)
return true;
if ( ap.read("-v"))
m_verbose = true;
if ( ap.read("--algorithms"))
m_method = GET_ALGO_LIST;
if ( ap.read("--parameters"))
m_method = GET_PARAMS;
if ( ap.read("-i", sp1))
{
ifstream s (ts1);
if (s.fail())
{
CFATAL<<__FILE__<<" Could not open input file <"<<ts1<<">";
return false;
}
try
{
Json::Value queryJson;
s >> queryJson;
loadJSON(queryJson);
}
catch (exception& e)
{
ossimNotify(ossimNotifyLevel_FATAL)<<__FILE__<<" Could not parse input JSON <"<<ts1<<">";
return false;
}
}
if ( ap.read("-o", sp1))
{
ofstream* s = new ofstream (ts1);
if (s->fail())
{
CFATAL<<__FILE__<<" Could not open output file <"<<ts1<<">";
return false;
}
m_outputStream = s;
}
else
m_outputStream = &clog;
return true;
}
void ossimAtpTool::loadJSON(const Json::Value& queryRoot)
{
ostringstream xmsg;
xmsg<<"ossimAtpTool::loadJSON() ";
// Fetch the desired method from the JSON if provided, otherwise rely on command line options:
m_method = GENERATE;
string method = queryRoot["method"].asString();
if (method == "getAlgorithms")
m_method = GET_ALGO_LIST;
else if (method == "getParameters")
m_method = GET_PARAMS;
// Fetch the desired algorithm or configuration:
AtpConfig& config = AtpConfig::instance();
string algorithm = queryRoot["algorithm"].asString();
if (algorithm.empty())
{
// An optional field specifies a configuration that contains the base-name of a custom
// parameters JSON file including algorithm type. Read that if specified:
m_configuration = queryRoot["configuration"].asString();
if (!m_configuration.empty())
{
if (!config.readConfig(m_configuration))
{
xmsg << "Fatal error trying to read default ATP configuration for selected "
"configuration <"<<m_configuration<<">";
throw ossimException(xmsg.str());
}
algorithm = config.getParameter("algorithm").asString();
}
}
// Otherwise read the algorithm's default config params from the system:
else if (!config.readConfig(algorithm))
{
xmsg << "Fatal error trying to read default ATP configuration for selected algorithm <"
<<algorithm<<">";
throw ossimException(xmsg.str());
}
// Assign enum data member used throughout the service:
if (algorithm == "crosscorr")
m_algorithm = CROSSCORR;
else if (method == "descriptor")
m_algorithm = DESCRIPTOR;
else if (method == "nasa")
m_algorithm = NASA;
else
m_algorithm = ALGO_UNASSIGNED;
// If parameters were provided in the JSON payload, have the config override the defaults:
const Json::Value& parameters = queryRoot["parameters"];
if (!parameters.isNull())
config.loadJSON(parameters);
if (config.diagnosticLevel(2))
clog<<"\nATP configuration after loading:\n"<<config<<endl;
if (m_method == GENERATE)
{
// Load the active photoblock from JSON.
// The root JSON object can optionally contain a photoblock with image list contained. If so,
// use that object to load images, otherwise use the root.
if (queryRoot.isMember("photoblock"))
m_photoBlock.reset(new PhotoBlock(queryRoot["photoblock"]));
else
m_photoBlock.reset(new PhotoBlock(queryRoot));
}
}
bool ossimAtpTool::execute()
{
ostringstream xmsg;
try
{
switch (m_method)
{
case GET_ALGO_LIST:
getAlgorithms();
break;
case GET_PARAMS:
getParameters();
break;
case GENERATE:
generate();
break;
default:
xmsg << "Fatal: No method selected prior to execute being called. I don't know what to do!";
throw ossimException(xmsg.str());
}
// Serialize JSON object for return:
(*m_outputStream) << m_responseJSON;
}
catch(ossimException &e)
{
CFATAL<<"Exception: "<<e.what()<<endl;
*m_outputStream<<"{ \"ERROR\": \"" << e.what() << "\" }\n"<<endl;
}
// close any open file streams:
ofstream* so = dynamic_cast<ofstream*>(m_outputStream);
if (so)
{
so->close();
delete so;
}
return true;
}
void ossimAtpTool::getKwlTemplate(ossimKeywordlist& kwl)
{
}
void ossimAtpTool::getAlgorithms()
{
m_responseJSON.clear();
Json::Value algoList;
algoList[0]["name"] = "crosscorr";
algoList[0]["description"] = "Matching by cross-correlation of raster patches";
algoList[0]["label"] = "Cross Correlation";
algoList[1]["name"] = "descriptor";
algoList[1]["description"] = "Matching by feature descriptors";
algoList[1]["label"] = "Descriptor";
//algoList[2]["name"] = "nasa";
//algoList[2]["description"] = "Tiepoint extraction using NASA tool.";
//algoList[2]["label"] = "NASA";
m_responseJSON["algorithms"] = algoList;
}
void ossimAtpTool::getParameters()
{
m_responseJSON.clear();
Json::Value params;
AtpConfig::instance().saveJSON(params);
m_responseJSON["parameters"] = params;
}
void ossimAtpTool::generate()
{
ostringstream xmsg;
xmsg<<"ossimAtpTool::generate() ";
switch (m_algorithm)
{
case CROSSCORR:
case DESCRIPTOR:
doPairwiseMatching();
break;
case NASA:
xmsg << "NASA Algorithm not yet implemented!";
throw ossimException(xmsg.str());
break;
case ALGO_UNASSIGNED:
default:
xmsg << "Fatal: No algorithm selected prior to execute being called. I don't know what to do!";
throw ossimException(xmsg.str());
}
}
void ossimAtpTool::doPairwiseMatching()
{
static const char* MODULE = "ossimAtpTool::doPairwiseMatching() ";
ostringstream xmsg;
xmsg<<MODULE;
if (!m_photoBlock || (m_photoBlock->getImageList().size() < 2))
{
xmsg << "No photoblock has been declared or it has less than two images. Cannot perform ATP.";
throw ossimException(xmsg.str());
}
shared_ptr<AtpGeneratorBase> generator;
// First obtain list of images from photoblock:
std::vector<shared_ptr<Image> >& imageList = m_photoBlock->getImageList();
int numImages = (int) imageList.size();
int numPairs = (numImages * (numImages-1))/2; // triangular number assumes all overlap
for (int i=0; i<(numImages-1); i++)
{
shared_ptr<Image> imageA = imageList[i];
for (int j=i+1; j<numImages; j++)
{
shared_ptr<Image> imageB = imageList[j];
// Instantiate the ATP generator for this pair:
if (m_algorithm == CROSSCORR)
generator.reset(new CorrelationAtpGenerator());
else if (m_algorithm == DESCRIPTOR)
generator.reset(new DescriptorAtpGenerator());
else if (m_algorithm == NASA)
{
xmsg << "NASA algorithm not yet supported. Cannot perform ATP.";
throw ossimException(xmsg.str());
}
// Generate tie points using A for features:
generator->setRefImage(imageA);
generator->setCmpImage(imageB);
ATP::AtpList tpList;
generator->generateTiePointList(tpList);
m_photoBlock->addTiePoints(tpList);
if (AtpConfig::instance().diagnosticLevel(2))
clog<<"Completed pairwise match for pair "<<i<<"-"<<j<<endl;
// Now reverse CMP and REF to find possible additional features on B:
bool doTwoWaySearch = AtpConfig::instance().getParameter("doTwoWaySearch").asBool();
if (doTwoWaySearch)
{
generator->setRefImage(imageB);
generator->setCmpImage(imageA);
tpList.clear();
generator->generateTiePointList(tpList);
m_photoBlock->addTiePoints(tpList);
if (AtpConfig::instance().diagnosticLevel(2))
clog<<"Completed pairwise match for pair "<<j<<"-"<<i<<endl;
}
}
}
// Save list to photoblock JSON:
Json::Value pbJson;
m_photoBlock->saveJSON(pbJson);
m_responseJSON["photoblock"] = pbJson;
if (AtpConfig::instance().diagnosticLevel(1))
clog<<"\n"<<MODULE<<"Total TPs found = "<<m_photoBlock->getTiePointList().size()<<endl;
}
}
<commit_msg>Fixed typo<commit_after>//**************************************************************************************************
//
// OSSIM Open Source Geospatial Data Processing Library
// See top level LICENSE.txt file for license information
//
//**************************************************************************************************
#include "ossimAtpTool.h"
#include <math.h>
#include "correlation/CorrelationAtpGenerator.h"
#include "descriptor/DescriptorAtpGenerator.h"
#include <ossim/base/ossimException.h>
#include <ossim/base/ossimGpt.h>
#include <ossim/base/ossimEcefPoint.h>
#include <ossim/base/ossimArgumentParser.h>
#include <ossim/base/ossimApplicationUsage.h>
#include <ossim/base/ossimKeywordNames.h>
#include <ossim/base/ossimException.h>
#include <ossim/base/ossimNotify.h>
#include <ossim/base/ossimException.h>
#include <cstdlib>
#include <iostream>
#include <memory>
#include <sstream>
using namespace std;
#define CINFO ossimNotify(ossimNotifyLevel_INFO)
#define CWARN ossimNotify(ossimNotifyLevel_WARN)
#define CFATAL ossimNotify(ossimNotifyLevel_FATAL)
namespace ATP
{
const char* ossimAtpTool::DESCRIPTION =
"Provides automatic tiepoint generation functionality. This tool uses JSON format to "
"communicate requests and results.";
ossimAtpTool::ossimAtpTool()
: m_outputStream (0),
m_verbose (false),
m_featureBased (true),
m_algorithm (ALGO_UNASSIGNED),
m_method (METHOD_UNASSIGNED)
{
}
ossimAtpTool::~ossimAtpTool()
{
}
void ossimAtpTool::setUsage(ossimArgumentParser& ap)
{
// Add global usage options. Don't include ossimChipProcUtil options as not appropriate.
ossimTool::setUsage(ap);
// Set the general usage:
ossimApplicationUsage* au = ap.getApplicationUsage();
ossimString usageString = ap.getApplicationName();
usageString += " atp [options] \n\n";
usageString +=
"Accesses automatic tiepoint generation functionality given JSON request on stdin (or input file if\n"
"-i specified). The response JSON is output to stdout unless -o option is specified.\n";
au->setCommandLineUsage(usageString);
// Set the command line options:
au->addCommandLineOption("--algorithms",
"List available auto-tie-point algorithms");
au->addCommandLineOption("-i <filename>",
"Reads request JSON from the input file specified instead of stdin.");
au->addCommandLineOption("-o <filename>",
"Outputs response JSON to the output file instead of stdout.");
au->addCommandLineOption("--parameters",
"List all ATP parameters with default values.");
au->addCommandLineOption("-v",
"Verbose. All non-response (debug) output to stdout is enabled.");
}
bool ossimAtpTool::initialize(ossimArgumentParser& ap)
{
string ts1;
ossimArgumentParser::ossimParameter sp1(ts1);
m_method = GENERATE;
if (!ossimTool::initialize(ap))
return false;
if (m_helpRequested)
return true;
if ( ap.read("-v"))
m_verbose = true;
if ( ap.read("--algorithms"))
m_method = GET_ALGO_LIST;
if ( ap.read("--parameters"))
m_method = GET_PARAMS;
if ( ap.read("-i", sp1))
{
ifstream s (ts1);
if (s.fail())
{
CFATAL<<__FILE__<<" Could not open input file <"<<ts1<<">";
return false;
}
try
{
Json::Value queryJson;
s >> queryJson;
loadJSON(queryJson);
}
catch (exception& e)
{
ossimNotify(ossimNotifyLevel_FATAL)<<__FILE__<<" Could not parse input JSON <"<<ts1<<">";
return false;
}
}
if ( ap.read("-o", sp1))
{
ofstream* s = new ofstream (ts1);
if (s->fail())
{
CFATAL<<__FILE__<<" Could not open output file <"<<ts1<<">";
return false;
}
m_outputStream = s;
}
else
m_outputStream = &clog;
return true;
}
void ossimAtpTool::loadJSON(const Json::Value& queryRoot)
{
ostringstream xmsg;
xmsg<<"ossimAtpTool::loadJSON() ";
// Fetch the desired method from the JSON if provided, otherwise rely on command line options:
m_method = GENERATE;
string method = queryRoot["method"].asString();
if (method == "getAlgorithms")
m_method = GET_ALGO_LIST;
else if (method == "getParameters")
m_method = GET_PARAMS;
// Fetch the desired algorithm or configuration:
AtpConfig& config = AtpConfig::instance();
string algorithm = queryRoot["algorithm"].asString();
if (algorithm.empty())
{
// An optional field specifies a configuration that contains the base-name of a custom
// parameters JSON file including algorithm type. Read that if specified:
m_configuration = queryRoot["configuration"].asString();
if (!m_configuration.empty())
{
if (!config.readConfig(m_configuration))
{
xmsg << "Fatal error trying to read default ATP configuration for selected "
"configuration <"<<m_configuration<<">";
throw ossimException(xmsg.str());
}
algorithm = config.getParameter("algorithm").asString();
}
}
// Otherwise read the algorithm's default config params from the system:
else if (!config.readConfig(algorithm))
{
xmsg << "Fatal error trying to read default ATP configuration for selected algorithm <"
<<algorithm<<">";
throw ossimException(xmsg.str());
}
// Assign enum data member used throughout the service:
if (algorithm == "crosscorr")
m_algorithm = CROSSCORR;
else if (algorithm == "descriptor")
m_algorithm = DESCRIPTOR;
else if (algorithm == "nasa")
m_algorithm = NASA;
else
m_algorithm = ALGO_UNASSIGNED;
// If parameters were provided in the JSON payload, have the config override the defaults:
const Json::Value& parameters = queryRoot["parameters"];
if (!parameters.isNull())
config.loadJSON(parameters);
if (config.diagnosticLevel(2))
clog<<"\nATP configuration after loading:\n"<<config<<endl;
if (m_method == GENERATE)
{
// Load the active photoblock from JSON.
// The root JSON object can optionally contain a photoblock with image list contained. If so,
// use that object to load images, otherwise use the root.
if (queryRoot.isMember("photoblock"))
m_photoBlock.reset(new PhotoBlock(queryRoot["photoblock"]));
else
m_photoBlock.reset(new PhotoBlock(queryRoot));
}
}
bool ossimAtpTool::execute()
{
ostringstream xmsg;
try
{
switch (m_method)
{
case GET_ALGO_LIST:
getAlgorithms();
break;
case GET_PARAMS:
getParameters();
break;
case GENERATE:
generate();
break;
default:
xmsg << "Fatal: No method selected prior to execute being called. I don't know what to do!";
throw ossimException(xmsg.str());
}
// Serialize JSON object for return:
(*m_outputStream) << m_responseJSON;
}
catch(ossimException &e)
{
CFATAL<<"Exception: "<<e.what()<<endl;
*m_outputStream<<"{ \"ERROR\": \"" << e.what() << "\" }\n"<<endl;
}
// close any open file streams:
ofstream* so = dynamic_cast<ofstream*>(m_outputStream);
if (so)
{
so->close();
delete so;
}
return true;
}
void ossimAtpTool::getKwlTemplate(ossimKeywordlist& kwl)
{
}
void ossimAtpTool::getAlgorithms()
{
m_responseJSON.clear();
Json::Value algoList;
algoList[0]["name"] = "crosscorr";
algoList[0]["description"] = "Matching by cross-correlation of raster patches";
algoList[0]["label"] = "Cross Correlation";
algoList[1]["name"] = "descriptor";
algoList[1]["description"] = "Matching by feature descriptors";
algoList[1]["label"] = "Descriptor";
//algoList[2]["name"] = "nasa";
//algoList[2]["description"] = "Tiepoint extraction using NASA tool.";
//algoList[2]["label"] = "NASA";
m_responseJSON["algorithms"] = algoList;
}
void ossimAtpTool::getParameters()
{
m_responseJSON.clear();
Json::Value params;
AtpConfig::instance().saveJSON(params);
m_responseJSON["parameters"] = params;
}
void ossimAtpTool::generate()
{
ostringstream xmsg;
xmsg<<"ossimAtpTool::generate() ";
switch (m_algorithm)
{
case CROSSCORR:
case DESCRIPTOR:
doPairwiseMatching();
break;
case NASA:
xmsg << "NASA Algorithm not yet implemented!";
throw ossimException(xmsg.str());
break;
case ALGO_UNASSIGNED:
default:
xmsg << "Fatal: No algorithm selected prior to execute being called. I don't know what to do!";
throw ossimException(xmsg.str());
}
}
void ossimAtpTool::doPairwiseMatching()
{
static const char* MODULE = "ossimAtpTool::doPairwiseMatching() ";
ostringstream xmsg;
xmsg<<MODULE;
if (!m_photoBlock || (m_photoBlock->getImageList().size() < 2))
{
xmsg << "No photoblock has been declared or it has less than two images. Cannot perform ATP.";
throw ossimException(xmsg.str());
}
shared_ptr<AtpGeneratorBase> generator;
// First obtain list of images from photoblock:
std::vector<shared_ptr<Image> >& imageList = m_photoBlock->getImageList();
int numImages = (int) imageList.size();
int numPairs = (numImages * (numImages-1))/2; // triangular number assumes all overlap
for (int i=0; i<(numImages-1); i++)
{
shared_ptr<Image> imageA = imageList[i];
for (int j=i+1; j<numImages; j++)
{
shared_ptr<Image> imageB = imageList[j];
// Instantiate the ATP generator for this pair:
if (m_algorithm == CROSSCORR)
generator.reset(new CorrelationAtpGenerator());
else if (m_algorithm == DESCRIPTOR)
generator.reset(new DescriptorAtpGenerator());
else if (m_algorithm == NASA)
{
xmsg << "NASA algorithm not yet supported. Cannot perform ATP.";
throw ossimException(xmsg.str());
}
// Generate tie points using A for features:
generator->setRefImage(imageA);
generator->setCmpImage(imageB);
ATP::AtpList tpList;
generator->generateTiePointList(tpList);
m_photoBlock->addTiePoints(tpList);
if (AtpConfig::instance().diagnosticLevel(2))
clog<<"Completed pairwise match for pair "<<i<<"-"<<j<<endl;
// Now reverse CMP and REF to find possible additional features on B:
bool doTwoWaySearch = AtpConfig::instance().getParameter("doTwoWaySearch").asBool();
if (doTwoWaySearch)
{
generator->setRefImage(imageB);
generator->setCmpImage(imageA);
tpList.clear();
generator->generateTiePointList(tpList);
m_photoBlock->addTiePoints(tpList);
if (AtpConfig::instance().diagnosticLevel(2))
clog<<"Completed pairwise match for pair "<<j<<"-"<<i<<endl;
}
}
}
// Save list to photoblock JSON:
Json::Value pbJson;
m_photoBlock->saveJSON(pbJson);
m_responseJSON["photoblock"] = pbJson;
if (AtpConfig::instance().diagnosticLevel(1))
clog<<"\n"<<MODULE<<"Total TPs found = "<<m_photoBlock->getTiePointList().size()<<endl;
}
}
<|endoftext|> |
<commit_before>#include <vcl/dialog.hxx>
#include <vcl/fixed.hxx>
#ifndef _SV_BUTTON_HXX
#include <vcl/button.hxx>
#endif
namespace desktop
{
void displayCmdlineHelp( void );
class CmdlineHelpDialog : public ModalDialog
{
public:
CmdlineHelpDialog ( void );
FixedText m_ftHead;
FixedText m_ftLeft;
FixedText m_ftRight;
FixedText m_ftBottom;
OKButton m_btOk;
};
}
<commit_msg>INTEGRATION: CWS fwk86 (1.3.998); FILE MERGED 2008/04/30 15:50:07 pb 1.3.998.2: RESYNC: (1.3-1.4); FILE MERGED 2008/03/06 09:28:21 cd 1.3.998.1: #i86384# Remove unused code from desktop<commit_after>#include <vcl/dialog.hxx>
#include <vcl/fixed.hxx>
#ifndef _SV_BUTTON_HXX
#include <vcl/button.hxx>
#endif
namespace desktop
{
void displayCmdlineHelp( void );
#ifndef UNX
class CmdlineHelpDialog : public ModalDialog
{
public:
CmdlineHelpDialog ( void );
FixedText m_ftHead;
FixedText m_ftLeft;
FixedText m_ftRight;
FixedText m_ftBottom;
OKButton m_btOk;
};
#endif
}
<|endoftext|> |
<commit_before>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*************************************************************************
*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* Copyright 2000, 2010 Oracle and/or its affiliates.
*
* OpenOffice.org - a multi-platform office productivity suite
*
* 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.
*
************************************************************************/
#include "desktopdllapi.h"
#include "app.hxx"
#include "cmdlineargs.hxx"
#include "cmdlinehelp.hxx"
#include <rtl/logfile.hxx>
#include <tools/extendapplicationenvironment.hxx>
int SVMain();
// -=-= main() -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
extern "C" int DESKTOP_DLLPUBLIC soffice_main()
{
tools::extendApplicationEnvironment();
RTL_LOGFILE_PRODUCT_TRACE( "PERFORMANCE - enter Main()" );
desktop::Desktop aDesktop;
// This string is used during initialization of the Gtk+ VCL module
aDesktop.SetAppName( rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("soffice")) );
#ifdef UNX
// handle --version and --help already here, otherwise they would be handled
// after VCL initialization that might fail if $DISPLAY is not set
const desktop::CommandLineArgs& rCmdLineArgs = aDesktop.GetCommandLineArgs();
if ( rCmdLineArgs.IsHelp() )
{
desktop::displayCmdlineHelp();
return EXIT_SUCCESS;
}
else if ( rCmdLineArgs.IsVersion() )
{
desktop::displayVersion();
return EXIT_SUCCESS;
}
#endif
return SVMain();
}
/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
<commit_msg>android: print out exception messages that escaped 'main'<commit_after>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*************************************************************************
*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* Copyright 2000, 2010 Oracle and/or its affiliates.
*
* OpenOffice.org - a multi-platform office productivity suite
*
* 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.
*
************************************************************************/
#include "desktopdllapi.h"
#include "app.hxx"
#include "cmdlineargs.hxx"
#include "cmdlinehelp.hxx"
#include <rtl/logfile.hxx>
#include <tools/extendapplicationenvironment.hxx>
int SVMain();
// -=-= main() -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
extern "C" int DESKTOP_DLLPUBLIC soffice_main()
{
#ifdef ANDROID
try {
#endif
tools::extendApplicationEnvironment();
RTL_LOGFILE_PRODUCT_TRACE( "PERFORMANCE - enter Main()" );
desktop::Desktop aDesktop;
// This string is used during initialization of the Gtk+ VCL module
aDesktop.SetAppName( rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("soffice")) );
#ifdef UNX
// handle --version and --help already here, otherwise they would be handled
// after VCL initialization that might fail if $DISPLAY is not set
const desktop::CommandLineArgs& rCmdLineArgs = aDesktop.GetCommandLineArgs();
if ( rCmdLineArgs.IsHelp() )
{
desktop::displayCmdlineHelp();
return EXIT_SUCCESS;
}
else if ( rCmdLineArgs.IsVersion() )
{
desktop::displayVersion();
return EXIT_SUCCESS;
}
#endif
return SVMain();
#ifdef ANDROID
} catch (const ::com::sun::star::uno::Exception &e) {
fprintf (stderr, "Not handled UNO exception at main: '%s'\n",
rtl::OUStringToOString(e.Message, RTL_TEXTENCODING_UTF8).getStr());
throw e; // to get exception type printed
}
#endif
}
/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
<|endoftext|> |
<commit_before>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*
* This file is part of the LibreOffice project.
*
* 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/.
*
* This file incorporates work covered by the following license notice:
*
* 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 .
*/
#include "acceptor.hxx"
#include <com/sun/star/bridge/BridgeFactory.hpp>
#include <com/sun/star/uno/XNamingService.hpp>
#include <comphelper/processfactory.hxx>
#include <cppuhelper/factory.hxx>
namespace desktop
{
extern "C" void workerfunc (void * acc)
{
((Acceptor*)acc)->run();
}
Mutex Acceptor::m_aMutex;
Acceptor::Acceptor( const Reference< XMultiServiceFactory >& rFactory )
: m_thread(NULL)
, m_aAcceptString()
, m_aConnectString()
, m_aProtocol()
, m_bInit(sal_False)
, m_bDying(false)
{
m_rSMgr = rFactory;
// get component context
m_rContext = comphelper::getComponentContext(m_rSMgr);
m_rAcceptor = Reference< XAcceptor > (m_rSMgr->createInstance(
rtl::OUString("com.sun.star.connection.Acceptor" )),
UNO_QUERY );
m_rBridgeFactory = BridgeFactory::create(m_rContext);
}
Acceptor::~Acceptor()
{
m_rAcceptor->stopAccepting();
oslThread t;
{
osl::MutexGuard g(m_aMutex);
t = m_thread;
}
//prevent locking if the thread is still waiting
m_bDying = true;
m_cEnable.set();
osl_joinWithThread(t);
{
// Make the final state of m_bridges visible to this thread (since
// m_thread is joined, the code that follows is the only one left
// accessing m_bridges):
osl::MutexGuard g(m_aMutex);
}
for (;;) {
com::sun::star::uno::Reference< com::sun::star::bridge::XBridge > b(
m_bridges.remove());
if (!b.is()) {
break;
}
com::sun::star::uno::Reference< com::sun::star::lang::XComponent >(
b, com::sun::star::uno::UNO_QUERY_THROW)->dispose();
}
}
void SAL_CALL Acceptor::run()
{
while ( m_rAcceptor.is() )
{
RTL_LOGFILE_CONTEXT( aLog, "desktop (lo119109) Acceptor::run" );
try
{
// wait until we get enabled
RTL_LOGFILE_CONTEXT_TRACE( aLog, "desktop (lo119109)"\
"Acceptor::run waiting for office to come up");
m_cEnable.wait();
if (m_bDying) //see destructor
break;
RTL_LOGFILE_CONTEXT_TRACE( aLog, "desktop (lo119109)"\
"Acceptor::run now enabled and continuing");
// accept connection
Reference< XConnection > rConnection = m_rAcceptor->accept( m_aConnectString );
// if we return without a valid connection we mus assume that the acceptor
// is destructed so we break out of the run method terminating the thread
if (! rConnection.is()) break;
OUString aDescription = rConnection->getDescription();
RTL_LOGFILE_CONTEXT_TRACE1( aLog, "desktop (lo119109) Acceptor::run connection %s",
OUStringToOString(aDescription, RTL_TEXTENCODING_ASCII_US).getStr());
// create instanceprovider for this connection
Reference< XInstanceProvider > rInstanceProvider(
(XInstanceProvider*)new AccInstanceProvider(m_rSMgr, rConnection));
// create the bridge. The remote end will have a reference to this bridge
// thus preventing the bridge from being disposed. When the remote end releases
// the bridge, it will be destructed.
Reference< XBridge > rBridge = m_rBridgeFactory->createBridge(
rtl::OUString() ,m_aProtocol ,rConnection ,rInstanceProvider );
osl::MutexGuard g(m_aMutex);
m_bridges.add(rBridge);
} catch (const Exception&) {
// connection failed...
// something went wrong during connection setup.
// just wait for a new connection to accept
}
}
}
// XInitialize
void SAL_CALL Acceptor::initialize( const Sequence<Any>& aArguments )
throw( Exception )
{
// prevent multiple initialization
ClearableMutexGuard aGuard( m_aMutex );
RTL_LOGFILE_CONTEXT( aLog, "destop (lo119109) Acceptor::initialize()" );
sal_Bool bOk = sal_False;
// arg count
int nArgs = aArguments.getLength();
// not yet initialized and acceptstring
if (!m_bInit && nArgs > 0 && (aArguments[0] >>= m_aAcceptString))
{
RTL_LOGFILE_CONTEXT_TRACE1( aLog, "desktop (lo119109) Acceptor::initialize string=%s",
OUStringToOString(m_aAcceptString, RTL_TEXTENCODING_ASCII_US).getStr());
// get connect string and protocol from accept string
// "<connectString>;<protocol>"
sal_Int32 nIndex1 = m_aAcceptString.indexOf( (sal_Unicode) ';' );
if (nIndex1 < 0) throw IllegalArgumentException(
OUString("Invalid accept-string format"), m_rContext, 1);
m_aConnectString = m_aAcceptString.copy( 0 , nIndex1 ).trim();
nIndex1++;
sal_Int32 nIndex2 = m_aAcceptString.indexOf( (sal_Unicode) ';' , nIndex1 );
if (nIndex2 < 0) nIndex2 = m_aAcceptString.getLength();
m_aProtocol = m_aAcceptString.copy( nIndex1, nIndex2 - nIndex1 );
// start accepting in new thread...
m_thread = osl_createThread(workerfunc, this);
m_bInit = sal_True;
bOk = sal_True;
}
// do we want to enable accepting?
sal_Bool bEnable = sal_False;
if (((nArgs == 1 && (aArguments[0] >>= bEnable)) ||
(nArgs == 2 && (aArguments[1] >>= bEnable))) &&
bEnable )
{
m_cEnable.set();
bOk = sal_True;
}
if (!bOk)
{
throw IllegalArgumentException(
OUString("invalid initialization"), m_rContext, 1);
}
}
// XServiceInfo
const sal_Char *Acceptor::serviceName = "com.sun.star.office.Acceptor";
const sal_Char *Acceptor::implementationName = "com.sun.star.office.comp.Acceptor";
const sal_Char *Acceptor::supportedServiceNames[] = {"com.sun.star.office.Acceptor", NULL};
OUString Acceptor::impl_getImplementationName()
{
return OUString::createFromAscii( implementationName );
}
OUString SAL_CALL Acceptor::getImplementationName()
throw (RuntimeException)
{
return Acceptor::impl_getImplementationName();
}
Sequence<OUString> Acceptor::impl_getSupportedServiceNames()
{
Sequence<OUString> aSequence;
for (int i=0; supportedServiceNames[i]!=NULL; i++) {
aSequence.realloc(i+1);
aSequence[i]=(OUString::createFromAscii(supportedServiceNames[i]));
}
return aSequence;
}
Sequence<OUString> SAL_CALL Acceptor::getSupportedServiceNames()
throw (RuntimeException)
{
return Acceptor::impl_getSupportedServiceNames();
}
sal_Bool SAL_CALL Acceptor::supportsService( const OUString&)
throw (RuntimeException)
{
return sal_False;
}
// Factory
Reference< XInterface > Acceptor::impl_getInstance( const Reference< XMultiServiceFactory >& aFactory )
{
try {
return (XComponent*) new Acceptor( aFactory );
} catch ( const Exception& ) {
return (XComponent*) NULL;
}
}
// InstanceProvider
AccInstanceProvider::AccInstanceProvider(const Reference<XMultiServiceFactory>& aFactory, const Reference<XConnection>& rConnection)
{
m_rSMgr = aFactory;
m_rConnection = rConnection;
}
AccInstanceProvider::~AccInstanceProvider()
{
}
Reference<XInterface> SAL_CALL AccInstanceProvider::getInstance (const OUString& aName )
throw ( NoSuchElementException )
{
Reference<XInterface> rInstance;
if ( aName.compareToAscii( "StarOffice.ServiceManager" ) == 0)
{
rInstance = Reference< XInterface >( m_rSMgr );
}
else if(aName.compareToAscii( "StarOffice.ComponentContext" ) == 0 )
{
rInstance = comphelper::getComponentContext( m_rSMgr );
}
else if ( aName.compareToAscii("StarOffice.NamingService" ) == 0 )
{
Reference< XNamingService > rNamingService(
m_rSMgr->createInstance( OUString("com.sun.star.uno.NamingService" )),
UNO_QUERY );
if ( rNamingService.is() )
{
rNamingService->registerObject(
OUString("StarOffice.ServiceManager" ), m_rSMgr );
rNamingService->registerObject(
OUString("StarOffice.ComponentContext" ), comphelper::getComponentContext( m_rSMgr ));
rInstance = rNamingService;
}
}
return rInstance;
}
}
// component management stuff...
// ----------------------------------------------------------------------------
extern "C"
{
using namespace desktop;
SAL_DLLPUBLIC_EXPORT void * SAL_CALL offacc_component_getFactory(const sal_Char *pImplementationName, void *pServiceManager, void *)
{
void* pReturn = NULL ;
if ( pImplementationName && pServiceManager )
{
// Define variables which are used in following macros.
Reference< XSingleServiceFactory > xFactory;
Reference< XMultiServiceFactory > xServiceManager(
reinterpret_cast< XMultiServiceFactory* >(pServiceManager));
if (Acceptor::impl_getImplementationName().equalsAscii( pImplementationName ) )
{
xFactory = Reference< XSingleServiceFactory >( cppu::createSingleFactory(
xServiceManager, Acceptor::impl_getImplementationName(),
Acceptor::impl_getInstance, Acceptor::impl_getSupportedServiceNames()) );
}
// Factory is valid - service was found.
if ( xFactory.is() )
{
xFactory->acquire();
pReturn = xFactory.get();
}
}
// Return with result of this operation.
return pReturn ;
}
} // extern "C"
/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
<commit_msg>Improve debug error reporting<commit_after>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*
* This file is part of the LibreOffice project.
*
* 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/.
*
* This file incorporates work covered by the following license notice:
*
* 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 .
*/
#include "acceptor.hxx"
#include <com/sun/star/bridge/BridgeFactory.hpp>
#include <com/sun/star/uno/XNamingService.hpp>
#include <comphelper/processfactory.hxx>
#include <cppuhelper/factory.hxx>
namespace desktop
{
extern "C" void workerfunc (void * acc)
{
((Acceptor*)acc)->run();
}
Mutex Acceptor::m_aMutex;
Acceptor::Acceptor( const Reference< XMultiServiceFactory >& rFactory )
: m_thread(NULL)
, m_aAcceptString()
, m_aConnectString()
, m_aProtocol()
, m_bInit(sal_False)
, m_bDying(false)
{
m_rSMgr = rFactory;
// get component context
m_rContext = comphelper::getComponentContext(m_rSMgr);
m_rAcceptor = Reference< XAcceptor > (m_rSMgr->createInstance(
rtl::OUString("com.sun.star.connection.Acceptor" )),
UNO_QUERY );
m_rBridgeFactory = BridgeFactory::create(m_rContext);
}
Acceptor::~Acceptor()
{
m_rAcceptor->stopAccepting();
oslThread t;
{
osl::MutexGuard g(m_aMutex);
t = m_thread;
}
//prevent locking if the thread is still waiting
m_bDying = true;
m_cEnable.set();
osl_joinWithThread(t);
{
// Make the final state of m_bridges visible to this thread (since
// m_thread is joined, the code that follows is the only one left
// accessing m_bridges):
osl::MutexGuard g(m_aMutex);
}
for (;;) {
com::sun::star::uno::Reference< com::sun::star::bridge::XBridge > b(
m_bridges.remove());
if (!b.is()) {
break;
}
com::sun::star::uno::Reference< com::sun::star::lang::XComponent >(
b, com::sun::star::uno::UNO_QUERY_THROW)->dispose();
}
}
void SAL_CALL Acceptor::run()
{
while ( m_rAcceptor.is() )
{
RTL_LOGFILE_CONTEXT( aLog, "desktop (lo119109) Acceptor::run" );
try
{
// wait until we get enabled
RTL_LOGFILE_CONTEXT_TRACE( aLog, "desktop (lo119109)"\
"Acceptor::run waiting for office to come up");
m_cEnable.wait();
if (m_bDying) //see destructor
break;
RTL_LOGFILE_CONTEXT_TRACE( aLog, "desktop (lo119109)"\
"Acceptor::run now enabled and continuing");
// accept connection
Reference< XConnection > rConnection = m_rAcceptor->accept( m_aConnectString );
// if we return without a valid connection we mus assume that the acceptor
// is destructed so we break out of the run method terminating the thread
if (! rConnection.is()) break;
OUString aDescription = rConnection->getDescription();
RTL_LOGFILE_CONTEXT_TRACE1( aLog, "desktop (lo119109) Acceptor::run connection %s",
OUStringToOString(aDescription, RTL_TEXTENCODING_ASCII_US).getStr());
// create instanceprovider for this connection
Reference< XInstanceProvider > rInstanceProvider(
(XInstanceProvider*)new AccInstanceProvider(m_rSMgr, rConnection));
// create the bridge. The remote end will have a reference to this bridge
// thus preventing the bridge from being disposed. When the remote end releases
// the bridge, it will be destructed.
Reference< XBridge > rBridge = m_rBridgeFactory->createBridge(
rtl::OUString() ,m_aProtocol ,rConnection ,rInstanceProvider );
osl::MutexGuard g(m_aMutex);
m_bridges.add(rBridge);
} catch (const Exception& e) {
SAL_WARN("desktop", "caught Exception \"" << e.Message << "\"");
// connection failed...
// something went wrong during connection setup.
// just wait for a new connection to accept
}
}
}
// XInitialize
void SAL_CALL Acceptor::initialize( const Sequence<Any>& aArguments )
throw( Exception )
{
// prevent multiple initialization
ClearableMutexGuard aGuard( m_aMutex );
RTL_LOGFILE_CONTEXT( aLog, "destop (lo119109) Acceptor::initialize()" );
sal_Bool bOk = sal_False;
// arg count
int nArgs = aArguments.getLength();
// not yet initialized and acceptstring
if (!m_bInit && nArgs > 0 && (aArguments[0] >>= m_aAcceptString))
{
RTL_LOGFILE_CONTEXT_TRACE1( aLog, "desktop (lo119109) Acceptor::initialize string=%s",
OUStringToOString(m_aAcceptString, RTL_TEXTENCODING_ASCII_US).getStr());
// get connect string and protocol from accept string
// "<connectString>;<protocol>"
sal_Int32 nIndex1 = m_aAcceptString.indexOf( (sal_Unicode) ';' );
if (nIndex1 < 0) throw IllegalArgumentException(
OUString("Invalid accept-string format"), m_rContext, 1);
m_aConnectString = m_aAcceptString.copy( 0 , nIndex1 ).trim();
nIndex1++;
sal_Int32 nIndex2 = m_aAcceptString.indexOf( (sal_Unicode) ';' , nIndex1 );
if (nIndex2 < 0) nIndex2 = m_aAcceptString.getLength();
m_aProtocol = m_aAcceptString.copy( nIndex1, nIndex2 - nIndex1 );
// start accepting in new thread...
m_thread = osl_createThread(workerfunc, this);
m_bInit = sal_True;
bOk = sal_True;
}
// do we want to enable accepting?
sal_Bool bEnable = sal_False;
if (((nArgs == 1 && (aArguments[0] >>= bEnable)) ||
(nArgs == 2 && (aArguments[1] >>= bEnable))) &&
bEnable )
{
m_cEnable.set();
bOk = sal_True;
}
if (!bOk)
{
throw IllegalArgumentException(
OUString("invalid initialization"), m_rContext, 1);
}
}
// XServiceInfo
const sal_Char *Acceptor::serviceName = "com.sun.star.office.Acceptor";
const sal_Char *Acceptor::implementationName = "com.sun.star.office.comp.Acceptor";
const sal_Char *Acceptor::supportedServiceNames[] = {"com.sun.star.office.Acceptor", NULL};
OUString Acceptor::impl_getImplementationName()
{
return OUString::createFromAscii( implementationName );
}
OUString SAL_CALL Acceptor::getImplementationName()
throw (RuntimeException)
{
return Acceptor::impl_getImplementationName();
}
Sequence<OUString> Acceptor::impl_getSupportedServiceNames()
{
Sequence<OUString> aSequence;
for (int i=0; supportedServiceNames[i]!=NULL; i++) {
aSequence.realloc(i+1);
aSequence[i]=(OUString::createFromAscii(supportedServiceNames[i]));
}
return aSequence;
}
Sequence<OUString> SAL_CALL Acceptor::getSupportedServiceNames()
throw (RuntimeException)
{
return Acceptor::impl_getSupportedServiceNames();
}
sal_Bool SAL_CALL Acceptor::supportsService( const OUString&)
throw (RuntimeException)
{
return sal_False;
}
// Factory
Reference< XInterface > Acceptor::impl_getInstance( const Reference< XMultiServiceFactory >& aFactory )
{
try {
return (XComponent*) new Acceptor( aFactory );
} catch ( const Exception& ) {
return (XComponent*) NULL;
}
}
// InstanceProvider
AccInstanceProvider::AccInstanceProvider(const Reference<XMultiServiceFactory>& aFactory, const Reference<XConnection>& rConnection)
{
m_rSMgr = aFactory;
m_rConnection = rConnection;
}
AccInstanceProvider::~AccInstanceProvider()
{
}
Reference<XInterface> SAL_CALL AccInstanceProvider::getInstance (const OUString& aName )
throw ( NoSuchElementException )
{
Reference<XInterface> rInstance;
if ( aName.compareToAscii( "StarOffice.ServiceManager" ) == 0)
{
rInstance = Reference< XInterface >( m_rSMgr );
}
else if(aName.compareToAscii( "StarOffice.ComponentContext" ) == 0 )
{
rInstance = comphelper::getComponentContext( m_rSMgr );
}
else if ( aName.compareToAscii("StarOffice.NamingService" ) == 0 )
{
Reference< XNamingService > rNamingService(
m_rSMgr->createInstance( OUString("com.sun.star.uno.NamingService" )),
UNO_QUERY );
if ( rNamingService.is() )
{
rNamingService->registerObject(
OUString("StarOffice.ServiceManager" ), m_rSMgr );
rNamingService->registerObject(
OUString("StarOffice.ComponentContext" ), comphelper::getComponentContext( m_rSMgr ));
rInstance = rNamingService;
}
}
return rInstance;
}
}
// component management stuff...
// ----------------------------------------------------------------------------
extern "C"
{
using namespace desktop;
SAL_DLLPUBLIC_EXPORT void * SAL_CALL offacc_component_getFactory(const sal_Char *pImplementationName, void *pServiceManager, void *)
{
void* pReturn = NULL ;
if ( pImplementationName && pServiceManager )
{
// Define variables which are used in following macros.
Reference< XSingleServiceFactory > xFactory;
Reference< XMultiServiceFactory > xServiceManager(
reinterpret_cast< XMultiServiceFactory* >(pServiceManager));
if (Acceptor::impl_getImplementationName().equalsAscii( pImplementationName ) )
{
xFactory = Reference< XSingleServiceFactory >( cppu::createSingleFactory(
xServiceManager, Acceptor::impl_getImplementationName(),
Acceptor::impl_getInstance, Acceptor::impl_getSupportedServiceNames()) );
}
// Factory is valid - service was found.
if ( xFactory.is() )
{
xFactory->acquire();
pReturn = xFactory.get();
}
}
// Return with result of this operation.
return pReturn ;
}
} // extern "C"
/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
<|endoftext|> |
<commit_before><commit_msg>* fix build error on arm<commit_after><|endoftext|> |
<commit_before>#include "mex.h"
#include <iostream>
#include "drakeUtil.h"
#include "RigidBodyManipulator.h"
#include "math.h"
using namespace Eigen;
using namespace std;
// convert Matlab cell array of strings into a C++ vector of strings
vector<string> get_strings(const mxArray *rhs) {
int num = mxGetNumberOfElements(rhs);
vector<string> strings(num);
for (int i=0; i<num; i++) {
const mxArray *ptr = mxGetCell(rhs,i);
int buflen = mxGetN(ptr)*sizeof(mxChar)+1;
char* str = (char*)mxMalloc(buflen);
mxGetString(ptr, str, buflen);
strings[i] = string(str);
mxFree(str);
}
return strings;
}
void
smoothDistancePenalty(double& c, MatrixXd& dc,
RigidBodyManipulator* robot,
const double min_distance,
const VectorXd& dist,
const MatrixXd& normal,
const MatrixXd& xA,
const MatrixXd& xB,
const vector<int>& idxA,
const vector<int>& idxB)
{
VectorXd scaled_dist, pairwise_costs;
MatrixXd ddist_dq, dscaled_dist_ddist, dpairwise_costs_dscaled_dist;
int num_pts = xA.cols();
ddist_dq = MatrixXd::Zero(num_pts,robot->num_dof);
// Scale distance
int nd = dist.size();
double recip_min_dist = 1/min_distance;
scaled_dist = recip_min_dist*dist - VectorXd::Ones(nd,1);
dscaled_dist_ddist = recip_min_dist*MatrixXd::Identity(nd,nd);
// Compute penalties
pairwise_costs = VectorXd::Zero(nd,1);
dpairwise_costs_dscaled_dist = MatrixXd::Zero(nd,nd);
for (int i = 0; i < nd; ++i) {
if (scaled_dist(i) < 0) {
double exp_recip_scaled_dist = exp(1/scaled_dist(i));
pairwise_costs(i) = -scaled_dist(i)*exp_recip_scaled_dist;
dpairwise_costs_dscaled_dist(i,i) = exp_recip_scaled_dist*(1/scaled_dist(i) - 1);
}
}
// Compute Jacobian of closest distance vector
std::vector< std::vector<int> > orig_idx_of_pt_on_bodyA(robot->num_bodies);
std::vector< std::vector<int> > orig_idx_of_pt_on_bodyB(robot->num_bodies);
for (int k = 0; k < num_pts; ++k) {
//DEBUG
//std::cout << "MinDistanceConstraint::eval: First loop: " << k << std::endl;
//std::cout << "pairwise_costs.size() = " << pairwise_costs.size() << std::endl;
//std::cout << "pairwise_costs.size() = " << pairwise_costs.size() << std::endl;
//END_DEBUG
if (pairwise_costs(k) > 0) {
orig_idx_of_pt_on_bodyA.at(idxA.at(k)).push_back(k);
orig_idx_of_pt_on_bodyB.at(idxB.at(k)).push_back(k);
}
}
for (int k = 0; k < robot->num_bodies; ++k) {
//DEBUG
//std::cout << "MinDistanceConstraint::eval: Second loop: " << k << std::endl;
//END_DEBUG
int l = 0;
int numA = orig_idx_of_pt_on_bodyA.at(k).size();
int numB = orig_idx_of_pt_on_bodyB.at(k).size();
MatrixXd x_k(3, numA + numB);
for (; l < numA; ++l) {
//DEBUG
//std::cout << "MinDistanceConstraint::eval: Third loop: " << l << std::endl;
//END_DEBUG
x_k.col(l) = xA.col(orig_idx_of_pt_on_bodyA.at(k).at(l));
}
for (; l < numA + numB; ++l) {
//DEBUG
//std::cout << "MinDistanceConstraint::eval: Fourth loop: " << l << std::endl;
//END_DEBUG
x_k.col(l) = xB.col(orig_idx_of_pt_on_bodyB.at(k).at(l-numA));
}
MatrixXd x_k_1(4,x_k.cols());
MatrixXd J_k(3*x_k.cols(),robot->num_dof);
x_k_1 << x_k, MatrixXd::Ones(1,x_k.cols());
robot->forwardJac(k,x_k_1,0,J_k);
l = 0;
for (; l < numA; ++l) {
//DEBUG
//std::cout << "MinDistanceConstraint::eval: Fifth loop: " << l << std::endl;
//END_DEBUG
ddist_dq.row(orig_idx_of_pt_on_bodyA.at(k).at(l)) += normal.col(orig_idx_of_pt_on_bodyA.at(k).at(l)).transpose() * J_k.block(3*l,0,3,robot->num_dof);
}
for (; l < numA+numB; ++l) {
//DEBUG
//std::cout << "MinDistanceConstraint::eval: Sixth loop: " << l << std::endl;
//END_DEBUG
ddist_dq.row(orig_idx_of_pt_on_bodyB.at(k).at(l-numA)) += -normal.col(orig_idx_of_pt_on_bodyB.at(k).at(l-numA)).transpose() * J_k.block(3*l,0,3,robot->num_dof);
}
}
MatrixXd dcost_dscaled_dist(dpairwise_costs_dscaled_dist.colwise().sum());
c = pairwise_costs.sum();
dc = dcost_dscaled_dist*dscaled_dist_ddist*ddist_dq;
};
/*
* mex interface for evaluating a smooth-penalty on violations of a
* minimum-distance constraint. For each eligible pair of collision geometries,
* a penalty is computed according to
*
* \f[
* c =
* \begin{cases}
* -de^{\frac{1}{d}}, & d < 0 \\
* 0, & d \ge 0.
* \end{cases}
* \f]
*
* where $d$ is the normalized violation of the minimum distance, $d_{min}$
*
* \f[
* d = \frac{(\phi - d_{min})}{d_{min}}
* \f]
*
* for a signed distance of $\phi$ between the geometries. These pairwise costs
* are summed to yield a single penalty which is zero if and only if all
* eligible pairs of collision geometries are separated by at least $d_{min}$.
*
* MATLAB signature:
*
* [penalty, dpenalty] = ...
* smoothDistancePenaltymex( mex_model_ptr, min_distance, allow_multiple_contacts,
* active_collision_options);
*/
void mexFunction( int nlhs, mxArray *plhs[],int nrhs, const mxArray *prhs[] ) {
if (nrhs < 2) {
mexErrMsgIdAndTxt("Drake:collisionDetectmex:NotEnoughInputs","Usage smoothDistancePenaltymex(model_ptr,min_distance)");
}
// first get the model_ptr back from matlab
RigidBodyManipulator *model= (RigidBodyManipulator*) getDrakeMexPointer(prhs[0]);
// Get the minimum allowable distance
double min_distance = mxGetScalar(prhs[1]);
// Parse `active_collision_options`
vector<int> active_bodies_idx;
set<string> active_group_names;
// First get the list of body indices for which to compute distances
const mxArray* active_collision_options = prhs[3];
const mxArray* body_idx = mxGetField(active_collision_options,0,"body_idx");
if (body_idx != NULL) {
int n_active_bodies = mxGetNumberOfElements(body_idx);
active_bodies_idx.resize(n_active_bodies);
if (mxGetClassID(body_idx) == mxINT32_CLASS) {
memcpy(active_bodies_idx.data(),(int*) mxGetData(body_idx),
sizeof(int)*n_active_bodies);
} else if(mxGetClassID(body_idx) == mxDOUBLE_CLASS) {
vector<double> tmp;
tmp.resize(n_active_bodies);
memcpy(tmp.data(),mxGetPr(body_idx),
sizeof(double)*n_active_bodies);
copy(tmp.begin(),tmp.end(),active_bodies_idx.begin());
} else {
mexErrMsgIdAndTxt("Drake:collisionDetectmex:WrongInputClass","active_collision_options.body_idx must be an int32 or a double array");
}
transform(active_bodies_idx.begin(),active_bodies_idx.end(),
active_bodies_idx.begin(),
[](int i){return --i;});
}
// Then get the group names for which to compute distances
const mxArray* collision_groups = mxGetField(active_collision_options,0,
"collision_groups");
if (collision_groups != NULL) {
for (const string& str : get_strings(collision_groups)) {
active_group_names.insert(str);
}
}
double penalty;
vector<int> bodyA_idx, bodyB_idx;
MatrixXd ptsA, ptsB, normals, JA, JB, Jd, dpenalty;
VectorXd dist;
if (active_bodies_idx.size() > 0) {
if (active_group_names.size() > 0) {
model-> collisionDetect(dist, normals, ptsA, ptsB, bodyA_idx, bodyB_idx,
active_bodies_idx,active_group_names);
} else {
model-> collisionDetect(dist, normals, ptsA, ptsB, bodyA_idx, bodyB_idx,
active_bodies_idx);
}
} else {
if (active_group_names.size() > 0) {
model-> collisionDetect(dist, normals, ptsA, ptsB, bodyA_idx, bodyB_idx,
active_group_names);
} else {
model-> collisionDetect(dist, normals, ptsA, ptsB, bodyA_idx, bodyB_idx);
}
}
smoothDistancePenalty(penalty, dpenalty, model, min_distance, dist, normals, ptsA, ptsB, bodyA_idx, bodyB_idx);
vector<int32_T> idxA(bodyA_idx.size());
transform(bodyA_idx.begin(),bodyA_idx.end(),idxA.begin(),
[](int i){return ++i;});
vector<int32_T> idxB(bodyB_idx.size());
transform(bodyB_idx.begin(),bodyB_idx.end(),idxB.begin(),
[](int i){return ++i;});
if (nlhs>0) {
plhs[0] = mxCreateDoubleScalar(penalty);
}
if (nlhs>1) {
plhs[1] = mxCreateDoubleMatrix(dpenalty.rows(),dpenalty.cols(),mxREAL);
memcpy(mxGetPr(plhs[1]),dpenalty.data(),sizeof(double)*dpenalty.size());
}
}
<commit_msg>Fix error message tag in smoothDistancePenaltymex<commit_after>#include "mex.h"
#include <iostream>
#include "drakeUtil.h"
#include "RigidBodyManipulator.h"
#include "math.h"
using namespace Eigen;
using namespace std;
// convert Matlab cell array of strings into a C++ vector of strings
vector<string> get_strings(const mxArray *rhs) {
int num = mxGetNumberOfElements(rhs);
vector<string> strings(num);
for (int i=0; i<num; i++) {
const mxArray *ptr = mxGetCell(rhs,i);
int buflen = mxGetN(ptr)*sizeof(mxChar)+1;
char* str = (char*)mxMalloc(buflen);
mxGetString(ptr, str, buflen);
strings[i] = string(str);
mxFree(str);
}
return strings;
}
void
smoothDistancePenalty(double& c, MatrixXd& dc,
RigidBodyManipulator* robot,
const double min_distance,
const VectorXd& dist,
const MatrixXd& normal,
const MatrixXd& xA,
const MatrixXd& xB,
const vector<int>& idxA,
const vector<int>& idxB)
{
VectorXd scaled_dist, pairwise_costs;
MatrixXd ddist_dq, dscaled_dist_ddist, dpairwise_costs_dscaled_dist;
int num_pts = xA.cols();
ddist_dq = MatrixXd::Zero(num_pts,robot->num_dof);
// Scale distance
int nd = dist.size();
double recip_min_dist = 1/min_distance;
scaled_dist = recip_min_dist*dist - VectorXd::Ones(nd,1);
dscaled_dist_ddist = recip_min_dist*MatrixXd::Identity(nd,nd);
// Compute penalties
pairwise_costs = VectorXd::Zero(nd,1);
dpairwise_costs_dscaled_dist = MatrixXd::Zero(nd,nd);
for (int i = 0; i < nd; ++i) {
if (scaled_dist(i) < 0) {
double exp_recip_scaled_dist = exp(1/scaled_dist(i));
pairwise_costs(i) = -scaled_dist(i)*exp_recip_scaled_dist;
dpairwise_costs_dscaled_dist(i,i) = exp_recip_scaled_dist*(1/scaled_dist(i) - 1);
}
}
// Compute Jacobian of closest distance vector
std::vector< std::vector<int> > orig_idx_of_pt_on_bodyA(robot->num_bodies);
std::vector< std::vector<int> > orig_idx_of_pt_on_bodyB(robot->num_bodies);
for (int k = 0; k < num_pts; ++k) {
//DEBUG
//std::cout << "MinDistanceConstraint::eval: First loop: " << k << std::endl;
//std::cout << "pairwise_costs.size() = " << pairwise_costs.size() << std::endl;
//std::cout << "pairwise_costs.size() = " << pairwise_costs.size() << std::endl;
//END_DEBUG
if (pairwise_costs(k) > 0) {
orig_idx_of_pt_on_bodyA.at(idxA.at(k)).push_back(k);
orig_idx_of_pt_on_bodyB.at(idxB.at(k)).push_back(k);
}
}
for (int k = 0; k < robot->num_bodies; ++k) {
//DEBUG
//std::cout << "MinDistanceConstraint::eval: Second loop: " << k << std::endl;
//END_DEBUG
int l = 0;
int numA = orig_idx_of_pt_on_bodyA.at(k).size();
int numB = orig_idx_of_pt_on_bodyB.at(k).size();
MatrixXd x_k(3, numA + numB);
for (; l < numA; ++l) {
//DEBUG
//std::cout << "MinDistanceConstraint::eval: Third loop: " << l << std::endl;
//END_DEBUG
x_k.col(l) = xA.col(orig_idx_of_pt_on_bodyA.at(k).at(l));
}
for (; l < numA + numB; ++l) {
//DEBUG
//std::cout << "MinDistanceConstraint::eval: Fourth loop: " << l << std::endl;
//END_DEBUG
x_k.col(l) = xB.col(orig_idx_of_pt_on_bodyB.at(k).at(l-numA));
}
MatrixXd x_k_1(4,x_k.cols());
MatrixXd J_k(3*x_k.cols(),robot->num_dof);
x_k_1 << x_k, MatrixXd::Ones(1,x_k.cols());
robot->forwardJac(k,x_k_1,0,J_k);
l = 0;
for (; l < numA; ++l) {
//DEBUG
//std::cout << "MinDistanceConstraint::eval: Fifth loop: " << l << std::endl;
//END_DEBUG
ddist_dq.row(orig_idx_of_pt_on_bodyA.at(k).at(l)) += normal.col(orig_idx_of_pt_on_bodyA.at(k).at(l)).transpose() * J_k.block(3*l,0,3,robot->num_dof);
}
for (; l < numA+numB; ++l) {
//DEBUG
//std::cout << "MinDistanceConstraint::eval: Sixth loop: " << l << std::endl;
//END_DEBUG
ddist_dq.row(orig_idx_of_pt_on_bodyB.at(k).at(l-numA)) += -normal.col(orig_idx_of_pt_on_bodyB.at(k).at(l-numA)).transpose() * J_k.block(3*l,0,3,robot->num_dof);
}
}
MatrixXd dcost_dscaled_dist(dpairwise_costs_dscaled_dist.colwise().sum());
c = pairwise_costs.sum();
dc = dcost_dscaled_dist*dscaled_dist_ddist*ddist_dq;
};
/*
* mex interface for evaluating a smooth-penalty on violations of a
* minimum-distance constraint. For each eligible pair of collision geometries,
* a penalty is computed according to
*
* \f[
* c =
* \begin{cases}
* -de^{\frac{1}{d}}, & d < 0 \\
* 0, & d \ge 0.
* \end{cases}
* \f]
*
* where $d$ is the normalized violation of the minimum distance, $d_{min}$
*
* \f[
* d = \frac{(\phi - d_{min})}{d_{min}}
* \f]
*
* for a signed distance of $\phi$ between the geometries. These pairwise costs
* are summed to yield a single penalty which is zero if and only if all
* eligible pairs of collision geometries are separated by at least $d_{min}$.
*
* MATLAB signature:
*
* [penalty, dpenalty] = ...
* smoothDistancePenaltymex( mex_model_ptr, min_distance, allow_multiple_contacts,
* active_collision_options);
*/
void mexFunction( int nlhs, mxArray *plhs[],int nrhs, const mxArray *prhs[] ) {
if (nrhs < 2) {
mexErrMsgIdAndTxt("Drake:smoothDistancePenaltymex:NotEnoughInputs","Usage smoothDistancePenaltymex(model_ptr,min_distance)");
}
// first get the model_ptr back from matlab
RigidBodyManipulator *model= (RigidBodyManipulator*) getDrakeMexPointer(prhs[0]);
// Get the minimum allowable distance
double min_distance = mxGetScalar(prhs[1]);
// Parse `active_collision_options`
vector<int> active_bodies_idx;
set<string> active_group_names;
// First get the list of body indices for which to compute distances
const mxArray* active_collision_options = prhs[3];
const mxArray* body_idx = mxGetField(active_collision_options,0,"body_idx");
if (body_idx != NULL) {
int n_active_bodies = mxGetNumberOfElements(body_idx);
active_bodies_idx.resize(n_active_bodies);
if (mxGetClassID(body_idx) == mxINT32_CLASS) {
memcpy(active_bodies_idx.data(),(int*) mxGetData(body_idx),
sizeof(int)*n_active_bodies);
} else if(mxGetClassID(body_idx) == mxDOUBLE_CLASS) {
vector<double> tmp;
tmp.resize(n_active_bodies);
memcpy(tmp.data(),mxGetPr(body_idx),
sizeof(double)*n_active_bodies);
copy(tmp.begin(),tmp.end(),active_bodies_idx.begin());
} else {
mexErrMsgIdAndTxt("Drake:smoothDistancePenaltymex:WrongInputClass","active_collision_options.body_idx must be an int32 or a double array");
}
transform(active_bodies_idx.begin(),active_bodies_idx.end(),
active_bodies_idx.begin(),
[](int i){return --i;});
}
// Then get the group names for which to compute distances
const mxArray* collision_groups = mxGetField(active_collision_options,0,
"collision_groups");
if (collision_groups != NULL) {
for (const string& str : get_strings(collision_groups)) {
active_group_names.insert(str);
}
}
double penalty;
vector<int> bodyA_idx, bodyB_idx;
MatrixXd ptsA, ptsB, normals, JA, JB, Jd, dpenalty;
VectorXd dist;
if (active_bodies_idx.size() > 0) {
if (active_group_names.size() > 0) {
model-> collisionDetect(dist, normals, ptsA, ptsB, bodyA_idx, bodyB_idx,
active_bodies_idx,active_group_names);
} else {
model-> collisionDetect(dist, normals, ptsA, ptsB, bodyA_idx, bodyB_idx,
active_bodies_idx);
}
} else {
if (active_group_names.size() > 0) {
model-> collisionDetect(dist, normals, ptsA, ptsB, bodyA_idx, bodyB_idx,
active_group_names);
} else {
model-> collisionDetect(dist, normals, ptsA, ptsB, bodyA_idx, bodyB_idx);
}
}
smoothDistancePenalty(penalty, dpenalty, model, min_distance, dist, normals, ptsA, ptsB, bodyA_idx, bodyB_idx);
vector<int32_T> idxA(bodyA_idx.size());
transform(bodyA_idx.begin(),bodyA_idx.end(),idxA.begin(),
[](int i){return ++i;});
vector<int32_T> idxB(bodyB_idx.size());
transform(bodyB_idx.begin(),bodyB_idx.end(),idxB.begin(),
[](int i){return ++i;});
if (nlhs>0) {
plhs[0] = mxCreateDoubleScalar(penalty);
}
if (nlhs>1) {
plhs[1] = mxCreateDoubleMatrix(dpenalty.rows(),dpenalty.cols(),mxREAL);
memcpy(mxGetPr(plhs[1]),dpenalty.data(),sizeof(double)*dpenalty.size());
}
}
<|endoftext|> |
<commit_before>/* Siconos-Kernel, Copyright INRIA 2005-2010.
* Siconos is a program dedicated to modeling, simulation and control
* of non smooth dynamical systems.
* Siconos is a 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
* (at your option) any later version.
* Siconos is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY ory 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 Siconos; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*
* Contact: Vincent ACARY, siconos-team@lists.gforge.inria.fr
*/
#include "FrictionContact.hpp"
#include "FrictionContactXML.hpp"
#include "Topology.hpp"
#include "Simulation.hpp"
#include "Model.hpp"
#include "NonSmoothDynamicalSystem.hpp"
#include "NewtonImpactFrictionNSL.hpp"
using namespace std;
using namespace RELATION;
FrictionContact::FrictionContact(int dimPb, const int newNumericsSolverId,
const std::string& newId):
LinearOSNS(newNumericsSolverId, "FrictionContact", newId), _contactProblemDim(dimPb)
{
if (dimPb == 2 && newNumericsSolverId == SICONOS_FRICTION_3D_NSGS)
_numerics_solver_id = SICONOS_FRICTION_2D_NSGS;
_numerics_problem.reset(new FrictionContactProblem);
if (dimPb == 2 || dimPb == 3)
frictionContact2D_setDefaultSolverOptions(&*_numerics_solver_options, _numerics_solver_id);
else
RuntimeException::selfThrow("cannot set defaults solver options for other problem dimension than 2 or 3");
}
// xml constructor
FrictionContact::FrictionContact(SP::OneStepNSProblemXML osNsPbXml):
LinearOSNS(osNsPbXml, "FrictionContact"), _contactProblemDim(3)
{
SP::FrictionContactXML xmlFC = boost::static_pointer_cast<FrictionContactXML>(osNsPbXml);
if (osNsPbXml->hasNumericsSolverName())
_numerics_solver_id = nameToId((char *)osNsPbXml->getNumericsSolverName().c_str());
else
_numerics_solver_id = SICONOS_FRICTION_3D_NSGS;
_numerics_problem.reset(new FrictionContactProblem);
// Read dimension of the problem (required parameter)
if (!xmlFC->hasProblemDim())
RuntimeException::selfThrow("FrictionContact: xml constructor failed, attribute for dimension of the problem (2D or 3D) is missing.");
_contactProblemDim = xmlFC->getProblemDim();
if (_contactProblemDim == 2 && _numerics_solver_id == SICONOS_FRICTION_3D_NSGS) _numerics_solver_id = SICONOS_FRICTION_2D_NSGS;
// initialize the _numerics_solver_options
if (_contactProblemDim == 2)
frictionContact2D_setDefaultSolverOptions(&*_numerics_solver_options, _numerics_solver_id);
else // if(_contactProblemDim == 3)
frictionContact3D_setDefaultSolverOptions(&*_numerics_solver_options, _numerics_solver_id);
}
void FrictionContact::initialize(SP::Simulation sim)
{
// - Checks memory allocation for main variables (M,q,w,z)
// - Formalizes the problem if the topology is time-invariant
// This function performs all steps that are time-invariant
// General initialize for OneStepNSProblem
LinearOSNS::initialize(sim);
// Connect to the right function according to dim. of the problem
if (_contactProblemDim == 2)
_frictionContact_driver = &frictionContact2D_driver;
else // if(_contactProblemDim == 3)
_frictionContact_driver = &frictionContact3D_driver;
// get topology
SP::Topology topology =
simulation()->model()->nonSmoothDynamicalSystem()->topology();
// Note that unitaryBlocks is up to date since updateUnitaryBlocks
// has been called during OneStepNSProblem::initialize()
// Fill vector of friction coefficients
int sizeMu = simulation()->model()->nonSmoothDynamicalSystem()
->topology()->indexSet(0)->size();
_mu.reset(new MuStorage());
_mu->reserve(sizeMu);
// If the topology is TimeInvariant ie if M structure does not
// change during simulation:
if (topology->isTimeInvariant() && !interactions()->isEmpty())
{
// Get index set from Simulation
SP::UnitaryRelationsGraph indexSet =
simulation()->indexSet(levelMin());
UnitaryRelationsGraph::VIterator ui, uiend;
for (boost::tie(ui, uiend) = indexSet->vertices(); ui != uiend; ++ui)
{
_mu->push_back(boost::static_pointer_cast<NewtonImpactFrictionNSL>
(indexSet->bundle(*ui)->interaction()->nonSmoothLaw())->mu());
}
}
}
int FrictionContact::compute(double time)
{
int info = 0;
// --- Prepare data for FrictionContact computing ---
preCompute(time);
// Update mu
_mu->clear();
SP::UnitaryRelationsGraph indexSet = simulation()->indexSet(levelMin());
UnitaryRelationsGraph::VIterator ui, uiend;
for (boost::tie(ui, uiend) = indexSet->vertices(); ui != uiend; ++ui)
{
_mu->push_back(boost::static_pointer_cast<NewtonImpactFrictionNSL>
(indexSet->bundle(*ui)->interaction()->nonSmoothLaw())->mu());
}
// --- Call Numerics driver ---
// Inputs:
// - the problem (M,q ...)
// - the unknowns (z,w)
// - the options for the solver (name, max iteration number ...)
// - the global options for Numerics (verbose mode ...)
if (_sizeOutput != 0)
{
// The FrictionContact Problem in Numerics format
FrictionContactProblem numerics_problem;
if (_contactProblemDim == 2)
numerics_problem.dimension = 2;
else // if(_contactProblemDim == 3)
numerics_problem.dimension = 3;
numerics_problem.M = &*_M->getNumericsMatrix();
numerics_problem.q = &*_q->getArray();
numerics_problem.numberOfContacts = _sizeOutput / _contactProblemDim;
numerics_problem.mu = &((*_mu)[0]);
// Call Numerics Driver for FrictionContact
info = (*_frictionContact_driver)(&numerics_problem,
&*_z->getArray() ,
&*_w->getArray() ,
&*_numerics_solver_options,
&*_numerics_options);
postCompute();
}
return info;
}
void FrictionContact::display() const
{
cout << "===== " << _contactProblemDim << "D Friction Contact Problem " << endl;
cout << "of size " << _sizeOutput << "(ie " << _sizeOutput / _contactProblemDim << " contacts)." << endl;
LinearOSNS::display();
}
FrictionContact* FrictionContact::convert(OneStepNSProblem* osnsp)
{
FrictionContact* fc2d = dynamic_cast<FrictionContact*>(osnsp);
return fc2d;
}
FrictionContact::~FrictionContact()
{
deleteSolverOptions(&*_numerics_solver_options);
}
<commit_msg>3D defaults options != 2D<commit_after>/* Siconos-Kernel, Copyright INRIA 2005-2010.
* Siconos is a program dedicated to modeling, simulation and control
* of non smooth dynamical systems.
* Siconos is a 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
* (at your option) any later version.
* Siconos is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY ory 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 Siconos; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*
* Contact: Vincent ACARY, siconos-team@lists.gforge.inria.fr
*/
#include "FrictionContact.hpp"
#include "FrictionContactXML.hpp"
#include "Topology.hpp"
#include "Simulation.hpp"
#include "Model.hpp"
#include "NonSmoothDynamicalSystem.hpp"
#include "NewtonImpactFrictionNSL.hpp"
using namespace std;
using namespace RELATION;
FrictionContact::FrictionContact(int dimPb, const int newNumericsSolverId,
const std::string& newId):
LinearOSNS(newNumericsSolverId, "FrictionContact", newId), _contactProblemDim(dimPb)
{
if (dimPb == 2 && newNumericsSolverId == SICONOS_FRICTION_3D_NSGS)
_numerics_solver_id = SICONOS_FRICTION_2D_NSGS;
_numerics_problem.reset(new FrictionContactProblem);
if (dimPb == 2)
frictionContact2D_setDefaultSolverOptions(&*_numerics_solver_options, _numerics_solver_id);
else if (dimPb == 3)
frictionContact3D_setDefaultSolverOptions(&*_numerics_solver_options, _numerics_solver_id);
else
RuntimeException::selfThrow("cannot set defaults solver options for other problem dimension than 2 or 3");
}
// xml constructor
FrictionContact::FrictionContact(SP::OneStepNSProblemXML osNsPbXml):
LinearOSNS(osNsPbXml, "FrictionContact"), _contactProblemDim(3)
{
SP::FrictionContactXML xmlFC = boost::static_pointer_cast<FrictionContactXML>(osNsPbXml);
if (osNsPbXml->hasNumericsSolverName())
_numerics_solver_id = nameToId((char *)osNsPbXml->getNumericsSolverName().c_str());
else
_numerics_solver_id = SICONOS_FRICTION_3D_NSGS;
_numerics_problem.reset(new FrictionContactProblem);
// Read dimension of the problem (required parameter)
if (!xmlFC->hasProblemDim())
RuntimeException::selfThrow("FrictionContact: xml constructor failed, attribute for dimension of the problem (2D or 3D) is missing.");
_contactProblemDim = xmlFC->getProblemDim();
if (_contactProblemDim == 2 && _numerics_solver_id == SICONOS_FRICTION_3D_NSGS) _numerics_solver_id = SICONOS_FRICTION_2D_NSGS;
// initialize the _numerics_solver_options
if (_contactProblemDim == 2)
frictionContact2D_setDefaultSolverOptions(&*_numerics_solver_options, _numerics_solver_id);
else // if(_contactProblemDim == 3)
frictionContact3D_setDefaultSolverOptions(&*_numerics_solver_options, _numerics_solver_id);
}
void FrictionContact::initialize(SP::Simulation sim)
{
// - Checks memory allocation for main variables (M,q,w,z)
// - Formalizes the problem if the topology is time-invariant
// This function performs all steps that are time-invariant
// General initialize for OneStepNSProblem
LinearOSNS::initialize(sim);
// Connect to the right function according to dim. of the problem
if (_contactProblemDim == 2)
_frictionContact_driver = &frictionContact2D_driver;
else // if(_contactProblemDim == 3)
_frictionContact_driver = &frictionContact3D_driver;
// get topology
SP::Topology topology =
simulation()->model()->nonSmoothDynamicalSystem()->topology();
// Note that unitaryBlocks is up to date since updateUnitaryBlocks
// has been called during OneStepNSProblem::initialize()
// Fill vector of friction coefficients
int sizeMu = simulation()->model()->nonSmoothDynamicalSystem()
->topology()->indexSet(0)->size();
_mu.reset(new MuStorage());
_mu->reserve(sizeMu);
// If the topology is TimeInvariant ie if M structure does not
// change during simulation:
if (topology->isTimeInvariant() && !interactions()->isEmpty())
{
// Get index set from Simulation
SP::UnitaryRelationsGraph indexSet =
simulation()->indexSet(levelMin());
UnitaryRelationsGraph::VIterator ui, uiend;
for (boost::tie(ui, uiend) = indexSet->vertices(); ui != uiend; ++ui)
{
_mu->push_back(boost::static_pointer_cast<NewtonImpactFrictionNSL>
(indexSet->bundle(*ui)->interaction()->nonSmoothLaw())->mu());
}
}
}
int FrictionContact::compute(double time)
{
int info = 0;
// --- Prepare data for FrictionContact computing ---
preCompute(time);
// Update mu
_mu->clear();
SP::UnitaryRelationsGraph indexSet = simulation()->indexSet(levelMin());
UnitaryRelationsGraph::VIterator ui, uiend;
for (boost::tie(ui, uiend) = indexSet->vertices(); ui != uiend; ++ui)
{
_mu->push_back(boost::static_pointer_cast<NewtonImpactFrictionNSL>
(indexSet->bundle(*ui)->interaction()->nonSmoothLaw())->mu());
}
// --- Call Numerics driver ---
// Inputs:
// - the problem (M,q ...)
// - the unknowns (z,w)
// - the options for the solver (name, max iteration number ...)
// - the global options for Numerics (verbose mode ...)
if (_sizeOutput != 0)
{
// The FrictionContact Problem in Numerics format
FrictionContactProblem numerics_problem;
if (_contactProblemDim == 2)
numerics_problem.dimension = 2;
else // if(_contactProblemDim == 3)
numerics_problem.dimension = 3;
numerics_problem.M = &*_M->getNumericsMatrix();
numerics_problem.q = &*_q->getArray();
numerics_problem.numberOfContacts = _sizeOutput / _contactProblemDim;
numerics_problem.mu = &((*_mu)[0]);
// Call Numerics Driver for FrictionContact
info = (*_frictionContact_driver)(&numerics_problem,
&*_z->getArray() ,
&*_w->getArray() ,
&*_numerics_solver_options,
&*_numerics_options);
postCompute();
}
return info;
}
void FrictionContact::display() const
{
cout << "===== " << _contactProblemDim << "D Friction Contact Problem " << endl;
cout << "of size " << _sizeOutput << "(ie " << _sizeOutput / _contactProblemDim << " contacts)." << endl;
LinearOSNS::display();
}
FrictionContact* FrictionContact::convert(OneStepNSProblem* osnsp)
{
FrictionContact* fc2d = dynamic_cast<FrictionContact*>(osnsp);
return fc2d;
}
FrictionContact::~FrictionContact()
{
deleteSolverOptions(&*_numerics_solver_options);
}
<|endoftext|> |
<commit_before>/*****************************************************************************
* cmd_input.cpp
*****************************************************************************
* Copyright (C) 2003 the VideoLAN team
* $Id$
*
* Authors: Cyril Deguet <asmax@via.ecp.fr>
* Olivier Teulière <ipkiss@via.ecp.fr>
*
* 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 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU 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., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA.
*****************************************************************************/
#include "cmd_input.hpp"
#include "cmd_dialogs.hpp"
#include <vlc_aout.h>
#include <vlc_input.h>
#include <vlc_playlist.h>
void CmdPlay::execute()
{
playlist_t *pPlaylist = getIntf()->p_sys->p_playlist;
if( pPlaylist == NULL )
{
return;
}
playlist_Lock( pPlaylist );
const bool b_empty = playlist_IsEmpty( pPlaylist );
playlist_Unlock( pPlaylist );
if( !b_empty )
{
playlist_Play( pPlaylist );
}
else
{
// If the playlist is empty, open a file requester instead
CmdDlgFile cmd( getIntf() );
cmd.execute();
}
}
void CmdPause::execute()
{
playlist_t *pPlaylist = getIntf()->p_sys->p_playlist;
if( pPlaylist == NULL )
{
return;
}
playlist_Pause( pPlaylist );
}
void CmdStop::execute()
{
playlist_t *pPlaylist = getIntf()->p_sys->p_playlist;
if( pPlaylist == NULL )
{
return;
}
playlist_Stop( pPlaylist );
}
void CmdSlower::execute()
{
playlist_t *pPlaylist = getIntf()->p_sys->p_playlist;
input_thread_t *pInput = playlist_CurrentInput( pPlaylist );
if( pInput )
{
vlc_value_t val;
val.b_bool = true;
var_Set( pInput, "rate-slower", val );
vlc_object_release( pInput );
}
}
void CmdFaster::execute()
{
playlist_t *pPlaylist = getIntf()->p_sys->p_playlist;
input_thread_t *pInput = playlist_CurrentInput( pPlaylist );
if( pInput )
{
vlc_value_t val;
val.b_bool = true;
var_Set( pInput, "rate-faster", val );
vlc_object_release( pInput );
}
}
void CmdMute::execute()
{
playlist_t *pPlaylist = getIntf()->p_sys->p_playlist;
aout_ToggleMute( pPlaylist, NULL );
}
void CmdVolumeUp::execute()
{
playlist_t *pPlaylist = getIntf()->p_sys->p_playlist;
aout_VolumeUp( pPlaylist, 1, NULL );
}
void CmdVolumeDown::execute()
{
playlist_t *pPlaylist = getIntf()->p_sys->p_playlist;
aout_VolumeDown( pPlaylist, 1, NULL );
}
<commit_msg>rate-(slower|faster) again.<commit_after>/*****************************************************************************
* cmd_input.cpp
*****************************************************************************
* Copyright (C) 2003 the VideoLAN team
* $Id$
*
* Authors: Cyril Deguet <asmax@via.ecp.fr>
* Olivier Teulière <ipkiss@via.ecp.fr>
*
* 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 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU 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., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA.
*****************************************************************************/
#include "cmd_input.hpp"
#include "cmd_dialogs.hpp"
#include <vlc_aout.h>
#include <vlc_input.h>
#include <vlc_playlist.h>
void CmdPlay::execute()
{
playlist_t *pPlaylist = getIntf()->p_sys->p_playlist;
if( pPlaylist == NULL )
{
return;
}
playlist_Lock( pPlaylist );
const bool b_empty = playlist_IsEmpty( pPlaylist );
playlist_Unlock( pPlaylist );
if( !b_empty )
{
playlist_Play( pPlaylist );
}
else
{
// If the playlist is empty, open a file requester instead
CmdDlgFile cmd( getIntf() );
cmd.execute();
}
}
void CmdPause::execute()
{
playlist_t *pPlaylist = getIntf()->p_sys->p_playlist;
if( pPlaylist == NULL )
{
return;
}
playlist_Pause( pPlaylist );
}
void CmdStop::execute()
{
playlist_t *pPlaylist = getIntf()->p_sys->p_playlist;
if( pPlaylist == NULL )
{
return;
}
playlist_Stop( pPlaylist );
}
void CmdSlower::execute()
{
playlist_t *pPlaylist = getIntf()->p_sys->p_playlist;
input_thread_t *pInput = playlist_CurrentInput( pPlaylist );
if( pInput )
{
var_TriggerCallback( pInput, "rate-slower" );
vlc_object_release( pInput );
}
}
void CmdFaster::execute()
{
playlist_t *pPlaylist = getIntf()->p_sys->p_playlist;
input_thread_t *pInput = playlist_CurrentInput( pPlaylist );
if( pInput )
{
var_TriggerCallback( pInput, "rate-faster" );
vlc_object_release( pInput );
}
}
void CmdMute::execute()
{
playlist_t *pPlaylist = getIntf()->p_sys->p_playlist;
aout_ToggleMute( pPlaylist, NULL );
}
void CmdVolumeUp::execute()
{
playlist_t *pPlaylist = getIntf()->p_sys->p_playlist;
aout_VolumeUp( pPlaylist, 1, NULL );
}
void CmdVolumeDown::execute()
{
playlist_t *pPlaylist = getIntf()->p_sys->p_playlist;
aout_VolumeDown( pPlaylist, 1, NULL );
}
<|endoftext|> |
<commit_before>/******************************************************************************
**
** Copyright (C) 2009-2011 Kyle Lutz <kyle.r.lutz@gmail.com>
** All rights reserved.
**
** This file is a part of the chemkit project. For more information
** see <http://www.chemkit.org>.
**
** 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 chemkit project nor the names of its
** contributors may be used to endorse or promote products derived
** from this software without specific prior written permission.
**
** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
** "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
** LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
** A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
** OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
** LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
** DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
** THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
** (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
**
******************************************************************************/
#include "residuetest.h"
#include <chemkit/chemkit.h>
#include <chemkit/residue.h>
#include <chemkit/molecule.h>
void ResidueTest::molecule()
{
chemkit::Molecule molecule;
chemkit::Residue *residue = new chemkit::Residue(&molecule);
QVERIFY(residue->molecule() == &molecule);
}
void ResidueTest::atomType()
{
chemkit::Molecule molecule;
chemkit::Residue *residue = new chemkit::Residue(&molecule);
chemkit::Atom *c1 = molecule.addAtom("C");
chemkit::Atom *c2 = molecule.addAtom("C");
residue->addAtom(c1);
residue->addAtom(c2);
QCOMPARE(residue->atomType(c1), std::string());
QCOMPARE(residue->atomType(c2), std::string());
residue->setAtomType(c1, "C1");
QCOMPARE(residue->atomType(c1), std::string("C1"));
QVERIFY(residue->atom("C1") == c1);
QVERIFY(residue->atom("C2") == 0);
residue->setAtomType(c2, "C2");
QCOMPARE(residue->atomType(c2), std::string("C2"));
QVERIFY(residue->atom("C2") == c2);
}
QTEST_APPLESS_MAIN(ResidueTest)
<commit_msg>Fix memory leak in ResidueTest<commit_after>/******************************************************************************
**
** Copyright (C) 2009-2011 Kyle Lutz <kyle.r.lutz@gmail.com>
** All rights reserved.
**
** This file is a part of the chemkit project. For more information
** see <http://www.chemkit.org>.
**
** 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 chemkit project nor the names of its
** contributors may be used to endorse or promote products derived
** from this software without specific prior written permission.
**
** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
** "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
** LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
** A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
** OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
** LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
** DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
** THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
** (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
**
******************************************************************************/
#include "residuetest.h"
#include <chemkit/chemkit.h>
#include <chemkit/residue.h>
#include <chemkit/molecule.h>
void ResidueTest::molecule()
{
chemkit::Molecule molecule;
chemkit::Residue residue(&molecule);
QVERIFY(residue.molecule() == &molecule);
}
void ResidueTest::atomType()
{
chemkit::Molecule molecule;
chemkit::Residue residue(&molecule);
chemkit::Atom *c1 = molecule.addAtom("C");
chemkit::Atom *c2 = molecule.addAtom("C");
residue.addAtom(c1);
residue.addAtom(c2);
QCOMPARE(residue.atomType(c1), std::string());
QCOMPARE(residue.atomType(c2), std::string());
residue.setAtomType(c1, "C1");
QCOMPARE(residue.atomType(c1), std::string("C1"));
QVERIFY(residue.atom("C1") == c1);
QVERIFY(residue.atom("C2") == 0);
residue.setAtomType(c2, "C2");
QCOMPARE(residue.atomType(c2), std::string("C2"));
QVERIFY(residue.atom("C2") == c2);
}
QTEST_APPLESS_MAIN(ResidueTest)
<|endoftext|> |
<commit_before>/*********************************************************************************
*
* Inviwo - Interactive Visualization Workshop
*
* Copyright (c) 2019 Inviwo Foundation
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
* ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
*********************************************************************************/
#include <modules/python3/pyutils.h>
#include <warn/push>
#include <warn/ignore/shadow>
#include <pybind11/pybind11.h>
#include <warn/pop>
namespace inviwo {
namespace pyutil {
void addModulePath(const std::string& path) {
namespace py = pybind11;
if (!Py_IsInitialized()) {
throw Exception("addModulePath(): Python is not initialized", IVW_CONTEXT_CUSTOM("pyutil"));
}
std::string pathConv = path;
replaceInString(pathConv, "\\", "/");
py::module::import("sys").attr("path").cast<py::list>().append(pathConv);
}
void removeModulePath(const std::string& path) {
namespace py = pybind11;
if (!Py_IsInitialized()) {
throw Exception("addModulePath(): Python is not initialized", IVW_CONTEXT_CUSTOM("pyutil"));
}
std::string pathConv = path;
replaceInString(pathConv, "\\", "/");
py::module::import("sys").attr("path").attr("remove")(pathConv);
}
ModulePath::ModulePath(const std::string& path) : path_{path} { addModulePath(path_); }
ModulePath::~ModulePath() { removeModulePath(path_); }
} // namespace pyutil
} // namespace inviwo
<commit_msg>Python: MIssing include<commit_after>/*********************************************************************************
*
* Inviwo - Interactive Visualization Workshop
*
* Copyright (c) 2019 Inviwo Foundation
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
* ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
*********************************************************************************/
#include <modules/python3/pyutils.h>
#include <inviwo/core/util/sourcecontext.h>
#include <inviwo/core/util/exception.h>
#include <inviwo/core/util/stringconversion.h>
#include <warn/push>
#include <warn/ignore/shadow>
#include <pybind11/pybind11.h>
#include <warn/pop>
namespace inviwo {
namespace pyutil {
void addModulePath(const std::string& path) {
namespace py = pybind11;
if (!Py_IsInitialized()) {
throw Exception("addModulePath(): Python is not initialized", IVW_CONTEXT_CUSTOM("pyutil"));
}
std::string pathConv = path;
replaceInString(pathConv, "\\", "/");
py::module::import("sys").attr("path").cast<py::list>().append(pathConv);
}
void removeModulePath(const std::string& path) {
namespace py = pybind11;
if (!Py_IsInitialized()) {
throw Exception("addModulePath(): Python is not initialized", IVW_CONTEXT_CUSTOM("pyutil"));
}
std::string pathConv = path;
replaceInString(pathConv, "\\", "/");
py::module::import("sys").attr("path").attr("remove")(pathConv);
}
ModulePath::ModulePath(const std::string& path) : path_{path} { addModulePath(path_); }
ModulePath::~ModulePath() { removeModulePath(path_); }
} // namespace pyutil
} // namespace inviwo
<|endoftext|> |
<commit_before>#include <cstdio>
#include <cmath>
#include "../../inmost.h"
using namespace INMOST;
int main(int argc,char ** argv)
{
int permut = 0;
int solver = 0; // 0 - INNER_ILU2, 1 - INNER_MLILUC, 2 - PETSc
// 3 - Trilinos_Aztec, 4 - Trilinos_Ifpack,
// 5 - Trilinos_ML, 6 - Trilinos_Belos, 7 - ANI
int rank,procs,newrank;
Solver::Initialize(&argc,&argv,"database.txt"); // Initialize the solver and MPI activity
#if defined(USE_MPI)
MPI_Comm_rank(MPI_COMM_WORLD,&rank); // Get the rank of the current process
MPI_Comm_size(MPI_COMM_WORLD,&procs); // Get the total number of processors used
#else
rank = 0;
procs = 1;
#endif
if (argc > 1) permut = atoi(argv[1]);
if (argc > 2) solver = atoi(argv[2]);
if (permut < procs) newrank = (rank + permut) % procs;
else newrank = (permut - rank) % procs;
std::cout << rank << " -> " << newrank << std::endl;
Solver::Type type;
switch(solver)
{
case 0: type = Solver::INNER_ILU2; break;
case 1: type = Solver::INNER_MLILUC; break;
case 2: type = Solver::PETSc; break;
case 3: type = Solver::Trilinos_Aztec; break;
case 4: type = Solver::Trilinos_Ifpack; break;
case 5: type = Solver::Trilinos_ML; break;
case 6: type = Solver::Trilinos_Belos; break;
case 7: type = Solver::ANI; break;
}
{
Solver S(type); // Specify the linear solver
Solver::Matrix A; // Declare the matrix of the linear system to be solved
Solver::Vector x,b; // Declare the solution and the right-hand side vectors
INMOST_DATA_ENUM_TYPE mbeg, mend;
mbeg = newrank * 10;
mend = (newrank+1) * 10;
A.SetInterval(mbeg,mend);
x.SetInterval(mbeg,mend);
b.SetInterval(mbeg,mend);
for( INMOST_DATA_ENUM_TYPE i = mbeg; i != mend; i++ )
{
A[i][i] = 10.0;
b[i] = i;
x[i] = 0.1;
}
if (rank==0) std::cout << "next call S.SetMatrix(A);" << std::endl;
S.SetMatrix(A); // Compute the preconditioner for the original matrix
if (rank==0) std::cout << "next call S.Solve(b,x);" << std::endl;
if( !S.Solve(b,x) ) // Solve the linear system with the previously computted preconditioner
{
if( rank == 0 )
std::cout << S.GetReason() << std::endl;
MPI_Abort(MPI_COMM_WORLD,-1);
}
double err = 0;
for( INMOST_DATA_ENUM_TYPE i = mbeg; i != mend; i++ )
{
err += (x[i] - static_cast<double>(i)/10.0);
}
#if defined(USE_MPI)
double tmp;
MPI_Allreduce(&err,&tmp,1,MPI_DOUBLE,MPI_SUM,MPI_COMM_WORLD);
err = tmp;
#endif
if (rank==0)
{
std::cout << "done, error " << err << "\t\t\t" << std::endl;
}
if( fabs(err) > 1.0e-5 || err!=err) MPI_Abort(MPI_COMM_WORLD,-1);
x.Save("output.rhs");
b.Save("b.rhs");
A.Save("A.mtx");
}
Solver::Finalize(); // Finalize solver and close MPI activity
return 0;
}<commit_msg>Tests: solver_test000: use L1 norm for validation<commit_after>#include <cstdio>
#include <cmath>
#include "../../inmost.h"
using namespace INMOST;
int main(int argc,char ** argv)
{
int permut = 0;
int solver = 0; // 0 - INNER_ILU2, 1 - INNER_MLILUC, 2 - PETSc
// 3 - Trilinos_Aztec, 4 - Trilinos_Ifpack,
// 5 - Trilinos_ML, 6 - Trilinos_Belos, 7 - ANI
int rank,procs,newrank;
Solver::Initialize(&argc,&argv,"database.txt"); // Initialize the solver and MPI activity
#if defined(USE_MPI)
MPI_Comm_rank(MPI_COMM_WORLD,&rank); // Get the rank of the current process
MPI_Comm_size(MPI_COMM_WORLD,&procs); // Get the total number of processors used
#else
rank = 0;
procs = 1;
#endif
if (argc > 1) permut = atoi(argv[1]);
if (argc > 2) solver = atoi(argv[2]);
if (permut < procs) newrank = (rank + permut) % procs;
else newrank = (permut - rank) % procs;
std::cout << rank << " -> " << newrank << std::endl;
Solver::Type type;
switch(solver)
{
case 0: type = Solver::INNER_ILU2; break;
case 1: type = Solver::INNER_MLILUC; break;
case 2: type = Solver::PETSc; break;
case 3: type = Solver::Trilinos_Aztec; break;
case 4: type = Solver::Trilinos_Ifpack; break;
case 5: type = Solver::Trilinos_ML; break;
case 6: type = Solver::Trilinos_Belos; break;
case 7: type = Solver::ANI; break;
}
{
Solver S(type); // Specify the linear solver
Solver::Matrix A; // Declare the matrix of the linear system to be solved
Solver::Vector x,b; // Declare the solution and the right-hand side vectors
INMOST_DATA_ENUM_TYPE mbeg, mend;
mbeg = newrank * 10;
mend = (newrank+1) * 10;
A.SetInterval(mbeg,mend);
x.SetInterval(mbeg,mend);
b.SetInterval(mbeg,mend);
for( INMOST_DATA_ENUM_TYPE i = mbeg; i != mend; i++ )
{
A[i][i] = 10.0;
b[i] = i;
x[i] = 0.1;
}
if (rank==0) std::cout << "next call S.SetMatrix(A);" << std::endl;
S.SetMatrix(A); // Compute the preconditioner for the original matrix
if (rank==0) std::cout << "next call S.Solve(b,x);" << std::endl;
if( !S.Solve(b,x) ) // Solve the linear system with the previously computted preconditioner
{
if( rank == 0 )
std::cout << S.GetReason() << std::endl;
MPI_Abort(MPI_COMM_WORLD,-1);
}
double err = 0;
for( INMOST_DATA_ENUM_TYPE i = mbeg; i != mend; i++ )
{
err += fabs(x[i] - static_cast<double>(i)/10.0);
}
#if defined(USE_MPI)
double tmp;
MPI_Allreduce(&err,&tmp,1,MPI_DOUBLE,MPI_SUM,MPI_COMM_WORLD);
err = tmp;
#endif
if (rank==0)
{
std::cout << "done, error " << err << "\t\t\t" << std::endl;
}
if( err > 1.0e-5 || err!=err) MPI_Abort(MPI_COMM_WORLD,-1);
x.Save("output.rhs");
b.Save("b.rhs");
A.Save("A.mtx");
}
Solver::Finalize(); // Finalize solver and close MPI activity
return 0;
}
<|endoftext|> |
<commit_before>/*
* Copyright (C) 2016-2018 Muhammad Tayyab Akram
*
* 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 <cassert>
#include <cstddef>
#include <cstring>
#include <vector>
extern "C" {
#include <Source/SFPattern.h>
#include <Source/SFScheme.h>
#include <Source/SFShapingKnowledge.h>
}
#include "OpenType/Builder.h"
#include "OpenType/Common.h"
#include "OpenType/GSUB.h"
#include "Utilities/General.h"
#include "Utilities/SFPattern+Testing.h"
#include "SchemeTester.h"
using namespace std;
using namespace SheenFigure::Tester;
using namespace SheenFigure::Tester::OpenType;
using namespace SheenFigure::Tester::Utilities;
class TestKnowledge {
public:
static SFShapingKnowledgeRef instance() { return &object->knowledge.shape; }
private:
static TestKnowledge *object;
struct {
vector<SFFeatureInfo> subst;
vector<SFFeatureInfo> pos;
} features;
struct {
SFScriptKnowledge script;
SFShapingKnowledge shape;
} knowledge;
static SFScriptKnowledgeRef seekScript(const void *, SFTag scriptTag)
{
if (scriptTag == tag("test")) {
return &object->knowledge.script;
}
return NULL;
}
TestKnowledge() {
features.subst = {
/* First Group. */
{ 1, tag("srqi"), REQUIRED, INDIVIDUAL, 0x00 },
{ 1, tag("srq1"), REQUIRED, SIMULTANEOUS, 0x00 },
{ 1, tag("son1"), ON_BY_DEFAULT, SIMULTANEOUS, 0x00 },
{ 1, tag("sof1"), OFF_BY_DEFAULT, SIMULTANEOUS, 0x00 },
/* Second Group. */
{ 2, tag("sim1"), REQUIRED, SIMULTANEOUS, 0x00 },
{ 2, tag("sim2"), REQUIRED, SIMULTANEOUS, 0x00 },
};
features.pos = {
/* Third Group. */
{ 3, tag("pof1"), OFF_BY_DEFAULT, SIMULTANEOUS, 0x00 },
{ 3, tag("pon1"), ON_BY_DEFAULT, SIMULTANEOUS, 0x00 },
{ 3, tag("prq1"), REQUIRED, SIMULTANEOUS, 0x00 },
{ 3, tag("prqi"), REQUIRED, INDIVIDUAL, 0x00 },
};
knowledge.script = {
SFTextDirectionLeftToRight,
{ features.subst.data(), features.subst.size() },
{ features.pos.data(), features.pos.size() }
};
knowledge.shape = {
&seekScript
};
}
};
TestKnowledge *TestKnowledge::object = new TestKnowledge();
static const UInt16 CUST = 0;
static const UInt16 PCST = 1;
static const UInt16 POF1 = 2;
static const UInt16 PON1 = 3;
static const UInt16 PRQ1 = 4;
static const UInt16 PRQI = 5;
static const UInt16 SCST = 6;
static const UInt16 SIM1 = 7;
static const UInt16 SIM2 = 8;
static const UInt16 SOF1 = 9;
static const UInt16 SON1 = 10;
static const UInt16 SRQ1 = 11;
static const UInt16 SRQI = 12;
static void loadTable(void *, SFTag tableTag, SFUInt8 *buffer, SFUInteger *length)
{
if (tableTag == tag("GSUB")) {
Builder builder;
FeatureListTable &featureList = builder.createFeatureList({
{tag("cust"), builder.createFeature({ CUST })},
{tag("scst"), builder.createFeature({ SCST })},
{tag("sim1"), builder.createFeature({ SIM1 })},
{tag("sim2"), builder.createFeature({ SIM2 })},
{tag("sof1"), builder.createFeature({ SOF1 })},
{tag("son1"), builder.createFeature({ SON1 })},
{tag("srq1"), builder.createFeature({ SRQ1 })},
{tag("srqi"), builder.createFeature({ SRQI })},
});
ScriptListTable &scriptList = builder.createScriptList({
{tag("test"), builder.createScript(builder.createLangSys({ 0, 1, 2, 3, 4, 5, 6, 7 }), {
{tag("LNG "), builder.createLangSys({ 7 })}
})}
});
GSUB &gsub = builder.createGSUB(&scriptList, &featureList, NULL);
Writer writer;
writer.write(&gsub);
if (length) {
*length = (SFUInteger)writer.size();
}
if (buffer) {
memcpy(buffer, writer.data(), (size_t)writer.size());
}
} else if (tableTag == tag("GPOS")) {
Builder builder;
FeatureListTable &featureList = builder.createFeatureList({
{tag("cust"), builder.createFeature({ CUST })},
{tag("pcst"), builder.createFeature({ PCST })},
{tag("pof1"), builder.createFeature({ POF1 })},
{tag("pon1"), builder.createFeature({ PON1 })},
{tag("prq1"), builder.createFeature({ PRQ1 })},
{tag("prqi"), builder.createFeature({ PRQI })},
});
ScriptListTable &scriptList = builder.createScriptList({
{tag("test"), builder.createScript(builder.createLangSys({ 0, 1, 2, 3, 4, 5 }), {
{tag("LNG "), builder.createLangSys({ 2 })}
})}
});
GPOS &gpos = builder.createGPOS(&scriptList, &featureList, NULL);
Writer writer;
writer.write(&gpos);
if (length) {
*length = (SFUInteger)writer.size();
}
if (buffer) {
memcpy(buffer, writer.data(), (size_t)writer.size());
}
}
}
static SFGlyphID getGlyphIDForCodepoint(void *, SFCodepoint)
{
return 0;
}
static SFAdvance getAdvanceForGlyph(void *, SFFontLayout, SFGlyphID)
{
return 0;
}
SchemeTester::SchemeTester()
{
}
void SchemeTester::testFeatures()
{
/* Test unique features. */
{
SFSchemeRef scheme = SFSchemeCreate();
SFTag featureTags[] = {
tag("ccmp"), tag("liga"), tag("dist"), tag("kern")
};
SFUInt16 featureValues[] = {
1, 2, 3, 4
};
SFUInteger featureCount = sizeof(featureValues) / sizeof(SFUInt16);
SFSchemeSetFeatureValues(scheme, featureTags, featureValues, featureCount);
assert(memcmp(scheme->_featureTags, featureTags, sizeof(featureTags)) == 0);
assert(memcmp(scheme->_featureValues, featureValues, sizeof(featureValues)) == 0);
assert(scheme->_featureCount == featureCount);
SFSchemeRelease(scheme);
}
/* Test duplicated features. */
{
SFSchemeRef scheme = SFSchemeCreate();
SFTag featureTags[] = {
tag("ccmp"), tag("liga"), tag("dist"), tag("kern"), tag("ccmp"), tag("kern")
};
SFUInt16 featureValues[] = {
1, 2, 3, 4, 5, 6
};
SFUInteger featureCount = sizeof(featureValues) / sizeof(SFUInt16);
SFSchemeSetFeatureValues(scheme, featureTags, featureValues, featureCount);
SFTag expectedTags[] = {
tag("ccmp"), tag("liga"), tag("dist"), tag("kern")
};
SFUInt16 expectedValues[] = {
5, 2, 3, 6
};
SFUInteger expectedCount = sizeof(expectedValues) / sizeof(SFUInt16);
assert(memcmp(scheme->_featureTags, expectedTags, sizeof(expectedTags)) == 0);
assert(memcmp(scheme->_featureValues, expectedValues, sizeof(expectedValues)) == 0);
assert(scheme->_featureCount == expectedCount);
SFSchemeRelease(scheme);
}
}
void SchemeTester::testBuild()
{
const SFFontProtocol protocol = {
.finalize = NULL,
.loadTable = &loadTable,
.getGlyphIDForCodepoint = &getGlyphIDForCodepoint,
.getAdvanceForGlyph = &getAdvanceForGlyph,
};
SFFontRef font = SFFontCreateWithProtocol(&protocol, NULL);
SFScheme scheme;
SFSchemeInitialize(&scheme, TestKnowledge::instance());
SFSchemeSetFont(&scheme, font);
SFSchemeSetScriptTag(&scheme, tag("test"));
/* Test with default language. */
{
SFSchemeSetLanguageTag(&scheme, tag("dflt"));
SFPatternRef pattern = SFSchemeBuildPattern(&scheme);
SFTag expectedTags[] = {
tag("srqi"), tag("srq1"), tag("son1"), tag("sim1"), tag("sim2"),
tag("pon1"), tag("prq1"), tag("prqi")
};
SFLookupInfo expectedLookups[] = {
{SRQI, 1}, {SON1, 1}, {SRQ1, 1}, {SIM1, 1}, {SIM2, 1},
{PON1, 1}, {PRQ1, 1}, {PRQI, 1}
};
SFFeatureUnit expectedUnits[] = {
{ { &expectedLookups[0], 1 }, { 0, 1 }, 0x00 },
{ { &expectedLookups[1], 2 }, { 1, 2 }, 0x00 },
{ { &expectedLookups[3], 2 }, { 3, 2 }, 0x00 },
{ { &expectedLookups[5], 2 }, { 5, 2 }, 0x00 },
{ { &expectedLookups[7], 1 }, { 7, 1 }, 0x00 },
};
SFPattern expectedPattern = {
.font = font,
.featureTags = { expectedTags, 8 },
.featureUnits = { expectedUnits, 3, 2 },
.scriptTag = tag("test"),
.languageTag = tag("dflt"),
.defaultDirection = SFTextDirectionLeftToRight,
};
assert(SFPatternEqualToPattern(pattern, &expectedPattern));
SFPatternRelease(pattern);
}
/* Test with a non-default language. */
{
SFSchemeSetLanguageTag(&scheme, tag("LNG "));
SFPatternRef pattern = SFSchemeBuildPattern(&scheme);
SFTag expectedTags[] = { tag("srqi") };
SFLookupInfo expectedLookups[] = { {SRQI, 1} };
SFFeatureUnit expectedUnits[] = {
{ { &expectedLookups[0], 1 }, { 0, 1 }, 0x00 },
};
SFPattern expectedPattern = {
.font = font,
.featureTags = { expectedTags, 1 },
.featureUnits = { expectedUnits, 1, 0 },
.scriptTag = tag("test"),
.languageTag = tag("LNG "),
.defaultDirection = SFTextDirectionLeftToRight,
};
assert(SFPatternEqualToPattern(pattern, &expectedPattern));
SFPatternRelease(pattern);
}
/* Test by trying to turn off required features. */
/* Test by disabling a feature marked as on by default. */
/* Test by enabling a feature marked as off by default. */
/* Test by setting custom value of a required feature. */
/* Test by setting custom value of a feature marked as on by default. */
/* Test by setting custom value of a feature marked as off by default. */
/* Test by enabling simultaneous features across multiple groups. */
/* Test by enabling custom features of GSUB and GPOS. */
/* Test by enabling a custom feature available in both GSUB and GPOS. */
{
SFTag featureTags[] = {
tag("srqi"), tag("prq1"), tag("son1"), tag("sof1"), tag("prqi"),
tag("pon1"), tag("pof1"), tag("scst"), tag("pcst"), tag("cust")
};
SFUInt16 featureValues[] = {
0, 0, 0, 1, 2, 3, 4, 5, 6, 7
};
SFSchemeSetLanguageTag(&scheme, tag("dflt"));
SFSchemeSetFeatureValues(&scheme, featureTags, featureValues, sizeof(featureValues) / sizeof(SFUInt16));
SFPatternRef pattern = SFSchemeBuildPattern(&scheme);
SFTag expectedTags[] = {
tag("srqi"), tag("srq1"), tag("sof1"), tag("sim1"), tag("sim2"), tag("scst"), tag("cust"),
tag("pof1"), tag("pon1"), tag("prq1"), tag("prqi"), tag("pcst")
};
SFLookupInfo expectedLookups[] = {
{SRQI, 1}, {SOF1, 1}, {SRQ1, 1}, {SIM1, 1}, {SIM2, 1}, {CUST, 7}, {SCST, 5},
{POF1, 4}, {PON1, 3}, {PRQ1, 1}, {PRQI, 2}, {PCST, 6}
};
SFFeatureUnit expectedUnits[] = {
{ { &expectedLookups[0], 1 }, { 0, 1 }, 0x00 },
{ { &expectedLookups[1], 2 }, { 1, 2 }, 0x00 },
{ { &expectedLookups[3], 2 }, { 3, 2 }, 0x00 },
{ { &expectedLookups[5], 2 }, { 5, 2 }, 0x00 },
{ { &expectedLookups[7], 3 }, { 7, 3 }, 0x00 },
{ { &expectedLookups[10], 1 }, { 10, 1 }, 0x00 },
{ { &expectedLookups[11], 1 }, { 11, 1 }, 0x00 },
};
SFPattern expectedPattern = {
.font = font,
.featureTags = { expectedTags, 12 },
.featureUnits = { expectedUnits, 4, 3 },
.scriptTag = tag("test"),
.languageTag = tag("dflt"),
.defaultDirection = SFTextDirectionLeftToRight,
};
assert(SFPatternEqualToPattern(pattern, &expectedPattern));
SFPatternRelease(pattern);
}
SFSchemeFinalize(&scheme);
SFFontRelease(font);
}
void SchemeTester::test()
{
testFeatures();
testBuild();
}
<commit_msg>[test] Left designated initializers in scheme tester<commit_after>/*
* Copyright (C) 2016-2018 Muhammad Tayyab Akram
*
* 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 <cassert>
#include <cstddef>
#include <cstring>
#include <vector>
extern "C" {
#include <Source/SFPattern.h>
#include <Source/SFScheme.h>
#include <Source/SFShapingKnowledge.h>
}
#include "OpenType/Builder.h"
#include "OpenType/Common.h"
#include "OpenType/GSUB.h"
#include "Utilities/General.h"
#include "Utilities/SFPattern+Testing.h"
#include "SchemeTester.h"
using namespace std;
using namespace SheenFigure::Tester;
using namespace SheenFigure::Tester::OpenType;
using namespace SheenFigure::Tester::Utilities;
class TestKnowledge {
public:
static SFShapingKnowledgeRef instance() { return &object->knowledge.shape; }
private:
static TestKnowledge *object;
struct {
vector<SFFeatureInfo> subst;
vector<SFFeatureInfo> pos;
} features;
struct {
SFScriptKnowledge script;
SFShapingKnowledge shape;
} knowledge;
static SFScriptKnowledgeRef seekScript(const void *, SFTag scriptTag)
{
if (scriptTag == tag("test")) {
return &object->knowledge.script;
}
return NULL;
}
TestKnowledge() {
features.subst = {
/* First Group. */
{ 1, tag("srqi"), REQUIRED, INDIVIDUAL, 0x00 },
{ 1, tag("srq1"), REQUIRED, SIMULTANEOUS, 0x00 },
{ 1, tag("son1"), ON_BY_DEFAULT, SIMULTANEOUS, 0x00 },
{ 1, tag("sof1"), OFF_BY_DEFAULT, SIMULTANEOUS, 0x00 },
/* Second Group. */
{ 2, tag("sim1"), REQUIRED, SIMULTANEOUS, 0x00 },
{ 2, tag("sim2"), REQUIRED, SIMULTANEOUS, 0x00 },
};
features.pos = {
/* Third Group. */
{ 3, tag("pof1"), OFF_BY_DEFAULT, SIMULTANEOUS, 0x00 },
{ 3, tag("pon1"), ON_BY_DEFAULT, SIMULTANEOUS, 0x00 },
{ 3, tag("prq1"), REQUIRED, SIMULTANEOUS, 0x00 },
{ 3, tag("prqi"), REQUIRED, INDIVIDUAL, 0x00 },
};
knowledge.script = {
SFTextDirectionLeftToRight,
{ features.subst.data(), features.subst.size() },
{ features.pos.data(), features.pos.size() }
};
knowledge.shape = {
&seekScript
};
}
};
TestKnowledge *TestKnowledge::object = new TestKnowledge();
static const UInt16 CUST = 0;
static const UInt16 PCST = 1;
static const UInt16 POF1 = 2;
static const UInt16 PON1 = 3;
static const UInt16 PRQ1 = 4;
static const UInt16 PRQI = 5;
static const UInt16 SCST = 6;
static const UInt16 SIM1 = 7;
static const UInt16 SIM2 = 8;
static const UInt16 SOF1 = 9;
static const UInt16 SON1 = 10;
static const UInt16 SRQ1 = 11;
static const UInt16 SRQI = 12;
static void loadTable(void *, SFTag tableTag, SFUInt8 *buffer, SFUInteger *length)
{
if (tableTag == tag("GSUB")) {
Builder builder;
FeatureListTable &featureList = builder.createFeatureList({
{tag("cust"), builder.createFeature({ CUST })},
{tag("scst"), builder.createFeature({ SCST })},
{tag("sim1"), builder.createFeature({ SIM1 })},
{tag("sim2"), builder.createFeature({ SIM2 })},
{tag("sof1"), builder.createFeature({ SOF1 })},
{tag("son1"), builder.createFeature({ SON1 })},
{tag("srq1"), builder.createFeature({ SRQ1 })},
{tag("srqi"), builder.createFeature({ SRQI })},
});
ScriptListTable &scriptList = builder.createScriptList({
{tag("test"), builder.createScript(builder.createLangSys({ 0, 1, 2, 3, 4, 5, 6, 7 }), {
{tag("LNG "), builder.createLangSys({ 7 })}
})}
});
GSUB &gsub = builder.createGSUB(&scriptList, &featureList, NULL);
Writer writer;
writer.write(&gsub);
if (length) {
*length = (SFUInteger)writer.size();
}
if (buffer) {
memcpy(buffer, writer.data(), (size_t)writer.size());
}
} else if (tableTag == tag("GPOS")) {
Builder builder;
FeatureListTable &featureList = builder.createFeatureList({
{tag("cust"), builder.createFeature({ CUST })},
{tag("pcst"), builder.createFeature({ PCST })},
{tag("pof1"), builder.createFeature({ POF1 })},
{tag("pon1"), builder.createFeature({ PON1 })},
{tag("prq1"), builder.createFeature({ PRQ1 })},
{tag("prqi"), builder.createFeature({ PRQI })},
});
ScriptListTable &scriptList = builder.createScriptList({
{tag("test"), builder.createScript(builder.createLangSys({ 0, 1, 2, 3, 4, 5 }), {
{tag("LNG "), builder.createLangSys({ 2 })}
})}
});
GPOS &gpos = builder.createGPOS(&scriptList, &featureList, NULL);
Writer writer;
writer.write(&gpos);
if (length) {
*length = (SFUInteger)writer.size();
}
if (buffer) {
memcpy(buffer, writer.data(), (size_t)writer.size());
}
}
}
SchemeTester::SchemeTester()
{
}
void SchemeTester::testFeatures()
{
/* Test unique features. */
{
SFSchemeRef scheme = SFSchemeCreate();
SFTag featureTags[] = {
tag("ccmp"), tag("liga"), tag("dist"), tag("kern")
};
SFUInt16 featureValues[] = {
1, 2, 3, 4
};
SFUInteger featureCount = sizeof(featureValues) / sizeof(SFUInt16);
SFSchemeSetFeatureValues(scheme, featureTags, featureValues, featureCount);
assert(memcmp(scheme->_featureTags, featureTags, sizeof(featureTags)) == 0);
assert(memcmp(scheme->_featureValues, featureValues, sizeof(featureValues)) == 0);
assert(scheme->_featureCount == featureCount);
SFSchemeRelease(scheme);
}
/* Test duplicated features. */
{
SFSchemeRef scheme = SFSchemeCreate();
SFTag featureTags[] = {
tag("ccmp"), tag("liga"), tag("dist"), tag("kern"), tag("ccmp"), tag("kern")
};
SFUInt16 featureValues[] = {
1, 2, 3, 4, 5, 6
};
SFUInteger featureCount = sizeof(featureValues) / sizeof(SFUInt16);
SFSchemeSetFeatureValues(scheme, featureTags, featureValues, featureCount);
SFTag expectedTags[] = {
tag("ccmp"), tag("liga"), tag("dist"), tag("kern")
};
SFUInt16 expectedValues[] = {
5, 2, 3, 6
};
SFUInteger expectedCount = sizeof(expectedValues) / sizeof(SFUInt16);
assert(memcmp(scheme->_featureTags, expectedTags, sizeof(expectedTags)) == 0);
assert(memcmp(scheme->_featureValues, expectedValues, sizeof(expectedValues)) == 0);
assert(scheme->_featureCount == expectedCount);
SFSchemeRelease(scheme);
}
}
void SchemeTester::testBuild()
{
const SFFontProtocol protocol = {
NULL,
&loadTable,
[](void *, SFCodepoint) -> SFGlyphID { return 0; },
[](void *, SFFontLayout, SFGlyphID) -> SFInt32 { return 0; }
};
SFFontRef font = SFFontCreateWithProtocol(&protocol, NULL);
SFScheme scheme;
SFSchemeInitialize(&scheme, TestKnowledge::instance());
SFSchemeSetFont(&scheme, font);
SFSchemeSetScriptTag(&scheme, tag("test"));
/* Test with default language. */
{
SFSchemeSetLanguageTag(&scheme, tag("dflt"));
SFPatternRef pattern = SFSchemeBuildPattern(&scheme);
SFTag expectedTags[] = {
tag("srqi"), tag("srq1"), tag("son1"), tag("sim1"), tag("sim2"),
tag("pon1"), tag("prq1"), tag("prqi")
};
SFLookupInfo expectedLookups[] = {
{SRQI, 1}, {SON1, 1}, {SRQ1, 1}, {SIM1, 1}, {SIM2, 1},
{PON1, 1}, {PRQ1, 1}, {PRQI, 1}
};
SFFeatureUnit expectedUnits[] = {
{ { &expectedLookups[0], 1 }, { 0, 1 }, 0x00 },
{ { &expectedLookups[1], 2 }, { 1, 2 }, 0x00 },
{ { &expectedLookups[3], 2 }, { 3, 2 }, 0x00 },
{ { &expectedLookups[5], 2 }, { 5, 2 }, 0x00 },
{ { &expectedLookups[7], 1 }, { 7, 1 }, 0x00 },
};
SFPattern expectedPattern = {
font,
{ expectedTags, 8 },
{ expectedUnits, 3, 2 },
tag("test"),
tag("dflt"),
SFTextDirectionLeftToRight,
1
};
assert(SFPatternEqualToPattern(pattern, &expectedPattern));
SFPatternRelease(pattern);
}
/* Test with a non-default language. */
{
SFSchemeSetLanguageTag(&scheme, tag("LNG "));
SFPatternRef pattern = SFSchemeBuildPattern(&scheme);
SFTag expectedTags[] = { tag("srqi") };
SFLookupInfo expectedLookups[] = { {SRQI, 1} };
SFFeatureUnit expectedUnits[] = {
{ { &expectedLookups[0], 1 }, { 0, 1 }, 0x00 },
};
SFPattern expectedPattern = {
font,
{ expectedTags, 1 },
{ expectedUnits, 1, 0 },
tag("test"),
tag("LNG "),
SFTextDirectionLeftToRight,
1
};
assert(SFPatternEqualToPattern(pattern, &expectedPattern));
SFPatternRelease(pattern);
}
/* Test by trying to turn off required features. */
/* Test by disabling a feature marked as on by default. */
/* Test by enabling a feature marked as off by default. */
/* Test by setting custom value of a required feature. */
/* Test by setting custom value of a feature marked as on by default. */
/* Test by setting custom value of a feature marked as off by default. */
/* Test by enabling simultaneous features across multiple groups. */
/* Test by enabling custom features of GSUB and GPOS. */
/* Test by enabling a custom feature available in both GSUB and GPOS. */
{
SFTag featureTags[] = {
tag("srqi"), tag("prq1"), tag("son1"), tag("sof1"), tag("prqi"),
tag("pon1"), tag("pof1"), tag("scst"), tag("pcst"), tag("cust")
};
SFUInt16 featureValues[] = {
0, 0, 0, 1, 2, 3, 4, 5, 6, 7
};
SFSchemeSetLanguageTag(&scheme, tag("dflt"));
SFSchemeSetFeatureValues(&scheme, featureTags, featureValues, sizeof(featureValues) / sizeof(SFUInt16));
SFPatternRef pattern = SFSchemeBuildPattern(&scheme);
SFTag expectedTags[] = {
tag("srqi"), tag("srq1"), tag("sof1"), tag("sim1"), tag("sim2"), tag("scst"), tag("cust"),
tag("pof1"), tag("pon1"), tag("prq1"), tag("prqi"), tag("pcst")
};
SFLookupInfo expectedLookups[] = {
{SRQI, 1}, {SOF1, 1}, {SRQ1, 1}, {SIM1, 1}, {SIM2, 1}, {CUST, 7}, {SCST, 5},
{POF1, 4}, {PON1, 3}, {PRQ1, 1}, {PRQI, 2}, {PCST, 6}
};
SFFeatureUnit expectedUnits[] = {
{ { &expectedLookups[0], 1 }, { 0, 1 }, 0x00 },
{ { &expectedLookups[1], 2 }, { 1, 2 }, 0x00 },
{ { &expectedLookups[3], 2 }, { 3, 2 }, 0x00 },
{ { &expectedLookups[5], 2 }, { 5, 2 }, 0x00 },
{ { &expectedLookups[7], 3 }, { 7, 3 }, 0x00 },
{ { &expectedLookups[10], 1 }, { 10, 1 }, 0x00 },
{ { &expectedLookups[11], 1 }, { 11, 1 }, 0x00 },
};
SFPattern expectedPattern = {
font,
{ expectedTags, 12 },
{ expectedUnits, 4, 3 },
tag("test"),
tag("dflt"),
SFTextDirectionLeftToRight,
1
};
assert(SFPatternEqualToPattern(pattern, &expectedPattern));
SFPatternRelease(pattern);
}
SFSchemeFinalize(&scheme);
SFFontRelease(font);
}
void SchemeTester::test()
{
testFeatures();
testBuild();
}
<|endoftext|> |
<commit_before>/*
* Copyright (c) 2003-2005 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.
*
* Authors: Steve Reinhardt
*/
#ifndef __SIM_SYSCALL_EMUL_BUF_HH__
#define __SIM_SYSCALL_EMUL_BUF_HH__
///
/// @file syscall_emul_buf.hh
///
/// This file defines buffer classes used to handle pointer arguments
/// in emulated syscalls.
#include <cstring>
#include "base/types.hh"
#include "mem/se_translating_port_proxy.hh"
/**
* Base class for BufferArg and TypedBufferArg, Not intended to be
* used directly.
*
* The BufferArg classes represent buffers in target user space that
* are passed by reference to an (emulated) system call. Each
* instance provides an internal (simulator-space) buffer of the
* appropriate size and tracks the user-space address. The copyIn()
* and copyOut() methods copy the user-space buffer to and from the
* simulator-space buffer, respectively.
*/
class BaseBufferArg {
public:
/**
* Allocate a buffer of size 'size' representing the memory at
* target address 'addr'.
*/
BaseBufferArg(Addr _addr, int _size)
: addr(_addr), size(_size), bufPtr(new uint8_t[size])
{
// clear out buffer: in case we only partially populate this,
// and then do a copyOut(), we want to make sure we don't
// introduce any random junk into the simulated address space
memset(bufPtr, 0, size);
}
virtual ~BaseBufferArg() { delete [] bufPtr; }
/**
* copy data into simulator space (read from target memory)
*/
virtual bool copyIn(SETranslatingPortProxy &memproxy)
{
memproxy.readBlob(addr, bufPtr, size);
return true; // no EFAULT detection for now
}
/**
* copy data out of simulator space (write to target memory)
*/
virtual bool copyOut(SETranslatingPortProxy &memproxy)
{
memproxy.writeBlob(addr, bufPtr, size);
return true; // no EFAULT detection for now
}
protected:
const Addr addr; ///< address of buffer in target address space
const int size; ///< buffer size
uint8_t * const bufPtr; ///< pointer to buffer in simulator space
};
/**
* BufferArg represents an untyped buffer in target user space that is
* passed by reference to an (emulated) system call.
*/
class BufferArg : public BaseBufferArg
{
public:
/**
* Allocate a buffer of size 'size' representing the memory at
* target address 'addr'.
*/
BufferArg(Addr _addr, int _size) : BaseBufferArg(_addr, _size) { }
/**
* Return a pointer to the internal simulator-space buffer.
*/
void *bufferPtr() { return bufPtr; }
};
/**
* TypedBufferArg is a class template; instances of this template
* represent typed buffers in target user space that are passed by
* reference to an (emulated) system call.
*
* This template provides operator overloads for convenience, allowing
* for example the use of '->' to reference fields within a struct
* type.
*/
template <class T>
class TypedBufferArg : public BaseBufferArg
{
public:
/**
* Allocate a buffer of type T representing the memory at target
* address 'addr'. The user can optionally specify a specific
* number of bytes to allocate to deal with structs that have
* variable-size arrays at the end.
*/
TypedBufferArg(Addr _addr, int _size = sizeof(T))
: BaseBufferArg(_addr, _size)
{ }
/**
* Convert TypedBufferArg<T> to a pointer to T that points to the
* internal buffer.
*/
operator T*() { return (T *)bufPtr; }
/**
* Convert TypedBufferArg<T> to a reference to T that references the
* internal buffer value.
*/
T &operator*() { return *((T *)bufPtr); }
/**
* Enable the use of '->' to reference fields where T is a struct
* type.
*/
T* operator->() { return (T *)bufPtr; }
/**
* Enable the use of '[]' to reference fields where T is an array
* type.
*/
T &operator[](int i) { return ((T *)bufPtr)[i]; }
};
#endif // __SIM_SYSCALL_EMUL_BUF_HH__
<commit_msg>syscall_emul: devirtualize BaseBufferArg methods<commit_after>/*
* Copyright (c) 2003-2005 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.
*
* Authors: Steve Reinhardt
*/
#ifndef __SIM_SYSCALL_EMUL_BUF_HH__
#define __SIM_SYSCALL_EMUL_BUF_HH__
///
/// @file syscall_emul_buf.hh
///
/// This file defines buffer classes used to handle pointer arguments
/// in emulated syscalls.
#include <cstring>
#include "base/types.hh"
#include "mem/se_translating_port_proxy.hh"
/**
* Base class for BufferArg and TypedBufferArg, Not intended to be
* used directly.
*
* The BufferArg classes represent buffers in target user space that
* are passed by reference to an (emulated) system call. Each
* instance provides an internal (simulator-space) buffer of the
* appropriate size and tracks the user-space address. The copyIn()
* and copyOut() methods copy the user-space buffer to and from the
* simulator-space buffer, respectively.
*/
class BaseBufferArg {
public:
/**
* Allocate a buffer of size 'size' representing the memory at
* target address 'addr'.
*/
BaseBufferArg(Addr _addr, int _size)
: addr(_addr), size(_size), bufPtr(new uint8_t[size])
{
// clear out buffer: in case we only partially populate this,
// and then do a copyOut(), we want to make sure we don't
// introduce any random junk into the simulated address space
memset(bufPtr, 0, size);
}
~BaseBufferArg() { delete [] bufPtr; }
/**
* copy data into simulator space (read from target memory)
*/
bool copyIn(SETranslatingPortProxy &memproxy)
{
memproxy.readBlob(addr, bufPtr, size);
return true; // no EFAULT detection for now
}
/**
* copy data out of simulator space (write to target memory)
*/
bool copyOut(SETranslatingPortProxy &memproxy)
{
memproxy.writeBlob(addr, bufPtr, size);
return true; // no EFAULT detection for now
}
protected:
const Addr addr; ///< address of buffer in target address space
const int size; ///< buffer size
uint8_t * const bufPtr; ///< pointer to buffer in simulator space
};
/**
* BufferArg represents an untyped buffer in target user space that is
* passed by reference to an (emulated) system call.
*/
class BufferArg : public BaseBufferArg
{
public:
/**
* Allocate a buffer of size 'size' representing the memory at
* target address 'addr'.
*/
BufferArg(Addr _addr, int _size) : BaseBufferArg(_addr, _size) { }
/**
* Return a pointer to the internal simulator-space buffer.
*/
void *bufferPtr() { return bufPtr; }
};
/**
* TypedBufferArg is a class template; instances of this template
* represent typed buffers in target user space that are passed by
* reference to an (emulated) system call.
*
* This template provides operator overloads for convenience, allowing
* for example the use of '->' to reference fields within a struct
* type.
*/
template <class T>
class TypedBufferArg : public BaseBufferArg
{
public:
/**
* Allocate a buffer of type T representing the memory at target
* address 'addr'. The user can optionally specify a specific
* number of bytes to allocate to deal with structs that have
* variable-size arrays at the end.
*/
TypedBufferArg(Addr _addr, int _size = sizeof(T))
: BaseBufferArg(_addr, _size)
{ }
/**
* Convert TypedBufferArg<T> to a pointer to T that points to the
* internal buffer.
*/
operator T*() { return (T *)bufPtr; }
/**
* Convert TypedBufferArg<T> to a reference to T that references the
* internal buffer value.
*/
T &operator*() { return *((T *)bufPtr); }
/**
* Enable the use of '->' to reference fields where T is a struct
* type.
*/
T* operator->() { return (T *)bufPtr; }
/**
* Enable the use of '[]' to reference fields where T is an array
* type.
*/
T &operator[](int i) { return ((T *)bufPtr)[i]; }
};
#endif // __SIM_SYSCALL_EMUL_BUF_HH__
<|endoftext|> |
<commit_before><commit_msg>サーバーから与えられた隠し要素をファイルに記録できるようにした<commit_after><|endoftext|> |
<commit_before>#if !defined(B9_MODULE_HPP_)
#define B9_MODULE_HPP_
#include <b9/instructions.hpp>
#include <cstdint>
#include <iostream>
#include <stdexcept>
#include <string>
#include <vector>
namespace b9 {
class Compiler;
class ExecutionContext;
class VirtualMachine;
// Function Definition
struct FunctionDef {
// Copy Constructor
FunctionDef(const std::string& name, std::uint32_t index,
const std::vector<Instruction>& instructions,
std::uint32_t nparams = 0, std::uint32_t nlocals = 0)
: name{name},
index{index},
instructions{instructions},
nparams{nparams},
nlocals{nlocals} {}
// Move Constructor
FunctionDef(const std::string& name, std::uint32_t index,
std::vector<Instruction>&& instructions, std::uint32_t nparams = 0,
std::uint32_t nlocals = 0)
: name{name},
index{index},
instructions{std::move(instructions)},
nparams{nparams},
nlocals{nlocals} {}
// Function Data
std::string name;
uint32_t index;
std::uint32_t nparams;
std::uint32_t nlocals;
std::vector<Instruction> instructions;
};
inline void operator<<(std::ostream& out, const FunctionDef& f) {
out << "(function \"" << f.name << "\" " << f.nparams << " " << f.nlocals;
std::size_t i = 0;
for (auto instruction : f.instructions) {
out << std::endl << " " << i << " " << instruction;
i++;
}
out << ")" << std::endl << std::endl;
}
inline bool operator==(const FunctionDef& lhs, const FunctionDef& rhs) {
return lhs.name == rhs.name && lhs.index == rhs.index &&
lhs.nparams == rhs.nparams && lhs.nlocals == rhs.nlocals;
}
/// Function not found exception.
struct FunctionNotFoundException : public std::runtime_error {
using std::runtime_error::runtime_error;
};
// Primitive Function from Interpreter call
extern "C" typedef void(PrimitiveFunction)(ExecutionContext* context);
/// An interpreter module.
struct Module {
std::vector<FunctionDef> functions;
std::vector<std::string> strings;
std::size_t getFunctionIndex(const std::string& name) const {
for (std::size_t i = 0; i < functions.size(); i++) {
if (functions[i].name == name) {
return i;
}
}
throw FunctionNotFoundException{name};
}
};
inline void operator<<(std::ostream& out, const Module& m) {
int32_t index = 0;
for (auto function : m.functions) {
out << function;
++index;
}
for (auto string : m.strings) {
out << "(string \"" << string << "\")" << std::endl;
}
out << std::endl;
}
inline bool operator==(const Module& lhs, const Module& rhs) {
return lhs.functions == rhs.functions && lhs.strings == rhs.strings;
}
} // namespace b9
#endif // B9_MODULE_HPP_
<commit_msg>Remove unused move constructor from FunctionDef<commit_after>#if !defined(B9_MODULE_HPP_)
#define B9_MODULE_HPP_
#include <b9/instructions.hpp>
#include <cstdint>
#include <iostream>
#include <stdexcept>
#include <string>
#include <vector>
namespace b9 {
class Compiler;
class ExecutionContext;
class VirtualMachine;
// Function Definition
struct FunctionDef {
FunctionDef(const std::string& name, std::uint32_t index,
const std::vector<Instruction>& instructions,
std::uint32_t nparams = 0, std::uint32_t nlocals = 0)
: name{name},
index{index},
instructions{instructions},
nparams{nparams},
nlocals{nlocals} {}
// Function Data
std::string name;
uint32_t index;
std::uint32_t nparams;
std::uint32_t nlocals;
std::vector<Instruction> instructions;
};
inline void operator<<(std::ostream& out, const FunctionDef& f) {
out << "(function \"" << f.name << "\" " << f.nparams << " " << f.nlocals;
std::size_t i = 0;
for (auto instruction : f.instructions) {
out << std::endl << " " << i << " " << instruction;
i++;
}
out << ")" << std::endl << std::endl;
}
inline bool operator==(const FunctionDef& lhs, const FunctionDef& rhs) {
return lhs.name == rhs.name && lhs.index == rhs.index &&
lhs.nparams == rhs.nparams && lhs.nlocals == rhs.nlocals;
}
/// Function not found exception.
struct FunctionNotFoundException : public std::runtime_error {
using std::runtime_error::runtime_error;
};
// Primitive Function from Interpreter call
extern "C" typedef void(PrimitiveFunction)(ExecutionContext* context);
/// An interpreter module.
struct Module {
std::vector<FunctionDef> functions;
std::vector<std::string> strings;
std::size_t getFunctionIndex(const std::string& name) const {
for (std::size_t i = 0; i < functions.size(); i++) {
if (functions[i].name == name) {
return i;
}
}
throw FunctionNotFoundException{name};
}
};
inline void operator<<(std::ostream& out, const Module& m) {
int32_t index = 0;
for (auto function : m.functions) {
out << function;
++index;
}
for (auto string : m.strings) {
out << "(string \"" << string << "\")" << std::endl;
}
out << std::endl;
}
inline bool operator==(const Module& lhs, const Module& rhs) {
return lhs.functions == rhs.functions && lhs.strings == rhs.strings;
}
} // namespace b9
#endif // B9_MODULE_HPP_
<|endoftext|> |
<commit_before>/*
* Copyright (c) 2017-2018, Rauli Laine
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
#include <plorth/gui/line-display.hpp>
namespace plorth
{
namespace gui
{
LineDisplay::LineDisplay()
: m_text_buffer(m_text_view.get_buffer())
, m_input_tag(m_text_buffer->create_tag("input"))
, m_output_tag(m_text_buffer->create_tag("output"))
, m_error_tag(m_text_buffer->create_tag("error"))
{
m_text_view.set_monospace(true);
m_text_view.set_editable(false);
m_scrolled_window.add(m_text_view);
m_scrolled_window.set_policy(Gtk::POLICY_NEVER, Gtk::POLICY_ALWAYS);
add(m_scrolled_window);
m_input_tag->property_foreground().set_value("gray");
m_output_tag->property_foreground().set_value("black");
m_error_tag->property_foreground().set_value("red");
}
void LineDisplay::add_line(const Glib::ustring& line, LineType type)
{
Glib::RefPtr<Gtk::TextTag> tag;
Glib::RefPtr<Gtk::Adjustment> adjustment;
auto end = m_text_buffer->end();
switch (type)
{
case LINE_TYPE_INPUT:
tag = m_input_tag;
break;
case LINE_TYPE_OUTPUT:
tag = m_output_tag;
break;
case LINE_TYPE_ERROR:
tag = m_error_tag;
break;
}
m_text_buffer->insert_with_tag(end, line, tag);
scroll_to_bottom();
}
void LineDisplay::scroll_to_bottom()
{
const auto adjustment = m_scrolled_window.get_vadjustment();
adjustment->set_value(adjustment->get_upper());
}
}
}
<commit_msg>Introduce horizontal wrapping in line display<commit_after>/*
* Copyright (c) 2017-2018, Rauli Laine
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
#include <plorth/gui/line-display.hpp>
namespace plorth
{
namespace gui
{
LineDisplay::LineDisplay()
: m_text_buffer(m_text_view.get_buffer())
, m_input_tag(m_text_buffer->create_tag("input"))
, m_output_tag(m_text_buffer->create_tag("output"))
, m_error_tag(m_text_buffer->create_tag("error"))
{
m_text_view.set_monospace(true);
m_text_view.set_editable(false);
m_text_view.set_wrap_mode(Gtk::WRAP_CHAR);
m_scrolled_window.add(m_text_view);
m_scrolled_window.set_policy(Gtk::POLICY_NEVER, Gtk::POLICY_ALWAYS);
add(m_scrolled_window);
m_input_tag->property_foreground().set_value("gray");
m_output_tag->property_foreground().set_value("black");
m_error_tag->property_foreground().set_value("red");
}
void LineDisplay::add_line(const Glib::ustring& line, LineType type)
{
Glib::RefPtr<Gtk::TextTag> tag;
Glib::RefPtr<Gtk::Adjustment> adjustment;
auto end = m_text_buffer->end();
switch (type)
{
case LINE_TYPE_INPUT:
tag = m_input_tag;
break;
case LINE_TYPE_OUTPUT:
tag = m_output_tag;
break;
case LINE_TYPE_ERROR:
tag = m_error_tag;
break;
}
m_text_buffer->insert_with_tag(end, line, tag);
scroll_to_bottom();
}
void LineDisplay::scroll_to_bottom()
{
const auto adjustment = m_scrolled_window.get_vadjustment();
adjustment->set_value(adjustment->get_upper());
}
}
}
<|endoftext|> |
<commit_before>///////////////////////////////////////////////////////////////////////////////
//
// File AdvectionDiffusionReaction.cpp
//
// For more information, please see: http://www.nektar.info
//
// The MIT License
//
// Copyright (c) 2006 Division of Applied Mathematics, Brown University (USA),
// Department of Aeronautics, Imperial College London (UK), and Scientific
// Computing and Imaging Institute, University of Utah (USA).
//
// License for the specific language governing rights and limitations under
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the "Software"),
// to deal in the Software without restriction, including without limitation
// the rights to use, copy, modify, merge, publish, distribute, sublicense,
// and/or sell copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included
// in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
// THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
//
// Description: Advection Diffusion Reaction class definition built on
// ADRBase class
//
///////////////////////////////////////////////////////////////////////////////
#include <AdvectionDiffusionReactionSolver/AdvectionDiffusionReaction.h>
#include <cstdio>
#include <cstdlib>
namespace Nektar
{
/**
* Basic construnctor
*/
AdvectionDiffusionReaction::AdvectionDiffusionReaction(void):
ADRBase(),
m_infosteps(100)
{
}
/**
* Constructor. Creates ... of #DisContField2D fields
*
* \param
* \param
*/
AdvectionDiffusionReaction::AdvectionDiffusionReaction(string &fileNameString):
ADRBase(fileNameString,true),
m_infosteps(10)
{
m_velocity = Array<OneD, Array<OneD, NekDouble> >(m_spacedim);
for(int i = 0; i < m_spacedim; ++i)
{
m_velocity[i] = Array<OneD, NekDouble> (GetPointsTot());
}
EvaluateAdvectionVelocity();
if(m_boundaryConditions->CheckForParameter("IO_InfoSteps") == true)
{
m_infosteps = m_boundaryConditions->GetParameter("IO_InfoSteps");
}
// check that any user defined boundary condition is indeed implemented
for(int n = 0; n < m_fields[0]->GetBndConditions().num_elements(); ++n)
{
// Time Dependent Boundary Condition (if no use defined then this is empty)
if (m_fields[0]->GetBndConditions()[n]->GetUserDefined().GetEquation() != "")
{
if (m_fields[0]->GetBndConditions()[n]->GetUserDefined().GetEquation() != "TimeDependent")
{
ASSERTL0(false,"Unknown USERDEFINEDTYPE boundary condition");
}
}
}
}
void AdvectionDiffusionReaction::EvaluateAdvectionVelocity()
{
int nq = m_fields[0]->GetPointsTot();
std::string velStr[3] = {"Vx","Vy","Vz"};
Array<OneD,NekDouble> x0(nq);
Array<OneD,NekDouble> x1(nq);
Array<OneD,NekDouble> x2(nq);
// get the coordinates (assuming all fields have the same
// discretisation)
m_fields[0]->GetCoords(x0,x1,x2);
for(int i = 0 ; i < m_velocity.num_elements(); i++)
{
SpatialDomains::ConstUserDefinedEqnShPtr ifunc = m_boundaryConditions->GetUserDefinedEqn(velStr[i]);
for(int j = 0; j < nq; j++)
{
m_velocity[i][j] = ifunc->Evaluate(x0[j],x1[j],x2[j]);
}
}
}
void AdvectionDiffusionReaction::ODEforcing(const Array<OneD, const Array<OneD, NekDouble> >&inarray,
Array<OneD, Array<OneD, NekDouble> >&outarray, NekDouble time)
{
int i;
int nvariables = inarray.num_elements();
int ncoeffs = inarray[0].num_elements();
SetBoundaryConditions(time);
switch(m_projectionType)
{
case eDiscontinuousGalerkin:
WeakDGAdvection(inarray, outarray);
for(i = 0; i < nvariables; ++i)
{
m_fields[i]->MultiplyByElmtInvMass(outarray[i],outarray[i]);
Vmath::Neg(ncoeffs,outarray[i],1);
}
break;
case eGalerkin:
{
Array<OneD, NekDouble> physfield(GetPointsTot());
for(i = 0; i < nvariables; ++i)
{
// Calculate -(\phi, V\cdot Grad(u))
m_fields[i]->BwdTrans(inarray[i],physfield);
WeakAdvectionNonConservativeForm(m_velocity,
physfield, outarray[i]);
Vmath::Neg(ncoeffs,outarray[i],1);
// Multiply by inverse of mass matrix to get forcing term
// m_fields[i]->MultiplyByInvMassMatrix(outarray[i],
// outarray[i],
// false, true);
}
}
break;
default:
ASSERTL0(false,"Unknown projection scheme");
break;
}
}
void AdvectionDiffusionReaction::ExplicitlyIntegrateAdvection(int nsteps)
{
int i,n,nchk = 0;
int ncoeffs = m_fields[0]->GetNcoeffs();
int nvariables = m_fields.num_elements();
// Get Integration scheme details
LibUtilities::TimeIntegrationSchemeKey IntKey(LibUtilities::eForwardEuler);
LibUtilities::TimeIntegrationSchemeSharedPtr IntScheme = LibUtilities::TimeIntegrationSchemeManager()[IntKey];
// Set up wrapper to fields data storage.
Array<OneD, Array<OneD, NekDouble> > fields(nvariables);
Array<OneD, Array<OneD, NekDouble> > in(nvariables);
Array<OneD, Array<OneD, NekDouble> > out(nvariables);
Array<OneD, Array<OneD, NekDouble> > tmp(nvariables);
Array<OneD, Array<OneD, NekDouble> > phys(nvariables);
for(i = 0; i < nvariables; ++i)
{
fields[i] = m_fields[i]->UpdateCoeffs();
in[i] = Array<OneD, NekDouble >(ncoeffs);
out[i] = Array<OneD, NekDouble >(ncoeffs);
tmp[i] = Array<OneD, NekDouble >(ncoeffs);
phys[i] = Array<OneD, NekDouble>(m_fields[0]->GetPointsTot());
Vmath::Vcopy(ncoeffs,m_fields[i]->GetCoeffs(),1,in[i],1);
}
int nInitSteps;
LibUtilities::TimeIntegrationSolutionSharedPtr u = IntScheme->InitializeScheme(m_timestep,m_time,nInitSteps,*this,fields);
for(n = nInitSteps; n < nsteps; ++n)
{
//----------------------------------------------
// Perform time step integration
//----------------------------------------------
switch(m_projectionType)
{
case eDiscontinuousGalerkin:
fields = IntScheme->ExplicitIntegration(m_timestep,*this,u);
break;
case eGalerkin:
{
//---------------------------------------------------------
// this is just a forward Euler to illustate that CG works
// get -D u^n
ODEforcing(in,out,m_time); // note that MultiplyByInvMassMatrix is not performed inside ODEforcing
// compute M u^n
for (i = 0; i < nvariables; ++i)
{
m_fields[0]->BwdTrans(in[i],phys[i]);
m_fields[0]->IProductWRTBase(phys[i],tmp[i]);
// f = M u^n - Dt D u^n
Vmath::Svtvp(ncoeffs,m_timestep,out[i],1,tmp[i],1,tmp[i],1);
// u^{n+1} = M^{-1} f
m_fields[i]->MultiplyByInvMassMatrix(tmp[i],out[i],false,false);
// fill results
Vmath::Vcopy(ncoeffs,out[i],1,in[i],1);
Vmath::Vcopy(ncoeffs,out[i],1,fields[i],1);
}
//---------------------------------------------------------
}
break;
}
m_time += m_timestep;
//----------------------------------------------
//----------------------------------------------
// Dump analyser information
//----------------------------------------------
if(!((n+1)%m_infosteps))
{
cout << "Steps: " << n+1 << "\t Time: " << m_time << endl;
}
if(n&&(!((n+1)%m_checksteps)))
{
for(i = 0; i < nvariables; ++i)
{
(m_fields[i]->UpdateCoeffs()) = fields[i];
}
Checkpoint_Output(nchk++);
}
}
for(i = 0; i < nvariables; ++i)
{
(m_fields[i]->UpdateCoeffs()) = fields[i];
}
}
//----------------------------------------------------
void AdvectionDiffusionReaction::SetBoundaryConditions(NekDouble time)
{
int nvariables = m_fields.num_elements();
// loop over Boundary Regions
for(int n = 0; n < m_fields[0]->GetBndConditions().num_elements(); ++n)
{
// Time Dependent Boundary Condition
if (m_fields[0]->GetBndConditions()[n]->GetUserDefined().GetEquation() == "TimeDependent")
{
for (int i = 0; i < nvariables; ++i)
{
m_fields[i]->EvaluateBoundaryConditions(time);
}
}
}
}
// Evaulate flux = m_fields*ivel for i th component of Vu
void AdvectionDiffusionReaction::GetFluxVector(const int i, Array<OneD, Array<OneD, NekDouble> > &physfield,
Array<OneD, Array<OneD, NekDouble> > &flux)
{
ASSERTL1(flux.num_elements() == m_velocity.num_elements(),"Dimension of flux array and velocity array do not match");
for(int j = 0; j < flux.num_elements(); ++j)
{
Vmath::Vmul(GetPointsTot(),physfield[i],1,
m_velocity[j],1,flux[j],1);
}
}
void AdvectionDiffusionReaction::NumericalFlux(Array<OneD, Array<OneD, NekDouble> > &physfield,
Array<OneD, Array<OneD, NekDouble> > &numflux)
{
int i;
int nTraceNumPoints = GetTracePointsTot();
int nvel = m_velocity.num_elements();
Array<OneD, NekDouble > Fwd(nTraceNumPoints);
Array<OneD, NekDouble > Bwd(nTraceNumPoints);
Array<OneD, NekDouble > Vn (nTraceNumPoints,0.0);
// Get Edge Velocity - Could be stored if time independent
for(i = 0; i < nvel; ++i)
{
m_fields[0]->ExtractTracePhys(m_velocity[i], Fwd);
Vmath::Vvtvp(nTraceNumPoints,m_traceNormals[i],1,Fwd,1,Vn,1,Vn,1);
}
for(i = 0; i < numflux.num_elements(); ++i)
{
m_fields[i]->GetFwdBwdTracePhys(physfield[i],Fwd,Bwd);
//evaulate upwinded m_fields[i]
m_fields[i]->GetTrace()->Upwind(Vn,Fwd,Bwd,numflux[i]);
// calculate m_fields[i]*Vn
Vmath::Vmul(nTraceNumPoints,numflux[i],1,Vn,1,numflux[i],1);
}
}
void AdvectionDiffusionReaction::NumericalFlux(Array<OneD, Array<OneD, NekDouble> > &physfield,
Array<OneD, Array<OneD, NekDouble> > &numfluxX,
Array<OneD, Array<OneD, NekDouble> > &numfluxY)
{
int i;
int nTraceNumPoints = GetTracePointsTot();
int nvel = m_velocity.num_elements();
Array<OneD, NekDouble > Fwd(nTraceNumPoints);
Array<OneD, NekDouble > Bwd(nTraceNumPoints);
Array<OneD, NekDouble > tmp(nTraceNumPoints,0.0);
Array<OneD, Array<OneD, NekDouble > > traceVelocity(2);
traceVelocity[0] = Array<OneD,NekDouble>(nTraceNumPoints,0.0);
traceVelocity[1] = Array<OneD,NekDouble>(nTraceNumPoints,0.0);
// Get Edge Velocity - Could be stored if time independent
m_fields[0]->ExtractTracePhys(m_velocity[0], traceVelocity[0]);
m_fields[0]->ExtractTracePhys(m_velocity[1], traceVelocity[1]);
m_fields[0]->GetFwdBwdTracePhys(physfield[0],Fwd,Bwd);
m_fields[0]->GetTrace()->Upwind(traceVelocity,Fwd,Bwd,tmp);
Vmath::Vmul(nTraceNumPoints,tmp,1,traceVelocity[0],1,numfluxX[0],1);
Vmath::Vmul(nTraceNumPoints,tmp,1,traceVelocity[1],1,numfluxY[0],1);
}
void AdvectionDiffusionReaction::Summary(std::ostream &out)
{
cout << "=======================================================================" << endl;
cout << "\tEquation Type : Advection Equation" << endl;
ADRBase::Summary(out);
cout << "=======================================================================" << endl;
}
} //end of namespace
/**
* $Log: AdvectionDiffusionReaction.cpp,v $
* Revision 1.3 2008/11/12 12:12:26 pvos
* Time Integration update
*
* Revision 1.2 2008/11/02 22:38:51 sherwin
* Updated parameter naming convention
*
* Revision 1.1 2008/10/31 10:50:10 pvos
* Restructured directory and CMakeFiles
*
* Revision 1.3 2008/10/29 22:51:07 sherwin
* Updates for const correctness and ODEforcing
*
* Revision 1.2 2008/10/19 15:59:20 sherwin
* Added Summary method
*
* Revision 1.1 2008/10/16 15:25:45 sherwin
* Working verion of restructured AdvectionDiffusionReactionSolver
*
* Revision 1.1 2008/08/22 09:48:23 pvos
* Added Claes' AdvectionDiffusionReaction, ShallowWater and Euler solver
*
**/
<commit_msg>Made 2D CG version working<commit_after>///////////////////////////////////////////////////////////////////////////////
//
// File AdvectionDiffusionReaction.cpp
//
// For more information, please see: http://www.nektar.info
//
// The MIT License
//
// Copyright (c) 2006 Division of Applied Mathematics, Brown University (USA),
// Department of Aeronautics, Imperial College London (UK), and Scientific
// Computing and Imaging Institute, University of Utah (USA).
//
// License for the specific language governing rights and limitations under
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the "Software"),
// to deal in the Software without restriction, including without limitation
// the rights to use, copy, modify, merge, publish, distribute, sublicense,
// and/or sell copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included
// in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
// THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
//
// Description: Advection Diffusion Reaction class definition built on
// ADRBase class
//
///////////////////////////////////////////////////////////////////////////////
#include <AdvectionDiffusionReactionSolver/AdvectionDiffusionReaction.h>
#include <cstdio>
#include <cstdlib>
namespace Nektar
{
/**
* Basic construnctor
*/
AdvectionDiffusionReaction::AdvectionDiffusionReaction(void):
ADRBase(),
m_infosteps(100)
{
}
/**
* Constructor. Creates ... of #DisContField2D fields
*
* \param
* \param
*/
AdvectionDiffusionReaction::AdvectionDiffusionReaction(string &fileNameString):
ADRBase(fileNameString,true),
m_infosteps(10)
{
m_velocity = Array<OneD, Array<OneD, NekDouble> >(m_spacedim);
for(int i = 0; i < m_spacedim; ++i)
{
m_velocity[i] = Array<OneD, NekDouble> (GetPointsTot());
}
EvaluateAdvectionVelocity();
if(m_boundaryConditions->CheckForParameter("IO_InfoSteps") == true)
{
m_infosteps = m_boundaryConditions->GetParameter("IO_InfoSteps");
}
// check that any user defined boundary condition is indeed implemented
for(int n = 0; n < m_fields[0]->GetBndConditions().num_elements(); ++n)
{
// Time Dependent Boundary Condition (if no use defined then this is empty)
if (m_fields[0]->GetBndConditions()[n]->GetUserDefined().GetEquation() != "")
{
if (m_fields[0]->GetBndConditions()[n]->GetUserDefined().GetEquation() != "TimeDependent")
{
ASSERTL0(false,"Unknown USERDEFINEDTYPE boundary condition");
}
}
}
}
void AdvectionDiffusionReaction::EvaluateAdvectionVelocity()
{
int nq = m_fields[0]->GetPointsTot();
std::string velStr[3] = {"Vx","Vy","Vz"};
Array<OneD,NekDouble> x0(nq);
Array<OneD,NekDouble> x1(nq);
Array<OneD,NekDouble> x2(nq);
// get the coordinates (assuming all fields have the same
// discretisation)
m_fields[0]->GetCoords(x0,x1,x2);
for(int i = 0 ; i < m_velocity.num_elements(); i++)
{
SpatialDomains::ConstUserDefinedEqnShPtr ifunc = m_boundaryConditions->GetUserDefinedEqn(velStr[i]);
for(int j = 0; j < nq; j++)
{
m_velocity[i][j] = ifunc->Evaluate(x0[j],x1[j],x2[j]);
}
}
}
void AdvectionDiffusionReaction::ODEforcing(const Array<OneD, const Array<OneD, NekDouble> >&inarray,
Array<OneD, Array<OneD, NekDouble> >&outarray, NekDouble time)
{
int i;
int nvariables = inarray.num_elements();
int ncoeffs = inarray[0].num_elements();
SetBoundaryConditions(time);
switch(m_projectionType)
{
case eDiscontinuousGalerkin:
WeakDGAdvection(inarray, outarray);
for(i = 0; i < nvariables; ++i)
{
m_fields[i]->MultiplyByElmtInvMass(outarray[i],outarray[i]);
Vmath::Neg(ncoeffs,outarray[i],1);
}
break;
case eGalerkin:
{
Array<OneD, NekDouble> physfield(GetPointsTot());
for(i = 0; i < nvariables; ++i)
{
// Calculate -(\phi, V\cdot Grad(u))
m_fields[i]->BwdTrans(inarray[i],physfield);
WeakAdvectionNonConservativeForm(m_velocity,
physfield, outarray[i]);
Vmath::Neg(ncoeffs,outarray[i],1);
//Multiply by inverse of mass matrix to get forcing term
m_fields[i]->MultiplyByInvMassMatrix(outarray[i],
outarray[i],
false,true);
}
}
break;
default:
ASSERTL0(false,"Unknown projection scheme");
break;
}
}
void AdvectionDiffusionReaction::ExplicitlyIntegrateAdvection(int nsteps)
{
int i,n,nchk = 0;
int ncoeffs = m_fields[0]->GetNcoeffs();
int nvariables = m_fields.num_elements();
// Get Integration scheme details
LibUtilities::TimeIntegrationSchemeKey IntKey(LibUtilities::eClassicalRungeKutta4);
LibUtilities::TimeIntegrationSchemeSharedPtr IntScheme = LibUtilities::TimeIntegrationSchemeManager()[IntKey];
// Set up wrapper to fields data storage.
Array<OneD, Array<OneD, NekDouble> > fields(nvariables);
for(i = 0; i < nvariables; ++i)
{
fields[i] = m_fields[i]->UpdateCoeffs();
}
int nInitSteps;
LibUtilities::TimeIntegrationSolutionSharedPtr u = IntScheme->InitializeScheme(m_timestep,m_time,nInitSteps,*this,fields);
for(n = nInitSteps; n < nsteps; ++n)
{
//----------------------------------------------
// Perform time step integration
//----------------------------------------------
fields = IntScheme->ExplicitIntegration(m_timestep,*this,u);
m_time += m_timestep;
//----------------------------------------------
// Dump analyser information
//----------------------------------------------
if(!((n+1)%m_infosteps))
{
cout << "Steps: " << n+1 << "\t Time: " << m_time << endl;
}
if(n&&(!((n+1)%m_checksteps)))
{
for(i = 0; i < nvariables; ++i)
{
(m_fields[i]->UpdateCoeffs()) = fields[i];
}
Checkpoint_Output(nchk++);
}
}
for(i = 0; i < nvariables; ++i)
{
(m_fields[i]->UpdateCoeffs()) = fields[i];
}
}
//----------------------------------------------------
void AdvectionDiffusionReaction::SetBoundaryConditions(NekDouble time)
{
int nvariables = m_fields.num_elements();
// loop over Boundary Regions
for(int n = 0; n < m_fields[0]->GetBndConditions().num_elements(); ++n)
{
// Time Dependent Boundary Condition
if (m_fields[0]->GetBndConditions()[n]->GetUserDefined().GetEquation() == "TimeDependent")
{
for (int i = 0; i < nvariables; ++i)
{
m_fields[i]->EvaluateBoundaryConditions(time);
}
}
}
}
// Evaulate flux = m_fields*ivel for i th component of Vu
void AdvectionDiffusionReaction::GetFluxVector(const int i, Array<OneD, Array<OneD, NekDouble> > &physfield,
Array<OneD, Array<OneD, NekDouble> > &flux)
{
ASSERTL1(flux.num_elements() == m_velocity.num_elements(),"Dimension of flux array and velocity array do not match");
for(int j = 0; j < flux.num_elements(); ++j)
{
Vmath::Vmul(GetPointsTot(),physfield[i],1,
m_velocity[j],1,flux[j],1);
}
}
void AdvectionDiffusionReaction::NumericalFlux(Array<OneD, Array<OneD, NekDouble> > &physfield,
Array<OneD, Array<OneD, NekDouble> > &numflux)
{
int i;
int nTraceNumPoints = GetTracePointsTot();
int nvel = m_velocity.num_elements();
Array<OneD, NekDouble > Fwd(nTraceNumPoints);
Array<OneD, NekDouble > Bwd(nTraceNumPoints);
Array<OneD, NekDouble > Vn (nTraceNumPoints,0.0);
// Get Edge Velocity - Could be stored if time independent
for(i = 0; i < nvel; ++i)
{
m_fields[0]->ExtractTracePhys(m_velocity[i], Fwd);
Vmath::Vvtvp(nTraceNumPoints,m_traceNormals[i],1,Fwd,1,Vn,1,Vn,1);
}
for(i = 0; i < numflux.num_elements(); ++i)
{
m_fields[i]->GetFwdBwdTracePhys(physfield[i],Fwd,Bwd);
//evaulate upwinded m_fields[i]
m_fields[i]->GetTrace()->Upwind(Vn,Fwd,Bwd,numflux[i]);
// calculate m_fields[i]*Vn
Vmath::Vmul(nTraceNumPoints,numflux[i],1,Vn,1,numflux[i],1);
}
}
void AdvectionDiffusionReaction::NumericalFlux(Array<OneD, Array<OneD, NekDouble> > &physfield,
Array<OneD, Array<OneD, NekDouble> > &numfluxX,
Array<OneD, Array<OneD, NekDouble> > &numfluxY)
{
int i;
int nTraceNumPoints = GetTracePointsTot();
int nvel = m_velocity.num_elements();
Array<OneD, NekDouble > Fwd(nTraceNumPoints);
Array<OneD, NekDouble > Bwd(nTraceNumPoints);
Array<OneD, NekDouble > tmp(nTraceNumPoints,0.0);
Array<OneD, Array<OneD, NekDouble > > traceVelocity(2);
traceVelocity[0] = Array<OneD,NekDouble>(nTraceNumPoints,0.0);
traceVelocity[1] = Array<OneD,NekDouble>(nTraceNumPoints,0.0);
// Get Edge Velocity - Could be stored if time independent
m_fields[0]->ExtractTracePhys(m_velocity[0], traceVelocity[0]);
m_fields[0]->ExtractTracePhys(m_velocity[1], traceVelocity[1]);
m_fields[0]->GetFwdBwdTracePhys(physfield[0],Fwd,Bwd);
m_fields[0]->GetTrace()->Upwind(traceVelocity,Fwd,Bwd,tmp);
Vmath::Vmul(nTraceNumPoints,tmp,1,traceVelocity[0],1,numfluxX[0],1);
Vmath::Vmul(nTraceNumPoints,tmp,1,traceVelocity[1],1,numfluxY[0],1);
}
void AdvectionDiffusionReaction::Summary(std::ostream &out)
{
cout << "=======================================================================" << endl;
cout << "\tEquation Type : Advection Equation" << endl;
ADRBase::Summary(out);
cout << "=======================================================================" << endl;
}
} //end of namespace
/**
* $Log: AdvectionDiffusionReaction.cpp,v $
* Revision 1.4 2008/11/17 08:20:14 claes
* Temporary fix for CG schemes. 1D CG working (but not for userdefined BC). 1D DG not working
*
* Revision 1.3 2008/11/12 12:12:26 pvos
* Time Integration update
*
* Revision 1.2 2008/11/02 22:38:51 sherwin
* Updated parameter naming convention
*
* Revision 1.1 2008/10/31 10:50:10 pvos
* Restructured directory and CMakeFiles
*
* Revision 1.3 2008/10/29 22:51:07 sherwin
* Updates for const correctness and ODEforcing
*
* Revision 1.2 2008/10/19 15:59:20 sherwin
* Added Summary method
*
* Revision 1.1 2008/10/16 15:25:45 sherwin
* Working verion of restructured AdvectionDiffusionReactionSolver
*
* Revision 1.1 2008/08/22 09:48:23 pvos
* Added Claes' AdvectionDiffusionReaction, ShallowWater and Euler solver
*
**/
<|endoftext|> |
<commit_before>#include "sox.h"
#include <QFile>
#include <QDir>
#include <QCoreApplication>
#include <QProcess>
Sox::Sox(QObject *parent) :
QObject(parent)
{
}
QString Sox::bin()
{
QString path;
QFile soxApp;
if (soxApp.exists(qApp->applicationDirPath()+QDir::separator()+"sox.exe"))
path = qApp->applicationDirPath()+QDir::separator()+"sox.exe";
else if (soxApp.exists(qApp->applicationDirPath()+QDir::separator()+"sox"))
path = qApp->applicationDirPath()+QDir::separator()+"sox";
else if (soxApp.exists(QDir::toNativeSeparators("/usr/bin/sox")))
path = QDir::toNativeSeparators("/usr/bin/sox");
else if (soxApp.exists(QDir::toNativeSeparators("/usr/local/bin/sox")))
path = QDir::toNativeSeparators("/usr/local/bin/sox");
return path;
}
QString Sox::about()
{
QString desc;
if (!bin().isEmpty()) {
QProcess proc;
proc.start(bin()+" --version");
proc.waitForFinished();
desc = proc.readAll().simplified();
proc.close();
}
return desc;
}
QString Sox::formats()
{
QString result;
QString tmp;
if (!bin().isEmpty()) {
QProcess proc;
proc.start(bin()+" --help");
proc.waitForFinished();
tmp = proc.readAll().simplified();
proc.close();
}
if (!tmp.isEmpty()) {
QStringList lines = tmp.split("AUDIO FILE FORMATS:");
if (!lines.isEmpty()) {
QStringList audioList = lines.takeLast().simplified().split(" ");
foreach(QString audioFormat, audioList) {
if (audioFormat.startsWith("PLAYLIST"))
break;
result.append("*."+audioFormat+" ");
}
}
}
return result;
}
QString Sox::dat(QString filename, float fps, int duration, bool x, bool y, int xFactor, int yFactor)
{
emit status(tr("Generating data ..."));
QString result;
QString data;
data=QDir::tempPath()+QDir::separator()+qApp->applicationName()+".dat";
QString curves;
QFile audioFile;
QFile tmp(data);
if (audioFile.exists(filename) && !bin().isEmpty()) {
if (tmp.exists())
tmp.remove();
QProcess proc;
QString exestring = bin()+" \""+filename+"\" -r "+QString::number(fps)+" \""+data+"\" trim 0 "+QString::number(duration/fps);
proc.start(exestring);
proc.waitForFinished();
proc.close();
}
else {
emit error(tr("Audio file or SoX does not exists"));
return result;
}
if (tmp.exists()) {
if (tmp.open(QIODevice::ReadOnly|QIODevice::Text))
curves = tmp.readAll();
tmp.close();
tmp.remove();
}
double maxX = 0;
double maxY = 0;
if (!curves.isEmpty()) {
QStringList lines = curves.split("\n", QString::SkipEmptyParts);
foreach(QString line, lines) {
if (!line.startsWith(";")) {
QStringList cordinates = line.simplified().split(" ");
int posCurr=0;
foreach(QString pos, cordinates) {
if (posCurr==1) {
double posX = pos.toDouble();
if (posX<0)
posX = -posX;
if (posX>maxX)
maxX=posX;
}
if (posCurr==2) {
double posY = pos.toDouble();
if (posY<0)
posY = -posY;
if (posY>maxY)
maxY=posY;
}
posCurr++;
}
}
}
}
if (!curves.isEmpty()) {
QString dat;
QStringList lines = curves.split("\n", QString::SkipEmptyParts);
foreach(QString line, lines) {
if (!line.startsWith(";")) {
QStringList cordinates = line.simplified().split(" ");
int posCurr=0;
foreach(QString pos, cordinates) {
if (posCurr==1 && x) {
dat.append(QString::number(pos.toDouble()*xFactor/maxX,'f',10));
if (!y)
dat.append("\n");
}
if (posCurr==2 && y) {
if (x)
dat.append("_");
dat.append(QString::number(pos.toDouble()*yFactor/maxY,'f',10)+"\n");
}
posCurr++;
}
}
}
result = dat;
}
if (result.isEmpty())
emit error(tr("No data collected"));
else
emit status(tr("Done"));
return result;
}
float Sox::duration(QString filename, float fps)
{
float result = 0;
QString tmp;
if (!bin().isEmpty()) {
QProcess proc;
QString exec = bin()+" \""+filename+"\" -n stat";
proc.setProcessChannelMode(QProcess::MergedChannels);
proc.start(exec);
proc.waitForFinished();
tmp = proc.readAll();
proc.close();
}
if (!tmp.isEmpty()) {
QStringList lines = tmp.split("\n");
foreach(QString line, lines) {
if (line.startsWith("Length (seconds):"))
result = line.simplified().remove("Length (seconds): ").toFloat();
}
}
if (fps>0 && result>0)
result = result*fps;
return result;
}
<commit_msg>always output x+y<commit_after>#include "sox.h"
#include <QFile>
#include <QDir>
#include <QCoreApplication>
#include <QProcess>
Sox::Sox(QObject *parent) :
QObject(parent)
{
}
QString Sox::bin()
{
QString path;
QFile soxApp;
if (soxApp.exists(qApp->applicationDirPath()+QDir::separator()+"sox.exe"))
path = qApp->applicationDirPath()+QDir::separator()+"sox.exe";
else if (soxApp.exists(qApp->applicationDirPath()+QDir::separator()+"sox"))
path = qApp->applicationDirPath()+QDir::separator()+"sox";
else if (soxApp.exists(QDir::toNativeSeparators("/usr/bin/sox")))
path = QDir::toNativeSeparators("/usr/bin/sox");
else if (soxApp.exists(QDir::toNativeSeparators("/usr/local/bin/sox")))
path = QDir::toNativeSeparators("/usr/local/bin/sox");
return path;
}
QString Sox::about()
{
QString desc;
if (!bin().isEmpty()) {
QProcess proc;
proc.start(bin()+" --version");
proc.waitForFinished();
desc = proc.readAll().simplified();
proc.close();
}
return desc;
}
QString Sox::formats()
{
QString result;
QString tmp;
if (!bin().isEmpty()) {
QProcess proc;
proc.start(bin()+" --help");
proc.waitForFinished();
tmp = proc.readAll().simplified();
proc.close();
}
if (!tmp.isEmpty()) {
QStringList lines = tmp.split("AUDIO FILE FORMATS:");
if (!lines.isEmpty()) {
QStringList audioList = lines.takeLast().simplified().split(" ");
foreach(QString audioFormat, audioList) {
if (audioFormat.startsWith("PLAYLIST"))
break;
result.append("*."+audioFormat+" ");
}
}
}
return result;
}
QString Sox::dat(QString filename, float fps, int duration, bool x, bool y, int xFactor, int yFactor)
{
emit status(tr("Generating data ..."));
QString result;
QString data;
data=QDir::tempPath()+QDir::separator()+qApp->applicationName()+".dat";
QString curves;
QFile audioFile;
QFile tmp(data);
if (audioFile.exists(filename) && !bin().isEmpty()) {
if (tmp.exists())
tmp.remove();
QProcess proc;
QString exestring = bin()+" \""+filename+"\" -r "+QString::number(fps)+" \""+data+"\" trim 0 "+QString::number(duration/fps);
proc.start(exestring);
proc.waitForFinished();
proc.close();
}
else {
emit error(tr("Audio file or SoX does not exists"));
return result;
}
if (tmp.exists()) {
if (tmp.open(QIODevice::ReadOnly|QIODevice::Text))
curves = tmp.readAll();
tmp.close();
tmp.remove();
}
double maxX = 0;
double maxY = 0;
if (!curves.isEmpty()) {
QStringList lines = curves.split("\n", QString::SkipEmptyParts);
foreach(QString line, lines) {
if (!line.startsWith(";")) {
QStringList cordinates = line.simplified().split(" ");
int posCurr=0;
foreach(QString pos, cordinates) {
if (posCurr==1) {
double posX = pos.toDouble();
if (posX<0)
posX = -posX;
if (posX>maxX)
maxX=posX;
}
if (posCurr==2) {
double posY = pos.toDouble();
if (posY<0)
posY = -posY;
if (posY>maxY)
maxY=posY;
}
posCurr++;
}
}
}
}
if (!curves.isEmpty()) {
QString dat;
QStringList lines = curves.split("\n", QString::SkipEmptyParts);
foreach(QString line, lines) {
if (!line.startsWith(";")) {
QStringList cordinates = line.simplified().split(" ");
int posCurr=0;
foreach(QString pos, cordinates) {
if (posCurr==1 && x) {
dat.append(QString::number(pos.toDouble()*xFactor/maxX,'f',10));
if (!y) {
dat.append("_0.00000");
dat.append("\n");
}
}
if (posCurr==2 && y) {
if (x)
dat.append("_");
else
dat.append("0.00000_");
dat.append(QString::number(pos.toDouble()*yFactor/maxY,'f',10)+"\n");
}
posCurr++;
}
}
}
result = dat;
}
if (result.isEmpty())
emit error(tr("No data collected"));
else
emit status(tr("Done"));
return result;
}
float Sox::duration(QString filename, float fps)
{
float result = 0;
QString tmp;
if (!bin().isEmpty()) {
QProcess proc;
QString exec = bin()+" \""+filename+"\" -n stat";
proc.setProcessChannelMode(QProcess::MergedChannels);
proc.start(exec);
proc.waitForFinished();
tmp = proc.readAll();
proc.close();
}
if (!tmp.isEmpty()) {
QStringList lines = tmp.split("\n");
foreach(QString line, lines) {
if (line.startsWith("Length (seconds):"))
result = line.simplified().remove("Length (seconds): ").toFloat();
}
}
if (fps>0 && result>0)
result = result*fps;
return result;
}
<|endoftext|> |
<commit_before>/* Copyright 2019 The TensorFlow Authors. All Rights Reserved.
Copyright 2021 The CFU PLayground Authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/
#include "tensorflow/lite/kernels/internal/reference/integer_ops/mnv2_conv.h"
#include "mnv2_cfu.h"
#include "perf.h"
#include "tf_util/print_params.h"
#ifdef SHOW_CONV_PERF
#define PERF_START(n) perf_enable_counter(n)
#define PERF_END(n) perf_disable_counter(n)
#else
#define PERF_START(n)
#define PERF_END(n)
#endif
//
// This file contains specialized conv 2D implementations to support
// MobileNet v2 models
//
namespace tflite {
namespace reference_integer_ops {
// Fixed-point per-channel-quantization convolution reference kernel.
void Mnv2ConvPerChannel1x1(
const ConvParams& params, const int32_t* output_multiplier,
const int32_t* output_shift, const RuntimeShape& input_shape,
const int8_t* input_data, const RuntimeShape& filter_shape,
const int8_t* filter_data, const RuntimeShape& bias_shape,
const int32_t* bias_data, const RuntimeShape& output_shape,
int8_t* output_data) {
PERF_START(2);
// Get parameters.
const int32_t input_offset = params.input_offset; // r = s(q - Z)
const int32_t output_offset = params.output_offset;
// Set min and max value of the output.
const int32_t output_activation_min = params.quantized_activation_min;
const int32_t output_activation_max = params.quantized_activation_max;
// Consistency check
TFLITE_DCHECK_LE(output_activation_min, output_activation_max);
TFLITE_DCHECK_EQ(input_shape.DimensionsCount(), 4);
TFLITE_DCHECK_EQ(filter_shape.DimensionsCount(), 4);
TFLITE_DCHECK_EQ(output_shape.DimensionsCount(), 4);
const int input_depth = MatchingDim(input_shape, 3, filter_shape, 3);
const int output_depth = MatchingDim(filter_shape, 0, output_shape, 3);
if (bias_data) {
TFLITE_DCHECK_EQ(bias_shape.FlatSize(), output_depth);
}
// Check dimensions of the tensors.
const int output_height = output_shape.Dims(1);
const int output_width = output_shape.Dims(2);
// Set parameters for op
const int input_depth_words = input_depth / 4;
CFU_SET_INPUT_DEPTH_WORDS(input_depth_words);
CFU_SET_OUTPUT_DEPTH(output_depth);
CFU_SET_INPUT_OFFSET(input_offset);
CFU_SET_OUTPUT_OFFSET(output_offset);
CFU_SET_ACTIVATION_MIN(output_activation_min);
CFU_SET_ACTIVATION_MAX(output_activation_max);
// Ensure accumulator clear before starting
CFU_GET_SET_ACCUMULATOR(0);
// Access filter data as words
uint32_t* filter_words = (uint32_t*)filter_data;
// Do the processing in batches, by output channel. batch size is number of
// output channels processed per batch and it is chosen to avoid overflowing
// filter_data memory, and then rounded down to a multiple of 4.
//
// For each batch, the entire input will be read once
#ifdef USE_CONV_SMALL_BATCHES
const int channels_per_batch =
std::min(output_depth, (2048 / input_depth) / 4 * 4);
#else
const int channels_per_batch =
std::min(output_depth, (NUM_FILTER_DATA_BYTES / input_depth) / 4 * 4);
#endif
const int num_pixels = output_height * output_width;
const int num_batches =
(channels_per_batch - 1 + output_depth) / channels_per_batch;
PERF_END(2);
for (int batch = 0; batch < num_batches; batch++) {
PERF_START(3);
const int batch_base = batch * channels_per_batch;
const int batch_end =
std::min(output_depth, batch_base + channels_per_batch);
const int batch_size = batch_end - batch_base;
// Load up parameters
CFU_SET_OUTPUT_BATCH_SIZE(batch_size);
for (int i = 0; i < batch_size; i++) {
CFU_STORE_OUTPUT_MULTIPLIER(*(output_multiplier++));
}
for (int i = 0; i < batch_size; i++) {
CFU_STORE_OUTPUT_SHIFT(*(output_shift++));
}
for (int i = 0; i < batch_size; i++) {
CFU_STORE_OUTPUT_BIAS(*(bias_data++));
}
PERF_END(3);
PERF_START(4);
// Load up weights
int num_filter_words = batch_size * input_depth / 4;
for (int i = 0; i < num_filter_words; i++) {
CFU_STORE_FILTER_VALUE(*(filter_words++));
}
PERF_END(4);
PERF_START(5);
// Reset input and output pointers
const uint32_t* input_ptr = (uint32_t*)input_data;
int8_t* output_ptr = output_data + batch_base;
for (int p = 0; p < num_pixels; p++) {
// Load one pixel's worth of input data
PERF_START(6);
for (int i = 0; i < input_depth_words; i++) {
uint32_t val = *(input_ptr++);
CFU_STORE_INPUT_VALUE(val);
}
PERF_END(6);
PERF_START(7);
for (int out_channel = batch_base; out_channel < batch_end;
++out_channel) {
CFU_MACC4_RUN_1();
int32_t acc = CFU_GET_SET_ACCUMULATOR(0);
int32_t out = CFU_POST_PROCESS(acc);
*(output_ptr++) = static_cast<int8_t>(out);
}
CFU_MARK_INPUT_READ_FINISHED();
output_ptr += output_depth - batch_size;
PERF_END(7);
}
PERF_END(5);
}
}
} // namespace reference_integer_ops
} // namespace tflite
<commit_msg>mnv2_first/mnv2_conv.cc: Unroll input data loading.<commit_after>/* Copyright 2019 The TensorFlow Authors. All Rights Reserved.
Copyright 2021 The CFU PLayground Authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/
#include "tensorflow/lite/kernels/internal/reference/integer_ops/mnv2_conv.h"
#include "mnv2_cfu.h"
#include "perf.h"
#include "tf_util/print_params.h"
#ifdef SHOW_CONV_PERF
#define PERF_START(n) perf_enable_counter(n)
#define PERF_END(n) perf_disable_counter(n)
#else
#define PERF_START(n)
#define PERF_END(n)
#endif
//
// This file contains specialized conv 2D implementations to support
// MobileNet v2 models
//
namespace tflite {
namespace reference_integer_ops {
// Fixed-point per-channel-quantization convolution reference kernel.
void Mnv2ConvPerChannel1x1(
const ConvParams& params, const int32_t* output_multiplier,
const int32_t* output_shift, const RuntimeShape& input_shape,
const int8_t* input_data, const RuntimeShape& filter_shape,
const int8_t* filter_data, const RuntimeShape& bias_shape,
const int32_t* bias_data, const RuntimeShape& output_shape,
int8_t* output_data) {
PERF_START(2);
// Get parameters.
const int32_t input_offset = params.input_offset; // r = s(q - Z)
const int32_t output_offset = params.output_offset;
// Set min and max value of the output.
const int32_t output_activation_min = params.quantized_activation_min;
const int32_t output_activation_max = params.quantized_activation_max;
// Consistency check
TFLITE_DCHECK_LE(output_activation_min, output_activation_max);
TFLITE_DCHECK_EQ(input_shape.DimensionsCount(), 4);
TFLITE_DCHECK_EQ(filter_shape.DimensionsCount(), 4);
TFLITE_DCHECK_EQ(output_shape.DimensionsCount(), 4);
const int input_depth = MatchingDim(input_shape, 3, filter_shape, 3);
const int output_depth = MatchingDim(filter_shape, 0, output_shape, 3);
if (bias_data) {
TFLITE_DCHECK_EQ(bias_shape.FlatSize(), output_depth);
}
// Check dimensions of the tensors.
const int output_height = output_shape.Dims(1);
const int output_width = output_shape.Dims(2);
// Set parameters for op
const int input_depth_words = input_depth / 4;
CFU_SET_INPUT_DEPTH_WORDS(input_depth_words);
CFU_SET_OUTPUT_DEPTH(output_depth);
CFU_SET_INPUT_OFFSET(input_offset);
CFU_SET_OUTPUT_OFFSET(output_offset);
CFU_SET_ACTIVATION_MIN(output_activation_min);
CFU_SET_ACTIVATION_MAX(output_activation_max);
// Ensure accumulator clear before starting
CFU_GET_SET_ACCUMULATOR(0);
// Access filter data as words
uint32_t* filter_words = (uint32_t*)filter_data;
// Do the processing in batches, by output channel. batch size is number of
// output channels processed per batch and it is chosen to avoid overflowing
// filter_data memory, and then rounded down to a multiple of 4.
//
// For each batch, the entire input will be read once
#ifdef USE_CONV_SMALL_BATCHES
const int channels_per_batch =
std::min(output_depth, (2048 / input_depth) / 4 * 4);
#else
const int channels_per_batch =
std::min(output_depth, (NUM_FILTER_DATA_BYTES / input_depth) / 4 * 4);
#endif
const int num_pixels = output_height * output_width;
const int num_batches =
(channels_per_batch - 1 + output_depth) / channels_per_batch;
PERF_END(2);
for (int batch = 0; batch < num_batches; batch++) {
PERF_START(3);
const int batch_base = batch * channels_per_batch;
const int batch_end =
std::min(output_depth, batch_base + channels_per_batch);
const int batch_size = batch_end - batch_base;
// Load up parameters
CFU_SET_OUTPUT_BATCH_SIZE(batch_size);
for (int i = 0; i < batch_size; i++) {
CFU_STORE_OUTPUT_MULTIPLIER(*(output_multiplier++));
}
for (int i = 0; i < batch_size; i++) {
CFU_STORE_OUTPUT_SHIFT(*(output_shift++));
}
for (int i = 0; i < batch_size; i++) {
CFU_STORE_OUTPUT_BIAS(*(bias_data++));
}
PERF_END(3);
PERF_START(4);
// Load up weights
int num_filter_words = batch_size * input_depth / 4;
for (int i = 0; i < num_filter_words; i++) {
CFU_STORE_FILTER_VALUE(*(filter_words++));
}
PERF_END(4);
PERF_START(5);
// Reset input and output pointers
const uint32_t* input_ptr = (uint32_t*)input_data;
int8_t* output_ptr = output_data + batch_base;
for (int p = 0; p < num_pixels; p++) {
// Load one pixel's worth of input data
PERF_START(6);
for (int i = 0; i < input_depth_words; i += 2) {
CFU_STORE_INPUT_VALUE(*(input_ptr++));
CFU_STORE_INPUT_VALUE(*(input_ptr++));
}
PERF_END(6);
PERF_START(7);
for (int out_channel = batch_base; out_channel < batch_end;
++out_channel) {
CFU_MACC4_RUN_1();
int32_t acc = CFU_GET_SET_ACCUMULATOR(0);
int32_t out = CFU_POST_PROCESS(acc);
*(output_ptr++) = static_cast<int8_t>(out);
}
CFU_MARK_INPUT_READ_FINISHED();
output_ptr += output_depth - batch_size;
PERF_END(7);
}
PERF_END(5);
}
}
} // namespace reference_integer_ops
} // namespace tflite
<|endoftext|> |
<commit_before>#include "V3DBatchModelGroup.h"
#ifndef VFRAME_NO_3D
#include "V3DCamera.h"
#include "V3DShader.h"
V3DBatchModelGroup::V3DBatchModelGroup(V3DObject* BaseObject, unsigned int MaxSize) : VGroup(MaxSize)
{
baseObject = BaseObject;
}
void V3DBatchModelGroup::Destroy()
{
VSUPERCLASS::Destroy();
delete baseObject;
}
void V3DBatchModelGroup::UpdateShader(V3DCamera* Camera, V3DShader* Shader)
{
currentCamera = Camera;
currentShader = Shader;
}
void V3DBatchModelGroup::Draw(sf::RenderTarget& RenderTarget)
{
for (unsigned int i = 0; i < members.size(); i++)
{
V3DObject* base = dynamic_cast<V3DObject*>(members[i]);
if (base != nullptr && base->exists && base->visible)
{
if (currentCamera->BoxInView(base->Position, baseObject->GetMinimum(), baseObject->GetMaximum()))
{
baseObject->Position = base->Position;
baseObject->Rotation = base->Rotation;
baseObject->Scale = base->Scale;
baseObject->UpdateShader(currentShader, currentCamera);
baseObject->Update(0.0f);
baseObject->Draw(RenderTarget);
}
}
}
}
#endif<commit_msg>Add BoxInView call to end of if statement to remove an unnecessary branch.<commit_after>#include "V3DBatchModelGroup.h"
#ifndef VFRAME_NO_3D
#include "V3DCamera.h"
#include "V3DShader.h"
V3DBatchModelGroup::V3DBatchModelGroup(V3DObject* BaseObject, unsigned int MaxSize) : VGroup(MaxSize)
{
baseObject = BaseObject;
}
void V3DBatchModelGroup::Destroy()
{
VSUPERCLASS::Destroy();
delete baseObject;
}
void V3DBatchModelGroup::UpdateShader(V3DCamera* Camera, V3DShader* Shader)
{
currentCamera = Camera;
currentShader = Shader;
}
void V3DBatchModelGroup::Draw(sf::RenderTarget& RenderTarget)
{
for (unsigned int i = 0; i < members.size(); i++)
{
V3DObject* base = dynamic_cast<V3DObject*>(members[i]);
if (base != nullptr && base->exists && base->visible && currentCamera->BoxInView(base->Position, baseObject->GetMinimum(), baseObject->GetMaximum()))
{
baseObject->Position = base->Position;
baseObject->Rotation = base->Rotation;
baseObject->Scale = base->Scale;
baseObject->UpdateShader(currentShader, currentCamera);
baseObject->Update(0.0f);
baseObject->Draw(RenderTarget);
}
}
}
#endif<|endoftext|> |
<commit_before>/*=========================================================================
Program: Visualization Toolkit
Module: vtkTkAppInit.cxx
Language: C++
Date: $Date$
Version: $Revision$
Copyright (c) 1993-2002 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.
=========================================================================*/
/*
* tkAppInit.c --
*
* Provides a default version of the Tcl_AppInit procedure for
* use in wish and similar Tk-based applications.
*
* Copyright (c) 1993 The Regents of the University of California.
* Copyright (c) 1994 Sun Microsystems, Inc.
*
* See the file "license.terms" for information on usage and redistribution
* of this file, and for a DISCLAIMER OF ALL WARRANTIES.
*/
#ifdef VTK_COMPILED_USING_MPI
# include <mpi.h>
# include "vtkMPIController.h"
#endif // VTK_COMPILED_USING_MPI
#include "vtkSystemIncludes.h"
#include "vtkToolkits.h"
#include "Wrapping/Tcl/vtkTkAppInitConfigure.h"
#if defined(CMAKE_INTDIR)
# define VTK_TCL_PACKAGE_DIR VTK_TCL_PACKAGE_DIR_BUILD "/" CMAKE_INTDIR
#else
# define VTK_TCL_PACKAGE_DIR VTK_TCL_PACKAGE_DIR_BUILD
#endif
#ifdef VTK_USE_RENDERING
# include "tk.h"
#else
# include "tcl.h"
#endif
/*
* Make sure all the kits register their classes with vtkInstantiator.
*/
#include "vtkCommonInstantiator.h"
#include "vtkFilteringInstantiator.h"
#include "vtkIOInstantiator.h"
#include "vtkImagingInstantiator.h"
#include "vtkGraphicsInstantiator.h"
#ifdef VTK_USE_RENDERING
#include "vtkRenderingInstantiator.h"
#endif
#ifdef VTK_USE_PATENTED
#include "vtkPatentedInstantiator.h"
#endif
#ifdef VTK_USE_HYBRID
#include "vtkHybridInstantiator.h"
#endif
#ifdef VTK_USE_PARALLEL
#include "vtkParallelInstantiator.h"
#endif
static void vtkTkAppInitEnableMSVCDebugHook();
/*
*----------------------------------------------------------------------
*
* main --
*
* This is the main program for the application.
*
* Results:
* None: Tk_Main never returns here, so this procedure never
* returns either.
*
* Side effects:
* Whatever the application does.
*
*----------------------------------------------------------------------
*/
#ifdef VTK_COMPILED_USING_MPI
class vtkMPICleanup {
public:
vtkMPICleanup()
{
this->Controller = 0;
}
void Initialize(int *argc, char ***argv)
{
MPI_Init(argc, argv);
this->Controller = vtkMPIController::New();
this->Controller->Initialize(argc, argv, 1);
vtkMultiProcessController::SetGlobalController(this->Controller);
}
~vtkMPICleanup()
{
if ( this->Controller )
{
this->Controller->Finalize();
this->Controller->Delete();
}
}
private:
vtkMPIController *Controller;
};
static vtkMPICleanup VTKMPICleanup;
#endif // VTK_COMPILED_USING_MPI
int
main(int argc, char **argv)
{
ios::sync_with_stdio();
vtkTkAppInitEnableMSVCDebugHook();
#ifdef VTK_COMPILED_USING_MPI
VTKMPICleanup.Initialize(&argc, &argv);
#endif // VTK_COMPILED_USING_MPI
#ifdef VTK_USE_RENDERING
Tk_Main(argc, argv, Tcl_AppInit);
#else
Tcl_Main(argc, argv, Tcl_AppInit);
#endif
return 0; /* Needed only to prevent compiler warning. */
}
/*
*----------------------------------------------------------------------
*
* Tcl_AppInit --
*
* This procedure performs application-specific initialization.
* Most applications, especially those that incorporate additional
* packages, will have their own version of this procedure.
*
* Results:
* Returns a standard Tcl completion code, and leaves an error
* message in interp->result if an error occurs.
*
* Side effects:
* Depends on the startup script.
*
*----------------------------------------------------------------------
*/
extern "C" int Vtkcommontcl_Init(Tcl_Interp *interp);
extern "C" int Vtkfilteringtcl_Init(Tcl_Interp *interp);
extern "C" int Vtkimagingtcl_Init(Tcl_Interp *interp);
extern "C" int Vtkgraphicstcl_Init(Tcl_Interp *interp);
extern "C" int Vtkiotcl_Init(Tcl_Interp *interp);
#ifdef VTK_USE_RENDERING
extern "C" int Vtkrenderingtcl_Init(Tcl_Interp *interp);
#if defined(VTK_DISABLE_TK_INIT) && !defined(VTK_USE_COCOA)
extern "C" int Vtktkrenderwidget_Init(Tcl_Interp *interp);
extern "C" int Vtktkimageviewerwidget_Init(Tcl_Interp *interp);
#endif
#endif
#ifdef VTK_USE_PATENTED
extern "C" int Vtkpatentedtcl_Init(Tcl_Interp *interp);
#endif
#ifdef VTK_USE_HYBRID
extern "C" int Vtkhybridtcl_Init(Tcl_Interp *interp);
#endif
#ifdef VTK_USE_PARALLEL
extern "C" int Vtkparalleltcl_Init(Tcl_Interp *interp);
#endif
void help() {
}
int Tcl_AppInit(Tcl_Interp *interp)
{
if (Tcl_Init(interp) == TCL_ERROR) {
return TCL_ERROR;
}
#ifdef VTK_USE_RENDERING
if (Tk_Init(interp) == TCL_ERROR) {
return TCL_ERROR;
}
#endif
/* init the core vtk stuff */
if (Vtkcommontcl_Init(interp) == TCL_ERROR)
{
return TCL_ERROR;
}
if (Vtkfilteringtcl_Init(interp) == TCL_ERROR)
{
return TCL_ERROR;
}
if (Vtkimagingtcl_Init(interp) == TCL_ERROR)
{
return TCL_ERROR;
}
if (Vtkgraphicstcl_Init(interp) == TCL_ERROR)
{
return TCL_ERROR;
}
if (Vtkiotcl_Init(interp) == TCL_ERROR)
{
return TCL_ERROR;
}
#ifdef VTK_USE_RENDERING
if (Vtkrenderingtcl_Init(interp) == TCL_ERROR)
{
return TCL_ERROR;
}
#if defined(VTK_DISABLE_TK_INIT) && !defined(VTK_USE_COCOA)
// Need to init here because rendering did not when this option is on
if (Vtktkrenderwidget_Init(interp) == TCL_ERROR)
{
return TCL_ERROR;
}
if (Vtktkimageviewerwidget_Init(interp) == TCL_ERROR)
{
return TCL_ERROR;
}
#endif
#endif
#ifdef VTK_USE_PATENTED
if (Vtkpatentedtcl_Init(interp) == TCL_ERROR)
{
return TCL_ERROR;
}
#endif
#ifdef VTK_USE_HYBRID
if (Vtkhybridtcl_Init(interp) == TCL_ERROR)
{
return TCL_ERROR;
}
#endif
#ifdef VTK_USE_PARALLEL
if (Vtkparalleltcl_Init(interp) == TCL_ERROR)
{
return TCL_ERROR;
}
#endif
/*
* Append path to VTK packages to auto_path
*/
static char script[] =
"foreach dir [list {" VTK_TCL_PACKAGE_DIR "} {" VTK_TCL_INSTALL_DIR "}"
" [file join [file dirname [file dirname [info nameofexecutable]]] Wrapping Tcl]"
" [file join [file dirname [file dirname [info nameofexecutable]]] lib vtk tcl]"
" ] {\n"
" if {[file isdirectory $dir]} {\n"
" lappend auto_path $dir\n"
" }\n"
"}\n"
"rename package package.orig\n"
"proc package {args} {\n"
" if {[catch {set package_res [eval package.orig $args]} catch_res]} {\n"
" global errorInfo env\n"
" if {[lindex $args 0] == \"require\"} {\n"
" set expecting {can\'t find package vtk}\n"
" if {![string compare -length [string length $expecting] $catch_res $expecting]} {\n"
" set msg {The Tcl interpreter was probably not able to find the"
" VTK packages. Please check that your TCLLIBPATH environment variable"
" includes the path to your VTK Tcl directory. You might find it under"
" your VTK binary directory in Wrapping/Tcl, or under your"
" site-specific {CMAKE_INSTALL_PREFIX}/lib/vtk/tcl directory.}\n"
" if {[info exists env(TCLLIBPATH)]} {\n"
" append msg \" The TCLLIBPATH current value is: $env(TCLLIBPATH).\"\n"
" }\n"
" set errorInfo \"$msg The TCLLIBPATH variable is a set of"
" space separated paths (hence, path containing spaces should be"
" surrounded by quotes first). Windows users should use forward"
" (Unix-style) slashes \'/\' instead of the usual backward slashes. "
" More informations can be found in the Wrapping/Tcl/README source"
" file (also available online at"
" http://www.vtk.org/cgi-bin/cvsweb.cgi/~checkout~/VTK/Wrapping/Tcl/README).\n"
"$errorInfo\"\n"
" }\n"
" }\n"
" error $catch_res $errorInfo\n"
" }\n"
" return $package_res\n"
"}\n";
Tcl_Eval(interp, script);
/*
* Specify a user-specific startup file to invoke if the application
* is run interactively. Typically the startup file is "~/.apprc"
* where "app" is the name of the application. If this line is deleted
* then no user-specific startup file will be run under any conditions.
*/
Tcl_SetVar(interp,
(char *) "tcl_rcFileName",
(char *) "~/.vtkrc",
TCL_GLOBAL_ONLY);
return TCL_OK;
}
// For a DEBUG build on MSVC, add a hook to prevent error dialogs when
// being run from DART.
#if defined(_MSC_VER) && defined(_DEBUG)
# include <crtdbg.h>
static int vtkTkAppInitDebugReport(int, char* message, int*)
{
fprintf(stderr, message);
exit(1);
return 0;
}
void vtkTkAppInitEnableMSVCDebugHook()
{
if(getenv("DART_TEST_FROM_DART"))
{
_CrtSetReportHook(vtkTkAppInitDebugReport);
}
}
#else
void vtkTkAppInitEnableMSVCDebugHook()
{
}
#endif
<commit_msg>BUG: fix for cygwin tcl wrap builds<commit_after>/*=========================================================================
Program: Visualization Toolkit
Module: vtkTkAppInit.cxx
Language: C++
Date: $Date$
Version: $Revision$
Copyright (c) 1993-2002 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.
=========================================================================*/
/*
* tkAppInit.c --
*
* Provides a default version of the Tcl_AppInit procedure for
* use in wish and similar Tk-based applications.
*
* Copyright (c) 1993 The Regents of the University of California.
* Copyright (c) 1994 Sun Microsystems, Inc.
*
* See the file "license.terms" for information on usage and redistribution
* of this file, and for a DISCLAIMER OF ALL WARRANTIES.
*/
#ifdef VTK_COMPILED_USING_MPI
# include <mpi.h>
# include "vtkMPIController.h"
#endif // VTK_COMPILED_USING_MPI
#include "vtkSystemIncludes.h"
#include "vtkToolkits.h"
#include "Wrapping/Tcl/vtkTkAppInitConfigure.h"
#if defined(CMAKE_INTDIR)
# define VTK_TCL_PACKAGE_DIR VTK_TCL_PACKAGE_DIR_BUILD "/" CMAKE_INTDIR
#else
# define VTK_TCL_PACKAGE_DIR VTK_TCL_PACKAGE_DIR_BUILD
#endif
#ifdef VTK_USE_RENDERING
# include "tk.h"
#else
# include "tcl.h"
#endif
/*
* Make sure all the kits register their classes with vtkInstantiator.
*/
#include "vtkCommonInstantiator.h"
#include "vtkFilteringInstantiator.h"
#include "vtkIOInstantiator.h"
#include "vtkImagingInstantiator.h"
#include "vtkGraphicsInstantiator.h"
#ifdef VTK_USE_RENDERING
#include "vtkRenderingInstantiator.h"
#endif
#ifdef VTK_USE_PATENTED
#include "vtkPatentedInstantiator.h"
#endif
#ifdef VTK_USE_HYBRID
#include "vtkHybridInstantiator.h"
#endif
#ifdef VTK_USE_PARALLEL
#include "vtkParallelInstantiator.h"
#endif
static void vtkTkAppInitEnableMSVCDebugHook();
/*
*----------------------------------------------------------------------
*
* main --
*
* This is the main program for the application.
*
* Results:
* None: Tk_Main never returns here, so this procedure never
* returns either.
*
* Side effects:
* Whatever the application does.
*
*----------------------------------------------------------------------
*/
#ifdef VTK_COMPILED_USING_MPI
class vtkMPICleanup {
public:
vtkMPICleanup()
{
this->Controller = 0;
}
void Initialize(int *argc, char ***argv)
{
MPI_Init(argc, argv);
this->Controller = vtkMPIController::New();
this->Controller->Initialize(argc, argv, 1);
vtkMultiProcessController::SetGlobalController(this->Controller);
}
~vtkMPICleanup()
{
if ( this->Controller )
{
this->Controller->Finalize();
this->Controller->Delete();
}
}
private:
vtkMPIController *Controller;
};
static vtkMPICleanup VTKMPICleanup;
#endif // VTK_COMPILED_USING_MPI
int
main(int argc, char **argv)
{
ios::sync_with_stdio();
vtkTkAppInitEnableMSVCDebugHook();
#ifdef VTK_COMPILED_USING_MPI
VTKMPICleanup.Initialize(&argc, &argv);
#endif // VTK_COMPILED_USING_MPI
#ifdef VTK_USE_RENDERING
Tk_Main(argc, argv, Tcl_AppInit);
#else
Tcl_Main(argc, argv, Tcl_AppInit);
#endif
return 0; /* Needed only to prevent compiler warning. */
}
/*
*----------------------------------------------------------------------
*
* Tcl_AppInit --
*
* This procedure performs application-specific initialization.
* Most applications, especially those that incorporate additional
* packages, will have their own version of this procedure.
*
* Results:
* Returns a standard Tcl completion code, and leaves an error
* message in interp->result if an error occurs.
*
* Side effects:
* Depends on the startup script.
*
*----------------------------------------------------------------------
*/
extern "C" int Vtkcommontcl_Init(Tcl_Interp *interp);
extern "C" int Vtkfilteringtcl_Init(Tcl_Interp *interp);
extern "C" int Vtkimagingtcl_Init(Tcl_Interp *interp);
extern "C" int Vtkgraphicstcl_Init(Tcl_Interp *interp);
extern "C" int Vtkiotcl_Init(Tcl_Interp *interp);
#ifdef VTK_USE_RENDERING
extern "C" int Vtkrenderingtcl_Init(Tcl_Interp *interp);
#if defined(VTK_DISABLE_TK_INIT) && !defined(VTK_USE_COCOA)
extern "C" int Vtktkrenderwidget_Init(Tcl_Interp *interp);
extern "C" int Vtktkimageviewerwidget_Init(Tcl_Interp *interp);
#endif
#endif
#ifdef VTK_USE_PATENTED
extern "C" int Vtkpatentedtcl_Init(Tcl_Interp *interp);
#endif
#ifdef VTK_USE_HYBRID
extern "C" int Vtkhybridtcl_Init(Tcl_Interp *interp);
#endif
#ifdef VTK_USE_PARALLEL
extern "C" int Vtkparalleltcl_Init(Tcl_Interp *interp);
#endif
void help() {
}
int Tcl_AppInit(Tcl_Interp *interp)
{
#ifdef __CYGWIN__
Tcl_SetVar(interp, "tclDefaultLibrary", "/usr/share/tcl" TCL_VERSION, TCL_GLOBAL_ONLY);
#endif
if (Tcl_Init(interp) == TCL_ERROR) {
return TCL_ERROR;
}
#ifdef VTK_USE_RENDERING
if (Tk_Init(interp) == TCL_ERROR) {
return TCL_ERROR;
}
#endif
/* init the core vtk stuff */
if (Vtkcommontcl_Init(interp) == TCL_ERROR)
{
return TCL_ERROR;
}
if (Vtkfilteringtcl_Init(interp) == TCL_ERROR)
{
return TCL_ERROR;
}
if (Vtkimagingtcl_Init(interp) == TCL_ERROR)
{
return TCL_ERROR;
}
if (Vtkgraphicstcl_Init(interp) == TCL_ERROR)
{
return TCL_ERROR;
}
if (Vtkiotcl_Init(interp) == TCL_ERROR)
{
return TCL_ERROR;
}
#ifdef VTK_USE_RENDERING
if (Vtkrenderingtcl_Init(interp) == TCL_ERROR)
{
return TCL_ERROR;
}
#if defined(VTK_DISABLE_TK_INIT) && !defined(VTK_USE_COCOA)
// Need to init here because rendering did not when this option is on
if (Vtktkrenderwidget_Init(interp) == TCL_ERROR)
{
return TCL_ERROR;
}
if (Vtktkimageviewerwidget_Init(interp) == TCL_ERROR)
{
return TCL_ERROR;
}
#endif
#endif
#ifdef VTK_USE_PATENTED
if (Vtkpatentedtcl_Init(interp) == TCL_ERROR)
{
return TCL_ERROR;
}
#endif
#ifdef VTK_USE_HYBRID
if (Vtkhybridtcl_Init(interp) == TCL_ERROR)
{
return TCL_ERROR;
}
#endif
#ifdef VTK_USE_PARALLEL
if (Vtkparalleltcl_Init(interp) == TCL_ERROR)
{
return TCL_ERROR;
}
#endif
/*
* Append path to VTK packages to auto_path
*/
static char script[] =
"foreach dir [list {" VTK_TCL_PACKAGE_DIR "} {" VTK_TCL_INSTALL_DIR "}"
" [file join [file dirname [file dirname [info nameofexecutable]]] Wrapping Tcl]"
" [file join [file dirname [file dirname [info nameofexecutable]]] lib vtk tcl]"
" ] {\n"
" if {[file isdirectory $dir]} {\n"
" lappend auto_path $dir\n"
" }\n"
"}\n"
"rename package package.orig\n"
"proc package {args} {\n"
" if {[catch {set package_res [eval package.orig $args]} catch_res]} {\n"
" global errorInfo env\n"
" if {[lindex $args 0] == \"require\"} {\n"
" set expecting {can\'t find package vtk}\n"
" if {![string compare -length [string length $expecting] $catch_res $expecting]} {\n"
" set msg {The Tcl interpreter was probably not able to find the"
" VTK packages. Please check that your TCLLIBPATH environment variable"
" includes the path to your VTK Tcl directory. You might find it under"
" your VTK binary directory in Wrapping/Tcl, or under your"
" site-specific {CMAKE_INSTALL_PREFIX}/lib/vtk/tcl directory.}\n"
" if {[info exists env(TCLLIBPATH)]} {\n"
" append msg \" The TCLLIBPATH current value is: $env(TCLLIBPATH).\"\n"
" }\n"
" set errorInfo \"$msg The TCLLIBPATH variable is a set of"
" space separated paths (hence, path containing spaces should be"
" surrounded by quotes first). Windows users should use forward"
" (Unix-style) slashes \'/\' instead of the usual backward slashes. "
" More informations can be found in the Wrapping/Tcl/README source"
" file (also available online at"
" http://www.vtk.org/cgi-bin/cvsweb.cgi/~checkout~/VTK/Wrapping/Tcl/README).\n"
"$errorInfo\"\n"
" }\n"
" }\n"
" error $catch_res $errorInfo\n"
" }\n"
" return $package_res\n"
"}\n";
Tcl_Eval(interp, script);
/*
* Specify a user-specific startup file to invoke if the application
* is run interactively. Typically the startup file is "~/.apprc"
* where "app" is the name of the application. If this line is deleted
* then no user-specific startup file will be run under any conditions.
*/
Tcl_SetVar(interp,
(char *) "tcl_rcFileName",
(char *) "~/.vtkrc",
TCL_GLOBAL_ONLY);
return TCL_OK;
}
// For a DEBUG build on MSVC, add a hook to prevent error dialogs when
// being run from DART.
#if defined(_MSC_VER) && defined(_DEBUG)
# include <crtdbg.h>
static int vtkTkAppInitDebugReport(int, char* message, int*)
{
fprintf(stderr, message);
exit(1);
return 0;
}
void vtkTkAppInitEnableMSVCDebugHook()
{
if(getenv("DART_TEST_FROM_DART"))
{
_CrtSetReportHook(vtkTkAppInitDebugReport);
}
}
#else
void vtkTkAppInitEnableMSVCDebugHook()
{
}
#endif
<|endoftext|> |
<commit_before>/* -*- mode: C++; tab-width: 8; indent-tabs-mode: t; c-basic-offset: 8 -*- */
// vim:sts=8:sw=8:ts=8:noet:sr:cino=>s,f0,{0,g0,(0,\:0,t0,+0,=s
//#include "goto-def.h"
/* Copyright (c) FFLAS-FFPACK
* Written by Clément Pernet <clement.pernet@imag.fr>
* ========LICENCE========
* This file is part of the library FFLAS-FFPACK.
*
* FFLAS-FFPACK 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
* ========LICENCE========
*/
// Please do not commit with any of these defines on - AB 2015-01-12
//#define __FFLASFFPACK_USE_TBB
//#define __FFLASFFPACK_USE_OPENMP
//#define __FFLASFFPACK_USE_DATAFLOW
//#define WINO_PARALLEL_TMPS
//#define PFGEMM_WINO_SEQ 32
//#define CLASSIC_SEQ
//#define WINO_SEQ
#define DEBUG 1
#undef NDEBUG
#include "fflas-ffpack/fflas-ffpack-config.h"
#include <iostream>
#include <givaro/modular-balanced.h>
#include "fflas-ffpack/config-blas.h"
#include "fflas-ffpack/fflas/fflas.h"
#include "fflas-ffpack/utils/timer.h"
#include "fflas-ffpack/utils/Matio.h"
#include "fflas-ffpack/utils/args-parser.h"
#include "tests/test-utils.h"
#ifdef __FFLASFFPACK_USE_KAAPI
#include "libkomp.h"
#endif
using namespace std;
//#ifdef __FFLASFFPACK_USE_DATAFLOW
template<class Element>
void Initialize(Element * C, size_t BS, size_t m, size_t n)
{
//#pragma omp parallel for collapse(2) schedule(runtime)
BS=std::max(BS, (size_t)__FFLASFFPACK_WINOTHRESHOLD_BAL );
PAR_BLOCK{
for(size_t p=0; p<m; p+=BS) ///row
for(size_t pp=0; pp<n; pp+=BS) //column
{
size_t M=BS, MM=BS;
if(!(p+BS<m))
M=m-p;
if(!(pp+BS<n))
MM=n-pp;
//#pragma omp task
TASK(MODE(),
{
for(size_t j=0; j<M; j++)
for(size_t jj=0; jj<MM; jj++)
C[(p+j)*n+pp+jj]=0;
});
}
// #pragma omp taskwait
CHECK_DEPENDENCIES
}
// printf("A = \n");
// for (size_t i=0; i<m; i+=128)
// {
// for (size_t j=0; j<n; j+=128)
// {
// int ld = komp_get_locality_domain_num_for( &C[i*n+j] );
// printf("%i ", ld);
// }
// printf("\n");
// }
}
// #else
// template<class Element>
// void Initialize(Element * C, size_t BS, size_t m, size_t n)
// {}
// #endif
int main(int argc, char** argv) {
size_t iter = 3 ;
int64_t q = 131071 ;
size_t m = 2000 ;
size_t k = 2000 ;
size_t n = 2000 ;
int nbw = -1 ;
int p=3;
int t=MAX_THREADS;
int NBK = -1;
Argument as[] = {
{ 'q', "-q Q", "Set the field characteristic (-1 for random).", TYPE_INT , &q },
{ 'm', "-m M", "Set the row dimension of A.", TYPE_INT , &m },
{ 'k', "-k K", "Set the col dimension of A.", TYPE_INT , &k },
{ 'n', "-n N", "Set the col dimension of B.", TYPE_INT , &n },
{ 'w', "-w N", "Set the number of winograd levels (-1 for random).", TYPE_INT , &nbw },
{ 'i', "-i R", "Set number of repetitions.", TYPE_INT , &iter },
{ 'p', "-p P", "0 for sequential, 1 for 2D iterative, 2 for 2D rec, 3 for 2D rec adaptive, 4 for 3D rc in-place, 5 for 3D rec, 6 for 3D rec adaptive.", TYPE_INT , &p },
{ 't', "-t T", "number of virtual threads to drive the partition.", TYPE_INT , &t },
{ 'b', "-b B", "number of numa blocks per dimension for the numa placement", TYPE_INT , &NBK },
END_OF_ARGUMENTS
};
FFLAS::parseArguments(argc,argv,as);
if (NBK==-1) NBK = t;
typedef Givaro::ModularBalanced<double> Field;
// typedef Givaro::ModularBalanced<int64_t> Field;
// typedef Givaro::ModularBalanced<float> Field;
typedef Field::Element Element;
Field F(q);
FFLAS::Timer chrono, freivalds;
double time=0.0, timev=0.0;
Element * A, * B, * C;
Field::RandIter G(F);
A = FFLAS::fflas_new(F,m,k,Alignment::CACHE_PAGESIZE);
//#pragma omp parallel for collapse(2) schedule(runtime)
if (p)
Initialize(A,m/size_t(NBK),m,k);
FFLAS::ParSeqHelper::Parallel H;
size_t i;
//#pragma omp for
PARFOR1D (i,0, m,H,
for (size_t j=0; j<(size_t)k; ++j)
G.random (*(A+i*k+j));
);
B = FFLAS::fflas_new(F,k,n,Alignment::CACHE_PAGESIZE);
//#pragma omp parallel for collapse(2) schedule(runtime)
if (p)
Initialize(B,k/NBK,k,n);
//#pragma omp parallel for
PARFOR1D (i, 0, k,H,
for (size_t j=0; j<(size_t)n; ++j)
G.random(*(B+i*n+j));
);
C = FFLAS::fflas_new(F,m,n,Alignment::CACHE_PAGESIZE);
//#pragma omp parallel for collapse(2) schedule(runtime)
if (p)
Initialize(C,m/NBK,m,n);
for (i=0;i<=iter;++i){
// if (argc > 4){
// A = read_field (F, argv[4], &n, &n);
// }
// else{
chrono.clear();
if (p && p!=7){
FFLAS::CuttingStrategy meth = FFLAS::RECURSIVE;
FFLAS::StrategyParameter strat = FFLAS::THREADS;
switch (p){
case 1: meth = FFLAS::BLOCK;break;
case 2: strat = FFLAS::TWO_D;break;
case 3: strat = FFLAS::TWO_D_ADAPT;break;
case 4: strat = FFLAS::THREE_D_INPLACE;break;
case 5: strat = FFLAS::THREE_D;break;
case 6: strat = FFLAS::THREE_D_ADAPT;break;
default: meth = FFLAS::BLOCK;break;
}
FFLAS::MMHelper<Field,FFLAS::MMHelperAlgo::Winograd,
typename FFLAS::ModeTraits<Field>::value,
FFLAS::ParSeqHelper::Parallel>
WH (F, nbw, FFLAS::ParSeqHelper::Parallel(t, meth, strat));
if (i) chrono.start();
PAR_BLOCK{
FFLAS::fgemm (F, FFLAS::FflasNoTrans, FFLAS::FflasNoTrans, m,n,k, F.one, A, k, B, n, F.zero, C,n,WH);
}
if (i) {chrono.stop(); time+=chrono.realtime();}
}else{
if(p==7){
FFLAS::MMHelper<Field, FFLAS::MMHelperAlgo::WinogradPar>
WH (F, nbw, FFLAS::ParSeqHelper::Sequential());
// cout<<"wino parallel"<<endl;
if (i) chrono.start();
PAR_BLOCK
{
FFLAS::fgemm (F, FFLAS::FflasNoTrans, FFLAS::FflasNoTrans, m,n,k, F.one, A, k, B, n, F.zero, C,n,WH);
}
if (i) {chrono.stop(); time+=chrono.realtime();}
}
else{
FFLAS::MMHelper<Field,FFLAS::MMHelperAlgo::Winograd>//,
//typename FFLAS::FieldTraits<Field>::value,
//FFLAS::ParSeqHelper::Parallel>
WH (F, nbw, FFLAS::ParSeqHelper::Sequential());
if (i) chrono.start();
FFLAS::fgemm (F, FFLAS::FflasNoTrans, FFLAS::FflasNoTrans, m,n,k, F.one, A, k, B, n, F.zero, C,n,WH);
if (i) {chrono.stop(); time+=chrono.realtime();}
}
}
freivalds.clear();
freivalds.start();
bool pass = FFLAS::freivalds(F, FFLAS::FflasNoTrans, FFLAS::FflasNoTrans, m,n,k, F.one, A, k, B, n, C,n);
freivalds.stop();
timev+=freivalds.usertime();
if (!pass)
std::cout<<"FAILED"<<std::endl;
}
FFLAS::fflas_delete( A);
FFLAS::fflas_delete( B);
FFLAS::fflas_delete( C);
// -----------
// Standard output for benchmark - Alexis Breust 2014/11/14
std::cout << "Time: " << time / double(iter)
<< " Gflops: " << (2.*double(m)/1000.*double(n)/1000.*double(k)/1000.0) / time * double(iter);
FFLAS::writeCommandString(std::cout, as) << std::endl;
#if DEBUG
std::cout<<"Freivalds vtime: "<<timev/(double)iter<<std::endl;
#endif
return 0;
}
<commit_msg>remove DEBUG mode in benchmark-fgemm<commit_after>/* -*- mode: C++; tab-width: 8; indent-tabs-mode: t; c-basic-offset: 8 -*- */
// vim:sts=8:sw=8:ts=8:noet:sr:cino=>s,f0,{0,g0,(0,\:0,t0,+0,=s
//#include "goto-def.h"
/* Copyright (c) FFLAS-FFPACK
* Written by Clément Pernet <clement.pernet@imag.fr>
* ========LICENCE========
* This file is part of the library FFLAS-FFPACK.
*
* FFLAS-FFPACK 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
* ========LICENCE========
*/
// Please do not commit with any of these defines on - AB 2015-01-12
//#define __FFLASFFPACK_USE_TBB
//#define __FFLASFFPACK_USE_OPENMP
//#define __FFLASFFPACK_USE_DATAFLOW
//#define WINO_PARALLEL_TMPS
//#define PFGEMM_WINO_SEQ 32
//#define CLASSIC_SEQ
//#define WINO_SEQ
//#define DEBUG 1
//#undef NDEBUG
#include "fflas-ffpack/fflas-ffpack-config.h"
#include <iostream>
#include <givaro/modular-balanced.h>
#include "fflas-ffpack/config-blas.h"
#include "fflas-ffpack/fflas/fflas.h"
#include "fflas-ffpack/utils/timer.h"
#include "fflas-ffpack/utils/Matio.h"
#include "fflas-ffpack/utils/args-parser.h"
#include "tests/test-utils.h"
#ifdef __FFLASFFPACK_USE_KAAPI
#include "libkomp.h"
#endif
using namespace std;
//#ifdef __FFLASFFPACK_USE_DATAFLOW
template<class Element>
void Initialize(Element * C, size_t BS, size_t m, size_t n)
{
//#pragma omp parallel for collapse(2) schedule(runtime)
BS=std::max(BS, (size_t)__FFLASFFPACK_WINOTHRESHOLD_BAL );
PAR_BLOCK{
for(size_t p=0; p<m; p+=BS) ///row
for(size_t pp=0; pp<n; pp+=BS) //column
{
size_t M=BS, MM=BS;
if(!(p+BS<m))
M=m-p;
if(!(pp+BS<n))
MM=n-pp;
//#pragma omp task
TASK(MODE(),
{
for(size_t j=0; j<M; j++)
for(size_t jj=0; jj<MM; jj++)
C[(p+j)*n+pp+jj]=0;
});
}
// #pragma omp taskwait
CHECK_DEPENDENCIES
}
// printf("A = \n");
// for (size_t i=0; i<m; i+=128)
// {
// for (size_t j=0; j<n; j+=128)
// {
// int ld = komp_get_locality_domain_num_for( &C[i*n+j] );
// printf("%i ", ld);
// }
// printf("\n");
// }
}
// #else
// template<class Element>
// void Initialize(Element * C, size_t BS, size_t m, size_t n)
// {}
// #endif
int main(int argc, char** argv) {
size_t iter = 3 ;
int64_t q = 131071 ;
size_t m = 2000 ;
size_t k = 2000 ;
size_t n = 2000 ;
int nbw = -1 ;
int p=3;
int t=MAX_THREADS;
int NBK = -1;
Argument as[] = {
{ 'q', "-q Q", "Set the field characteristic (-1 for random).", TYPE_INT , &q },
{ 'm', "-m M", "Set the row dimension of A.", TYPE_INT , &m },
{ 'k', "-k K", "Set the col dimension of A.", TYPE_INT , &k },
{ 'n', "-n N", "Set the col dimension of B.", TYPE_INT , &n },
{ 'w', "-w N", "Set the number of winograd levels (-1 for random).", TYPE_INT , &nbw },
{ 'i', "-i R", "Set number of repetitions.", TYPE_INT , &iter },
{ 'p', "-p P", "0 for sequential, 1 for 2D iterative, 2 for 2D rec, 3 for 2D rec adaptive, 4 for 3D rc in-place, 5 for 3D rec, 6 for 3D rec adaptive.", TYPE_INT , &p },
{ 't', "-t T", "number of virtual threads to drive the partition.", TYPE_INT , &t },
{ 'b', "-b B", "number of numa blocks per dimension for the numa placement", TYPE_INT , &NBK },
END_OF_ARGUMENTS
};
FFLAS::parseArguments(argc,argv,as);
if (NBK==-1) NBK = t;
typedef Givaro::ModularBalanced<double> Field;
// typedef Givaro::ModularBalanced<int64_t> Field;
// typedef Givaro::ModularBalanced<float> Field;
typedef Field::Element Element;
Field F(q);
FFLAS::Timer chrono, freivalds;
double time=0.0, timev=0.0;
Element * A, * B, * C;
Field::RandIter G(F);
A = FFLAS::fflas_new(F,m,k,Alignment::CACHE_PAGESIZE);
//#pragma omp parallel for collapse(2) schedule(runtime)
if (p)
Initialize(A,m/size_t(NBK),m,k);
FFLAS::ParSeqHelper::Parallel H;
size_t i;
//#pragma omp for
PARFOR1D (i,0, m,H,
for (size_t j=0; j<(size_t)k; ++j)
G.random (*(A+i*k+j));
);
B = FFLAS::fflas_new(F,k,n,Alignment::CACHE_PAGESIZE);
//#pragma omp parallel for collapse(2) schedule(runtime)
if (p)
Initialize(B,k/NBK,k,n);
//#pragma omp parallel for
PARFOR1D (i, 0, k,H,
for (size_t j=0; j<(size_t)n; ++j)
G.random(*(B+i*n+j));
);
C = FFLAS::fflas_new(F,m,n,Alignment::CACHE_PAGESIZE);
//#pragma omp parallel for collapse(2) schedule(runtime)
if (p)
Initialize(C,m/NBK,m,n);
for (i=0;i<=iter;++i){
// if (argc > 4){
// A = read_field (F, argv[4], &n, &n);
// }
// else{
chrono.clear();
if (p && p!=7){
FFLAS::CuttingStrategy meth = FFLAS::RECURSIVE;
FFLAS::StrategyParameter strat = FFLAS::THREADS;
switch (p){
case 1: meth = FFLAS::BLOCK;break;
case 2: strat = FFLAS::TWO_D;break;
case 3: strat = FFLAS::TWO_D_ADAPT;break;
case 4: strat = FFLAS::THREE_D_INPLACE;break;
case 5: strat = FFLAS::THREE_D;break;
case 6: strat = FFLAS::THREE_D_ADAPT;break;
default: meth = FFLAS::BLOCK;break;
}
FFLAS::MMHelper<Field,FFLAS::MMHelperAlgo::Winograd,
typename FFLAS::ModeTraits<Field>::value,
FFLAS::ParSeqHelper::Parallel>
WH (F, nbw, FFLAS::ParSeqHelper::Parallel(t, meth, strat));
if (i) chrono.start();
PAR_BLOCK{
FFLAS::fgemm (F, FFLAS::FflasNoTrans, FFLAS::FflasNoTrans, m,n,k, F.one, A, k, B, n, F.zero, C,n,WH);
}
if (i) {chrono.stop(); time+=chrono.realtime();}
}else{
if(p==7){
FFLAS::MMHelper<Field, FFLAS::MMHelperAlgo::WinogradPar>
WH (F, nbw, FFLAS::ParSeqHelper::Sequential());
// cout<<"wino parallel"<<endl;
if (i) chrono.start();
PAR_BLOCK
{
FFLAS::fgemm (F, FFLAS::FflasNoTrans, FFLAS::FflasNoTrans, m,n,k, F.one, A, k, B, n, F.zero, C,n,WH);
}
if (i) {chrono.stop(); time+=chrono.realtime();}
}
else{
FFLAS::MMHelper<Field,FFLAS::MMHelperAlgo::Winograd>//,
//typename FFLAS::FieldTraits<Field>::value,
//FFLAS::ParSeqHelper::Parallel>
WH (F, nbw, FFLAS::ParSeqHelper::Sequential());
if (i) chrono.start();
FFLAS::fgemm (F, FFLAS::FflasNoTrans, FFLAS::FflasNoTrans, m,n,k, F.one, A, k, B, n, F.zero, C,n,WH);
if (i) {chrono.stop(); time+=chrono.realtime();}
}
}
freivalds.clear();
freivalds.start();
bool pass = FFLAS::freivalds(F, FFLAS::FflasNoTrans, FFLAS::FflasNoTrans, m,n,k, F.one, A, k, B, n, C,n);
freivalds.stop();
timev+=freivalds.usertime();
if (!pass)
std::cout<<"FAILED"<<std::endl;
}
FFLAS::fflas_delete( A);
FFLAS::fflas_delete( B);
FFLAS::fflas_delete( C);
// -----------
// Standard output for benchmark - Alexis Breust 2014/11/14
std::cout << "Time: " << time / double(iter)
<< " Gflops: " << (2.*double(m)/1000.*double(n)/1000.*double(k)/1000.0) / time * double(iter);
FFLAS::writeCommandString(std::cout, as) << std::endl;
#if DEBUG
std::cout<<"Freivalds vtime: "<<timev/(double)iter<<std::endl;
#endif
return 0;
}
<|endoftext|> |
<commit_before>#include "chr/cross/CrossSketch.h"
#if defined(CHR_PLATFORM_DESKTOP) || defined(CHR_PLATFORM_EMSCRIPTEN)
#include "chr/cross/CrossDelegate.h"
#endif
#if defined(CHR_PLATFORM_DESKTOP)
#define STB_IMAGE_WRITE_IMPLEMENTATION
#include "stb_image_write.h"
#endif
using namespace std;
namespace chr
{
#if defined(CHR_PLATFORM_DESKTOP)
void CrossSketch::run(int width, int height, int aaSamples, int depthBits)
{
CrossDelegate delegate;
delegate.run(width, height, aaSamples, depthBits);
}
#elif defined(CHR_PLATFORM_EMSCRIPTEN)
void CrossSketch::run(int aaSamples, int depthBits)
{
CrossDelegate delegate;
delegate.run(aaSamples, depthBits);
}
#endif
double CrossSketch::getElapsedSeconds()
{
return timer.getSeconds(); // OUR FrameClock IS NOT SUITED BECAUSE IT PROVIDES A UNIQUE TIME-SAMPLE PER FRAME
}
int CrossSketch::getElapsedFrames()
{
return frameCount;
}
FrameClock::Ref CrossSketch::clock() const
{
return _clock;
}
// ---
void CrossSketch::performSetup(const WindowInfo &windowInfo)
{
this->windowInfo = windowInfo;
forceResize = true;
setup();
}
void CrossSketch::performResize(const glm::vec2 &size, float safeAreaInsetsTop, float safeAreaInsetsBottom)
{
if (forceResize || (size != windowInfo.size))
{
windowInfo.size = size;
windowInfo.safeAreaInsetsTop = safeAreaInsetsTop;
windowInfo.safeAreaInsetsBottom = safeAreaInsetsBottom;
forceResize = false;
resize();
}
}
void CrossSketch::performStart(StartReason reason)
{
frameCount = 0;
timer.start();
_clock->start();
start(reason);
}
void CrossSketch::performStop(StopReason reason)
{
timer.stop();
_clock->stop();
stop(reason);
}
void CrossSketch::performUpdate()
{
update();
frameCount++;
}
#if defined(CHR_PLATFORM_DESKTOP)
void CrossSketch::grabScreen(const fs::path &destinationDirectory)
{
stringstream stream;
stream << std::setfill('0') << std::setw(6) << grabbedFrameCount++;
fs::path filePath = destinationDirectory / ("IMG_" + stream.str() + ".png");
performGrabScreen(filePath);
}
void CrossSketch::performGrabScreen(const fs::path &filePath)
{
int w = windowInfo.width;
int h = windowInfo.height;
uint8_t *pixels = new uint8_t[w * h * 3];
glPixelStorei(GL_PACK_ALIGNMENT, 1);
glReadPixels(0, 0, w, h, GL_RGB, GL_UNSIGNED_BYTE, (GLvoid*)pixels);
stbi_flip_vertically_on_write(1);
if (stbi_write_png(filePath.string().data(), w, h, 3, pixels, 3 * w))
{
LOGI << "IMAGE WRITTEN: " << filePath.string() << endl;
}
else
{
LOGE << "ERROR WRITING IMAGE: " << filePath.string() << endl;
}
delete[] pixels;
}
#endif
}
<commit_msg>core: Fixing issue with Linux<commit_after>#include "chr/cross/CrossSketch.h"
#if defined(CHR_PLATFORM_DESKTOP) || defined(CHR_PLATFORM_EMSCRIPTEN)
#include "chr/cross/CrossDelegate.h"
#endif
#if defined(CHR_PLATFORM_DESKTOP)
#define STB_IMAGE_WRITE_IMPLEMENTATION
#include "stb_image_write.h"
#endif
#include <iomanip>
using namespace std;
namespace chr
{
#if defined(CHR_PLATFORM_DESKTOP)
void CrossSketch::run(int width, int height, int aaSamples, int depthBits)
{
CrossDelegate delegate;
delegate.run(width, height, aaSamples, depthBits);
}
#elif defined(CHR_PLATFORM_EMSCRIPTEN)
void CrossSketch::run(int aaSamples, int depthBits)
{
CrossDelegate delegate;
delegate.run(aaSamples, depthBits);
}
#endif
double CrossSketch::getElapsedSeconds()
{
return timer.getSeconds(); // OUR FrameClock IS NOT SUITED BECAUSE IT PROVIDES A UNIQUE TIME-SAMPLE PER FRAME
}
int CrossSketch::getElapsedFrames()
{
return frameCount;
}
FrameClock::Ref CrossSketch::clock() const
{
return _clock;
}
// ---
void CrossSketch::performSetup(const WindowInfo &windowInfo)
{
this->windowInfo = windowInfo;
forceResize = true;
setup();
}
void CrossSketch::performResize(const glm::vec2 &size, float safeAreaInsetsTop, float safeAreaInsetsBottom)
{
if (forceResize || (size != windowInfo.size))
{
windowInfo.size = size;
windowInfo.safeAreaInsetsTop = safeAreaInsetsTop;
windowInfo.safeAreaInsetsBottom = safeAreaInsetsBottom;
forceResize = false;
resize();
}
}
void CrossSketch::performStart(StartReason reason)
{
frameCount = 0;
timer.start();
_clock->start();
start(reason);
}
void CrossSketch::performStop(StopReason reason)
{
timer.stop();
_clock->stop();
stop(reason);
}
void CrossSketch::performUpdate()
{
update();
frameCount++;
}
#if defined(CHR_PLATFORM_DESKTOP)
void CrossSketch::grabScreen(const fs::path &destinationDirectory)
{
stringstream stream;
stream << std::setfill('0') << std::setw(6) << grabbedFrameCount++;
fs::path filePath = destinationDirectory / ("IMG_" + stream.str() + ".png");
performGrabScreen(filePath);
}
void CrossSketch::performGrabScreen(const fs::path &filePath)
{
int w = windowInfo.width;
int h = windowInfo.height;
uint8_t *pixels = new uint8_t[w * h * 3];
glPixelStorei(GL_PACK_ALIGNMENT, 1);
glReadPixels(0, 0, w, h, GL_RGB, GL_UNSIGNED_BYTE, (GLvoid*)pixels);
stbi_flip_vertically_on_write(1);
if (stbi_write_png(filePath.string().data(), w, h, 3, pixels, 3 * w))
{
LOGI << "IMAGE WRITTEN: " << filePath.string() << endl;
}
else
{
LOGE << "ERROR WRITING IMAGE: " << filePath.string() << endl;
}
delete[] pixels;
}
#endif
}
<|endoftext|> |
<commit_before>/**
* @cond ___LICENSE___
*
* Copyright (c) 2016 Koen Visscher, Paul Visscher and individual contributors.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*
* @endcond
*/
#include "manager/controllerManager.h"
#include "manager/pluginManager.h"
#include "plugin/plugin.h"
#include "common/file.h"
#include "api/console.h"
#include "preproc/os.h"
#include "config.h"
#define BOOST_DLL_FORCE_ALIAS_INSTANTIATION
#include <boost/dll/runtime_symbol_info.hpp>
#include <boost/dll/shared_library.hpp>
void PluginManager::OnPreInit()
{
LoadPlugins( FindPlugins() );
}
void PluginManager::OnPostRelease()
{
for ( auto plugin : mPlugins )
{
delete plugin.second;
}
mPlugins.clear();
}
void PluginManager::SetBlackList( const std::set< std::string > &blacklist )
{
mBlacklist = blacklist;
}
void PluginManager::LoadPlugins( const std::vector< std::string > &plugins )
{
for ( auto plugin : plugins )
{
boost::dll::shared_library *lib = new boost::dll::shared_library( plugin, boost::dll::load_mode::append_decorations );
std::string pluginName = GetName( plugin );
if ( !LoadPlugin( lib, pluginName, plugin ) )
{
lib->unload();
delete lib;
}
}
}
bool PluginManager::LoadPlugin( boost::dll::shared_library *lib, std::string pluginName,
std::string plugin )
{
const std::string func = GetLoadFunction( pluginName );
if ( lib->has( func ) && !IsBlacklisted( pluginName ) && !IsLoaded( pluginName ) )
{
PluginInfo info = lib->get< PluginInfo( SystemManager * )>( func )( mManagerHolder->system );
std::string name = info.manager->GetName();
StorePlugin( info, plugin, pluginName );
return true;
}
return false;
}
void PluginManager::StorePlugin( const PluginInfo &info, std::string plugin, std::string pluginName )
{
Console::Initf( "Initialising library '%s' on path '%s'.", info.manager->GetName(), plugin );
mManagerHolder->controller->Add( info.type, info.manager );
mAreLoaded.insert( pluginName );
}
bool PluginManager::IsBlacklisted( const std::string &name ) const
{
return mBlacklist.find( name ) != mBlacklist.end();
}
bool PluginManager::IsLoaded( const std::string &name ) const
{
return mAreLoaded.find( name ) != mAreLoaded.end();
}
std::string PluginManager::GetName( const std::string &plugin ) const
{
std::string fileName = Path::GetFileName( plugin, true );
#if !(OS_IS_WINDOWS)
fileName = String::Replace( fileName, "lib", "" );
#endif
return fileName;
}
std::string PluginManager::GetLoadFunction( const std::string &fileName ) const
{
return "Load" + fileName + "Plugin";
}
std::vector< std::string > PluginManager::FindPlugins()
{
std::vector< std::string > plugins;
for ( auto file : File::List( Path::GetExeDirectory() + PROGRAM_PLUGIN_DIRECTORY ) )
{
if ( File::IsSharedLibrary( file ) )
{
plugins.push_back( file );
}
}
return plugins;
}
<commit_msg>fix Addext<commit_after>/**
* @cond ___LICENSE___
*
* Copyright (c) 2016 Koen Visscher, Paul Visscher and individual contributors.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*
* @endcond
*/
#include "manager/controllerManager.h"
#include "manager/pluginManager.h"
#include "plugin/plugin.h"
#include "common/file.h"
#include "api/console.h"
#include "preproc/os.h"
#include "config.h"
#define BOOST_DLL_FORCE_ALIAS_INSTANTIATION
#include <boost/dll/runtime_symbol_info.hpp>
#include <boost/dll/shared_library.hpp>
void PluginManager::OnPreInit()
{
LoadPlugins( FindPlugins() );
}
void PluginManager::OnPostRelease()
{
for ( auto plugin : mPlugins )
{
delete plugin.second;
}
mPlugins.clear();
}
void PluginManager::SetBlackList( const std::set< std::string > &blacklist )
{
mBlacklist = blacklist;
}
void PluginManager::LoadPlugins( const std::vector< std::string > &plugins )
{
for ( auto plugin : plugins )
{
boost::dll::shared_library *lib = new boost::dll::shared_library( plugin, boost::dll::load_mode::append_decorations );
std::string pluginName = GetName( plugin );
if ( !LoadPlugin( lib, pluginName, plugin ) )
{
lib->unload();
delete lib;
}
}
}
bool PluginManager::LoadPlugin( boost::dll::shared_library *lib, std::string pluginName,
std::string plugin )
{
const std::string func = GetLoadFunction( pluginName );
if ( lib->has( func ) && !IsBlacklisted( pluginName ) && !IsLoaded( pluginName ) )
{
PluginInfo info = lib->get< PluginInfo( SystemManager * )>( func )( mManagerHolder->system );
std::string name = info.manager->GetName();
StorePlugin( info, plugin, pluginName );
return true;
}
return false;
}
void PluginManager::StorePlugin( const PluginInfo &info, std::string plugin, std::string pluginName )
{
Console::Initf( "Initialising library '%s' on path '%s'.", info.manager->GetName(), plugin );
mManagerHolder->controller->AddExt( info.type, info.manager );
mAreLoaded.insert( pluginName );
}
bool PluginManager::IsBlacklisted( const std::string &name ) const
{
return mBlacklist.find( name ) != mBlacklist.end();
}
bool PluginManager::IsLoaded( const std::string &name ) const
{
return mAreLoaded.find( name ) != mAreLoaded.end();
}
std::string PluginManager::GetName( const std::string &plugin ) const
{
std::string fileName = Path::GetFileName( plugin, true );
#if !(OS_IS_WINDOWS)
fileName = String::Replace( fileName, "lib", "" );
#endif
return fileName;
}
std::string PluginManager::GetLoadFunction( const std::string &fileName ) const
{
return "Load" + fileName + "Plugin";
}
std::vector< std::string > PluginManager::FindPlugins()
{
std::vector< std::string > plugins;
for ( auto file : File::List( Path::GetExeDirectory() + PROGRAM_PLUGIN_DIRECTORY ) )
{
if ( File::IsSharedLibrary( file ) )
{
plugins.push_back( file );
}
}
return plugins;
}
<|endoftext|> |
<commit_before>#include <cstdint>
#include <iostream>
template<size_t N>
using num = std::integral_constant<size_t, N>;
auto typeFromID(num<7>){
double ret{17.0};
return ret;
}
auto typeFromID(num<8>){
uint64_t ret{19};
return ret;
}
auto typeFromID(num<9>){
const char* ret{"A"};
return ret;
}
template <typename... Ts> struct tuple {};
template <typename ID , typename T, typename... Ts>
struct tuple<ID, T, Ts...> : tuple<Ts...> {
tuple() : tuple<Ts...>(), tail(typeFromID(ID{})){}
//decltype(typeFromID(ID{})) tail;
T tail;
static constexpr size_t id{ID::value};
};
template <size_t ID, typename... Ts>
constexpr bool is_right(){
constexpr size_t id{tuple<Ts...>::id};
return id==ID;
}
template <size_t ID, typename... Ts, typename std::enable_if_t<is_right<ID, Ts...>(), std::nullptr_t> = nullptr>
auto& get(tuple<Ts...>& t) {
return t.tail;
}
template <size_t ID, typename I, typename T, typename... Ts, typename std::enable_if_t<!is_right<ID, I, T, Ts...>(), std::nullptr_t> = nullptr>
auto& get(tuple<I, T, Ts...>& t) {
//TODO : Static assert to verify the the ID we are using is actually usable
//stackoverflow.com/questions/29603364/type-trait-to-check-that-all-types-in-a-parameter-pack-are-copy-constructible
tuple<Ts...>& base = t;
return get<ID>(base);
}
<commit_msg>Dont use T anymore in ctor<commit_after>#include <cstdint>
#include <iostream>
template<size_t N>
using num = std::integral_constant<size_t, N>;
auto typeFromID(num<7>){
double ret{17.0};
return ret;
}
auto typeFromID(num<8>){
uint64_t ret{19};
return ret;
}
auto typeFromID(num<9>){
const char* ret{"A"};
return ret;
}
template <typename... Ts> struct tuple {};
template <typename ID , typename T, typename... Ts>
struct tuple<ID, T, Ts...> : tuple<Ts...> {
tuple() : tuple<Ts...>(), tail(typeFromID(ID{})){}
decltype(typeFromID(ID{})) tail;
static constexpr size_t id{ID::value};
};
template <size_t ID, typename... Ts>
constexpr bool is_right(){
constexpr size_t id{tuple<Ts...>::id};
return id==ID;
}
template <size_t ID, typename... Ts, typename std::enable_if_t<is_right<ID, Ts...>(), std::nullptr_t> = nullptr>
auto& get(tuple<Ts...>& t) {
return t.tail;
}
template <size_t ID, typename I, typename T, typename... Ts, typename std::enable_if_t<!is_right<ID, I, T, Ts...>(), std::nullptr_t> = nullptr>
auto& get(tuple<I, T, Ts...>& t) {
//TODO : Static assert to verify the the ID we are using is actually usable
//stackoverflow.com/questions/29603364/type-trait-to-check-that-all-types-in-a-parameter-pack-are-copy-constructible
tuple<Ts...>& base = t;
return get<ID>(base);
}
<|endoftext|> |
<commit_before>// RUN: %clang_cc1 -debug-info-kind=limited -triple %itanium_abi_triple \
// RUN: -fdebug-prefix-map=%S=/SOURCE_ROOT %s -emit-llvm -o - | FileCheck %s
template <typename T> void b(T) {}
void c() {
// CHECK: !DISubprogram(name: "b<(lambda at
// CHECK-SAME: /SOURCE_ROOT/debug-prefix-map-lambda.cpp
// CHECK-SAME: [[@LINE+1]]:{{[0-9]+}})>"
b([]{});
}
<commit_msg>Relax test to also work on Windows.<commit_after>// RUN: %clang_cc1 -debug-info-kind=limited -triple %itanium_abi_triple \
// RUN: -fdebug-prefix-map=%S=/SOURCE_ROOT %s -emit-llvm -o - | FileCheck %s
template <typename T> void b(T) {}
void c() {
// CHECK: !DISubprogram(name: "b<(lambda at
// CHECK-SAME: SOURCE_ROOT
// CHECK-SAME: [[@LINE+1]]:{{[0-9]+}})>"
b([]{});
}
<|endoftext|> |
<commit_before>// ========================================================================== //
// This file is part of DO++, a basic set of libraries in C++ for computer
// vision.
//
// Copyright (C) 2013 David Ok <david.ok8@gmail.com>
//
// 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/.
// ========================================================================== //
#include <gtest/gtest.h>
#include <DO/ImageProcessing/ImagePyramid.hpp>
#include "../AssertHelpers.hpp"
using namespace std;
using namespace DO;
TEST(TestInterpolation, test_interpolation)
{
Image<float> f(2, 2);
f.matrix() <<
0, 1,
0, 1;
double eps = 1e-8;
double value;
for (int x = 0; x < 2; ++x)
{
for (int y = 0; y < 2; ++y)
{
Vector2d p;
p.x() = x == 0 ? 0 : 1-eps;
p.y() = y == 0 ? 0 : 1-eps;
value = interpolate(f, p);
ASSERT_NEAR(f(x, y), value, 1e-7);
}
}
value = interpolate(f, Vector2d(0.5, 0.0));
ASSERT_NEAR(0.5, value, 1e-7);
value = interpolate(f, Vector2d(0.5, 0.2));
ASSERT_NEAR(0.5, value, 1e-7);
value = interpolate(f, Vector2d(0.5, 0.1));
ASSERT_NEAR(0.5, value, 1e-7);
value = interpolate(f, Vector2d(0.5, 0.8));
ASSERT_NEAR(0.5, value, 1e-7);
value = interpolate(f, Vector2d(0.5, 1.-eps));
ASSERT_NEAR(0.5, value, 1e-7);
f.matrix() <<
0, 0,
1, 1;
value = interpolate(f, Vector2d(0.0, 0.5));
ASSERT_NEAR(0.5, value, 1e-7);
value = interpolate(f, Vector2d(0.2, 0.5));
ASSERT_NEAR(0.5, value, 1e-7);
value = interpolate(f, Vector2d(0.5, 0.5));
ASSERT_NEAR(0.5, value, 1e-7);
value = interpolate(f, Vector2d(0.8, 0.5));
ASSERT_NEAR(0.5, value, 1e-7);
value = interpolate(f, Vector2d(1.-eps, 0.5));
ASSERT_NEAR(0.5, value, 1e-7);
}
int main(int argc, char** argv)
{
testing::InitGoogleTest(&argc, argv);
return RUN_ALL_TESTS();
}<commit_msg>Fixed wrong header inclusion.<commit_after>// ========================================================================== //
// This file is part of DO++, a basic set of libraries in C++ for computer
// vision.
//
// Copyright (C) 2013 David Ok <david.ok8@gmail.com>
//
// 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/.
// ========================================================================== //
#include <gtest/gtest.h>
#include <DO/ImageProcessing/Interpolation.hpp>
#include "../AssertHelpers.hpp"
using namespace std;
using namespace DO;
TEST(TestInterpolation, test_interpolation)
{
Image<float> f(2, 2);
f.matrix() <<
0, 1,
0, 1;
double eps = 1e-8;
double value;
for (int x = 0; x < 2; ++x)
{
for (int y = 0; y < 2; ++y)
{
Vector2d p;
p.x() = x == 0 ? 0 : 1-eps;
p.y() = y == 0 ? 0 : 1-eps;
value = interpolate(f, p);
ASSERT_NEAR(f(x, y), value, 1e-7);
}
}
value = interpolate(f, Vector2d(0.5, 0.0));
ASSERT_NEAR(0.5, value, 1e-7);
value = interpolate(f, Vector2d(0.5, 0.2));
ASSERT_NEAR(0.5, value, 1e-7);
value = interpolate(f, Vector2d(0.5, 0.1));
ASSERT_NEAR(0.5, value, 1e-7);
value = interpolate(f, Vector2d(0.5, 0.8));
ASSERT_NEAR(0.5, value, 1e-7);
value = interpolate(f, Vector2d(0.5, 1.-eps));
ASSERT_NEAR(0.5, value, 1e-7);
f.matrix() <<
0, 0,
1, 1;
value = interpolate(f, Vector2d(0.0, 0.5));
ASSERT_NEAR(0.5, value, 1e-7);
value = interpolate(f, Vector2d(0.2, 0.5));
ASSERT_NEAR(0.5, value, 1e-7);
value = interpolate(f, Vector2d(0.5, 0.5));
ASSERT_NEAR(0.5, value, 1e-7);
value = interpolate(f, Vector2d(0.8, 0.5));
ASSERT_NEAR(0.5, value, 1e-7);
value = interpolate(f, Vector2d(1.-eps, 0.5));
ASSERT_NEAR(0.5, value, 1e-7);
}
int main(int argc, char** argv)
{
testing::InitGoogleTest(&argc, argv);
return RUN_ALL_TESTS();
}<|endoftext|> |
<commit_before>#include "view/SceneView.h"
#include "DotSceneLoader.h"
#include "util/BulletDebugDrawer.h"
#include <OgreRoot.h>
#include <OgreViewport.h>
#include <OgreConfigFile.h>
#include <OgreEntity.h>
#include <OgreWindowEventUtilities.h>
#include <sstream>
#include <string>
SceneView::SceneView(Rally::Model::World& world) :
world(world),
camera(NULL),
sceneManager(NULL),
renderWindow(NULL) {
}
SceneView::~SceneView() {
delete bulletDebugDrawer;
Ogre::Root* root = Ogre::Root::getSingletonPtr();
delete root;
}
void SceneView::initialize(std::string resourceConfigPath, std::string pluginConfigPath) {
Ogre::Root* root = new Ogre::Root(pluginConfigPath);
this->loadResourceConfig(resourceConfigPath);
// (The actual precaching is done below, once there is a render context)
if(!root->restoreConfig() && !root->showConfigDialog()) {
throw std::runtime_error("Could neither restore Ogre config, nor read it from the user.");
}
renderWindow = root->initialise(
true, // auto-create the render window now
"Rally Sport Racing Game");
sceneManager = root->createSceneManager("OctreeSceneManager"); // Todo: Research a good scene manager
// This should be done after creating a scene manager, so that there is a render context (GL/D3D)
Ogre::ResourceGroupManager::getSingleton().initialiseAllResourceGroups();
camera = this->addCamera("MainCamera");
Ogre::Viewport* viewport = this->addViewport(camera);
camera->setAspectRatio(Ogre::Real(viewport->getActualWidth()) / Ogre::Real(viewport->getActualHeight()));
Ogre::SceneNode* sceneNode = sceneManager->getRootSceneNode()->createChildSceneNode();
sceneNode->setPosition(Ogre::Vector3(0, 110.0f, 0));
sceneManager->setAmbientLight(Ogre::ColourValue(1, 1, 1));
Ogre::Light* light = sceneManager->createLight("MainLight");
// Load the scene.
DotSceneLoader loader;
loader.parseDotScene("world.scene", "General", sceneManager, sceneNode);
// Todo: Move to appropriate view
Ogre::Entity* playerCarEntity = sceneManager->createEntity("PlayerCar", "car.mesh");
playerCarNode = sceneManager->getRootSceneNode()->createChildSceneNode();
playerCarNode->attachObject(playerCarEntity);
playerCarNode->scale(Ogre::Vector3(2.0f, 1.0f, 4.0f) / playerCarEntity->getBoundingBox().getSize()); // Force scale to 2, 1, 4. Might be buggy...
// Debug draw Bullet
bulletDebugDrawer = new Rally::Util::BulletDebugDrawer(sceneManager);
world.getPhysicsWorld().getDynamicsWorld()->setDebugDrawer(bulletDebugDrawer);
}
Ogre::Viewport* SceneView::addViewport(Ogre::Camera* followedCamera) {
Ogre::Viewport* viewport = renderWindow->addViewport(camera);
viewport->setBackgroundColour(Ogre::ColourValue(0, 0, 0));
return viewport;
}
Ogre::Camera* SceneView::addCamera(Ogre::String cameraName) {
// Setup camera to match viewport
Ogre::Camera* camera = sceneManager->createCamera(cameraName);
camera->setNearClipDistance(5);
return camera;
}
void SceneView::loadResourceConfig(Ogre::String resourceConfigPath) {
Ogre::ResourceGroupManager& resourceGroupManager = Ogre::ResourceGroupManager::getSingleton();
Ogre::ConfigFile resourceConfig;
resourceConfig.load(resourceConfigPath);
for(Ogre::ConfigFile::SectionIterator sectionIterator = resourceConfig.getSectionIterator();
sectionIterator.hasMoreElements();
sectionIterator.moveNext()) {
Ogre::ConfigFile::SettingsMultiMap* settings = sectionIterator.peekNextValue();
// Now load all the resources for this resource group
for(Ogre::ConfigFile::SettingsMultiMap::iterator resource = settings->begin();
resource != settings->end();
++resource) {
resourceGroupManager.addResourceLocation(
resource->second, // filename of directory
resource->first, // resource type
sectionIterator.peekNextKey()); // resource group
}
}
}
bool SceneView::renderFrame() {
Ogre::WindowEventUtilities::messagePump();
if(renderWindow->isClosed()) {
return false;
} else {
updatePlayerCar();
world.getPhysicsWorld().getDynamicsWorld()->debugDrawWorld();
Ogre::Root& root = Ogre::Root::getSingleton();
if(!root.renderOneFrame()) {
return false;
}
}
return true;
}
void SceneView::updatePlayerCar() {
// Todo: Move to separate view
Rally::Model::Car& playerCar = world.getPlayerCar();
Rally::Vector3 position = playerCar.getPosition();
playerCarNode->setPosition(position);
playerCarNode->setOrientation(playerCar.getOrientation());
Rally::Vector3 cameraPosition = position + Ogre::Vector3(0.0f, 350.0f, -500.0f);
camera->setPosition(cameraPosition);
sceneManager->getLight("MainLight")->setPosition(cameraPosition);
camera->lookAt(position);
}
void SceneView::remoteCarUpdated(int carId, const Rally::Model::RemoteCar& remoteCar) {
// Todo: Move to separate view
std::ostringstream baseNameStream;
baseNameStream << "RemoteCar_" << carId;
std::string baseString = baseNameStream.str();
std::string nodeName = baseString + "_Node";
Ogre::SceneNode* remoteCarNode;
if(sceneManager->hasSceneNode(nodeName)) {
remoteCarNode = sceneManager->getSceneNode(nodeName);// Throws if nodeName not found.
} else {
// Lazily construct if not found
Ogre::Entity* remoteCarEntity = sceneManager->createEntity(baseString + "_Entity", "car.mesh");
remoteCarNode = sceneManager->getRootSceneNode()->createChildSceneNode(nodeName);
remoteCarNode->attachObject(remoteCarEntity);
remoteCarNode->scale(Ogre::Vector3(2.0f, 1.0f, 4.0f) / remoteCarEntity->getBoundingBox().getSize()); // Force scale to 2, 1, 4. Might be buggy...
}
remoteCarNode->setPosition(remoteCar.getPosition());
remoteCarNode->setOrientation(remoteCar.getOrientation());
/*std::map<const Rally::Model::RemoteCar&, TheViewType::iterator found = remoteCarViews.find(remoteCar);
// Lazily construct if not found
if(found == remoteCarViews.end()) {
found = remoteCarViews.insert(std::map<const Rally::Model::RemoteCar&, TheViewType>::value_type(remoteCar,
TheViewType(remoteCar))).first;
}*/
}
void SceneView::remoteCarRemoved(int carId, const Rally::Model::RemoteCar& remoteCar) {
// Todo: Move to separate view
std::ostringstream baseNameStream;
baseNameStream << "RemoteCar_" << carId;
std::string baseString = baseNameStream.str();
sceneManager->destroySceneNode(baseString + "_Node");
sceneManager->destroyEntity(baseString + "_Entity");
}
<commit_msg>Moved camera a bit closer to the car.<commit_after>#include "view/SceneView.h"
#include "DotSceneLoader.h"
#include "util/BulletDebugDrawer.h"
#include <OgreRoot.h>
#include <OgreViewport.h>
#include <OgreConfigFile.h>
#include <OgreEntity.h>
#include <OgreWindowEventUtilities.h>
#include <sstream>
#include <string>
SceneView::SceneView(Rally::Model::World& world) :
world(world),
camera(NULL),
sceneManager(NULL),
renderWindow(NULL) {
}
SceneView::~SceneView() {
delete bulletDebugDrawer;
Ogre::Root* root = Ogre::Root::getSingletonPtr();
delete root;
}
void SceneView::initialize(std::string resourceConfigPath, std::string pluginConfigPath) {
Ogre::Root* root = new Ogre::Root(pluginConfigPath);
this->loadResourceConfig(resourceConfigPath);
// (The actual precaching is done below, once there is a render context)
if(!root->restoreConfig() && !root->showConfigDialog()) {
throw std::runtime_error("Could neither restore Ogre config, nor read it from the user.");
}
renderWindow = root->initialise(
true, // auto-create the render window now
"Rally Sport Racing Game");
sceneManager = root->createSceneManager("OctreeSceneManager"); // Todo: Research a good scene manager
// This should be done after creating a scene manager, so that there is a render context (GL/D3D)
Ogre::ResourceGroupManager::getSingleton().initialiseAllResourceGroups();
camera = this->addCamera("MainCamera");
Ogre::Viewport* viewport = this->addViewport(camera);
camera->setAspectRatio(Ogre::Real(viewport->getActualWidth()) / Ogre::Real(viewport->getActualHeight()));
Ogre::SceneNode* sceneNode = sceneManager->getRootSceneNode()->createChildSceneNode();
sceneNode->setPosition(Ogre::Vector3(0, 110.0f, 0));
sceneManager->setAmbientLight(Ogre::ColourValue(1, 1, 1));
Ogre::Light* light = sceneManager->createLight("MainLight");
// Load the scene.
DotSceneLoader loader;
loader.parseDotScene("world.scene", "General", sceneManager, sceneNode);
// Todo: Move to appropriate view
Ogre::Entity* playerCarEntity = sceneManager->createEntity("PlayerCar", "car.mesh");
playerCarNode = sceneManager->getRootSceneNode()->createChildSceneNode();
playerCarNode->attachObject(playerCarEntity);
playerCarNode->scale(Ogre::Vector3(2.0f, 1.0f, 4.0f) / playerCarEntity->getBoundingBox().getSize()); // Force scale to 2, 1, 4. Might be buggy...
// Debug draw Bullet
bulletDebugDrawer = new Rally::Util::BulletDebugDrawer(sceneManager);
world.getPhysicsWorld().getDynamicsWorld()->setDebugDrawer(bulletDebugDrawer);
}
Ogre::Viewport* SceneView::addViewport(Ogre::Camera* followedCamera) {
Ogre::Viewport* viewport = renderWindow->addViewport(camera);
viewport->setBackgroundColour(Ogre::ColourValue(0, 0, 0));
return viewport;
}
Ogre::Camera* SceneView::addCamera(Ogre::String cameraName) {
// Setup camera to match viewport
Ogre::Camera* camera = sceneManager->createCamera(cameraName);
camera->setNearClipDistance(5);
return camera;
}
void SceneView::loadResourceConfig(Ogre::String resourceConfigPath) {
Ogre::ResourceGroupManager& resourceGroupManager = Ogre::ResourceGroupManager::getSingleton();
Ogre::ConfigFile resourceConfig;
resourceConfig.load(resourceConfigPath);
for(Ogre::ConfigFile::SectionIterator sectionIterator = resourceConfig.getSectionIterator();
sectionIterator.hasMoreElements();
sectionIterator.moveNext()) {
Ogre::ConfigFile::SettingsMultiMap* settings = sectionIterator.peekNextValue();
// Now load all the resources for this resource group
for(Ogre::ConfigFile::SettingsMultiMap::iterator resource = settings->begin();
resource != settings->end();
++resource) {
resourceGroupManager.addResourceLocation(
resource->second, // filename of directory
resource->first, // resource type
sectionIterator.peekNextKey()); // resource group
}
}
}
bool SceneView::renderFrame() {
Ogre::WindowEventUtilities::messagePump();
if(renderWindow->isClosed()) {
return false;
} else {
updatePlayerCar();
world.getPhysicsWorld().getDynamicsWorld()->debugDrawWorld();
Ogre::Root& root = Ogre::Root::getSingleton();
if(!root.renderOneFrame()) {
return false;
}
}
return true;
}
void SceneView::updatePlayerCar() {
// Todo: Move to separate view
Rally::Model::Car& playerCar = world.getPlayerCar();
Rally::Vector3 position = playerCar.getPosition();
playerCarNode->setPosition(position);
playerCarNode->setOrientation(playerCar.getOrientation());
Rally::Vector3 cameraPosition = position + Ogre::Vector3(0.0f, 2.0f*35.0f, 2.0f*-50.0f);
camera->setPosition(cameraPosition);
sceneManager->getLight("MainLight")->setPosition(cameraPosition);
camera->lookAt(position);
}
void SceneView::remoteCarUpdated(int carId, const Rally::Model::RemoteCar& remoteCar) {
// Todo: Move to separate view
std::ostringstream baseNameStream;
baseNameStream << "RemoteCar_" << carId;
std::string baseString = baseNameStream.str();
std::string nodeName = baseString + "_Node";
Ogre::SceneNode* remoteCarNode;
if(sceneManager->hasSceneNode(nodeName)) {
remoteCarNode = sceneManager->getSceneNode(nodeName);// Throws if nodeName not found.
} else {
// Lazily construct if not found
Ogre::Entity* remoteCarEntity = sceneManager->createEntity(baseString + "_Entity", "car.mesh");
remoteCarNode = sceneManager->getRootSceneNode()->createChildSceneNode(nodeName);
remoteCarNode->attachObject(remoteCarEntity);
remoteCarNode->scale(Ogre::Vector3(2.0f, 1.0f, 4.0f) / remoteCarEntity->getBoundingBox().getSize()); // Force scale to 2, 1, 4. Might be buggy...
}
remoteCarNode->setPosition(remoteCar.getPosition());
remoteCarNode->setOrientation(remoteCar.getOrientation());
/*std::map<const Rally::Model::RemoteCar&, TheViewType::iterator found = remoteCarViews.find(remoteCar);
// Lazily construct if not found
if(found == remoteCarViews.end()) {
found = remoteCarViews.insert(std::map<const Rally::Model::RemoteCar&, TheViewType>::value_type(remoteCar,
TheViewType(remoteCar))).first;
}*/
}
void SceneView::remoteCarRemoved(int carId, const Rally::Model::RemoteCar& remoteCar) {
// Todo: Move to separate view
std::ostringstream baseNameStream;
baseNameStream << "RemoteCar_" << carId;
std::string baseString = baseNameStream.str();
sceneManager->destroySceneNode(baseString + "_Node");
sceneManager->destroyEntity(baseString + "_Entity");
}
<|endoftext|> |
<commit_before>#include <iostream>
#include <iomanip>
#include "janssonxx.h"
using namespace std;
#define ASSERT_OP(lhs, rhs, op, m) \
do { \
if(!((lhs) op (rhs))) { \
std::cerr << std::boolalpha; \
std::cerr << __FILE__ << '[' << __LINE__ << "]: ERROR: " << (m) << std::endl; \
std::cerr << "\ttest: " << #lhs << ' ' << #op << ' ' << #rhs << std::endl; \
std::cerr << "\tresult: " << (lhs) << ' ' << #op << ' ' << (rhs) << std::endl; \
return 1; \
} \
} while(0)
#define ASSERT_EQ(lhs, rhs, m) ASSERT_OP(lhs, rhs, ==, m)
#define ASSERT_NE(lhs, rhs, m) ASSERT_OP(lhs, rhs, !=, m)
#define ASSERT_TRUE(p, m) ASSERT_OP(p, true, ==, m)
#define ASSERT_FALSE(p, m) ASSERT_OP(p, true, !=, m)
int main() {
jansson::Value e1(jansson::Value::load_file("test.json"));
jansson::Value e2(e1);
jansson::Value e3;
jansson::Value e4(jansson::Value::load_string("{\"foo\": true, \"bar\": \"test\"}"));
ASSERT_TRUE(e1.is_object(), "e1 is not an object");
ASSERT_TRUE(e2.is_object(), "e2 is not an object");
ASSERT_TRUE(e3.is_undefined(), "e3 has a defined value");
ASSERT_TRUE(e4.is_object(), "e4 is not an object");
ASSERT_EQ(e1.size(), 1, "e1 has too many properties");
ASSERT_EQ(e2.size(), 1, "e2 has too many properties");
ASSERT_EQ(e4.size(), 2, "e4 does not have 2 elements");
ASSERT_TRUE(e1.get("web-app").is_object(), "e1[0].web-app is not an object");
ASSERT_EQ(e1.get("web-app").get("servlet").at(0).get("servlet-class").as_string(), "org.cofax.cds.CDSServlet", "property has incorrect value");
ASSERT_EQ(e1["web-app"]["servlet"][0]["servlet-class"].as_string(), "org.cofax.cds.CDSServlet", "property has incorrect value");
ASSERT_EQ(e4["foo"].as_boolean(), true, "property has incorrect value");
jansson::Iterator i(e1.get("web-app"));
ASSERT_EQ(i.key(), "taglib", "first iterator result has incorrect key");
i.next();
ASSERT_EQ(i.key(), "servlet", "first iterator result has incorrect key");
i.next();
ASSERT_EQ(i.key(), "servlet-mapping", "first iterator result has incorrect key");
i.next();
ASSERT_FALSE(i.valid(), "iterator has more values than expected");
e3 = jansson::Value::from(12.34);
ASSERT_TRUE(e3.is_number(), "e3 is not a number after assignment");
ASSERT_EQ(e3.as_real(), 12.34, "e3 has incorrect value after assignment");
e3 = jansson::Value::from(true);
ASSERT_TRUE(e3.is_boolean(), "e3 is not a boolean after assignment");
ASSERT_EQ(e3.as_boolean(), true, "e3 has incorrect value after assignment");
e3 = jansson::Value::from("foobar");
ASSERT_TRUE(e3.is_string(), "e3 is not a string after assignment");
ASSERT_EQ(e3.as_string(), "foobar", "e3 has incorrect value after assignment");
e3.set(0, jansson::Value::from("foobar"));
ASSERT_TRUE(e3.is_array(), "e3 is not an array after index assignment");
ASSERT_EQ(e3.size(), 1, "e3 has incorrect number of elements after assignment");
ASSERT_EQ(e3[0].as_string(), "foobar", "e3[0] has incorrect value after assignment");
e3.set(1, jansson::Value::from("foobar"));
ASSERT_TRUE(e3.is_array(), "e3 is not an array after index assignment");
ASSERT_EQ(e3.size(), 2, "e3 has incorrect number of elements after assignment");
ASSERT_EQ(e3[1].as_string(), "foobar", "e3[0] has incorrect value after assignment");
e3.set(0, jansson::Value::from("barfoo"));
ASSERT_TRUE(e3.is_array(), "e3 is not an array after index assignment");
ASSERT_EQ(e3.size(), 2, "e3 has incorrect number of elements after assignment");
ASSERT_EQ(e3[0].as_string(), "barfoo", "e3[0] has incorrect value after assignment");
e3.set(100, jansson::Value::null());
ASSERT_TRUE(e3.is_array(), "e3 is not an array after index assignment");
ASSERT_EQ(e3.size(), 2, "e3 has incorrect number of elements after assignment");
return 0;
}
<commit_msg>test object property assignment and clear<commit_after>#include <iostream>
#include <iomanip>
#include "janssonxx.h"
using namespace std;
#define ASSERT_OP(lhs, rhs, op, m) \
do { \
if(!((lhs) op (rhs))) { \
std::cerr << std::boolalpha; \
std::cerr << __FILE__ << '[' << __LINE__ << "]: ERROR: " << (m) << std::endl; \
std::cerr << "\ttest: " << #lhs << ' ' << #op << ' ' << #rhs << std::endl; \
std::cerr << "\tresult: " << (lhs) << ' ' << #op << ' ' << (rhs) << std::endl; \
return 1; \
} \
} while(0)
#define ASSERT_EQ(lhs, rhs, m) ASSERT_OP(lhs, rhs, ==, m)
#define ASSERT_NE(lhs, rhs, m) ASSERT_OP(lhs, rhs, !=, m)
#define ASSERT_TRUE(p, m) ASSERT_OP(p, true, ==, m)
#define ASSERT_FALSE(p, m) ASSERT_OP(p, true, !=, m)
int main() {
jansson::Value e1(jansson::Value::load_file("test.json"));
jansson::Value e2(e1);
jansson::Value e3;
jansson::Value e4(jansson::Value::load_string("{\"foo\": true, \"bar\": \"test\"}"));
ASSERT_TRUE(e1.is_object(), "e1 is not an object");
ASSERT_TRUE(e2.is_object(), "e2 is not an object");
ASSERT_TRUE(e3.is_undefined(), "e3 has a defined value");
ASSERT_TRUE(e4.is_object(), "e4 is not an object");
ASSERT_EQ(e1.size(), 1, "e1 has too many properties");
ASSERT_EQ(e2.size(), 1, "e2 has too many properties");
ASSERT_EQ(e4.size(), 2, "e4 does not have 2 elements");
ASSERT_TRUE(e1.get("web-app").is_object(), "e1[0].web-app is not an object");
ASSERT_EQ(e1.get("web-app").get("servlet").at(0).get("servlet-class").as_string(), "org.cofax.cds.CDSServlet", "property has incorrect value");
ASSERT_EQ(e1["web-app"]["servlet"][0]["servlet-class"].as_string(), "org.cofax.cds.CDSServlet", "property has incorrect value");
ASSERT_EQ(e4["foo"].as_boolean(), true, "property has incorrect value");
jansson::Iterator i(e1.get("web-app"));
ASSERT_EQ(i.key(), "taglib", "first iterator result has incorrect key");
i.next();
ASSERT_EQ(i.key(), "servlet", "first iterator result has incorrect key");
i.next();
ASSERT_EQ(i.key(), "servlet-mapping", "first iterator result has incorrect key");
i.next();
ASSERT_FALSE(i.valid(), "iterator has more values than expected");
e3 = jansson::Value::from(12.34);
ASSERT_TRUE(e3.is_number(), "e3 is not a number after assignment");
ASSERT_EQ(e3.as_real(), 12.34, "e3 has incorrect value after assignment");
e3 = jansson::Value::from(true);
ASSERT_TRUE(e3.is_boolean(), "e3 is not a boolean after assignment");
ASSERT_EQ(e3.as_boolean(), true, "e3 has incorrect value after assignment");
e3 = jansson::Value::from("foobar");
ASSERT_TRUE(e3.is_string(), "e3 is not a string after assignment");
ASSERT_EQ(e3.as_string(), "foobar", "e3 has incorrect value after assignment");
e3 = jansson::Value::object();
ASSERT_TRUE(e3.is_object(), "e3 is not an object after assignment");
e3 = jansson::Value::null();
ASSERT_TRUE(e3.is_null(), "e3 is not null after assignment");
e3.set(0, jansson::Value::from("foobar"));
ASSERT_TRUE(e3.is_array(), "e3 is not an array after index assignment");
ASSERT_EQ(e3.size(), 1, "e3 has incorrect number of elements after assignment");
ASSERT_EQ(e3[0].as_string(), "foobar", "e3[0] has incorrect value after assignment");
e3.set(1, jansson::Value::from("foobar"));
ASSERT_TRUE(e3.is_array(), "e3 is not an array after index assignment");
ASSERT_EQ(e3.size(), 2, "e3 has incorrect number of elements after assignment");
ASSERT_EQ(e3[1].as_string(), "foobar", "e3[0] has incorrect value after assignment");
e3.set(0, jansson::Value::from("barfoo"));
ASSERT_TRUE(e3.is_array(), "e3 is not an array after index assignment");
ASSERT_EQ(e3.size(), 2, "e3 has incorrect number of elements after assignment");
ASSERT_EQ(e3[0].as_string(), "barfoo", "e3[0] has incorrect value after assignment");
e3.set(100, jansson::Value::null());
ASSERT_TRUE(e3.is_array(), "e3 is not an array after index assignment");
ASSERT_EQ(e3.size(), 2, "e3 has incorrect number of elements after assignment");
e3.clear();
ASSERT_EQ(e3.size(), 0, "e3 has incorrect number of elements after clear");
e3.set("foo", jansson::Value::from("test"));
ASSERT_TRUE(e3.is_object(), "e3 is not an object after property assignment");
ASSERT_EQ(e3.size(), 1, "e3 has incorrect number of properties after assignment");
ASSERT_EQ(e3["foo"].as_string(), "test", "e3.foo has incorrect value after assignment");
e3.set("foo", jansson::Value::from("again"));
ASSERT_TRUE(e3.is_object(), "e3 is not an object after property assignment");
ASSERT_EQ(e3.size(), 1, "e3 has incorrect number of properties after assignment");
ASSERT_EQ(e3["foo"].as_string(), "again", "e3.foo has incorrect value after assignment");
e3.set("bar", jansson::Value::from("test"));
ASSERT_TRUE(e3.is_object(), "e3 is not an object after property assignment");
ASSERT_EQ(e3.size(), 2, "e3 has incorrect number of properties after assignment");
ASSERT_EQ(e3["bar"].as_string(), "test", "e3.foo has incorrect value after assignment");
e3.clear();
ASSERT_EQ(e3.size(), 0, "e3 has incorrect number of properties after clear");
return 0;
}
<|endoftext|> |
<commit_before>/**
* @file Cosa/SPI/Driver/HCI.cpp
* @version 1.0
*
* @section License
* Copyright (C) 2015, Mikael Patel
*
* 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.
*
* This file is part of the Arduino Che Cosa project.
*/
#include "Cosa/SPI/Driver/HCI.hh"
#include "Cosa/RTC.hh"
#include "Cosa/Trace.hh"
int
HCI::read(void* msg, size_t len)
{
if (!m_available) return (0);
uint16_t payload;
int res = -EFAULT;
spi.acquire(this);
spi.begin();
if (spi.transfer(SPI_OP_READ) == SPI_OP_REPLY) {
spi.transfer(0);
spi.transfer(0);
payload = spi.transfer(0);
payload = (payload << 8) | spi.transfer(0);
if (payload <= len) {
res = payload;
spi.read(msg, res);
}
else {
for (uint16_t i = 0; i < payload; i++) spi.transfer(0);
res = -EINVAL;
}
}
m_available = false;
spi.end();
spi.release();
return (res);
}
int
HCI::read(uint16_t &op, void* args, uint8_t len)
{
if (!m_available) return (0);
uint16_t payload;
bool padding;
int res = -EFAULT;
op = 0;
spi.acquire(this);
spi.begin();
if (spi.transfer(SPI_OP_READ) == SPI_OP_REPLY) {
res = -ENOMSG;
spi.transfer(0);
spi.transfer(0);
payload = spi.transfer(0);
payload = (payload << 8) | spi.transfer(0);
if (payload >= sizeof(HCI::cmnd_header_t)) {
cmnd_header_t header;
spi.read(&header, sizeof(header));
payload -= sizeof(header);
res = -EINVAL;
if (header.type == HCI_TYPE_EVNT || header.type == HCI_TYPE_DATA) {
op = header.cmnd;
if (header.len <= len) {
res = header.len;
padding = ((res & 1) == 0);
spi.read(args, res);
if (padding) spi.transfer(0);
}
}
}
}
if (res < 0) {
for (uint16_t i = 0; i < payload; i++) spi.transfer(0);
}
m_available = false;
spi.end();
spi.release();
return (res);
}
int
HCI::write(uint8_t type, uint16_t op, const void* args, uint8_t len, bool progmem)
{
bool padding = (len & 1) == 0;
int payload = sizeof(cmnd_header_t) + len + padding;
int res = -EFAULT;
spi.acquire(this);
spi.begin();
if (spi.transfer(SPI_OP_WRITE) == SPI_OP_REPLY) {
spi.transfer(payload >> 8);
spi.transfer(payload);
spi.transfer(0);
spi.transfer(0);
spi.transfer(type);
spi.transfer(op & 0xff);
spi.transfer(op >> 8);
spi.transfer(len);
if (progmem)
spi.write_P(args, len);
else
spi.write(args, len);
if (padding) spi.transfer(0);
res = len;
}
spi.end();
spi.release();
return (res);
}
int
HCI::await(uint16_t op, void* args, uint8_t len)
{
uint32_t start = RTC::millis();
uint16_t event;
int res;
while (1) {
do {
while (!m_available && (RTC::since(start) < m_timeout)) yield();
if (!m_available) return (-ETIME);
res = read(event, args, len);
} while (res == -ENOMSG);
if ((res < 0) || (op == event)) return (res);
INFO("await: op=%xd, event=%xd", op, event);
};
return (-ENOMSG);
}
int
HCI::listen(uint16_t &event, void* args, uint8_t len)
{
uint32_t start = RTC::millis();
int res;
do {
while (!m_available && (RTC::since(start) < m_timeout)) yield();
if (!m_available) return (-ETIME);
res = read(event, args, len);
} while (res == -ENOMSG);
return (res);
}
int
HCI::read_data(uint8_t op, void* args, uint8_t args_len,
void* data, uint16_t data_len)
{
if (!m_available) return (0);
uint16_t payload;
int res = -EFAULT;
spi.acquire(this);
spi.begin();
if (spi.transfer(SPI_OP_READ) == SPI_OP_REPLY) {
res = -ENOMSG;
spi.transfer(0);
spi.transfer(0);
payload = spi.transfer(0);
payload = (payload << 8) | spi.transfer(0);
if (payload >= sizeof(HCI::data_header_t)) {
data_header_t header;
spi.read(&header, sizeof(header));
payload -= sizeof(header);
res = -EINVAL;
if (header.type == HCI_TYPE_DATA) {
if (header.cmnd == op && header.args_len == args_len) {
res = header.payload_len - args_len;
if ((uint16_t) res <= data_len) {
if (args != NULL)
spi.read(args, args_len);
else
for (uint8_t i = 0; i < args_len; i++) spi.transfer(0);
spi.read(data, res);
if (header.payload_len & 1) spi.transfer(0);
}
}
}
}
}
if (res < 0) {
for (uint16_t i = 0; i < payload; i++) spi.transfer(0);
}
m_available = false;
spi.end();
spi.release();
return (res);
}
int
HCI::write_data(uint8_t op, const void* args, uint8_t args_len,
const void* data, uint16_t data_len, bool progmem)
{
int len = args_len + data_len;
int payload = sizeof(data_header_t) + len;
bool padding = (payload & 1) == 0;
if (padding) payload += 1;
int res = -EFAULT;
spi.acquire(this);
spi.begin();
if (spi.transfer(SPI_OP_WRITE) == SPI_OP_REPLY) {
spi.transfer(payload >> 8);
spi.transfer(payload);
spi.transfer(0);
spi.transfer(0);
spi.transfer(HCI_TYPE_DATA);
spi.transfer(op);
spi.transfer(args_len);
spi.transfer(len);
spi.transfer(len >> 8);
spi.write(args, args_len);
if (progmem)
spi.write_P(data, data_len);
else
spi.write(data, data_len);
if (padding) spi.transfer(0);
res = len;
}
spi.end();
spi.release();
return (res);
}
<commit_msg>Remove compiler warnings.<commit_after>/**
* @file Cosa/SPI/Driver/HCI.cpp
* @version 1.0
*
* @section License
* Copyright (C) 2015, Mikael Patel
*
* 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.
*
* This file is part of the Arduino Che Cosa project.
*/
#include "Cosa/SPI/Driver/HCI.hh"
#include "Cosa/RTC.hh"
#include "Cosa/Trace.hh"
int
HCI::read(void* msg, size_t len)
{
if (!m_available) return (0);
uint16_t payload;
int res = -EFAULT;
spi.acquire(this);
spi.begin();
if (spi.transfer(SPI_OP_READ) == SPI_OP_REPLY) {
spi.transfer(0);
spi.transfer(0);
payload = spi.transfer(0);
payload = (payload << 8) | spi.transfer(0);
if (payload <= len) {
res = payload;
spi.read(msg, res);
}
else {
for (uint16_t i = 0; i < payload; i++) spi.transfer(0);
res = -EINVAL;
}
}
m_available = false;
spi.end();
spi.release();
return (res);
}
int
HCI::read(uint16_t &op, void* args, uint8_t len)
{
if (!m_available) return (0);
uint16_t payload = 0;
bool padding;
int res = -EFAULT;
op = 0;
spi.acquire(this);
spi.begin();
if (spi.transfer(SPI_OP_READ) == SPI_OP_REPLY) {
res = -ENOMSG;
spi.transfer(0);
spi.transfer(0);
payload = spi.transfer(0);
payload = (payload << 8) | spi.transfer(0);
if (payload >= sizeof(HCI::cmnd_header_t)) {
cmnd_header_t header;
spi.read(&header, sizeof(header));
payload -= sizeof(header);
res = -EINVAL;
if (header.type == HCI_TYPE_EVNT || header.type == HCI_TYPE_DATA) {
op = header.cmnd;
if (header.len <= len) {
res = header.len;
padding = ((res & 1) == 0);
spi.read(args, res);
if (padding) spi.transfer(0);
}
}
}
}
if (res < 0) {
for (uint16_t i = 0; i < payload; i++) spi.transfer(0);
}
m_available = false;
spi.end();
spi.release();
return (res);
}
int
HCI::write(uint8_t type, uint16_t op, const void* args, uint8_t len, bool progmem)
{
bool padding = (len & 1) == 0;
int payload = sizeof(cmnd_header_t) + len + padding;
int res = -EFAULT;
spi.acquire(this);
spi.begin();
if (spi.transfer(SPI_OP_WRITE) == SPI_OP_REPLY) {
spi.transfer(payload >> 8);
spi.transfer(payload);
spi.transfer(0);
spi.transfer(0);
spi.transfer(type);
spi.transfer(op & 0xff);
spi.transfer(op >> 8);
spi.transfer(len);
if (progmem)
spi.write_P(args, len);
else
spi.write(args, len);
if (padding) spi.transfer(0);
res = len;
}
spi.end();
spi.release();
return (res);
}
int
HCI::await(uint16_t op, void* args, uint8_t len)
{
uint32_t start = RTC::millis();
uint16_t event;
int res;
while (1) {
do {
while (!m_available && (RTC::since(start) < m_timeout)) yield();
if (!m_available) return (-ETIME);
res = read(event, args, len);
} while (res == -ENOMSG);
if ((res < 0) || (op == event)) return (res);
INFO("await: op=%xd, event=%xd", op, event);
};
return (-ENOMSG);
}
int
HCI::listen(uint16_t &event, void* args, uint8_t len)
{
uint32_t start = RTC::millis();
int res;
do {
while (!m_available && (RTC::since(start) < m_timeout)) yield();
if (!m_available) return (-ETIME);
res = read(event, args, len);
} while (res == -ENOMSG);
return (res);
}
int
HCI::read_data(uint8_t op, void* args, uint8_t args_len,
void* data, uint16_t data_len)
{
if (!m_available) return (0);
uint16_t payload = 0;
int res = -EFAULT;
spi.acquire(this);
spi.begin();
if (spi.transfer(SPI_OP_READ) == SPI_OP_REPLY) {
res = -ENOMSG;
spi.transfer(0);
spi.transfer(0);
payload = spi.transfer(0);
payload = (payload << 8) | spi.transfer(0);
if (payload >= sizeof(HCI::data_header_t)) {
data_header_t header;
spi.read(&header, sizeof(header));
payload -= sizeof(header);
res = -EINVAL;
if (header.type == HCI_TYPE_DATA) {
if (header.cmnd == op && header.args_len == args_len) {
res = header.payload_len - args_len;
if ((uint16_t) res <= data_len) {
if (args != NULL)
spi.read(args, args_len);
else
for (uint8_t i = 0; i < args_len; i++) spi.transfer(0);
spi.read(data, res);
if (header.payload_len & 1) spi.transfer(0);
}
}
}
}
}
if (res < 0) {
for (uint16_t i = 0; i < payload; i++) spi.transfer(0);
}
m_available = false;
spi.end();
spi.release();
return (res);
}
int
HCI::write_data(uint8_t op, const void* args, uint8_t args_len,
const void* data, uint16_t data_len, bool progmem)
{
int len = args_len + data_len;
int payload = sizeof(data_header_t) + len;
bool padding = (payload & 1) == 0;
if (padding) payload += 1;
int res = -EFAULT;
spi.acquire(this);
spi.begin();
if (spi.transfer(SPI_OP_WRITE) == SPI_OP_REPLY) {
spi.transfer(payload >> 8);
spi.transfer(payload);
spi.transfer(0);
spi.transfer(0);
spi.transfer(HCI_TYPE_DATA);
spi.transfer(op);
spi.transfer(args_len);
spi.transfer(len);
spi.transfer(len >> 8);
spi.write(args, args_len);
if (progmem)
spi.write_P(data, data_len);
else
spi.write(data, data_len);
if (padding) spi.transfer(0);
res = len;
}
spi.end();
spi.release();
return (res);
}
<|endoftext|> |
<commit_before>/***************************************************************************
xloggertestcase.cpp
-------------------
begin : 2003/12/02
copyright : (C) 2003 by Michael CATANZARITI
email : mcatan@free.fr
***************************************************************************/
/***************************************************************************
* Copyright (C) The Apache Software Foundation. All rights reserved. *
* *
* This software is published under the terms of the Apache Software *
* License version 1.1, a copy of which has been included with this *
* distribution in the license.apl file. *
***************************************************************************/
#include <cppunit/TestFixture.h>
#include <cppunit/extensions/HelperMacros.h>
#include "xlogger.h"
#include <log4cxx/xml/domconfigurator.h>
#include "../util/transformer.h"
#include "../util/compare.h"
using namespace log4cxx;
using namespace log4cxx::helpers;
using namespace log4cxx::xml;
#define FILTERED "output/filtered"
/**
Tests handling of custom loggers.
*/
class XLoggerTestCase : public CppUnit::TestFixture
{
CPPUNIT_TEST_SUITE(XLoggerTestCase);
CPPUNIT_TEST(test1);
CPPUNIT_TEST(test2);
CPPUNIT_TEST_SUITE_END();
XLoggerPtr logger;
public:
void setUp()
{
logger =
(XLoggerPtr) XLogger::getLogger(
_T("org.apache.log4j.customLogger.XLoggerTestCase"));
}
void tearDown()
{
logger->getLoggerRepository()->resetConfiguration();
}
void test1() { common(_T("1")); }
void test2() { common(_T("2")); }
void common(const String& number)
{
DOMConfigurator::configure(_T("input/xml/customLogger")
+number+_T(".xml"));
int i = -1;
LOG4CXX_TRACE(logger, _T("Message ") << ++i);
LOG4CXX_DEBUG(logger, _T("Message ") << ++i);
LOG4CXX_WARN(logger, _T("Message ") << ++i);
LOG4CXX_ERROR(logger, _T("Message ") << ++i);
LOG4CXX_FATAL(logger, _T("Message ") << ++i);
LOG4CXX_DEBUG(logger, _T("Message ") << ++i);
CPPUNIT_ASSERT(Compare::compare(_T("output/temp"),
_T("witness/customLogger.")+number));
}
};
CPPUNIT_TEST_SUITE_REGISTRATION(XLoggerTestCase);
<commit_msg>*** empty log message ***<commit_after>/***************************************************************************
xloggertestcase.cpp
-------------------
begin : 2003/12/02
copyright : (C) 2003 by Michael CATANZARITI
email : mcatan@free.fr
***************************************************************************/
/***************************************************************************
* Copyright (C) The Apache Software Foundation. All rights reserved. *
* *
* This software is published under the terms of the Apache Software *
* License version 1.1, a copy of which has been included with this *
* distribution in the license.apl file. *
***************************************************************************/
#include <cppunit/TestFixture.h>
#include <cppunit/extensions/HelperMacros.h>
#include "xlogger.h"
#include <log4cxx/xml/domconfigurator.h>
#include "../util/transformer.h"
#include "../util/compare.h"
using namespace log4cxx;
using namespace log4cxx::helpers;
using namespace log4cxx::xml;
/**
Tests handling of custom loggers.
*/
class XLoggerTestCase : public CppUnit::TestFixture
{
CPPUNIT_TEST_SUITE(XLoggerTestCase);
CPPUNIT_TEST(test1);
CPPUNIT_TEST(test2);
CPPUNIT_TEST_SUITE_END();
XLoggerPtr logger;
public:
void setUp()
{
logger =
(XLoggerPtr) XLogger::getLogger(
_T("org.apache.log4j.customLogger.XLoggerTestCase"));
}
void tearDown()
{
logger->getLoggerRepository()->resetConfiguration();
}
void test1() { common(_T("1")); }
void test2() { common(_T("2")); }
void common(const String& number)
{
DOMConfigurator::configure(_T("input/xml/customLogger")
+number+_T(".xml"));
int i = -1;
LOG4CXX_TRACE(logger, _T("Message ") << ++i);
LOG4CXX_DEBUG(logger, _T("Message ") << ++i);
LOG4CXX_WARN(logger, _T("Message ") << ++i);
LOG4CXX_ERROR(logger, _T("Message ") << ++i);
LOG4CXX_FATAL(logger, _T("Message ") << ++i);
LOG4CXX_DEBUG(logger, _T("Message ") << ++i);
CPPUNIT_ASSERT(Compare::compare(_T("output/temp"),
_T("witness/customLogger.")+number));
}
};
CPPUNIT_TEST_SUITE_REGISTRATION(XLoggerTestCase);
<|endoftext|> |
<commit_before>/**
* @author: Jeff Thompson
* See COPYING for copyright and distribution information.
*/
#include <cstdlib>
#include <sstream>
#include <iostream>
#include <boost/date_time/posix_time/posix_time_types.hpp>
#include <boost/date_time/posix_time/time_serialize.hpp>
#include <boost/date_time/gregorian/gregorian.hpp>
#include <ndn-cpp/ContentObject.hpp>
using namespace std;
using namespace ndn;
using namespace boost::posix_time;
using namespace boost::gregorian;
unsigned char ContentObject1[] = {
0x04, 0x82, // ContentObject
0x02, 0xaa, // Signature
0x03, 0xb2, // SignatureBits
0x08, 0x85, 0x20, 0xea, 0xb5, 0xb0, 0x63, 0xda, 0x94, 0xe9, 0x68, 0x7a,
0x8e, 0x65, 0x60, 0xe0, 0xc6, 0x43, 0x96, 0xd9, 0x69, 0xb4, 0x40, 0x72, 0x52, 0x00, 0x2c, 0x8e, 0x2a, 0xf5,
0x47, 0x12, 0x59, 0x93, 0xda, 0xed, 0x82, 0xd0, 0xf8, 0xe6, 0x65, 0x09, 0x87, 0x84, 0x54, 0xc7, 0xce, 0x9a,
0x93, 0x0d, 0x47, 0xf1, 0xf9, 0x3b, 0x98, 0x78, 0x2c, 0x22, 0x21, 0xd9, 0x2b, 0xda, 0x03, 0x30, 0x84, 0xf3,
0xc5, 0x52, 0x64, 0x2b, 0x1d, 0xde, 0x50, 0xe0, 0xee, 0xca, 0xa2, 0x73, 0x7a, 0x93, 0x30, 0xa8, 0x47, 0x7f,
0x6f, 0x41, 0xb0, 0xc8, 0x6e, 0x89, 0x1c, 0xcc, 0xf9, 0x01, 0x44, 0xc3, 0x08, 0xcf, 0x77, 0x47, 0xfc, 0xed,
0x48, 0xf0, 0x4c, 0xe9, 0xc2, 0x3b, 0x7d, 0xef, 0x6e, 0xa4, 0x80, 0x40, 0x9e, 0x43, 0xb6, 0x77, 0x7a, 0x1d,
0x51, 0xed, 0x98, 0x33, 0x93, 0xdd, 0x88, 0x01, 0x0e, 0xd3,
0x00,
0x00,
0xf2, 0xfa, 0x9d, 0x6e, 0x64, 0x6e, 0x00, 0xfa, 0x9d, 0x61, 0x62, 0x63, 0x00, 0x00, // Name
0x01, 0xa2, // SignedInfo
0x03, 0xe2, // PublisherPublicKeyDigest
0x02, 0x85, 0xb5, 0x50, 0x6b, 0x1a,
0xba, 0x3d, 0xa7, 0x76, 0x1b, 0x0f, 0x8d, 0x61, 0xa4, 0xaa, 0x7e, 0x3b, 0x6d, 0x15, 0xb4, 0x26, 0xfe, 0xb5,
0xbd, 0xa8, 0x23, 0x89, 0xac, 0xa7, 0x65, 0xa3, 0xb8, 0x1c,
0x00,
0x02, 0xba, // Timestamp
0xb5, 0x05, 0x1d, 0xde, 0xe9, 0x5b, 0xdb,
0x00,
0x01, 0xe2, // KeyLocator
0x01, 0xda, // Key
0x0a, 0x95, 0x30, 0x81, 0x9f, 0x30, 0x0d, 0x06, 0x09, 0x2a, 0x86,
0x48, 0x86, 0xf7, 0x0d, 0x01, 0x01, 0x01, 0x05, 0x00, 0x03, 0x81, 0x8d, 0x00, 0x30, 0x81, 0x89, 0x02, 0x81,
0x81, 0x00, 0xe1, 0x7d, 0x30, 0xa7, 0xd8, 0x28, 0xab, 0x1b, 0x84, 0x0b, 0x17, 0x54, 0x2d, 0xca, 0xf6, 0x20,
0x7a, 0xfd, 0x22, 0x1e, 0x08, 0x6b, 0x2a, 0x60, 0xd1, 0x6c, 0xb7, 0xf5, 0x44, 0x48, 0xba, 0x9f, 0x3f, 0x08,
0xbc, 0xd0, 0x99, 0xdb, 0x21, 0xdd, 0x16, 0x2a, 0x77, 0x9e, 0x61, 0xaa, 0x89, 0xee, 0xe5, 0x54, 0xd3, 0xa4,
0x7d, 0xe2, 0x30, 0xbc, 0x7a, 0xc5, 0x90, 0xd5, 0x24, 0x06, 0x7c, 0x38, 0x98, 0xbb, 0xa6, 0xf5, 0xdc, 0x43,
0x60, 0xb8, 0x45, 0xed, 0xa4, 0x8c, 0xbd, 0x9c, 0xf1, 0x26, 0xa7, 0x23, 0x44, 0x5f, 0x0e, 0x19, 0x52, 0xd7,
0x32, 0x5a, 0x75, 0xfa, 0xf5, 0x56, 0x14, 0x4f, 0x9a, 0x98, 0xaf, 0x71, 0x86, 0xb0, 0x27, 0x86, 0x85, 0xb8,
0xe2, 0xc0, 0x8b, 0xea, 0x87, 0x17, 0x1b, 0x4d, 0xee, 0x58, 0x5c, 0x18, 0x28, 0x29, 0x5b, 0x53, 0x95, 0xeb,
0x4a, 0x17, 0x77, 0x9f, 0x02, 0x03, 0x01, 0x00, 0x01,
0x00,
0x00,
0x00,
0x01, 0x9a, // Content
0xc5, 0x53, 0x55, 0x43, 0x43, 0x45, 0x53, 0x53, 0x21,
0x00,
0x00,
1
};
const ptime UNIX_EPOCH_TIME = ptime (date (1970, Jan, 1));
int main(int argc, char** argv)
{
try {
ContentObject contentObject;
contentObject.decode(ContentObject1, sizeof(ContentObject1));
cout << "ContentObject name " << contentObject.getName().to_uri() << endl;
ptime timestamp = UNIX_EPOCH_TIME + milliseconds(contentObject.getSignedInfo().getTimestampMilliseconds());
cout << "ContentObject timestamp " << timestamp.date().year() << "/" << timestamp.date().month() << "/" << timestamp.date().day()
<< " " << timestamp.time_of_day().hours() << ":" << timestamp.time_of_day().minutes() << ":" << timestamp.time_of_day().seconds() << endl;
ptr_lib::shared_ptr<vector<unsigned char> > encoding = contentObject.encode();
cout << "ContentObject encoding length " << encoding->size() << " vs. sizeof(ContentObject1) " << sizeof(ContentObject1) << endl;
ContentObject reDecodedContentObject;
reDecodedContentObject.decode(*encoding);
cout << "Re-decoded ContentObject name " << reDecodedContentObject.getName().to_uri() << endl;
timestamp = UNIX_EPOCH_TIME + milliseconds(reDecodedContentObject.getSignedInfo().getTimestampMilliseconds());
cout << "Re-decoded ContentObject timestamp " << timestamp.date().year() << "/" << timestamp.date().month() << "/" << timestamp.date().day() << endl;
} catch (exception &e) {
cout << "exception: " << e.what() << endl;
}
return 0;
}
<commit_msg>Comment out boost time functions for now.<commit_after>/**
* @author: Jeff Thompson
* See COPYING for copyright and distribution information.
*/
#include <cstdlib>
#include <sstream>
#include <iostream>
#if 0
#include <boost/date_time/posix_time/posix_time_types.hpp>
#include <boost/date_time/posix_time/time_serialize.hpp>
#include <boost/date_time/gregorian/gregorian.hpp>
#endif
#include <ndn-cpp/ContentObject.hpp>
using namespace std;
using namespace ndn;
#if 0
using namespace boost::posix_time;
using namespace boost::gregorian;
#endif
unsigned char ContentObject1[] = {
0x04, 0x82, // ContentObject
0x02, 0xaa, // Signature
0x03, 0xb2, // SignatureBits
0x08, 0x85, 0x20, 0xea, 0xb5, 0xb0, 0x63, 0xda, 0x94, 0xe9, 0x68, 0x7a,
0x8e, 0x65, 0x60, 0xe0, 0xc6, 0x43, 0x96, 0xd9, 0x69, 0xb4, 0x40, 0x72, 0x52, 0x00, 0x2c, 0x8e, 0x2a, 0xf5,
0x47, 0x12, 0x59, 0x93, 0xda, 0xed, 0x82, 0xd0, 0xf8, 0xe6, 0x65, 0x09, 0x87, 0x84, 0x54, 0xc7, 0xce, 0x9a,
0x93, 0x0d, 0x47, 0xf1, 0xf9, 0x3b, 0x98, 0x78, 0x2c, 0x22, 0x21, 0xd9, 0x2b, 0xda, 0x03, 0x30, 0x84, 0xf3,
0xc5, 0x52, 0x64, 0x2b, 0x1d, 0xde, 0x50, 0xe0, 0xee, 0xca, 0xa2, 0x73, 0x7a, 0x93, 0x30, 0xa8, 0x47, 0x7f,
0x6f, 0x41, 0xb0, 0xc8, 0x6e, 0x89, 0x1c, 0xcc, 0xf9, 0x01, 0x44, 0xc3, 0x08, 0xcf, 0x77, 0x47, 0xfc, 0xed,
0x48, 0xf0, 0x4c, 0xe9, 0xc2, 0x3b, 0x7d, 0xef, 0x6e, 0xa4, 0x80, 0x40, 0x9e, 0x43, 0xb6, 0x77, 0x7a, 0x1d,
0x51, 0xed, 0x98, 0x33, 0x93, 0xdd, 0x88, 0x01, 0x0e, 0xd3,
0x00,
0x00,
0xf2, 0xfa, 0x9d, 0x6e, 0x64, 0x6e, 0x00, 0xfa, 0x9d, 0x61, 0x62, 0x63, 0x00, 0x00, // Name
0x01, 0xa2, // SignedInfo
0x03, 0xe2, // PublisherPublicKeyDigest
0x02, 0x85, 0xb5, 0x50, 0x6b, 0x1a,
0xba, 0x3d, 0xa7, 0x76, 0x1b, 0x0f, 0x8d, 0x61, 0xa4, 0xaa, 0x7e, 0x3b, 0x6d, 0x15, 0xb4, 0x26, 0xfe, 0xb5,
0xbd, 0xa8, 0x23, 0x89, 0xac, 0xa7, 0x65, 0xa3, 0xb8, 0x1c,
0x00,
0x02, 0xba, // Timestamp
0xb5, 0x05, 0x1d, 0xde, 0xe9, 0x5b, 0xdb,
0x00,
0x01, 0xe2, // KeyLocator
0x01, 0xda, // Key
0x0a, 0x95, 0x30, 0x81, 0x9f, 0x30, 0x0d, 0x06, 0x09, 0x2a, 0x86,
0x48, 0x86, 0xf7, 0x0d, 0x01, 0x01, 0x01, 0x05, 0x00, 0x03, 0x81, 0x8d, 0x00, 0x30, 0x81, 0x89, 0x02, 0x81,
0x81, 0x00, 0xe1, 0x7d, 0x30, 0xa7, 0xd8, 0x28, 0xab, 0x1b, 0x84, 0x0b, 0x17, 0x54, 0x2d, 0xca, 0xf6, 0x20,
0x7a, 0xfd, 0x22, 0x1e, 0x08, 0x6b, 0x2a, 0x60, 0xd1, 0x6c, 0xb7, 0xf5, 0x44, 0x48, 0xba, 0x9f, 0x3f, 0x08,
0xbc, 0xd0, 0x99, 0xdb, 0x21, 0xdd, 0x16, 0x2a, 0x77, 0x9e, 0x61, 0xaa, 0x89, 0xee, 0xe5, 0x54, 0xd3, 0xa4,
0x7d, 0xe2, 0x30, 0xbc, 0x7a, 0xc5, 0x90, 0xd5, 0x24, 0x06, 0x7c, 0x38, 0x98, 0xbb, 0xa6, 0xf5, 0xdc, 0x43,
0x60, 0xb8, 0x45, 0xed, 0xa4, 0x8c, 0xbd, 0x9c, 0xf1, 0x26, 0xa7, 0x23, 0x44, 0x5f, 0x0e, 0x19, 0x52, 0xd7,
0x32, 0x5a, 0x75, 0xfa, 0xf5, 0x56, 0x14, 0x4f, 0x9a, 0x98, 0xaf, 0x71, 0x86, 0xb0, 0x27, 0x86, 0x85, 0xb8,
0xe2, 0xc0, 0x8b, 0xea, 0x87, 0x17, 0x1b, 0x4d, 0xee, 0x58, 0x5c, 0x18, 0x28, 0x29, 0x5b, 0x53, 0x95, 0xeb,
0x4a, 0x17, 0x77, 0x9f, 0x02, 0x03, 0x01, 0x00, 0x01,
0x00,
0x00,
0x00,
0x01, 0x9a, // Content
0xc5, 0x53, 0x55, 0x43, 0x43, 0x45, 0x53, 0x53, 0x21,
0x00,
0x00,
1
};
#if 0
const ptime UNIX_EPOCH_TIME = ptime (date (1970, Jan, 1));
#endif
int main(int argc, char** argv)
{
try {
ContentObject contentObject;
contentObject.decode(ContentObject1, sizeof(ContentObject1));
cout << "ContentObject name " << contentObject.getName().to_uri() << endl;
#if 0
ptime timestamp = UNIX_EPOCH_TIME + milliseconds(contentObject.getSignedInfo().getTimestampMilliseconds());
cout << "ContentObject timestamp " << timestamp.date().year() << "/" << timestamp.date().month() << "/" << timestamp.date().day()
<< " " << timestamp.time_of_day().hours() << ":" << timestamp.time_of_day().minutes() << ":" << timestamp.time_of_day().seconds() << endl;
#endif
ptr_lib::shared_ptr<vector<unsigned char> > encoding = contentObject.encode();
cout << "ContentObject encoding length " << encoding->size() << " vs. sizeof(ContentObject1) " << sizeof(ContentObject1) << endl;
ContentObject reDecodedContentObject;
reDecodedContentObject.decode(*encoding);
cout << "Re-decoded ContentObject name " << reDecodedContentObject.getName().to_uri() << endl;
#if 0
timestamp = UNIX_EPOCH_TIME + milliseconds(reDecodedContentObject.getSignedInfo().getTimestampMilliseconds());
cout << "Re-decoded ContentObject timestamp " << timestamp.date().year() << "/" << timestamp.date().month() << "/" << timestamp.date().day() << endl;
#endif
} catch (exception &e) {
cout << "exception: " << e.what() << endl;
}
return 0;
}
<|endoftext|> |
<commit_before>// Copyright 2020 DeepMind Technologies 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 "pybind_utils.h" // controller
#include <dlfcn.h>
#include <string>
#include "dm_robotics/support/logging.h"
#include "absl/strings/substitute.h"
#include "dm_robotics/mujoco/mjlib.h"
#include "pybind11/pybind11.h" // pybind
namespace dm_robotics::internal {
namespace {
namespace py = pybind11;
constexpr char kDmControlMjModelClassName[] = "MjModel";
constexpr char kDmControlMjDataClassName[] = "MjData";
// Returns a ctypes module for use through pybind.
py::module GetCtypesModule() {
static PyObject* const ctypes_module_ptr = []() -> PyObject* {
py::module ctypes_module = py::module::import("ctypes");
PyObject* ctypes_module_ptr = ctypes_module.ptr();
Py_XINCREF(ctypes_module_ptr);
return ctypes_module_ptr;
}();
return py::reinterpret_borrow<py::module>(ctypes_module_ptr);
}
// Returns a pointer to the underlying object pointed to by `ctypes_obj`.
// Note that does not increment the reference count.
template <class T>
T* GetPointer(py::handle mjwrapper_object) {
#ifdef DM_ROBOTICS_USE_NEW_MUJOCO_BINDINGS
return reinterpret_cast<T*>(
mjwrapper_object.attr("_address").cast<std::uintptr_t>());
#else
auto ctypes_module = GetCtypesModule();
return reinterpret_cast<T*>(
ctypes_module.attr("addressof")(mjwrapper_object.attr("contents"))
.cast<std::uintptr_t>());
#endif
}
// Returns a pointer to a MuJoCo mjModel or mjData from the dm_control wrappers
// around these objects. The dm_control wrappers are such that the `ptr`
// attributes return a ctypes object bound to underlying MuJoCo native type.
//
// Raises a `RuntimeError` exception in Python if the handle does not contain a
// `ptr` attribute.
template <class T>
T* GetMujocoPointerFromDmControlWrapperHandle(py::handle dm_control_wrapper) {
if (!py::hasattr(dm_control_wrapper, "ptr")) {
RaiseRuntimeErrorWithMessage(
"GetMujocoPointerFromDmControlWrapperHandle: handle does not have a "
"`ptr` attribute. This function assumes that dm_control wrappers "
"around mjModel and mjData contain a `ptr` attribute with the MuJoCo "
"native type.");
}
return GetPointer<T>(dm_control_wrapper.attr("ptr"));
}
} // namespace
void RaiseRuntimeErrorWithMessage(absl::string_view message) {
PyErr_SetString(PyExc_RuntimeError, std::string(message).c_str());
throw py::error_already_set();
}
const MjLib* LoadMjLibFromDmControl() {
py::gil_scoped_acquire gil;
// Get the path to the DSO.
const py::module mjbindings(
py::module::import("dm_control.mujoco.wrapper.mjbindings"));
const std::string dso_path =
mjbindings.attr("mjlib").attr("_name").cast<std::string>();
// Create the MjLib object by dlopen'ing the DSO.
return new MjLib(dso_path, RTLD_NOW);
}
// Helper function for getting an mjModel object from a py::handle.
const mjModel* GetmjModelOrRaise(py::handle obj) {
const std::string class_name =
obj.attr("__class__").attr("__name__").cast<std::string>();
if (class_name != kDmControlMjModelClassName) {
RaiseRuntimeErrorWithMessage(absl::Substitute(
"GetmjModelOrRaise: the class name of the argument [$0] does not match "
"the expected dm_control type name for mjModel [$1].",
class_name, kDmControlMjModelClassName));
}
return GetMujocoPointerFromDmControlWrapperHandle<mjModel>(obj);
}
// Helper function for getting an mjData object from a py::handle.
const mjData* GetmjDataOrRaise(py::handle obj) {
const std::string class_name =
obj.attr("__class__").attr("__name__").cast<std::string>();
if (class_name != kDmControlMjDataClassName) {
RaiseRuntimeErrorWithMessage(absl::Substitute(
"GetmjDataOrRaise: the class name of the argument [$0] does not match "
"the expected dm_control type name for mjData [$1].",
class_name, kDmControlMjDataClassName));
}
return GetMujocoPointerFromDmControlWrapperHandle<mjData>(obj);
}
} // namespace dm_robotics::internal
<commit_msg>Fix how we locate mujoco.so.<commit_after>// Copyright 2020 DeepMind Technologies 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 "pybind_utils.h" // controller
#include <dlfcn.h>
#include <errno.h>
#include <string.h>
#include <sys/stat.h>
#include <string>
#include "dm_robotics/support/logging.h"
#include "absl/strings/substitute.h"
#include "dm_robotics/mujoco/mjlib.h"
#include "pybind11/pybind11.h" // pybind
namespace dm_robotics::internal {
namespace {
namespace py = pybind11;
constexpr char kDmControlMjModelClassName[] = "MjModel";
constexpr char kDmControlMjDataClassName[] = "MjData";
// Returns a ctypes module for use through pybind.
py::module GetCtypesModule() {
static PyObject* const ctypes_module_ptr = []() -> PyObject* {
py::module ctypes_module = py::module::import("ctypes");
PyObject* ctypes_module_ptr = ctypes_module.ptr();
Py_XINCREF(ctypes_module_ptr);
return ctypes_module_ptr;
}();
return py::reinterpret_borrow<py::module>(ctypes_module_ptr);
}
// Returns a pointer to the underlying object pointed to by `ctypes_obj`.
// Note that does not increment the reference count.
template <class T>
T* GetPointer(py::handle mjwrapper_object) {
#ifdef DM_ROBOTICS_USE_NEW_MUJOCO_BINDINGS
return reinterpret_cast<T*>(
mjwrapper_object.attr("_address").cast<std::uintptr_t>());
#else
auto ctypes_module = GetCtypesModule();
return reinterpret_cast<T*>(
ctypes_module.attr("addressof")(mjwrapper_object.attr("contents"))
.cast<std::uintptr_t>());
#endif
}
// Returns a pointer to a MuJoCo mjModel or mjData from the dm_control wrappers
// around these objects. The dm_control wrappers are such that the `ptr`
// attributes return a ctypes object bound to underlying MuJoCo native type.
//
// Raises a `RuntimeError` exception in Python if the handle does not contain a
// `ptr` attribute.
template <class T>
T* GetMujocoPointerFromDmControlWrapperHandle(py::handle dm_control_wrapper) {
if (!py::hasattr(dm_control_wrapper, "ptr")) {
RaiseRuntimeErrorWithMessage(
"GetMujocoPointerFromDmControlWrapperHandle: handle does not have a "
"`ptr` attribute. This function assumes that dm_control wrappers "
"around mjModel and mjData contain a `ptr` attribute with the MuJoCo "
"native type.");
}
return GetPointer<T>(dm_control_wrapper.attr("ptr"));
}
} // namespace
void RaiseRuntimeErrorWithMessage(absl::string_view message) {
PyErr_SetString(PyExc_RuntimeError, std::string(message).c_str());
throw py::error_already_set();
}
const MjLib* LoadMjLibFromDmControl() {
py::gil_scoped_acquire gil;
// Get the path to the mujoco library.
const py::module mujoco(py::module::import("mujoco"));
const auto path = mujoco.attr("__path__").cast<std::vector<std::string>>();
const std::string version = mujoco.attr("__version__").cast<std::string>();
if (path.empty()) {
RaiseRuntimeErrorWithMessage("mujoco.__path__ is empty");
return nullptr;
}
const std::string dso_path = path[0] + "/libmujoco.so." + version;
struct stat buffer;
if (stat(dso_path.c_str(), &buffer) != 0) {
RaiseRuntimeErrorWithMessage(absl::Substitute(
"LoadMjLibFromDmComtrol: Cannot access mujoco library file "
"$0, error: $1",
dso_path, strerror(errno)));
return nullptr;
}
py::print("Loading mujoco from " + dso_path);
// Create the MjLib object by dlopen'ing the DSO.
return new MjLib(dso_path, RTLD_NOW);
}
// Helper function for getting an mjModel object from a py::handle.
const mjModel* GetmjModelOrRaise(py::handle obj) {
const std::string class_name =
obj.attr("__class__").attr("__name__").cast<std::string>();
if (class_name != kDmControlMjModelClassName) {
RaiseRuntimeErrorWithMessage(absl::Substitute(
"GetmjModelOrRaise: the class name of the argument [$0] does not match "
"the expected dm_control type name for mjModel [$1].",
class_name, kDmControlMjModelClassName));
}
return GetMujocoPointerFromDmControlWrapperHandle<mjModel>(obj);
}
// Helper function for getting an mjData object from a py::handle.
const mjData* GetmjDataOrRaise(py::handle obj) {
const std::string class_name =
obj.attr("__class__").attr("__name__").cast<std::string>();
if (class_name != kDmControlMjDataClassName) {
RaiseRuntimeErrorWithMessage(absl::Substitute(
"GetmjDataOrRaise: the class name of the argument [$0] does not match "
"the expected dm_control type name for mjData [$1].",
class_name, kDmControlMjDataClassName));
}
return GetMujocoPointerFromDmControlWrapperHandle<mjData>(obj);
}
} // namespace dm_robotics::internal
<|endoftext|> |
<commit_before>#include "../src/http/server/server_connection.h"
#include "../src/protocol/handler_http1.h"
#include "../src/http/server/server_traits.h"
#include "mocks/mock_connector.h"
#include <gtest/gtest.h>
#include <gmock/gmock.h>
using namespace http;
TEST(server_connection, invalid_request) {
boost::asio::io_service io;
MockConnector::wcb cb = [](dstring chunk){};
auto handler_test = std::make_shared<server::handler_http1<http::server_traits>>(http::proto_version::HTTP11);
auto connector = std::make_shared<MockConnector>(io, cb);
connector->handler(handler_test);
bool called{false};
handler_test->on_request([&called](auto conn, auto req, auto resp) {
req->on_error([&called](auto conn, auto &error){
ASSERT_TRUE(conn);
ASSERT_EQ(error.errc(), http::error_code::decoding);
called = true;
});
});
connector->io_service().post([connector](){ connector->read("GET /prova HTTP_WRONG!!!/1.1"); });
connector->io_service().run();
ASSERT_TRUE(called);
}
TEST(server_connection, valid_request) {
boost::asio::io_service io;
MockConnector::wcb cb = [](dstring chunk){};
auto handler_test = std::make_shared<server::handler_http1<http::server_traits>>(http::proto_version::HTTP11);
auto connector = std::make_shared<MockConnector>(io, cb);
connector->handler(handler_test);
size_t expected_cb_counter{2};
size_t cb_counter{0};
handler_test->on_request([&cb_counter](auto conn, auto req, auto resp) {
req->on_headers([&cb_counter](auto req){
++cb_counter;
});
req->on_finished([&cb_counter](auto req){
++cb_counter;
});
});
connector->io_service().post([connector](){ connector->read("GET / HTTP/1.1\r\n"
"host:localhost:1443\r\n"
"date: Tue, 17 May 2016 14:53:09 GMT\r\n"
"\r\n"); });
connector->io_service().run();
ASSERT_EQ(cb_counter, expected_cb_counter);
}
TEST(server_connection, on_connector_nulled) {
boost::asio::io_service io;
MockConnector::wcb cb = [](dstring chunk){};
auto handler_test = std::make_shared<server::handler_http1<http::server_traits>>(http::proto_version::HTTP11);
auto connector = std::make_shared<MockConnector>(io, cb);
connector->handler(handler_test);
size_t expected_req_cb_counter{2};
size_t expected_error_cb_counter{1};
size_t req_cb_counter{0};
size_t error_cb_counter{0};
handler_test->on_request([&req_cb_counter, &connector, &error_cb_counter](auto conn, auto req, auto resp) {
req->on_headers([&req_cb_counter](auto req){
++req_cb_counter;
});
req->on_finished([&req_cb_counter, &conn, &connector, resp](auto req){
++req_cb_counter;
connector = nullptr;
resp->headers(http::http_response{});
});
conn->on_error([&error_cb_counter](auto conn, const http::connection_error &error){
ASSERT_TRUE(conn);
ASSERT_EQ(error.errc(), http::error_code::closed_by_client);
std::cout << "conn on error" << std::endl;
++error_cb_counter;
});
});
connector->io_service().post([connector](){
connector->read("GET / HTTP/1.1\r\n"
"host:localhost:1443\r\n"
"date: Tue, 17 May 2016 14:53:09 GMT\r\n"
"\r\n");
});
connector->io_service().run();
ASSERT_EQ(req_cb_counter, expected_req_cb_counter);
ASSERT_EQ(error_cb_counter, expected_error_cb_counter);
}
<commit_msg>added test for send_continue<commit_after>#include "../src/http/server/server_connection.h"
#include "../src/protocol/handler_http1.h"
#include "../src/http/server/server_traits.h"
#include "mocks/mock_connector.h"
#include <gtest/gtest.h>
#include <gmock/gmock.h>
using namespace http;
TEST(server_connection, invalid_request) {
boost::asio::io_service io;
MockConnector::wcb cb = [](dstring chunk){};
auto handler_test = std::make_shared<server::handler_http1<http::server_traits>>(http::proto_version::HTTP11);
auto connector = std::make_shared<MockConnector>(io, cb);
connector->handler(handler_test);
bool called{false};
handler_test->on_request([&called](auto conn, auto req, auto resp) {
req->on_error([&called](auto conn, auto &error){
ASSERT_TRUE(conn);
ASSERT_EQ(error.errc(), http::error_code::decoding);
called = true;
});
});
connector->io_service().post([connector](){ connector->read("GET /prova HTTP_WRONG!!!/1.1"); });
connector->io_service().run();
ASSERT_TRUE(called);
}
TEST(server_connection, valid_request) {
boost::asio::io_service io;
MockConnector::wcb cb = [](dstring chunk){};
auto handler_test = std::make_shared<server::handler_http1<http::server_traits>>(http::proto_version::HTTP11);
auto connector = std::make_shared<MockConnector>(io, cb);
connector->handler(handler_test);
size_t expected_cb_counter{2};
size_t cb_counter{0};
handler_test->on_request([&cb_counter](auto conn, auto req, auto resp) {
req->on_headers([&cb_counter](auto req){
++cb_counter;
});
req->on_finished([&cb_counter](auto req){
++cb_counter;
});
});
connector->io_service().post([connector](){ connector->read("GET / HTTP/1.1\r\n"
"host:localhost:1443\r\n"
"date: Tue, 17 May 2016 14:53:09 GMT\r\n"
"\r\n"); });
connector->io_service().run();
ASSERT_EQ(cb_counter, expected_cb_counter);
}
TEST(server_connection, on_connector_nulled) {
boost::asio::io_service io;
MockConnector::wcb cb = [](dstring chunk){};
auto handler_test = std::make_shared<server::handler_http1<http::server_traits>>(http::proto_version::HTTP11);
auto connector = std::make_shared<MockConnector>(io, cb);
connector->handler(handler_test);
size_t expected_req_cb_counter{2};
size_t expected_error_cb_counter{1};
size_t req_cb_counter{0};
size_t error_cb_counter{0};
handler_test->on_request([&req_cb_counter, &connector, &error_cb_counter](auto conn, auto req, auto resp) {
req->on_headers([&req_cb_counter](auto req){
++req_cb_counter;
});
req->on_finished([&req_cb_counter, &conn, &connector, resp](auto req){
++req_cb_counter;
connector = nullptr;
resp->headers(http::http_response{});
});
conn->on_error([&error_cb_counter](auto conn, const http::connection_error &error){
ASSERT_TRUE(conn);
ASSERT_EQ(error.errc(), http::error_code::closed_by_client);
std::cout << "conn on error" << std::endl;
++error_cb_counter;
});
});
connector->io_service().post([connector](){
connector->read("GET / HTTP/1.1\r\n"
"host:localhost:1443\r\n"
"date: Tue, 17 May 2016 14:53:09 GMT\r\n"
"\r\n");
});
connector->io_service().run();
ASSERT_EQ(req_cb_counter, expected_req_cb_counter);
ASSERT_EQ(error_cb_counter, expected_error_cb_counter);
}
TEST(server_connection, response_continue) {
boost::asio::io_service io;
std::string accumulator{};
bool rcvd{false};
MockConnector::wcb cb = [&accumulator, &rcvd](dstring chunk){
accumulator += std::string(chunk);
if(accumulator == "HTTP/1.1 100 Continue\r\ncontent-length: 0\r\n\r\n") {
rcvd = true;
}
};
auto handler_test = std::make_shared<server::handler_http1<http::server_traits>>(http::proto_version::HTTP11);
auto connector = std::make_shared<MockConnector>(io, cb);
connector->handler(handler_test);
handler_test->on_request([](auto conn, auto req, auto resp) {
req->on_headers([resp](auto req){
resp->send_continue();
});
});
connector->io_service().post([connector](){ connector->read("GET / HTTP/1.1\r\n"
"host:localhost:1443\r\n"
"date: Tue, 17 May 2016 14:53:09 GMT\r\n"
"\r\n"); });
connector->io_service().run();
ASSERT_TRUE(rcvd);
}
<|endoftext|> |
<commit_before>#include "../../view/editorViewScene.h"
#include <QtCore/qmath.h>
#include "../nodeElement.h"
#include "portHandler.h"
qreal const PortHandler::mMaximumFractionPartValue = 0.9999;
PortHandler::PortHandler(NodeElement *node, qReal::models::GraphicalModelAssistApi *graphicalAssistApi,
QList<StatPoint> const &pointPorts, QList<StatLine> const &linePorts)
: mNode(node), mGraphicalAssistApi(graphicalAssistApi)
, mPointPorts(pointPorts), mLinePorts(linePorts)
{
}
qreal PortHandler::minDistanceFromLinePort(int linePortNumber, QPointF const &location) const
{
QLineF const linePort = transformPortForNodeSize(mLinePorts[linePortNumber]);
// Triangle side values.
qreal const a = linePort.length();
qreal const b = QLineF(linePort.p1(), location).length();
qreal const c = QLineF(linePort.p2(), location).length();
qreal const nearestPoint= nearestPointOfLinePort(linePortNumber, location);
if ((nearestPoint < 0) || (nearestPoint > mMaximumFractionPartValue)) {
return qMin(b, c);
} else {
qreal const p = (a + b + c) / 2;
qreal const triangleSquare = sqrt(p * (p - a) * (p - b) * (p - c));
qreal const minDistance = 2 * triangleSquare / a;
return minDistance;
}
}
qreal PortHandler::distanceFromPointPort(int pointPortNumber, QPointF const &location) const
{
return QLineF(transformPortForNodeSize(mPointPorts[pointPortNumber]), location).length();
}
qreal PortHandler::nearestPointOfLinePort(int linePortNumber, QPointF const &location) const
{
qreal nearestPointOfLinePort = 0;
QLineF linePort = transformPortForNodeSize(mLinePorts[linePortNumber]);
qreal const y1 = linePort.y1();
qreal const y2 = linePort.y2();
qreal const x1 = linePort.x1();
qreal const x2 = linePort.x2();
if (x1 == x2) {
nearestPointOfLinePort = (location.y() - y1) / (y2 - y1);
} else if (y1 == y2) {
nearestPointOfLinePort = (location.x() - x1) / (x2 - x1);
} else {
qreal const k = (y2 - y1) / (x2 - x1);
qreal const b2 = location.y() + 1 / k * location.x();
qreal const b = y1 - k * x1;
qreal const x3 = k / (1 + k * k) * (b2 - b);
nearestPointOfLinePort = (x3 - x1) / (x2 - x1);
}
return nearestPointOfLinePort;
}
QLineF PortHandler::transformPortForNodeSize(StatLine const &port) const
{
qreal const x1 = port.line.x1() * (port.prop_x1 ? port.initWidth : mNode->contentsRect().width());
qreal const y1 = port.line.y1() * (port.prop_y1 ? port.initHeight : mNode->contentsRect().height());
qreal const x2 = port.line.x2() * (port.prop_x2 ? port.initWidth : mNode->contentsRect().width());
qreal const y2 = port.line.y2() * (port.prop_y2 ? port.initHeight : mNode->contentsRect().height());
return QLineF(x1, y1, x2, y2);
}
QPointF PortHandler::transformPortForNodeSize(StatPoint const &port) const
{
qreal const x = port.point.x() * (port.prop_x ? port.initWidth : mNode->contentsRect().width());
qreal const y = port.point.y() * (port.prop_y ? port.initHeight : mNode->contentsRect().height());
return QPointF(x, y);
}
void PortHandler::connectTemporaryRemovedLinksToPort(IdList const &temporaryRemovedLinks, QString const &direction)
{
foreach (Id const &edgeId, temporaryRemovedLinks) {
EdgeElement *edge = dynamic_cast<EdgeElement *>(static_cast<EditorViewScene *>(mNode->scene())->getElem(edgeId));
if (edge == NULL) {
continue;
}
if (direction == "from") {
QPointF const startPos = edge->mapFromItem(mNode, nearestPort(edge->line().first()));
edge->placeStartTo(startPos);
} else {
QPointF const endPos = edge->mapFromItem(mNode, nearestPort(edge->line().last()));
edge->placeEndTo(endPos);
}
edge->connectToPort();
}
}
QPointF const PortHandler::portPos(qreal id) const
{
if (id < 0.0) {
return QPointF(0, 0);
}
// portNum - integral id part, number of port
int portNum = portNumber(id);
if (portNum < mPointPorts.size()) {
return transformPortForNodeSize(mPointPorts[portNum]);
}
if (portNum < mPointPorts.size() + mLinePorts.size()) {
return transformPortForNodeSize(mLinePorts.at(portNum - mPointPorts.size())).pointAt(id - qFloor(id));
} else {
return QPointF(0, 0);
}
}
int PortHandler::portNumber(qreal id)
{
return qFloor(id);
}
QPointF const PortHandler::nearestPort(QPointF const &location) const
{
// location in scene coords, so we map it to mNode.
QPointF const locationInLocalCoords = location - mNode->boundingRect().topLeft();
QPointF nearestPortPoint;
qreal minDistance = -1; // just smth negative
// Point port observing.
QPair<int, qreal> const pointPortRes = nearestPointPortNumberAndDistance(locationInLocalCoords);
if (pointPortRes.second >= 0) {
minDistance = pointPortRes.second;
nearestPortPoint = transformPortForNodeSize(mPointPorts[pointPortRes.first]);
}
// Line port observing.
QPair<int, qreal> const linePortRes = nearestLinePortNumberAndDistance(locationInLocalCoords);
if (linePortRes.second >= 0 &&
(linePortRes.second < minDistance || minDistance < 0)
) {
minDistance = linePortRes.second;
qreal const positionAtLineCoef = qMin(qMax(0., nearestPointOfLinePort(linePortRes.first, locationInLocalCoords)), mMaximumFractionPartValue);
QLineF const sceneLine = transformPortForNodeSize(mLinePorts[linePortRes.first]);
nearestPortPoint = sceneLine.pointAt(positionAtLineCoef);
}
if (minDistance > 0) {
// Moving to scene coords.
return nearestPortPoint + mNode->boundingRect().topLeft();
}
return location;
}
qreal PortHandler::pointPortId(QPointF const &location) const
{
int pointPortNumber = 0;
foreach (StatPoint const &pointPort, mPointPorts) {
if (QRectF(transformPortForNodeSize(pointPort) - QPointF(kvadratik, kvadratik),
QSizeF(kvadratik * 2, kvadratik * 2)
).contains(location))
{
return pointPortNumber;
}
pointPortNumber++;
}
return mNonexistentPortId;
}
qreal PortHandler::linePortId(QPointF const &location) const
{
int linePortNumber = 0;
foreach (StatLine const &linePort, mLinePorts) {
QPainterPathStroker ps;
ps.setWidth(kvadratik - 5);
QPainterPath path;
QLineF const line = transformPortForNodeSize(linePort);
path.moveTo(line.p1());
path.lineTo(line.p2());
path = ps.createStroke(path);
if (path.contains(location)) {
return linePortNumber + mPointPorts.size()
+ qMin(QLineF(line.p1(), location).length() / line.length()
, mMaximumFractionPartValue);
}
linePortNumber++;
}
return mNonexistentPortId;
}
QPair<int, qreal> PortHandler::nearestPointPortNumberAndDistance(QPointF const &location) const
{
qreal minDistance = -1; // just smth negative
int minDistancePointPortNumber = -1; // just smth negative
for (int pointPortNumber = 0; pointPortNumber < mPointPorts.size(); pointPortNumber++) {
qreal const currentDistance = distanceFromPointPort(pointPortNumber, location);
if (currentDistance < minDistance || minDistance < 0) {
minDistancePointPortNumber = pointPortNumber;
minDistance = currentDistance;
}
}
return qMakePair(minDistancePointPortNumber, minDistance);
}
QPair<int, qreal> PortHandler::nearestLinePortNumberAndDistance(QPointF const &location) const
{
qreal minDistance = -1; // just smth negative
int minDistanceLinePortNumber = -1; // just smth negative
for (int linePortNumber = 0; linePortNumber < mLinePorts.size(); linePortNumber++) {
qreal const currentDistance = minDistanceFromLinePort(linePortNumber, location);
if (currentDistance < minDistance || minDistance < 0) {
minDistanceLinePortNumber = linePortNumber;
minDistance = currentDistance;
}
}
return qMakePair(minDistanceLinePortNumber, minDistance);
}
qreal PortHandler::portId(QPointF const &location) const
{
if (mPointPorts.empty() && mLinePorts.empty()) {
return mNonexistentPortId;
}
// Finding in point port locality
qreal locationPointPortId = pointPortId(location);
if (locationPointPortId != mNonexistentPortId) {
return locationPointPortId;
}
// Finding in line port locality
qreal locationLinePortId = linePortId(location);
if (locationLinePortId != mNonexistentPortId) {
return locationLinePortId;
}
// Nearest ports
QPair<int, qreal> const pointPortRes = nearestPointPortNumberAndDistance(location);
QPair<int, qreal> const linePortRes = nearestLinePortNumberAndDistance(location);
// Second field is distance.
// In case it is less than 0 there is no ports of appropriate kind.
// First field is number of port in port list of appropriate kind.
if (!(pointPortRes.second < 0)) {
if (pointPortRes.second < linePortRes.second || linePortRes.second < 0) {
return pointPortRes.first;
}
return mNonexistentPortId;
} else {
// There is only line ports.
// And they exist, because of first method if.
qreal nearestPoint = nearestPointOfLinePort(linePortRes.first, location);
// Moving nearestPointOfLinePort value to [0, 1).
nearestPoint = qMin(0., nearestPoint);
nearestPoint = qMax(mMaximumFractionPartValue, nearestPoint);
return (linePortRes.first + mPointPorts.size()) // Integral part of ID.
+ nearestPoint; // Fractional part of ID.
// More information about ID parts in *Useful information* before class declaration.
}
}
int PortHandler::numberOfPorts() const
{
return (mPointPorts.size() + mLinePorts.size());
}
void PortHandler::connectLinksToPorts()
{
QList<QGraphicsItem *> const items = mNode->scene()->items(mNode->scenePos());
foreach (QGraphicsItem *item, items) {
EdgeElement *edge = dynamic_cast<EdgeElement *>(item);
if (edge) {
edge->connectToPort();
return;
}
}
}
void PortHandler::checkConnectionsToPort()
{
//FIXME
connectTemporaryRemovedLinksToPort(mGraphicalAssistApi->temporaryRemovedLinksFrom(mNode->id()), "from");
connectTemporaryRemovedLinksToPort(mGraphicalAssistApi->temporaryRemovedLinksTo(mNode->id()), "to");
connectTemporaryRemovedLinksToPort(mGraphicalAssistApi->temporaryRemovedLinksNone(mNode->id()), QString());
mGraphicalAssistApi->removeTemporaryRemovedLinks(mNode->id());
// i have no idea what this method does, but it is called when the element
// is dropped on scene. so i'll just leave this code here for now.
connectLinksToPorts();
}
void PortHandler::arrangeLinearPorts()
{
int lpId = mPointPorts.size(); //point ports before linear
foreach (StatLine const &linePort, mLinePorts) {
//sort first by slope, then by current portNumber
QMap<QPair<qreal, qreal>, EdgeElement*> sortedEdges;
QLineF const portLine = linePort;
qreal const dx = portLine.dx();
qreal const dy = portLine.dy();
foreach (EdgeElement* edge, mNode->edgeList()) {
qreal portSrcId = edge->portIdOn(mNode).first;
qreal portDstId = edge->portIdOn(mNode).second;
qreal currentPortId = -1.0;
if (portNumber(portSrcId) == lpId) {
currentPortId = portSrcId;
}
if (portNumber(portDstId) == lpId) {
currentPortId = portDstId;
}
if (currentPortId != -1.0) {
QPointF const conn = edge->connectionPoint(mNode);
QPointF const next = edge->nextFrom(mNode);
qreal const x1 = conn.x();
qreal const y1 = conn.y();
qreal const x2 = next.x();
qreal const y2 = next.y();
qreal const len = sqrt((x2 - x1) * (x2 - x1) + (y2 - y1) * (y2 - y1));
qreal const scalarProduct = ((x2 - x1) * dx + (y2 - y1) * dy) / len;
sortedEdges.insertMulti(qMakePair(currentPortId, scalarProduct), edge);
}
}
//by now, edges of this port are sorted by their optimal slope.
int const n = sortedEdges.size();
int i = 0;
foreach (EdgeElement* edge, sortedEdges) {
qreal const newId = lpId + (i + 1.0) / (n + 1);
edge->moveConnection(mNode, newId);
i++;
}
lpId++; //next linear port.
}
}
void PortHandler::setGraphicalAssistApi(qReal::models::GraphicalModelAssistApi *graphicalAssistApi)
{
mGraphicalAssistApi = graphicalAssistApi;
}
<commit_msg>Some refactoring.<commit_after>#include "../../view/editorViewScene.h"
#include <QtCore/qmath.h>
#include "../nodeElement.h"
#include "portHandler.h"
qreal const PortHandler::mMaximumFractionPartValue = 0.9999;
PortHandler::PortHandler(NodeElement *node, qReal::models::GraphicalModelAssistApi *graphicalAssistApi,
QList<StatPoint> const &pointPorts, QList<StatLine> const &linePorts)
: mNode(node), mGraphicalAssistApi(graphicalAssistApi)
, mPointPorts(pointPorts), mLinePorts(linePorts)
{
}
qreal PortHandler::minDistanceFromLinePort(int linePortNumber, QPointF const &location) const
{
QLineF const linePort = transformPortForNodeSize(mLinePorts[linePortNumber]);
// Triangle side values.
qreal const a = linePort.length();
qreal const b = QLineF(linePort.p1(), location).length();
qreal const c = QLineF(linePort.p2(), location).length();
qreal const nearestPoint= nearestPointOfLinePort(linePortNumber, location);
if ((nearestPoint < 0) || (nearestPoint > mMaximumFractionPartValue)) {
return qMin(b, c);
} else {
qreal const p = (a + b + c) / 2;
qreal const triangleSquare = sqrt(p * (p - a) * (p - b) * (p - c));
qreal const minDistance = 2 * triangleSquare / a;
return minDistance;
}
}
qreal PortHandler::distanceFromPointPort(int pointPortNumber, QPointF const &location) const
{
return QLineF(transformPortForNodeSize(mPointPorts[pointPortNumber]), location).length();
}
qreal PortHandler::nearestPointOfLinePort(int linePortNumber, QPointF const &location) const
{
qreal nearestPointOfLinePort = 0;
QLineF linePort = transformPortForNodeSize(mLinePorts[linePortNumber]);
qreal const y1 = linePort.y1();
qreal const y2 = linePort.y2();
qreal const x1 = linePort.x1();
qreal const x2 = linePort.x2();
if (x1 == x2) {
nearestPointOfLinePort = (location.y() - y1) / (y2 - y1);
} else if (y1 == y2) {
nearestPointOfLinePort = (location.x() - x1) / (x2 - x1);
} else {
qreal const k = (y2 - y1) / (x2 - x1);
qreal const b2 = location.y() + 1 / k * location.x();
qreal const b = y1 - k * x1;
qreal const x3 = k / (1 + k * k) * (b2 - b);
nearestPointOfLinePort = (x3 - x1) / (x2 - x1);
}
return nearestPointOfLinePort;
}
QLineF PortHandler::transformPortForNodeSize(StatLine const &port) const
{
qreal const x1 = port.line.x1() * (port.prop_x1 ? port.initWidth : mNode->contentsRect().width());
qreal const y1 = port.line.y1() * (port.prop_y1 ? port.initHeight : mNode->contentsRect().height());
qreal const x2 = port.line.x2() * (port.prop_x2 ? port.initWidth : mNode->contentsRect().width());
qreal const y2 = port.line.y2() * (port.prop_y2 ? port.initHeight : mNode->contentsRect().height());
return QLineF(x1, y1, x2, y2);
}
QPointF PortHandler::transformPortForNodeSize(StatPoint const &port) const
{
qreal const x = port.point.x() * (port.prop_x ? port.initWidth : mNode->contentsRect().width());
qreal const y = port.point.y() * (port.prop_y ? port.initHeight : mNode->contentsRect().height());
return QPointF(x, y);
}
void PortHandler::connectTemporaryRemovedLinksToPort(IdList const &temporaryRemovedLinks, QString const &direction)
{
foreach (Id const &edgeId, temporaryRemovedLinks) {
EdgeElement *edge = dynamic_cast<EdgeElement *>(static_cast<EditorViewScene *>(mNode->scene())->getElem(edgeId));
if (edge == NULL) {
continue;
}
if (direction == "from") {
QPointF const startPos = edge->mapFromItem(mNode, nearestPort(edge->line().first()));
edge->placeStartTo(startPos);
} else {
QPointF const endPos = edge->mapFromItem(mNode, nearestPort(edge->line().last()));
edge->placeEndTo(endPos);
}
edge->connectToPort();
}
}
QPointF const PortHandler::portPos(qreal id) const
{
if (id < 0.0) {
return QPointF(0, 0);
}
// portNum - integral id part, number of port
int portNum = portNumber(id);
if (portNum < mPointPorts.size()) {
return transformPortForNodeSize(mPointPorts[portNum]);
}
if (portNum < mPointPorts.size() + mLinePorts.size()) {
return transformPortForNodeSize(mLinePorts.at(portNum - mPointPorts.size())).pointAt(id - qFloor(id));
} else {
return QPointF(0, 0);
}
}
int PortHandler::portNumber(qreal id)
{
return qFloor(id);
}
QPointF const PortHandler::nearestPort(QPointF const &location) const
{
// location in scene coords, so we map it to mNode.
QPointF const locationInLocalCoords = location - mNode->boundingRect().topLeft();
QPointF nearestPortPoint;
qreal minDistance = -1; // just smth negative
// Point port observing.
QPair<int, qreal> const pointPortRes = nearestPointPortNumberAndDistance(locationInLocalCoords);
if (pointPortRes.second >= 0) {
minDistance = pointPortRes.second;
nearestPortPoint = transformPortForNodeSize(mPointPorts[pointPortRes.first]);
}
// Line port observing.
QPair<int, qreal> const linePortRes = nearestLinePortNumberAndDistance(locationInLocalCoords);
if (linePortRes.second >= 0 &&
(linePortRes.second < minDistance || minDistance < 0)
) {
minDistance = linePortRes.second;
qreal const positionAtLineCoef = qMin(qMax(0., nearestPointOfLinePort(linePortRes.first, locationInLocalCoords)), mMaximumFractionPartValue);
QLineF const sceneLine = transformPortForNodeSize(mLinePorts[linePortRes.first]);
nearestPortPoint = sceneLine.pointAt(positionAtLineCoef);
}
if (minDistance > 0) {
// Moving to scene coords.
return nearestPortPoint + mNode->boundingRect().topLeft();
}
return location;
}
qreal PortHandler::pointPortId(QPointF const &location) const
{
int pointPortNumber = 0;
foreach (StatPoint const &pointPort, mPointPorts) {
if (QRectF(transformPortForNodeSize(pointPort) - QPointF(kvadratik, kvadratik),
QSizeF(kvadratik * 2, kvadratik * 2)
).contains(location))
{
return pointPortNumber;
}
pointPortNumber++;
}
return mNonexistentPortId;
}
qreal PortHandler::linePortId(QPointF const &location) const
{
int linePortNumber = 0;
foreach (StatLine const &linePort, mLinePorts) {
QPainterPathStroker ps;
ps.setWidth(kvadratik - 5);
QPainterPath path;
QLineF const line = transformPortForNodeSize(linePort);
path.moveTo(line.p1());
path.lineTo(line.p2());
path = ps.createStroke(path);
if (path.contains(location)) {
return linePortNumber + mPointPorts.size()
+ qMin(QLineF(line.p1(), location).length() / line.length()
, mMaximumFractionPartValue);
}
linePortNumber++;
}
return mNonexistentPortId;
}
QPair<int, qreal> PortHandler::nearestPointPortNumberAndDistance(QPointF const &location) const
{
qreal minDistance = -1; // just smth negative
int minDistancePointPortNumber = -1; // just smth negative
for (int pointPortNumber = 0; pointPortNumber < mPointPorts.size(); pointPortNumber++) {
qreal const currentDistance = distanceFromPointPort(pointPortNumber, location);
if (currentDistance < minDistance || minDistance < 0) {
minDistancePointPortNumber = pointPortNumber;
minDistance = currentDistance;
}
}
return qMakePair(minDistancePointPortNumber, minDistance);
}
QPair<int, qreal> PortHandler::nearestLinePortNumberAndDistance(QPointF const &location) const
{
qreal minDistance = -1; // just smth negative
int minDistanceLinePortNumber = -1; // just smth negative
for (int linePortNumber = 0; linePortNumber < mLinePorts.size(); linePortNumber++) {
qreal const currentDistance = minDistanceFromLinePort(linePortNumber, location);
if (currentDistance < minDistance || minDistance < 0) {
minDistanceLinePortNumber = linePortNumber;
minDistance = currentDistance;
}
}
return qMakePair(minDistanceLinePortNumber, minDistance);
}
qreal PortHandler::portId(QPointF const &location) const
{
if (mPointPorts.empty() && mLinePorts.empty()) {
return mNonexistentPortId;
}
// Finding in point port locality
qreal locationPointPortId = pointPortId(location);
if (locationPointPortId != mNonexistentPortId) {
return locationPointPortId;
}
// Finding in line port locality
qreal locationLinePortId = linePortId(location);
if (locationLinePortId != mNonexistentPortId) {
return locationLinePortId;
}
// Nearest ports
QPair<int, qreal> const pointPortRes = nearestPointPortNumberAndDistance(location);
QPair<int, qreal> const linePortRes = nearestLinePortNumberAndDistance(location);
// Second field is distance.
// In case it is less than 0 there is no ports of appropriate kind.
// First field is number of port in port list of appropriate kind.
if (!(pointPortRes.second < 0)) {
if (pointPortRes.second < linePortRes.second || linePortRes.second < 0) {
return pointPortRes.first;
}
return mNonexistentPortId;
} else {
// There is only line ports.
// And they exist, because of first method if.
qreal nearestPoint = nearestPointOfLinePort(linePortRes.first, location);
// Moving nearestPointOfLinePort value to [0, 1).
nearestPoint = qMin(0., nearestPoint);
nearestPoint = qMax(mMaximumFractionPartValue, nearestPoint);
return (linePortRes.first + mPointPorts.size()) // Integral part of ID.
+ nearestPoint; // Fractional part of ID.
// More information about ID parts in *Useful information* before class declaration.
}
}
int PortHandler::numberOfPorts() const
{
return (mPointPorts.size() + mLinePorts.size());
}
void PortHandler::connectLinksToPorts()
{
QList<QGraphicsItem *> const items = mNode->scene()->items(mNode->scenePos());
foreach (QGraphicsItem *item, items) {
EdgeElement *edge = dynamic_cast<EdgeElement *>(item);
if (edge) {
edge->connectToPort();
return;
}
}
}
void PortHandler::checkConnectionsToPort()
{
//FIXME
connectTemporaryRemovedLinksToPort(mGraphicalAssistApi->temporaryRemovedLinksFrom(mNode->id()), "from");
connectTemporaryRemovedLinksToPort(mGraphicalAssistApi->temporaryRemovedLinksTo(mNode->id()), "to");
connectTemporaryRemovedLinksToPort(mGraphicalAssistApi->temporaryRemovedLinksNone(mNode->id()), QString());
mGraphicalAssistApi->removeTemporaryRemovedLinks(mNode->id());
// i have no idea what this method does, but it is called when the element
// is dropped on scene. so i'll just leave this code here for now.
connectLinksToPorts();
}
void PortHandler::arrangeLinearPorts()
{
int lpId = mPointPorts.size(); //point ports before linear
foreach (StatLine const &linePort, mLinePorts) {
//sort first by slope, then by current portNumber
QMap<QPair<qreal, qreal>, EdgeElement*> sortedEdges;
QLineF const portLine = linePort;
qreal const dx = portLine.dx();
qreal const dy = portLine.dy();
foreach (EdgeElement* edge, mNode->edgeList()) {
//edge->portIdOn(mNode) returns a pair of ports id of the mNode associated with the ends of edge.
// returns -1.0 if the current end of edge is not connected to the mNode.
QPair<qreal, qreal> edgePortId = edge->portIdOn(mNode);
qreal currentPortId = -1.0;
if (portNumber(edgePortId.first) == lpId) {
currentPortId = edgePortId.first;
}
if (portNumber(edgePortId.second) == lpId) {
currentPortId = edgePortId.second;
}
if (currentPortId != -1.0) {
QPointF const conn = edge->connectionPoint(mNode);
QPointF const next = edge->nextFrom(mNode);
qreal const x1 = conn.x();
qreal const y1 = conn.y();
qreal const x2 = next.x();
qreal const y2 = next.y();
qreal const len = sqrt((x2 - x1) * (x2 - x1) + (y2 - y1) * (y2 - y1));
qreal const scalarProduct = ((x2 - x1) * dx + (y2 - y1) * dy) / len;
sortedEdges.insertMulti(qMakePair(currentPortId, scalarProduct), edge);
}
}
//by now, edges of this port are sorted by their optimal slope.
int const n = sortedEdges.size();
int i = 0;
foreach (EdgeElement* edge, sortedEdges) {
qreal const newId = lpId + (i + 1.0) / (n + 1);
edge->moveConnection(mNode, newId);
i++;
}
lpId++; //next linear port.
}
}
void PortHandler::setGraphicalAssistApi(qReal::models::GraphicalModelAssistApi *graphicalAssistApi)
{
mGraphicalAssistApi = graphicalAssistApi;
}
<|endoftext|> |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.