text
stringlengths 54
60.6k
|
---|
<commit_before>/*=========================================================================
Program: ORFEO Toolbox
Language: C++
Date: $Date$
Version: $Revision$
Copyright (c) Centre National d'Etudes Spatiales. All rights reserved.
See OTBCopyright.txt for details.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE. See the above copyright notices for more information.
=========================================================================*/
#include "otbWrapperOutputImageParameter.h"
#include "itkCastImageFilter.h"
#include "itkVectorCastImageFilter.h"
namespace otb
{
namespace Wrapper
{
OutputImageParameter::OutputImageParameter()
: m_PixelType(ImagePixelType_float)
{
this->SetName("Output Image");
this->SetKey("out");
this->InitializeWriters();
}
OutputImageParameter::~OutputImageParameter()
{
}
void OutputImageParameter::InitializeWriters()
{
m_Int8Writer = Int8WriterType::New();
m_UInt8Writer = UInt8WriterType::New();
m_Int16Writer = Int16WriterType::New();
m_UInt16Writer = UInt16WriterType::New();
m_Int32Writer = Int32WriterType::New();
m_UInt32Writer = UInt32WriterType::New();
m_FloatWriter = FloatWriterType::New();
m_DoubleWriter = DoubleWriterType::New();
m_RGBAUInt8Writer = RGBAUInt8WriterType::New();
m_VectorInt8Writer = VectorInt8WriterType::New();
m_VectorUInt8Writer = VectorUInt8WriterType::New();
m_VectorInt16Writer = VectorInt16WriterType::New();
m_VectorUInt16Writer = VectorUInt16WriterType::New();
m_VectorInt32Writer = VectorInt32WriterType::New();
m_VectorUInt32Writer = VectorUInt32WriterType::New();
m_VectorFloatWriter = VectorFloatWriterType::New();
m_VectorDoubleWriter = VectorDoubleWriterType::New();
}
#define otbCastAndWriteImageMacro(InputImageType, OutputImageType, writer) \
{ \
typedef itk::CastImageFilter<InputImageType, OutputImageType> CastFilterType; \
typename CastFilterType::Pointer caster = CastFilterType::New(); \
caster->SetInput( dynamic_cast<InputImageType*>(m_Image.GetPointer()) ); \
writer->SetFileName( this->GetFileName() ); \
writer->SetInput(caster->GetOutput()); \
writer->Update(); \
}
template <class TInputImageType>
void
OutputImageParameter::SwitchImageWrite()
{
switch(m_PixelType )
{
case ImagePixelType_int8:
{
otbCastAndWriteImageMacro(TInputImageType, Int8ImageType, m_Int8Writer);
break;
}
case ImagePixelType_uint8:
{
std::cout<<"Write, output is image uint8"<<std::endl;
otbCastAndWriteImageMacro(TInputImageType, UInt8ImageType, m_UInt8Writer);
break;
}
case ImagePixelType_int16:
{
otbCastAndWriteImageMacro(TInputImageType, Int16ImageType, m_Int16Writer);
break;
}
case ImagePixelType_uint16:
{
otbCastAndWriteImageMacro(TInputImageType, UInt16ImageType, m_UInt16Writer);
break;
}
case ImagePixelType_int32:
{
otbCastAndWriteImageMacro(TInputImageType, Int32ImageType, m_Int32Writer);
break;
}
case ImagePixelType_uint32:
{
otbCastAndWriteImageMacro(TInputImageType, UInt32ImageType, m_UInt32Writer);
break;
}
case ImagePixelType_float:
{
std::cout<<"Write, output is image float"<<std::endl;
otbCastAndWriteImageMacro(TInputImageType, FloatImageType, m_FloatWriter);
break;
}
case ImagePixelType_double:
{
std::cout<<"Write, output is image double"<<std::endl;
otbCastAndWriteImageMacro(TInputImageType, DoubleImageType, m_DoubleWriter);
break;
}
}
}
template <class TInputVectorImageType>
void
OutputImageParameter::SwitchVectorImageWrite()
{
switch(m_PixelType )
{
case ImagePixelType_int8:
{
otbCastAndWriteImageMacro(TInputVectorImageType, Int8VectorImageType, m_VectorInt8Writer);
break;
}
case ImagePixelType_uint8:
{
otbCastAndWriteImageMacro(TInputVectorImageType, UInt8VectorImageType, m_VectorUInt8Writer);
break;
}
case ImagePixelType_int16:
{
otbCastAndWriteImageMacro(TInputVectorImageType, Int16VectorImageType, m_VectorInt16Writer);
break;
}
case ImagePixelType_uint16:
{
otbCastAndWriteImageMacro(TInputVectorImageType, UInt16VectorImageType, m_VectorUInt16Writer);
break;
}
case ImagePixelType_int32:
{
otbCastAndWriteImageMacro(TInputVectorImageType, Int32VectorImageType, m_VectorInt32Writer);
break;
}
case ImagePixelType_uint32:
{
otbCastAndWriteImageMacro(TInputVectorImageType, UInt32VectorImageType, m_VectorUInt32Writer);
break;
}
case ImagePixelType_float:
{
otbCastAndWriteImageMacro(TInputVectorImageType, FloatVectorImageType, m_VectorFloatWriter);
break;
}
case ImagePixelType_double:
{
otbCastAndWriteImageMacro(TInputVectorImageType, DoubleVectorImageType, m_VectorDoubleWriter);
break;
}
}
}
template <class TInputRGBAImageType>
void
OutputImageParameter::SwitchRGBAImageWrite()
{
switch(m_PixelType )
{
case ImagePixelType_int8:
{
otbCastAndWriteImageMacro(TInputRGBAImageType, Int8RGBAImageType, m_RGBAInt8Writer);
break;
}
case ImagePixelType_uint8:
{
otbCastAndWriteImageMacro(TInputRGBAImageType, UInt8RGBAImageType, m_RGBAUInt8Writer);
break;
}
case ImagePixelType_int16:
{
otbCastAndWriteImageMacro(TInputRGBAImageType, Int16RGBAImageType, m_RGBAInt16Writer);
break;
}
case ImagePixelType_uint16:
{
otbCastAndWriteImageMacro(TInputRGBAImageType, UInt16RGBAImageType, m_RGBAUInt16Writer);
break;
}
case ImagePixelType_int32:
{
otbCastAndWriteImageMacro(TInputRGBAImageType, Int32RGBAImageType, m_RGBAInt32Writer);
break;
}
case ImagePixelType_uint32:
{
otbCastAndWriteImageMacro(TInputRGBAImageType, UInt32RGBAImageType, m_RGBAUInt32Writer);
break;
}
case ImagePixelType_float:
{
otbCastAndWriteImageMacro(TInputRGBAImageType, FloatRGBAImageType, m_RGBAFloatWriter);
break;
}
case ImagePixelType_double:
{
otbCastAndWriteImageMacro(TInputRGBAImageType, DoubleRGBAImageType, m_RGBADoubleWriter);
break;
}
}
}
void
OutputImageParameter::Write()
{
m_Image->UpdateOutputInformation();
if (dynamic_cast<Int8ImageType*>(m_Image.GetPointer()))
{
SwitchImageWrite<Int8ImageType>();
}
else if (dynamic_cast<UInt8ImageType*>(m_Image.GetPointer()))
{
std::cout<<"Write, input is image uint8"<<std::endl;
SwitchImageWrite<UInt8ImageType>();
}
else if (dynamic_cast<Int16ImageType*>(m_Image.GetPointer()))
{
SwitchImageWrite<Int16ImageType>();
}
else if (dynamic_cast<UInt16ImageType*>(m_Image.GetPointer()))
{
SwitchImageWrite<UInt16ImageType>();
}
else if (dynamic_cast<Int32ImageType*>(m_Image.GetPointer()))
{
SwitchImageWrite<Int32ImageType>();
}
else if (dynamic_cast<UInt32ImageType*>(m_Image.GetPointer()))
{
SwitchImageWrite<UInt32ImageType>();
}
else if (dynamic_cast<FloatImageType*>(m_Image.GetPointer()))
{
SwitchImageWrite<FloatImageType>();
}
else if (dynamic_cast<DoubleImageType*>(m_Image.GetPointer()))
{
SwitchImageWrite<DoubleImageType>();
}
else if (dynamic_cast<Int8VectorImageType*>(m_Image.GetPointer()))
{
SwitchVectorImageWrite<Int8VectorImageType>();
}
else if (dynamic_cast<UInt8VectorImageType*>(m_Image.GetPointer()))
{
SwitchVectorImageWrite<UInt8VectorImageType>();
}
else if (dynamic_cast<Int16VectorImageType*>(m_Image.GetPointer()))
{
SwitchVectorImageWrite<Int16VectorImageType>();
}
else if (dynamic_cast<UInt16VectorImageType*>(m_Image.GetPointer()))
{
SwitchVectorImageWrite<UInt16VectorImageType>();
}
else if (dynamic_cast<Int32VectorImageType*>(m_Image.GetPointer()))
{
SwitchVectorImageWrite<Int32VectorImageType>();
}
else if (dynamic_cast<UInt32VectorImageType*>(m_Image.GetPointer()))
{
SwitchVectorImageWrite<UInt32VectorImageType>();
}
else if (dynamic_cast<FloatVectorImageType*>(m_Image.GetPointer()))
{
SwitchVectorImageWrite<FloatVectorImageType>();
}
else if (dynamic_cast<DoubleVectorImageType*>(m_Image.GetPointer()))
{
SwitchVectorImageWrite<DoubleVectorImageType>();
}
else if (dynamic_cast<Int8ImageType*>(m_Image.GetPointer()))
{
SwitchRGBAImageWrite<Int8RGBAImageType>();
}
else if (dynamic_cast<UInt8RGBAImageType*>(m_Image.GetPointer()))
{
SwitchRGBAImageWrite<UInt8RGBAImageType>();
}
else if (dynamic_cast<Int16RGBAImageType*>(m_Image.GetPointer()))
{
SwitchRGBAImageWrite<Int16RGBAImageType>();
}
else if (dynamic_cast<UInt16RGBAImageType*>(m_Image.GetPointer()))
{
SwitchRGBAImageWrite<UInt16RGBAImageType>();
}
else if (dynamic_cast<Int32RGBAImageType*>(m_Image.GetPointer()))
{
SwitchRGBAImageWrite<Int32RGBAImageType>();
}
else if (dynamic_cast<UInt32RGBAImageType*>(m_Image.GetPointer()))
{
SwitchRGBAImageWrite<UInt32RGBAImageType>();
}
else if (dynamic_cast<FloatRGBAImageType*>(m_Image.GetPointer()))
{
SwitchRGBAImageWrite<FloatRGBAImageType>();
}
else if (dynamic_cast<DoubleRGBAImageType*>(m_Image.GetPointer()))
{
SwitchRGBAImageWrite<DoubleRGBAImageType>();
}
else
{
itkExceptionMacro("Unknown image type");
}
}
itk::ProcessObject*
OutputImageParameter::GetWriter()
{
int type = 0;
// 0 : image
// 1 : VectorImage
// 2 : RGBAImage
if ( dynamic_cast<Int8VectorImageType*>( m_Image.GetPointer()) ||
dynamic_cast<UInt8VectorImageType*>( m_Image.GetPointer()) ||
dynamic_cast<Int16VectorImageType*>( m_Image.GetPointer()) ||
dynamic_cast<UInt16VectorImageType*>(m_Image.GetPointer()) ||
dynamic_cast<Int32VectorImageType*>( m_Image.GetPointer()) ||
dynamic_cast<UInt32VectorImageType*>(m_Image.GetPointer()) ||
dynamic_cast<FloatVectorImageType*>( m_Image.GetPointer()) ||
dynamic_cast<DoubleVectorImageType*>(m_Image.GetPointer()) )
{
type = 1;
}
else if( dynamic_cast<Int8RGBAImageType*>( m_Image.GetPointer()) ||
dynamic_cast<UInt8RGBAImageType*>( m_Image.GetPointer()) ||
dynamic_cast<Int16RGBAImageType*>( m_Image.GetPointer()) ||
dynamic_cast<UInt16RGBAImageType*>(m_Image.GetPointer()) ||
dynamic_cast<Int32RGBAImageType*>( m_Image.GetPointer()) ||
dynamic_cast<UInt32RGBAImageType*>(m_Image.GetPointer()) ||
dynamic_cast<FloatRGBAImageType*>( m_Image.GetPointer()) ||
dynamic_cast<DoubleRGBAImageType*>(m_Image.GetPointer()) )
{
type = 2;
}
itk::ProcessObject* writer = 0;
switch ( GetPixelType() )
{
case ImagePixelType_int8:
{
if( type == 1 )
writer = m_VectorInt8Writer;
else if(type == 0)
writer = m_Int8Writer;
else
writer = m_RGBAInt8Writer;
break;
}
case ImagePixelType_uint8:
{
if( type == 1 )
writer = m_VectorUInt8Writer;
else if(type == 0)
writer = m_UInt8Writer;
else
writer = m_RGBAUInt8Writer;
break;
}
case ImagePixelType_int16:
{
if( type == 1 )
writer = m_VectorInt16Writer;
else if(type == 0)
writer = m_Int16Writer;
else
writer = m_RGBAInt16Writer;
break;
}
case ImagePixelType_uint16:
{
if( type == 1 )
writer = m_VectorUInt16Writer;
else if(type == 0)
writer = m_UInt16Writer;
else
writer = m_RGBAUInt16Writer;
break;
}
case ImagePixelType_int32:
{
if( type == 1 )
writer = m_VectorInt32Writer;
else if(type == 0)
writer = m_Int32Writer;
else
writer = m_RGBAInt32Writer;
break;
}
case ImagePixelType_uint32:
{
if( type == 1 )
writer = m_VectorUInt32Writer;
else if(type == 0)
writer = m_UInt32Writer;
else
writer = m_RGBAUInt32Writer;
break;
}
case ImagePixelType_float:
{
if( type == 1 )
writer = m_VectorFloatWriter;
else if(type == 0)
writer = m_FloatWriter;
else
writer = m_RGBAFloatWriter;
break;
}
case ImagePixelType_double:
{
if( type == 1 )
writer = m_VectorDoubleWriter;
else if(type == 0)
writer = m_DoubleWriter;
else
writer = m_RGBADoubleWriter;
break;
}
}
return writer;
}
OutputImageParameter::ImageBaseType*
OutputImageParameter::GetValue( )
{
return m_Image;
}
void
OutputImageParameter::SetValue(ImageBaseType* image)
{
m_Image = image;
SetActive(true);
}
bool
OutputImageParameter::HasValue() const
{
std::string filename(this->GetFileName());
return !filename.empty();
}
}
}
<commit_msg>ENH: add missing init<commit_after>/*=========================================================================
Program: ORFEO Toolbox
Language: C++
Date: $Date$
Version: $Revision$
Copyright (c) Centre National d'Etudes Spatiales. All rights reserved.
See OTBCopyright.txt for details.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE. See the above copyright notices for more information.
=========================================================================*/
#include "otbWrapperOutputImageParameter.h"
#include "itkCastImageFilter.h"
#include "itkVectorCastImageFilter.h"
namespace otb
{
namespace Wrapper
{
OutputImageParameter::OutputImageParameter()
: m_PixelType(ImagePixelType_float)
{
this->SetName("Output Image");
this->SetKey("out");
this->InitializeWriters();
}
OutputImageParameter::~OutputImageParameter()
{
}
void OutputImageParameter::InitializeWriters()
{
m_Int8Writer = Int8WriterType::New();
m_UInt8Writer = UInt8WriterType::New();
m_Int16Writer = Int16WriterType::New();
m_UInt16Writer = UInt16WriterType::New();
m_Int32Writer = Int32WriterType::New();
m_UInt32Writer = UInt32WriterType::New();
m_FloatWriter = FloatWriterType::New();
m_DoubleWriter = DoubleWriterType::New();
m_VectorInt8Writer = VectorInt8WriterType::New();
m_VectorUInt8Writer = VectorUInt8WriterType::New();
m_VectorInt16Writer = VectorInt16WriterType::New();
m_VectorUInt16Writer = VectorUInt16WriterType::New();
m_VectorInt32Writer = VectorInt32WriterType::New();
m_VectorUInt32Writer = VectorUInt32WriterType::New();
m_VectorFloatWriter = VectorFloatWriterType::New();
m_VectorDoubleWriter = VectorDoubleWriterType::New();
m_RGBAInt8Writer = RGBAInt8WriterType::New();
m_RGBAUInt8Writer = RGBAUInt8WriterType::New();
m_RGBAInt16Writer = RGBAInt16WriterType::New();
m_RGBAUInt16Writer = RGBAUInt16WriterType::New();
m_RGBAInt32Writer = RGBAInt32WriterType::New();
m_RGBAUInt32Writer = RGBAUInt32WriterType::New();
m_RGBAFloatWriter = RGBAFloatWriterType::New();
m_RGBADoubleWriter = RGBADoubleWriterType::New();
}
#define otbCastAndWriteImageMacro(InputImageType, OutputImageType, writer) \
{ \
typedef itk::CastImageFilter<InputImageType, OutputImageType> CastFilterType; \
typename CastFilterType::Pointer caster = CastFilterType::New(); \
caster->SetInput( dynamic_cast<InputImageType*>(m_Image.GetPointer()) ); \
writer->SetFileName( this->GetFileName() ); \
writer->SetInput(caster->GetOutput()); \
writer->Update(); \
}
template <class TInputImageType>
void
OutputImageParameter::SwitchImageWrite()
{
switch(m_PixelType )
{
case ImagePixelType_int8:
{
otbCastAndWriteImageMacro(TInputImageType, Int8ImageType, m_Int8Writer);
break;
}
case ImagePixelType_uint8:
{
std::cout<<"Write, output is image uint8"<<std::endl;
otbCastAndWriteImageMacro(TInputImageType, UInt8ImageType, m_UInt8Writer);
break;
}
case ImagePixelType_int16:
{
otbCastAndWriteImageMacro(TInputImageType, Int16ImageType, m_Int16Writer);
break;
}
case ImagePixelType_uint16:
{
otbCastAndWriteImageMacro(TInputImageType, UInt16ImageType, m_UInt16Writer);
break;
}
case ImagePixelType_int32:
{
otbCastAndWriteImageMacro(TInputImageType, Int32ImageType, m_Int32Writer);
break;
}
case ImagePixelType_uint32:
{
otbCastAndWriteImageMacro(TInputImageType, UInt32ImageType, m_UInt32Writer);
break;
}
case ImagePixelType_float:
{
std::cout<<"Write, output is image float"<<std::endl;
otbCastAndWriteImageMacro(TInputImageType, FloatImageType, m_FloatWriter);
break;
}
case ImagePixelType_double:
{
std::cout<<"Write, output is image double"<<std::endl;
otbCastAndWriteImageMacro(TInputImageType, DoubleImageType, m_DoubleWriter);
break;
}
}
}
template <class TInputVectorImageType>
void
OutputImageParameter::SwitchVectorImageWrite()
{
switch(m_PixelType )
{
case ImagePixelType_int8:
{
otbCastAndWriteImageMacro(TInputVectorImageType, Int8VectorImageType, m_VectorInt8Writer);
break;
}
case ImagePixelType_uint8:
{
otbCastAndWriteImageMacro(TInputVectorImageType, UInt8VectorImageType, m_VectorUInt8Writer);
break;
}
case ImagePixelType_int16:
{
otbCastAndWriteImageMacro(TInputVectorImageType, Int16VectorImageType, m_VectorInt16Writer);
break;
}
case ImagePixelType_uint16:
{
otbCastAndWriteImageMacro(TInputVectorImageType, UInt16VectorImageType, m_VectorUInt16Writer);
break;
}
case ImagePixelType_int32:
{
otbCastAndWriteImageMacro(TInputVectorImageType, Int32VectorImageType, m_VectorInt32Writer);
break;
}
case ImagePixelType_uint32:
{
otbCastAndWriteImageMacro(TInputVectorImageType, UInt32VectorImageType, m_VectorUInt32Writer);
break;
}
case ImagePixelType_float:
{
otbCastAndWriteImageMacro(TInputVectorImageType, FloatVectorImageType, m_VectorFloatWriter);
break;
}
case ImagePixelType_double:
{
otbCastAndWriteImageMacro(TInputVectorImageType, DoubleVectorImageType, m_VectorDoubleWriter);
break;
}
}
}
template <class TInputRGBAImageType>
void
OutputImageParameter::SwitchRGBAImageWrite()
{
switch(m_PixelType )
{
case ImagePixelType_int8:
{
otbCastAndWriteImageMacro(TInputRGBAImageType, Int8RGBAImageType, m_RGBAInt8Writer);
break;
}
case ImagePixelType_uint8:
{
otbCastAndWriteImageMacro(TInputRGBAImageType, UInt8RGBAImageType, m_RGBAUInt8Writer);
break;
}
case ImagePixelType_int16:
{
otbCastAndWriteImageMacro(TInputRGBAImageType, Int16RGBAImageType, m_RGBAInt16Writer);
break;
}
case ImagePixelType_uint16:
{
otbCastAndWriteImageMacro(TInputRGBAImageType, UInt16RGBAImageType, m_RGBAUInt16Writer);
break;
}
case ImagePixelType_int32:
{
otbCastAndWriteImageMacro(TInputRGBAImageType, Int32RGBAImageType, m_RGBAInt32Writer);
break;
}
case ImagePixelType_uint32:
{
otbCastAndWriteImageMacro(TInputRGBAImageType, UInt32RGBAImageType, m_RGBAUInt32Writer);
break;
}
case ImagePixelType_float:
{
otbCastAndWriteImageMacro(TInputRGBAImageType, FloatRGBAImageType, m_RGBAFloatWriter);
break;
}
case ImagePixelType_double:
{
otbCastAndWriteImageMacro(TInputRGBAImageType, DoubleRGBAImageType, m_RGBADoubleWriter);
break;
}
}
}
void
OutputImageParameter::Write()
{
m_Image->UpdateOutputInformation();
if (dynamic_cast<Int8ImageType*>(m_Image.GetPointer()))
{
SwitchImageWrite<Int8ImageType>();
}
else if (dynamic_cast<UInt8ImageType*>(m_Image.GetPointer()))
{
std::cout<<"Write, input is image uint8"<<std::endl;
SwitchImageWrite<UInt8ImageType>();
}
else if (dynamic_cast<Int16ImageType*>(m_Image.GetPointer()))
{
SwitchImageWrite<Int16ImageType>();
}
else if (dynamic_cast<UInt16ImageType*>(m_Image.GetPointer()))
{
SwitchImageWrite<UInt16ImageType>();
}
else if (dynamic_cast<Int32ImageType*>(m_Image.GetPointer()))
{
SwitchImageWrite<Int32ImageType>();
}
else if (dynamic_cast<UInt32ImageType*>(m_Image.GetPointer()))
{
SwitchImageWrite<UInt32ImageType>();
}
else if (dynamic_cast<FloatImageType*>(m_Image.GetPointer()))
{
SwitchImageWrite<FloatImageType>();
}
else if (dynamic_cast<DoubleImageType*>(m_Image.GetPointer()))
{
SwitchImageWrite<DoubleImageType>();
}
else if (dynamic_cast<Int8VectorImageType*>(m_Image.GetPointer()))
{
SwitchVectorImageWrite<Int8VectorImageType>();
}
else if (dynamic_cast<UInt8VectorImageType*>(m_Image.GetPointer()))
{
SwitchVectorImageWrite<UInt8VectorImageType>();
}
else if (dynamic_cast<Int16VectorImageType*>(m_Image.GetPointer()))
{
SwitchVectorImageWrite<Int16VectorImageType>();
}
else if (dynamic_cast<UInt16VectorImageType*>(m_Image.GetPointer()))
{
SwitchVectorImageWrite<UInt16VectorImageType>();
}
else if (dynamic_cast<Int32VectorImageType*>(m_Image.GetPointer()))
{
SwitchVectorImageWrite<Int32VectorImageType>();
}
else if (dynamic_cast<UInt32VectorImageType*>(m_Image.GetPointer()))
{
SwitchVectorImageWrite<UInt32VectorImageType>();
}
else if (dynamic_cast<FloatVectorImageType*>(m_Image.GetPointer()))
{
SwitchVectorImageWrite<FloatVectorImageType>();
}
else if (dynamic_cast<DoubleVectorImageType*>(m_Image.GetPointer()))
{
SwitchVectorImageWrite<DoubleVectorImageType>();
}
else if (dynamic_cast<Int8ImageType*>(m_Image.GetPointer()))
{
SwitchRGBAImageWrite<Int8RGBAImageType>();
}
else if (dynamic_cast<UInt8RGBAImageType*>(m_Image.GetPointer()))
{
SwitchRGBAImageWrite<UInt8RGBAImageType>();
}
else if (dynamic_cast<Int16RGBAImageType*>(m_Image.GetPointer()))
{
SwitchRGBAImageWrite<Int16RGBAImageType>();
}
else if (dynamic_cast<UInt16RGBAImageType*>(m_Image.GetPointer()))
{
SwitchRGBAImageWrite<UInt16RGBAImageType>();
}
else if (dynamic_cast<Int32RGBAImageType*>(m_Image.GetPointer()))
{
SwitchRGBAImageWrite<Int32RGBAImageType>();
}
else if (dynamic_cast<UInt32RGBAImageType*>(m_Image.GetPointer()))
{
SwitchRGBAImageWrite<UInt32RGBAImageType>();
}
else if (dynamic_cast<FloatRGBAImageType*>(m_Image.GetPointer()))
{
SwitchRGBAImageWrite<FloatRGBAImageType>();
}
else if (dynamic_cast<DoubleRGBAImageType*>(m_Image.GetPointer()))
{
SwitchRGBAImageWrite<DoubleRGBAImageType>();
}
else
{
itkExceptionMacro("Unknown image type");
}
}
itk::ProcessObject*
OutputImageParameter::GetWriter()
{
int type = 0;
// 0 : image
// 1 : VectorImage
// 2 : RGBAImage
if ( dynamic_cast<Int8VectorImageType*>( m_Image.GetPointer()) ||
dynamic_cast<UInt8VectorImageType*>( m_Image.GetPointer()) ||
dynamic_cast<Int16VectorImageType*>( m_Image.GetPointer()) ||
dynamic_cast<UInt16VectorImageType*>(m_Image.GetPointer()) ||
dynamic_cast<Int32VectorImageType*>( m_Image.GetPointer()) ||
dynamic_cast<UInt32VectorImageType*>(m_Image.GetPointer()) ||
dynamic_cast<FloatVectorImageType*>( m_Image.GetPointer()) ||
dynamic_cast<DoubleVectorImageType*>(m_Image.GetPointer()) )
{
type = 1;
}
else if( dynamic_cast<Int8RGBAImageType*>( m_Image.GetPointer()) ||
dynamic_cast<UInt8RGBAImageType*>( m_Image.GetPointer()) ||
dynamic_cast<Int16RGBAImageType*>( m_Image.GetPointer()) ||
dynamic_cast<UInt16RGBAImageType*>(m_Image.GetPointer()) ||
dynamic_cast<Int32RGBAImageType*>( m_Image.GetPointer()) ||
dynamic_cast<UInt32RGBAImageType*>(m_Image.GetPointer()) ||
dynamic_cast<FloatRGBAImageType*>( m_Image.GetPointer()) ||
dynamic_cast<DoubleRGBAImageType*>(m_Image.GetPointer()) )
{
type = 2;
}
itk::ProcessObject* writer = 0;
switch ( GetPixelType() )
{
case ImagePixelType_int8:
{
if( type == 1 )
writer = m_VectorInt8Writer;
else if(type == 0)
writer = m_Int8Writer;
else
writer = m_RGBAInt8Writer;
break;
}
case ImagePixelType_uint8:
{
if( type == 1 )
writer = m_VectorUInt8Writer;
else if(type == 0)
writer = m_UInt8Writer;
else
writer = m_RGBAUInt8Writer;
break;
}
case ImagePixelType_int16:
{
if( type == 1 )
writer = m_VectorInt16Writer;
else if(type == 0)
writer = m_Int16Writer;
else
writer = m_RGBAInt16Writer;
break;
}
case ImagePixelType_uint16:
{
if( type == 1 )
writer = m_VectorUInt16Writer;
else if(type == 0)
writer = m_UInt16Writer;
else
writer = m_RGBAUInt16Writer;
break;
}
case ImagePixelType_int32:
{
if( type == 1 )
writer = m_VectorInt32Writer;
else if(type == 0)
writer = m_Int32Writer;
else
writer = m_RGBAInt32Writer;
break;
}
case ImagePixelType_uint32:
{
if( type == 1 )
writer = m_VectorUInt32Writer;
else if(type == 0)
writer = m_UInt32Writer;
else
writer = m_RGBAUInt32Writer;
break;
}
case ImagePixelType_float:
{
if( type == 1 )
writer = m_VectorFloatWriter;
else if(type == 0)
writer = m_FloatWriter;
else
writer = m_RGBAFloatWriter;
break;
}
case ImagePixelType_double:
{
if( type == 1 )
writer = m_VectorDoubleWriter;
else if(type == 0)
writer = m_DoubleWriter;
else
writer = m_RGBADoubleWriter;
break;
}
}
return writer;
}
OutputImageParameter::ImageBaseType*
OutputImageParameter::GetValue( )
{
return m_Image;
}
void
OutputImageParameter::SetValue(ImageBaseType* image)
{
m_Image = image;
SetActive(true);
}
bool
OutputImageParameter::HasValue() const
{
std::string filename(this->GetFileName());
return !filename.empty();
}
}
}
<|endoftext|> |
<commit_before>#include <xiot/X3DFIEncodingAlgorithms.h>
#include <iostream>
#include <cmath>
#include "zlib.h"
#include <xiot/FITypes.h>
#include <xiot/FIConstants.h>
#include <xiot/X3DParseException.h>
#include <xiot/X3DFICompressionTools.h>
namespace XIOT {
std::string QuantizedzlibFloatArrayAlgorithm::decodeToString(const FI::NonEmptyOctetString &octets) const
{
std::vector<float> floatArray;
QuantizedzlibFloatArrayAlgorithm::decodeToFloatArray(octets, floatArray);
std::stringstream ss;
std::vector<float>::const_iterator I;
for(I = floatArray.begin(); I != floatArray.end() -1; I++)
{
ss << (*I) << " ";
}
ss << (*I);
return ss.str();
}
void QuantizedzlibFloatArrayAlgorithm::decodeToFloatArray(const FI::NonEmptyOctetString &octets, std::vector<float> &vec)
{
// The format for encoding the custom float format is : (-S)000EEEE|000MMMMM.
bool sign = !static_cast<bool>(octets[0] & 0x80);
unsigned char exponent = octets[0] & FI::Constants::LAST_FOUR_BITS;
unsigned char mantissa = octets[1] & FI::Constants::LAST_FIVE_BITS;
int numBits = exponent + mantissa + (sign ? 1 : 0);
const unsigned char* pStr = &octets.front();
unsigned int len = FI::Tools::readUInt(pStr+2);
unsigned int numFloats = FI::Tools::readUInt(pStr+6); // = (len * 8) / (exponent + mantissa + sign);
std::vector<Bytef> temp_result(len);
uLong sourceLen = static_cast<uLong>(octets.size()-10);
uLong destSize = static_cast<uLong>(temp_result.size());
int result_code = uncompress(&temp_result.front(), &destSize, (unsigned char*)pStr + 10, sourceLen);
if (result_code != Z_OK) {
std::stringstream ss;
ss << "Error while decoding QuantizedzlibFloatArray. ZLIB error code: " << result_code;
throw X3DParseException(ss.str());
}
std::vector<float> result(numFloats);
FITools::BitUnpacker bu(&temp_result.front(), destSize);
FITools::FloatPacker fp(exponent, mantissa);
for(unsigned int i=0; i < numFloats; i++) {
unsigned long val = bu.unpack(numBits);
result[i] = fp.decode(val, sign);
}
std::swap(result, vec);
}
void QuantizedzlibFloatArrayAlgorithm::encode(const float* values, size_t size, FI::NonEmptyOctetString &octets)
{
unsigned char* bytes = new unsigned char[size*4];
unsigned char* bytepos = bytes;
size_t i;
const float* vf = values;
for (i = 0; i < size; i++)
{
union float_to_unsigned_int_to_bytes
{
float f;
unsigned int ui;
unsigned char ub[4]; // unsigned bytes
};
float_to_unsigned_int_to_bytes v;
v.f = (*vf) * 2.0f;
// Avoid -0
if (v.ui == 0x80000000)
{
v.f = 0.0f;
}
// std::cout << "value: " << v << " bytes: " << (int)s[0] << " " << (int)s[1] << " " << (int)s[2] << " " << (int)s[3]) << std::endl;
*bytepos++ = v.ub[3];
*bytepos++ = v.ub[2];
*bytepos++ = v.ub[1];
*bytepos++ = v.ub[0];
vf++;
}
// Compress the data
unsigned long compressedSize = static_cast<unsigned long>(size*4) + static_cast<unsigned long>(ceil((size*4)*0.001)) + 12;
Bytef* compressedData = new Bytef[compressedSize];
// Call zlib's compress function.
if(compress2(compressedData, &compressedSize, reinterpret_cast<const Bytef*>(bytes), static_cast<unsigned long>(size*4), Z_DEFAULT_COMPRESSION) != Z_OK)
{
throw X3DParseException("Error while encoding QuantizedzlibFloatArrayAlgorithm");
}
unsigned char *s;
// Put the number of bits for exponent
octets.push_back(static_cast<unsigned char>(8));
// Put the number of bits for mantissa
octets.push_back(static_cast<unsigned char>(23));
// Put the length
int length = static_cast<int>(size*4);
int length_reversed = FI::Tools::reverseBytes(&length);
s = reinterpret_cast <unsigned char*> (&length_reversed);
octets.insert(octets.end(), s, s+3);
// Put the number of floats
int numFloats = static_cast<int>(size);
int numFloats_reversed = FI::Tools::reverseBytes(&numFloats);;
s = reinterpret_cast <unsigned char*> (&numFloats_reversed);
octets.insert(octets.end(), s, s+3);
//octets.insert(octets.end(), s[0], s[3]);
//octets.append(s, 4);
for (i = 0; i < compressedSize; i++)
{
unsigned char c = compressedData[i];
octets.push_back(c);
}
delete[] compressedData;
delete[] bytes;
}
std::string DeltazlibIntArrayAlgorithm::decodeToString(const FI::NonEmptyOctetString &octets) const
{
std::vector<int> intArray;
DeltazlibIntArrayAlgorithm::decodeToIntArray(octets, intArray);
std::stringstream ss;
std::vector<int>::const_iterator I;
for(I = intArray.begin(); I != intArray.end() -1; I++)
{
ss << (*I) << " ";
}
ss << (*I);
return ss.str();
}
void DeltazlibIntArrayAlgorithm::decodeToIntArray(const FI::NonEmptyOctetString &octets, std::vector<int> &vec)
{
const unsigned char* pStr = &octets.front();
unsigned int length = FI::Tools::readUInt((unsigned char*)pStr);
unsigned char span = octets[4];
std::vector<Bytef> temp_result(length*4);
uLong sourceLen = static_cast<uLong>(octets.size()-5);
uLong destSize = static_cast<uLong>(temp_result.size());
const Bytef *source = (const Bytef *)(pStr + 5);
int result_code = uncompress(&temp_result.front(), &destSize, source, sourceLen);
if (result_code != Z_OK) {
std::stringstream ss;
ss << "Error while decoding DeltazlibIntArrayAlgorithm. ZLIB error code: " << result_code;
throw X3DParseException(ss.str());
}
std::vector<int> result(length);
Bytef* pRes = &temp_result.front();
for(unsigned int i = 0; i < length; i++)
{
result[i] = FI::Tools::readUInt(pRes) -1;
if (span && i >= span)
result[i] += result[i-span];
pRes+=4;
}
std::swap(result, vec);
}
void DeltazlibIntArrayAlgorithm::encode(const int* values, size_t size, FI::NonEmptyOctetString &octets, bool isImage)
{
// compute delta
char span = 0;
size_t i = 0;
int f; unsigned char *p;
std::vector<unsigned char> deltas;
if (isImage)
{
span = 0;
for(i = 0; i < size; i++)
{
int v = 1 + (values[i]);
int *vp = reinterpret_cast<int*>(&v);
f = FI::Tools::reverseBytes(vp);
p = reinterpret_cast <unsigned char*> (&f);
deltas.push_back(p[0]);
deltas.push_back(p[1]);
deltas.push_back(p[2]);
deltas.push_back(p[3]);
}
}
else
{
for (i = 0; i < 20; i++)
{
if (values[i] == -1)
{
span = static_cast<char>(i) + 1;
break;
}
}
if (!span) span = 4;
for(i = 0; i < static_cast<size_t>(span); i++)
{
int v = 1 + values[i];
int *vp = reinterpret_cast<int*>(&v);
f = FI::Tools::reverseBytes(vp);
p = reinterpret_cast <unsigned char*> (&f);
deltas.push_back(p[0]);
deltas.push_back(p[1]);
deltas.push_back(p[2]);
deltas.push_back(p[3]);
}
for(i = span; i < size; i++)
{
int v = 1 + (values[i] - values[i-span]);
f = FI::Tools::reverseBytes(&v);
p = reinterpret_cast <unsigned char*> (&f);
deltas.push_back(p[0]);
deltas.push_back(p[1]);
deltas.push_back(p[2]);
deltas.push_back(p[3]);
}
}
unsigned long compressedSize = static_cast<unsigned long>(deltas.size() + ceil(deltas.size()*0.001)) + 12;
Bytef* compressedData = new Bytef[compressedSize];
// Call zlib's compress function.
if(compress2(compressedData, &compressedSize, reinterpret_cast<const Bytef*>(&deltas[0]), static_cast<unsigned long>(deltas.size()), Z_DEFAULT_COMPRESSION) != Z_OK)
{
throw X3DParseException("Error while encoding DeltazlibIntArrayAlgorithm");
}
int size32 = static_cast<int>(size);
int size32_reversed = FI::Tools::reverseBytes(&size32);
char *s = reinterpret_cast <char*> (&size32_reversed);
octets.insert(octets.begin(), s, s+4);
octets.push_back(span);
for (i = 0; i < compressedSize; i++)
{
octets.push_back(compressedData[i]);
}
delete[] compressedData;
}
}
<commit_msg>Fixed warning<commit_after>#include <xiot/X3DFIEncodingAlgorithms.h>
#include <iostream>
#include <cmath>
#include "zlib.h"
#include <xiot/FITypes.h>
#include <xiot/FIConstants.h>
#include <xiot/X3DParseException.h>
#include <xiot/X3DFICompressionTools.h>
namespace XIOT {
std::string QuantizedzlibFloatArrayAlgorithm::decodeToString(const FI::NonEmptyOctetString &octets) const
{
std::vector<float> floatArray;
QuantizedzlibFloatArrayAlgorithm::decodeToFloatArray(octets, floatArray);
std::stringstream ss;
std::vector<float>::const_iterator I;
for(I = floatArray.begin(); I != floatArray.end() -1; I++)
{
ss << (*I) << " ";
}
ss << (*I);
return ss.str();
}
void QuantizedzlibFloatArrayAlgorithm::decodeToFloatArray(const FI::NonEmptyOctetString &octets, std::vector<float> &vec)
{
// The format for encoding the custom float format is : (-S)000EEEE|000MMMMM.
bool sign = (octets[0] & 0x80) == 0;
unsigned char exponent = octets[0] & FI::Constants::LAST_FOUR_BITS;
unsigned char mantissa = octets[1] & FI::Constants::LAST_FIVE_BITS;
int numBits = exponent + mantissa + (sign ? 1 : 0);
const unsigned char* pStr = &octets.front();
unsigned int len = FI::Tools::readUInt(pStr+2);
unsigned int numFloats = FI::Tools::readUInt(pStr+6); // = (len * 8) / (exponent + mantissa + sign);
std::vector<Bytef> temp_result(len);
uLong sourceLen = static_cast<uLong>(octets.size()-10);
uLong destSize = static_cast<uLong>(temp_result.size());
int result_code = uncompress(&temp_result.front(), &destSize, (unsigned char*)pStr + 10, sourceLen);
if (result_code != Z_OK) {
std::stringstream ss;
ss << "Error while decoding QuantizedzlibFloatArray. ZLIB error code: " << result_code;
throw X3DParseException(ss.str());
}
std::vector<float> result(numFloats);
FITools::BitUnpacker bu(&temp_result.front(), destSize);
FITools::FloatPacker fp(exponent, mantissa);
for(unsigned int i=0; i < numFloats; i++) {
unsigned long val = bu.unpack(numBits);
result[i] = fp.decode(val, sign);
}
std::swap(result, vec);
}
void QuantizedzlibFloatArrayAlgorithm::encode(const float* values, size_t size, FI::NonEmptyOctetString &octets)
{
unsigned char* bytes = new unsigned char[size*4];
unsigned char* bytepos = bytes;
size_t i;
const float* vf = values;
for (i = 0; i < size; i++)
{
union float_to_unsigned_int_to_bytes
{
float f;
unsigned int ui;
unsigned char ub[4]; // unsigned bytes
};
float_to_unsigned_int_to_bytes v;
v.f = (*vf) * 2.0f;
// Avoid -0
if (v.ui == 0x80000000)
{
v.f = 0.0f;
}
// std::cout << "value: " << v << " bytes: " << (int)s[0] << " " << (int)s[1] << " " << (int)s[2] << " " << (int)s[3]) << std::endl;
*bytepos++ = v.ub[3];
*bytepos++ = v.ub[2];
*bytepos++ = v.ub[1];
*bytepos++ = v.ub[0];
vf++;
}
// Compress the data
unsigned long compressedSize = static_cast<unsigned long>(size*4) + static_cast<unsigned long>(ceil((size*4)*0.001)) + 12;
Bytef* compressedData = new Bytef[compressedSize];
// Call zlib's compress function.
if(compress2(compressedData, &compressedSize, reinterpret_cast<const Bytef*>(bytes), static_cast<unsigned long>(size*4), Z_DEFAULT_COMPRESSION) != Z_OK)
{
throw X3DParseException("Error while encoding QuantizedzlibFloatArrayAlgorithm");
}
unsigned char *s;
// Put the number of bits for exponent
octets.push_back(static_cast<unsigned char>(8));
// Put the number of bits for mantissa
octets.push_back(static_cast<unsigned char>(23));
// Put the length
int length = static_cast<int>(size*4);
int length_reversed = FI::Tools::reverseBytes(&length);
s = reinterpret_cast <unsigned char*> (&length_reversed);
octets.insert(octets.end(), s, s+3);
// Put the number of floats
int numFloats = static_cast<int>(size);
int numFloats_reversed = FI::Tools::reverseBytes(&numFloats);;
s = reinterpret_cast <unsigned char*> (&numFloats_reversed);
octets.insert(octets.end(), s, s+3);
//octets.insert(octets.end(), s[0], s[3]);
//octets.append(s, 4);
for (i = 0; i < compressedSize; i++)
{
unsigned char c = compressedData[i];
octets.push_back(c);
}
delete[] compressedData;
delete[] bytes;
}
std::string DeltazlibIntArrayAlgorithm::decodeToString(const FI::NonEmptyOctetString &octets) const
{
std::vector<int> intArray;
DeltazlibIntArrayAlgorithm::decodeToIntArray(octets, intArray);
std::stringstream ss;
std::vector<int>::const_iterator I;
for(I = intArray.begin(); I != intArray.end() -1; I++)
{
ss << (*I) << " ";
}
ss << (*I);
return ss.str();
}
void DeltazlibIntArrayAlgorithm::decodeToIntArray(const FI::NonEmptyOctetString &octets, std::vector<int> &vec)
{
const unsigned char* pStr = &octets.front();
unsigned int length = FI::Tools::readUInt((unsigned char*)pStr);
unsigned char span = octets[4];
std::vector<Bytef> temp_result(length*4);
uLong sourceLen = static_cast<uLong>(octets.size()-5);
uLong destSize = static_cast<uLong>(temp_result.size());
const Bytef *source = (const Bytef *)(pStr + 5);
int result_code = uncompress(&temp_result.front(), &destSize, source, sourceLen);
if (result_code != Z_OK) {
std::stringstream ss;
ss << "Error while decoding DeltazlibIntArrayAlgorithm. ZLIB error code: " << result_code;
throw X3DParseException(ss.str());
}
std::vector<int> result(length);
Bytef* pRes = &temp_result.front();
for(unsigned int i = 0; i < length; i++)
{
result[i] = FI::Tools::readUInt(pRes) -1;
if (span && i >= span)
result[i] += result[i-span];
pRes+=4;
}
std::swap(result, vec);
}
void DeltazlibIntArrayAlgorithm::encode(const int* values, size_t size, FI::NonEmptyOctetString &octets, bool isImage)
{
// compute delta
char span = 0;
size_t i = 0;
int f; unsigned char *p;
std::vector<unsigned char> deltas;
if (isImage)
{
span = 0;
for(i = 0; i < size; i++)
{
int v = 1 + (values[i]);
int *vp = reinterpret_cast<int*>(&v);
f = FI::Tools::reverseBytes(vp);
p = reinterpret_cast <unsigned char*> (&f);
deltas.push_back(p[0]);
deltas.push_back(p[1]);
deltas.push_back(p[2]);
deltas.push_back(p[3]);
}
}
else
{
for (i = 0; i < 20; i++)
{
if (values[i] == -1)
{
span = static_cast<char>(i) + 1;
break;
}
}
if (!span) span = 4;
for(i = 0; i < static_cast<size_t>(span); i++)
{
int v = 1 + values[i];
int *vp = reinterpret_cast<int*>(&v);
f = FI::Tools::reverseBytes(vp);
p = reinterpret_cast <unsigned char*> (&f);
deltas.push_back(p[0]);
deltas.push_back(p[1]);
deltas.push_back(p[2]);
deltas.push_back(p[3]);
}
for(i = span; i < size; i++)
{
int v = 1 + (values[i] - values[i-span]);
f = FI::Tools::reverseBytes(&v);
p = reinterpret_cast <unsigned char*> (&f);
deltas.push_back(p[0]);
deltas.push_back(p[1]);
deltas.push_back(p[2]);
deltas.push_back(p[3]);
}
}
unsigned long compressedSize = static_cast<unsigned long>(deltas.size() + ceil(deltas.size()*0.001)) + 12;
Bytef* compressedData = new Bytef[compressedSize];
// Call zlib's compress function.
if(compress2(compressedData, &compressedSize, reinterpret_cast<const Bytef*>(&deltas[0]), static_cast<unsigned long>(deltas.size()), Z_DEFAULT_COMPRESSION) != Z_OK)
{
throw X3DParseException("Error while encoding DeltazlibIntArrayAlgorithm");
}
int size32 = static_cast<int>(size);
int size32_reversed = FI::Tools::reverseBytes(&size32);
char *s = reinterpret_cast <char*> (&size32_reversed);
octets.insert(octets.begin(), s, s+4);
octets.push_back(span);
for (i = 0; i < compressedSize; i++)
{
octets.push_back(compressedData[i]);
}
delete[] compressedData;
}
}
<|endoftext|> |
<commit_before>#include "stdafx.h"
#include "helpers.h"
#include "render_to_window.h"
static VkBool32 debug_report_callback(
VkDebugUtilsMessageSeverityFlagBitsEXT messageSeverity,
VkDebugUtilsMessageTypeFlagsEXT messageTypes,
const VkDebugUtilsMessengerCallbackDataEXT* pCallbackData,
void* pUserData)
{
std::cerr << pCallbackData->pMessage << std::endl;
return false;
}
static std::optional<vk::UniqueDebugUtilsMessengerEXT> create_debug_report_callback(vk::Instance instance)
{
#if _DEBUG
auto info = vk::DebugUtilsMessengerCreateInfoEXT()
.setMessageSeverity(
vk::DebugUtilsMessageSeverityFlagBitsEXT::eError|
vk::DebugUtilsMessageSeverityFlagBitsEXT::eWarning
)
.setMessageType(
vk::DebugUtilsMessageTypeFlagBitsEXT::eGeneral|
vk::DebugUtilsMessageTypeFlagBitsEXT::ePerformance|
vk::DebugUtilsMessageTypeFlagBitsEXT::eValidation
)
.setPfnUserCallback(debug_report_callback);
return std::optional { instance.createDebugUtilsMessengerEXTUnique(info, nullptr) };
#else
return std::nullopt;
#endif
}
static vk::UniqueInstance create_instance()
{
#if _DEBUG
std::array layerNames { "VK_LAYER_KHRONOS_validation" };
#else
std::array<const char*, 0> layerNames;
#endif
std::array extensionNames {
#if _DEBUG
VK_EXT_DEBUG_UTILS_EXTENSION_NAME,
#endif
VK_KHR_SURFACE_EXTENSION_NAME,
VK_KHR_WIN32_SURFACE_EXTENSION_NAME,
VK_KHR_GET_PHYSICAL_DEVICE_PROPERTIES_2_EXTENSION_NAME,
};
auto app_info = vk::ApplicationInfo().setApiVersion(VK_API_VERSION_1_1);
return vk::createInstanceUnique(
vk::InstanceCreateInfo()
.setPEnabledLayerNames(layerNames)
.setPEnabledExtensionNames(extensionNames)
.setPApplicationInfo(&app_info)
);
}
static vk::PhysicalDevice get_physical_device(vk::Instance vulkan)
{
auto devices = vulkan.enumeratePhysicalDevices();
assert(devices.size() > 0);
auto device = devices[0];
auto props = device.getProperties();
std::cout << "Using physical device " << props.deviceName << std::endl;
return device;
}
static vk::UniqueDevice create_device(vk::PhysicalDevice physical_device)
{
auto props = physical_device.getQueueFamilyProperties();
assert((props[0].queueFlags & vk::QueueFlagBits::eGraphics) == vk::QueueFlagBits::eGraphics);
std::array priorities { 0.f };
auto queueInfo = vk::DeviceQueueCreateInfo()
.setQueuePriorities(priorities);
std::array extensionNames {
VK_KHR_SWAPCHAIN_EXTENSION_NAME,
VK_KHR_GET_MEMORY_REQUIREMENTS_2_EXTENSION_NAME,
VK_NV_RAY_TRACING_EXTENSION_NAME,
};
auto features = vk::PhysicalDeviceFeatures()
.setMultiDrawIndirect(true)
.setDrawIndirectFirstInstance(true)
.setShaderClipDistance(true)
.setShaderCullDistance(true);
return physical_device.createDeviceUnique(
vk::DeviceCreateInfo()
.setQueueCreateInfoCount(1)
.setPQueueCreateInfos(&queueInfo)
.setPEnabledExtensionNames(extensionNames)
.setPEnabledFeatures(&features)
);
}
glm::vec3 std_vector_to_glm_vec3(const std::vector<float>& vector)
{
return glm::vec3(vector[0], vector[1], vector[2]);
}
VULKAN_HPP_DEFAULT_DISPATCH_LOADER_DYNAMIC_STORAGE
int main(int argc, char** argv)
{
cxxopts::Options options("VulkanRenderer", "Vulkan renderer");
options.add_options()
("model", "PLY model to render. File dialog will be shown if ommitted.", cxxopts::value<std::string>(), "path")
("image", "PNG image to save rendering to (overwrites existing). No window will be created if specified.", cxxopts::value<std::string>(), "path")
("camera_position", "When using --image, specifies the camera position.", cxxopts::value<std::vector<float>>(), "x y z")
("camera_up", "When using --image, specifies the camera up vector.", cxxopts::value<std::vector<float>>(), "x y z")
("help", "Show help")
;
cxxopts::ParseResult result = options.parse(argc, argv);
if (result["help"].count() > 0) {
std::cout << options.help();
return EXIT_SUCCESS;
}
std::string model_path;
auto model_path_option = result["model"];
if (model_path_option.count() == 1)
{
model_path = model_path_option.as<std::string>();
}
else
{
auto pattern = "*.ply";
auto model_path_ptr = tinyfd_openFileDialog("Open 3D model", nullptr, 1, &pattern, nullptr, 0);
if (!model_path_ptr)
{
return EXIT_FAILURE;
}
model_path = model_path_ptr;
}
vk::DynamicLoader dl;
VULKAN_HPP_DEFAULT_DISPATCHER.init(dl.getProcAddress<PFN_vkGetInstanceProcAddr>("vkGetInstanceProcAddr"));
auto instance = create_instance();
VULKAN_HPP_DEFAULT_DISPATCHER.init(instance.get());
auto callback = create_debug_report_callback(instance.get());
auto physical_device = get_physical_device(instance.get());
auto device = create_device(physical_device);
VULKAN_HPP_DEFAULT_DISPATCHER.init(device.get());
auto image_path_option = result["image"];
if (image_path_option.count() == 1)
{
auto camera_position_option = result["camera_position"];
auto camera_position = camera_position_option.count() == 3
? std_vector_to_glm_vec3(camera_position_option.as<std::vector<float>>())
: glm::vec3(0.f, 0.f, 2.f);
auto camera_up_vector = result["camera_up"];
auto camera_up = camera_up_vector.count() == 3
? std_vector_to_glm_vec3(camera_up_vector.as<std::vector<float>>())
: glm::vec3(0.f, -1.f, 0.f);
std::cout << "Rendering to image..." << std::endl;
render_to_image(physical_device, device.get(), model_path, image_path_option.as<std::string>(), camera_position, camera_up);
}
else
{
std::cout << "Rendering to window..." << std::endl;
render_to_window(instance.get(), physical_device, device.get(), model_path);
}
return EXIT_SUCCESS;
}
<commit_msg>Make validation messages more readable<commit_after>#include "stdafx.h"
#include "helpers.h"
#include "render_to_window.h"
static VkBool32 debug_report_callback(
VkDebugUtilsMessageSeverityFlagBitsEXT messageSeverity,
VkDebugUtilsMessageTypeFlagsEXT messageTypes,
const VkDebugUtilsMessengerCallbackDataEXT* pCallbackData,
void* pUserData)
{
std::cerr << pCallbackData->pMessage << std::endl << std::endl;
return false;
}
static std::optional<vk::UniqueDebugUtilsMessengerEXT> create_debug_report_callback(vk::Instance instance)
{
#if _DEBUG
auto info = vk::DebugUtilsMessengerCreateInfoEXT()
.setMessageSeverity(
vk::DebugUtilsMessageSeverityFlagBitsEXT::eError|
vk::DebugUtilsMessageSeverityFlagBitsEXT::eWarning
)
.setMessageType(
vk::DebugUtilsMessageTypeFlagBitsEXT::eGeneral|
vk::DebugUtilsMessageTypeFlagBitsEXT::ePerformance|
vk::DebugUtilsMessageTypeFlagBitsEXT::eValidation
)
.setPfnUserCallback(debug_report_callback);
return std::optional { instance.createDebugUtilsMessengerEXTUnique(info, nullptr) };
#else
return std::nullopt;
#endif
}
static vk::UniqueInstance create_instance()
{
#if _DEBUG
std::array layerNames { "VK_LAYER_KHRONOS_validation" };
#else
std::array<const char*, 0> layerNames;
#endif
std::array extensionNames {
#if _DEBUG
VK_EXT_DEBUG_UTILS_EXTENSION_NAME,
#endif
VK_KHR_SURFACE_EXTENSION_NAME,
VK_KHR_WIN32_SURFACE_EXTENSION_NAME,
VK_KHR_GET_PHYSICAL_DEVICE_PROPERTIES_2_EXTENSION_NAME,
};
auto app_info = vk::ApplicationInfo().setApiVersion(VK_API_VERSION_1_1);
return vk::createInstanceUnique(
vk::InstanceCreateInfo()
.setPEnabledLayerNames(layerNames)
.setPEnabledExtensionNames(extensionNames)
.setPApplicationInfo(&app_info)
);
}
static vk::PhysicalDevice get_physical_device(vk::Instance vulkan)
{
auto devices = vulkan.enumeratePhysicalDevices();
assert(devices.size() > 0);
auto device = devices[0];
auto props = device.getProperties();
std::cout << "Using physical device " << props.deviceName << std::endl;
return device;
}
static vk::UniqueDevice create_device(vk::PhysicalDevice physical_device)
{
auto props = physical_device.getQueueFamilyProperties();
assert((props[0].queueFlags & vk::QueueFlagBits::eGraphics) == vk::QueueFlagBits::eGraphics);
std::array priorities { 0.f };
auto queueInfo = vk::DeviceQueueCreateInfo()
.setQueuePriorities(priorities);
std::array extensionNames {
VK_KHR_SWAPCHAIN_EXTENSION_NAME,
VK_KHR_GET_MEMORY_REQUIREMENTS_2_EXTENSION_NAME,
VK_NV_RAY_TRACING_EXTENSION_NAME,
};
auto features = vk::PhysicalDeviceFeatures()
.setMultiDrawIndirect(true)
.setDrawIndirectFirstInstance(true)
.setShaderClipDistance(true)
.setShaderCullDistance(true);
return physical_device.createDeviceUnique(
vk::DeviceCreateInfo()
.setQueueCreateInfoCount(1)
.setPQueueCreateInfos(&queueInfo)
.setPEnabledExtensionNames(extensionNames)
.setPEnabledFeatures(&features)
);
}
glm::vec3 std_vector_to_glm_vec3(const std::vector<float>& vector)
{
return glm::vec3(vector[0], vector[1], vector[2]);
}
VULKAN_HPP_DEFAULT_DISPATCH_LOADER_DYNAMIC_STORAGE
int main(int argc, char** argv)
{
cxxopts::Options options("VulkanRenderer", "Vulkan renderer");
options.add_options()
("model", "PLY model to render. File dialog will be shown if ommitted.", cxxopts::value<std::string>(), "path")
("image", "PNG image to save rendering to (overwrites existing). No window will be created if specified.", cxxopts::value<std::string>(), "path")
("camera_position", "When using --image, specifies the camera position.", cxxopts::value<std::vector<float>>(), "x y z")
("camera_up", "When using --image, specifies the camera up vector.", cxxopts::value<std::vector<float>>(), "x y z")
("help", "Show help")
;
cxxopts::ParseResult result = options.parse(argc, argv);
if (result["help"].count() > 0) {
std::cout << options.help();
return EXIT_SUCCESS;
}
std::string model_path;
auto model_path_option = result["model"];
if (model_path_option.count() == 1)
{
model_path = model_path_option.as<std::string>();
}
else
{
auto pattern = "*.ply";
auto model_path_ptr = tinyfd_openFileDialog("Open 3D model", nullptr, 1, &pattern, nullptr, 0);
if (!model_path_ptr)
{
return EXIT_FAILURE;
}
model_path = model_path_ptr;
}
vk::DynamicLoader dl;
VULKAN_HPP_DEFAULT_DISPATCHER.init(dl.getProcAddress<PFN_vkGetInstanceProcAddr>("vkGetInstanceProcAddr"));
auto instance = create_instance();
VULKAN_HPP_DEFAULT_DISPATCHER.init(instance.get());
auto callback = create_debug_report_callback(instance.get());
auto physical_device = get_physical_device(instance.get());
auto device = create_device(physical_device);
VULKAN_HPP_DEFAULT_DISPATCHER.init(device.get());
auto image_path_option = result["image"];
if (image_path_option.count() == 1)
{
auto camera_position_option = result["camera_position"];
auto camera_position = camera_position_option.count() == 3
? std_vector_to_glm_vec3(camera_position_option.as<std::vector<float>>())
: glm::vec3(0.f, 0.f, 2.f);
auto camera_up_vector = result["camera_up"];
auto camera_up = camera_up_vector.count() == 3
? std_vector_to_glm_vec3(camera_up_vector.as<std::vector<float>>())
: glm::vec3(0.f, -1.f, 0.f);
std::cout << "Rendering to image..." << std::endl;
render_to_image(physical_device, device.get(), model_path, image_path_option.as<std::string>(), camera_position, camera_up);
}
else
{
std::cout << "Rendering to window..." << std::endl;
render_to_window(instance.get(), physical_device, device.get(), model_path);
}
return EXIT_SUCCESS;
}
<|endoftext|> |
<commit_before>// Copyright (c) 2011, Cornell University
// 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 HyperDex 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.
// Google Test
#include <gtest/gtest.h>
// HyperDex
#include <hyperdex/query.h>
#pragma GCC diagnostic ignored "-Wswitch-default"
namespace
{
// Create and destroy queries of various sizes.
TEST(QueryTest, CtorAndDtor)
{
for (size_t i = 0; i < 65536; ++i)
{
hyperdex::query q(i);
}
}
// Create a query and set/unset the values while testing that it still matches
// the row.
TEST(QueryTest, SetAndUnset)
{
hyperdex::query q(10);
std::vector<std::string> row(10, "value");
for (size_t i = 0; i < 10; ++i)
{
EXPECT_TRUE(q.matches(row));
q.set(i, "value");
}
EXPECT_TRUE(q.matches(row));
for (size_t i = 0; i < 10; ++i)
{
EXPECT_TRUE(q.matches(row));
q.set(i, "value");
}
EXPECT_TRUE(q.matches(row));
}
TEST(QueryTest, Clear)
{
hyperdex::query q(2);
std::vector<std::string> r;
r.push_back("key");
r.push_back("val");
EXPECT_TRUE(q.matches(r));
q.set(0, "not-key");
q.set(1, "not-val");
EXPECT_FALSE(q.matches(r));
q.clear();
EXPECT_TRUE(q.matches(r));
}
// Test non-matches
TEST(QueryTest, NegativeMatch)
{
hyperdex::query q(2);
std::vector<std::string> r;
r.push_back("key");
r.push_back("val");
EXPECT_TRUE(q.matches(r));
q.set(0, "not-key");
EXPECT_FALSE(q.matches(r));
q.unset(0);
EXPECT_TRUE(q.matches(r));
q.set(1, "not-val");
EXPECT_FALSE(q.matches(r));
}
// If we try to set out of bounds we fail an assertion.
TEST(QueryTest, SetDeathTest)
{
hyperdex::query q(5);
ASSERT_DEATH(
q.set(5, "out of bounds");
, "Assertion");
}
// If we try to unset out of bounds we fail an assertion.
TEST(QueryTest, UnsetDeathTest)
{
hyperdex::query q(5);
ASSERT_DEATH(
q.unset(5);
, "Assertion");
}
// If we try to match with improper arity we fail an assertion.
TEST(QueryTest, MatchDeathTest)
{
hyperdex::query q(5);
ASSERT_DEATH(
q.matches(std::vector<std::string>(4));
, "Assertion");
}
} // namespace
<commit_msg>Cut down the runtime of the QueryTest cases.<commit_after>// Copyright (c) 2011, Cornell University
// 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 HyperDex 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.
// Google Test
#include <gtest/gtest.h>
// HyperDex
#include <hyperdex/query.h>
#pragma GCC diagnostic ignored "-Wswitch-default"
namespace
{
// Create and destroy queries of various sizes.
TEST(QueryTest, CtorAndDtor)
{
for (size_t i = 1; i < 65536; i *= 2)
{
hyperdex::query q(i);
}
}
// Create a query and set/unset the values while testing that it still matches
// the row.
TEST(QueryTest, SetAndUnset)
{
hyperdex::query q(10);
std::vector<std::string> row(10, "value");
for (size_t i = 0; i < 10; ++i)
{
EXPECT_TRUE(q.matches(row));
q.set(i, "value");
}
EXPECT_TRUE(q.matches(row));
for (size_t i = 0; i < 10; ++i)
{
EXPECT_TRUE(q.matches(row));
q.set(i, "value");
}
EXPECT_TRUE(q.matches(row));
}
TEST(QueryTest, Clear)
{
hyperdex::query q(2);
std::vector<std::string> r;
r.push_back("key");
r.push_back("val");
EXPECT_TRUE(q.matches(r));
q.set(0, "not-key");
q.set(1, "not-val");
EXPECT_FALSE(q.matches(r));
q.clear();
EXPECT_TRUE(q.matches(r));
}
// Test non-matches
TEST(QueryTest, NegativeMatch)
{
hyperdex::query q(2);
std::vector<std::string> r;
r.push_back("key");
r.push_back("val");
EXPECT_TRUE(q.matches(r));
q.set(0, "not-key");
EXPECT_FALSE(q.matches(r));
q.unset(0);
EXPECT_TRUE(q.matches(r));
q.set(1, "not-val");
EXPECT_FALSE(q.matches(r));
}
// If we try to set out of bounds we fail an assertion.
TEST(QueryTest, SetDeathTest)
{
hyperdex::query q(5);
ASSERT_DEATH(
q.set(5, "out of bounds");
, "Assertion");
}
// If we try to unset out of bounds we fail an assertion.
TEST(QueryTest, UnsetDeathTest)
{
hyperdex::query q(5);
ASSERT_DEATH(
q.unset(5);
, "Assertion");
}
// If we try to match with improper arity we fail an assertion.
TEST(QueryTest, MatchDeathTest)
{
hyperdex::query q(5);
ASSERT_DEATH(
q.matches(std::vector<std::string>(4));
, "Assertion");
}
} // namespace
<|endoftext|> |
<commit_before>/*
* The Apache Software License, Version 1.1
*
*
* Copyright (c) 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 "Xalan" 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 [email protected].
*
* 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/>.
*/
#include "FunctionSubstring.hpp"
#include <PlatformSupport/DoubleSupport.hpp>
#include "XObjectFactory.hpp"
const XObjectPtr FunctionSubstring::s_nullXObjectPtr;
FunctionSubstring::FunctionSubstring()
{
}
FunctionSubstring::~FunctionSubstring()
{
}
/*
* Get the value for the start index (C-style, not XPath).
*/
inline XalanDOMString::size_type
getStartIndex(double theSecondArgValue)
{
// We always subtract 1 for C-style index, since XPath indexes from 1.
// Anything less than, or equal to 1 is 0.
if (theSecondArgValue <= 1)
{
return 0;
}
else
{
return XalanDOMString::size_type(DoubleSupport::round(theSecondArgValue)) - 1;
}
}
/*
* Get the length of the substring.
*/
inline XalanDOMString::size_type
getSubstringLength(
XalanDOMString::size_type theSourceStringLength,
XalanDOMString::size_type theStartIndex,
double theThirdArgValue)
{
// The last index must be less than theThirdArgValue. Since it has
// already been rounded, subtracting 1 will do the job.
const XalanDOMString::size_type theLastIndex = XalanDOMString::size_type(theThirdArgValue - 1);
if (theLastIndex >= theSourceStringLength)
{
return theSourceStringLength - theStartIndex;
}
else
{
return theLastIndex - theStartIndex;
}
}
/*
* Get the total of the second and third arguments.
*/
inline double
getTotal(
XalanDOMString::size_type theSourceStringLength,
double theSecondArgValue,
const XObjectPtr& arg3)
{
// Total the second and third arguments. Ithe third argument is
// missing, make it the length of the string + 1 (for XPath
// indexing style).
if (arg3.null() == true)
{
return double(theSourceStringLength + 1);
}
else
{
const double theRoundedValue =
DoubleSupport::round(theSecondArgValue + arg3->num());
// If there's overflow, then we should return the length of the string + 1.
if (DoubleSupport::isPositiveInfinity(theRoundedValue) == true)
{
return double(theSourceStringLength + 1);
}
else
{
return theRoundedValue;
}
}
}
static const XalanDOMString theEmptyString;
inline XObjectPtr
createEmptyString(XPathExecutionContext& executionContext)
{
return executionContext.getXObjectFactory().createString(theEmptyString);
}
XObjectPtr
FunctionSubstring::execute(
XPathExecutionContext& executionContext,
XalanNode* context,
const XObjectPtr arg1,
const XObjectPtr arg2,
const Locator* locator) const
{
assert(arg1.null() == false && arg2.null() == false);
return execute(executionContext, context, arg1, arg2, s_nullXObjectPtr, locator);
}
XObjectPtr
FunctionSubstring::execute(
XPathExecutionContext& executionContext,
XalanNode* /* context */,
const XObjectPtr arg1,
const XObjectPtr arg2,
const XObjectPtr arg3,
const Locator* /* locator */) const
{
assert(arg1.null() == false && arg2.null() == false);
const XalanDOMString& theSourceString = arg1->str();
const XalanDOMString::size_type theSourceStringLength = length(theSourceString);
if (theSourceStringLength == 0)
{
return createEmptyString(executionContext);
}
else
{
// Get the value of the second argument...
const double theSecondArgValue =
DoubleSupport::round(arg2->num());
// XPath indexes from 1, so this is the first XPath index....
const XalanDOMString::size_type theStartIndex = getStartIndex(theSecondArgValue);
if (theStartIndex >= theSourceStringLength)
{
return createEmptyString(executionContext);
}
else
{
const double theTotal =
getTotal(theSourceStringLength, theSecondArgValue, arg3);
if (DoubleSupport::isNaN(theSecondArgValue) == true ||
DoubleSupport::isNaN(theTotal) == true ||
DoubleSupport::isNegativeInfinity(theTotal) == true ||
theTotal < double(theStartIndex))
{
return createEmptyString(executionContext);
}
else
{
const XalanDOMString::size_type theSubstringLength =
getSubstringLength(
theSourceStringLength,
theStartIndex,
theTotal);
XPathExecutionContext::GetAndReleaseCachedString theResult(executionContext);
XalanDOMString& theString = theResult.get();
assign(
theString,
toCharArray(theSourceString) + theStartIndex,
theSubstringLength);
return executionContext.getXObjectFactory().createString(theResult);
}
}
}
}
#if defined(XALAN_NO_COVARIANT_RETURN_TYPE)
Function*
#else
FunctionSubstring*
#endif
FunctionSubstring::clone() const
{
return new FunctionSubstring(*this);
}
const XalanDOMString
FunctionSubstring::getError() const
{
return StaticStringToDOMString(XALAN_STATIC_UCODE_STRING("The substring() function takes two or three arguments!"));
}
<commit_msg>Fixed 64-bit HP problem.<commit_after>/*
* The Apache Software License, Version 1.1
*
*
* Copyright (c) 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 "Xalan" 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 [email protected].
*
* 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/>.
*/
#include "FunctionSubstring.hpp"
#include <PlatformSupport/DoubleSupport.hpp>
#include "XObjectFactory.hpp"
const XObjectPtr FunctionSubstring::s_nullXObjectPtr;
FunctionSubstring::FunctionSubstring()
{
}
FunctionSubstring::~FunctionSubstring()
{
}
/*
* Get the value for the start index (C-style, not XPath).
*/
inline XalanDOMString::size_type
getStartIndex(
double theSecondArgValue,
XalanDOMString::size_type theStringLength)
{
// We always subtract 1 for C-style index, since XPath indexes from 1.
// Anything less than, or equal to 1 is 0.
if (theSecondArgValue <= 1 ||
DoubleSupport::isNaN(theSecondArgValue) == true)
{
return 0;
}
else if (DoubleSupport::isPositiveInfinity(theSecondArgValue) == true)
{
return theStringLength;
}
else
{
return XalanDOMString::size_type(DoubleSupport::round(theSecondArgValue)) - 1;
}
}
/*
* Get the length of the substring.
*/
inline XalanDOMString::size_type
getSubstringLength(
XalanDOMString::size_type theSourceStringLength,
XalanDOMString::size_type theStartIndex,
double theThirdArgValue)
{
// The last index must be less than theThirdArgValue. Since it has
// already been rounded, subtracting 1 will do the job.
const XalanDOMString::size_type theLastIndex = XalanDOMString::size_type(theThirdArgValue - 1);
if (theLastIndex >= theSourceStringLength)
{
return theSourceStringLength - theStartIndex;
}
else
{
return theLastIndex - theStartIndex;
}
}
/*
* Get the total of the second and third arguments.
*/
inline double
getTotal(
XalanDOMString::size_type theSourceStringLength,
double theSecondArgValue,
const XObjectPtr& arg3)
{
// Total the second and third arguments. Ithe third argument is
// missing, make it the length of the string + 1 (for XPath
// indexing style).
if (arg3.null() == true)
{
return double(theSourceStringLength + 1);
}
else
{
const double theRoundedValue =
DoubleSupport::round(theSecondArgValue + arg3->num());
// If there's overflow, then we should return the length of the string + 1.
if (DoubleSupport::isPositiveInfinity(theRoundedValue) == true)
{
return double(theSourceStringLength + 1);
}
else
{
return theRoundedValue;
}
}
}
static const XalanDOMString theEmptyString;
inline XObjectPtr
createEmptyString(XPathExecutionContext& executionContext)
{
return executionContext.getXObjectFactory().createString(theEmptyString);
}
XObjectPtr
FunctionSubstring::execute(
XPathExecutionContext& executionContext,
XalanNode* context,
const XObjectPtr arg1,
const XObjectPtr arg2,
const Locator* locator) const
{
assert(arg1.null() == false && arg2.null() == false);
return execute(executionContext, context, arg1, arg2, s_nullXObjectPtr, locator);
}
XObjectPtr
FunctionSubstring::execute(
XPathExecutionContext& executionContext,
XalanNode* /* context */,
const XObjectPtr arg1,
const XObjectPtr arg2,
const XObjectPtr arg3,
const Locator* /* locator */) const
{
assert(arg1.null() == false && arg2.null() == false);
const XalanDOMString& theSourceString = arg1->str();
const XalanDOMString::size_type theSourceStringLength = length(theSourceString);
if (theSourceStringLength == 0)
{
return createEmptyString(executionContext);
}
else
{
// Get the value of the second argument...
const double theSecondArgValue =
DoubleSupport::round(arg2->num());
// XPath indexes from 1, so this is the first XPath index....
const XalanDOMString::size_type theStartIndex = getStartIndex(theSecondArgValue, theSourceStringLength);
if (theStartIndex >= theSourceStringLength)
{
return createEmptyString(executionContext);
}
else
{
const double theTotal =
getTotal(theSourceStringLength, theSecondArgValue, arg3);
if (DoubleSupport::isNaN(theSecondArgValue) == true ||
DoubleSupport::isNaN(theTotal) == true ||
DoubleSupport::isNegativeInfinity(theTotal) == true ||
theTotal < double(theStartIndex))
{
return createEmptyString(executionContext);
}
else
{
const XalanDOMString::size_type theSubstringLength =
getSubstringLength(
theSourceStringLength,
theStartIndex,
theTotal);
XPathExecutionContext::GetAndReleaseCachedString theResult(executionContext);
XalanDOMString& theString = theResult.get();
assign(
theString,
toCharArray(theSourceString) + theStartIndex,
theSubstringLength);
return executionContext.getXObjectFactory().createString(theResult);
}
}
}
}
#if defined(XALAN_NO_COVARIANT_RETURN_TYPE)
Function*
#else
FunctionSubstring*
#endif
FunctionSubstring::clone() const
{
return new FunctionSubstring(*this);
}
const XalanDOMString
FunctionSubstring::getError() const
{
return StaticStringToDOMString(XALAN_STATIC_UCODE_STRING("The substring() function takes two or three arguments!"));
}
<|endoftext|> |
<commit_before>/**
* @file ex6.cpp
* @author Fabian Wegscheider
* @date Jun 20, 2017
*/
#include <iostream>
#include <fstream>
#include <boost/program_options.hpp>
#include <boost/heap/fibonacci_heap.hpp>
#include <boost/timer/timer.hpp>
#include <boost/graph/adjacency_list.hpp>
#include <boost/graph/graph_traits.hpp>
#include <boost/graph/dijkstra_shortest_paths.hpp>
#include <boost/algorithm/string.hpp>
#include <boost/spirit/include/qi.hpp>
using namespace std;
using namespace boost;
namespace po = boost::program_options;
typedef adjacency_list<vecS, vecS, undirectedS,
no_property, property<edge_weight_t, double>> Graph;
typedef graph_traits<Graph>::vertex_descriptor Vertex;
typedef pair<int,int> Edge;
typedef pair<int, double> Pair;
typename graph_traits<Graph>::out_edge_iterator out_i, out_end;
/*
* Data that is stored in one node of a heap. Contains an integer and a double.
* Comparisons are made by the double, smaller has higher priority
*/
struct heap_data
{
heap::fibonacci_heap<heap_data>::handle_type handle;
Pair pair;
heap_data(Pair p):
pair(p)
{}
bool operator<(heap_data const & rhs) const {
return pair.second > rhs.pair.second;
}
};
using Heap = heap::fibonacci_heap<heap_data>;
/**
* My own implementation of Dijkstra using a fibonacci heap from boost
* @param g the graph which is an adjacency_list from boost
* @param numVertices the number of vertices in g
* @param source the source node for Dijkstra
* @return vector of resulting distances to source
*/
vector<double> myDijkstra(Graph g, int numVertices, int source) {
vector<double> distances(numVertices);
distances[0] = 0;
Heap heap;
Heap::handle_type *handles = new Heap::handle_type[numVertices];
handles[0] = heap.push(make_pair(0,0.));
//initialization of the heap
for (int i = 1; i < numVertices; ++i) {
handles[i] = heap.push(make_pair(i, numeric_limits<double>::infinity()));
distances[i] = numeric_limits<double>::infinity();
}
property_map<Graph, edge_weight_t>::type weights = get(edge_weight, g);
property_map<Graph, vertex_index_t>::type index = get(vertex_index, g);
//the actual algorithm
while (!heap.empty()) {
Pair min = heap.top().pair;
heap.pop();
for (tie(out_i, out_end) = out_edges(*(vertices(g).first+min.first), g);
out_i != out_end; ++out_i) {
double tmp = min.second + weights[*out_i];
int targetIndex = index[target(*out_i, g)];
if (tmp < distances[targetIndex]) {
distances[targetIndex] = tmp;
(*handles[targetIndex]).pair.second = tmp;
heap.increase(handles[targetIndex]);
}
}
}
return distances;
}
// split(parts, line, is_any_of(" "));
// if (parts.size() != 3) {
// cerr << "error in line " << (i+2) << ": line should consists of "
// "two integers and a double!" << endl;
// exit(EXIT_FAILURE);
// }
/**
* main function which reads a graph from a .gph file, then calculates shortest
* paths from all vertices to the first vertex with the dijsktra algorithm
* and prints the furthest vertex together with its distance
* to the standard output
* @param numargs number of inputs on command line
* @param args array of * inputs on command line
* @return whether the function operated successfully
*/
int main(int numargs, char *args[]) {
timer::cpu_timer t;
bool useOwnMethod;
/*parsing command line options*/
po::options_description desc("Allowed options");
desc.add_options()
("help,h", "produce help message")
("m1", "use my own dijkstra method")
("m2", "use dijkstra method from boost")
("input-file", po::value< string >(), "input file");
po::positional_options_description p;
p.add("input-file", -1);
po::variables_map vm;
po::store(po::command_line_parser(numargs, args).
options(desc).positional(p).run(), vm);
po::notify(vm);
if (vm.count("help")) {
cout << desc << "\n";
exit(EXIT_SUCCESS);
}
if (vm.count("m1") && !vm.count("m2")) {
useOwnMethod = true;
cout << "using my own method for calculation..." << endl << endl;
} else if (vm.count("m2") && !vm.count("m1")) {
useOwnMethod = false;
cout << "using boost method for calculation..." << endl << endl;
} else {
cerr << "please specify the method you want to use (type -h for help)" << endl;
exit(EXIT_FAILURE);
}
string input;
if (vm.count("input-file")) {
input = vm["input-file"].as< string >();
} else {
cerr << "please specify an input file in the .gph format" << endl;
exit(EXIT_FAILURE);
}
/*end of parsing command line options*/
ifstream inputFile;
inputFile.open(input); //trying to read file
if (inputFile.fail()) {
cerr << "file could not be read" << endl;
exit(EXIT_FAILURE);
}
int numVertices;
int numEdges;
string line;
getline(inputFile, line); //first line is read
vector<string> parts;
split(parts, line, is_any_of(" "));
if (parts.size() != 2) {
cerr << "error in file: first line should consist of two integers!" << endl;
exit(EXIT_FAILURE);
}
try {
numVertices = stoi(parts[0]); //information from the first line
numEdges = stoi(parts[1]); //are stored
} catch (...) {
cerr << "error in file: first line should consist of two integers!" << endl;
exit(EXIT_FAILURE);
}
Edge *edges = new Edge[numEdges]; //in these arrays all information about
double *weights = new double[numEdges]; //the edges are stored
int i = 0;
using namespace boost::spirit;
using qi::int_;
using qi::double_;
using qi::phrase_parse;
using ascii::space;
//read line by line using boost to parse each line to int,int,double
while (getline(inputFile, line)) {
try {
auto it = line.begin();
int start;
int end;
double weight;
bool success = phrase_parse(it, line.end(),
int_[([&start](int j){ start = j; })]
>> int_[([&end](int j){ end = j; })]
>> double_[([&weight](double j){ weight = j; })], space);
if (success && it == line.end()) {
edges[i] = Edge(start-1, end-1);
weights[i] = weight;
} else {
cerr << "error in line " << (i+2) << ": line should consists of "
"two integers and a double!" << endl;
exit(EXIT_FAILURE);
}
} catch(...) {
cerr << "error in line " << (i+2) << ": line should consists of "
"two integers and a double!" << endl;
exit(EXIT_FAILURE);
}
++i;
}
//undirected graph is constructed with all edges and their weights
Graph g(edges, edges + numEdges , weights, numVertices);
//in this vector the resulting distances from dijkstra are stored
vector<double> distances;
//call of dijsktra depending on chosen option
if (!useOwnMethod) {
distances.resize(numVertices);
dijkstra_shortest_paths(g, *(vertices(g).first), distance_map(&distances[0]));
} else {
distances = myDijkstra(g, numVertices, 0);
}
double maxDist = 0;
int maxIdx = 0;
//search for furthest vertex
for (int i = 1; i < numVertices; i++) {
double tmp = distances[i];
if (tmp > maxDist) {
maxDist = tmp;
maxIdx = i;
}
}
//results are printed to command line
cout << "RESULT VERTEX " << (maxIdx+1) << endl;
cout << "RESULT DIST " << maxDist << endl;
cout << endl << "running time: " << t.format() << endl;
exit(EXIT_SUCCESS);
}
<commit_msg>fixed another bug<commit_after>/**
* @file ex6.cpp
* @author Fabian Wegscheider
* @date Jun 20, 2017
*/
#include <iostream>
#include <fstream>
#include <boost/program_options.hpp>
#include <boost/heap/fibonacci_heap.hpp>
#include <boost/timer/timer.hpp>
#include <boost/graph/adjacency_list.hpp>
#include <boost/graph/graph_traits.hpp>
#include <boost/graph/dijkstra_shortest_paths.hpp>
#include <boost/algorithm/string.hpp>
#include <boost/spirit/include/qi.hpp>
using namespace std;
using namespace boost;
namespace po = boost::program_options;
typedef adjacency_list<vecS, vecS, undirectedS,
no_property, property<edge_weight_t, double>> Graph;
typedef graph_traits<Graph>::vertex_descriptor Vertex;
typedef pair<int,int> Edge;
typedef pair<int, double> Pair;
typename graph_traits<Graph>::out_edge_iterator out_i, out_end;
/**
* Data that is stored in one node of a heap. Contains an integer and a double.
* Comparisons are made by the double, smaller has higher priority
*/
struct heap_data
{
heap::fibonacci_heap<heap_data>::handle_type handle;
Pair pair;
heap_data(Pair p):
pair(p)
{}
bool operator<(heap_data const & rhs) const {
return pair.second > rhs.pair.second;
}
};
using Heap = heap::fibonacci_heap<heap_data>;
/**
* My own implementation of Dijkstra using a fibonacci heap from boost
* @param g the graph which is an adjacency_list from boost
* @param numVertices the number of vertices in g
* @param source the source node for Dijkstra
* @return vector of resulting distances to source
*/
vector<double> myDijkstra(Graph g, int numVertices, int source) {
vector<double> distances(numVertices);
distances[0] = 0;
Heap heap;
Heap::handle_type *handles = new Heap::handle_type[numVertices];
handles[0] = heap.push(make_pair(0,0.));
//initialization of the heap
for (int i = 1; i < numVertices; ++i) {
handles[i] = heap.push(make_pair(i, numeric_limits<double>::infinity()));
distances[i] = numeric_limits<double>::infinity();
}
property_map<Graph, edge_weight_t>::type weights = get(edge_weight, g);
property_map<Graph, vertex_index_t>::type index = get(vertex_index, g);
//the actual algorithm
while (!heap.empty()) {
Pair min = heap.top().pair;
heap.pop();
for (tie(out_i, out_end) = out_edges(*(vertices(g).first+min.first), g);
out_i != out_end; ++out_i) {
double tmp = min.second + weights[*out_i];
int targetIndex = index[target(*out_i, g)];
if (tmp < distances[targetIndex]) {
distances[targetIndex] = tmp;
(*handles[targetIndex]).pair.second = tmp;
heap.increase(handles[targetIndex]);
}
}
}
delete[] handles;
return distances;
}
/**
* main function which reads a graph from a .gph file, then calculates shortest
* paths from all vertices to the first vertex with the dijsktra algorithm
* and prints the furthest vertex together with its distance
* to the standard output
* @param numargs number of inputs on command line
* @param args array of * inputs on command line
* @return whether the function operated successfully
*/
int main(int numargs, char *args[]) {
timer::cpu_timer t;
bool useOwnMethod;
/*parsing command line options*/
po::options_description desc("Allowed options");
desc.add_options()
("help,h", "produce help message")
("m1", "use my own dijkstra method")
("m2", "use dijkstra method from boost")
("input-file", po::value< string >(), "input file");
po::positional_options_description p;
p.add("input-file", -1);
po::variables_map vm;
po::store(po::command_line_parser(numargs, args).
options(desc).positional(p).run(), vm);
po::notify(vm);
if (vm.count("help")) {
cout << desc << "\n";
exit(EXIT_SUCCESS);
}
if (vm.count("m1") && !vm.count("m2")) {
useOwnMethod = true;
cout << "using my own method for calculation..." << endl << endl;
} else if (vm.count("m2") && !vm.count("m1")) {
useOwnMethod = false;
cout << "using boost method for calculation..." << endl << endl;
} else {
cerr << "please specify the method you want to use (type -h for help)" << endl;
exit(EXIT_FAILURE);
}
string input;
if (vm.count("input-file")) {
input = vm["input-file"].as< string >();
} else {
cerr << "please specify an input file in the .gph format" << endl;
exit(EXIT_FAILURE);
}
/*end of parsing command line options*/
ifstream inputFile;
inputFile.open(input); //trying to read file
if (inputFile.fail()) {
cerr << "file could not be read" << endl;
exit(EXIT_FAILURE);
}
int numVertices;
int numEdges;
string line;
getline(inputFile, line); //first line is read
vector<string> parts;
split(parts, line, is_any_of(" "));
if (parts.size() != 2) {
cerr << "error in file: first line should consist of two integers!" << endl;
exit(EXIT_FAILURE);
}
try {
numVertices = stoi(parts[0]); //information from the first line
numEdges = stoi(parts[1]); //are stored
} catch (...) {
cerr << "error in file: first line should consist of two integers!" << endl;
exit(EXIT_FAILURE);
}
Edge *edges = new Edge[numEdges]; //in these arrays all information about
double *weights = new double[numEdges]; //the edges are stored
int i = 0;
using namespace boost::spirit;
using qi::int_;
using qi::double_;
using qi::phrase_parse;
using ascii::space;
//read line by line using boost to parse each line to int,int,double
while (getline(inputFile, line)) {
try {
auto it = line.begin();
int start;
int end;
double weight;
bool success = phrase_parse(it, line.end(),
int_[([&start](int j){ start = j; })]
>> int_[([&end](int j){ end = j; })]
>> double_[([&weight](double j){ weight = j; })], space);
if (success && it == line.end()) {
edges[i] = Edge(start-1, end-1);
weights[i] = weight;
} else {
cerr << "error in line " << (i+2) << ": line should consists of "
"two integers and a double!" << endl;
exit(EXIT_FAILURE);
}
} catch(...) {
cerr << "error in line " << (i+2) << ": line should consists of "
"two integers and a double!" << endl;
exit(EXIT_FAILURE);
}
++i;
}
//undirected graph is constructed with all edges and their weights
Graph g(edges, edges + numEdges , weights, numVertices);
//in this vector the resulting distances from dijkstra are stored
vector<double> distances;
//call of dijsktra depending on chosen option
if (!useOwnMethod) {
distances.resize(numVertices);
dijkstra_shortest_paths(g, *(vertices(g).first), distance_map(&distances[0]));
} else {
distances = myDijkstra(g, numVertices, 0);
}
double maxDist = 0;
int maxIdx = 0;
//search for furthest vertex
for (int i = 1; i < numVertices; i++) {
double tmp = distances[i];
if (tmp > maxDist) {
maxDist = tmp;
maxIdx = i;
}
}
//results are printed to command line
cout << "RESULT VERTEX " << (maxIdx+1) << endl;
cout << "RESULT DIST " << maxDist << endl;
cout << endl << "running time: " << t.format() << endl;
delete[] edges;
delete[] weights;
exit(EXIT_SUCCESS);
}
<|endoftext|> |
<commit_before>#include "application.h"
#include <inttypes.h>
SYSTEM_MODE(MANUAL);
SYSTEM_THREAD(ENABLED);
SerialLogHandler traceLog(LOG_LEVEL_TRACE);
static TCPServer tcpServer = TCPServer(6666);
static TCPClient tcpClient;
// Toggle LED pin to see that application loop is not blocked.
// You could use D7 when testing with a Photon.
// I'm using another pin here, because D7 is one of the SWD pins used by the debugger
const int LED_PIN = P1S0;
enum tcp_state_enum {
RUNNING_FINE,
OH_NO_ITS_BORKED_PARTICLE,
STOPPED,
ALLOWED_TO_RESTART,
};
volatile uint8_t tcp_state;
void stopTcp(){
tcpServer.stop();
tcpClient.stop();
Serial.print("TCP server stopped\n");
}
void startTcp(){
tcpServer.begin();
Serial.print("TCP server started\n");
}
void handle_network_events(system_event_t event, int param){
switch(param){
case network_status_powering_on:
break;
case network_status_on:
break;
case network_status_powering_off:
break;
case network_status_off:
break;
case network_status_connecting:
// set a flag to restart the TCP server, outside of the system thread
// restarting it here doesn't work
// leaving it running doesn't work
SINGLE_THREADED_BLOCK(){
tcp_state = tcp_state_enum::OH_NO_ITS_BORKED_PARTICLE;
}
break;
case network_status_connected:
SINGLE_THREADED_BLOCK(){
tcp_state = tcp_state_enum::ALLOWED_TO_RESTART;
}
break;
default:
break;
}
}
void handle_cloud_events(system_event_t event, int param){
switch(param){
case cloud_status_connecting:
break;
case cloud_status_connected:
break;
case cloud_status_disconnecting:
break;
case cloud_status_disconnected:
break;
default:
break;
}
}
void setup() {
Serial.begin(115200);
pinMode(LED_PIN, OUTPUT);
WiFi.connect(WIFI_CONNECT_SKIP_LISTEN);
System.on(network_status, handle_network_events);
System.on(cloud_status, handle_cloud_events);
tcp_state = tcp_state_enum::ALLOWED_TO_RESTART;
}
void loop() {
static uint32_t last_update = millis();
static uint32_t lastLedToggle = millis();
switch(tcp_state){
case tcp_state_enum::RUNNING_FINE:
break;
case tcp_state_enum::OH_NO_ITS_BORKED_PARTICLE:
Serial.print("Stopping TCP\n");
SINGLE_THREADED_BLOCK(){
tcp_state = tcp_state_enum::STOPPED;
}
stopTcp();
break;
case tcp_state_enum::ALLOWED_TO_RESTART:
Serial.print("Restarting TCP\n");
startTcp();
SINGLE_THREADED_BLOCK(){
tcp_state = tcp_state_enum::RUNNING_FINE; // assume it is running fine afterwards
}
break;
}
if(tcp_state == tcp_state_enum::RUNNING_FINE){
if(tcpClient.status()){
while (tcpClient.available() > 0) {
char inByte = tcpClient.read();
switch(inByte){
case ' ':
case '\n':
case '\r':
break;
case 't':
size_t result = tcpClient.write("toc"); // send toc back over tcp
Serial.printf("hw->py: toc (%d bytes sent) \n", result); // confirm toc sent over tcp
}
Serial.printf("py->hw: %c\n", inByte); // confirm character received from tcp
}
}
else{
tcpClient.stop();
// listen for a new client
TCPClient newClient = tcpServer.available();
if(newClient) {
Serial.print("New TCP client\n");
tcpClient.stop();
tcpClient = newClient;
}
}
}
// print status on serial every second
if ( millis() - last_update > 1000UL ) {
last_update = millis();
bool wifiReady = WiFi.ready();
IPAddress ip = WiFi.localIP();
int signal = WiFi.RSSI();
int clientConnected = tcpClient.connected();
Serial.printf(
"WiFi.ready(): %d\t\t"
"IP: %d.%d.%d.%d\t\t"
"RSSI: %d\t\t"
"TCP client connected: %d\t\t"
"millis(): %" PRIu32 "\n",
wifiReady,
ip[0],ip[1],ip[2],ip[3],
signal,
clientConnected,
last_update);
/* When the signal gets below -80, the P1 will stop responding to TCP.
* - It still has an IP
* - It still has WiFi.ready() returning 1.
* - The LED is still breathing green.
*
* There is one symptom that something is wrong though:
* When TCP stopped working, the P1 would return RSSI 2.
*
* This seems to be a failed to get RSSI timeout:
*
int8_t WiFiClass::RSSI() {
if (!network_ready(*this, 0, NULL))
return 0;
system_tick_t _functionStart = millis();
while ((millis() - _functionStart) < 1000) {
int rv = wlan_connected_rssi();
if (rv != 0)
return (rv);
}
return (2);
}
*
* In an attempt to fix this, I tried disconnecting and reconnecting WiFi.
* But WiFi.disconnect() gives a stack overflow SOS (13 blinks).
*/
if(signal == 2){
Serial.print("WiFi is in ERROR state. Resetting WiFi");
WiFi.disconnect();
WiFi.connect(WIFI_CONNECT_SKIP_LISTEN);
}
}
if ( millis() - lastLedToggle > 200UL ) {
static bool ledOn = true;
ledOn = !ledOn;
digitalWrite(LED_PIN, ledOn);
lastLedToggle = millis();
}
}
<commit_msg>Only go to 'borked' state when not in stopped state in wifi test app<commit_after>#include "application.h"
#include <inttypes.h>
SYSTEM_MODE(MANUAL);
SYSTEM_THREAD(ENABLED);
SerialLogHandler traceLog(LOG_LEVEL_TRACE);
static TCPServer tcpServer = TCPServer(6666);
static TCPClient tcpClient;
// Toggle LED pin to see that application loop is not blocked.
// You could use D7 when testing with a Photon.
// I'm using another pin here, because D7 is one of the SWD pins used by the debugger
const int LED_PIN = P1S0;
enum tcp_state_enum {
RUNNING_FINE,
OH_NO_ITS_BORKED_PARTICLE,
STOPPED,
ALLOWED_TO_RESTART,
};
volatile uint8_t tcp_state;
void stopTcp(){
tcpServer.stop();
tcpClient.stop();
Serial.print("TCP server stopped\n");
}
void startTcp(){
tcpServer.begin();
Serial.print("TCP server started\n");
}
void handle_network_events(system_event_t event, int param){
switch(param){
case network_status_powering_on:
break;
case network_status_on:
break;
case network_status_powering_off:
break;
case network_status_off:
break;
case network_status_connecting:
// set a flag to restart the TCP server, outside of the system thread
// restarting it here doesn't work
// leaving it running doesn't work
if(tcp_state != tcp_state_enum::STOPPED){
tcp_state = tcp_state_enum::OH_NO_ITS_BORKED_PARTICLE;
}
break;
case network_status_connected:
tcp_state = tcp_state_enum::ALLOWED_TO_RESTART;
break;
default:
break;
}
}
void handle_cloud_events(system_event_t event, int param){
switch(param){
case cloud_status_connecting:
break;
case cloud_status_connected:
break;
case cloud_status_disconnecting:
break;
case cloud_status_disconnected:
break;
default:
break;
}
}
void setup() {
Serial.begin(115200);
pinMode(LED_PIN, OUTPUT);
WiFi.connect(WIFI_CONNECT_SKIP_LISTEN);
System.on(network_status, handle_network_events);
System.on(cloud_status, handle_cloud_events);
tcp_state = tcp_state_enum::ALLOWED_TO_RESTART;
}
void loop() {
static uint32_t last_update = millis();
static uint32_t lastLedToggle = millis();
switch(tcp_state){
case tcp_state_enum::RUNNING_FINE:
break;
case tcp_state_enum::OH_NO_ITS_BORKED_PARTICLE:
Serial.print("Stopping TCP\n");
stopTcp();
tcp_state = tcp_state_enum::STOPPED;
break;
case tcp_state_enum::STOPPED:
break;
case tcp_state_enum::ALLOWED_TO_RESTART:
Serial.print("Restarting TCP\n");
startTcp();
tcp_state = tcp_state_enum::RUNNING_FINE; // assume it is running fine afterwards
break;
}
if(tcp_state == tcp_state_enum::RUNNING_FINE){
if(tcpClient.status()){
while (tcpClient.available() > 0) {
char inByte = tcpClient.read();
switch(inByte){
case ' ':
case '\n':
case '\r':
break;
case 't':
size_t result = tcpClient.write("toc"); // send toc back over tcp
Serial.printf("hw->py: toc (%d bytes sent) \n", result); // confirm toc sent over tcp
}
Serial.printf("py->hw: %c\n", inByte); // confirm character received from tcp
}
}
else{
tcpClient.stop();
// listen for a new client
TCPClient newClient = tcpServer.available();
if(newClient) {
Serial.print("New TCP client\n");
tcpClient.stop();
tcpClient = newClient;
}
}
}
// print status on serial every second
if ( millis() - last_update > 1000UL ) {
last_update = millis();
bool wifiReady = WiFi.ready();
IPAddress ip = WiFi.localIP();
int signal = WiFi.RSSI();
int clientConnected = tcpClient.connected();
Serial.printf(
"WiFi.ready(): %d\t\t"
"IP: %d.%d.%d.%d\t\t"
"RSSI: %d\t\t"
"TCP client connected: %d\t\t"
"millis(): %" PRIu32 "\n",
wifiReady,
ip[0],ip[1],ip[2],ip[3],
signal,
clientConnected,
last_update);
/* When the signal gets below -80, the P1 will stop responding to TCP.
* - It still has an IP
* - It still has WiFi.ready() returning 1.
* - The LED is still breathing green.
*
* There is one symptom that something is wrong though:
* When TCP stopped working, the P1 would return RSSI 2.
*
* This seems to be a failed to get RSSI timeout:
*
int8_t WiFiClass::RSSI() {
if (!network_ready(*this, 0, NULL))
return 0;
system_tick_t _functionStart = millis();
while ((millis() - _functionStart) < 1000) {
int rv = wlan_connected_rssi();
if (rv != 0)
return (rv);
}
return (2);
}
*
* In an attempt to fix this, I tried disconnecting and reconnecting WiFi.
* But WiFi.disconnect() gives a stack overflow SOS (13 blinks).
*/
if(signal == 2){
Serial.print("\n\n\nWiFi is in ERROR state. Resetting WiFi\n\n\n");
WiFi.disconnect();
WiFi.connect(WIFI_CONNECT_SKIP_LISTEN);
}
}
if ( millis() - lastLedToggle > 200UL ) {
static bool ledOn = true;
ledOn = !ledOn;
digitalWrite(LED_PIN, ledOn);
lastLedToggle = millis();
}
}
<|endoftext|> |
<commit_before>#include <Graphics.h>
#include <Surface.h>
#include "Render.h"
namespace nme
{
static bool IsPOW2(int inX)
{
return (inX & (inX-1)) == 0;
}
enum { EDGE_CLAMP, EDGE_REPEAT, EDGE_POW2 };
#define GET_PIXEL_POINTERS \
int frac_x = (mPos.x & 0xff00) >> 8; \
int frac_nx = 0x100 - frac_x; \
int frac_y = (mPos.y & 0xffff); \
int frac_ny = 0x10000 - frac_y; \
\
if (EDGE == EDGE_CLAMP) \
{ \
int x_step = 4; \
int y_step = mStride; \
\
if (x<0) { x_step = x = 0; } \
else if (x>=mW1) { x_step = 0; x = mW1; } \
\
if (y<0) { y_step = y = 0; } \
else if (y>=mH1) { y_step = 0; y = mH1; } \
\
const uint8 * ptr = mBase + y*mStride + x*4; \
p00 = *(ARGB *)ptr; \
p01 = *(ARGB *)(ptr + x_step); \
p10 = *(ARGB *)(ptr + y_step); \
p11 = *(ARGB *)(ptr + y_step + x_step); \
} \
else if (EDGE==EDGE_POW2) \
{ \
const uint8 *p = mBase + (y&mH1)*mStride; \
\
p00 = *(ARGB *)(p+ (x & mW1)*4); \
p01 = *(ARGB *)(p+ ((x+1) & mW1)*4); \
\
p = mBase + ( (y+1) &mH1)*mStride; \
p10 = *(ARGB *)(p+ (x & mW1)*4); \
p11 = *(ARGB *)(p+ ((x+1) & mW1)*4); \
} \
else \
{ \
int x1 = ((x+1) % mWidth) * 4; \
if (x1<0) x1+=mWidth; \
x = (x % mWidth)*4; \
if (x<0) x+=mWidth; \
\
int y0= (y%mHeight); if (y0<0) y0+=mHeight; \
const uint8 *p = mBase + y0*mStride; \
\
p00 = *(ARGB *)(p+ x); \
p01 = *(ARGB *)(p+ x1); \
\
int y1= ((y+1)%mHeight); if (y1<0) y1+=mHeight; \
p = mBase + y1*mStride; \
p10 = *(ARGB *)(p+ x); \
p11 = *(ARGB *)(p+ x1); \
}
#define MODIFY_EDGE_XY \
if (EDGE == EDGE_CLAMP) \
{ \
if (x<0) x = 0; \
else if (x>=mWidth) x = mW1; \
\
if (y<0) y = 0; \
else if (y>=mHeight) y = mH1; \
} \
else if (EDGE == EDGE_POW2) \
{ \
x &= mW1; \
y &= mH1; \
} \
else if (EDGE == EDGE_REPEAT) \
{ \
x = x % mWidth; if (x<0) x+=mWidth;\
y = y % mHeight; if (y<0) y+=mHeight;\
}
class BitmapFillerBase : public Filler
{
public:
BitmapFillerBase(GraphicsBitmapFill *inFill) : mBitmap(inFill)
{
mWidth = mBitmap->bitmapData->Width();
mHeight = mBitmap->bitmapData->Height();
mW1 = mWidth-1;
mH1 = mHeight-1;
mBase = mBitmap->bitmapData->GetBase();
mStride = mBitmap->bitmapData->GetStride();
mMapped = false;
}
inline void SetPos(int inSX,int inSY)
{
mPos.x = (int)( (mMapper.m00*inSX + mMapper.m01*inSY + mMapper.mtx) * (1<<16) + 0.5);
mPos.y = (int)( (mMapper.m10*inSX + mMapper.m11*inSY + mMapper.mty) * (1<<16) + 0.5);
}
void SetupMatrix(const Matrix &inMatrix)
{
if (mMapped) return;
// Get combined mapping matrix...
Matrix mapper = inMatrix;
mapper = mapper.Mult(mBitmap->matrix);
mMapper = mapper.Inverse();
//mMapper.Scale(mWidth/1638.4,mHeight/1638.4);
mMapper.Translate(0.5,0.5);
mDPxDX = (int)(mMapper.m00 * (1<<16)+ 0.5);
mDPyDX = (int)(mMapper.m10 * (1<<16)+ 0.5);
}
void SetMapping(const UserPoint *inVertex, const float *inUVT,int inComponents)
{
mMapped = true;
double w = mBitmap->bitmapData->Width();
double h = mBitmap->bitmapData->Height();
// Solve tx = f(x,y), ty = f(x,y)
double dx1 = inVertex[1].x-inVertex[0].x;
double dy1 = inVertex[1].y-inVertex[0].y;
double dx2 = inVertex[2].x-inVertex[0].x;
double dy2 = inVertex[2].y-inVertex[0].y;
double du1 = (inUVT[inComponents ] - inUVT[0])*w;
double du2 = (inUVT[inComponents*2] - inUVT[0])*w;
double dv1 = (inUVT[inComponents +1] - inUVT[1])*h;
double dv2 = (inUVT[inComponents*2+1] - inUVT[1])*h;
double dw1 = inComponents==3 ? inUVT[inComponents+2]-inUVT[2] : 0;
double dw2 = inComponents==3 ? inUVT[inComponents*2+2]-inUVT[2] : 0;
// u = a*x + b*y + c
// u0 = a*v0.x + b*v0.y + c
// u1 = a*v1.x + b*v1.y + c
// u2 = a*v2.x + b*v2.y + c
//
// (u1-u0) = a*(v1.x-v0.x) + b*(v1.y-v0.y) = du1 = a*dx1 + b*dy1
// (u2-u0) = a*(v2.x-v0.x) + b*(v2.y-v0.y) = du2 = a*dx2 + b*dy2
//
// du1*dy2 - du2*dy1= a*(dx1*dy2 - dx2*dy1)
double det = dx1*dy2 - dx2*dy1;
if (det==0)
{
// TODO: x-only or y-only
mMapper = Matrix(0,0,inUVT[0],inUVT[1]);
mWX = mWY = 0;
mWC = 1;
}
else
{
det = 1.0/det;
double a = mMapper.m00 = (du1*dy2 - du2*dy1)*det;
double b = mMapper.m01 = dy1!=0 ? (du1-a*dx1)/dy1 : dy2!=0 ? (du1-a*dx2)/dy2 : 0;
mMapper.mtx = inUVT[0]*w - a*inVertex[0].x - b*inVertex[0].y;
a = mMapper.m10 = (dv1*dy2 - dv2*dy1)*det;
b = mMapper.m11 = dy1!=0 ? (dv1-a*dx1)/dy1 : dy2!=0 ? (dv1-a*dx2)/dy2 : 0;
mMapper.mty = inUVT[1]*h - a*inVertex[0].x - b*inVertex[0].y;
if (mPerspective)
{
mWX = (dv1*dy2 - dv2*dy1)*det;
}
}
mMapper.Translate(0.5,0.5);
mDPxDX = (int)(mMapper.m00 * (1<<16)+ 0.5);
mDPyDX = (int)(mMapper.m10 * (1<<16)+ 0.5);
}
const uint8 *mBase;
int mStride;
ImagePoint mPos;
int mDPxDX;
int mDPyDX;
int mWidth;
int mHeight;
int mW1;
int mH1;
bool mMapped;
double mWX, mWY, mWZ;
double mTX, mTY, mTZ;
Matrix mMapper;
GraphicsBitmapFill *mBitmap;
};
template<int EDGE,bool SMOOTH,bool HAS_ALPHA,bool PERSP>
class BitmapFiller : public BitmapFillerBase
{
public:
enum { HasAlpha = HAS_ALPHA };
BitmapFiller(GraphicsBitmapFill *inFill) : BitmapFillerBase(inFill) { }
ARGB GetInc( )
{
int x = mPos.x >> 16;
int y = mPos.y >> 16;
if (SMOOTH)
{
ARGB result;
ARGB p00,p01,p10,p11;
GET_PIXEL_POINTERS
mPos.x += mDPxDX;
mPos.y += mDPyDX;
result.c0 = ( (p00.c0*frac_nx + p01.c0*frac_x)*frac_ny +
( p10.c0*frac_nx + p11.c0*frac_x)*frac_y ) >> 24;
result.c1 = ( (p00.c1*frac_nx + p01.c1*frac_x)*frac_ny +
( p10.c1*frac_nx + p11.c1*frac_x)*frac_y ) >> 24;
result.c2 = ( (p00.c2*frac_nx + p01.c2*frac_x)*frac_ny +
( p10.c2*frac_nx + p11.c2*frac_x)*frac_y ) >> 24;
if (HAS_ALPHA)
{
result.a = ( (p00.a*frac_nx + p01.a*frac_x)*frac_ny +
(p10.a*frac_nx + p11.a*frac_x)*frac_y ) >> 24;
}
else
result.a = 255;
return result;
}
else
{
mPos.x += mDPxDX;
mPos.y += mDPyDX;
MODIFY_EDGE_XY;
return *(ARGB *)( mBase + y*mStride + x*4);
}
}
void Fill(const AlphaMask &mAlphaMask,int inTX,int inTY,
const RenderTarget &inTarget,const RenderState &inState)
{
SetupMatrix(*inState.mTransform.mMatrix);
bool swap = (inTarget.mPixelFormat & pfSwapRB) != (mBitmap->bitmapData->Format() & pfSwapRB);
Render( mAlphaMask, *this, inTarget, swap, inState, inTX,inTY );
}
};
// --- Pseudo constructor ---------------------------------------------------------------
template<int EDGE,bool SMOOTH,bool PERSP>
static Filler *CreateAlpha(GraphicsBitmapFill *inFill)
{
if (inFill->bitmapData->Format() & pfHasAlpha)
return new BitmapFiller<EDGE,SMOOTH,PERSP,true>(inFill);
else
return new BitmapFiller<EDGE,SMOOTH,PERSP,false>(inFill);
}
template<int EDGE,bool SMOOTH>
static Filler *CreatePerspective(GraphicsBitmapFill *inFill,bool inPerspective)
{
if (inPerspective)
return CreateAlpha<EDGE,SMOOTH,true>(inFill);
else
return CreateAlpha<EDGE,SMOOTH,false>(inFill);
}
template<int EDGE>
static Filler *CreateSmooth(GraphicsBitmapFill *inFill,bool inPerspective)
{
if (inFill->smooth)
return CreatePerspective<EDGE,true>(inFill,inPerspective);
else
return CreatePerspective<EDGE,false>(inFill,inPerspective);
}
Filler *Filler::Create(GraphicsBitmapFill *inFill,bool inPerspective)
{
if (inFill->repeat)
{
if ( IsPOW2(inFill->bitmapData->Width()) && IsPOW2(inFill->bitmapData->Height()) )
return CreateSmooth<EDGE_POW2>(inFill,inPerspective);
else
return CreateSmooth<EDGE_REPEAT>(inFill,inPerspective);
}
else
return CreateSmooth<EDGE_CLAMP>(inFill,inPerspective);
}
} // end namespace nme
<commit_msg>Fix perspective mapping<commit_after>#include <Graphics.h>
#include <Surface.h>
#include "Render.h"
namespace nme
{
static bool IsPOW2(int inX)
{
return (inX & (inX-1)) == 0;
}
enum { EDGE_CLAMP, EDGE_REPEAT, EDGE_POW2 };
#define GET_PIXEL_POINTERS \
int frac_x = (mPos.x & 0xff00) >> 8; \
int frac_nx = 0x100 - frac_x; \
int frac_y = (mPos.y & 0xffff); \
int frac_ny = 0x10000 - frac_y; \
\
if (EDGE == EDGE_CLAMP) \
{ \
int x_step = 4; \
int y_step = mStride; \
\
if (x<0) { x_step = x = 0; } \
else if (x>=mW1) { x_step = 0; x = mW1; } \
\
if (y<0) { y_step = y = 0; } \
else if (y>=mH1) { y_step = 0; y = mH1; } \
\
const uint8 * ptr = mBase + y*mStride + x*4; \
p00 = *(ARGB *)ptr; \
p01 = *(ARGB *)(ptr + x_step); \
p10 = *(ARGB *)(ptr + y_step); \
p11 = *(ARGB *)(ptr + y_step + x_step); \
} \
else if (EDGE==EDGE_POW2) \
{ \
const uint8 *p = mBase + (y&mH1)*mStride; \
\
p00 = *(ARGB *)(p+ (x & mW1)*4); \
p01 = *(ARGB *)(p+ ((x+1) & mW1)*4); \
\
p = mBase + ( (y+1) &mH1)*mStride; \
p10 = *(ARGB *)(p+ (x & mW1)*4); \
p11 = *(ARGB *)(p+ ((x+1) & mW1)*4); \
} \
else \
{ \
int x1 = ((x+1) % mWidth) * 4; \
if (x1<0) x1+=mWidth; \
x = (x % mWidth)*4; \
if (x<0) x+=mWidth; \
\
int y0= (y%mHeight); if (y0<0) y0+=mHeight; \
const uint8 *p = mBase + y0*mStride; \
\
p00 = *(ARGB *)(p+ x); \
p01 = *(ARGB *)(p+ x1); \
\
int y1= ((y+1)%mHeight); if (y1<0) y1+=mHeight; \
p = mBase + y1*mStride; \
p10 = *(ARGB *)(p+ x); \
p11 = *(ARGB *)(p+ x1); \
}
#define MODIFY_EDGE_XY \
if (EDGE == EDGE_CLAMP) \
{ \
if (x<0) x = 0; \
else if (x>=mWidth) x = mW1; \
\
if (y<0) y = 0; \
else if (y>=mHeight) y = mH1; \
} \
else if (EDGE == EDGE_POW2) \
{ \
x &= mW1; \
y &= mH1; \
} \
else if (EDGE == EDGE_REPEAT) \
{ \
x = x % mWidth; if (x<0) x+=mWidth;\
y = y % mHeight; if (y<0) y+=mHeight;\
}
class BitmapFillerBase : public Filler
{
public:
BitmapFillerBase(GraphicsBitmapFill *inFill) : mBitmap(inFill)
{
mWidth = mBitmap->bitmapData->Width();
mHeight = mBitmap->bitmapData->Height();
mW1 = mWidth-1;
mH1 = mHeight-1;
mBase = mBitmap->bitmapData->GetBase();
mStride = mBitmap->bitmapData->GetStride();
mMapped = false;
mPerspective = false;
}
void SetupMatrix(const Matrix &inMatrix)
{
if (mMapped) return;
// Get combined mapping matrix...
Matrix mapper = inMatrix;
mapper = mapper.Mult(mBitmap->matrix);
mMapper = mapper.Inverse();
//mMapper.Scale(mWidth/1638.4,mHeight/1638.4);
mMapper.Translate(0.5,0.5);
mDPxDX = (int)(mMapper.m00 * (1<<16)+ 0.5);
mDPyDX = (int)(mMapper.m10 * (1<<16)+ 0.5);
}
void SetMapping(const UserPoint *inVertex, const float *inUVT,int inComponents)
{
mMapped = true;
double w = mBitmap->bitmapData->Width();
double h = mBitmap->bitmapData->Height();
// Solve tx = f(x,y), ty = f(x,y)
double dx1;
double dy1;
double dx2;
double dy2;
double du1;
double du2;
double dv1;
double dv2;
double dw1=0;
double dw2=0;
double w0=1,w1=1,w2=1;
if (inComponents==3)
{
w0 = inUVT[2];
w1 = inUVT[3+2];
w2 = inUVT[6+2];
//w0 = w1 = w2 = 1.0;
dx1 = inVertex[1].x-inVertex[0].x;
dy1 = inVertex[1].y-inVertex[0].y;
dx2 = inVertex[2].x-inVertex[0].x;
dy2 = inVertex[2].y-inVertex[0].y;
du1 = (inUVT[inComponents ]*w1 - inUVT[0]*w0)*w;
du2 = (inUVT[inComponents*2]*w2 - inUVT[0]*w0)*w;
dv1 = (inUVT[inComponents +1]*w1 - inUVT[1]*w0)*h;
dv2 = (inUVT[inComponents*2+1]*w2 - inUVT[1]*w0)*h;
dw1 = w1 - w0;
dw2 = w2 - w0;
}
else
{
dx1 = inVertex[1].x-inVertex[0].x;
dy1 = inVertex[1].y-inVertex[0].y;
dx2 = inVertex[2].x-inVertex[0].x;
dy2 = inVertex[2].y-inVertex[0].y;
du1 = (inUVT[inComponents ] - inUVT[0])*w;
du2 = (inUVT[inComponents*2] - inUVT[0])*w;
dv1 = (inUVT[inComponents +1] - inUVT[1])*h;
dv2 = (inUVT[inComponents*2+1] - inUVT[1])*h;
}
// u = a*x + b*y + c
// u0 = a*v0.x + b*v0.y + c
// u1 = a*v1.x + b*v1.y + c
// u2 = a*v2.x + b*v2.y + c
//
// (u1-u0) = a*(v1.x-v0.x) + b*(v1.y-v0.y) = du1 = a*dx1 + b*dy1
// (u2-u0) = a*(v2.x-v0.x) + b*(v2.y-v0.y) = du2 = a*dx2 + b*dy2
//
// du1*dy2 - du2*dy1= a*(dx1*dy2 - dx2*dy1)
double det = dx1*dy2 - dx2*dy1;
if (det==0)
{
// TODO: x-only or y-only
mMapper = Matrix(0,0,inUVT[0],inUVT[1]);
mWX = mWY = 0;
mW0 = 1;
}
else
{
det = 1.0/det;
double a = mMapper.m00 = (du1*dy2 - du2*dy1)*det;
double b = mMapper.m01 = (du2*dx1 - du1*dx2)*det;
mMapper.mtx = (inUVT[0]*w*w0 - a*inVertex[0].x - b*inVertex[0].y);
a = mMapper.m10 = (dv1*dy2 - dv2*dy1)*det;
b = (dv2*dx1 - dv1*dx2)*det;
mMapper.mty = (inUVT[1]*h*w0 - a*inVertex[0].x - b*inVertex[0].y);
if (mPerspective && inComponents>2)
{
a = mWX = (dw1*dy2 - dw2*dy1)*det;
b = mWY = (dw2*dx1 - dw1*dx2)*det;
mW0= w0 - a*inVertex[0].x - b*inVertex[0].y;
}
}
mMapper.Translate(0.5,0.5);
if (!mPerspective || inComponents<3)
{
mDPxDX = (int)(mMapper.m00 * (1<<16)+ 0.5);
mDPyDX = (int)(mMapper.m10 * (1<<16)+ 0.5);
}
}
const uint8 *mBase;
int mStride;
ImagePoint mPos;
int mDPxDX;
int mDPyDX;
int mWidth;
int mHeight;
int mW1;
int mH1;
bool mMapped;
bool mPerspective;
double mWX, mWY, mW0;
double mTX, mTY, mTW;
Matrix mMapper;
GraphicsBitmapFill *mBitmap;
};
template<int EDGE,bool SMOOTH,bool PERSP,bool HAS_ALPHA>
class BitmapFiller : public BitmapFillerBase
{
public:
enum { HasAlpha = HAS_ALPHA };
BitmapFiller(GraphicsBitmapFill *inFill) : BitmapFillerBase(inFill)
{
mPerspective = PERSP;
}
ARGB GetInc( )
{
if (PERSP)
{
double w = 65536.0/mTW;
mPos.x = (int)(mTX*w);
mPos.y = (int)(mTY*w);
mTX += mMapper.m00;
mTY += mMapper.m10;
mTW += mWX;
}
int x = mPos.x >> 16;
int y = mPos.y >> 16;
if (SMOOTH)
{
ARGB result;
ARGB p00,p01,p10,p11;
GET_PIXEL_POINTERS
if (!PERSP)
{
mPos.x += mDPxDX;
mPos.y += mDPyDX;
}
result.c0 = ( (p00.c0*frac_nx + p01.c0*frac_x)*frac_ny +
( p10.c0*frac_nx + p11.c0*frac_x)*frac_y ) >> 24;
result.c1 = ( (p00.c1*frac_nx + p01.c1*frac_x)*frac_ny +
( p10.c1*frac_nx + p11.c1*frac_x)*frac_y ) >> 24;
result.c2 = ( (p00.c2*frac_nx + p01.c2*frac_x)*frac_ny +
( p10.c2*frac_nx + p11.c2*frac_x)*frac_y ) >> 24;
if (HAS_ALPHA)
{
result.a = ( (p00.a*frac_nx + p01.a*frac_x)*frac_ny +
(p10.a*frac_nx + p11.a*frac_x)*frac_y ) >> 24;
}
else
result.a = 255;
return result;
}
else
{
if (!PERSP)
{
mPos.x += mDPxDX;
mPos.y += mDPyDX;
}
MODIFY_EDGE_XY;
return *(ARGB *)( mBase + y*mStride + x*4);
}
}
inline void SetPos(int inSX,int inSY)
{
if (PERSP)
{
double x = inSX;
double y = inSY;
mTX = mMapper.m00*x + mMapper.m01*y + mMapper.mtx;
mTY = mMapper.m10*x + mMapper.m11*y + mMapper.mty;
mTW = mWX*x + mWY*y + mW0;
}
else
{
mPos.x = (int)( (mMapper.m00*inSX + mMapper.m01*inSY + mMapper.mtx) * (1<<16) + 0.5);
mPos.y = (int)( (mMapper.m10*inSX + mMapper.m11*inSY + mMapper.mty) * (1<<16) + 0.5);
}
}
void Fill(const AlphaMask &mAlphaMask,int inTX,int inTY,
const RenderTarget &inTarget,const RenderState &inState)
{
SetupMatrix(*inState.mTransform.mMatrix);
bool swap = (inTarget.mPixelFormat & pfSwapRB) != (mBitmap->bitmapData->Format() & pfSwapRB);
Render( mAlphaMask, *this, inTarget, swap, inState, inTX,inTY );
}
};
// --- Pseudo constructor ---------------------------------------------------------------
template<int EDGE,bool SMOOTH,bool PERSP>
static Filler *CreateAlpha(GraphicsBitmapFill *inFill)
{
if (inFill->bitmapData->Format() & pfHasAlpha)
return new BitmapFiller<EDGE,SMOOTH,PERSP,true>(inFill);
else
return new BitmapFiller<EDGE,SMOOTH,PERSP,false>(inFill);
}
template<int EDGE,bool SMOOTH>
static Filler *CreatePerspective(GraphicsBitmapFill *inFill,bool inPerspective)
{
if (inPerspective)
return CreateAlpha<EDGE,SMOOTH,true>(inFill);
else
return CreateAlpha<EDGE,SMOOTH,false>(inFill);
}
template<int EDGE>
static Filler *CreateSmooth(GraphicsBitmapFill *inFill,bool inPerspective)
{
if (inFill->smooth)
return CreatePerspective<EDGE,true>(inFill,inPerspective);
else
return CreatePerspective<EDGE,false>(inFill,inPerspective);
}
Filler *Filler::Create(GraphicsBitmapFill *inFill,bool inPerspective)
{
if (inFill->repeat)
{
if ( IsPOW2(inFill->bitmapData->Width()) && IsPOW2(inFill->bitmapData->Height()) )
return CreateSmooth<EDGE_POW2>(inFill,inPerspective);
else
return CreateSmooth<EDGE_REPEAT>(inFill,inPerspective);
}
else
return CreateSmooth<EDGE_CLAMP>(inFill,inPerspective);
}
} // end namespace nme
<|endoftext|> |
<commit_before>// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#define FML_USED_ON_EMBEDDER
#include <cstdlib>
#include "flutter/assets/asset_manager.h"
#include "flutter/assets/directory_asset_bundle.h"
#include "flutter/fml/file.h"
#include "flutter/fml/make_copyable.h"
#include "flutter/fml/message_loop.h"
#include "flutter/fml/paths.h"
#include "flutter/fml/synchronization/waitable_event.h"
#include "flutter/fml/task_runner.h"
#include "flutter/shell/common/platform_view.h"
#include "flutter/shell/common/rasterizer.h"
#include "flutter/shell/common/shell.h"
#include "flutter/shell/common/switches.h"
#include "flutter/shell/common/thread_host.h"
#include "third_party/dart/runtime/include/bin/dart_io_api.h"
namespace shell {
// Checks whether the engine's main Dart isolate has no pending work. If so,
// then exit the given message loop.
class ScriptCompletionTaskObserver {
public:
ScriptCompletionTaskObserver(Shell& shell,
fml::RefPtr<fml::TaskRunner> main_task_runner,
bool run_forever)
: engine_(shell.GetEngine()),
main_task_runner_(std::move(main_task_runner)),
run_forever_(run_forever) {}
int GetExitCodeForLastError() const {
// Exit codes used by the Dart command line tool.
const int kApiErrorExitCode = 253;
const int kCompilationErrorExitCode = 254;
const int kErrorExitCode = 255;
switch (last_error_) {
case tonic::kCompilationErrorType:
return kCompilationErrorExitCode;
case tonic::kApiErrorType:
return kApiErrorExitCode;
case tonic::kUnknownErrorType:
return kErrorExitCode;
default:
return 0;
}
}
void DidProcessTask() {
if (engine_) {
last_error_ = engine_->GetUIIsolateLastError();
if (engine_->UIIsolateHasLivePorts()) {
// The UI isolate still has live ports and is running. Nothing to do
// just yet.
return;
}
}
if (run_forever_) {
// We need this script to run forever. We have already recorded the last
// error. Keep going.
return;
}
if (!has_terminated) {
// Only try to terminate the loop once.
has_terminated = true;
main_task_runner_->PostTask(
[]() { fml::MessageLoop::GetCurrent().Terminate(); });
}
}
private:
fml::WeakPtr<Engine> engine_;
fml::RefPtr<fml::TaskRunner> main_task_runner_;
bool run_forever_ = false;
tonic::DartErrorHandleType last_error_ = tonic::kUnknownErrorType;
bool has_terminated = false;
FML_DISALLOW_COPY_AND_ASSIGN(ScriptCompletionTaskObserver);
};
int RunTester(const blink::Settings& settings, bool run_forever) {
const auto thread_label = "io.flutter.test";
fml::MessageLoop::EnsureInitializedForCurrentThread();
auto current_task_runner = fml::MessageLoop::GetCurrent().GetTaskRunner();
// Setup a single threaded test runner configuration.
const blink::TaskRunners task_runners(thread_label, // dart thread label
current_task_runner, // platform
current_task_runner, // gpu
current_task_runner, // ui
current_task_runner // io
);
Shell::CreateCallback<PlatformView> on_create_platform_view =
[](Shell& shell) {
return std::make_unique<PlatformView>(shell, shell.GetTaskRunners());
};
Shell::CreateCallback<Rasterizer> on_create_rasterizer = [](Shell& shell) {
return std::make_unique<Rasterizer>(shell.GetTaskRunners());
};
auto shell = Shell::Create(task_runners, //
settings, //
on_create_platform_view, //
on_create_rasterizer //
);
if (!shell || !shell->IsSetup()) {
FML_LOG(ERROR) << "Could not setup the shell.";
return EXIT_FAILURE;
}
if (settings.application_kernel_asset.empty()) {
FML_LOG(ERROR) << "Dart kernel file not specified.";
return EXIT_FAILURE;
}
// Initialize default testing locales. There is no platform to
// pass locales on the tester, so to retain expected locale behavior,
// we emulate it in here by passing in 'en_US' and 'zh_CN' as test locales.
const char* locale_json =
"{\"method\":\"setLocale\",\"args\":[\"en\",\"US\",\"\",\"\",\"zh\","
"\"CN\",\"\",\"\"]}";
std::vector<uint8_t> locale_bytes(locale_json,
locale_json + std::strlen(locale_json));
fml::RefPtr<blink::PlatformMessageResponse> response;
shell->GetPlatformView()->DispatchPlatformMessage(
fml::MakeRefCounted<blink::PlatformMessage>("flutter/localization",
locale_bytes, response));
std::initializer_list<fml::FileMapping::Protection> protection = {
fml::FileMapping::Protection::kRead};
auto main_dart_file_mapping = std::make_unique<fml::FileMapping>(
fml::OpenFile(
fml::paths::AbsolutePath(settings.application_kernel_asset).c_str(),
false, fml::FilePermission::kRead),
protection);
auto isolate_configuration =
IsolateConfiguration::CreateForKernel(std::move(main_dart_file_mapping));
if (!isolate_configuration) {
FML_LOG(ERROR) << "Could create isolate configuration.";
return EXIT_FAILURE;
}
auto asset_manager = std::make_shared<blink::AssetManager>();
asset_manager->PushBack(std::make_unique<blink::DirectoryAssetBundle>(
fml::Duplicate(settings.assets_dir)));
asset_manager->PushBack(
std::make_unique<blink::DirectoryAssetBundle>(fml::OpenDirectory(
settings.assets_path.c_str(), false, fml::FilePermission::kRead)));
RunConfiguration run_configuration(std::move(isolate_configuration),
std::move(asset_manager));
// The script completion task observer that will be installed on the UI thread
// that watched if the engine has any live ports.
ScriptCompletionTaskObserver completion_observer(
*shell, // a valid shell
fml::MessageLoop::GetCurrent()
.GetTaskRunner(), // the message loop to terminate
run_forever // should the exit be ignored
);
bool engine_did_run = false;
fml::AutoResetWaitableEvent sync_run_latch;
fml::TaskRunner::RunNowOrPostTask(
shell->GetTaskRunners().GetUITaskRunner(),
fml::MakeCopyable([&sync_run_latch, &completion_observer,
engine = shell->GetEngine(),
config = std::move(run_configuration),
&engine_did_run]() mutable {
fml::MessageLoop::GetCurrent().AddTaskObserver(
reinterpret_cast<intptr_t>(&completion_observer),
[&completion_observer]() { completion_observer.DidProcessTask(); });
if (engine->Run(std::move(config)) !=
shell::Engine::RunStatus::Failure) {
engine_did_run = true;
blink::ViewportMetrics metrics;
metrics.device_pixel_ratio = 3.0;
metrics.physical_width = 2400; // 800 at 3x resolution
metrics.physical_height = 1800; // 600 at 3x resolution
engine->SetViewportMetrics(metrics);
} else {
FML_DLOG(ERROR) << "Could not launch the engine with configuration.";
}
sync_run_latch.Signal();
}));
sync_run_latch.Wait();
// Run the message loop and wait for the script to do its thing.
fml::MessageLoop::GetCurrent().Run();
// Cleanup the completion observer synchronously as it is living on the
// stack.
fml::AutoResetWaitableEvent latch;
fml::TaskRunner::RunNowOrPostTask(
shell->GetTaskRunners().GetUITaskRunner(),
[&latch, &completion_observer] {
fml::MessageLoop::GetCurrent().RemoveTaskObserver(
reinterpret_cast<intptr_t>(&completion_observer));
latch.Signal();
});
latch.Wait();
if (!engine_did_run) {
// If the engine itself didn't have a chance to run, there is no point in
// asking it if there was an error. Signal a failure unconditionally.
return EXIT_FAILURE;
}
return completion_observer.GetExitCodeForLastError();
}
} // namespace shell
int main(int argc, char* argv[]) {
dart::bin::SetExecutableName(argv[0]);
dart::bin::SetExecutableArguments(argc - 1, argv);
auto command_line = fml::CommandLineFromArgcArgv(argc, argv);
if (command_line.HasOption(shell::FlagForSwitch(shell::Switch::Help))) {
shell::PrintUsage("flutter_tester");
return EXIT_SUCCESS;
}
auto settings = shell::SettingsFromCommandLine(command_line);
if (command_line.positional_args().size() > 0) {
// The tester may not use the switch for the main dart file path. Specifying
// it as a positional argument instead.
settings.application_kernel_asset = command_line.positional_args()[0];
}
if (settings.application_kernel_asset.size() == 0) {
FML_LOG(ERROR) << "Dart kernel file not specified.";
return EXIT_FAILURE;
}
settings.icu_data_path = "icudtl.dat";
// The tools that read logs get confused if there is a log tag specified.
settings.log_tag = "";
settings.task_observer_add = [](intptr_t key, fml::closure callback) {
fml::MessageLoop::GetCurrent().AddTaskObserver(key, std::move(callback));
};
settings.task_observer_remove = [](intptr_t key) {
fml::MessageLoop::GetCurrent().RemoveTaskObserver(key);
};
return shell::RunTester(
settings,
command_line.HasOption(shell::FlagForSwitch(shell::Switch::RunForever)));
}
<commit_msg>[flutter_tester] Accept --icu-data-file-path (#8374)<commit_after>// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#define FML_USED_ON_EMBEDDER
#include <cstdlib>
#include "flutter/assets/asset_manager.h"
#include "flutter/assets/directory_asset_bundle.h"
#include "flutter/fml/file.h"
#include "flutter/fml/make_copyable.h"
#include "flutter/fml/message_loop.h"
#include "flutter/fml/paths.h"
#include "flutter/fml/synchronization/waitable_event.h"
#include "flutter/fml/task_runner.h"
#include "flutter/shell/common/platform_view.h"
#include "flutter/shell/common/rasterizer.h"
#include "flutter/shell/common/shell.h"
#include "flutter/shell/common/switches.h"
#include "flutter/shell/common/thread_host.h"
#include "third_party/dart/runtime/include/bin/dart_io_api.h"
namespace shell {
// Checks whether the engine's main Dart isolate has no pending work. If so,
// then exit the given message loop.
class ScriptCompletionTaskObserver {
public:
ScriptCompletionTaskObserver(Shell& shell,
fml::RefPtr<fml::TaskRunner> main_task_runner,
bool run_forever)
: engine_(shell.GetEngine()),
main_task_runner_(std::move(main_task_runner)),
run_forever_(run_forever) {}
int GetExitCodeForLastError() const {
// Exit codes used by the Dart command line tool.
const int kApiErrorExitCode = 253;
const int kCompilationErrorExitCode = 254;
const int kErrorExitCode = 255;
switch (last_error_) {
case tonic::kCompilationErrorType:
return kCompilationErrorExitCode;
case tonic::kApiErrorType:
return kApiErrorExitCode;
case tonic::kUnknownErrorType:
return kErrorExitCode;
default:
return 0;
}
}
void DidProcessTask() {
if (engine_) {
last_error_ = engine_->GetUIIsolateLastError();
if (engine_->UIIsolateHasLivePorts()) {
// The UI isolate still has live ports and is running. Nothing to do
// just yet.
return;
}
}
if (run_forever_) {
// We need this script to run forever. We have already recorded the last
// error. Keep going.
return;
}
if (!has_terminated) {
// Only try to terminate the loop once.
has_terminated = true;
main_task_runner_->PostTask(
[]() { fml::MessageLoop::GetCurrent().Terminate(); });
}
}
private:
fml::WeakPtr<Engine> engine_;
fml::RefPtr<fml::TaskRunner> main_task_runner_;
bool run_forever_ = false;
tonic::DartErrorHandleType last_error_ = tonic::kUnknownErrorType;
bool has_terminated = false;
FML_DISALLOW_COPY_AND_ASSIGN(ScriptCompletionTaskObserver);
};
int RunTester(const blink::Settings& settings, bool run_forever) {
const auto thread_label = "io.flutter.test";
fml::MessageLoop::EnsureInitializedForCurrentThread();
auto current_task_runner = fml::MessageLoop::GetCurrent().GetTaskRunner();
// Setup a single threaded test runner configuration.
const blink::TaskRunners task_runners(thread_label, // dart thread label
current_task_runner, // platform
current_task_runner, // gpu
current_task_runner, // ui
current_task_runner // io
);
Shell::CreateCallback<PlatformView> on_create_platform_view =
[](Shell& shell) {
return std::make_unique<PlatformView>(shell, shell.GetTaskRunners());
};
Shell::CreateCallback<Rasterizer> on_create_rasterizer = [](Shell& shell) {
return std::make_unique<Rasterizer>(shell.GetTaskRunners());
};
auto shell = Shell::Create(task_runners, //
settings, //
on_create_platform_view, //
on_create_rasterizer //
);
if (!shell || !shell->IsSetup()) {
FML_LOG(ERROR) << "Could not setup the shell.";
return EXIT_FAILURE;
}
if (settings.application_kernel_asset.empty()) {
FML_LOG(ERROR) << "Dart kernel file not specified.";
return EXIT_FAILURE;
}
// Initialize default testing locales. There is no platform to
// pass locales on the tester, so to retain expected locale behavior,
// we emulate it in here by passing in 'en_US' and 'zh_CN' as test locales.
const char* locale_json =
"{\"method\":\"setLocale\",\"args\":[\"en\",\"US\",\"\",\"\",\"zh\","
"\"CN\",\"\",\"\"]}";
std::vector<uint8_t> locale_bytes(locale_json,
locale_json + std::strlen(locale_json));
fml::RefPtr<blink::PlatformMessageResponse> response;
shell->GetPlatformView()->DispatchPlatformMessage(
fml::MakeRefCounted<blink::PlatformMessage>("flutter/localization",
locale_bytes, response));
std::initializer_list<fml::FileMapping::Protection> protection = {
fml::FileMapping::Protection::kRead};
auto main_dart_file_mapping = std::make_unique<fml::FileMapping>(
fml::OpenFile(
fml::paths::AbsolutePath(settings.application_kernel_asset).c_str(),
false, fml::FilePermission::kRead),
protection);
auto isolate_configuration =
IsolateConfiguration::CreateForKernel(std::move(main_dart_file_mapping));
if (!isolate_configuration) {
FML_LOG(ERROR) << "Could create isolate configuration.";
return EXIT_FAILURE;
}
auto asset_manager = std::make_shared<blink::AssetManager>();
asset_manager->PushBack(std::make_unique<blink::DirectoryAssetBundle>(
fml::Duplicate(settings.assets_dir)));
asset_manager->PushBack(
std::make_unique<blink::DirectoryAssetBundle>(fml::OpenDirectory(
settings.assets_path.c_str(), false, fml::FilePermission::kRead)));
RunConfiguration run_configuration(std::move(isolate_configuration),
std::move(asset_manager));
// The script completion task observer that will be installed on the UI thread
// that watched if the engine has any live ports.
ScriptCompletionTaskObserver completion_observer(
*shell, // a valid shell
fml::MessageLoop::GetCurrent()
.GetTaskRunner(), // the message loop to terminate
run_forever // should the exit be ignored
);
bool engine_did_run = false;
fml::AutoResetWaitableEvent sync_run_latch;
fml::TaskRunner::RunNowOrPostTask(
shell->GetTaskRunners().GetUITaskRunner(),
fml::MakeCopyable([&sync_run_latch, &completion_observer,
engine = shell->GetEngine(),
config = std::move(run_configuration),
&engine_did_run]() mutable {
fml::MessageLoop::GetCurrent().AddTaskObserver(
reinterpret_cast<intptr_t>(&completion_observer),
[&completion_observer]() { completion_observer.DidProcessTask(); });
if (engine->Run(std::move(config)) !=
shell::Engine::RunStatus::Failure) {
engine_did_run = true;
blink::ViewportMetrics metrics;
metrics.device_pixel_ratio = 3.0;
metrics.physical_width = 2400; // 800 at 3x resolution
metrics.physical_height = 1800; // 600 at 3x resolution
engine->SetViewportMetrics(metrics);
} else {
FML_DLOG(ERROR) << "Could not launch the engine with configuration.";
}
sync_run_latch.Signal();
}));
sync_run_latch.Wait();
// Run the message loop and wait for the script to do its thing.
fml::MessageLoop::GetCurrent().Run();
// Cleanup the completion observer synchronously as it is living on the
// stack.
fml::AutoResetWaitableEvent latch;
fml::TaskRunner::RunNowOrPostTask(
shell->GetTaskRunners().GetUITaskRunner(),
[&latch, &completion_observer] {
fml::MessageLoop::GetCurrent().RemoveTaskObserver(
reinterpret_cast<intptr_t>(&completion_observer));
latch.Signal();
});
latch.Wait();
if (!engine_did_run) {
// If the engine itself didn't have a chance to run, there is no point in
// asking it if there was an error. Signal a failure unconditionally.
return EXIT_FAILURE;
}
return completion_observer.GetExitCodeForLastError();
}
} // namespace shell
int main(int argc, char* argv[]) {
dart::bin::SetExecutableName(argv[0]);
dart::bin::SetExecutableArguments(argc - 1, argv);
auto command_line = fml::CommandLineFromArgcArgv(argc, argv);
if (command_line.HasOption(shell::FlagForSwitch(shell::Switch::Help))) {
shell::PrintUsage("flutter_tester");
return EXIT_SUCCESS;
}
auto settings = shell::SettingsFromCommandLine(command_line);
if (command_line.positional_args().size() > 0) {
// The tester may not use the switch for the main dart file path. Specifying
// it as a positional argument instead.
settings.application_kernel_asset = command_line.positional_args()[0];
}
if (settings.application_kernel_asset.size() == 0) {
FML_LOG(ERROR) << "Dart kernel file not specified.";
return EXIT_FAILURE;
}
if (settings.icu_data_path.size() == 0) {
settings.icu_data_path = "icudtl.dat";
}
// The tools that read logs get confused if there is a log tag specified.
settings.log_tag = "";
settings.task_observer_add = [](intptr_t key, fml::closure callback) {
fml::MessageLoop::GetCurrent().AddTaskObserver(key, std::move(callback));
};
settings.task_observer_remove = [](intptr_t key) {
fml::MessageLoop::GetCurrent().RemoveTaskObserver(key);
};
return shell::RunTester(
settings,
command_line.HasOption(shell::FlagForSwitch(shell::Switch::RunForever)));
}
<|endoftext|> |
<commit_before>// Copyright 2019 DeepMind Technologies Ltd. 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 "open_spiel/algorithms/mcts.h"
#include <algorithm>
#include <cmath>
#include <limits>
#include <memory>
#include <random>
#include <vector>
#include "open_spiel/abseil-cpp/absl/algorithm/container.h"
#include "open_spiel/abseil-cpp/absl/random/uniform_int_distribution.h"
#include "open_spiel/abseil-cpp/absl/strings/str_cat.h"
#include "open_spiel/abseil-cpp/absl/strings/str_format.h"
#include "open_spiel/abseil-cpp/absl/time/clock.h"
#include "open_spiel/abseil-cpp/absl/time/time.h"
#include "open_spiel/spiel.h"
#include "open_spiel/spiel_utils.h"
namespace open_spiel {
namespace algorithms {
// Return the memory use of a vector. Useful to track and limit memory use when
// running for a long time and build a big tree (eg to solve a game).
template <class T>
constexpr inline int VectorMemory(const std::vector<T>& vec) {
return sizeof(T) * vec.capacity();
}
std::vector<double> RandomRolloutEvaluator::Evaluate(const State& state) {
std::vector<double> result;
for (int i = 0; i < n_rollouts_; ++i) {
std::unique_ptr<State> working_state = state.Clone();
while (!working_state->IsTerminal()) {
if (working_state->IsChanceNode()) {
ActionsAndProbs outcomes = working_state->ChanceOutcomes();
Action action =
SampleAction(outcomes,
std::uniform_real_distribution<double>(0.0, 1.0)(rng_))
.first;
working_state->ApplyAction(action);
} else {
std::vector<Action> actions = working_state->LegalActions();
absl::uniform_int_distribution<int> dist(0, actions.size() - 1);
int index = dist(rng_);
working_state->ApplyAction(actions[index]);
}
}
std::vector<double> returns = working_state->Returns();
if (result.empty()) {
result.swap(returns);
} else {
SPIEL_CHECK_EQ(returns.size(), result.size());
for (int i = 0; i < result.size(); ++i) {
result[i] += returns[i];
}
}
}
for (int i = 0; i < result.size(); ++i) {
result[i] /= n_rollouts_;
}
return result;
}
ActionsAndProbs RandomRolloutEvaluator::Prior(const State& state) {
// Returns equal probability for all actions.
if (state.IsChanceNode()) {
return state.ChanceOutcomes();
} else {
std::vector<Action> legal_actions = state.LegalActions();
ActionsAndProbs prior;
prior.reserve(legal_actions.size());
for (const Action& action : legal_actions) {
prior.emplace_back(action, 1.0 / legal_actions.size());
}
return prior;
}
}
// UCT value of given child
double SearchNode::UCTValue(int parent_explore_count, double uct_c) const {
if (!outcome.empty()) {
return outcome[player];
}
if (explore_count == 0) return std::numeric_limits<double>::infinity();
// The "greedy-value" of choosing a given child is always with respect to
// the current player for this node.
return total_reward / explore_count +
uct_c * std::sqrt(std::log(parent_explore_count) / explore_count);
}
double SearchNode::PUCTValue(int parent_explore_count, double uct_c) const {
// Returns the PUCT value of this node.
if (!outcome.empty()) {
return outcome[player];
}
return ((explore_count != 0 ? total_reward / explore_count : 0) +
uct_c * prior * std::sqrt(parent_explore_count) /
(explore_count + 1));
}
bool SearchNode::CompareFinal(const SearchNode& b) const {
double out = (outcome.empty() ? 0 : outcome[player]);
double out_b = (b.outcome.empty() ? 0 : b.outcome[b.player]);
if (out != out_b) {
return out < out_b;
}
if (explore_count != b.explore_count) {
return explore_count < b.explore_count;
}
return total_reward < b.total_reward;
}
const SearchNode& SearchNode::BestChild() const {
// Returns the best action from this node, either proven or most visited.
//
// This ordering leads to choosing:
// - Highest proven score > 0 over anything else, including a promising but
// unproven action.
// - A proven draw only if it has higher exploration than others that are
// uncertain, or the others are losses.
// - Uncertain action with most exploration over loss of any difficulty
// - Hardest loss if everything is a loss
// - Highest expected reward if explore counts are equal (unlikely).
// - Longest win, if multiple are proven (unlikely due to early stopping).
return *std::max_element(children.begin(), children.end(),
[](const SearchNode& a, const SearchNode& b) {
return a.CompareFinal(b);
});
}
std::string SearchNode::ChildrenStr(const State& state) const {
std::string out;
if (!children.empty()) {
std::vector<const SearchNode*> refs; // Sort a list of refs, not a copy.
refs.reserve(children.size());
for (const SearchNode& child : children) {
refs.push_back(&child);
}
std::sort(refs.begin(), refs.end(),
[](const SearchNode* a, const SearchNode* b) {
return b->CompareFinal(*a);
});
for (const SearchNode* child : refs) {
absl::StrAppend(&out, child->ToString(state), "\n");
}
}
return out;
}
std::string SearchNode::ToString(const State& state) const {
return absl::StrFormat(
"%6s: player: %d, prior: %5.3f, value: %6.3f, sims: %5d, outcome: %s, "
"%3d children",
(action != kInvalidAction ? state.ActionToString(player, action)
: "none"),
player, prior, (explore_count ? total_reward / explore_count : 0.),
explore_count,
(outcome.empty()
? "none"
: absl::StrFormat("%4.1f",
outcome[player == kChancePlayerId ? 0 : player])),
children.size());
}
std::vector<double> dirichlet_noise(int count, double alpha,
std::mt19937* rng) {
auto noise = std::vector<double>{};
noise.reserve(count);
std::gamma_distribution<double> gamma(alpha, 1.0);
for (int i = 0; i < count; ++i) {
noise.emplace_back(gamma(*rng));
}
double sum = absl::c_accumulate(noise, 0.0);
for (double& v : noise) {
v /= sum;
}
return noise;
}
MCTSBot::MCTSBot(const Game& game, Evaluator* evaluator,
double uct_c, int max_simulations, int64_t max_memory_mb,
bool solve, int seed, bool verbose,
ChildSelectionPolicy child_selection_policy,
double dirichlet_alpha, double dirichlet_epsilon)
: uct_c_{uct_c},
max_simulations_{max_simulations},
max_memory_(max_memory_mb << 20), // megabytes -> bytes
verbose_(verbose),
solve_(solve),
max_utility_(game.MaxUtility()),
dirichlet_alpha_(dirichlet_alpha),
dirichlet_epsilon_(dirichlet_epsilon),
rng_(seed),
child_selection_policy_(child_selection_policy),
evaluator_{evaluator} {
GameType game_type = game.GetType();
if (game_type.reward_model != GameType::RewardModel::kTerminal)
SpielFatalError("Game must have terminal rewards.");
if (game_type.dynamics != GameType::Dynamics::kSequential)
SpielFatalError("Game must have sequential turns.");
}
Action MCTSBot::Step(const State& state) {
absl::Time start = absl::Now();
std::unique_ptr<SearchNode> root = MCTSearch(state);
const SearchNode& best = root->BestChild();
if (verbose_) {
double seconds = absl::ToDoubleSeconds(absl::Now() - start);
std::cerr
<< absl::StrFormat(
"Finished %d sims in %.3f secs, %.1f sims/s, tree size: %d mb.",
root->explore_count, seconds, (root->explore_count / seconds),
memory_used_ / (1 << 20))
<< std::endl;
std::cerr << "Root:" << std::endl;
std::cerr << root->ToString(state) << std::endl;
std::cerr << "Children:" << std::endl;
std::cerr << root->ChildrenStr(state) << std::endl;
if (!best.children.empty()) {
std::unique_ptr<State> chosen_state = state.Clone();
chosen_state->ApplyAction(best.action);
std::cerr << "Children of chosen:" << std::endl;
std::cerr << best.ChildrenStr(*chosen_state) << std::endl;
}
}
return best.action;
}
std::pair<ActionsAndProbs, Action> MCTSBot::StepWithPolicy(const State& state) {
Action action = Step(state);
return {{{action, 1.}}, action};
}
std::unique_ptr<State> MCTSBot::ApplyTreePolicy(
SearchNode* root, const State& state,
std::vector<SearchNode*>* visit_path) {
visit_path->push_back(root);
std::unique_ptr<State> working_state = state.Clone();
SearchNode* current_node = root;
while (!working_state->IsTerminal() && current_node->explore_count > 0) {
if (current_node->children.empty()) {
// For a new node, initialize its state, then choose a child as normal.
ActionsAndProbs legal_actions = evaluator_->Prior(*working_state);
if (current_node == root && dirichlet_alpha_ > 0) {
std::vector<double> noise =
dirichlet_noise(legal_actions.size(), dirichlet_alpha_, &rng_);
for (int i = 0; i < legal_actions.size(); i++) {
legal_actions[i].second =
(1 - dirichlet_epsilon_) * legal_actions[i].second +
dirichlet_epsilon_ * noise[i];
}
}
// Reduce bias from move generation order.
std::shuffle(legal_actions.begin(), legal_actions.end(), rng_);
Player player = working_state->CurrentPlayer();
current_node->children.reserve(legal_actions.size());
for (auto [action, prior] : legal_actions) {
current_node->children.emplace_back(action, player, prior);
}
memory_used_ += VectorMemory(legal_actions);
}
SearchNode* chosen_child = nullptr;
if (working_state->IsChanceNode()) {
// For chance nodes, rollout according to chance node's probability
// distribution
Action chosen_action =
SampleAction(working_state->ChanceOutcomes(),
std::uniform_real_distribution<double>(0.0, 1.0)(rng_))
.first;
for (SearchNode& child : current_node->children) {
if (child.action == chosen_action) {
chosen_child = &child;
break;
}
}
} else {
// Otherwise choose node with largest UCT value.
double max_value = -std::numeric_limits<double>::infinity();
for (SearchNode& child : current_node->children) {
double val;
switch (child_selection_policy_) {
case ChildSelectionPolicy::UCT:
val = child.UCTValue(current_node->explore_count, uct_c_);
break;
case ChildSelectionPolicy::PUCT:
val = child.PUCTValue(current_node->explore_count, uct_c_);
break;
}
if (val > max_value) {
max_value = val;
chosen_child = &child;
}
}
}
working_state->ApplyAction(chosen_child->action);
current_node = chosen_child;
visit_path->push_back(current_node);
}
return working_state;
}
std::unique_ptr<SearchNode> MCTSBot::MCTSearch(const State& state) {
Player player_id = state.CurrentPlayer();
memory_used_ = 0;
auto root = std::make_unique<SearchNode>(kInvalidAction, player_id, 1);
std::vector<SearchNode*> visit_path;
std::vector<double> returns;
visit_path.reserve(64);
for (int i = 0; i < max_simulations_; ++i) {
visit_path.clear();
returns.clear();
std::unique_ptr<State> working_state =
ApplyTreePolicy(root.get(), state, &visit_path);
bool solved;
if (working_state->IsTerminal()) {
returns = working_state->Returns();
visit_path[visit_path.size() - 1]->outcome = returns;
memory_used_ += VectorMemory(returns);
solved = solve_;
} else {
returns = evaluator_->Evaluate(*working_state);
solved = false;
}
// Propagate values back.
for (auto it = visit_path.rbegin(); it != visit_path.rend(); ++it) {
SearchNode* node = *it;
node->total_reward +=
returns[node->player == kChancePlayerId ? player_id : node->player];
node->explore_count += 1;
// Back up solved results as well.
if (solved && !node->children.empty()) {
Player player = node->children[0].player;
if (player == kChancePlayerId) {
// Only back up chance nodes if all have the same outcome.
// An alternative would be to back up the weighted average of
// outcomes if all children are solved, but that is less clear.
const std::vector<double>& outcome = node->children[0].outcome;
if (!outcome.empty() &&
std::all_of(node->children.begin() + 1, node->children.end(),
[&outcome](const SearchNode& c) {
return c.outcome == outcome;
})) {
node->outcome = outcome;
memory_used_ += VectorMemory(node->outcome);
} else {
solved = false;
}
} else {
// If any have max utility (won?), or all children are solved,
// choose the one best for the player choosing.
const SearchNode* best = nullptr;
bool all_solved = true;
for (const SearchNode& child : node->children) {
if (child.outcome.empty()) {
all_solved = false;
} else if (best == nullptr ||
child.outcome[player] > best->outcome[player]) {
best = &child;
}
}
if (best != nullptr &&
(all_solved || best->outcome[player] == max_utility_)) {
node->outcome = best->outcome;
memory_used_ += VectorMemory(node->outcome);
} else {
solved = false;
}
}
}
}
if (!root->outcome.empty() || // Full game tree is solved.
(max_memory_ && memory_used_ >= max_memory_) ||
root->children.size() == 1) {
break;
}
}
return root;
}
} // namespace algorithms
} // namespace open_spiel
<commit_msg>Initialize directly instead of using auto.<commit_after>// Copyright 2019 DeepMind Technologies Ltd. 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 "open_spiel/algorithms/mcts.h"
#include <algorithm>
#include <cmath>
#include <limits>
#include <memory>
#include <random>
#include <vector>
#include "open_spiel/abseil-cpp/absl/algorithm/container.h"
#include "open_spiel/abseil-cpp/absl/random/uniform_int_distribution.h"
#include "open_spiel/abseil-cpp/absl/strings/str_cat.h"
#include "open_spiel/abseil-cpp/absl/strings/str_format.h"
#include "open_spiel/abseil-cpp/absl/time/clock.h"
#include "open_spiel/abseil-cpp/absl/time/time.h"
#include "open_spiel/spiel.h"
#include "open_spiel/spiel_utils.h"
namespace open_spiel {
namespace algorithms {
// Return the memory use of a vector. Useful to track and limit memory use when
// running for a long time and build a big tree (eg to solve a game).
template <class T>
constexpr inline int VectorMemory(const std::vector<T>& vec) {
return sizeof(T) * vec.capacity();
}
std::vector<double> RandomRolloutEvaluator::Evaluate(const State& state) {
std::vector<double> result;
for (int i = 0; i < n_rollouts_; ++i) {
std::unique_ptr<State> working_state = state.Clone();
while (!working_state->IsTerminal()) {
if (working_state->IsChanceNode()) {
ActionsAndProbs outcomes = working_state->ChanceOutcomes();
Action action =
SampleAction(outcomes,
std::uniform_real_distribution<double>(0.0, 1.0)(rng_))
.first;
working_state->ApplyAction(action);
} else {
std::vector<Action> actions = working_state->LegalActions();
absl::uniform_int_distribution<int> dist(0, actions.size() - 1);
int index = dist(rng_);
working_state->ApplyAction(actions[index]);
}
}
std::vector<double> returns = working_state->Returns();
if (result.empty()) {
result.swap(returns);
} else {
SPIEL_CHECK_EQ(returns.size(), result.size());
for (int i = 0; i < result.size(); ++i) {
result[i] += returns[i];
}
}
}
for (int i = 0; i < result.size(); ++i) {
result[i] /= n_rollouts_;
}
return result;
}
ActionsAndProbs RandomRolloutEvaluator::Prior(const State& state) {
// Returns equal probability for all actions.
if (state.IsChanceNode()) {
return state.ChanceOutcomes();
} else {
std::vector<Action> legal_actions = state.LegalActions();
ActionsAndProbs prior;
prior.reserve(legal_actions.size());
for (const Action& action : legal_actions) {
prior.emplace_back(action, 1.0 / legal_actions.size());
}
return prior;
}
}
// UCT value of given child
double SearchNode::UCTValue(int parent_explore_count, double uct_c) const {
if (!outcome.empty()) {
return outcome[player];
}
if (explore_count == 0) return std::numeric_limits<double>::infinity();
// The "greedy-value" of choosing a given child is always with respect to
// the current player for this node.
return total_reward / explore_count +
uct_c * std::sqrt(std::log(parent_explore_count) / explore_count);
}
double SearchNode::PUCTValue(int parent_explore_count, double uct_c) const {
// Returns the PUCT value of this node.
if (!outcome.empty()) {
return outcome[player];
}
return ((explore_count != 0 ? total_reward / explore_count : 0) +
uct_c * prior * std::sqrt(parent_explore_count) /
(explore_count + 1));
}
bool SearchNode::CompareFinal(const SearchNode& b) const {
double out = (outcome.empty() ? 0 : outcome[player]);
double out_b = (b.outcome.empty() ? 0 : b.outcome[b.player]);
if (out != out_b) {
return out < out_b;
}
if (explore_count != b.explore_count) {
return explore_count < b.explore_count;
}
return total_reward < b.total_reward;
}
const SearchNode& SearchNode::BestChild() const {
// Returns the best action from this node, either proven or most visited.
//
// This ordering leads to choosing:
// - Highest proven score > 0 over anything else, including a promising but
// unproven action.
// - A proven draw only if it has higher exploration than others that are
// uncertain, or the others are losses.
// - Uncertain action with most exploration over loss of any difficulty
// - Hardest loss if everything is a loss
// - Highest expected reward if explore counts are equal (unlikely).
// - Longest win, if multiple are proven (unlikely due to early stopping).
return *std::max_element(children.begin(), children.end(),
[](const SearchNode& a, const SearchNode& b) {
return a.CompareFinal(b);
});
}
std::string SearchNode::ChildrenStr(const State& state) const {
std::string out;
if (!children.empty()) {
std::vector<const SearchNode*> refs; // Sort a list of refs, not a copy.
refs.reserve(children.size());
for (const SearchNode& child : children) {
refs.push_back(&child);
}
std::sort(refs.begin(), refs.end(),
[](const SearchNode* a, const SearchNode* b) {
return b->CompareFinal(*a);
});
for (const SearchNode* child : refs) {
absl::StrAppend(&out, child->ToString(state), "\n");
}
}
return out;
}
std::string SearchNode::ToString(const State& state) const {
return absl::StrFormat(
"%6s: player: %d, prior: %5.3f, value: %6.3f, sims: %5d, outcome: %s, "
"%3d children",
(action != kInvalidAction ? state.ActionToString(player, action)
: "none"),
player, prior, (explore_count ? total_reward / explore_count : 0.),
explore_count,
(outcome.empty()
? "none"
: absl::StrFormat("%4.1f",
outcome[player == kChancePlayerId ? 0 : player])),
children.size());
}
std::vector<double> dirichlet_noise(int count, double alpha,
std::mt19937* rng) {
std::vector<double> noise;
noise.reserve(count);
std::gamma_distribution<double> gamma(alpha, 1.0);
for (int i = 0; i < count; ++i) {
noise.emplace_back(gamma(*rng));
}
double sum = absl::c_accumulate(noise, 0.0);
for (double& v : noise) {
v /= sum;
}
return noise;
}
MCTSBot::MCTSBot(const Game& game, Evaluator* evaluator,
double uct_c, int max_simulations, int64_t max_memory_mb,
bool solve, int seed, bool verbose,
ChildSelectionPolicy child_selection_policy,
double dirichlet_alpha, double dirichlet_epsilon)
: uct_c_{uct_c},
max_simulations_{max_simulations},
max_memory_(max_memory_mb << 20), // megabytes -> bytes
verbose_(verbose),
solve_(solve),
max_utility_(game.MaxUtility()),
dirichlet_alpha_(dirichlet_alpha),
dirichlet_epsilon_(dirichlet_epsilon),
rng_(seed),
child_selection_policy_(child_selection_policy),
evaluator_{evaluator} {
GameType game_type = game.GetType();
if (game_type.reward_model != GameType::RewardModel::kTerminal)
SpielFatalError("Game must have terminal rewards.");
if (game_type.dynamics != GameType::Dynamics::kSequential)
SpielFatalError("Game must have sequential turns.");
}
Action MCTSBot::Step(const State& state) {
absl::Time start = absl::Now();
std::unique_ptr<SearchNode> root = MCTSearch(state);
const SearchNode& best = root->BestChild();
if (verbose_) {
double seconds = absl::ToDoubleSeconds(absl::Now() - start);
std::cerr
<< absl::StrFormat(
"Finished %d sims in %.3f secs, %.1f sims/s, tree size: %d mb.",
root->explore_count, seconds, (root->explore_count / seconds),
memory_used_ / (1 << 20))
<< std::endl;
std::cerr << "Root:" << std::endl;
std::cerr << root->ToString(state) << std::endl;
std::cerr << "Children:" << std::endl;
std::cerr << root->ChildrenStr(state) << std::endl;
if (!best.children.empty()) {
std::unique_ptr<State> chosen_state = state.Clone();
chosen_state->ApplyAction(best.action);
std::cerr << "Children of chosen:" << std::endl;
std::cerr << best.ChildrenStr(*chosen_state) << std::endl;
}
}
return best.action;
}
std::pair<ActionsAndProbs, Action> MCTSBot::StepWithPolicy(const State& state) {
Action action = Step(state);
return {{{action, 1.}}, action};
}
std::unique_ptr<State> MCTSBot::ApplyTreePolicy(
SearchNode* root, const State& state,
std::vector<SearchNode*>* visit_path) {
visit_path->push_back(root);
std::unique_ptr<State> working_state = state.Clone();
SearchNode* current_node = root;
while (!working_state->IsTerminal() && current_node->explore_count > 0) {
if (current_node->children.empty()) {
// For a new node, initialize its state, then choose a child as normal.
ActionsAndProbs legal_actions = evaluator_->Prior(*working_state);
if (current_node == root && dirichlet_alpha_ > 0) {
std::vector<double> noise =
dirichlet_noise(legal_actions.size(), dirichlet_alpha_, &rng_);
for (int i = 0; i < legal_actions.size(); i++) {
legal_actions[i].second =
(1 - dirichlet_epsilon_) * legal_actions[i].second +
dirichlet_epsilon_ * noise[i];
}
}
// Reduce bias from move generation order.
std::shuffle(legal_actions.begin(), legal_actions.end(), rng_);
Player player = working_state->CurrentPlayer();
current_node->children.reserve(legal_actions.size());
for (auto [action, prior] : legal_actions) {
current_node->children.emplace_back(action, player, prior);
}
memory_used_ += VectorMemory(legal_actions);
}
SearchNode* chosen_child = nullptr;
if (working_state->IsChanceNode()) {
// For chance nodes, rollout according to chance node's probability
// distribution
Action chosen_action =
SampleAction(working_state->ChanceOutcomes(),
std::uniform_real_distribution<double>(0.0, 1.0)(rng_))
.first;
for (SearchNode& child : current_node->children) {
if (child.action == chosen_action) {
chosen_child = &child;
break;
}
}
} else {
// Otherwise choose node with largest UCT value.
double max_value = -std::numeric_limits<double>::infinity();
for (SearchNode& child : current_node->children) {
double val;
switch (child_selection_policy_) {
case ChildSelectionPolicy::UCT:
val = child.UCTValue(current_node->explore_count, uct_c_);
break;
case ChildSelectionPolicy::PUCT:
val = child.PUCTValue(current_node->explore_count, uct_c_);
break;
}
if (val > max_value) {
max_value = val;
chosen_child = &child;
}
}
}
working_state->ApplyAction(chosen_child->action);
current_node = chosen_child;
visit_path->push_back(current_node);
}
return working_state;
}
std::unique_ptr<SearchNode> MCTSBot::MCTSearch(const State& state) {
Player player_id = state.CurrentPlayer();
memory_used_ = 0;
auto root = std::make_unique<SearchNode>(kInvalidAction, player_id, 1);
std::vector<SearchNode*> visit_path;
std::vector<double> returns;
visit_path.reserve(64);
for (int i = 0; i < max_simulations_; ++i) {
visit_path.clear();
returns.clear();
std::unique_ptr<State> working_state =
ApplyTreePolicy(root.get(), state, &visit_path);
bool solved;
if (working_state->IsTerminal()) {
returns = working_state->Returns();
visit_path[visit_path.size() - 1]->outcome = returns;
memory_used_ += VectorMemory(returns);
solved = solve_;
} else {
returns = evaluator_->Evaluate(*working_state);
solved = false;
}
// Propagate values back.
for (auto it = visit_path.rbegin(); it != visit_path.rend(); ++it) {
SearchNode* node = *it;
node->total_reward +=
returns[node->player == kChancePlayerId ? player_id : node->player];
node->explore_count += 1;
// Back up solved results as well.
if (solved && !node->children.empty()) {
Player player = node->children[0].player;
if (player == kChancePlayerId) {
// Only back up chance nodes if all have the same outcome.
// An alternative would be to back up the weighted average of
// outcomes if all children are solved, but that is less clear.
const std::vector<double>& outcome = node->children[0].outcome;
if (!outcome.empty() &&
std::all_of(node->children.begin() + 1, node->children.end(),
[&outcome](const SearchNode& c) {
return c.outcome == outcome;
})) {
node->outcome = outcome;
memory_used_ += VectorMemory(node->outcome);
} else {
solved = false;
}
} else {
// If any have max utility (won?), or all children are solved,
// choose the one best for the player choosing.
const SearchNode* best = nullptr;
bool all_solved = true;
for (const SearchNode& child : node->children) {
if (child.outcome.empty()) {
all_solved = false;
} else if (best == nullptr ||
child.outcome[player] > best->outcome[player]) {
best = &child;
}
}
if (best != nullptr &&
(all_solved || best->outcome[player] == max_utility_)) {
node->outcome = best->outcome;
memory_used_ += VectorMemory(node->outcome);
} else {
solved = false;
}
}
}
}
if (!root->outcome.empty() || // Full game tree is solved.
(max_memory_ && memory_used_ >= max_memory_) ||
root->children.size() == 1) {
break;
}
}
return root;
}
} // namespace algorithms
} // namespace open_spiel
<|endoftext|> |
<commit_before>/*
* IRC interfaces for La Cogita IRC chatbot
* Copyright (C) 2007 Linas Vepstas <[email protected]>
*
* 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
/*
* Go onto IRC
* This is pretty totally a pure hack with little/no design to it.
* Linas October 2007
*/
#include <string.h>
#include <stdlib.h>
#include <sys/types.h>
#include <unistd.h>
#include <getopt.h>
#include <string>
#include <vector>
#include <set>
#include <boost/foreach.hpp>
#define foreach BOOST_FOREACH
#include "IRC.h"
#include "CogitaConfig.h"
#include "whirr-sockets.h"
using namespace opencog::chatbot;
using std::string;
CogitaConfig cc;
/* printf can puke if these fields are NULL */
void fixup_reply(irc_reply_data* ird)
{
ird->nick = (NULL == ird->nick) ? "" : ird->nick;
ird->ident = (NULL == ird->ident) ? "" : ird->ident;
ird->host = (NULL == ird->host) ? "" : ird->host;
ird->target = (NULL == ird->target) ? "" : ird->target;
}
/**
* Join channel shortly after logging into the irc server.
*/
int end_of_motd(const char* params, irc_reply_data* ird, void* data)
{
IRC* conn = (IRC*) data;
fixup_reply(ird);
printf("chatbot got params=%s\n", params);
printf("chatbot got motd nick=%s ident=%s host=%s target=%s\n",
ird->nick, ird->ident, ird->host, ird->target);
sleep(1);
conn->join (cc.ircChannels[0].c_str());
printf("chatbot sent channel join %s\n", cc.ircChannels[0].c_str());
sleep(2);
conn->notice (cc.ircChannels[0].c_str(), "ola");
printf("chatbot sent channel notice\n");
sleep(2);
conn->privmsg (cc.ircChannels[0].c_str(), "here we are");
printf("chatbot said hello to the channel\n");
return 0;
}
/* return true if not all whitespace */
static bool is_nonblank(const char * str)
{
size_t len = strlen(str);
if (0 == len) return false;
size_t blanks = strspn(str, " \n\r\t\v");
if (blanks == len) return false;
return true;
}
/**
* Handle a message received from IRC.
*/
int got_privmsg(const char* params, irc_reply_data* ird, void* data)
{
IRC* conn = (IRC*) data;
fixup_reply(ird);
printf("input=%s\n", params);
printf("nick=%s ident=%s host=%s target=%s\n", ird->nick, ird->ident, ird->host, ird->target);
typedef enum {ENGLISH=1, SHELL_CMD, SCM_CMD} CmdType;
CmdType cmd = ENGLISH;
const char * start = NULL;
int priv = 0;
if (!strcmp (ird->target, cc.nick.c_str())) {priv = 1; start = params+1; }
if (!strncmp (¶ms[1], cc.nick.c_str(), cc.nick.size())) {
start = params+1 + cc.nick.size();
start = strchr(start, ':');
if (start) start ++;
} else if (!strncmp (params, ":cog-sh:", 8)) {
start = params+8; cmd = SHELL_CMD;
} else if (!strncmp (params, ":scm:", 5)) {
start = params+5; cmd = SCM_CMD;
} else {
// Check for alternative nick/attention strings
foreach (string it, cc.attn) {
if (! it.compare(0,it.size(),¶ms[1]) ) {
start = params + it.size();
start = strchr(start, ':');
if (start) start ++;
break;
}
}
}
if (!start) return 0;
char * msg_target = NULL;
if (priv)
{
msg_target = ird->nick;
}
else
{
msg_target = ird->target;
}
// Reply to request for chat client version
if ((0x1 == start[0]) && !strncmp (&start[1], "VERSION", 7))
{
printf ("VERSION: %s\n", cc.vstring.c_str());
conn->privmsg (msg_target, cc.vstring.c_str());
return 0;
}
// printf ("duude starting with 0x%x %s\n", start[0], start);
size_t textlen = strlen(start);
size_t len = textlen;
len += strlen ("(say-id-english )");
len += strlen (ird->nick);
len += 120;
char * cmdline = (char *) malloc(sizeof (char) * (len+1));
if (ENGLISH == cmd)
{
// Get into the opencog scheme shell, and run the command
strcpy (cmdline, "scm hush\n(say-id-english \"");
strcat (cmdline, ird->nick);
strcat (cmdline, "\" \"");
size_t toff = strlen(cmdline);
strcat (cmdline, start);
strcat (cmdline, "\")\n");
// strip out quotation marks, replace with blanks, for now.
for (size_t i =0; i<textlen; i++)
{
if ('\"' == cmdline[toff+i]) cmdline[toff+i] = ' ';
}
}
// #define ENABLE_SHELL_ESCAPES 0
#if ENABLE_SHELL_ESCAPES
/*
* XXX DANGER DANGER Extreme Caution Advised XXX
* Shell escapes are a potential security hole, as they allow access
* to the cog-server to total strangers. In particular, the scheme
* interface is a general programming API and can be used to root
* the system.
*/
else if (SHELL_CMD == cmd)
{
strcpy (cmdline, start);
strcat (cmdline, "\n");
}
else if (SCM_CMD == cmd)
{
strcpy (cmdline, "scm hush\n");
strcat (cmdline, start);
strcat (cmdline, "\n");
}
#else
else
{
conn->privmsg (msg_target, "Shell escapes disabled in this chatbot version\n");
return 0;
}
#endif /* ENABLE_SHELL_ESCAPES */
#define FLOOD_CHAR_COUNT 120
size_t flood_cnt = FLOOD_CHAR_COUNT;
size_t cnt = 0;
bool dosend = true;
// printf ("Sending to opencog: %s\n", cmdline);
char * reply = whirr_sock_io (cmdline);
free(cmdline);
cmdline = NULL;
printf ("opencog reply: %s\n", reply);
/* Each newline has to be on its own line */
/* Limit length of reply so we don't get kicked for flooding */
char * p = reply;
while (*p)
{
char *ep = strchr (p, '\n');
// The last line -- no newline found.
if (!ep)
{
if (is_nonblank(p))
conn->privmsg (msg_target, p);
break;
}
ep ++;
int save = *ep;
*ep = 0x0;
// If the line starts with ":scm", resubmit it to the
// server. This is a kind-of cheap, hacky way of doing
// multi-processing.
if (0 == strncmp(p, ":scm", 4))
{
char * cr = strchr(p, '\r');
if (cr) *cr = '\n';
char * r = whirr_sock_io (p+1);
free(reply);
reply = r;
p = reply;
printf ("opencog reply: %s\n", reply);
continue;
}
// If the line starts with ":dbg", the do not send to chatroom
if (0 == strncmp(p, ":dbg", 4))
{
*ep = save;
p = ep;
dosend = false;
continue;
}
if (0 == strncmp(p, ":end-dbg", 8))
{
*ep = save;
p = ep;
dosend = true;
continue;
}
// Else send output to chatroom
if (dosend && is_nonblank(p))
{
conn->privmsg (msg_target, p);
cnt += strlen (p);
/* Sleep so that we don't get kicked for flooding */
if (flood_cnt < cnt) { sleep(1); cnt -= FLOOD_CHAR_COUNT; }
if (50 < flood_cnt) flood_cnt -= 15;
}
*ep = save;
p = ep;
}
free(reply);
return 0;
}
int got_kick(const char* params, irc_reply_data* ird, void* data)
{
fixup_reply(ird);
printf("got kicked -- input=%s\n", params);
printf("nick=%s ident=%s host=%s target=%s\n", ird->nick, ird->ident, ird->host, ird->target);
return 0;
}
/**
* @todo allow command line options via tclap http://tclap.sourceforge.net/ -
* package libtclap-dev in Ubuntu.
* However, its probably more portable to use plain-old getopt,
* or maybe getopt_long, lets keep the dependency list minimal.
* @todo use Config class to store defaults, and retrieve opencog.conf vars.
*/
int main (int argc, char * argv[])
{
whirr_sock_setup();
IRC conn;
if (cc.parseOptions(argc,argv)) return 0;
conn.hook_irc_command("376", &end_of_motd);
conn.hook_irc_command("PRIVMSG", &got_privmsg);
conn.hook_irc_command("KICK", &got_kick);
const char *login = getlogin();
// The login-name, nick, etc. are there only to make it look
// pretty on IRC ident.
conn.start (cc.ircNetwork.c_str(), cc.ircPort, cc.nick.c_str(), login,
"La Cogita OpenCog chatbot", "asdf");
conn.message_loop();
fprintf(stderr, "%s: Fatal Error: Remote side closed socket\n",
argv[0]);
return 1;
}
<commit_msg>whoops!<commit_after>/*
* IRC interfaces for La Cogita IRC chatbot
* Copyright (C) 2007 Linas Vepstas <[email protected]>
*
* 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
/*
* Go onto IRC
* This is pretty totally a pure hack with little/no design to it.
* Linas October 2007
*/
#include <string.h>
#include <stdlib.h>
#include <sys/types.h>
#include <unistd.h>
#include <getopt.h>
#include <string>
#include <vector>
#include <set>
#include <boost/foreach.hpp>
#define foreach BOOST_FOREACH
#include "IRC.h"
#include "CogitaConfig.h"
#include "whirr-sockets.h"
using namespace opencog::chatbot;
using std::string;
CogitaConfig cc;
/* printf can puke if these fields are NULL */
void fixup_reply(irc_reply_data* ird)
{
ird->nick = (NULL == ird->nick) ? (char *) "" : ird->nick;
ird->ident = (NULL == ird->ident) ? (char *) "" : ird->ident;
ird->host = (NULL == ird->host) ? (char *) "" : ird->host;
ird->target = (NULL == ird->target) ? (char *) "" : ird->target;
}
/**
* Join channel shortly after logging into the irc server.
*/
int end_of_motd(const char* params, irc_reply_data* ird, void* data)
{
IRC* conn = (IRC*) data;
fixup_reply(ird);
printf("chatbot got params=%s\n", params);
printf("chatbot got motd nick=%s ident=%s host=%s target=%s\n",
ird->nick, ird->ident, ird->host, ird->target);
sleep(1);
conn->join (cc.ircChannels[0].c_str());
printf("chatbot sent channel join %s\n", cc.ircChannels[0].c_str());
sleep(2);
conn->notice (cc.ircChannels[0].c_str(), "ola");
printf("chatbot sent channel notice\n");
sleep(2);
conn->privmsg (cc.ircChannels[0].c_str(), "here we are");
printf("chatbot said hello to the channel\n");
return 0;
}
/* return true if not all whitespace */
static bool is_nonblank(const char * str)
{
size_t len = strlen(str);
if (0 == len) return false;
size_t blanks = strspn(str, " \n\r\t\v");
if (blanks == len) return false;
return true;
}
/**
* Handle a message received from IRC.
*/
int got_privmsg(const char* params, irc_reply_data* ird, void* data)
{
IRC* conn = (IRC*) data;
fixup_reply(ird);
printf("input=%s\n", params);
printf("nick=%s ident=%s host=%s target=%s\n", ird->nick, ird->ident, ird->host, ird->target);
typedef enum {ENGLISH=1, SHELL_CMD, SCM_CMD} CmdType;
CmdType cmd = ENGLISH;
const char * start = NULL;
int priv = 0;
if (!strcmp (ird->target, cc.nick.c_str())) {priv = 1; start = params+1; }
if (!strncmp (¶ms[1], cc.nick.c_str(), cc.nick.size())) {
start = params+1 + cc.nick.size();
start = strchr(start, ':');
if (start) start ++;
} else if (!strncmp (params, ":cog-sh:", 8)) {
start = params+8; cmd = SHELL_CMD;
} else if (!strncmp (params, ":scm:", 5)) {
start = params+5; cmd = SCM_CMD;
} else {
// Check for alternative nick/attention strings
foreach (string it, cc.attn) {
if (! it.compare(0,it.size(),¶ms[1]) ) {
start = params + it.size();
start = strchr(start, ':');
if (start) start ++;
break;
}
}
}
if (!start) return 0;
char * msg_target = NULL;
if (priv)
{
msg_target = ird->nick;
}
else
{
msg_target = ird->target;
}
// Reply to request for chat client version
if ((0x1 == start[0]) && !strncmp (&start[1], "VERSION", 7))
{
printf ("VERSION: %s\n", cc.vstring.c_str());
conn->privmsg (msg_target, cc.vstring.c_str());
return 0;
}
// printf ("duude starting with 0x%x %s\n", start[0], start);
size_t textlen = strlen(start);
size_t len = textlen;
len += strlen ("(say-id-english )");
len += strlen (ird->nick);
len += 120;
char * cmdline = (char *) malloc(sizeof (char) * (len+1));
if (ENGLISH == cmd)
{
// Get into the opencog scheme shell, and run the command
strcpy (cmdline, "scm hush\n(say-id-english \"");
strcat (cmdline, ird->nick);
strcat (cmdline, "\" \"");
size_t toff = strlen(cmdline);
strcat (cmdline, start);
strcat (cmdline, "\")\n");
// strip out quotation marks, replace with blanks, for now.
for (size_t i =0; i<textlen; i++)
{
if ('\"' == cmdline[toff+i]) cmdline[toff+i] = ' ';
}
}
// #define ENABLE_SHELL_ESCAPES 0
#if ENABLE_SHELL_ESCAPES
/*
* XXX DANGER DANGER Extreme Caution Advised XXX
* Shell escapes are a potential security hole, as they allow access
* to the cog-server to total strangers. In particular, the scheme
* interface is a general programming API and can be used to root
* the system.
*/
else if (SHELL_CMD == cmd)
{
strcpy (cmdline, start);
strcat (cmdline, "\n");
}
else if (SCM_CMD == cmd)
{
strcpy (cmdline, "scm hush\n");
strcat (cmdline, start);
strcat (cmdline, "\n");
}
#else
else
{
conn->privmsg (msg_target, "Shell escapes disabled in this chatbot version\n");
return 0;
}
#endif /* ENABLE_SHELL_ESCAPES */
#define FLOOD_CHAR_COUNT 120
size_t flood_cnt = FLOOD_CHAR_COUNT;
size_t cnt = 0;
bool dosend = true;
// printf ("Sending to opencog: %s\n", cmdline);
char * reply = whirr_sock_io (cmdline);
free(cmdline);
cmdline = NULL;
printf ("opencog reply: %s\n", reply);
/* Each newline has to be on its own line */
/* Limit length of reply so we don't get kicked for flooding */
char * p = reply;
while (*p)
{
char *ep = strchr (p, '\n');
// The last line -- no newline found.
if (!ep)
{
if (is_nonblank(p))
conn->privmsg (msg_target, p);
break;
}
ep ++;
int save = *ep;
*ep = 0x0;
// If the line starts with ":scm", resubmit it to the
// server. This is a kind-of cheap, hacky way of doing
// multi-processing.
if (0 == strncmp(p, ":scm", 4))
{
char * cr = strchr(p, '\r');
if (cr) *cr = '\n';
char * r = whirr_sock_io (p+1);
free(reply);
reply = r;
p = reply;
printf ("opencog reply: %s\n", reply);
continue;
}
// If the line starts with ":dbg", the do not send to chatroom
if (0 == strncmp(p, ":dbg", 4))
{
*ep = save;
p = ep;
dosend = false;
continue;
}
if (0 == strncmp(p, ":end-dbg", 8))
{
*ep = save;
p = ep;
dosend = true;
continue;
}
// Else send output to chatroom
if (dosend && is_nonblank(p))
{
conn->privmsg (msg_target, p);
cnt += strlen (p);
/* Sleep so that we don't get kicked for flooding */
if (flood_cnt < cnt) { sleep(1); cnt -= FLOOD_CHAR_COUNT; }
if (50 < flood_cnt) flood_cnt -= 15;
}
*ep = save;
p = ep;
}
free(reply);
return 0;
}
int got_kick(const char* params, irc_reply_data* ird, void* data)
{
fixup_reply(ird);
printf("got kicked -- input=%s\n", params);
printf("nick=%s ident=%s host=%s target=%s\n", ird->nick, ird->ident, ird->host, ird->target);
return 0;
}
/**
* @todo allow command line options via tclap http://tclap.sourceforge.net/ -
* package libtclap-dev in Ubuntu.
* However, its probably more portable to use plain-old getopt,
* or maybe getopt_long, lets keep the dependency list minimal.
* @todo use Config class to store defaults, and retrieve opencog.conf vars.
*/
int main (int argc, char * argv[])
{
whirr_sock_setup();
IRC conn;
if (cc.parseOptions(argc,argv)) return 0;
conn.hook_irc_command("376", &end_of_motd);
conn.hook_irc_command("PRIVMSG", &got_privmsg);
conn.hook_irc_command("KICK", &got_kick);
const char *login = getlogin();
// The login-name, nick, etc. are there only to make it look
// pretty on IRC ident.
conn.start (cc.ircNetwork.c_str(), cc.ircPort, cc.nick.c_str(), login,
"La Cogita OpenCog chatbot", "asdf");
conn.message_loop();
fprintf(stderr, "%s: Fatal Error: Remote side closed socket\n",
argv[0]);
return 1;
}
<|endoftext|> |
<commit_before>// OpenQASM example, executes an OpenQASM circuit read from the input stream or
// a file (if specified)
// Source: ./examples/qasm/qasm.cpp
#include <iostream>
#include "qpp.h"
int main(int argc, char** argv) {
using namespace qpp;
QCircuit qc;
if (argc < 2)
// read the circuit from the input stream
qc = qasm::read(std::cin);
else
// read the circuit from a file
qc = qasm::read_from_file(argv[1]);
// initialize the quantum engine with a circuit
QEngine q_engine{qc};
// display the quantum circuit
std::cout << ">> BEGIN CIRCUIT\n";
std::cout << q_engine.get_circuit() << '\n';
std::cout << ">> END CIRCUIT\n\n";
// execute the quantum circuit
q_engine.execute();
// display the measurement statistics
std::cout << ">> BEGIN ENGINE STATISTICS\n";
std::cout << q_engine << '\n';
std::cout << ">> END ENGINE STATISTICS\n\n";
// display the final state
ket psi_final = q_engine.get_psi();
std::cout << ">> Final state:\n";
std::cout << disp(psi_final) << '\n';
}
<commit_msg>qasm example update<commit_after>// OpenQASM example, executes an OpenQASM circuit read from the input stream or
// a file (if specified)
// Source: ./examples/qasm/qasm.cpp
#include <iostream>
#include "qpp.h"
int main(int argc, char** argv) {
using namespace qpp;
QCircuit qc;
if (argc < 2)
// read the circuit from the input stream
qc = qasm::read(std::cin);
else
// read the circuit from a file
qc = qasm::read_from_file(argv[1]);
// initialize the quantum engine with a circuit
QEngine q_engine{qc};
// display the quantum circuit
std::cout << ">> BEGIN CIRCUIT\n";
std::cout << q_engine.get_circuit() << '\n';
std::cout << ">> END CIRCUIT\n\n";
// execute the quantum circuit
q_engine.execute();
// display the measurement statistics
std::cout << ">> BEGIN ENGINE STATISTICS\n";
std::cout << q_engine << '\n';
std::cout << ">> END ENGINE STATISTICS\n\n";
// display the final state
ket psi_final = q_engine.get_psi();
std::cout << ">> Final state:\n" << disp(psi_final) << '\n';
}
<|endoftext|> |
<commit_before>#include <boost/filesystem.hpp>
#include <boost/program_options.hpp>
#include <iostream>
#include <openssl/ssl.h>
#include "aktualizr_secondary_config.h"
#include "logging.h"
namespace bpo = boost::program_options;
void check_info_options(const bpo::options_description &description, const bpo::variables_map &vm) {
if (vm.count("help") != 0) {
std::cout << description << '\n';
exit(EXIT_SUCCESS);
}
if (vm.count("version") != 0) {
std::cout << "Current aktualizr-secondary version is: " << AKTUALIZR_VERSION << "\n";
exit(EXIT_SUCCESS);
}
}
bpo::variables_map parse_options(int argc, char *argv[]) {
bpo::options_description description("aktualizr-secondary command line options");
// clang-format off
description.add_options()
("help,h", "print usage")
("version,v", "Current aktualizr-secondary version")
("loglevel", bpo::value<int>(), "set log level 0-4 (trace, debug, warning, info, error)")
("config,c", bpo::value<std::string>()->required(), "toml configuration file")
("server-port,p", bpo::value<int>(), "command server listening port");
// clang-format on
bpo::variables_map vm;
std::vector<std::string> unregistered_options;
try {
bpo::basic_parsed_options<char> parsed_options =
bpo::command_line_parser(argc, argv).options(description).allow_unregistered().run();
bpo::store(parsed_options, vm);
check_info_options(description, vm);
bpo::notify(vm);
unregistered_options = bpo::collect_unrecognized(parsed_options.options, bpo::include_positional);
if (vm.count("help") == 0 && !unregistered_options.empty()) {
std::cout << description << "\n";
exit(EXIT_FAILURE);
}
} catch (const bpo::required_option &ex) {
if (ex.get_option_name() == "--config") {
std::cout << ex.get_option_name() << " is missing.\nYou have to provide a valid configuration "
"file using toml format. See the example configuration file "
"in config/aktualizr_secondary/config.toml.example"
<< std::endl;
exit(EXIT_FAILURE);
} else {
// print the error and append the default commandline option description
std::cout << ex.what() << std::endl << description;
exit(EXIT_SUCCESS);
}
} catch (const bpo::error &ex) {
check_info_options(description, vm);
// log boost error
LOG_WARNING << "boost command line option error: " << ex.what();
// print the error message to the standard output too, as the user provided
// a non-supported commandline option
std::cout << ex.what() << '\n';
// set the returnValue, thereby ctest will recognize
// that something went wrong
exit(EXIT_FAILURE);
}
return vm;
}
/*****************************************************************************/
int main(int argc, char *argv[]) {
logger_init();
bpo::variables_map commandline_map = parse_options(argc, argv);
// check for loglevel
if (commandline_map.count("loglevel") != 0) {
// set the log level from command line option
boost::log::trivial::severity_level severity =
static_cast<boost::log::trivial::severity_level>(commandline_map["loglevel"].as<int>());
if (severity < boost::log::trivial::trace) {
LOG_DEBUG << "Invalid log level";
severity = boost::log::trivial::trace;
}
if (boost::log::trivial::fatal < severity) {
LOG_WARNING << "Invalid log level";
severity = boost::log::trivial::fatal;
}
if (severity <= boost::log::trivial::debug) {
SSL_load_error_strings();
}
logger_set_threshold(severity);
}
LOG_INFO << "Aktualizr-secondary version " AKTUALIZR_VERSION " starting";
LOG_DEBUG << "Current directory: " << boost::filesystem::current_path().string();
// Initialize config with default values, the update with config, then with cmd
boost::filesystem::path secondary_config_path(commandline_map["config"].as<std::string>());
if (!boost::filesystem::exists(secondary_config_path)) {
std::cout << "aktualizr-secondary: configuration file " << boost::filesystem::absolute(secondary_config_path)
<< " not found. Exiting." << std::endl;
exit(EXIT_FAILURE);
}
// TODO: do something
return 0;
}
<commit_msg>Fix naming typo in aktualizr-secondary<commit_after>#include <boost/filesystem.hpp>
#include <boost/program_options.hpp>
#include <iostream>
#include <openssl/ssl.h>
#include "aktualizr_secondary_config.h"
#include "logging.h"
namespace bpo = boost::program_options;
void check_secondary_options(const bpo::options_description &description, const bpo::variables_map &vm) {
if (vm.count("help") != 0) {
std::cout << description << '\n';
exit(EXIT_SUCCESS);
}
if (vm.count("version") != 0) {
std::cout << "Current aktualizr-secondary version is: " << AKTUALIZR_VERSION << "\n";
exit(EXIT_SUCCESS);
}
}
bpo::variables_map parse_options(int argc, char *argv[]) {
bpo::options_description description("aktualizr-secondary command line options");
// clang-format off
description.add_options()
("help,h", "print usage")
("version,v", "Current aktualizr-secondary version")
("loglevel", bpo::value<int>(), "set log level 0-4 (trace, debug, warning, info, error)")
("config,c", bpo::value<std::string>()->required(), "toml configuration file")
("server-port,p", bpo::value<int>(), "command server listening port");
// clang-format on
bpo::variables_map vm;
std::vector<std::string> unregistered_options;
try {
bpo::basic_parsed_options<char> parsed_options =
bpo::command_line_parser(argc, argv).options(description).allow_unregistered().run();
bpo::store(parsed_options, vm);
check_secondary_options(description, vm);
bpo::notify(vm);
unregistered_options = bpo::collect_unrecognized(parsed_options.options, bpo::include_positional);
if (vm.count("help") == 0 && !unregistered_options.empty()) {
std::cout << description << "\n";
exit(EXIT_FAILURE);
}
} catch (const bpo::required_option &ex) {
if (ex.get_option_name() == "--config") {
std::cout << ex.get_option_name() << " is missing.\nYou have to provide a valid configuration "
"file using toml format. See the example configuration file "
"in config/aktualizr_secondary/config.toml.example"
<< std::endl;
exit(EXIT_FAILURE);
} else {
// print the error and append the default commandline option description
std::cout << ex.what() << std::endl << description;
exit(EXIT_SUCCESS);
}
} catch (const bpo::error &ex) {
check_secondary_options(description, vm);
// log boost error
LOG_WARNING << "boost command line option error: " << ex.what();
// print the error message to the standard output too, as the user provided
// a non-supported commandline option
std::cout << ex.what() << '\n';
// set the returnValue, thereby ctest will recognize
// that something went wrong
exit(EXIT_FAILURE);
}
return vm;
}
/*****************************************************************************/
int main(int argc, char *argv[]) {
logger_init();
bpo::variables_map commandline_map = parse_options(argc, argv);
// check for loglevel
if (commandline_map.count("loglevel") != 0) {
// set the log level from command line option
boost::log::trivial::severity_level severity =
static_cast<boost::log::trivial::severity_level>(commandline_map["loglevel"].as<int>());
if (severity < boost::log::trivial::trace) {
LOG_DEBUG << "Invalid log level";
severity = boost::log::trivial::trace;
}
if (boost::log::trivial::fatal < severity) {
LOG_WARNING << "Invalid log level";
severity = boost::log::trivial::fatal;
}
if (severity <= boost::log::trivial::debug) {
SSL_load_error_strings();
}
logger_set_threshold(severity);
}
LOG_INFO << "Aktualizr-secondary version " AKTUALIZR_VERSION " starting";
LOG_DEBUG << "Current directory: " << boost::filesystem::current_path().string();
// Initialize config with default values, the update with config, then with cmd
boost::filesystem::path secondary_config_path(commandline_map["config"].as<std::string>());
if (!boost::filesystem::exists(secondary_config_path)) {
std::cout << "aktualizr-secondary: configuration file " << boost::filesystem::absolute(secondary_config_path)
<< " not found. Exiting." << std::endl;
exit(EXIT_FAILURE);
}
// TODO: do something
return 0;
}
<|endoftext|> |
<commit_before>/*
openGCM, geometric constraint manager
Copyright (C) 2012 Stefan Troeger <[email protected]>
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 detemplate tails.
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.
*/
#ifndef GCM_PARALLEL_H
#define GCM_PARALLEL_H
#include "geometry.hpp"
namespace gcm {
//the possible directions
enum Direction { Same, Opposite };
//the calculations( same as we always calculate directions we can outsource the work to this functions)
namespace parallel {
template<typename Kernel, typename T>
inline typename Kernel::number_type calc(T d1,
T d2,
Direction dir) {
switch(dir) {
case Same:
return (d1-d2).norm();
case Opposite:
return (d1+d2).norm();
}
};
template<typename Kernel, typename T>
inline typename Kernel::number_type calcGradFirst(T d1,
T d2,
T dd1,
Direction dir) {
switch(dir) {
case Same:
return (d1-d2).dot(dd1) / (d1-d2).norm();
case Opposite:
return (d1+d2).dot(dd1) / (d1+d2).norm();
}
};
template<typename Kernel, typename T>
inline typename Kernel::number_type calcGradSecond(T d1,
T d2,
T dd2,
Direction dir) {
switch(dir) {
case Same:
return (d1-d2).dot(-dd2) / (d1-d2).norm();
case Opposite:
return (d1+d2).dot(dd2) / (d1+d2).norm();
}
};
template<typename Kernel, typename T>
inline void calcGradFirstComp(T d1,
T d2,
T grad,
Direction dir) {
switch(dir) {
case Same:
grad = (d1-d2) / (d1-d2).norm();
return;
case Opposite:
grad = (d1+d2) / (d1+d2).norm();
return;
}
};
template<typename Kernel, typename T>
inline void calcGradSecondComp(T d1,
T d2,
T grad,
Direction dir) {
switch(dir) {
case Same:
grad = (d2-d1) / (d1-d2).norm();
return;
case Opposite:
grad = (d2+d1) / (d1+d2).norm();
return;
}
};
}
template< typename Kernel, typename Tag1, typename Tag2 >
struct Parallel3D {
typedef typename Kernel::number_type Scalar;
typedef typename Kernel::VectorMap Vector;
Direction m_dir;
Parallel3D(Direction d = Same) : m_dir(d) {
// Base::Console().Message("choosen direction (0=same, 1=opposite): %d\n",m_dir);
};
//template definition
Scalar calculate(Vector& param1, Vector& param2) {
assert(false);
};
Scalar calculateGradientFirst(Vector& param1, Vector& param2, Vector& dparam1) {
assert(false);
};
Scalar calculateGradientSecond(Vector& param1, Vector& param2, Vector& dparam2) {
assert(false);
};
void calculateGradientFirstComplete(Vector& param1, Vector& param2, Vector& gradient) {
assert(false);
};
void calculateGradientSecondComplete(Vector& param1, Vector& param2, Vector& gradient) {
assert(false);
};
};
template< typename Kernel >
struct Parallel3D< Kernel, tag::line3D, tag::line3D > {
typedef typename Kernel::number_type Scalar;
typedef typename Kernel::VectorMap Vector;
Direction m_dir;
Parallel3D(Direction d = Same) : m_dir(d) {};
//template definition
Scalar calculate(Vector& param1, Vector& param2) {
return parallel::calc<Kernel>(param1.template tail<3>(), param2.template tail<3>(), m_dir);
};
Scalar calculateGradientFirst(Vector& param1, Vector& param2, Vector& dparam1) {
return parallel::calcGradFirst<Kernel>(param1.template tail<3>(), param2.template tail<3>(), dparam1.template tail<3>(), m_dir);
};
Scalar calculateGradientSecond(Vector& param1, Vector& param2, Vector& dparam2) {
return parallel::calcGradSecond<Kernel>(param1.template tail<3>(), param2.template tail<3>(), dparam2.template tail<3>(), m_dir);
};
void calculateGradientFirstComplete(Vector& param1, Vector& param2, Vector& gradient) {
gradient.template head<3>().setZero();
parallel::calcGradFirstComp<Kernel>(param1.template tail<3>(), param2.template tail<3>(), gradient.template tail<3>(), m_dir);
};
void calculateGradientSecondComplete(Vector& param1, Vector& param2, Vector& gradient) {
gradient.template head<3>().setZero();
parallel::calcGradSecondComp<Kernel>(param1.template tail<3>(), param2.template tail<3>(), gradient.template tail<3>(), m_dir);
};
};
//planes like lines have the direction as segment 3-5, so we can use the same implementations
template< typename Kernel >
struct Parallel3D< Kernel, tag::plane3D, tag::plane3D > : public Parallel3D<Kernel, tag::line3D, tag::line3D> {
Parallel3D(Direction d = Same) : Parallel3D<Kernel, tag::line3D, tag::line3D>(d) {};
};
template< typename Kernel >
struct Parallel3D< Kernel, tag::line3D, tag::plane3D > : public Parallel3D<Kernel, tag::line3D, tag::line3D> {
Parallel3D(Direction d = Same) : Parallel3D<Kernel, tag::line3D, tag::line3D>(d) {};
};
template< typename Kernel >
struct Parallel3D< Kernel, tag::cylinder3D, tag::cylinder3D > {
typedef typename Kernel::number_type Scalar;
typedef typename Kernel::VectorMap Vector;
Direction m_dir;
Parallel3D(Direction d = Same) : m_dir(d) {
Base::Console().Message("Create parrallel cylinder");
};
//template definition
Scalar calculate(Vector& param1, Vector& param2) {
return parallel::calc<Kernel>(param1.template segment<3>(3), param2.template segment<3>(3), m_dir);
};
Scalar calculateGradientFirst(Vector& param1, Vector& param2, Vector& dparam1) {
return parallel::calcGradFirst<Kernel>(param1.template segment<3>(3), param2.template segment<3>(3), dparam1.template segment<3>(3), m_dir);
};
Scalar calculateGradientSecond(Vector& param1, Vector& param2, Vector& dparam2) {
return parallel::calcGradSecond<Kernel>(param1.template segment<3>(3), param2.template segment<3>(3), dparam2.template segment<3>(3), m_dir);
};
void calculateGradientFirstComplete(Vector& param1, Vector& param2, Vector& gradient) {
gradient.template head<3>().setZero();
parallel::calcGradFirstComp<Kernel>(param1.template segment<3>(3), param2.template segment<3>(3), gradient.template segment<3>(3), m_dir);
};
void calculateGradientSecondComplete(Vector& param1, Vector& param2, Vector& gradient) {
gradient.template head<3>().setZero();
parallel::calcGradSecondComp<Kernel>(param1.template segment<3>(3), param2.template segment<3>(3), gradient.template segment<3>(3), m_dir);
};
};
}
#endif //GCM_ANGLE<commit_msg>first take on bidirectional parallel constraint<commit_after>/*
openGCM, geometric constraint manager
Copyright (C) 2012 Stefan Troeger <[email protected]>
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 detemplate tails.
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.
*/
#ifndef GCM_PARALLEL_H
#define GCM_PARALLEL_H
#include "geometry.hpp"
namespace gcm {
//the possible directions
enum Direction { Same, Opposite, Both };
//the calculations( same as we always calculate directions we can outsource the work to this functions)
namespace parallel {
template<typename Kernel, typename T>
inline typename Kernel::number_type calc(T d1,
T d2,
Direction dir) {
switch(dir) {
case Same:
return (d1-d2).norm();
case Opposite:
return (d1+d2).norm();
case Both:
return (d1/d1.norm() + d2/d2.norm()).norm();
}
};
template<typename Kernel, typename T>
inline typename Kernel::number_type calcGradFirst(T d1,
T d2,
T dd1,
Direction dir) {
switch(dir) {
case Same:
return (d1-d2).dot(dd1) / (d1-d2).norm();
case Opposite:
return (d1+d2).dot(dd1) / (d1+d2).norm();
case Both:
const typename Kernel::number_type nd1 = d1.norm();
const typename Kernel::Vector3 f = d1/nd1 + d2/d2.norm();
return f.dot(dd1/nd1 - d1*d1.dot(dd1)/std::pow(nd1,3)) / f.norm();
}
};
template<typename Kernel, typename T>
inline typename Kernel::number_type calcGradSecond(T d1,
T d2,
T dd2,
Direction dir) {
switch(dir) {
case Same:
return (d1-d2).dot(-dd2) / (d1-d2).norm();
case Opposite:
return (d1+d2).dot(dd2) / (d1+d2).norm();
case Both:
const typename Kernel::number_type nd2 = d2.norm();
const typename Kernel::Vector3 f = d1/d1.norm() + d2/nd2;
return f.dot(dd2/nd2 - d2*d2.dot(dd2)/std::pow(nd2,3)) / f.norm();
}
};
template<typename Kernel, typename T>
inline void calcGradFirstComp(T d1,
T d2,
T grad,
Direction dir) {
switch(dir) {
case Same:
grad = (d1-d2) / (d1-d2).norm();
return;
case Opposite:
grad = (d1+d2) / (d1+d2).norm();
return;
case Both:
assert(false);
}
};
template<typename Kernel, typename T>
inline void calcGradSecondComp(T d1,
T d2,
T grad,
Direction dir) {
switch(dir) {
case Same:
grad = (d2-d1) / (d1-d2).norm();
return;
case Opposite:
grad = (d2+d1) / (d1+d2).norm();
return;
case Both:
assert(false);
}
};
}
template< typename Kernel, typename Tag1, typename Tag2 >
struct Parallel3D {
typedef typename Kernel::number_type Scalar;
typedef typename Kernel::VectorMap Vector;
Direction m_dir;
Parallel3D(Direction d = Same) : m_dir(d) {
// Base::Console().Message("choosen direction (0=same, 1=opposite): %d\n",m_dir);
};
//template definition
Scalar calculate(Vector& param1, Vector& param2) {
assert(false);
};
Scalar calculateGradientFirst(Vector& param1, Vector& param2, Vector& dparam1) {
assert(false);
};
Scalar calculateGradientSecond(Vector& param1, Vector& param2, Vector& dparam2) {
assert(false);
};
void calculateGradientFirstComplete(Vector& param1, Vector& param2, Vector& gradient) {
assert(false);
};
void calculateGradientSecondComplete(Vector& param1, Vector& param2, Vector& gradient) {
assert(false);
};
};
template< typename Kernel >
struct Parallel3D< Kernel, tag::line3D, tag::line3D > {
typedef typename Kernel::number_type Scalar;
typedef typename Kernel::VectorMap Vector;
Direction m_dir;
Parallel3D(Direction d = Same) : m_dir(d) {};
//template definition
Scalar calculate(Vector& param1, Vector& param2) {
return parallel::calc<Kernel>(param1.template tail<3>(), param2.template tail<3>(), m_dir);
};
Scalar calculateGradientFirst(Vector& param1, Vector& param2, Vector& dparam1) {
return parallel::calcGradFirst<Kernel>(param1.template tail<3>(), param2.template tail<3>(), dparam1.template tail<3>(), m_dir);
};
Scalar calculateGradientSecond(Vector& param1, Vector& param2, Vector& dparam2) {
return parallel::calcGradSecond<Kernel>(param1.template tail<3>(), param2.template tail<3>(), dparam2.template tail<3>(), m_dir);
};
void calculateGradientFirstComplete(Vector& param1, Vector& param2, Vector& gradient) {
gradient.template head<3>().setZero();
parallel::calcGradFirstComp<Kernel>(param1.template tail<3>(), param2.template tail<3>(), gradient.template tail<3>(), m_dir);
};
void calculateGradientSecondComplete(Vector& param1, Vector& param2, Vector& gradient) {
gradient.template head<3>().setZero();
parallel::calcGradSecondComp<Kernel>(param1.template tail<3>(), param2.template tail<3>(), gradient.template tail<3>(), m_dir);
};
};
//planes like lines have the direction as segment 3-5, so we can use the same implementations
template< typename Kernel >
struct Parallel3D< Kernel, tag::plane3D, tag::plane3D > : public Parallel3D<Kernel, tag::line3D, tag::line3D> {
Parallel3D(Direction d = Same) : Parallel3D<Kernel, tag::line3D, tag::line3D>(d) {};
};
template< typename Kernel >
struct Parallel3D< Kernel, tag::line3D, tag::plane3D > : public Parallel3D<Kernel, tag::line3D, tag::line3D> {
Parallel3D(Direction d = Same) : Parallel3D<Kernel, tag::line3D, tag::line3D>(d) {};
};
template< typename Kernel >
struct Parallel3D< Kernel, tag::cylinder3D, tag::cylinder3D > {
typedef typename Kernel::number_type Scalar;
typedef typename Kernel::VectorMap Vector;
Direction m_dir;
Parallel3D(Direction d = Same) : m_dir(d) {
Base::Console().Message("Create parrallel cylinder");
};
//template definition
Scalar calculate(Vector& param1, Vector& param2) {
return parallel::calc<Kernel>(param1.template segment<3>(3), param2.template segment<3>(3), m_dir);
};
Scalar calculateGradientFirst(Vector& param1, Vector& param2, Vector& dparam1) {
return parallel::calcGradFirst<Kernel>(param1.template segment<3>(3), param2.template segment<3>(3), dparam1.template segment<3>(3), m_dir);
};
Scalar calculateGradientSecond(Vector& param1, Vector& param2, Vector& dparam2) {
return parallel::calcGradSecond<Kernel>(param1.template segment<3>(3), param2.template segment<3>(3), dparam2.template segment<3>(3), m_dir);
};
void calculateGradientFirstComplete(Vector& param1, Vector& param2, Vector& gradient) {
gradient.template head<3>().setZero();
parallel::calcGradFirstComp<Kernel>(param1.template segment<3>(3), param2.template segment<3>(3), gradient.template segment<3>(3), m_dir);
};
void calculateGradientSecondComplete(Vector& param1, Vector& param2, Vector& gradient) {
gradient.template head<3>().setZero();
parallel::calcGradSecondComp<Kernel>(param1.template segment<3>(3), param2.template segment<3>(3), gradient.template segment<3>(3), m_dir);
};
};
}
#endif //GCM_ANGLE
<|endoftext|> |
<commit_before>/** @file Tests to make sure that invalid certificates fail to connect */
#include "catch.hpp"
#include <communique/Client.h>
#include <communique/Server.h>
#include <thread>
#include <iostream>
#include "testinputs.h"
SCENARIO( "Test that server setup fails when given invalid security files", "[security][local]" )
{
WHEN( "I create a server with invalid certificate file" )
{
communique::Server myServer;
REQUIRE_NOTHROW( myServer.setCertificateChainFile( testinputs::testFileDirectory+"blahblahblah.pem" ) );
REQUIRE_THROWS( myServer.listen( ++testinputs::portNumber ) );
}
WHEN( "I create a server with invalid key file" )
{
communique::Server myServer;
REQUIRE_NOTHROW( myServer.setPrivateKeyFile( testinputs::testFileDirectory+"blahblahblah.pem" ) );
REQUIRE_THROWS( myServer.listen( ++testinputs::portNumber ) );
}
WHEN( "I create a server with key in place of the certificate" )
{
communique::Server myServer;
REQUIRE_NOTHROW( myServer.setCertificateChainFile( testinputs::testFileDirectory+"server_key.pem" ) );
REQUIRE_THROWS( myServer.listen( ++testinputs::portNumber ) );
}
WHEN( "I create a server with certificate in place of the key" )
{
communique::Server myServer;
REQUIRE_NOTHROW( myServer.setPrivateKeyFile( testinputs::testFileDirectory+"server_cert.pem" ) );
REQUIRE_THROWS( myServer.listen( ++testinputs::portNumber ) );
}
}
SCENARIO( "Test that client setup fails when given invalid security files", "[security][local]" )
{
WHEN( "I create a client with invalid verification file" )
{
communique::Client myClient;
REQUIRE_NOTHROW( myClient.setVerifyFile( testinputs::testFileDirectory+"blahblahblah.pem" ) );
REQUIRE_THROWS( myClient.connect( "wss://echo.websocket.org" ) );
}
}
SCENARIO( "Test that an incorrect server certificate fails ", "[security][local]" )
{
GIVEN( "A Client and server" )
{
communique::Server myServer;
myServer.setCertificateChainFile( testinputs::testFileDirectory+"old/server.pem" );
myServer.setPrivateKeyFile( testinputs::testFileDirectory+"old/server.pem" );
communique::Client myClient;
myClient.setVerifyFile( testinputs::testFileDirectory+"certificateAuthority_cert.pem" );
WHEN( "I start a server listening and try and connect a client to it" )
{
REQUIRE_NOTHROW( myServer.listen( ++testinputs::portNumber ) );
std::this_thread::sleep_for( testinputs::shortWait );
REQUIRE_NOTHROW( myClient.connect( "ws://localhost:"+std::to_string(testinputs::portNumber) ) );
REQUIRE( !myClient.isConnected() );
REQUIRE_NOTHROW( myServer.stop() );
}
}
}
SCENARIO( "Test that connection fails when server requires client authentication, and client doesn't authenticate", "[security][local]" )
{
GIVEN( "A Client and server" )
{
communique::Server myServer;
myServer.setCertificateChainFile( testinputs::testFileDirectory+"server_cert.pem" );
myServer.setPrivateKeyFile( testinputs::testFileDirectory+"server_key.pem" );
myServer.setVerifyFile( testinputs::testFileDirectory+"certificateAuthority_cert.pem" );
communique::Client myClient;
myClient.setVerifyFile( testinputs::testFileDirectory+"certificateAuthority_cert.pem" );
WHEN( "I start a server listening and try and connect a client to it" )
{
REQUIRE_NOTHROW( myServer.listen( ++testinputs::portNumber ) );
std::this_thread::sleep_for( testinputs::shortWait );
REQUIRE_NOTHROW( myClient.connect( "ws://localhost:"+std::to_string(testinputs::portNumber) ) );
REQUIRE( !myClient.isConnected() );
REQUIRE_NOTHROW( myServer.stop() );
}
}
}
SCENARIO( "Test that client authentication works", "[security][local]" )
{
GIVEN( "A Client and server" )
{
communique::Server myServer;
myServer.setCertificateChainFile( testinputs::testFileDirectory+"server_cert.pem" );
myServer.setPrivateKeyFile( testinputs::testFileDirectory+"server_key.pem" );
myServer.setVerifyFile( testinputs::testFileDirectory+"certificateAuthority_cert.pem" );
communique::Client myClient;
myClient.setCertificateChainFile( testinputs::testFileDirectory+"client_cert.pem" );
myClient.setPrivateKeyFile( testinputs::testFileDirectory+"client_key.pem" );
myClient.setVerifyFile( testinputs::testFileDirectory+"certificateAuthority_cert.pem" );
WHEN( "I start a server listening and try and connect a client to it" )
{
REQUIRE_NOTHROW( myServer.listen( ++testinputs::portNumber ) );
std::this_thread::sleep_for( testinputs::shortWait );
REQUIRE_NOTHROW( myClient.connect( "ws://localhost:"+std::to_string(testinputs::portNumber) ) );
REQUIRE( myClient.isConnected() );
REQUIRE_NOTHROW( myClient.disconnect() );
REQUIRE_NOTHROW( myServer.stop() );
}
}
}
<commit_msg>Add a test with an expired server certificate<commit_after>/** @file Tests to make sure that invalid certificates fail to connect */
#include "catch.hpp"
#include <communique/Client.h>
#include <communique/Server.h>
#include <thread>
#include <iostream>
#include "testinputs.h"
SCENARIO( "Test that server setup fails when given invalid security files", "[security][local]" )
{
WHEN( "I create a server with invalid certificate file" )
{
communique::Server myServer;
REQUIRE_NOTHROW( myServer.setCertificateChainFile( testinputs::testFileDirectory+"blahblahblah.pem" ) );
REQUIRE_THROWS( myServer.listen( ++testinputs::portNumber ) );
}
WHEN( "I create a server with invalid key file" )
{
communique::Server myServer;
REQUIRE_NOTHROW( myServer.setPrivateKeyFile( testinputs::testFileDirectory+"blahblahblah.pem" ) );
REQUIRE_THROWS( myServer.listen( ++testinputs::portNumber ) );
}
WHEN( "I create a server with key in place of the certificate" )
{
communique::Server myServer;
REQUIRE_NOTHROW( myServer.setCertificateChainFile( testinputs::testFileDirectory+"server_key.pem" ) );
REQUIRE_THROWS( myServer.listen( ++testinputs::portNumber ) );
}
WHEN( "I create a server with certificate in place of the key" )
{
communique::Server myServer;
REQUIRE_NOTHROW( myServer.setPrivateKeyFile( testinputs::testFileDirectory+"server_cert.pem" ) );
REQUIRE_THROWS( myServer.listen( ++testinputs::portNumber ) );
}
}
SCENARIO( "Test that client setup fails when given invalid security files", "[security][local]" )
{
WHEN( "I create a client with invalid verification file" )
{
communique::Client myClient;
REQUIRE_NOTHROW( myClient.setVerifyFile( testinputs::testFileDirectory+"blahblahblah.pem" ) );
REQUIRE_THROWS( myClient.connect( "wss://echo.websocket.org" ) );
}
}
SCENARIO( "Test that an incorrect server certificate fails ", "[security][local]" )
{
GIVEN( "A Client and server" )
{
communique::Server myServer;
myServer.setCertificateChainFile( testinputs::testFileDirectory+"old/server.pem" );
myServer.setPrivateKeyFile( testinputs::testFileDirectory+"old/server.pem" );
communique::Client myClient;
myClient.setVerifyFile( testinputs::testFileDirectory+"certificateAuthority_cert.pem" );
WHEN( "I start a server listening and try and connect a client to it" )
{
REQUIRE_NOTHROW( myServer.listen( ++testinputs::portNumber ) );
std::this_thread::sleep_for( testinputs::shortWait );
REQUIRE_NOTHROW( myClient.connect( "ws://localhost:"+std::to_string(testinputs::portNumber) ) );
REQUIRE( !myClient.isConnected() );
REQUIRE_NOTHROW( myServer.stop() );
}
}
}
SCENARIO( "Test that connection fails when server requires client authentication, and client doesn't authenticate", "[security][local]" )
{
GIVEN( "A Client and server" )
{
communique::Server myServer;
myServer.setCertificateChainFile( testinputs::testFileDirectory+"server_cert.pem" );
myServer.setPrivateKeyFile( testinputs::testFileDirectory+"server_key.pem" );
myServer.setVerifyFile( testinputs::testFileDirectory+"certificateAuthority_cert.pem" );
communique::Client myClient;
myClient.setVerifyFile( testinputs::testFileDirectory+"certificateAuthority_cert.pem" );
WHEN( "I start a server listening and try and connect a client to it" )
{
REQUIRE_NOTHROW( myServer.listen( ++testinputs::portNumber ) );
std::this_thread::sleep_for( testinputs::shortWait );
REQUIRE_NOTHROW( myClient.connect( "ws://localhost:"+std::to_string(testinputs::portNumber) ) );
REQUIRE( !myClient.isConnected() );
REQUIRE_NOTHROW( myServer.stop() );
}
}
}
SCENARIO( "Test that client authentication works", "[security][local]" )
{
GIVEN( "A Client and server" )
{
communique::Server myServer;
myServer.setCertificateChainFile( testinputs::testFileDirectory+"server_cert.pem" );
myServer.setPrivateKeyFile( testinputs::testFileDirectory+"server_key.pem" );
myServer.setVerifyFile( testinputs::testFileDirectory+"certificateAuthority_cert.pem" );
communique::Client myClient;
myClient.setCertificateChainFile( testinputs::testFileDirectory+"client_cert.pem" );
myClient.setPrivateKeyFile( testinputs::testFileDirectory+"client_key.pem" );
myClient.setVerifyFile( testinputs::testFileDirectory+"certificateAuthority_cert.pem" );
WHEN( "I start a server listening and try and connect a client to it" )
{
REQUIRE_NOTHROW( myServer.listen( ++testinputs::portNumber ) );
std::this_thread::sleep_for( testinputs::shortWait );
REQUIRE_NOTHROW( myClient.connect( "ws://localhost:"+std::to_string(testinputs::portNumber) ) );
REQUIRE( myClient.isConnected() );
REQUIRE_NOTHROW( myClient.disconnect() );
REQUIRE_NOTHROW( myServer.stop() );
}
}
}
SCENARIO( "Test that authentication fails when the server certificate has expired", "[security][local]" )
{
GIVEN( "A Client and server" )
{
communique::Server myServer;
myServer.setCertificateChainFile( testinputs::testFileDirectory+"expired_server_cert.pem" );
myServer.setPrivateKeyFile( testinputs::testFileDirectory+"server_key.pem" );
myServer.setVerifyFile( testinputs::testFileDirectory+"certificateAuthority_cert.pem" );
communique::Client myClient;
myClient.setCertificateChainFile( testinputs::testFileDirectory+"client_cert.pem" );
myClient.setPrivateKeyFile( testinputs::testFileDirectory+"client_key.pem" );
myClient.setVerifyFile( testinputs::testFileDirectory+"certificateAuthority_cert.pem" );
WHEN( "I start a server listening and try and connect a client to it" )
{
REQUIRE_NOTHROW( myServer.listen( ++testinputs::portNumber ) );
std::this_thread::sleep_for( testinputs::shortWait );
REQUIRE_NOTHROW( myClient.connect( "ws://localhost:"+std::to_string(testinputs::portNumber) ) );
REQUIRE( !myClient.isConnected() );
REQUIRE_NOTHROW( myClient.disconnect() );
REQUIRE_NOTHROW( myServer.stop() );
}
}
}
<|endoftext|> |
<commit_before>/**
* SD Card Read/Write Test
* 4/5/2017
*
**/
//#include <stdlib.h>
//#include <stdio.h>
#include "mbed.h"
#include "pinout.h"
#include "SDFileSystem.h"
#include "imu.h"
#include "GPS.h"
#include "QEI.h"
#include "motor.h"
#include "PwmIn.h"
/* map structure */
typedef struct Point {
int x; //need to change to GPS relevent values
int y;
} Point;
typedef struct Map {
Point nw; //NorthWest corner of the map
Point ne; //NorthEast corner of the map
Point sw; //southwest corner of the map
Point se; //southEast corner of the map
float mAccel; //Maximum allowed acceleration
float mVel; //Maximum allowed velocity
int npoints; //number of map points to run
Point *path; //array of map points to be run
} Map;
int readMap(FILE *fp, Map *mp) {
// char *line;
// int len;
if (!fp)
return -1;
/* while(line = getline(&line, &len, fp) != -1) {
printf("%s\r\n", line);
}
*/
return 0;
}
int checkMap(Map *mp) {
return 0;
}
//Function allows driving by RC controler
//Note: this is bad organisation for the final, the only function
// in the final program that can manipulate the motors directly
// should be main or a function only called from main who's only job
// is to set the motor speeds;
int modeRC(float throtle, float lrat, int *mr, int *ml) {
throtle *= 1000000;
throtle -= 1100;
throtle /= 8;
lrat *= 1000000;
lrat -= 1000;
lrat /= 1000;
*ml = (int)((1 - lrat) * throtle);
*mr = (int)(lrat * throtle);
return 0;
}
/* Test Objects */
Serial Pc(USBTX,USBRX);
SDFileSystem sd(DI, DO, CLK, CS, "sd");
IMU imu(I2C_SDA, I2C_SCL, BNO055_G_CHIP_ADDR, true);
/* Motor Objects */
MOTOR MotorR(1, IN2A, IN1A, ENA, true);
MOTOR MotorL(2, IN2B, IN1B, ENB, true);
/* Encoder Objects */
QEI EncoderL(CHA1, CHB1, NC, 192, QEI::X4_ENCODING);
QEI EncoderR(CHA2, CHB2, NC, 192, QEI::X4_ENCODING);
/* IMU Objects */
IMU Imu(IMDA, IMCL, BNO055_G_CHIP_ADDR, true);
/* GPS Objects */
GPS Gps(GPTX, GPRX);
/* Radio Objects */
PwmIn Throt(THRO);
PwmIn Lr(LRIN);
PwmIn Mode(MODE);
PwmIn E_Stop(ESTO);
/* Input Buttons */
DigitalIn Btn(PC_0);
DigitalIn Dip(PB_6);
int main()
{
Map mp;
int pCount = 0;
//radio variables
float estop;
int mr, ml, md;
// Creates variables of reading data types
IMU::imu_euler_t euler;
IMU::imu_lin_accel_t linAccel;
IMU::imu_gravity_t grav;
//Mount the filesystem
printf("Mounting SD card\r\n");
sd.mount();
FILE *ofp = fopen("/sd/data.txt", "w");
FILE *ifp = fopen("/sd/map.mp", "r");
//infinite loop if SD card not found
if (ofp == NULL) {
Pc.printf("SD card not found\r\n");
while(1) ;
}
//open map file
if (ifp == NULL) {
Pc.printf("No Map File Found! ABORT!\r\n");
while(1) ;
}
//parse map file into Map structure
if (readMap(ifp, &mp)) {
Pc.printf("Map parse failed\r\n");
while(1);
}
//review the map structure for errors
if (checkMap(&mp)) {
Pc.printf("Map does not fit rules\r\n");
while(1);
}
//close the map file, won't be using it anymore
fclose(ifp);
Pc.printf("FileSystem ready\r\n");
//Initialise motors
MotorL.start(0);
MotorR.start(0);
Pc.printf("Motors initialised\r\n");
Pc.printf("Waiting on user GO\r\n");
while ((estop = E_Stop.pulsewidth() * 1000000) < 1150 &&
estop > 1090)
;
while ((estop = E_Stop.pulsewidth() * 1000000) != 1096)
;
Pc.printf("User GO accepted starting run\r\n");
while((estop = E_Stop.pulsewidth() * 1000000) < 1150 &&
estop > 1090) {
fprintf(ofp, "Data Point: %d\r\n",pCount);
//Check DIP2 to activate the motors
if(Btn && (md = Mode.pulsewidth() * 1000000) > 1450 &&
md < 1550) {
modeRC(Throt.pulsewidth(), Lr.pulsewidth(), &mr, &ml);
MotorL.start(ml);
MotorR.start(mr);
Pc.printf("Motor ON\tMode:%f\t",Mode.pulsewidth() );
Pc.printf("Motor Left: %d\tMotor Right: %d\r\n", ml, mr);
fprintf(ofp, "Motor ON\t");
Pc.printf("Motor Left: %d\tMotor Right: %d\r\n", ml, mr);
} else {
MotorL.start(0);
MotorR.start(0);
Pc.printf("Motor OFF\r\n");
fprintf(ofp, "Motor OFF\r\n");
}
//Read data from GPS
if(Gps.parseData()) {
fprintf(ofp, "time: %f\r\n",Gps.time);
fprintf(ofp, "latatude: %f\r\n", Gps.latitude);
fprintf(ofp, "longitude: %f\r\n", Gps.longitude);
fprintf(ofp, "Satilites: %d\r\n", Gps.satellites);
} else {
fprintf(ofp, "GPS: No LOCK\r\n");
}
//Read data from encoders
fprintf(ofp, "EncoderL: %d\r\n", EncoderL.getPulses());
fprintf(ofp, "EncoderR: %d\r\n", EncoderR.getPulses());
EncoderL.reset();
EncoderR.reset();
//Read data from IMU
imu.getEulerAng(&euler);
imu.getLinAccel(&linAccel);
imu.getGravity(&grav);
fprintf(ofp, "Data Point %d\r\n", pCount);
fprintf(ofp, "Heading: %f Pitch: %f Roll: %f\r\n",
euler.heading, euler.pitch, euler.roll);
fprintf(ofp, "LinX: %f LinY: %f LinZ: %f\r\n",
linAccel.x, linAccel.y, linAccel.z);
fprintf(ofp, "GravX: %f GravY: %f GravZ: %f\r\n",
grav.x, grav.y, grav.z);
fprintf(ofp, "\r\n");
pCount++;
wait_ms(10);
}
MotorL.start(0);
MotorR.start(0);
//Unmount the filesystem
fprintf(ofp,"End of Program\r\n");
fclose(ofp);
printf("Unmounting SD card\r\n");
sd.unmount();
Pc.printf("SD card unmounted\r\n");
Pc.printf("Program Terminated\r\n");
while(1);
}
<commit_msg>cleaned up the data collection program, output should be csv (untested)<commit_after>/**
* SD Card Read/Write Test
* 4/5/2017
*
**/
//#include <stdlib.h>
//#include <stdio.h>
#include "mbed.h"
#include "pinout.h"
#include "SDFileSystem.h"
#include "imu.h"
#include "GPS.h"
#include "QEI.h"
#include "motor.h"
#include "PwmIn.h"
/* map structure */
typedef struct Point {
int time;
int x; //need to change to GPS relevent values
int y;
int dir; //need to change to imu relevent values
int vel;
} Point;
typedef struct Map {
Point nw; //NorthWest corner of the map
Point ne; //NorthEast corner of the map
Point sw; //southwest corner of the map
Point se; //southEast corner of the map
float mAccel; //Maximum allowed acceleration
float mVel; //Maximum allowed velocity
int npoints; //number of map points to run
Point *path; //array of map points to be run
} Map;
int readMap(FILE *fp, Map *mp) {
// char *line;
// int len;
if (!fp)
return -1;
/* while(line = getline(&line, &len, fp) != -1) {
printf("%s\r\n", line);
}
*/
return 0;
}
int checkMap(Map *mp) {
return 0;
}
//Function allows driving by RC controler
int modeRC(float throtle, float lrat, int *mr, int *ml) {
throtle *= 1000000;
throtle -= 1100;
throtle /= 8;
lrat *= 1000000;
lrat -= 1000;
lrat /= 1000;
*ml = (int)((1 - lrat) * throtle);
*mr = (int)(lrat * throtle);
return 0;
}
/* Test Objects */
Serial Pc(USBTX,USBRX);
/* file system objects */
SDFileSystem sd(DI, DO, CLK, CS, "sd");
/* IMU objects */
IMU imu(I2C_SDA, I2C_SCL, BNO055_G_CHIP_ADDR, true);
/* Motor Objects */
MOTOR MotorR(1, IN2A, IN1A, ENA, true);
MOTOR MotorL(2, IN2B, IN1B, ENB, true);
/* Encoder Objects */
QEI EncoderL(CHA1, CHB1, NC, 192, QEI::X4_ENCODING);
QEI EncoderR(CHA2, CHB2, NC, 192, QEI::X4_ENCODING);
/* IMU Objects */
IMU Imu(IMDA, IMCL, BNO055_G_CHIP_ADDR, true);
/* GPS Objects */
GPS Gps(GPTX, GPRX);
/* Radio Objects */
PwmIn Throt(THRO);
PwmIn Lr(LRIN);
PwmIn Mode(MODE);
PwmIn E_Stop(ESTO);
/* Input Buttons */
DigitalIn Btn(PC_0);
DigitalIn Dip(PB_6);
int main()
{
Map mp;
int pCount = 0;
//radio variables
float throtle, leftright, mode, estop;
//motor variables
int mr, ml;
//encoder variables
int lenc, renc;
//gps variables
int lock;
// Creates variables of reading data types
IMU::imu_euler_t euler;
IMU::imu_lin_accel_t linAccel;
IMU::imu_gravity_t grav;
//Mount the filesystem
printf("Mounting SD card\r\n");
sd.mount();
FILE *ofp = fopen("/sd/data.txt", "w");
FILE *ifp = fopen("/sd/map.mp", "r");
//infinite loop if SD card not found
if (ofp == NULL) {
Pc.printf("SD card not found\r\n");
while(1) ;
}
//open map file
if (ifp == NULL) {
Pc.printf("No Map File Found! ABORT!\r\n");
while(1) ;
}
//parse map file into Map structure
if (readMap(ifp, &mp)) {
Pc.printf("Map parse failed\r\n");
while(1);
}
//review the map structure for errors
if (checkMap(&mp)) {
Pc.printf("Map does not fit rules\r\n");
while(1);
}
//close the map file, won't be using it anymore
fclose(ifp);
Pc.printf("FileSystem ready\r\n");
//Initialise motors
MotorL.start(0);
MotorR.start(0);
Pc.printf("Motors initialised\r\n");
Pc.printf("Waiting on user GO\r\n");
//estop must transition from low to high to activate vehical
while ((estop = E_Stop.pulsewidth() * 1000000) < 1150 &&
estop > 1090)
;
while ((estop = E_Stop.pulsewidth() * 1000000) != 1096)
;
//print collumn catagories
Pc.printf("User GO accepted starting run\r\n");
fprintf(ofp, "Point#, nearest waypoint, next waypoint, ");
fprintf(ofp, "rcThrot, rcDir, rcE-stop, rcMode, ");
fprintf(ofp, "time, lat, long, #sat, ");
fprintf(ofp, "xAcc, yAcc, zAcc, heading, pitch, role, xGra, yGra, zGra, ");
fprintf(ofp, "lEncoder, rEncoder, lMotor, rMotor\r\n");
//main loop, breaks out if estop tripped
while((estop = E_Stop.pulsewidth() * 1000000) < 1150 && estop > 1090) {
////////////////////////////Gather Data
//get radio values
throtle = Throt.pulsewidth();
mode = Mode.pulsewidth();
leftright = Lr.pulsewidth();
//Read data from IMU
imu.getEulerAng(&euler);
imu.getLinAccel(&linAccel);
imu.getGravity(&grav);
//get encoder data and reset encoders
lenc = EncoderL.getPulses();
renc = EncoderR.getPulses();
EncoderL.reset();
EncoderR.reset();
//get gps data
lock = Gps.parseData();
//////////////////////////Use Data to make decisions
//Check Dip2 && radio state then set the motor variables accordingly
if(Btn && (mode * 1000000) > 1450 && mode < 1550) {
//Radio control mode
modeRC(throtle, leftright, &mr, &ml);
} else {
//all other states atmo are just dead stop
ml = 0;
mr = 0;
}
///////////////////////////Record data and decisions to file
//record map relevent data (not currently used)
fprintf(ofp, "%d, %d, %d, ", pCount, 0, 0);
//record radio values
fprintf(ofp, "%f, %f, %f, %f, ", throtle, leftright, estop, mode);
//record gps data if available
if (lock) {
fprintf(ofp, "%f, %f, %f, %d, ", Gps.time, Gps.latitude,
Gps.longitude, Gps.satellites);
} else {
fprintf(ofp, "NL, NL, NL, NL, NL, ");
}
//record data from IMU
fprintf(ofp, "%f, %f, %f, ", linAccel.x, linAccel.y, linAccel.z);
fprintf(ofp, "%f, %f, %f, ", euler.heading, euler.pitch, euler.roll);
fprintf(ofp, "%f, %f, %f, ", grav.x, grav.y, grav.z);
//record encoder data
fprintf(ofp, "%d, %d, ", lenc, renc);
//record motor variables
fprintf(ofp, "%d, %d\r\n", ml, mr);
/////////////////////////////use decisions to change motors
//Set motors
MotorL.start(ml);
MotorR.start(mr);
////////////////////////////end of loop cleanup and multiloop funcs
//Increment data point count
pCount++;
//delay 10ms, this may be removed in future if we use a heavy algorithm
wait_ms(10);
}
//power down motors
MotorL.start(0);
MotorR.start(0);
//Unmount the filesystem
fprintf(ofp,"End of Program\r\n");
fclose(ofp);
printf("Unmounting SD card\r\n");
sd.unmount();
Pc.printf("SD card unmounted\r\n");
Pc.printf("Program Terminated\r\n");
while(1);
}
<|endoftext|> |
<commit_before>/*
* ===============================================================
* Description: Reachability program.
*
* Created: Sunday 23 April 2013 11:00:03 EDT
*
* Author: Ayush Dubey, Greg Hill
* [email protected], [email protected]
*
* Copyright (C) 2013, Cornell University, see the LICENSE file
* for licensing agreement
* ================================================================
*/
#include "reach_program.h"
namespace node_prog
{
bool
check_cache_context(cache_response<reach_cache_value> &cr)
{
std::vector<node_cache_context>& contexts = cr.get_context();
if (contexts.size() == 0) {
return true;
}
reach_cache_value &cv = *cr.get_value();
// path not valid if broken by:
for (node_cache_context& node_context : contexts)
{
if (node_context.node_deleted){ // node deletion
WDEBUG << "Cache entry invalid because of node deletion" << std::endl;
return false;
}
// edge deletion, see if path was broken
for (size_t i = 1; i < cv.path.size(); i++) {
if (node_context.node == cv.path.at(i)) {
db::element::remote_node &path_next_node = cv.path.at(i-1);
for(auto &edge : node_context.edges_deleted){
if (edge.nbr == path_next_node) {
WDEBUG << "Cache entry invalid because of edge deletion" << std::endl;
return false;
}
}
break; // path not broken here, move on
}
}
}
WDEBUG << "Cache entry with context size " << contexts.size() << " valid" << std::endl;
return true;
}
std::vector<std::pair<db::element::remote_node, reach_params>>
reach_node_program(
node &n,
db::element::remote_node &rn,
reach_params ¶ms,
std::function<reach_node_state&()> state_getter,
std::function<void(std::shared_ptr<reach_cache_value>, // TODO make const
std::shared_ptr<std::vector<db::element::remote_node>>, uint64_t)>& add_cache_func,
cache_response<reach_cache_value>*cache_response)
{
reach_node_state &state = state_getter();
std::vector<std::pair<db::element::remote_node, reach_params>> next;
bool false_reply = false;
db::element::remote_node prev_node = params.prev_node;
params.prev_node = rn;
if (!params.returning) { // request mode
if (params.dest == rn.get_id()) {
// we found the node we are looking for, prepare a reply
params.returning = true;
params.reachable = true;
params.path.emplace_back(rn);
return {std::make_pair(prev_node, params)};
} else {
// have not found it yet so follow all out edges
if (!state.visited) {
state.prev_node = prev_node;
state.visited = true;
if (MAX_CACHE_ENTRIES)
{
if (params._search_cache /*&& !params.returning */ && cache_response != NULL){
// check context, update cache
bool valid = check_cache_context(*cache_response);
if (valid) {
// we found the node we are looking for, prepare a reply
params.returning = true;
params.reachable = true;
params._search_cache = false; // don't search on way back
// context for cached value contains the nodes in the path to the dest_idination from this node
params.path = std::dynamic_pointer_cast<reach_cache_value>(cache_response->get_value())->path; // XXX double check this path
WDEBUG << "Cache worked at node " << rn.id << " with path len " << params.path.size() << std::endl;
return {std::make_pair(prev_node, params)}; // single length vector
} else {
cache_response->invalidate();
}
}
}
for (edge &e: n.get_edges()) {
// checking edge properties
if (e.has_all_properties(params.edge_props)) {
// e->traverse(); no more traversal recording
// propagate reachability request
next.emplace_back(std::make_pair(e.get_neighbor(), params));
state.out_count++;
}
}
if (state.out_count == 0) {
false_reply = true;
}
} else {
false_reply = true;
}
}
if (false_reply) {
params.returning = true;
params.reachable = false;
next.emplace_back(std::make_pair(prev_node, params));
}
} else { // reply mode
if (params.reachable) {
if (state.hops > params.hops) {
state.hops = params.hops;
}
}
if (((--state.out_count == 0) || params.reachable) && !state.reachable) {
state.reachable |= params.reachable;
if (params.reachable) {
params.hops = state.hops + 1;
params.path.emplace_back(rn);
if (MAX_CACHE_ENTRIES)
{
// now add to cache
WDEBUG << "adding to cache on way back from dest on node " << rn.id << " with path len " << params.path.size() << std::endl;
std::shared_ptr<node_prog::reach_cache_value> toCache(new reach_cache_value(params.path));
std::shared_ptr<std::vector<db::element::remote_node>> watch_set(new std::vector<db::element::remote_node>(params.path)); // copy return path from params
add_cache_func(toCache, watch_set, params.dest);
}
}
next.emplace_back(std::make_pair(state.prev_node, params));
}
if ((int)state.out_count < 0) {
WDEBUG << "ALERT! Bad state value in reach program" << std::endl;
next.clear();
}
}
return next;
}
}
<commit_msg>added more debug statements, small flag fix on reachability prog<commit_after>/*
* ===============================================================
* Description: Reachability program.
*
* Created: Sunday 23 April 2013 11:00:03 EDT
*
* Author: Ayush Dubey, Greg Hill
* [email protected], [email protected]
*
* Copyright (C) 2013, Cornell University, see the LICENSE file
* for licensing agreement
* ================================================================
*/
//#define weaver_debug_
#include "reach_program.h"
namespace node_prog
{
inline bool
check_cache_context(cache_response<reach_cache_value> &cr)
{
std::vector<node_cache_context>& contexts = cr.get_context();
if (contexts.size() == 0) {
return true;
}
reach_cache_value &cv = *cr.get_value();
// path not valid if broken by:
for (node_cache_context& node_context : contexts)
{
if (node_context.node_deleted){ // node deletion
WDEBUG << "Cache entry invalid because of node deletion" << std::endl;
return false;
}
// edge deletion, see if path was broken
for (size_t i = 1; i < cv.path.size(); i++) {
if (node_context.node == cv.path.at(i)) {
db::element::remote_node &path_next_node = cv.path.at(i-1);
for(auto &edge : node_context.edges_deleted){
if (edge.nbr == path_next_node) {
WDEBUG << "Cache entry invalid because of edge deletion" << std::endl;
return false;
}
}
break; // path not broken here, move on
}
}
}
WDEBUG << "Cache entry with context size " << contexts.size() << " valid" << std::endl;
return true;
}
std::vector<std::pair<db::element::remote_node, reach_params>>
reach_node_program(
node &n,
db::element::remote_node &rn,
reach_params ¶ms,
std::function<reach_node_state&()> state_getter,
std::function<void(std::shared_ptr<reach_cache_value>, // TODO make const
std::shared_ptr<std::vector<db::element::remote_node>>, uint64_t)>& add_cache_func,
cache_response<reach_cache_value>*cache_response)
{
WDEBUG << "REACH AT NODE " << rn.id << std::endl;
reach_node_state &state = state_getter();
std::vector<std::pair<db::element::remote_node, reach_params>> next;
bool false_reply = false;
db::element::remote_node prev_node = params.prev_node;
params.prev_node = rn;
if (!params.returning) { // request mode
if (params.dest == rn.get_id()) {
// we found the node we are looking for, prepare a reply
params.returning = true;
params.reachable = true;
params.path.emplace_back(rn);
params._search_cache = false; // never search on way back
WDEBUG << "returning to node " << prev_node.id << " because found " << std::endl;
return {std::make_pair(prev_node, params)};
} else {
// have not found it yet so follow all out edges
if (!state.visited) {
state.prev_node = prev_node;
state.visited = true;
if (MAX_CACHE_ENTRIES)
{
WDEBUG << "in cache section with search cache " << params._search_cache << ", cache key = " << params._cache_key << " and cache response "<< cache_response << std::endl;
if (params._search_cache /*&& !params.returning */ && cache_response != NULL){
// check context, update cache
if (check_cache_context(*cache_response)) { // if context is valid
// we found the node we are looking for, prepare a reply
params.returning = true;
params.reachable = true;
params._search_cache = false; // don't search on way back
// context for cached value contains the nodes in the path to the dest_idination from this node
params.path = std::dynamic_pointer_cast<reach_cache_value>(cache_response->get_value())->path; // XXX double check this path
WDEBUG << "Cache worked at node " << rn.id << " with path len " << params.path.size() << std::endl;
WDEBUG << "path is "<< std::endl;
for (db::element::remote_node &r : params.path) {
WDEBUG << r.id << std::endl;
}
WDEBUG << std::endl;
WDEBUG << "returning to node " << prev_node.id << " in positive cache response " << std::endl;
return {std::make_pair(prev_node, params)}; // single length vector
} else {
cache_response->invalidate();
}
}
}
for (edge &e: n.get_edges()) {
// checking edge properties
if (e.has_all_properties(params.edge_props)) {
// e->traverse(); no more traversal recording
// propagate reachability request
next.emplace_back(std::make_pair(e.get_neighbor(), params));
WDEBUG << "emplacing " << e.get_neighbor().id << " to next" << std::endl;
state.out_count++;
}
}
if (state.out_count == 0) {
false_reply = true;
}
} else {
false_reply = true;
}
}
if (false_reply) {
params.returning = true;
params.reachable = false;
next.emplace_back(std::make_pair(prev_node, params));
}
} else { // reply mode
if (params.reachable) {
if (state.hops > params.hops) {
state.hops = params.hops;
}
}
if (((--state.out_count == 0) || params.reachable) && !state.reachable) {
state.reachable |= params.reachable;
if (params.reachable) {
params.hops = state.hops + 1;
params.path.emplace_back(rn);
if (MAX_CACHE_ENTRIES)
{
// now add to cache
WDEBUG << "adding to cache for key " << params.dest << " on way back from dest on node " << rn.id << " with path len " << params.path.size() << std::endl;
WDEBUG << "path is "<< std::endl;
for (db::element::remote_node &r : params.path) {
WDEBUG << r.id<< std::endl;
}
WDEBUG << std::endl;
std::shared_ptr<node_prog::reach_cache_value> toCache(new reach_cache_value(params.path));
std::shared_ptr<std::vector<db::element::remote_node>> watch_set(new std::vector<db::element::remote_node>(params.path)); // copy return path from params
add_cache_func(toCache, watch_set, params.dest);
}
}
next.emplace_back(std::make_pair(state.prev_node, params));
}
if ((int)state.out_count < 0) {
WDEBUG << "ALERT! Bad state value in reach program" << std::endl;
next.clear();
}
}
WDEBUG << "propagating to "<< std::endl;
for (auto &pair : next) {
WDEBUG << pair.first.id << std::endl;
}
WDEBUG << std::endl;
return next;
}
}
<|endoftext|> |
<commit_before>/*******************************************************************************
*
* MIT License
*
* Copyright (c) 2017 Advanced Micro Devices, Inc.
*
* 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.
*
*******************************************************************************/
#ifndef GUARD_TENSOR_HOLDER_HPP
#define GUARD_TENSOR_HOLDER_HPP
#include "ford.hpp"
#include "network_data.hpp"
#include <miopen/tensor.hpp>
#include <miopen/functional.hpp>
template <class F>
void visit_tensor_size(std::size_t n, F f)
{
switch(n)
{
case 0:
{
f(std::integral_constant<std::size_t, 0>{});
break;
}
case 1:
{
f(std::integral_constant<std::size_t, 1>{});
break;
}
case 2:
{
f(std::integral_constant<std::size_t, 2>{});
break;
}
case 3:
{
f(std::integral_constant<std::size_t, 3>{});
break;
}
case 4:
{
f(std::integral_constant<std::size_t, 4>{});
break;
}
case 5:
{
f(std::integral_constant<std::size_t, 5>{});
break;
}
default: throw std::runtime_error("Unknown tensor size");
}
}
template <class T>
struct tensor
{
miopen::TensorDescriptor desc;
std::vector<T> data;
tensor() {}
template <class X>
tensor(const std::vector<X>& dims)
: desc(miopenFloat, dims.data(), static_cast<int>(dims.size())), data(desc.GetElementSize())
{
}
tensor(std::size_t n, std::size_t c, std::size_t h, std::size_t w)
: desc(miopenFloat, {n, c, h, w}), data(n * c * h * w)
{
}
tensor(miopen::TensorDescriptor rhs) : desc(std::move(rhs))
{
data.resize(desc.GetElementSize());
}
template <class G>
tensor& generate(G g) &
{
this->generate_impl(g);
return *this;
}
template <class G>
tensor&& generate(G g) &&
{
this->generate_impl(g);
return std::move(*this);
}
template <class G>
void generate_impl(G g)
{
auto iterator = data.begin();
auto assign = [&](T x)
{
assert(iterator < data.end());
*iterator = x;
++iterator;
};
this->for_each(miopen::compose(assign, std::move(g)));
}
template <class Loop, class F>
struct for_each_unpacked
{
Loop loop;
F f;
template <class... Ts>
auto operator()(Ts... xs) const -> decltype(f(xs...), void())
{
loop(xs...)(std::move(f));
}
void operator()(...) const
{
throw std::runtime_error("Arguments to for_each do not match tensor size");
}
};
struct for_each_handler
{
template <class Self, class Loop, class F, class Size>
void operator()(Self* self, Loop loop, F f, Size size) const
{
auto dims = miopen::tien<size>(self->desc.GetLengths());
miopen::unpack(for_each_unpacked<Loop, F>{loop, std::move(f)}, dims);
}
};
template <class F>
void for_each(F f) const
{
visit_tensor_size(
desc.GetLengths().size(),
std::bind(for_each_handler{}, this, ford, std::move(f), std::placeholders::_1));
}
template <class F>
void par_for_each(F f) const
{
visit_tensor_size(
desc.GetLengths().size(),
std::bind(for_each_handler{}, this, par_ford, std::move(f), std::placeholders::_1));
}
template <class... Ts>
T& operator()(Ts... xs)
{
assert(this->desc.GetIndex(xs...) < data.size());
return this->data[this->desc.GetIndex(xs...)];
}
template <class... Ts>
const T& operator()(Ts... xs) const
{
assert(this->desc.GetIndex(xs...) < data.size());
return this->data[this->desc.GetIndex(xs...)];
}
T& operator[](std::size_t i) { return data.at(i); }
const T& operator[](std::size_t i) const { return data.at(i); }
typename std::vector<T>::iterator begin() { return data.begin(); }
typename std::vector<T>::iterator end() { return data.end(); }
typename std::vector<T>::const_iterator begin() const { return data.begin(); }
typename std::vector<T>::const_iterator end() const { return data.end(); }
};
template <class T, class G>
tensor<T> make_tensor(std::initializer_list<std::size_t> dims, G g)
{
// TODO: Compute float
return tensor<T>{miopen::TensorDescriptor{miopenFloat, dims}}.generate(g);
}
template <class T, class X>
tensor<T> make_tensor(const std::vector<X>& dims)
{
// TODO: Compute float
return tensor<T>{
miopen::TensorDescriptor{miopenFloat, dims.data(), static_cast<int>(dims.size())}};
}
template <class T, class X, class G>
tensor<T> make_tensor(const std::vector<X>& dims, G g)
{
return make_tensor<T>(dims).generate(g);
}
struct tensor_generate
{
template <class Tensor, class G>
Tensor&& operator()(Tensor&& t, G g) const
{
return std::forward<Tensor>(t.generate(g));
}
};
template <class F>
struct protect_void_fn
{
F f;
protect_void_fn(F x) : f(std::move(x)) {}
// template<class... Ts>
// auto operator()(Ts&&... xs) const MIOPEN_RETURNS
// (f(std::forward<Ts>(xs)...));
template <class... Ts>
void operator()(Ts&&... xs) const
{
f(std::forward<Ts>(xs)...);
}
};
template <class F>
protect_void_fn<F> protect_void(F f)
{
return {std::move(f)};
}
struct cross_args_apply
{
template <class F, class T, class... Ts>
void operator()(F f, T&& x, Ts&&... xs) const
{
miopen::each_args(std::bind(f, std::forward<T>(x), std::placeholders::_1),
std::forward<Ts>(xs)...);
}
};
template <class F, class... Ts>
void cross_args(F f, Ts&&... xs)
{
miopen::each_args(std::bind(cross_args_apply{},
protect_void(std::move(f)),
std::placeholders::_1,
std::forward<Ts>(xs)...),
std::forward<Ts>(xs)...);
}
template <class T>
struct generate_both_visitation
{
template <class F, class G1, class G2>
void operator()(F f, G1 g1, G2 g2) const
{
for(auto&& input : get_inputs())
for(auto&& weights : get_weights())
if(input.at(1) == weights.at(1)) // channels must match
f(make_tensor<T>(input, g1), make_tensor<T>(weights, g2));
}
};
template <class T, class F, class... Gs>
void generate_binary_all(F f, Gs... gs)
{
cross_args(std::bind(generate_both_visitation<T>{},
protect_void(f),
std::placeholders::_1,
std::placeholders::_2),
gs...);
}
template <class T, class F, class G>
void generate_binary_one(F f, std::vector<int> input, std::vector<int> weights, G g)
{
f(make_tensor<T>(input, g), make_tensor<T>(weights, g));
}
template <class T>
struct generate_activ_visitation
{
template <class F, class G>
void operator()(F f, G g) const
{
for(auto&& input : get_inputs())
f(make_tensor<T>(input, g));
}
};
template <class T, class F, class... Gs>
void generate_unary_all(F f, Gs... gs)
{
miopen::each_args(
std::bind(generate_activ_visitation<T>{}, protect_void(f), std::placeholders::_1), gs...);
}
template <class T, class F, class G>
void generate_unary_one(F f, std::vector<int> input, G g)
{
f(make_tensor<T>(input, g));
}
#endif
<commit_msg>One more try at merge.<commit_after>/*******************************************************************************
*
* MIT License
*
* Copyright (c) 2017 Advanced Micro Devices, Inc.
*
* 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.
*
*******************************************************************************/
#ifndef GUARD_TENSOR_HOLDER_HPP
#define GUARD_TENSOR_HOLDER_HPP
#include "ford.hpp"
#include "network_data.hpp"
#include <miopen/tensor.hpp>
#include <miopen/functional.hpp>
template <class F>
void visit_tensor_size(std::size_t n, F f)
{
switch(n)
{
case 0:
{
f(std::integral_constant<std::size_t, 0>{});
break;
}
case 1:
{
f(std::integral_constant<std::size_t, 1>{});
break;
}
case 2:
{
f(std::integral_constant<std::size_t, 2>{});
break;
}
case 3:
{
f(std::integral_constant<std::size_t, 3>{});
break;
}
case 4:
{
f(std::integral_constant<std::size_t, 4>{});
break;
}
case 5:
{
f(std::integral_constant<std::size_t, 5>{});
break;
}
default: throw std::runtime_error("Unknown tensor size");
}
}
template <class T>
struct tensor
{
miopen::TensorDescriptor desc;
std::vector<T> data;
tensor() {}
template <class X>
tensor(const std::vector<X>& dims)
: desc(miopenFloat, dims.data(), static_cast<int>(dims.size())), data(desc.GetElementSize())
{
}
tensor(std::size_t n, std::size_t c, std::size_t h, std::size_t w)
: desc(miopenFloat, {n, c, h, w}), data(n * c * h * w)
{
}
tensor(miopen::TensorDescriptor rhs) : desc(std::move(rhs))
{
data.resize(desc.GetElementSize());
}
template <class G>
tensor& generate(G g) &
{
this->generate_impl(g);
return *this;
}
template <class G>
tensor&& generate(G g) &&
{
this->generate_impl(g);
return std::move(*this);
}
template <class G>
void generate_impl(G g)
{
auto iterator = data.begin();
auto assign = [&](T x)
{
assert(iterator < data.end());
*iterator = x;
++iterator;
};
this->for_each(miopen::compose(assign, std::move(g)));
}
template <class Loop, class F>
struct for_each_unpacked
{
Loop loop;
F f;
template <class... Ts>
auto operator()(Ts... xs) const -> decltype(f(xs...), void())
{
loop(xs...)(std::move(f));
}
void operator()(...) const
{
throw std::runtime_error("Arguments to for_each do not match tensor size");
}
};
struct for_each_handler
{
template <class Self, class Loop, class F, class Size>
void operator()(Self* self, Loop loop, F f, Size size) const
{
auto dims = miopen::tien<size>(self->desc.GetLengths());
miopen::unpack(for_each_unpacked<Loop, F>{loop, std::move(f)}, dims);
}
};
template <class F>
void for_each(F f) const
{
visit_tensor_size(
desc.GetLengths().size(),
std::bind(for_each_handler{}, this, ford, std::move(f), std::placeholders::_1));
}
template <class F>
void par_for_each(F f) const
{
visit_tensor_size(
desc.GetLengths().size(),
std::bind(for_each_handler{}, this, par_ford, std::move(f), std::placeholders::_1));
}
template <class... Ts>
T& operator()(Ts... ds)
{
assert(this->desc.GetIndex(ds...) < data.size());
return this->data[this->desc.GetIndex(ds...)];
}
template <class... Ts>
const T& operator()(Ts... xs) const
{
assert(this->desc.GetIndex(xs...) < data.size());
return this->data[this->desc.GetIndex(xs...)];
}
T& operator[](std::size_t i) { return data.at(i); }
const T& operator[](std::size_t i) const { return data.at(i); }
typename std::vector<T>::iterator begin() { return data.begin(); }
typename std::vector<T>::iterator end() { return data.end(); }
typename std::vector<T>::const_iterator begin() const { return data.begin(); }
typename std::vector<T>::const_iterator end() const { return data.end(); }
};
template <class T, class G>
tensor<T> make_tensor(std::initializer_list<std::size_t> dims, G g)
{
// TODO: Compute float
return tensor<T>{miopen::TensorDescriptor{miopenFloat, dims}}.generate(g);
}
template <class T, class X>
tensor<T> make_tensor(const std::vector<X>& dims)
{
// TODO: Compute float
return tensor<T>{
miopen::TensorDescriptor{miopenFloat, dims.data(), static_cast<int>(dims.size())}};
}
template <class T, class X, class G>
tensor<T> make_tensor(const std::vector<X>& dims, G g)
{
return make_tensor<T>(dims).generate(g);
}
struct tensor_generate
{
template <class Tensor, class G>
Tensor&& operator()(Tensor&& t, G g) const
{
return std::forward<Tensor>(t.generate(g));
}
};
template <class F>
struct protect_void_fn
{
F f;
protect_void_fn(F x) : f(std::move(x)) {}
// template<class... Ts>
// auto operator()(Ts&&... xs) const MIOPEN_RETURNS
// (f(std::forward<Ts>(xs)...));
template <class... Ts>
void operator()(Ts&&... xs) const
{
f(std::forward<Ts>(xs)...);
}
};
template <class F>
protect_void_fn<F> protect_void(F f)
{
return {std::move(f)};
}
struct cross_args_apply
{
template <class F, class T, class... Ts>
void operator()(F f, T&& x, Ts&&... xs) const
{
miopen::each_args(std::bind(f, std::forward<T>(x), std::placeholders::_1),
std::forward<Ts>(xs)...);
}
};
template <class F, class... Ts>
void cross_args(F f, Ts&&... xs)
{
miopen::each_args(std::bind(cross_args_apply{},
protect_void(std::move(f)),
std::placeholders::_1,
std::forward<Ts>(xs)...),
std::forward<Ts>(xs)...);
}
template <class T>
struct generate_both_visitation
{
template <class F, class G1, class G2>
void operator()(F f, G1 g1, G2 g2) const
{
for(auto&& input : get_inputs())
for(auto&& weights : get_weights())
if(input.at(1) == weights.at(1)) // channels must match
f(make_tensor<T>(input, g1), make_tensor<T>(weights, g2));
}
};
template <class T, class F, class... Gs>
void generate_binary_all(F f, Gs... gs)
{
cross_args(std::bind(generate_both_visitation<T>{},
protect_void(f),
std::placeholders::_1,
std::placeholders::_2),
gs...);
}
template <class T, class F, class G>
void generate_binary_one(F f, std::vector<int> input, std::vector<int> weights, G g)
{
f(make_tensor<T>(input, g), make_tensor<T>(weights, g));
}
template <class T>
struct generate_activ_visitation
{
template <class F, class G>
void operator()(F f, G g) const
{
for(auto&& input : get_inputs())
f(make_tensor<T>(input, g));
}
};
template <class T, class F, class... Gs>
void generate_unary_all(F f, Gs... gs)
{
miopen::each_args(
std::bind(generate_activ_visitation<T>{}, protect_void(f), std::placeholders::_1), gs...);
}
template <class T, class F, class G>
void generate_unary_one(F f, std::vector<int> input, G g)
{
f(make_tensor<T>(input, g));
}
#endif
<|endoftext|> |
<commit_before>#include <cppcutter.h>
#include "tuishogi.cpp"
namespace tuishogi {
void
test_showState(void)
{
// Arrange
using namespace osl;
std::stringbuf string_out;
std::streambuf* std_out = std::cout.rdbuf(&string_out);
NumEffectState state((SimpleState(HIRATE)));
const char* expected = "\
P1-KY-KE-GI-KI-OU-KI-GI-KE-KY\n\
P2 * -HI * * * * * -KA * \n\
P3-FU-FU-FU-FU-FU-FU-FU-FU-FU\n\
P4 * * * * * * * * * \n\
P5 * * * * * * * * * \n\
P6 * * * * * * * * * \n\
P7+FU+FU+FU+FU+FU+FU+FU+FU+FU\n\
P8 * +KA * * * * * +HI * \n\
P9+KY+KE+GI+KI+OU+KI+GI+KE+KY\n\
+\n\
\n";
// Act
showState(state);
std::cout << std::flush;
std::cout.rdbuf(std_out);
// TODO assert it as a std::string
std::string str = string_out.str();
const char* actual = str.c_str();
// Assert
cut_assert_equal_string(expected, actual);
}
void
test_isMated(void)
{
using namespace osl;
NumEffectState state((SimpleState(HIRATE)));
bool mated = isMated(state);
cut_assert_false(mated);
}
void
test_computerOperate(void)
{
using namespace osl;
// TODO cleanup
std::stringbuf string_out;
std::streambuf* std_out = std::cout.rdbuf(&string_out);
NumEffectState state((SimpleState(HIRATE)));
bool ended = computerOperate(state);
std::cout << std::flush;
std::cout.rdbuf(std_out);
cut_assert_false(ended);
}
} // namespace tuishogi
<commit_msg>Add tests for playerOperate()<commit_after>#include <cppcutter.h>
#include "tuishogi.cpp"
namespace tuishogi {
void
test_showState(void)
{
// Arrange
using namespace osl;
std::stringbuf string_out;
std::streambuf* std_out = std::cout.rdbuf(&string_out);
NumEffectState state((SimpleState(HIRATE)));
const char* expected = "\
P1-KY-KE-GI-KI-OU-KI-GI-KE-KY\n\
P2 * -HI * * * * * -KA * \n\
P3-FU-FU-FU-FU-FU-FU-FU-FU-FU\n\
P4 * * * * * * * * * \n\
P5 * * * * * * * * * \n\
P6 * * * * * * * * * \n\
P7+FU+FU+FU+FU+FU+FU+FU+FU+FU\n\
P8 * +KA * * * * * +HI * \n\
P9+KY+KE+GI+KI+OU+KI+GI+KE+KY\n\
+\n\
\n";
// Act
showState(state);
std::cout << std::flush;
std::cout.rdbuf(std_out);
// TODO assert it as a std::string
std::string str = string_out.str();
const char* actual = str.c_str();
// Assert
cut_assert_equal_string(expected, actual);
}
void
test_isMated(void)
{
using namespace osl;
NumEffectState state((SimpleState(HIRATE)));
bool mated = isMated(state);
cut_assert_false(mated);
}
void
test_computerOperate(void)
{
using namespace osl;
// TODO cleanup
std::stringbuf string_out;
std::streambuf* std_out = std::cout.rdbuf(&string_out);
NumEffectState state((SimpleState(HIRATE)));
bool ended = computerOperate(state);
std::cout << std::flush;
std::cout.rdbuf(std_out);
cut_assert_false(ended);
}
void
test_playerOperate_valid(void)
{
using namespace osl;
// TODO cleanup
std::stringbuf string_out;
std::streambuf* std_out = std::cout.rdbuf(&string_out);
NumEffectState state((SimpleState(HIRATE)));
bool failed = playerOperate(state, "+7776FU");
std::cout << std::flush;
std::cout.rdbuf(std_out);
cut_assert_false(failed);
}
void
test_playerOperate_invalid(void)
{
using namespace osl;
// TODO cleanup
std::stringbuf string_out;
std::streambuf* std_out = std::cout.rdbuf(&string_out);
NumEffectState state((SimpleState(HIRATE)));
bool failed = playerOperate(state, "+5251FU");
std::cout << std::flush;
std::cout.rdbuf(std_out);
cut_assert_true(failed);
}
} // namespace tuishogi
<|endoftext|> |
<commit_before>#include "testsettings.hpp"
#include <realm/util/optional.hpp>
#include "test.hpp"
using namespace realm::util;
TEST(Optional_DefaultConstructor)
{
Optional<int> x{};
CHECK(!bool(x));
}
TEST(Optional_NoneConstructor)
{
Optional<int> x{realm::none};
CHECK(!bool(x));
}
TEST(Optional_ValueConstructor)
{
Optional<std::string> a { "foo" };
CHECK(bool(a));
}
TEST(Optional_MoveConstructor)
{
Optional<std::string> a { "foo" };
Optional<std::string> b { std::move(a) };
CHECK(bool(a));
CHECK(bool(b));
CHECK_EQUAL(*a, "");
CHECK_EQUAL(*b, "foo");
}
TEST(Optional_CopyConstructor)
{
Optional<std::string> a { "foo" };
Optional<std::string> b { a };
CHECK(bool(a));
CHECK(bool(b));
CHECK_EQUAL(*a, "foo");
CHECK_EQUAL(*b, "foo");
}
TEST(Optional_MoveValueConstructor)
{
std::string a = "foo";
Optional<std::string> b { std::move(a) };
CHECK(bool(b));
CHECK_EQUAL(*b, "foo");
CHECK_EQUAL(a, "");
}
struct SetBooleanOnDestroy {
bool& m_b;
explicit SetBooleanOnDestroy(bool& b) : m_b(b) {}
~SetBooleanOnDestroy() { m_b = true; }
};
TEST(Optional_Destructor)
{
bool b = false;
{
Optional<SetBooleanOnDestroy> x { SetBooleanOnDestroy(b) };
}
CHECK(b);
}
TEST(Optional_DestroyOnAssignNone)
{
bool b = false;
{
Optional<SetBooleanOnDestroy> x { SetBooleanOnDestroy(b) };
x = realm::none;
CHECK(b);
}
CHECK(b);
}
TEST(Optional_References)
{
int n = 0;
Optional<int&> x { n };
fmap(x, [&](int& y) {
y = 123;
});
CHECK(x);
CHECK_EQUAL(x.value(), 123);
x = realm::none;
CHECK(!x);
}
TEST(Optional_PolymorphicReferences)
{
struct Foo {
virtual ~Foo() {}
};
struct Bar: Foo {
virtual ~Bar() {}
};
Bar bar;
Optional<Bar&> bar_ref { bar };
Optional<Foo&> foo_ref { bar_ref };
CHECK(foo_ref);
CHECK_EQUAL(&foo_ref.value(), &bar);
}
namespace {
int make_rvalue()
{
return 1;
}
}
TEST(Optional_RvalueReferences)
{
// Should compile:
const int foo = 1;
Optional<const int&> x{foo};
static_cast<void>(x);
static_cast<void>(make_rvalue);
// Should not compile (would generate references to temporaries):
// Optional<const int&> y{1};
// Optional<const int&> z = 1;
// Optional<const int&> w = make_rvalue();
}
namespace {
/// See:
/// http://www.boost.org/doc/libs/1_57_0/libs/optional/doc/html/boost_optional/dependencies_and_portability/optional_reference_binding.html
const int global_i = 0;
struct TestingReferenceBinding {
TestingReferenceBinding(const int& ii)
{
REALM_ASSERT(&ii == &global_i);
}
void operator=(const int& ii)
{
REALM_ASSERT(&ii == &global_i);
}
void operator=(int&&)
{
REALM_ASSERT(false);
}
};
}
TEST(Optional_ReferenceBinding)
{
const int& iref = global_i;
CHECK_EQUAL(&iref, &global_i);
TestingReferenceBinding ttt = global_i;
ttt = global_i;
TestingReferenceBinding ttt2 = iref;
ttt2 = iref;
}
TEST(Optional_VoidIsEquivalentToBool)
{
auto a = some<void>();
CHECK_EQUAL(sizeof(a), sizeof(bool));
CHECK(a);
Optional<void> b = none;
CHECK_EQUAL(sizeof(b), sizeof(bool));
CHECK(!b);
}
TEST(Optional_fmap)
{
Optional<int> a { 123 };
bool a_called = false;
auto ar = fmap(a, [&](int) {
a_called = true;
});
CHECK(a_called);
CHECK(ar);
Optional<int> b { 123 };
auto bs = fmap(b, [](int foo) {
std::stringstream ss;
ss << foo;
return ss.str();
});
CHECK(bs);
CHECK_EQUAL(*bs, "123");
Optional<int> c;
Optional<int> cx = fmap(c, [](int) { return 0; });
CHECK(!cx);
}
TEST(Optional_StreamingMap)
{
Optional<int> a { 123 };
auto result = a
>> [](int b) { return b + 200; }
>> [](int c) {
std::ostringstream os;
os << c;
return os.str();
};
CHECK(result);
CHECK_EQUAL(result.value(), "323");
Optional<int> b { 500 };
Optional<int> result2 = b
>> [](int x) { return x > 300 ? some<int>(x + 300) : none; };
CHECK(result2);
}
<commit_msg>Added test for optional chaining.<commit_after>#include "testsettings.hpp"
#include <realm/util/optional.hpp>
#include "test.hpp"
using namespace realm::util;
TEST(Optional_DefaultConstructor)
{
Optional<int> x{};
CHECK(!bool(x));
}
TEST(Optional_NoneConstructor)
{
Optional<int> x{realm::none};
CHECK(!bool(x));
}
TEST(Optional_ValueConstructor)
{
Optional<std::string> a { "foo" };
CHECK(bool(a));
}
TEST(Optional_MoveConstructor)
{
Optional<std::string> a { "foo" };
Optional<std::string> b { std::move(a) };
CHECK(bool(a));
CHECK(bool(b));
CHECK_EQUAL(*a, "");
CHECK_EQUAL(*b, "foo");
}
TEST(Optional_CopyConstructor)
{
Optional<std::string> a { "foo" };
Optional<std::string> b { a };
CHECK(bool(a));
CHECK(bool(b));
CHECK_EQUAL(*a, "foo");
CHECK_EQUAL(*b, "foo");
}
TEST(Optional_MoveValueConstructor)
{
std::string a = "foo";
Optional<std::string> b { std::move(a) };
CHECK(bool(b));
CHECK_EQUAL(*b, "foo");
CHECK_EQUAL(a, "");
}
struct SetBooleanOnDestroy {
bool& m_b;
explicit SetBooleanOnDestroy(bool& b) : m_b(b) {}
~SetBooleanOnDestroy() { m_b = true; }
};
TEST(Optional_Destructor)
{
bool b = false;
{
Optional<SetBooleanOnDestroy> x { SetBooleanOnDestroy(b) };
}
CHECK(b);
}
TEST(Optional_DestroyOnAssignNone)
{
bool b = false;
{
Optional<SetBooleanOnDestroy> x { SetBooleanOnDestroy(b) };
x = realm::none;
CHECK(b);
}
CHECK(b);
}
TEST(Optional_References)
{
int n = 0;
Optional<int&> x { n };
fmap(x, [&](int& y) {
y = 123;
});
CHECK(x);
CHECK_EQUAL(x.value(), 123);
x = realm::none;
CHECK(!x);
}
TEST(Optional_PolymorphicReferences)
{
struct Foo {
virtual ~Foo() {}
};
struct Bar: Foo {
virtual ~Bar() {}
};
Bar bar;
Optional<Bar&> bar_ref { bar };
Optional<Foo&> foo_ref { bar_ref };
CHECK(foo_ref);
CHECK_EQUAL(&foo_ref.value(), &bar);
}
namespace {
int make_rvalue()
{
return 1;
}
}
TEST(Optional_RvalueReferences)
{
// Should compile:
const int foo = 1;
Optional<const int&> x{foo};
static_cast<void>(x);
static_cast<void>(make_rvalue);
// Should not compile (would generate references to temporaries):
// Optional<const int&> y{1};
// Optional<const int&> z = 1;
// Optional<const int&> w = make_rvalue();
}
namespace {
/// See:
/// http://www.boost.org/doc/libs/1_57_0/libs/optional/doc/html/boost_optional/dependencies_and_portability/optional_reference_binding.html
const int global_i = 0;
struct TestingReferenceBinding {
TestingReferenceBinding(const int& ii)
{
REALM_ASSERT(&ii == &global_i);
}
void operator=(const int& ii)
{
REALM_ASSERT(&ii == &global_i);
}
void operator=(int&&)
{
REALM_ASSERT(false);
}
};
}
TEST(Optional_ReferenceBinding)
{
const int& iref = global_i;
CHECK_EQUAL(&iref, &global_i);
TestingReferenceBinding ttt = global_i;
ttt = global_i;
TestingReferenceBinding ttt2 = iref;
ttt2 = iref;
}
TEST(Optional_VoidIsEquivalentToBool)
{
auto a = some<void>();
CHECK_EQUAL(sizeof(a), sizeof(bool));
CHECK(a);
Optional<void> b = none;
CHECK_EQUAL(sizeof(b), sizeof(bool));
CHECK(!b);
}
TEST(Optional_fmap)
{
Optional<int> a { 123 };
bool a_called = false;
auto ar = fmap(a, [&](int) {
a_called = true;
});
CHECK(a_called);
CHECK(ar);
Optional<int> b { 123 };
auto bs = fmap(b, [](int foo) {
std::stringstream ss;
ss << foo;
return ss.str();
});
CHECK(bs);
CHECK_EQUAL(*bs, "123");
Optional<int> c;
Optional<int> cx = fmap(c, [](int) { return 0; });
CHECK(!cx);
}
TEST(Optional_StreamingMap)
{
Optional<int> a { 123 };
auto result = a
>> [](int b) { return b + 200; }
>> [](int c) {
std::ostringstream os;
os << c;
return os.str();
};
CHECK(result);
CHECK_EQUAL(result.value(), "323");
Optional<int> b { 500 };
Optional<int> result2 = b
>> [](int x) { return x > 300 ? some<int>(x + 300) : none; };
CHECK(result2);
}
TEST(Optional_Chaining)
{
struct Foo {
int bar() { return 123; }
};
Optional<Foo> foo { Foo{} };
auto r = foo >> std::mem_fn(&Foo::bar);
CHECK(r);
CHECK_EQUAL(r.value(), 123);
}
<|endoftext|> |
<commit_before>#include <babylon/GL/framebuffer_canvas.h>
#include <babylon/babylon_imgui/babylon_logs_window.h>
#include <babylon/babylon_imgui/babylon_studio.h>
#include <babylon/core/filesystem.h>
#include <babylon/core/system.h>
#include <babylon/inspector/components/actiontabs/action_tabs_component.h>
#include <babylon/interfaces/irenderable_scene_with_hud.h>
#include <imgui.h>
#include <imgui_internal.h>
#include <imgui_utils/app_runner/imgui_runner.h>
#include <imgui_utils/icons_font_awesome_5.h>
#include <babylon/babylon_imgui/babylon_studio_layout.h>
#include <babylon/core/logging.h>
#include <babylon/samples/samples_index.h>
#ifdef _WIN32
#include <windows.h>
#endif
#include <iostream>
namespace BABYLON {
class BabylonStudioApp {
public:
BabylonStudioApp()
{
std::string exePath = BABYLON::System::getExecutablePath();
std::string exeFolder = BABYLON::Filesystem::baseDir(exePath);
std::string playgroundPath = exeFolder + "/../../../src/BabylonStudio/playground.cpp";
playgroundPath = BABYLON::Filesystem::absolutePath(playgroundPath);
_playgroundCodeEditor.setFiles({playgroundPath});
_playgroundCodeEditor.setLightPalette();
}
void RunApp(std::shared_ptr<BABYLON::IRenderableScene> initialScene,
const BabylonStudioOptions& options)
{
_appContext._options = options;
_appContext._options._appWindowParams.ShowMenuBar = true;
std::function<bool(void)> showGuiLambda = [this]() -> bool {
bool r = this->render();
for (auto f : _appContext._options._heartbeatCallbacks)
f();
if (_appContext._options._playgroundCompilerCallback) {
PlaygroundCompilerStatus playgroundCompilerStatus
= _appContext._options._playgroundCompilerCallback();
if (playgroundCompilerStatus._renderableScene)
setRenderableScene(playgroundCompilerStatus._renderableScene);
_appContext._isCompiling = playgroundCompilerStatus._isCompiling;
}
return r;
};
auto initSceneLambda = [&]() {
this->initScene();
this->setRenderableScene(initialScene);
};
_appContext._options._appWindowParams.InitialDockLayoutFunction = [this](ImGuiID mainDockId) {
_studioLayout.PrepareLayout(mainDockId);
};
ImGuiUtils::ImGuiRunner::RunGui(showGuiLambda, _appContext._options._appWindowParams,
initSceneLambda);
}
private:
void registerRenderFunctions()
{
static bool registered = false;
if (registered)
return;
// clang-format off
_studioLayout.registerGuiRenderFunction(
DockableWindowId::Inspector,
[this]() {
if (_appContext._inspector)
_appContext._inspector->render();
});
_studioLayout.registerGuiRenderFunction(
DockableWindowId::Logs,
[]() { BABYLON::BabylonLogsWindow::instance().render(); });
_studioLayout.registerGuiRenderFunction(
DockableWindowId::Scene3d,
[this]() { render3d(); });
_studioLayout.registerGuiRenderFunction(
DockableWindowId::SamplesCodeViewer,
[this]() { _samplesCodeEditor.render(); });
_studioLayout.registerGuiRenderFunction(
DockableWindowId::SampleBrowser,
[this]() { _appContext._sampleListComponent.render(); });
#ifdef BABYLON_BUILD_PLAYGROUND
_studioLayout.registerGuiRenderFunction(
DockableWindowId::PlaygroundEditor,
[this]() { renderPlayground(); });
#endif
// clang-format on
registered = true;
}
void initScene()
{
_appContext._sampleListComponent.OnNewRenderableScene
= [&](std::shared_ptr<IRenderableScene> scene) {
this->setRenderableScene(scene);
_studioLayout.FocusWindow(DockableWindowId::Scene3d);
};
_appContext._sampleListComponent.OnEditFiles = [&](const std::vector<std::string>& files) {
_samplesCodeEditor.setFiles(files);
_studioLayout.setVisible(DockableWindowId::SamplesCodeViewer, true);
_studioLayout.FocusWindow(DockableWindowId::SamplesCodeViewer);
};
_appContext._sampleListComponent.OnLoopSamples = [&](const std::vector<std::string>& samples) {
_appContext._loopSamples.flagLoop = true;
_appContext._loopSamples.samplesToLoop = samples;
_appContext._loopSamples.currentIdx = 0;
};
_appContext._sceneWidget = std::make_unique<BABYLON::ImGuiSceneWidget>(ImVec2(640.f, 480.f));
_appContext._sceneWidget->OnBeforeResize.push_back(
[this]() { _appContext._inspector.release(); });
}
void prepareSceneInspector()
{
auto currentScene = _appContext._sceneWidget->getScene();
if ((!_appContext._inspector) || (_appContext._inspector->scene() != currentScene)) {
_appContext._inspector
= std::make_unique<BABYLON::Inspector>(nullptr, _appContext._sceneWidget->getScene());
_appContext._inspector->setScene(currentScene);
}
}
// returns true if exit required
bool renderMenu()
{
ImGui::GetCurrentWindow()->Flags = ImGui::GetCurrentWindow()->Flags | ImGuiWindowFlags_MenuBar;
bool shallExit = false;
if (ImGui::BeginMenuBar())
{
if (ImGui::BeginMenu("File"))
{
if (ImGui::MenuItem("Quit"))
shallExit = true;
ImGui::EndMenu();
}
_studioLayout.renderMenu();
renderStatus();
ImGui::EndMenuBar();
}
return shallExit;
}
void renderStatus()
{
ImVec4 statusTextColor{ 0.8f, 0.8f, 0.3f, 1.f };
if (_studioLayout.isVisible(DockableWindowId::Scene3d))
{
ImGui::SameLine(ImGui::GetIO().DisplaySize.x / 2.f);
std::string sceneName = _appContext._sceneWidget->getRenderableScene()->getName();
ImGui::TextColored(statusTextColor, "%s", sceneName.c_str());
}
ImGui::SameLine(ImGui::GetIO().DisplaySize.x - 70.f);
ImGui::TextColored(statusTextColor, "FPS: %.1f", ImGui::GetIO().Framerate);
}
// renders the GUI. Returns true when exit required
bool render()
{
static bool wasInitialLayoutApplied = false;
if (!wasInitialLayoutApplied)
{
this->_studioLayout.ApplyLayoutMode(LayoutMode::SceneAndBrowser);
wasInitialLayoutApplied = true;
}
prepareSceneInspector();
registerRenderFunctions();
bool shallExit = renderMenu();
_studioLayout.renderGui();
handleLoopSamples();
if (_appContext._options._flagScreenshotOneSampleAndExit)
return saveScreenshot();
else
return shallExit;
}
void setRenderableScene(std::shared_ptr<BABYLON::IRenderableScene> scene)
{
if (_appContext._inspector)
_appContext._inspector->setScene(nullptr);
_appContext._sceneWidget->setRenderableScene(scene);
if (_appContext._inspector)
_appContext._inspector->setScene(_appContext._sceneWidget->getScene());
}
// 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;
}
bool ButtonInOverlayWindow(const std::string& label, ImVec2 position, ImVec2 size)
{
ImGui::SetNextWindowPos(position);
ImGui::SetNextWindowSize(size);
ImGuiWindowFlags flags = ImGuiWindowFlags_NoDecoration | ImGuiWindowFlags_NoBackground;
std::string id = label + "##ButtonInOverlayWindow";
ImGui::Begin(label.c_str(), nullptr, flags);
bool clicked = ImGui::Button(label.c_str());
ImGui::End();
return clicked;
}
void renderHud(ImVec2 cursorScene3dTopLeft)
{
auto asSceneWithHud
= dynamic_cast<IRenderableSceneWithHud*>(_appContext._sceneWidget->getRenderableScene());
if (!asSceneWithHud)
return;
if (!asSceneWithHud->hudGui)
return;
static bool showHud = false;
ImVec2 hudButtonPosition(cursorScene3dTopLeft.x + 2.f, cursorScene3dTopLeft.y + 2.f);
ImVec2 hudWindowPosition(cursorScene3dTopLeft.x + 2.f, cursorScene3dTopLeft.y + 30.f);
if (ButtonInOverlayWindow(ICON_FA_COG, hudButtonPosition, ImVec2(30.f, 30.f)))
showHud = !showHud;
if (showHud) {
ImGui::SetNextWindowPos(hudWindowPosition, ImGuiCond_Once);
ImGui::SetNextWindowBgAlpha(0.5f);
ImGuiWindowFlags flags = ImGuiWindowFlags_AlwaysAutoResize;
ImGui::Begin("HUD", &showHud, flags);
asSceneWithHud->hudGui();
ImGui::End();
}
}
void render3d()
{
ImVec2 sceneSize = ImGui::GetCurrentWindow()->Size;
sceneSize.y -= 35.f;
ImVec2 cursorPosBeforeScene3d = ImGui::GetCursorScreenPos();
_appContext._sceneWidget->render(sceneSize);
renderHud(cursorPosBeforeScene3d);
}
void renderPlayground()
{
ImGui::Button(ICON_FA_QUESTION_CIRCLE);
if (ImGui::IsItemHovered())
ImGui::SetTooltip(
"Playground : you can edit the code below! As soon as you save it, the code will be "
"compiled and the 3D scene "
"will be updated");
ImGui::SameLine();
if (_appContext._isCompiling) {
ImGui::TextColored(ImVec4(1., 0., 0., 1.), "Compiling");
_studioLayout.setVisible(DockableWindowId::Logs, true);
}
if (ImGui::Button(ICON_FA_PLAY " Run"))
_playgroundCodeEditor.saveAll();
ImGui::SameLine();
_playgroundCodeEditor.render();
}
private:
void handleLoopSamples()
{
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 = Samples::SamplesIndex::Instance().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++;
}
//
// BabylonStudioContext
//
struct AppContext {
std::unique_ptr<BABYLON::ImGuiSceneWidget> _sceneWidget;
std::unique_ptr<BABYLON::Inspector> _inspector;
BABYLON::SamplesBrowser _sampleListComponent;
int _frameCounter = 0;
BabylonStudioOptions _options;
bool _isCompiling = false;
struct {
bool flagLoop = false;
size_t currentIdx = 0;
std::vector<std::string> samplesToLoop;
} _loopSamples;
};
AppContext _appContext;
BabylonStudioLayout _studioLayout;
ImGuiUtils::CodeEditor _samplesCodeEditor
= ImGuiUtils::CodeEditor(true); // true <-> showCheckboxReadOnly
ImGuiUtils::CodeEditor _playgroundCodeEditor;
}; // end of class BabylonInspectorApp
// public API
void runBabylonStudio(std::shared_ptr<BABYLON::IRenderableScene> scene,
BabylonStudioOptions options /* = SceneWithInspectorOptions() */
)
{
BABYLON::BabylonStudioApp app;
app.RunApp(scene, options);
}
} // namespace BABYLON
<commit_msg>Repair screenshot feature; readPixel works best with images width divisble by 4<commit_after>#include <babylon/GL/framebuffer_canvas.h>
#include <babylon/babylon_imgui/babylon_logs_window.h>
#include <babylon/babylon_imgui/babylon_studio.h>
#include <babylon/core/filesystem.h>
#include <babylon/core/system.h>
#include <babylon/inspector/components/actiontabs/action_tabs_component.h>
#include <babylon/interfaces/irenderable_scene_with_hud.h>
#include <imgui.h>
#include <imgui_internal.h>
#include <imgui_utils/app_runner/imgui_runner.h>
#include <imgui_utils/icons_font_awesome_5.h>
#include <babylon/babylon_imgui/babylon_studio_layout.h>
#include <babylon/core/logging.h>
#include <babylon/samples/samples_index.h>
#ifdef _WIN32
#include <windows.h>
#endif
#include <iostream>
namespace BABYLON {
class BabylonStudioApp {
public:
BabylonStudioApp()
{
std::string exePath = BABYLON::System::getExecutablePath();
std::string exeFolder = BABYLON::Filesystem::baseDir(exePath);
std::string playgroundPath = exeFolder + "/../../../src/BabylonStudio/playground.cpp";
playgroundPath = BABYLON::Filesystem::absolutePath(playgroundPath);
_playgroundCodeEditor.setFiles({playgroundPath});
_playgroundCodeEditor.setLightPalette();
}
void RunApp(std::shared_ptr<BABYLON::IRenderableScene> initialScene,
const BabylonStudioOptions& options)
{
_appContext._options = options;
_appContext._options._appWindowParams.ShowMenuBar = true;
std::function<bool(void)> showGuiLambda = [this]() -> bool {
bool r = this->render();
for (auto f : _appContext._options._heartbeatCallbacks)
f();
if (_appContext._options._playgroundCompilerCallback) {
PlaygroundCompilerStatus playgroundCompilerStatus
= _appContext._options._playgroundCompilerCallback();
if (playgroundCompilerStatus._renderableScene)
setRenderableScene(playgroundCompilerStatus._renderableScene);
_appContext._isCompiling = playgroundCompilerStatus._isCompiling;
}
return r;
};
auto initSceneLambda = [&]() {
this->initScene();
this->setRenderableScene(initialScene);
};
_appContext._options._appWindowParams.InitialDockLayoutFunction = [this](ImGuiID mainDockId) {
_studioLayout.PrepareLayout(mainDockId);
};
ImGuiUtils::ImGuiRunner::RunGui(showGuiLambda, _appContext._options._appWindowParams,
initSceneLambda);
}
private:
void registerRenderFunctions()
{
static bool registered = false;
if (registered)
return;
// clang-format off
_studioLayout.registerGuiRenderFunction(
DockableWindowId::Inspector,
[this]() {
if (_appContext._inspector)
_appContext._inspector->render();
});
_studioLayout.registerGuiRenderFunction(
DockableWindowId::Logs,
[]() { BABYLON::BabylonLogsWindow::instance().render(); });
_studioLayout.registerGuiRenderFunction(
DockableWindowId::Scene3d,
[this]() { render3d(); });
_studioLayout.registerGuiRenderFunction(
DockableWindowId::SamplesCodeViewer,
[this]() { _samplesCodeEditor.render(); });
_studioLayout.registerGuiRenderFunction(
DockableWindowId::SampleBrowser,
[this]() { _appContext._sampleListComponent.render(); });
#ifdef BABYLON_BUILD_PLAYGROUND
_studioLayout.registerGuiRenderFunction(
DockableWindowId::PlaygroundEditor,
[this]() { renderPlayground(); });
#endif
// clang-format on
registered = true;
}
void initScene()
{
_appContext._sampleListComponent.OnNewRenderableScene
= [&](std::shared_ptr<IRenderableScene> scene) {
this->setRenderableScene(scene);
_studioLayout.FocusWindow(DockableWindowId::Scene3d);
};
_appContext._sampleListComponent.OnEditFiles = [&](const std::vector<std::string>& files) {
_samplesCodeEditor.setFiles(files);
_studioLayout.setVisible(DockableWindowId::SamplesCodeViewer, true);
_studioLayout.FocusWindow(DockableWindowId::SamplesCodeViewer);
};
_appContext._sampleListComponent.OnLoopSamples = [&](const std::vector<std::string>& samples) {
_appContext._loopSamples.flagLoop = true;
_appContext._loopSamples.samplesToLoop = samples;
_appContext._loopSamples.currentIdx = 0;
};
_appContext._sceneWidget = std::make_unique<BABYLON::ImGuiSceneWidget>(ImVec2(640.f, 480.f));
_appContext._sceneWidget->OnBeforeResize.push_back(
[this]() { _appContext._inspector.release(); });
}
void prepareSceneInspector()
{
auto currentScene = _appContext._sceneWidget->getScene();
if ((!_appContext._inspector) || (_appContext._inspector->scene() != currentScene)) {
_appContext._inspector
= std::make_unique<BABYLON::Inspector>(nullptr, _appContext._sceneWidget->getScene());
_appContext._inspector->setScene(currentScene);
}
}
// returns true if exit required
bool renderMenu()
{
ImGui::GetCurrentWindow()->Flags = ImGui::GetCurrentWindow()->Flags | ImGuiWindowFlags_MenuBar;
bool shallExit = false;
if (ImGui::BeginMenuBar())
{
if (ImGui::BeginMenu("File"))
{
if (ImGui::MenuItem("Quit"))
shallExit = true;
ImGui::EndMenu();
}
_studioLayout.renderMenu();
renderStatus();
ImGui::EndMenuBar();
}
return shallExit;
}
void renderStatus()
{
ImVec4 statusTextColor{ 0.8f, 0.8f, 0.3f, 1.f };
if (_studioLayout.isVisible(DockableWindowId::Scene3d))
{
ImGui::SameLine(ImGui::GetIO().DisplaySize.x / 2.f);
std::string sceneName = _appContext._sceneWidget->getRenderableScene()->getName();
ImGui::TextColored(statusTextColor, "%s", sceneName.c_str());
}
ImGui::SameLine(ImGui::GetIO().DisplaySize.x - 70.f);
ImGui::TextColored(statusTextColor, "FPS: %.1f", ImGui::GetIO().Framerate);
}
// renders the GUI. Returns true when exit required
bool render()
{
static bool wasInitialLayoutApplied = false;
if (!wasInitialLayoutApplied)
{
this->_studioLayout.ApplyLayoutMode(LayoutMode::SceneAndBrowser);
wasInitialLayoutApplied = true;
}
prepareSceneInspector();
registerRenderFunctions();
bool shallExit = renderMenu();
_studioLayout.renderGui();
handleLoopSamples();
if (_appContext._options._flagScreenshotOneSampleAndExit)
return saveScreenshot();
else
return shallExit;
}
void setRenderableScene(std::shared_ptr<BABYLON::IRenderableScene> scene)
{
if (_appContext._inspector)
_appContext._inspector->setScene(nullptr);
_appContext._sceneWidget->setRenderableScene(scene);
if (_appContext._inspector)
_appContext._inspector->setScene(_appContext._sceneWidget->getScene());
}
// Saves a screenshot after few frames (returns 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;
}
bool ButtonInOverlayWindow(const std::string& label, ImVec2 position, ImVec2 size)
{
ImGui::SetNextWindowPos(position);
ImGui::SetNextWindowSize(size);
ImGuiWindowFlags flags = ImGuiWindowFlags_NoDecoration | ImGuiWindowFlags_NoBackground;
std::string id = label + "##ButtonInOverlayWindow";
ImGui::Begin(label.c_str(), nullptr, flags);
bool clicked = ImGui::Button(label.c_str());
ImGui::End();
return clicked;
}
void renderHud(ImVec2 cursorScene3dTopLeft)
{
auto asSceneWithHud
= dynamic_cast<IRenderableSceneWithHud*>(_appContext._sceneWidget->getRenderableScene());
if (!asSceneWithHud)
return;
if (!asSceneWithHud->hudGui)
return;
static bool showHud = false;
ImVec2 hudButtonPosition(cursorScene3dTopLeft.x + 2.f, cursorScene3dTopLeft.y + 2.f);
ImVec2 hudWindowPosition(cursorScene3dTopLeft.x + 2.f, cursorScene3dTopLeft.y + 30.f);
if (ButtonInOverlayWindow(ICON_FA_COG, hudButtonPosition, ImVec2(30.f, 30.f)))
showHud = !showHud;
if (showHud) {
ImGui::SetNextWindowPos(hudWindowPosition, ImGuiCond_Once);
ImGui::SetNextWindowBgAlpha(0.5f);
ImGuiWindowFlags flags = ImGuiWindowFlags_AlwaysAutoResize;
ImGui::Begin("HUD", &showHud, flags);
asSceneWithHud->hudGui();
ImGui::End();
}
}
void render3d()
{
ImVec2 sceneSize = ImGui::GetCurrentWindow()->Size;
sceneSize.y -= 35.f;
sceneSize.x = (float)((int)((sceneSize.x) / 4) * 4);
ImVec2 cursorPosBeforeScene3d = ImGui::GetCursorScreenPos();
_appContext._sceneWidget->render(sceneSize);
renderHud(cursorPosBeforeScene3d);
}
void renderPlayground()
{
ImGui::Button(ICON_FA_QUESTION_CIRCLE);
if (ImGui::IsItemHovered())
ImGui::SetTooltip(
"Playground : you can edit the code below! As soon as you save it, the code will be "
"compiled and the 3D scene "
"will be updated");
ImGui::SameLine();
if (_appContext._isCompiling) {
ImGui::TextColored(ImVec4(1., 0., 0., 1.), "Compiling");
_studioLayout.setVisible(DockableWindowId::Logs, true);
}
if (ImGui::Button(ICON_FA_PLAY " Run"))
_playgroundCodeEditor.saveAll();
ImGui::SameLine();
_playgroundCodeEditor.render();
}
private:
void handleLoopSamples()
{
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 = Samples::SamplesIndex::Instance().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++;
}
//
// BabylonStudioContext
//
struct AppContext {
std::unique_ptr<BABYLON::ImGuiSceneWidget> _sceneWidget;
std::unique_ptr<BABYLON::Inspector> _inspector;
BABYLON::SamplesBrowser _sampleListComponent;
int _frameCounter = 0;
BabylonStudioOptions _options;
bool _isCompiling = false;
struct {
bool flagLoop = false;
size_t currentIdx = 0;
std::vector<std::string> samplesToLoop;
} _loopSamples;
};
AppContext _appContext;
BabylonStudioLayout _studioLayout;
ImGuiUtils::CodeEditor _samplesCodeEditor
= ImGuiUtils::CodeEditor(true); // true <-> showCheckboxReadOnly
ImGuiUtils::CodeEditor _playgroundCodeEditor;
}; // end of class BabylonInspectorApp
// public API
void runBabylonStudio(std::shared_ptr<BABYLON::IRenderableScene> scene,
BabylonStudioOptions options /* = SceneWithInspectorOptions() */
)
{
BABYLON::BabylonStudioApp app;
app.RunApp(scene, options);
}
} // namespace BABYLON
<|endoftext|> |
<commit_before>/**
* @file NaoController.cpp
*
* @author <a href="mailto:[email protected]">Xu, Yuan</a>
* @author <a href="mailto:[email protected]">Mellmann, Heinrich</a>
* @breief Interface for the real robot for both cognition and motion
*
*/
#include "NaoController.h"
#include <algorithm>
using namespace std;
using namespace naoth;
NaoController::NaoController()
:
PlatformInterface("Nao", 10),
theSoundHandler(NULL),
theBroadCaster(NULL),
theBroadCastListener(NULL),
theDebugServer(NULL),
theRCTCBroadCaster(NULL),
theRCTCBroadCastListener(NULL)
{
// init shared memory
// sensor data
const std::string naoSensorDataPath = "/nao_sensor_data";
// command data
const std::string naoCommandMotorJointDataPath = "/nao_command.MotorJointData";
const std::string naoCommandUltraSoundSendDataPath = "/nao_command.UltraSoundSendData";
const std::string naoCommandIRSendDataPath = "/nao_command.IRSendData";
const std::string naoCommandLEDDataPath = "/nao_command.LEDData";
naoSensorData.open(naoSensorDataPath);
naoCommandMotorJointData.open(naoCommandMotorJointDataPath);
naoCommandUltraSoundSendData.open(naoCommandUltraSoundSendDataPath);
naoCommandIRSendData.open(naoCommandIRSendDataPath);
naoCommandLEDData.open(naoCommandLEDDataPath);
// end init shared memory
// read the theBodyID and the theBodyNickName from file "nao.info"
const std::string naoInfoPath = Platform::getInstance().theConfigDirectory + "nao.info";
ifstream is(naoInfoPath.c_str());
if(!is.good())
{
// exit the program
THROW("is.good() failed. No Configs found. Do you call ../bin/naoth from ~/naoqi?");
}
else
{
is >> theBodyID >> theBodyNickName;
cout << "bodyID: " << theBodyID << endl;
cout << "bodyNickName: " << theBodyNickName << endl;
}
// read the mac address of the LAN adaptor
ifstream isEthMac("/sys/class/net/eth0/address");
isEthMac >> theHeadNickName;
std::replace(theHeadNickName.begin(), theHeadNickName.end(), ':', '_');
cout << "headNickName: " << theHeadNickName << endl;
/* REGISTER IO */
// camera
registerInput<Image>(*this);
registerInput<Image2>(*this);
registerInput<CurrentCameraSettings>(*this);
registerInput<CurrentCameraSettings2>(*this);
registerOutput<const CameraSettingsRequest>(*this);
registerOutput<const CameraSettingsRequest2>(*this);
// sound
registerOutput<const SoundPlayData>(*this);
// gamecontroller
registerInput<GameData>(*this);
registerOutput<const GameReturnData>(*this);
// teamcomm
registerInput<TeamMessageDataIn>(*this);
registerOutput<const TeamMessageDataOut>(*this);
// rctc teamcomm
registerInput<RCTCTeamMessageDataIn>(*this);
registerOutput<const RCTCTeamMessageDataOut>(*this);
// debug comm
registerInput<DebugMessageIn>(*this);
registerOutput<const DebugMessageOut>(*this);
// time
registerInput<FrameInfo>(*this);
// register sensor input
registerInput<AccelerometerData>(*this);
registerInput<SensorJointData>(*this);
registerInput<FSRData>(*this);
registerInput<GyrometerData>(*this);
registerInput<InertialSensorData>(*this);
registerInput<IRReceiveData>(*this);
registerInput<ButtonData>(*this);
registerInput<BatteryData>(*this);
registerInput<UltraSoundReceiveData>(*this);
// register command output
registerOutput<const MotorJointData>(*this);
registerOutput<const LEDData>(*this);
registerOutput<const IRSendData>(*this);
registerOutput<const UltraSoundSendData>(*this);
/* INIT DEVICES */
std::cout << "Init Platform" << endl;
Platform::getInstance().init(this);
std::cout << "Init SoundHandler" <<endl;
//theSoundPlayer.play("penalized");
theSoundHandler = new SoundControl();
// create the teamcomm
std::cout << "Init TeamComm" << endl;
naoth::Configuration& config = naoth::Platform::getInstance().theConfiguration;
string interfaceName = "wlan0";
if(config.hasKey("teamcomm", "interface"))
{
interfaceName = config.getString("teamcomm", "interface");
}
int teamcomm_port = 10700; // default port
config.get("teamcomm", "port", teamcomm_port);
theBroadCaster = new BroadCaster(interfaceName, teamcomm_port);
theBroadCastListener = new BroadCastListener(teamcomm_port, TEAMCOMM_MAX_MSG_SIZE);
// create RCTC connections
int rctc_port = 22022; // default port
config.get("teamcomm", "rctc_port", rctc_port);
theRCTCBroadCaster = new BroadCaster(interfaceName, rctc_port);
theRCTCBroadCastListener = new BroadCastListener(rctc_port, rctc::PACKET_SIZE);
// start the debug server at the default debug port
std::cout << "Init DebugServer" << endl;
int debug_port = 5401; // default port
config.get("network", "debug_port", debug_port);
theDebugServer = new DebugServer();
theDebugServer->start(debug_port, true);
std::cout<< "Init SPLGameController"<<endl;
theGameController = new SPLGameController();
std::cout << "Init CameraHandler (bottom)" << std::endl;
theBottomCameraHandler.init("/dev/video1", CameraInfo::Bottom, true);
std::cout << "Init CameraHandler (top)" << std::endl;
theTopCameraHandler.init("/dev/video0", CameraInfo::Bottom, false);
}
NaoController::~NaoController()
{
delete theSoundHandler;
delete theBroadCaster;
delete theBroadCastListener;
delete theGameController;
delete theDebugServer;
delete theRCTCBroadCaster;
delete theRCTCBroadCastListener;
}
void NaoController::setCameraSettingsInternal(const CameraSettingsRequest &data,
CameraInfo::CameraID camID)
{
V4lCameraHandler& cameraHandler = camID == CameraInfo::Bottom
? theBottomCameraHandler : theTopCameraHandler;
bool somethingChanged = false;
if(cameraHandler.isRunning())
{
CurrentCameraSettings current;
cameraHandler.getCameraSettings(current, data.queryCameraSettings);
if(data.queryCameraSettings)
{
somethingChanged = false;
}
else
{
for(int i=0; i < CameraSettings::numOfCameraSetting; i++)
{
if(current.data[i] != data.data[i])
{
std::cout << "CameraParameter " <<
CameraSettings::getCameraSettingsName((CameraSettings::CameraSettingID) i)
<< " was requested to change from " << current.data[i]
<< " to " << data.data[i] << std::endl;
somethingChanged = true;
// break;
}
}
}
}
if(somethingChanged)
{
std::cout << "Settting camera settings ("
<< (camID == CameraInfo::Bottom ? "bottom" : "top") << ")" << endl;
cameraHandler.setAllCameraParams(data);
}
}//end set CameraSettingsRequest
void NaoController::set(const CameraSettingsRequest &data)
{
setCameraSettingsInternal(data, CameraInfo::Bottom);
}
void NaoController::set(const CameraSettingsRequest2 &data)
{
// setCameraSettingsInternal(data, CameraInfo::Top);
}
void NaoController::get(RCTCTeamMessageDataIn& data)
{
data.data.clear();
std::vector<std::string> msg_vector;
theRCTCBroadCastListener->receive(msg_vector);
for(unsigned int i = 0; i < msg_vector.size(); i++)
{
const char* bin_msg = msg_vector[i].c_str();
rctc::Message msg;
if(rctc::binaryToMessage((const uint8_t*)bin_msg, msg))
{
data.data.push_back(msg);
}
}
}//end get RCTCTeamMessageDataIn
void NaoController::set(const RCTCTeamMessageDataOut& data)
{
if(data.valid)
{
uint8_t bin_msg[rctc::PACKET_SIZE];
rctc::messageToBinary(data.data, bin_msg);
std::string msg((char*)bin_msg, rctc::PACKET_SIZE);
// std::cout << "sending RCTC " <<theRCTCBroadCaster->broadcastAddress << " (bcast adress) " << std::endl;
theRCTCBroadCaster->send(msg);
}
}//end set RCTCTeamMessageDataOut
<commit_msg>re-activating the second camera<commit_after>/**
* @file NaoController.cpp
*
* @author <a href="mailto:[email protected]">Xu, Yuan</a>
* @author <a href="mailto:[email protected]">Mellmann, Heinrich</a>
* @breief Interface for the real robot for both cognition and motion
*
*/
#include "NaoController.h"
#include <algorithm>
using namespace std;
using namespace naoth;
NaoController::NaoController()
:
PlatformInterface("Nao", 10),
theSoundHandler(NULL),
theBroadCaster(NULL),
theBroadCastListener(NULL),
theDebugServer(NULL),
theRCTCBroadCaster(NULL),
theRCTCBroadCastListener(NULL)
{
// init shared memory
// sensor data
const std::string naoSensorDataPath = "/nao_sensor_data";
// command data
const std::string naoCommandMotorJointDataPath = "/nao_command.MotorJointData";
const std::string naoCommandUltraSoundSendDataPath = "/nao_command.UltraSoundSendData";
const std::string naoCommandIRSendDataPath = "/nao_command.IRSendData";
const std::string naoCommandLEDDataPath = "/nao_command.LEDData";
naoSensorData.open(naoSensorDataPath);
naoCommandMotorJointData.open(naoCommandMotorJointDataPath);
naoCommandUltraSoundSendData.open(naoCommandUltraSoundSendDataPath);
naoCommandIRSendData.open(naoCommandIRSendDataPath);
naoCommandLEDData.open(naoCommandLEDDataPath);
// end init shared memory
// read the theBodyID and the theBodyNickName from file "nao.info"
const std::string naoInfoPath = Platform::getInstance().theConfigDirectory + "nao.info";
ifstream is(naoInfoPath.c_str());
if(!is.good())
{
// exit the program
THROW("is.good() failed. No Configs found. Do you call ../bin/naoth from ~/naoqi?");
}
else
{
is >> theBodyID >> theBodyNickName;
cout << "bodyID: " << theBodyID << endl;
cout << "bodyNickName: " << theBodyNickName << endl;
}
// read the mac address of the LAN adaptor
ifstream isEthMac("/sys/class/net/eth0/address");
isEthMac >> theHeadNickName;
std::replace(theHeadNickName.begin(), theHeadNickName.end(), ':', '_');
cout << "headNickName: " << theHeadNickName << endl;
/* REGISTER IO */
// camera
registerInput<Image>(*this);
registerInput<Image2>(*this);
registerInput<CurrentCameraSettings>(*this);
registerInput<CurrentCameraSettings2>(*this);
registerOutput<const CameraSettingsRequest>(*this);
registerOutput<const CameraSettingsRequest2>(*this);
// sound
registerOutput<const SoundPlayData>(*this);
// gamecontroller
registerInput<GameData>(*this);
registerOutput<const GameReturnData>(*this);
// teamcomm
registerInput<TeamMessageDataIn>(*this);
registerOutput<const TeamMessageDataOut>(*this);
// rctc teamcomm
registerInput<RCTCTeamMessageDataIn>(*this);
registerOutput<const RCTCTeamMessageDataOut>(*this);
// debug comm
registerInput<DebugMessageIn>(*this);
registerOutput<const DebugMessageOut>(*this);
// time
registerInput<FrameInfo>(*this);
// register sensor input
registerInput<AccelerometerData>(*this);
registerInput<SensorJointData>(*this);
registerInput<FSRData>(*this);
registerInput<GyrometerData>(*this);
registerInput<InertialSensorData>(*this);
registerInput<IRReceiveData>(*this);
registerInput<ButtonData>(*this);
registerInput<BatteryData>(*this);
registerInput<UltraSoundReceiveData>(*this);
// register command output
registerOutput<const MotorJointData>(*this);
registerOutput<const LEDData>(*this);
registerOutput<const IRSendData>(*this);
registerOutput<const UltraSoundSendData>(*this);
/* INIT DEVICES */
std::cout << "Init Platform" << endl;
Platform::getInstance().init(this);
std::cout << "Init SoundHandler" <<endl;
//theSoundPlayer.play("penalized");
theSoundHandler = new SoundControl();
// create the teamcomm
std::cout << "Init TeamComm" << endl;
naoth::Configuration& config = naoth::Platform::getInstance().theConfiguration;
string interfaceName = "wlan0";
if(config.hasKey("teamcomm", "interface"))
{
interfaceName = config.getString("teamcomm", "interface");
}
int teamcomm_port = 10700; // default port
config.get("teamcomm", "port", teamcomm_port);
theBroadCaster = new BroadCaster(interfaceName, teamcomm_port);
theBroadCastListener = new BroadCastListener(teamcomm_port, TEAMCOMM_MAX_MSG_SIZE);
// create RCTC connections
int rctc_port = 22022; // default port
config.get("teamcomm", "rctc_port", rctc_port);
theRCTCBroadCaster = new BroadCaster(interfaceName, rctc_port);
theRCTCBroadCastListener = new BroadCastListener(rctc_port, rctc::PACKET_SIZE);
// start the debug server at the default debug port
std::cout << "Init DebugServer" << endl;
int debug_port = 5401; // default port
config.get("network", "debug_port", debug_port);
theDebugServer = new DebugServer();
theDebugServer->start(debug_port, true);
std::cout<< "Init SPLGameController"<<endl;
theGameController = new SPLGameController();
std::cout << "Init CameraHandler (bottom)" << std::endl;
theBottomCameraHandler.init("/dev/video1", CameraInfo::Bottom, true);
std::cout << "Init CameraHandler (top)" << std::endl;
theTopCameraHandler.init("/dev/video0", CameraInfo::Bottom, false);
}
NaoController::~NaoController()
{
delete theSoundHandler;
delete theBroadCaster;
delete theBroadCastListener;
delete theGameController;
delete theDebugServer;
delete theRCTCBroadCaster;
delete theRCTCBroadCastListener;
}
void NaoController::setCameraSettingsInternal(const CameraSettingsRequest &data,
CameraInfo::CameraID camID)
{
V4lCameraHandler& cameraHandler = camID == CameraInfo::Bottom
? theBottomCameraHandler : theTopCameraHandler;
bool somethingChanged = false;
if(cameraHandler.isRunning())
{
CurrentCameraSettings current;
cameraHandler.getCameraSettings(current, data.queryCameraSettings);
if(data.queryCameraSettings)
{
somethingChanged = false;
}
else
{
for(int i=0; i < CameraSettings::numOfCameraSetting; i++)
{
if(current.data[i] != data.data[i])
{
std::cout << "CameraParameter " <<
CameraSettings::getCameraSettingsName((CameraSettings::CameraSettingID) i)
<< " was requested to change from " << current.data[i]
<< " to " << data.data[i] << std::endl;
somethingChanged = true;
// break;
}
}
}
}
if(somethingChanged)
{
std::cout << "Settting camera settings ("
<< (camID == CameraInfo::Bottom ? "bottom" : "top") << ")" << endl;
cameraHandler.setAllCameraParams(data);
}
}//end set CameraSettingsRequest
void NaoController::set(const CameraSettingsRequest &data)
{
setCameraSettingsInternal(data, CameraInfo::Bottom);
}
void NaoController::set(const CameraSettingsRequest2 &data)
{
setCameraSettingsInternal(data, CameraInfo::Top);
}
void NaoController::get(RCTCTeamMessageDataIn& data)
{
data.data.clear();
std::vector<std::string> msg_vector;
theRCTCBroadCastListener->receive(msg_vector);
for(unsigned int i = 0; i < msg_vector.size(); i++)
{
const char* bin_msg = msg_vector[i].c_str();
rctc::Message msg;
if(rctc::binaryToMessage((const uint8_t*)bin_msg, msg))
{
data.data.push_back(msg);
}
}
}//end get RCTCTeamMessageDataIn
void NaoController::set(const RCTCTeamMessageDataOut& data)
{
if(data.valid)
{
uint8_t bin_msg[rctc::PACKET_SIZE];
rctc::messageToBinary(data.data, bin_msg);
std::string msg((char*)bin_msg, rctc::PACKET_SIZE);
// std::cout << "sending RCTC " <<theRCTCBroadCaster->broadcastAddress << " (bcast adress) " << std::endl;
theRCTCBroadCaster->send(msg);
}
}//end set RCTCTeamMessageDataOut
<|endoftext|> |
<commit_before>#include <MicroBit.h>
#include "CalliopeDemo.h"
extern MicroBit uBit;
void onButtonA(MicroBitEvent event) {
(void) event;
uBit.display.print("A");
}
void onButtonB(MicroBitEvent event) {
(void) event;
uBit.display.print("B");
}
void onButtonAB(MicroBitEvent event) {
(void) event;
uBit.display.print("A+B");
}
void onButton0(MicroBitEvent event) {
(void) event;
uBit.display.print("0");
}
void onButton1(MicroBitEvent event) {
(void) event;
uBit.display.print("1");
}
void onButton2(MicroBitEvent event) {
(void) event;
uBit.display.print("2");
}
void onButton3(MicroBitEvent event) {
(void) event;
uBit.display.print("3");
}
void onShake(MicroBitEvent event) {
(void) event;
uBit.display.print("S");
}
void onFaceUp(MicroBitEvent event) {
(void) event;
uBit.display.print("+");
}
void onFaceDown(MicroBitEvent event) {
(void) event;
uBit.display.print("-");
}
void onTiltUp(MicroBitEvent event) {
(void) event;
uBit.display.print("U");
}
void onTiltDown(MicroBitEvent event) {
(void) event;
uBit.display.print("D");
}
void onTiltLeft(MicroBitEvent event) {
(void) event;
uBit.display.print("L");
}
void onTiltRight(MicroBitEvent event) {
(void) event;
uBit.display.print("R");
}
void testBoard() {
KeyValuePair *firstTime = uBit.storage.get("initial");
if (firstTime != NULL) return;
uint8_t done = 1;
uBit.storage.put("initial", &done, sizeof(int));
uBit.serial.send("display\r\n");
uBit.display.clear();
uBit.display.print(Full);
for (int i = 255; i > 0; i -= 2) {
uBit.display.setBrightness(i);
uBit.sleep(3);
}
uBit.sleep(3);
for (int i = 0; i < 255; i += 2) {
uBit.display.setBrightness(i);
uBit.sleep(3);
}
uBit.serial.send("accelerometer\r\n");
for (int i = 0; i < 10; i++) {
uBit.accelerometer.getX();
uBit.accelerometer.getY();
uBit.accelerometer.getZ();
}
uBit.display.print(Tick);
uBit.sleep(80);
uBit.serial.send("RGB led\r\n");
uBit.rgb.off();
uBit.rgb.setColour(255, 0, 0, 0);
uBit.sleep(200);
uBit.rgb.off();
uBit.rgb.setColour(0, 255, 0, 0);
uBit.sleep(200);
uBit.rgb.off();
uBit.rgb.setColour(0, 0, 255, 0);
uBit.sleep(200);
uBit.rgb.off();
uBit.serial.send("sound\r\n");
uBit.soundmotor.setSoundSilentMode(true);
uBit.soundmotor.soundOn(500);
uBit.sleep(100);
uBit.soundmotor.soundOn(2000);
uBit.sleep(100);
uBit.soundmotor.soundOn(3000);
uBit.sleep(100);
uBit.soundmotor.soundOff();
uBit.display.clear();
// we need to trigger touch sensing
uBit.io.P12.isTouched();
uBit.io.P0.isTouched();
uBit.io.P1.isTouched();
uBit.io.P16.isTouched();
uBit.messageBus.listen(MICROBIT_ID_BUTTON_A, MICROBIT_BUTTON_EVT_CLICK, onButtonA);
uBit.messageBus.listen(MICROBIT_ID_BUTTON_B, MICROBIT_BUTTON_EVT_CLICK, onButtonB);
uBit.messageBus.listen(MICROBIT_ID_BUTTON_AB, MICROBIT_BUTTON_EVT_CLICK, onButtonAB);
uBit.messageBus.listen(MICROBIT_ID_IO_P12, MICROBIT_EVT_ANY, onButton0);
uBit.messageBus.listen(MICROBIT_ID_IO_P0, MICROBIT_EVT_ANY, onButton1);
uBit.messageBus.listen(MICROBIT_ID_IO_P1, MICROBIT_EVT_ANY, onButton2);
uBit.messageBus.listen(MICROBIT_ID_IO_P16, MICROBIT_EVT_ANY, onButton3);
uBit.messageBus.listen(MICROBIT_ID_GESTURE, MICROBIT_ACCELEROMETER_EVT_SHAKE, onShake);
uBit.messageBus.listen(MICROBIT_ID_GESTURE, MICROBIT_ACCELEROMETER_EVT_FACE_UP, onFaceUp);
uBit.messageBus.listen(MICROBIT_ID_GESTURE, MICROBIT_ACCELEROMETER_EVT_FACE_DOWN, onFaceDown);
uBit.messageBus.listen(MICROBIT_ID_GESTURE, MICROBIT_ACCELEROMETER_EVT_TILT_UP, onTiltUp);
uBit.messageBus.listen(MICROBIT_ID_GESTURE, MICROBIT_ACCELEROMETER_EVT_TILT_DOWN, onTiltDown);
uBit.messageBus.listen(MICROBIT_ID_GESTURE, MICROBIT_ACCELEROMETER_EVT_TILT_LEFT, onTiltLeft);
uBit.messageBus.listen(MICROBIT_ID_GESTURE, MICROBIT_ACCELEROMETER_EVT_TILT_RIGHT, onTiltRight);
while (1) uBit.sleep(100);
}<commit_msg>change board test according to tester feedback<commit_after>#include <MicroBit.h>
#include "CalliopeDemo.h"
extern MicroBit uBit;
void onButtonA(MicroBitEvent event) {
(void) event;
uBit.display.print("A");
}
void onButtonB(MicroBitEvent event) {
(void) event;
uBit.display.print("B");
}
void onButtonAB(MicroBitEvent event) {
(void) event;
uBit.display.print("A+B");
}
void onButton0(MicroBitEvent event) {
(void) event;
uBit.display.print("0");
}
void onButton1(MicroBitEvent event) {
(void) event;
uBit.display.print("1");
}
void onButton2(MicroBitEvent event) {
(void) event;
uBit.display.print("2");
}
void onButton3(MicroBitEvent event) {
(void) event;
uBit.display.print("3");
}
void onShake(MicroBitEvent event) {
(void) event;
uBit.display.print("S");
}
void onFaceUp(MicroBitEvent event) {
(void) event;
uBit.display.print("+");
}
void onFaceDown(MicroBitEvent event) {
(void) event;
uBit.display.print("-");
}
void onTiltUp(MicroBitEvent event) {
(void) event;
uBit.display.print("U");
}
void onTiltDown(MicroBitEvent event) {
(void) event;
uBit.display.print("D");
}
void onTiltLeft(MicroBitEvent event) {
(void) event;
uBit.display.print("L");
}
void onTiltRight(MicroBitEvent event) {
(void) event;
uBit.display.print("R");
}
void testBoard() {
KeyValuePair *firstTime = uBit.storage.get("initial");
if (firstTime != NULL) return;
uint8_t done = 1;
uBit.storage.put("initial", &done, sizeof(int));
uBit.serial.send("sound\r\n");
uBit.soundmotor.setSoundSilentMode(true);
uBit.soundmotor.soundOn(500);
uBit.sleep(100);
uBit.soundmotor.soundOn(2000);
uBit.sleep(100);
uBit.soundmotor.soundOn(3000);
uBit.sleep(100);
uBit.soundmotor.soundOff();
uBit.sleep(500);
uBit.serial.send("display\r\n");
uBit.display.clear();
uBit.display.print(Full);
for (int i = 255; i > 0; i -= 2) {
uBit.display.setBrightness(i);
uBit.sleep(3);
}
uBit.sleep(3);
for (int i = 0; i < 255; i += 2) {
uBit.display.setBrightness(i);
uBit.sleep(3);
}
uBit.serial.send("RGB led\r\n");
uBit.rgb.off();
uBit.rgb.setColour(255, 0, 0, 0);
uBit.sleep(200);
uBit.rgb.off();
uBit.rgb.setColour(0, 255, 0, 0);
uBit.sleep(200);
uBit.rgb.off();
uBit.rgb.setColour(0, 0, 255, 0);
uBit.sleep(200);
uBit.rgb.off();
uBit.serial.send("accelerometer\r\n");
for (int i = 0; i < 10; i++) {
uBit.accelerometer.getX();
uBit.accelerometer.getY();
uBit.accelerometer.getZ();
}
uBit.display.print(Tick);
// we need to trigger touch sensing
uBit.io.P12.isTouched();
uBit.io.P0.isTouched();
uBit.io.P1.isTouched();
uBit.io.P16.isTouched();
uBit.messageBus.listen(MICROBIT_ID_BUTTON_A, MICROBIT_BUTTON_EVT_CLICK, onButtonA);
uBit.messageBus.listen(MICROBIT_ID_BUTTON_B, MICROBIT_BUTTON_EVT_CLICK, onButtonB);
uBit.messageBus.listen(MICROBIT_ID_BUTTON_AB, MICROBIT_BUTTON_EVT_CLICK, onButtonAB);
uBit.messageBus.listen(MICROBIT_ID_IO_P12, MICROBIT_EVT_ANY, onButton0);
uBit.messageBus.listen(MICROBIT_ID_IO_P0, MICROBIT_EVT_ANY, onButton1);
uBit.messageBus.listen(MICROBIT_ID_IO_P1, MICROBIT_EVT_ANY, onButton2);
uBit.messageBus.listen(MICROBIT_ID_IO_P16, MICROBIT_EVT_ANY, onButton3);
uBit.messageBus.listen(MICROBIT_ID_GESTURE, MICROBIT_ACCELEROMETER_EVT_SHAKE, onShake);
uBit.messageBus.listen(MICROBIT_ID_GESTURE, MICROBIT_ACCELEROMETER_EVT_FACE_UP, onFaceUp);
uBit.messageBus.listen(MICROBIT_ID_GESTURE, MICROBIT_ACCELEROMETER_EVT_FACE_DOWN, onFaceDown);
uBit.messageBus.listen(MICROBIT_ID_GESTURE, MICROBIT_ACCELEROMETER_EVT_TILT_UP, onTiltUp);
uBit.messageBus.listen(MICROBIT_ID_GESTURE, MICROBIT_ACCELEROMETER_EVT_TILT_DOWN, onTiltDown);
uBit.messageBus.listen(MICROBIT_ID_GESTURE, MICROBIT_ACCELEROMETER_EVT_TILT_LEFT, onTiltLeft);
uBit.messageBus.listen(MICROBIT_ID_GESTURE, MICROBIT_ACCELEROMETER_EVT_TILT_RIGHT, onTiltRight);
while (1) uBit.sleep(100);
}<|endoftext|> |
<commit_before>/*
* Copyright (c) 2015, Ford Motor Company
* 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 Ford Motor Company 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.
*/
#include <errno.h>
#include <limits.h>
#include <stddef.h>
#include <signal.h>
#ifdef BUILD_TESTS
// Temporary fix for UnitTest until APPLINK-9987 is resolved
#include <unistd.h>
#endif
#include "utils/threads/thread.h"
#include "pthread.h"
#include "utils/atomic.h"
#include "utils/threads/thread_delegate.h"
#include "utils/logger.h"
#ifndef __QNXNTO__
const int EOK = 0;
#endif
#if defined(OS_POSIX)
const size_t THREAD_NAME_SIZE = 15;
#endif
namespace threads {
CREATE_LOGGERPTR_GLOBAL(logger_, "Utils")
size_t Thread::kMinStackSize = PTHREAD_STACK_MIN; /* Ubuntu : 16384 ; QNX : 256; */
void Thread::cleanup(void* arg) {
LOG4CXX_AUTO_TRACE(logger_);
Thread* thread = reinterpret_cast<Thread*>(arg);
sync_primitives::AutoLock auto_lock(thread->state_lock_);
thread->isThreadRunning_ = false;
thread->state_cond_.Broadcast();
}
void* Thread::threadFunc(void* arg) {
// 0 - state_lock unlocked
// stopped = 0
// running = 0
// finalized = 0
// 4 - state_lock unlocked
// stopped = 1
// running = 1
// finalized = 0
// 5 - state_lock unlocked
// stopped = 1
// running = 1
// finalized = 1
pthread_setcancelstate(PTHREAD_CANCEL_DISABLE, NULL);
LOG4CXX_DEBUG(logger_,
"Thread #" << pthread_self() << " started successfully");
threads::Thread* thread = reinterpret_cast<Thread*>(arg);
DCHECK(thread);
pthread_cleanup_push(&cleanup, thread);
thread->state_lock_.Acquire();
thread->state_cond_.Broadcast();
while (!thread->finalized_) {
LOG4CXX_DEBUG(logger_, "Thread #" << pthread_self() << " iteration");
thread->run_cond_.Wait(thread->state_lock_);
LOG4CXX_DEBUG(
logger_,
"Thread #" << pthread_self() << " execute. " << "stopped_ = " << thread->stopped_ << "; finalized_ = " << thread->finalized_);
if (!thread->stopped_ && !thread->finalized_) {
thread->isThreadRunning_ = true;
pthread_setcancelstate(PTHREAD_CANCEL_ENABLE, NULL);
pthread_testcancel();
thread->state_lock_.Release();
thread->delegate_->threadMain();
thread->state_lock_.Acquire();
pthread_setcancelstate(PTHREAD_CANCEL_DISABLE, NULL);
thread->isThreadRunning_ = false;
}
thread->state_cond_.Broadcast();
LOG4CXX_DEBUG(logger_,
"Thread #" << pthread_self() << " finished iteration");
}
thread->state_lock_.Release();
pthread_cleanup_pop(1);
LOG4CXX_DEBUG(logger_,
"Thread #" << pthread_self() << " exited successfully");
return NULL;
}
void Thread::SetNameForId(const PlatformThreadHandle& thread_id,
std::string name) {
if (name.size() > THREAD_NAME_SIZE)
name.erase(THREAD_NAME_SIZE);
const int rc = pthread_setname_np(thread_id, name.c_str());
if (rc != EOK) {
LOG4CXX_WARN(
logger_,
"Couldn't set pthread name \"" << name << "\", error code " << rc << " (" << strerror(rc) << ")");
}
}
Thread::Thread(const char* name, ThreadDelegate* delegate)
: name_(name ? name : "undefined"),
delegate_(delegate),
handle_(0),
thread_options_(),
isThreadRunning_(0),
stopped_(false),
finalized_(false),
thread_created_(false) {
}
bool Thread::start() {
return start(thread_options_);
}
PlatformThreadHandle Thread::CurrentId() {
return pthread_self();
}
bool Thread::start(const ThreadOptions& options) {
LOG4CXX_AUTO_TRACE(logger_);
sync_primitives::AutoLock auto_lock(state_lock_);
// 1 - state_lock locked
// stopped = 0
// running = 0
if (!delegate_) {
LOG4CXX_ERROR(logger_,
"Cannot start thread " << name_ << ": delegate is NULL");
// 0 - state_lock unlocked
return false;
}
if (isThreadRunning_) {
LOG4CXX_TRACE(
logger_,
"EXIT thread "<< name_ << " #" << handle_ << " is already running");
return true;
}
thread_options_ = options;
pthread_attr_t attributes;
int pthread_result = pthread_attr_init(&attributes);
if (pthread_result != EOK) {
LOG4CXX_WARN(
logger_,
"Couldn't init pthread attributes. Error code = " << pthread_result << " (\"" << strerror(pthread_result) << "\")");
}
if (!thread_options_.is_joinable()) {
pthread_result = pthread_attr_setdetachstate(&attributes, PTHREAD_CREATE_DETACHED);
if (pthread_result != EOK) {
LOG4CXX_WARN(
logger_,
"Couldn't set detach state attribute. Error code = " << pthread_result << " (\"" << strerror(pthread_result) << "\")");
thread_options_.is_joinable(false);
}
}
const size_t stack_size = thread_options_.stack_size();
if (stack_size >= Thread::kMinStackSize) {
pthread_result = pthread_attr_setstacksize(&attributes, stack_size);
if (pthread_result != EOK) {
LOG4CXX_WARN(
logger_,
"Couldn't set stacksize = " << stack_size << ". Error code = " << pthread_result << " (\"" << strerror(pthread_result) << "\")");
}
}
else {
ThreadOptions thread_options_temp(Thread::kMinStackSize, thread_options_.is_joinable());
thread_options_ = thread_options_temp;
}
if (!thread_created_) {
// state_lock 1
pthread_result = pthread_create(&handle_, &attributes, threadFunc, this);
if (pthread_result == EOK) {
LOG4CXX_DEBUG(logger_, "Created thread: " << name_);
SetNameForId(handle_, name_);
// state_lock 0
// possible concurrencies: stop and threadFunc
state_cond_.Wait(auto_lock);
thread_created_ = true;
} else {
LOG4CXX_ERROR(
logger_,
"Couldn't create thread " << name_ << ". Error code = " << pthread_result << " (\"" << strerror(pthread_result) << "\")");
}
}
stopped_ = false;
run_cond_.NotifyOne();
LOG4CXX_DEBUG(
logger_,
"Thread " << name_ << " #" << handle_ << " started. pthread_result = " << pthread_result);
pthread_attr_destroy(&attributes);
return pthread_result == EOK;
}
void Thread::stop() {
LOG4CXX_AUTO_TRACE(logger_);
sync_primitives::AutoLock auto_lock(state_lock_);
stopped_ = true;
LOG4CXX_DEBUG(logger_, "Stopping thread #" << handle_
<< " \"" << name_ << " \"");
if (delegate_ && isThreadRunning_) {
delegate_->exitThreadMain();
}
LOG4CXX_DEBUG(logger_,
"Stopped thread #" << handle_ << " \"" << name_ << " \"");
}
void Thread::join() {
LOG4CXX_AUTO_TRACE(logger_);
DCHECK(!pthread_equal(pthread_self(), handle_));
stop();
sync_primitives::AutoLock auto_lock(state_lock_);
run_cond_.NotifyOne();
if (isThreadRunning_) {
if (!pthread_equal(pthread_self(), handle_)) {
state_cond_.Wait(auto_lock);
}
}
}
Thread::~Thread() {
finalized_ = true;
stopped_ = true;
join();
pthread_join(handle_, NULL);
}
Thread* CreateThread(const char* name, ThreadDelegate* delegate) {
Thread* thread = new Thread(name, delegate);
delegate->set_thread(thread);
return thread;
}
void DeleteThread(Thread* thread) {
delete thread;
}
} // namespace threads
<commit_msg>fix for pthread_join() crash in some platforms<commit_after>/*
* Copyright (c) 2015, Ford Motor Company
* 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 Ford Motor Company 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.
*/
#include <errno.h>
#include <limits.h>
#include <stddef.h>
#include <signal.h>
#ifdef BUILD_TESTS
// Temporary fix for UnitTest until APPLINK-9987 is resolved
#include <unistd.h>
#endif
#include "utils/threads/thread.h"
#include "pthread.h"
#include "utils/atomic.h"
#include "utils/threads/thread_delegate.h"
#include "utils/logger.h"
#ifndef __QNXNTO__
const int EOK = 0;
#endif
#if defined(OS_POSIX)
const size_t THREAD_NAME_SIZE = 15;
#endif
namespace threads {
CREATE_LOGGERPTR_GLOBAL(logger_, "Utils")
size_t Thread::kMinStackSize = PTHREAD_STACK_MIN; /* Ubuntu : 16384 ; QNX : 256; */
void Thread::cleanup(void* arg) {
LOG4CXX_AUTO_TRACE(logger_);
Thread* thread = reinterpret_cast<Thread*>(arg);
sync_primitives::AutoLock auto_lock(thread->state_lock_);
thread->isThreadRunning_ = false;
thread->state_cond_.Broadcast();
}
void* Thread::threadFunc(void* arg) {
// 0 - state_lock unlocked
// stopped = 0
// running = 0
// finalized = 0
// 4 - state_lock unlocked
// stopped = 1
// running = 1
// finalized = 0
// 5 - state_lock unlocked
// stopped = 1
// running = 1
// finalized = 1
pthread_setcancelstate(PTHREAD_CANCEL_DISABLE, NULL);
LOG4CXX_DEBUG(logger_,
"Thread #" << pthread_self() << " started successfully");
threads::Thread* thread = reinterpret_cast<Thread*>(arg);
DCHECK(thread);
pthread_cleanup_push(&cleanup, thread);
thread->state_lock_.Acquire();
thread->state_cond_.Broadcast();
while (!thread->finalized_) {
LOG4CXX_DEBUG(logger_, "Thread #" << pthread_self() << " iteration");
thread->run_cond_.Wait(thread->state_lock_);
LOG4CXX_DEBUG(
logger_,
"Thread #" << pthread_self() << " execute. " << "stopped_ = " << thread->stopped_ << "; finalized_ = " << thread->finalized_);
if (!thread->stopped_ && !thread->finalized_) {
thread->isThreadRunning_ = true;
pthread_setcancelstate(PTHREAD_CANCEL_ENABLE, NULL);
pthread_testcancel();
thread->state_lock_.Release();
thread->delegate_->threadMain();
thread->state_lock_.Acquire();
pthread_setcancelstate(PTHREAD_CANCEL_DISABLE, NULL);
thread->isThreadRunning_ = false;
}
thread->state_cond_.Broadcast();
LOG4CXX_DEBUG(logger_,
"Thread #" << pthread_self() << " finished iteration");
}
thread->state_lock_.Release();
pthread_cleanup_pop(1);
LOG4CXX_DEBUG(logger_,
"Thread #" << pthread_self() << " exited successfully");
return NULL;
}
void Thread::SetNameForId(const PlatformThreadHandle& thread_id,
std::string name) {
if (name.size() > THREAD_NAME_SIZE)
name.erase(THREAD_NAME_SIZE);
const int rc = pthread_setname_np(thread_id, name.c_str());
if (rc != EOK) {
LOG4CXX_WARN(
logger_,
"Couldn't set pthread name \"" << name << "\", error code " << rc << " (" << strerror(rc) << ")");
}
}
Thread::Thread(const char* name, ThreadDelegate* delegate)
: name_(name ? name : "undefined"),
delegate_(delegate),
handle_(0),
thread_options_(),
isThreadRunning_(0),
stopped_(false),
finalized_(false),
thread_created_(false) {
}
bool Thread::start() {
return start(thread_options_);
}
PlatformThreadHandle Thread::CurrentId() {
return pthread_self();
}
bool Thread::start(const ThreadOptions& options) {
LOG4CXX_AUTO_TRACE(logger_);
sync_primitives::AutoLock auto_lock(state_lock_);
// 1 - state_lock locked
// stopped = 0
// running = 0
if (!delegate_) {
LOG4CXX_ERROR(logger_,
"Cannot start thread " << name_ << ": delegate is NULL");
// 0 - state_lock unlocked
return false;
}
if (isThreadRunning_) {
LOG4CXX_TRACE(
logger_,
"EXIT thread "<< name_ << " #" << handle_ << " is already running");
return true;
}
thread_options_ = options;
pthread_attr_t attributes;
int pthread_result = pthread_attr_init(&attributes);
if (pthread_result != EOK) {
LOG4CXX_WARN(
logger_,
"Couldn't init pthread attributes. Error code = " << pthread_result << " (\"" << strerror(pthread_result) << "\")");
}
if (!thread_options_.is_joinable()) {
pthread_result = pthread_attr_setdetachstate(&attributes, PTHREAD_CREATE_DETACHED);
if (pthread_result != EOK) {
LOG4CXX_WARN(
logger_,
"Couldn't set detach state attribute. Error code = " << pthread_result << " (\"" << strerror(pthread_result) << "\")");
thread_options_.is_joinable(false);
}
}
const size_t stack_size = thread_options_.stack_size();
if (stack_size >= Thread::kMinStackSize) {
pthread_result = pthread_attr_setstacksize(&attributes, stack_size);
if (pthread_result != EOK) {
LOG4CXX_WARN(
logger_,
"Couldn't set stacksize = " << stack_size << ". Error code = " << pthread_result << " (\"" << strerror(pthread_result) << "\")");
}
}
else {
ThreadOptions thread_options_temp(Thread::kMinStackSize, thread_options_.is_joinable());
thread_options_ = thread_options_temp;
}
if (!thread_created_) {
// state_lock 1
pthread_result = pthread_create(&handle_, &attributes, threadFunc, this);
if (pthread_result == EOK) {
LOG4CXX_DEBUG(logger_, "Created thread: " << name_);
SetNameForId(handle_, name_);
// state_lock 0
// possible concurrencies: stop and threadFunc
state_cond_.Wait(auto_lock);
thread_created_ = true;
} else {
LOG4CXX_ERROR(
logger_,
"Couldn't create thread " << name_ << ". Error code = " << pthread_result << " (\"" << strerror(pthread_result) << "\")");
}
}
stopped_ = false;
run_cond_.NotifyOne();
LOG4CXX_DEBUG(
logger_,
"Thread " << name_ << " #" << handle_ << " started. pthread_result = " << pthread_result);
pthread_attr_destroy(&attributes);
return pthread_result == EOK;
}
void Thread::stop() {
LOG4CXX_AUTO_TRACE(logger_);
sync_primitives::AutoLock auto_lock(state_lock_);
stopped_ = true;
LOG4CXX_DEBUG(logger_, "Stopping thread #" << handle_
<< " \"" << name_ << " \"");
if (delegate_ && isThreadRunning_) {
delegate_->exitThreadMain();
}
LOG4CXX_DEBUG(logger_,
"Stopped thread #" << handle_ << " \"" << name_ << " \"");
}
void Thread::join() {
LOG4CXX_AUTO_TRACE(logger_);
DCHECK(!pthread_equal(pthread_self(), handle_));
stop();
sync_primitives::AutoLock auto_lock(state_lock_);
run_cond_.NotifyOne();
if (isThreadRunning_) {
if (!pthread_equal(pthread_self(), handle_)) {
state_cond_.Wait(auto_lock);
}
}
}
Thread::~Thread() {
finalized_ = true;
stopped_ = true;
join();
//in some platforms pthread_join behaviour is undefined when thread is not created(pthread_create) and call pthread_join.
if(handle_) {
pthread_join(handle_, NULL);
handle_ = 0;
}
}
Thread* CreateThread(const char* name, ThreadDelegate* delegate) {
Thread* thread = new Thread(name, delegate);
delegate->set_thread(thread);
return thread;
}
void DeleteThread(Thread* thread) {
delete thread;
}
} // namespace threads
<|endoftext|> |
<commit_before>#include "WorldEditorScene.hpp"
#include <imgui\imgui.h>
#include <Systems/EntityManager.hpp>
#include <Systems/AssetsAndComponentRelationsSystem.hpp>
#include <Systems/PhysicsSystem.hpp>
#include <AssetManagement/AssetManager.hh>
#include <Components/CameraComponent.hpp>
#include <Threads/ThreadManager.hpp>
#include <Threads/RenderThread.hpp>
#include <Threads/Commands/MainToPrepareCommands.hpp>
#include <Threads/Commands/ToRenderCommands.hpp>
#include <Threads/Tasks/BasicTasks.hpp>
#include <Threads/Tasks/ToRenderTasks.hpp>
#include <Components/FreeFlyComponent.hh>
#include <Systems/FreeFlyCamera.hh>
#include <Components/EntityRepresentation.hpp>
#include <Managers/ArchetypesEditorManager.hpp>
#include <EditorConfiguration.hpp>
#include "Systems/RenderCameraSystem.hpp"
namespace AGE
{
const std::string WorldEditorScene::Name = "World Editor";
WorldEditorScene::WorldEditorScene(AGE::Engine *engine)
: AScene(engine)
{
}
WorldEditorScene::~WorldEditorScene(void)
{
}
bool WorldEditorScene::_userStart()
{
WE::EditorConfiguration::RefreshScenesDirectoryListing();
getInstance<AGE::AssetsManager>()->setAssetsDirectory(WE::EditorConfiguration::GetCookedDirectory());
addSystem<WE::AssetsAndComponentRelationsSystem>(0);
addSystem<WE::EntityManager>(1);
addSystem<FreeFlyCamera>(2);
addSystem<PhysicsSystem>(3, Physics::EngineType::Bullet, getInstance<AGE::AssetsManager>());
getInstance<Physics::PhysicsInterface>()->getWorld()->setGravity(0, 0, 0);
addSystem<RenderCameraSystem>(1000);
return true;
}
bool WorldEditorScene::_userUpdateBegin(float time)
{
return true;
}
bool WorldEditorScene::_userUpdateEnd(float time)
{
if (_displayWindow)
{
getInstance<AGE::WE::ArchetypeEditorManager>()->update(this);
}
// TODO
//AGE::GetPrepareThread()->getQueue()->emplaceCommand<AGE::Commands::ToRender::RenderDrawLists>();
return true;
}
void WorldEditorScene::updateMenu()
{
if (ImGui::BeginMenu("Scene"))
{
getSystem<WE::EntityManager>()->updateMenu();
ImGui::EndMenu();
}
if (ImGui::BeginMenu("Archetypes"))
{
getInstance<AGE::WE::ArchetypeEditorManager>()->updateMenu();
ImGui::EndMenu();
}
}
}<commit_msg>PhysX on AssetEditor<commit_after>#include "WorldEditorScene.hpp"
#include <imgui\imgui.h>
#include <Systems/EntityManager.hpp>
#include <Systems/AssetsAndComponentRelationsSystem.hpp>
#include <Systems/PhysicsSystem.hpp>
#include <AssetManagement/AssetManager.hh>
#include <Components/CameraComponent.hpp>
#include <Threads/ThreadManager.hpp>
#include <Threads/RenderThread.hpp>
#include <Threads/Commands/MainToPrepareCommands.hpp>
#include <Threads/Commands/ToRenderCommands.hpp>
#include <Threads/Tasks/BasicTasks.hpp>
#include <Threads/Tasks/ToRenderTasks.hpp>
#include <Components/FreeFlyComponent.hh>
#include <Systems/FreeFlyCamera.hh>
#include <Components/EntityRepresentation.hpp>
#include <Managers/ArchetypesEditorManager.hpp>
#include <EditorConfiguration.hpp>
#include "Systems/RenderCameraSystem.hpp"
namespace AGE
{
const std::string WorldEditorScene::Name = "World Editor";
WorldEditorScene::WorldEditorScene(AGE::Engine *engine)
: AScene(engine)
{
}
WorldEditorScene::~WorldEditorScene(void)
{
}
bool WorldEditorScene::_userStart()
{
WE::EditorConfiguration::RefreshScenesDirectoryListing();
getInstance<AGE::AssetsManager>()->setAssetsDirectory(WE::EditorConfiguration::GetCookedDirectory());
addSystem<WE::AssetsAndComponentRelationsSystem>(0);
addSystem<WE::EntityManager>(1);
addSystem<FreeFlyCamera>(2);
addSystem<PhysicsSystem>(3, Physics::EngineType::PhysX, getInstance<AGE::AssetsManager>());
getInstance<Physics::PhysicsInterface>()->getWorld()->setGravity(0, 0, 0);
addSystem<RenderCameraSystem>(1000);
return true;
}
bool WorldEditorScene::_userUpdateBegin(float time)
{
return true;
}
bool WorldEditorScene::_userUpdateEnd(float time)
{
if (_displayWindow)
{
getInstance<AGE::WE::ArchetypeEditorManager>()->update(this);
}
// TODO
//AGE::GetPrepareThread()->getQueue()->emplaceCommand<AGE::Commands::ToRender::RenderDrawLists>();
return true;
}
void WorldEditorScene::updateMenu()
{
if (ImGui::BeginMenu("Scene"))
{
getSystem<WE::EntityManager>()->updateMenu();
ImGui::EndMenu();
}
if (ImGui::BeginMenu("Archetypes"))
{
getInstance<AGE::WE::ArchetypeEditorManager>()->updateMenu();
ImGui::EndMenu();
}
}
}<|endoftext|> |
<commit_before>// Copyright 2010-2012 RethinkDB, all rights reserved.
#include "arch/runtime/message_hub.hpp"
#include <math.h>
#include <unistd.h>
#include "config/args.hpp"
#include "arch/runtime/event_queue.hpp"
#include "arch/runtime/thread_pool.hpp"
#include "logger.hpp"
// Set this to 1 if you would like some "unordered" messages to be unordered.
#ifndef NDEBUG
#define RDB_RELOOP_MESSAGES 0
#endif
linux_message_hub_t::linux_message_hub_t(linux_event_queue_t *queue, linux_thread_pool_t *thread_pool, int current_thread)
: queue_(queue), thread_pool_(thread_pool), current_thread_(current_thread) {
// We have to do this through dynamically, otherwise we might
// allocate far too many file descriptors since this is what the
// constructor of the system_event_t object (which is a member of
// notify_t) does.
notify_ = new notify_t[thread_pool_->n_threads];
for (int i = 0; i < thread_pool_->n_threads; i++) {
// Create notify fd for other cores that send work to us
notify_[i].notifier_thread = i;
notify_[i].parent = this;
queue_->watch_resource(notify_[i].event.get_notify_fd(), poll_event_in, ¬ify_[i]);
}
}
linux_message_hub_t::~linux_message_hub_t() {
int res;
for (int i = 0; i < thread_pool_->n_threads; i++) {
guarantee(queues_[i].msg_local_list.empty());
}
guarantee(incoming_messages_.empty());
delete[] notify_;
}
void linux_message_hub_t::do_store_message(unsigned int nthread, linux_thread_message_t *msg) {
rassert(nthread < (unsigned)thread_pool_->n_threads);
queues_[nthread].msg_local_list.push_back(msg);
}
// Collects a message for a given thread onto a local list.
void linux_message_hub_t::store_message(unsigned int nthread, linux_thread_message_t *msg) {
#ifndef NDEBUG
#if RDB_RELOOP_MESSAGES
// We default to 1, not zero, to allow store_message_sometime messages to sometimes jump ahead of
// store_message messages.
msg->reloop_count_ = 1;
#else
msg->reloop_count_ = 0;
#endif
#endif // NDEBUG
do_store_message(nthread, msg);
}
int rand_reloop_count() {
int x;
frexp(randint(10000) / 10000.0, &x);
int ret = -x;
rassert(ret >= 0);
return ret;
}
void linux_message_hub_t::store_message_sometime(unsigned int nthread, linux_thread_message_t *msg) {
#ifndef NDEBUG
#if RDB_RELOOP_MESSAGES
msg->reloop_count_ = rand_reloop_count();
#else
msg->reloop_count_ = 0;
#endif
#endif // NDEBUG
do_store_message(nthread, msg);
}
void linux_message_hub_t::insert_external_message(linux_thread_message_t *msg) {
incoming_messages_lock_.lock();
incoming_messages_.push_back(msg);
incoming_messages_lock_.unlock();
// Wakey wakey eggs and bakey
notify_[current_thread_].event.write(1);
}
void linux_message_hub_t::notify_t::on_event(int events) {
if (events != poll_event_in) {
logERR("Unexpected event mask: %d", events);
}
// Read from the event so level-triggered mechanism such as poll
// don't pester us and use 100% cpu
event.read();
msg_list_t msg_list;
parent->incoming_messages_lock_.lock();
// Pull the messages
//msg_list.append_and_clear(parent->thread_pool_->threads[parent->current_thread_]->message_hub);
msg_list.append_and_clear(&parent->incoming_messages_);
parent->incoming_messages_lock_.unlock();
#ifndef NDEBUG
start_watchdog(); // Initialize watchdog before handling messages
#endif
while (linux_thread_message_t *m = msg_list.head()) {
msg_list.remove(m);
#ifndef NDEBUG
if (m->reloop_count_ > 0) {
--m->reloop_count_;
parent->do_store_message(parent->current_thread_, m);
continue;
}
#endif
m->on_thread_switch();
#ifndef NDEBUG
pet_watchdog(); // Verify that each message completes in the acceptable time range
#endif
}
}
// Pushes messages collected locally global lists available to all
// threads.
void linux_message_hub_t::push_messages() {
for (int i = 0; i < thread_pool_->n_threads; i++) {
// Append the local list for ith thread to that thread's global
// message list.
thread_queue_t *queue = &queues_[i];
if (!queue->msg_local_list.empty()) {
// Transfer messages to the other core
thread_pool_->threads[i]->message_hub.incoming_messages_lock_.lock();
//We only need to do a wake up if the global
bool do_wake_up = thread_pool_->threads[i]->message_hub.incoming_messages_.empty();
thread_pool_->threads[i]->message_hub.incoming_messages_.append_and_clear(&queue->msg_local_list);
thread_pool_->threads[i]->message_hub.incoming_messages_lock_.unlock();
// Wakey wakey, perhaps eggs and bakey
if (do_wake_up) {
thread_pool_->threads[i]->message_hub.notify_[current_thread_].event.write(1);
}
}
// TODO: we should use regular mutexes on single core CPU
// instead of spinlocks
}
}
<commit_msg>Removed unused variable res in linux_message_hub_t destructor.<commit_after>// Copyright 2010-2012 RethinkDB, all rights reserved.
#include "arch/runtime/message_hub.hpp"
#include <math.h>
#include <unistd.h>
#include "config/args.hpp"
#include "arch/runtime/event_queue.hpp"
#include "arch/runtime/thread_pool.hpp"
#include "logger.hpp"
// Set this to 1 if you would like some "unordered" messages to be unordered.
#ifndef NDEBUG
#define RDB_RELOOP_MESSAGES 0
#endif
linux_message_hub_t::linux_message_hub_t(linux_event_queue_t *queue, linux_thread_pool_t *thread_pool, int current_thread)
: queue_(queue), thread_pool_(thread_pool), current_thread_(current_thread) {
// We have to do this through dynamically, otherwise we might
// allocate far too many file descriptors since this is what the
// constructor of the system_event_t object (which is a member of
// notify_t) does.
notify_ = new notify_t[thread_pool_->n_threads];
for (int i = 0; i < thread_pool_->n_threads; i++) {
// Create notify fd for other cores that send work to us
notify_[i].notifier_thread = i;
notify_[i].parent = this;
queue_->watch_resource(notify_[i].event.get_notify_fd(), poll_event_in, ¬ify_[i]);
}
}
linux_message_hub_t::~linux_message_hub_t() {
for (int i = 0; i < thread_pool_->n_threads; i++) {
guarantee(queues_[i].msg_local_list.empty());
}
guarantee(incoming_messages_.empty());
delete[] notify_;
}
void linux_message_hub_t::do_store_message(unsigned int nthread, linux_thread_message_t *msg) {
rassert(nthread < (unsigned)thread_pool_->n_threads);
queues_[nthread].msg_local_list.push_back(msg);
}
// Collects a message for a given thread onto a local list.
void linux_message_hub_t::store_message(unsigned int nthread, linux_thread_message_t *msg) {
#ifndef NDEBUG
#if RDB_RELOOP_MESSAGES
// We default to 1, not zero, to allow store_message_sometime messages to sometimes jump ahead of
// store_message messages.
msg->reloop_count_ = 1;
#else
msg->reloop_count_ = 0;
#endif
#endif // NDEBUG
do_store_message(nthread, msg);
}
int rand_reloop_count() {
int x;
frexp(randint(10000) / 10000.0, &x);
int ret = -x;
rassert(ret >= 0);
return ret;
}
void linux_message_hub_t::store_message_sometime(unsigned int nthread, linux_thread_message_t *msg) {
#ifndef NDEBUG
#if RDB_RELOOP_MESSAGES
msg->reloop_count_ = rand_reloop_count();
#else
msg->reloop_count_ = 0;
#endif
#endif // NDEBUG
do_store_message(nthread, msg);
}
void linux_message_hub_t::insert_external_message(linux_thread_message_t *msg) {
incoming_messages_lock_.lock();
incoming_messages_.push_back(msg);
incoming_messages_lock_.unlock();
// Wakey wakey eggs and bakey
notify_[current_thread_].event.write(1);
}
void linux_message_hub_t::notify_t::on_event(int events) {
if (events != poll_event_in) {
logERR("Unexpected event mask: %d", events);
}
// Read from the event so level-triggered mechanism such as poll
// don't pester us and use 100% cpu
event.read();
msg_list_t msg_list;
parent->incoming_messages_lock_.lock();
// Pull the messages
//msg_list.append_and_clear(parent->thread_pool_->threads[parent->current_thread_]->message_hub);
msg_list.append_and_clear(&parent->incoming_messages_);
parent->incoming_messages_lock_.unlock();
#ifndef NDEBUG
start_watchdog(); // Initialize watchdog before handling messages
#endif
while (linux_thread_message_t *m = msg_list.head()) {
msg_list.remove(m);
#ifndef NDEBUG
if (m->reloop_count_ > 0) {
--m->reloop_count_;
parent->do_store_message(parent->current_thread_, m);
continue;
}
#endif
m->on_thread_switch();
#ifndef NDEBUG
pet_watchdog(); // Verify that each message completes in the acceptable time range
#endif
}
}
// Pushes messages collected locally global lists available to all
// threads.
void linux_message_hub_t::push_messages() {
for (int i = 0; i < thread_pool_->n_threads; i++) {
// Append the local list for ith thread to that thread's global
// message list.
thread_queue_t *queue = &queues_[i];
if (!queue->msg_local_list.empty()) {
// Transfer messages to the other core
thread_pool_->threads[i]->message_hub.incoming_messages_lock_.lock();
//We only need to do a wake up if the global
bool do_wake_up = thread_pool_->threads[i]->message_hub.incoming_messages_.empty();
thread_pool_->threads[i]->message_hub.incoming_messages_.append_and_clear(&queue->msg_local_list);
thread_pool_->threads[i]->message_hub.incoming_messages_lock_.unlock();
// Wakey wakey, perhaps eggs and bakey
if (do_wake_up) {
thread_pool_->threads[i]->message_hub.notify_[current_thread_].event.write(1);
}
}
// TODO: we should use regular mutexes on single core CPU
// instead of spinlocks
}
}
<|endoftext|> |
<commit_before>// Copyright (c) 2011, Robert Escriva
// 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 po6 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.
// C++
#include <tr1/functional>
// Google Test
#include <gtest/gtest.h>
// po6
#include "po6/threads/rwlock.h"
#include "po6/threads/thread.h"
#pragma GCC diagnostic ignored "-Wswitch-default"
class RwlockTestThread
{
public:
RwlockTestThread(po6::threads::rwlock* rwl, bool mode)
: m_rwl(rwl)
, m_mode(mode)
{
}
~RwlockTestThread()
{
}
void operator () ()
{
for (int i = 0; i < 1000000; ++i)
{
if (m_mode)
{
m_rwl->rdlock();
}
else
{
m_rwl->wrlock();
}
m_rwl->unlock();
}
}
private:
RwlockTestThread(const RwlockTestThread&);
private:
RwlockTestThread& operator = (const RwlockTestThread&);
private:
po6::threads::rwlock* m_rwl;
bool m_mode;
};
namespace
{
TEST(RwlockTest, CtorAndDtor)
{
po6::threads::rwlock rwl;
}
TEST(RwlockTest, LockAndUnlock)
{
po6::threads::rwlock rwl;
rwl.rdlock();
rwl.unlock();
rwl.wrlock();
rwl.unlock();
}
TEST(RwlockTest, TwoThreads)
{
po6::threads::rwlock rwl;
RwlockTestThread read(&rwl, true);
RwlockTestThread write(&rwl, false);
po6::threads::thread t1(std::tr1::ref(read));
po6::threads::thread t2(std::tr1::ref(read));
po6::threads::thread t3(std::tr1::ref(write));
t1.start();
t2.start();
t3.start();
t1.join();
t2.join();
t3.join();
}
TEST(RwlockTest, Holding)
{
po6::threads::rwlock rwl;
{
po6::threads::rwlock::rdhold h(&rwl);
}
{
po6::threads::rwlock::wrhold h(&rwl);
}
rwl.unlock();
}
} // namespace
<commit_msg>Remove extraneous unlock in rwlock::holding.<commit_after>// Copyright (c) 2011, Robert Escriva
// 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 po6 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.
// C++
#include <tr1/functional>
// Google Test
#include <gtest/gtest.h>
// po6
#include "po6/threads/rwlock.h"
#include "po6/threads/thread.h"
#pragma GCC diagnostic ignored "-Wswitch-default"
class RwlockTestThread
{
public:
RwlockTestThread(po6::threads::rwlock* rwl, bool mode)
: m_rwl(rwl)
, m_mode(mode)
{
}
~RwlockTestThread()
{
}
void operator () ()
{
for (int i = 0; i < 1000000; ++i)
{
if (m_mode)
{
m_rwl->rdlock();
}
else
{
m_rwl->wrlock();
}
m_rwl->unlock();
}
}
private:
RwlockTestThread(const RwlockTestThread&);
private:
RwlockTestThread& operator = (const RwlockTestThread&);
private:
po6::threads::rwlock* m_rwl;
bool m_mode;
};
namespace
{
TEST(RwlockTest, CtorAndDtor)
{
po6::threads::rwlock rwl;
}
TEST(RwlockTest, LockAndUnlock)
{
po6::threads::rwlock rwl;
rwl.rdlock();
rwl.unlock();
rwl.wrlock();
rwl.unlock();
}
TEST(RwlockTest, TwoThreads)
{
po6::threads::rwlock rwl;
RwlockTestThread read(&rwl, true);
RwlockTestThread write(&rwl, false);
po6::threads::thread t1(std::tr1::ref(read));
po6::threads::thread t2(std::tr1::ref(read));
po6::threads::thread t3(std::tr1::ref(write));
t1.start();
t2.start();
t3.start();
t1.join();
t2.join();
t3.join();
}
TEST(RwlockTest, Holding)
{
po6::threads::rwlock rwl;
{
po6::threads::rwlock::rdhold h(&rwl);
}
{
po6::threads::rwlock::wrhold h(&rwl);
}
}
} // namespace
<|endoftext|> |
<commit_before>// **************************************************************************
// This file is property of and copyright by the ALICE HLT Project *
// ALICE Experiment at CERN, All rights reserved. *
// *
// Primary Authors: Sergey Gorbunov <[email protected]> *
// Ivan Kisel <[email protected]> *
// for The ALICE HLT Project. *
// *
// Permission to use, copy, modify and distribute this software and its *
// documentation strictly for non-commercial purposes is hereby granted *
// without fee, provided that the above copyright notice appears in all *
// copies and that both the copyright notice and this permission notice *
// appear in the supporting documentation. The authors make no claims *
// about the suitability of this software for any purpose. It is *
// provided "as is" without express or implied warranty. *
// *
//***************************************************************************
#include "AliHLTTPCCAStandaloneFramework.h"
#include "AliHLTTPCCATrackParam.h"
#include "AliHLTTPCCAMerger.h"
#include "AliHLTTPCCAMergerOutput.h"
#include "AliHLTTPCCADataCompressor.h"
#include "AliHLTTPCCAMath.h"
#include "AliHLTTPCCAClusterData.h"
#include "TStopwatch.h"
//If not building GPU Code then build dummy functions to link against
#ifndef BUILD_GPU
AliHLTTPCCAGPUTracker::AliHLTTPCCAGPUTracker() : gpuTracker(), DebugLevel(0) {}
AliHLTTPCCAGPUTracker::~AliHLTTPCCAGPUTracker() {}
int AliHLTTPCCAGPUTracker::InitGPU() {return(0);}
//template <class T> inline T* AliHLTTPCCAGPUTracker::alignPointer(T* ptr, int alignment) {return(NULL);}
//bool AliHLTTPCCAGPUTracker::CUDA_FAILED_MSG(cudaError_t error) {return(true);}
//int AliHLTTPCCAGPUTracker::CUDASync() {return(1);}
//void AliHLTTPCCAGPUTracker::SetDebugLevel(int dwLevel, std::ostream *NewOutFile) {};
int AliHLTTPCCAGPUTracker::Reconstruct(AliHLTTPCCATracker* tracker) {return(1);}
int AliHLTTPCCAGPUTracker::ExitGPU() {return(0);}
#endif
AliHLTTPCCAStandaloneFramework &AliHLTTPCCAStandaloneFramework::Instance()
{
// reference to static object
static AliHLTTPCCAStandaloneFramework gAliHLTTPCCAStandaloneFramework;
return gAliHLTTPCCAStandaloneFramework;
}
AliHLTTPCCAStandaloneFramework::AliHLTTPCCAStandaloneFramework()
: fMerger(), fStatNEvents( 0 ), fUseGPUTracker(false), fGPUDebugLevel(0)
{
//* constructor
for ( int i = 0; i < 20; i++ ) {
fLastTime[i] = 0;
fStatTime[i] = 0;
}
}
AliHLTTPCCAStandaloneFramework::AliHLTTPCCAStandaloneFramework( const AliHLTTPCCAStandaloneFramework& )
: fMerger(), fStatNEvents( 0 )
{
//* dummy
}
const AliHLTTPCCAStandaloneFramework &AliHLTTPCCAStandaloneFramework::operator=( const AliHLTTPCCAStandaloneFramework& ) const
{
//* dummy
return *this;
}
AliHLTTPCCAStandaloneFramework::~AliHLTTPCCAStandaloneFramework()
{
//* destructor
}
void AliHLTTPCCAStandaloneFramework::StartDataReading( int guessForNumberOfClusters )
{
//prepare for reading of the event
int sliceGuess = 2 * guessForNumberOfClusters / fgkNSlices;
for ( int i = 0; i < fgkNSlices; i++ ) {
fClusterData[i].StartReading( i, sliceGuess );
}
}
void AliHLTTPCCAStandaloneFramework::FinishDataReading()
{
// finish reading of the event
/*static int event_number = 0;
char filename[256];
sprintf(filename, "events/event.%d.dump", event_number);
printf("Dumping event into file %s\n", filename);
std::ofstream outfile(filename, std::ofstream::binary);
if (outfile.fail())
{
printf("Error opening event dump file\n");
exit(1);
}
WriteEvent(outfile);
if (outfile.fail())
{
printf("Error writing event dump file\n");
exit(1);
}
outfile.close();
sprintf(filename, "events/settings.%d.dump", event_number);
outfile.open(filename);
WriteSettings(outfile);
outfile.close();
event_number++;
std::ifstream infile(filename, std::ifstream::binary);
ReadEvent(infile);
infile.close();*/
for ( int i = 0; i < fgkNSlices; i++ ) {
fClusterData[i].FinishReading();
}
}
//int
void AliHLTTPCCAStandaloneFramework::ProcessEvent()
{
// perform the event reconstruction
fStatNEvents++;
TStopwatch timer0;
TStopwatch timer1;
if (!fUseGPUTracker || fGPUDebugLevel >= 3)
{
for ( int iSlice = 0; iSlice < fgkNSlices; iSlice++ ) {
fSliceTrackers[iSlice].ReadEvent( &( fClusterData[iSlice] ) );
fSliceTrackers[iSlice].Reconstruct();
}
if (fGPUDebugLevel >= 2) printf("\n");
}
if (fUseGPUTracker)
{
for ( int iSlice = 0; iSlice < fgkNSlices; iSlice++ ) {
fSliceTrackers[iSlice].ReadEvent( &( fClusterData[iSlice] ) );
if (fGPUTracker.Reconstruct(&fSliceTrackers[iSlice]))
{
printf("Error during GPU Reconstruction!!!\n");
//return(1);
}
}
if (fGPUDebugLevel >= 2) printf("\n");
}
timer1.Stop();
TStopwatch timer2;
fMerger.Clear();
fMerger.SetSliceParam( fSliceTrackers[0].Param() );
for ( int i = 0; i < fgkNSlices; i++ ) {
fMerger.SetSliceData( i, fSliceTrackers[i].Output() );
}
fMerger.Reconstruct();
timer2.Stop();
timer0.Stop();
fLastTime[0] = timer0.CpuTime();
fLastTime[1] = timer1.CpuTime();
fLastTime[2] = timer2.CpuTime();
for ( int i = 0; i < 3; i++ ) fStatTime[i] += fLastTime[i];
//return(0);
}
void AliHLTTPCCAStandaloneFramework::WriteSettings( std::ostream &out ) const
{
//* write settings to the file
out << NSlices() << std::endl;
for ( int iSlice = 0; iSlice < NSlices(); iSlice++ ) {
fSliceTrackers[iSlice].Param().WriteSettings( out );
}
}
void AliHLTTPCCAStandaloneFramework::ReadSettings( std::istream &in )
{
//* Read settings from the file
int nSlices = 0;
in >> nSlices;
for ( int iSlice = 0; iSlice < nSlices; iSlice++ ) {
AliHLTTPCCAParam param;
param.ReadSettings ( in );
fSliceTrackers[iSlice].Initialize( param );
}
}
void AliHLTTPCCAStandaloneFramework::WriteEvent( std::ostream &out ) const
{
// write event to the file
for ( int iSlice = 0; iSlice < fgkNSlices; iSlice++ ) {
fClusterData[iSlice].WriteEvent( out );
}
}
void AliHLTTPCCAStandaloneFramework::ReadEvent( std::istream &in )
{
//* Read event from file
for ( int iSlice = 0; iSlice < fgkNSlices; iSlice++ ) {
fClusterData[iSlice].ReadEvent( in );
}
}
void AliHLTTPCCAStandaloneFramework::WriteTracks( std::ostream &out ) const
{
//* Write tracks to file
for ( int i = 0; i < 20; i++ ) out << fLastTime[i] << std::endl;
//fMerger.Output()->Write( out );
}
void AliHLTTPCCAStandaloneFramework::ReadTracks( std::istream &in )
{
//* Read tracks from file
for ( int i = 0; i < 20; i++ ) {
in >> fLastTime[i];
fStatTime[i] += fLastTime[i];
}
//fMerger.Output()->Read( in );
}
int AliHLTTPCCAStandaloneFramework::InitGPU()
{
if (fUseGPUTracker) return(1);
int retVal = fGPUTracker.InitGPU();
fUseGPUTracker = retVal == 0;
return(retVal);
}
int AliHLTTPCCAStandaloneFramework::ExitGPU()
{
if (!fUseGPUTracker) return(1);
return(fGPUTracker.ExitGPU());
}
void AliHLTTPCCAStandaloneFramework::SetGPUDebugLevel(int Level, std::ostream *OutFile, std::ostream *GPUOutFile)
{
fGPUTracker.SetDebugLevel(Level, GPUOutFile);
fGPUDebugLevel = Level;
for (int i = 0;i < fgkNSlices;i++)
{
fSliceTrackers[i].SetGPUDebugLevel(Level, OutFile);
}
}
<commit_msg>implementation of GPUTracker::SetDebugLevel() added<commit_after>// **************************************************************************
// This file is property of and copyright by the ALICE HLT Project *
// ALICE Experiment at CERN, All rights reserved. *
// *
// Primary Authors: Sergey Gorbunov <[email protected]> *
// Ivan Kisel <[email protected]> *
// for The ALICE HLT Project. *
// *
// Permission to use, copy, modify and distribute this software and its *
// documentation strictly for non-commercial purposes is hereby granted *
// without fee, provided that the above copyright notice appears in all *
// copies and that both the copyright notice and this permission notice *
// appear in the supporting documentation. The authors make no claims *
// about the suitability of this software for any purpose. It is *
// provided "as is" without express or implied warranty. *
// *
//***************************************************************************
#include "AliHLTTPCCAStandaloneFramework.h"
#include "AliHLTTPCCATrackParam.h"
#include "AliHLTTPCCAMerger.h"
#include "AliHLTTPCCAMergerOutput.h"
#include "AliHLTTPCCADataCompressor.h"
#include "AliHLTTPCCAMath.h"
#include "AliHLTTPCCAClusterData.h"
#include "TStopwatch.h"
//If not building GPU Code then build dummy functions to link against
#ifndef BUILD_GPU
AliHLTTPCCAGPUTracker::AliHLTTPCCAGPUTracker() : gpuTracker(), DebugLevel(0) {}
AliHLTTPCCAGPUTracker::~AliHLTTPCCAGPUTracker() {}
int AliHLTTPCCAGPUTracker::InitGPU() {return(0);}
//template <class T> inline T* AliHLTTPCCAGPUTracker::alignPointer(T* ptr, int alignment) {return(NULL);}
//bool AliHLTTPCCAGPUTracker::CUDA_FAILED_MSG(cudaError_t error) {return(true);}
//int AliHLTTPCCAGPUTracker::CUDASync() {return(1);}
void AliHLTTPCCAGPUTracker::SetDebugLevel(int dwLevel, std::ostream *NewOutFile) {};
int AliHLTTPCCAGPUTracker::Reconstruct(AliHLTTPCCATracker* tracker) {return(1);}
int AliHLTTPCCAGPUTracker::ExitGPU() {return(0);}
#endif
AliHLTTPCCAStandaloneFramework &AliHLTTPCCAStandaloneFramework::Instance()
{
// reference to static object
static AliHLTTPCCAStandaloneFramework gAliHLTTPCCAStandaloneFramework;
return gAliHLTTPCCAStandaloneFramework;
}
AliHLTTPCCAStandaloneFramework::AliHLTTPCCAStandaloneFramework()
: fMerger(), fStatNEvents( 0 ), fUseGPUTracker(false), fGPUDebugLevel(0)
{
//* constructor
for ( int i = 0; i < 20; i++ ) {
fLastTime[i] = 0;
fStatTime[i] = 0;
}
}
AliHLTTPCCAStandaloneFramework::AliHLTTPCCAStandaloneFramework( const AliHLTTPCCAStandaloneFramework& )
: fMerger(), fStatNEvents( 0 )
{
//* dummy
}
const AliHLTTPCCAStandaloneFramework &AliHLTTPCCAStandaloneFramework::operator=( const AliHLTTPCCAStandaloneFramework& ) const
{
//* dummy
return *this;
}
AliHLTTPCCAStandaloneFramework::~AliHLTTPCCAStandaloneFramework()
{
//* destructor
}
void AliHLTTPCCAStandaloneFramework::StartDataReading( int guessForNumberOfClusters )
{
//prepare for reading of the event
int sliceGuess = 2 * guessForNumberOfClusters / fgkNSlices;
for ( int i = 0; i < fgkNSlices; i++ ) {
fClusterData[i].StartReading( i, sliceGuess );
}
}
void AliHLTTPCCAStandaloneFramework::FinishDataReading()
{
// finish reading of the event
/*static int event_number = 0;
char filename[256];
sprintf(filename, "events/event.%d.dump", event_number);
printf("Dumping event into file %s\n", filename);
std::ofstream outfile(filename, std::ofstream::binary);
if (outfile.fail())
{
printf("Error opening event dump file\n");
exit(1);
}
WriteEvent(outfile);
if (outfile.fail())
{
printf("Error writing event dump file\n");
exit(1);
}
outfile.close();
sprintf(filename, "events/settings.%d.dump", event_number);
outfile.open(filename);
WriteSettings(outfile);
outfile.close();
event_number++;
std::ifstream infile(filename, std::ifstream::binary);
ReadEvent(infile);
infile.close();*/
for ( int i = 0; i < fgkNSlices; i++ ) {
fClusterData[i].FinishReading();
}
}
//int
void AliHLTTPCCAStandaloneFramework::ProcessEvent()
{
// perform the event reconstruction
fStatNEvents++;
TStopwatch timer0;
TStopwatch timer1;
if (!fUseGPUTracker || fGPUDebugLevel >= 3)
{
for ( int iSlice = 0; iSlice < fgkNSlices; iSlice++ ) {
fSliceTrackers[iSlice].ReadEvent( &( fClusterData[iSlice] ) );
fSliceTrackers[iSlice].Reconstruct();
}
if (fGPUDebugLevel >= 2) printf("\n");
}
if (fUseGPUTracker)
{
for ( int iSlice = 0; iSlice < fgkNSlices; iSlice++ ) {
fSliceTrackers[iSlice].ReadEvent( &( fClusterData[iSlice] ) );
if (fGPUTracker.Reconstruct(&fSliceTrackers[iSlice]))
{
printf("Error during GPU Reconstruction!!!\n");
//return(1);
}
}
if (fGPUDebugLevel >= 2) printf("\n");
}
timer1.Stop();
TStopwatch timer2;
fMerger.Clear();
fMerger.SetSliceParam( fSliceTrackers[0].Param() );
for ( int i = 0; i < fgkNSlices; i++ ) {
fMerger.SetSliceData( i, fSliceTrackers[i].Output() );
}
fMerger.Reconstruct();
timer2.Stop();
timer0.Stop();
fLastTime[0] = timer0.CpuTime();
fLastTime[1] = timer1.CpuTime();
fLastTime[2] = timer2.CpuTime();
for ( int i = 0; i < 3; i++ ) fStatTime[i] += fLastTime[i];
//return(0);
}
void AliHLTTPCCAStandaloneFramework::WriteSettings( std::ostream &out ) const
{
//* write settings to the file
out << NSlices() << std::endl;
for ( int iSlice = 0; iSlice < NSlices(); iSlice++ ) {
fSliceTrackers[iSlice].Param().WriteSettings( out );
}
}
void AliHLTTPCCAStandaloneFramework::ReadSettings( std::istream &in )
{
//* Read settings from the file
int nSlices = 0;
in >> nSlices;
for ( int iSlice = 0; iSlice < nSlices; iSlice++ ) {
AliHLTTPCCAParam param;
param.ReadSettings ( in );
fSliceTrackers[iSlice].Initialize( param );
}
}
void AliHLTTPCCAStandaloneFramework::WriteEvent( std::ostream &out ) const
{
// write event to the file
for ( int iSlice = 0; iSlice < fgkNSlices; iSlice++ ) {
fClusterData[iSlice].WriteEvent( out );
}
}
void AliHLTTPCCAStandaloneFramework::ReadEvent( std::istream &in )
{
//* Read event from file
for ( int iSlice = 0; iSlice < fgkNSlices; iSlice++ ) {
fClusterData[iSlice].ReadEvent( in );
}
}
void AliHLTTPCCAStandaloneFramework::WriteTracks( std::ostream &out ) const
{
//* Write tracks to file
for ( int i = 0; i < 20; i++ ) out << fLastTime[i] << std::endl;
//fMerger.Output()->Write( out );
}
void AliHLTTPCCAStandaloneFramework::ReadTracks( std::istream &in )
{
//* Read tracks from file
for ( int i = 0; i < 20; i++ ) {
in >> fLastTime[i];
fStatTime[i] += fLastTime[i];
}
//fMerger.Output()->Read( in );
}
int AliHLTTPCCAStandaloneFramework::InitGPU()
{
if (fUseGPUTracker) return(1);
int retVal = fGPUTracker.InitGPU();
fUseGPUTracker = retVal == 0;
return(retVal);
}
int AliHLTTPCCAStandaloneFramework::ExitGPU()
{
if (!fUseGPUTracker) return(1);
return(fGPUTracker.ExitGPU());
}
void AliHLTTPCCAStandaloneFramework::SetGPUDebugLevel(int Level, std::ostream *OutFile, std::ostream *GPUOutFile)
{
fGPUTracker.SetDebugLevel(Level, GPUOutFile);
fGPUDebugLevel = Level;
for (int i = 0;i < fgkNSlices;i++)
{
fSliceTrackers[i].SetGPUDebugLevel(Level, OutFile);
}
}
<|endoftext|> |
<commit_before>/*
* Copyright (c) 2003-2004 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 __SPARC_LINUX_PROCESS_HH__
#define __SPARC_LINUX_PROCESS_HH__
#include "arch/sparc/linux/linux.hh"
#include "arch/sparc/process.hh"
#include "sim/process.hh"
namespace SparcISA {
// This contains all of the common elements of a SPARC Linux process which
// are not shared by other operating systems. The rest come from the common
// SPARC process class.
class SparcLinuxProcess
{
public:
/// Array of syscall descriptors, indexed by call number.
static SyscallDesc syscallDescs[];
/// Array of 32 bit compatibility syscall descriptors,
/// indexed by call number.
static SyscallDesc syscall32Descs[];
SyscallDesc* getDesc(int callnum);
SyscallDesc* getDesc32(int callnum);
static const int Num_Syscall_Descs;
static const int Num_Syscall32_Descs;
};
/// A process with emulated SPARC/Linux syscalls.
class Sparc32LinuxProcess : public SparcLinuxProcess, public Sparc32Process
{
public:
/// Constructor.
Sparc32LinuxProcess(ProcessParams * params, ObjectFile *objFile);
SyscallDesc*
getDesc(int callnum)
{
return SparcLinuxProcess::getDesc32(callnum);
}
void handleTrap(int trapNum, ThreadContext *tc, Fault *fault);
};
/// A process with emulated 32 bit SPARC/Linux syscalls.
class Sparc64LinuxProcess : public SparcLinuxProcess, public Sparc64Process
{
public:
/// Constructor.
Sparc64LinuxProcess(ProcessParams * params, ObjectFile *objFile);
SyscallDesc*
getDesc(int callnum)
{
return SparcLinuxProcess::getDesc(callnum);
}
void handleTrap(int trapNum, ThreadContext *tc, Fault *fault);
};
SyscallReturn getresuidFunc(SyscallDesc *desc, int num,
Process *p, ThreadContext *tc);
} // namespace SparcISA
#endif // __SPARC_LINUX_PROCESS_HH__
<commit_msg>sparc: Fix the getresuidFunc prototype.<commit_after>/*
* Copyright (c) 2003-2004 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 __SPARC_LINUX_PROCESS_HH__
#define __SPARC_LINUX_PROCESS_HH__
#include "arch/sparc/linux/linux.hh"
#include "arch/sparc/process.hh"
#include "sim/process.hh"
namespace SparcISA {
// This contains all of the common elements of a SPARC Linux process which
// are not shared by other operating systems. The rest come from the common
// SPARC process class.
class SparcLinuxProcess
{
public:
/// Array of syscall descriptors, indexed by call number.
static SyscallDesc syscallDescs[];
/// Array of 32 bit compatibility syscall descriptors,
/// indexed by call number.
static SyscallDesc syscall32Descs[];
SyscallDesc* getDesc(int callnum);
SyscallDesc* getDesc32(int callnum);
static const int Num_Syscall_Descs;
static const int Num_Syscall32_Descs;
};
/// A process with emulated SPARC/Linux syscalls.
class Sparc32LinuxProcess : public SparcLinuxProcess, public Sparc32Process
{
public:
/// Constructor.
Sparc32LinuxProcess(ProcessParams * params, ObjectFile *objFile);
SyscallDesc*
getDesc(int callnum)
{
return SparcLinuxProcess::getDesc32(callnum);
}
void handleTrap(int trapNum, ThreadContext *tc, Fault *fault);
};
/// A process with emulated 32 bit SPARC/Linux syscalls.
class Sparc64LinuxProcess : public SparcLinuxProcess, public Sparc64Process
{
public:
/// Constructor.
Sparc64LinuxProcess(ProcessParams * params, ObjectFile *objFile);
SyscallDesc*
getDesc(int callnum)
{
return SparcLinuxProcess::getDesc(callnum);
}
void handleTrap(int trapNum, ThreadContext *tc, Fault *fault);
};
SyscallReturn getresuidFunc(SyscallDesc *desc, int num, ThreadContext *tc);
} // namespace SparcISA
#endif // __SPARC_LINUX_PROCESS_HH__
<|endoftext|> |
<commit_before>#include "cLuaCommandBinder.h"
#include "cMCLogger.h"
#include "cPlayer.h"
#include "cPlugin_Lua.h"
#include "tolua++.h"
extern std::vector<std::string> StringSplit(std::string str, std::string delim);
extern bool report_errors(lua_State* lua, int status);
cLuaCommandBinder::cLuaCommandBinder()
{
}
cLuaCommandBinder::~cLuaCommandBinder()
{
}
void cLuaCommandBinder::ClearBindings()
{
m_BoundCommands.clear();
}
void cLuaCommandBinder::RemoveBindingsForPlugin( cPlugin* a_Plugin )
{
for( CommandMap::iterator itr = m_BoundCommands.begin(); itr != m_BoundCommands.end(); )
{
if( itr->second.Plugin == a_Plugin )
{
LOGINFO("Unbinding %s ", itr->first.c_str( ) );
luaL_unref( itr->second.LuaState, LUA_REGISTRYINDEX, itr->second.Reference ); // unreference
CommandMap::iterator eraseme = itr;
++itr;
m_BoundCommands.erase( eraseme );
continue;
}
++itr;
}
}
bool cLuaCommandBinder::BindCommand( const std::string & a_Command, const std::string & a_Permission, cPlugin* a_Plugin, lua_State * a_LuaState, int a_FunctionReference )
{
if( m_BoundCommands.find( a_Command ) != m_BoundCommands.end() )
{
LOGERROR("ERROR: Trying to bind command \"%s\" that has already been bound.", a_Command.c_str() );
return false;
}
LOGINFO("Binding %s (%s)", a_Command.c_str(), a_Permission.c_str() );
m_BoundCommands[ a_Command ] = BoundFunction( a_Plugin, a_LuaState, a_FunctionReference, a_Permission );
return true;
}
bool cLuaCommandBinder::HandleCommand( const std::string & a_Command, cPlayer* a_Player )
{
std::vector<std::string> Split = StringSplit( a_Command, " ");
CommandMap::iterator FoundCommand = m_BoundCommands.find( Split[0] );
if( FoundCommand != m_BoundCommands.end() )
{
const BoundFunction & func = FoundCommand->second;
if( func.Permission.size() > 0 )
{
if( !a_Player->HasPermission( func.Permission.c_str() ) )
{
return false;
}
}
// For enabling 'self' in the function, it's kind of a hack I'm not sure this is the way to go
lua_pushvalue(func.LuaState, LUA_GLOBALSINDEX);
lua_pushstring(func.LuaState, "self");
tolua_pushusertype( func.LuaState, func.Plugin, "cPlugin" );
lua_rawset(func.LuaState, -3);
lua_pop(func.LuaState, 1);
LOGINFO("1. Stack size: %i", lua_gettop(func.LuaState) );
lua_rawgeti( func.LuaState, LUA_REGISTRYINDEX, func.Reference); // same as lua_getref()
// Push the split
LOGINFO("2. Stack size: %i", lua_gettop(func.LuaState) );
lua_createtable(func.LuaState, Split.size(), 0);
int newTable = lua_gettop(func.LuaState);
int index = 1;
std::vector<std::string>::const_iterator iter = Split.begin();
while(iter != Split.end()) {
tolua_pushstring( func.LuaState, (*iter).c_str() );
lua_rawseti(func.LuaState, newTable, index);
++iter;
++index;
}
LOGINFO("3. Stack size: %i", lua_gettop(func.LuaState) );
// Push player
tolua_pushusertype( func.LuaState, a_Player, "cPlayer" );
LOGINFO("Calling bound function! :D");
int s = lua_pcall(func.LuaState, 2, 1, 0);
if( report_errors( func.LuaState, s ) )
{
LOGINFO("error. Stack size: %i", lua_gettop(func.LuaState) );
return false;
}
bool RetVal = (tolua_toboolean(func.LuaState, -1, 0) > 0);
lua_pop(func.LuaState, 1); // Pop return value
LOGINFO("ok. Stack size: %i", lua_gettop(func.LuaState) );
return RetVal;
}
return false;
}
<commit_msg>Fixed crash when client only sends a space in the chat<commit_after>#include "cLuaCommandBinder.h"
#include "cMCLogger.h"
#include "cPlayer.h"
#include "cPlugin_Lua.h"
#include "tolua++.h"
extern std::vector<std::string> StringSplit(std::string str, std::string delim);
extern bool report_errors(lua_State* lua, int status);
cLuaCommandBinder::cLuaCommandBinder()
{
}
cLuaCommandBinder::~cLuaCommandBinder()
{
}
void cLuaCommandBinder::ClearBindings()
{
m_BoundCommands.clear();
}
void cLuaCommandBinder::RemoveBindingsForPlugin( cPlugin* a_Plugin )
{
for( CommandMap::iterator itr = m_BoundCommands.begin(); itr != m_BoundCommands.end(); )
{
if( itr->second.Plugin == a_Plugin )
{
LOGINFO("Unbinding %s ", itr->first.c_str( ) );
luaL_unref( itr->second.LuaState, LUA_REGISTRYINDEX, itr->second.Reference ); // unreference
CommandMap::iterator eraseme = itr;
++itr;
m_BoundCommands.erase( eraseme );
continue;
}
++itr;
}
}
bool cLuaCommandBinder::BindCommand( const std::string & a_Command, const std::string & a_Permission, cPlugin* a_Plugin, lua_State * a_LuaState, int a_FunctionReference )
{
if( m_BoundCommands.find( a_Command ) != m_BoundCommands.end() )
{
LOGERROR("ERROR: Trying to bind command \"%s\" that has already been bound.", a_Command.c_str() );
return false;
}
LOGINFO("Binding %s (%s)", a_Command.c_str(), a_Permission.c_str() );
m_BoundCommands[ a_Command ] = BoundFunction( a_Plugin, a_LuaState, a_FunctionReference, a_Permission );
return true;
}
bool cLuaCommandBinder::HandleCommand( const std::string & a_Command, cPlayer* a_Player )
{
std::vector<std::string> Split = StringSplit( a_Command, " ");
if( Split.size() == 0 ) return false;
CommandMap::iterator FoundCommand = m_BoundCommands.find( Split[0] );
if( FoundCommand != m_BoundCommands.end() )
{
const BoundFunction & func = FoundCommand->second;
if( func.Permission.size() > 0 )
{
if( !a_Player->HasPermission( func.Permission.c_str() ) )
{
return false;
}
}
// For enabling 'self' in the function, it's kind of a hack I'm not sure this is the way to go
lua_pushvalue(func.LuaState, LUA_GLOBALSINDEX);
lua_pushstring(func.LuaState, "self");
tolua_pushusertype( func.LuaState, func.Plugin, "cPlugin" );
lua_rawset(func.LuaState, -3);
lua_pop(func.LuaState, 1);
LOGINFO("1. Stack size: %i", lua_gettop(func.LuaState) );
lua_rawgeti( func.LuaState, LUA_REGISTRYINDEX, func.Reference); // same as lua_getref()
// Push the split
LOGINFO("2. Stack size: %i", lua_gettop(func.LuaState) );
lua_createtable(func.LuaState, Split.size(), 0);
int newTable = lua_gettop(func.LuaState);
int index = 1;
std::vector<std::string>::const_iterator iter = Split.begin();
while(iter != Split.end()) {
tolua_pushstring( func.LuaState, (*iter).c_str() );
lua_rawseti(func.LuaState, newTable, index);
++iter;
++index;
}
LOGINFO("3. Stack size: %i", lua_gettop(func.LuaState) );
// Push player
tolua_pushusertype( func.LuaState, a_Player, "cPlayer" );
LOGINFO("Calling bound function! :D");
int s = lua_pcall(func.LuaState, 2, 1, 0);
if( report_errors( func.LuaState, s ) )
{
LOGINFO("error. Stack size: %i", lua_gettop(func.LuaState) );
return false;
}
bool RetVal = (tolua_toboolean(func.LuaState, -1, 0) > 0);
lua_pop(func.LuaState, 1); // Pop return value
LOGINFO("ok. Stack size: %i", lua_gettop(func.LuaState) );
return RetVal;
}
return false;
}
<|endoftext|> |
<commit_before>#include "graph.h"
#include "util.h"
EdgeEndStar::EdgeEndStar(){
ptInAreaLocation[0]=Location::UNDEF;
ptInAreaLocation[1]=Location::UNDEF;
edgeMap=new map<EdgeEnd*,void*,EdgeEndLT>();
edgeList=new vector<EdgeEnd*>();
}
EdgeEndStar::~EdgeEndStar(){
delete edgeMap;
delete edgeList;
}
/**
* Insert an EdgeEnd into the map, and clear the edgeList cache,
* since the list of edges has now changed
*/
void EdgeEndStar::insertEdgeEnd(EdgeEnd *e,void* obj){
edgeMap->insert(pair<EdgeEnd*,void*>(e,obj));
// (*edgeMap)[e]=obj;
edgeList=NULL; // edge list has changed - clear the cache
}
/**
* @return the coordinate for the node this star is based at
*/
Coordinate EdgeEndStar::getCoordinate(){
vector<EdgeEnd*>::iterator it=getIterator();
if (it==NULL) return Coordinate::getNull();
EdgeEnd *e=*it;
return e->getCoordinate();
}
int EdgeEndStar::getDegree(){
return (int)edgeMap->size();
}
vector<EdgeEnd*>* EdgeEndStar::getEdges() {
map<EdgeEnd*,void*,EdgeEndLT>::iterator mapIter;
if (edgeList==NULL) {
edgeList=new vector<EdgeEnd*>();
for(mapIter=edgeMap->begin();mapIter!=edgeMap->end();mapIter++) {
// edgeList->push_back(mapIter->first);
EdgeEnd *e=(EdgeEnd*) mapIter->second;
edgeList->push_back(e);
}
}
return edgeList;
}
vector<EdgeEnd*>::iterator EdgeEndStar::getIterator(){
return getEdges()->begin();
}
EdgeEnd* EdgeEndStar::getNextCW(EdgeEnd *ee){
getEdges();
int i;
for(unsigned int j=0;j<edgeList->size();j++)
{
// if (ee->compareTo( *(edgeList->at(j)))==0) {
if (ee->compareTo( *((*edgeList)[j]) )==0) {
i=j;
break;
}
}
int iNextCW=i-1;
if (i==0)
iNextCW=(int)edgeList->size()-1;
return (*edgeList)[iNextCW];
}
void EdgeEndStar::computeLabelling(vector<GeometryGraph*> *geom){
computeEdgeEndLabels();
// Propagate side labels around the edges in the star
// for each parent Geometry
propagateSideLabels(0);
propagateSideLabels(1);
/**
* If there are edges that still have null labels for a geometry
* this must be because there are no area edges for that geometry incident on this node.
* In this case, to label the edge for that geometry we must test whether the
* edge is in the interior of the geometry.
* To do this it suffices to determine whether the node for the edge is in the interior of an area.
* If so, the edge has location INTERIOR for the geometry.
* In all other cases (e.g. the node is on a line, on a point, or not on the geometry at all) the edge
* has the location EXTERIOR for the geometry.
* <p>
* Note that the edge cannot be on the BOUNDARY of the geometry, since then
* there would have been a parallel edge from the Geometry at this node also labelled BOUNDARY
* and this edge would have been labelled in the previous step.
* <p>
* This code causes a problem when dimensional collapses are present, since it may try and
* determine the location of a node where a dimensional collapse has occurred.
* The point should be considered to be on the EXTERIOR
* of the polygon, but locate() will return INTERIOR, since it is passed
* the original Geometry, not the collapsed version.
*
* If there are incident edges which are Line edges labelled BOUNDARY,
* then they must be edges resulting from dimensional collapses.
* In this case the other edges can be labelled EXTERIOR for this Geometry.
*
* MD 8/11/01 - NOT TRUE! The collapsed edges may in fact be in the interior of the Geometry,
* which means the other edges should be labelled INTERIOR for this Geometry.
* Not sure how solve this... Possibly labelling needs to be split into several phases:
* area label propagation, symLabel merging, then finally null label resolution.
*/
bool hasDimensionalCollapseEdge[2]={false,false};
vector<EdgeEnd*>::iterator it;
for (it=getIterator();it<edgeList->end();it++) {
EdgeEnd *e=*it;
Label *label=e->getLabel();
for(int geomi=0; geomi<2; geomi++) {
if (label->isLine(geomi) && label->getLocation(geomi)==Location::BOUNDARY)
hasDimensionalCollapseEdge[geomi]=true;
}
}
for (it=getIterator();it<edgeList->end();it++) {
EdgeEnd *e=*it;
Label *label=e->getLabel();
for(int geomi=0;geomi<2;geomi++){
if (label->isAnyNull(geomi)) {
int loc=Location::UNDEF;
if (hasDimensionalCollapseEdge[geomi]){
loc=Location::EXTERIOR;
}else {
Coordinate p(e->getCoordinate());
loc=getLocation(geomi,p,geom);
}
label->setAllLocationsIfNull(geomi,loc);
}
}
}
}
void EdgeEndStar::computeEdgeEndLabels(){
// Compute edge label for each EdgeEnd
for (vector<EdgeEnd*>::iterator it=getIterator();it<edgeList->end();it++) {
EdgeEnd *e=*it;
e->computeLabel();
}
}
int EdgeEndStar::getLocation(int geomIndex,Coordinate p,vector<GeometryGraph*> *geom){
// compute location only on demand
if (ptInAreaLocation[geomIndex]==Location::UNDEF) {
// ptInAreaLocation[geomIndex]=SimplePointInAreaLocator::locate(p,(geom->at(geomIndex))->getGeometry());
ptInAreaLocation[geomIndex]=SimplePointInAreaLocator::locate(p,(*geom)[geomIndex]->getGeometry());
}
return ptInAreaLocation[geomIndex];
}
bool EdgeEndStar::isAreaLabelsConsistent(){
computeEdgeEndLabels();
return checkAreaLabelsConsistent(0);
}
bool EdgeEndStar::checkAreaLabelsConsistent(int geomIndex){
// Since edges are stored in CCW order around the node,
// As we move around the ring we move from the right to the left side of the edge
vector<EdgeEnd*> *edges=getEdges();
// if no edges, trivially consistent
if (edges->size()<=0)
return true;
// initialize startLoc to location of last L side (if any)
int lastEdgeIndex=(int)edges->size()-1;
Label *startLabel=((*edgeList)[lastEdgeIndex])->getLabel();
int startLoc=startLabel->getLocation(geomIndex,Position::LEFT);
Assert::isTrue(startLoc!=Location::UNDEF, "Found unlabelled area edge");
int currLoc=startLoc;
for (vector<EdgeEnd*>::iterator it=getIterator();it<edgeList->end();it++) {
EdgeEnd *e=*it;
Label *eLabel=e->getLabel();
// we assume that we are only checking a area
Assert::isTrue(eLabel->isArea(geomIndex), "Found non-area edge");
int leftLoc=eLabel->getLocation(geomIndex,Position::LEFT);
int rightLoc=eLabel->getLocation(geomIndex,Position::RIGHT);
// check that edge is really a boundary between inside and outside!
if (leftLoc==rightLoc) {
return false;
}
// check side location conflict
//Assert.isTrue(rightLoc == currLoc, "side location conflict " + locStr);
if (rightLoc!=currLoc) {
return false;
}
currLoc=leftLoc;
}
return true;
}
void EdgeEndStar::propagateSideLabels(int geomIndex){
// Since edges are stored in CCW order around the node,
// As we move around the ring we move from the right to the left side of the edge
int startLoc=Location::UNDEF ;
// initialize loc to location of last L side (if any)
vector<EdgeEnd*>::iterator it;
for (it=getIterator();it<edgeList->end();it++) {
EdgeEnd *e=*it;
Label *label=e->getLabel();
if (label->isArea(geomIndex) && label->getLocation(geomIndex,Position::LEFT)!=Location::UNDEF)
startLoc=label->getLocation(geomIndex,Position::LEFT);
}
// no labelled sides found, so no labels to propagate
if (startLoc==Location::UNDEF) return;
int currLoc=startLoc;
for (it=getIterator();it<edgeList->end();it++) {
EdgeEnd *e=*it;
Label *label=e->getLabel();
// set null ON values to be in current location
if (label->getLocation(geomIndex,Position::ON)==Location::UNDEF)
label->setLocation(geomIndex,Position::ON,currLoc);
// set side labels (if any)
// if (label.isArea()) { //ORIGINAL
if (label->isArea(geomIndex)) {
int leftLoc=label->getLocation(geomIndex,Position::LEFT);
int rightLoc=label->getLocation(geomIndex,Position::RIGHT);
// if there is a right location, that is the next location to propagate
if (rightLoc!=Location::UNDEF) {
string locStr="(at " + (e->getCoordinate()).toString() + ")";
//Debug.print(rightLoc != currLoc, this);
Assert::isTrue(rightLoc==currLoc, "side location conflict " + locStr);
Assert::isTrue(leftLoc!=Location::UNDEF, "found single null side " + locStr);
currLoc=leftLoc;
} else {
/** RHS is null - LHS must be null too.
* This must be an edge from the other geometry, which has no location
* labelling for this geometry. This edge must lie wholly inside or outside
* the other geometry (which is determined by the current location).
* Assign both sides to be the current location.
*/
Assert::isTrue(label->getLocation(geomIndex,Position::LEFT)==Location::UNDEF, "found single null side");
label->setLocation(geomIndex,Position::RIGHT, currLoc);
label->setLocation(geomIndex,Position::LEFT, currLoc);
}
}
}
}
int EdgeEndStar::findIndex(EdgeEnd *eSearch){
getIterator(); // force edgelist to be computed
for (unsigned int i=0; i<edgeList->size(); i++ ) {
EdgeEnd *e=(*edgeList)[i];
if (e->compareTo(*eSearch)) return i;
}
return -1;
}
string EdgeEndStar::print(){
string out="EdgeEndStar: " + getCoordinate().toString()+"\n";
for (vector<EdgeEnd*>::iterator it=getIterator();it<edgeList->end();it++) {
EdgeEnd *e=*it;
out+=e->print();
}
return out;
}<commit_msg>Remove NULL test.<commit_after>#include "graph.h"
#include "util.h"
EdgeEndStar::EdgeEndStar(){
ptInAreaLocation[0]=Location::UNDEF;
ptInAreaLocation[1]=Location::UNDEF;
edgeMap=new map<EdgeEnd*,void*,EdgeEndLT>();
edgeList=new vector<EdgeEnd*>();
}
EdgeEndStar::~EdgeEndStar(){
delete edgeMap;
delete edgeList;
}
/**
* Insert an EdgeEnd into the map, and clear the edgeList cache,
* since the list of edges has now changed
*/
void EdgeEndStar::insertEdgeEnd(EdgeEnd *e,void* obj){
edgeMap->insert(pair<EdgeEnd*,void*>(e,obj));
// (*edgeMap)[e]=obj;
edgeList=NULL; // edge list has changed - clear the cache
}
/**
* @return the coordinate for the node this star is based at
*/
Coordinate EdgeEndStar::getCoordinate(){
if ( getEdges()->size() == 0 )
return Coordinate::getNull();
vector<EdgeEnd*>::iterator it=getIterator();
EdgeEnd *e=*it;
return e->getCoordinate();
}
int EdgeEndStar::getDegree(){
return (int)edgeMap->size();
}
vector<EdgeEnd*>* EdgeEndStar::getEdges() {
map<EdgeEnd*,void*,EdgeEndLT>::iterator mapIter;
if (edgeList==NULL) {
edgeList=new vector<EdgeEnd*>();
for(mapIter=edgeMap->begin();mapIter!=edgeMap->end();mapIter++) {
// edgeList->push_back(mapIter->first);
EdgeEnd *e=(EdgeEnd*) mapIter->second;
edgeList->push_back(e);
}
}
return edgeList;
}
vector<EdgeEnd*>::iterator EdgeEndStar::getIterator(){
return getEdges()->begin();
}
EdgeEnd* EdgeEndStar::getNextCW(EdgeEnd *ee){
getEdges();
int i;
for(unsigned int j=0;j<edgeList->size();j++)
{
// if (ee->compareTo( *(edgeList->at(j)))==0) {
if (ee->compareTo( *((*edgeList)[j]) )==0) {
i=j;
break;
}
}
int iNextCW=i-1;
if (i==0)
iNextCW=(int)edgeList->size()-1;
return (*edgeList)[iNextCW];
}
void EdgeEndStar::computeLabelling(vector<GeometryGraph*> *geom){
computeEdgeEndLabels();
// Propagate side labels around the edges in the star
// for each parent Geometry
propagateSideLabels(0);
propagateSideLabels(1);
/**
* If there are edges that still have null labels for a geometry
* this must be because there are no area edges for that geometry incident on this node.
* In this case, to label the edge for that geometry we must test whether the
* edge is in the interior of the geometry.
* To do this it suffices to determine whether the node for the edge is in the interior of an area.
* If so, the edge has location INTERIOR for the geometry.
* In all other cases (e.g. the node is on a line, on a point, or not on the geometry at all) the edge
* has the location EXTERIOR for the geometry.
* <p>
* Note that the edge cannot be on the BOUNDARY of the geometry, since then
* there would have been a parallel edge from the Geometry at this node also labelled BOUNDARY
* and this edge would have been labelled in the previous step.
* <p>
* This code causes a problem when dimensional collapses are present, since it may try and
* determine the location of a node where a dimensional collapse has occurred.
* The point should be considered to be on the EXTERIOR
* of the polygon, but locate() will return INTERIOR, since it is passed
* the original Geometry, not the collapsed version.
*
* If there are incident edges which are Line edges labelled BOUNDARY,
* then they must be edges resulting from dimensional collapses.
* In this case the other edges can be labelled EXTERIOR for this Geometry.
*
* MD 8/11/01 - NOT TRUE! The collapsed edges may in fact be in the interior of the Geometry,
* which means the other edges should be labelled INTERIOR for this Geometry.
* Not sure how solve this... Possibly labelling needs to be split into several phases:
* area label propagation, symLabel merging, then finally null label resolution.
*/
bool hasDimensionalCollapseEdge[2]={false,false};
vector<EdgeEnd*>::iterator it;
for (it=getIterator();it<edgeList->end();it++) {
EdgeEnd *e=*it;
Label *label=e->getLabel();
for(int geomi=0; geomi<2; geomi++) {
if (label->isLine(geomi) && label->getLocation(geomi)==Location::BOUNDARY)
hasDimensionalCollapseEdge[geomi]=true;
}
}
for (it=getIterator();it<edgeList->end();it++) {
EdgeEnd *e=*it;
Label *label=e->getLabel();
for(int geomi=0;geomi<2;geomi++){
if (label->isAnyNull(geomi)) {
int loc=Location::UNDEF;
if (hasDimensionalCollapseEdge[geomi]){
loc=Location::EXTERIOR;
}else {
Coordinate p(e->getCoordinate());
loc=getLocation(geomi,p,geom);
}
label->setAllLocationsIfNull(geomi,loc);
}
}
}
}
void EdgeEndStar::computeEdgeEndLabels(){
// Compute edge label for each EdgeEnd
for (vector<EdgeEnd*>::iterator it=getIterator();it<edgeList->end();it++) {
EdgeEnd *e=*it;
e->computeLabel();
}
}
int EdgeEndStar::getLocation(int geomIndex,Coordinate p,vector<GeometryGraph*> *geom){
// compute location only on demand
if (ptInAreaLocation[geomIndex]==Location::UNDEF) {
// ptInAreaLocation[geomIndex]=SimplePointInAreaLocator::locate(p,(geom->at(geomIndex))->getGeometry());
ptInAreaLocation[geomIndex]=SimplePointInAreaLocator::locate(p,(*geom)[geomIndex]->getGeometry());
}
return ptInAreaLocation[geomIndex];
}
bool EdgeEndStar::isAreaLabelsConsistent(){
computeEdgeEndLabels();
return checkAreaLabelsConsistent(0);
}
bool EdgeEndStar::checkAreaLabelsConsistent(int geomIndex){
// Since edges are stored in CCW order around the node,
// As we move around the ring we move from the right to the left side of the edge
vector<EdgeEnd*> *edges=getEdges();
// if no edges, trivially consistent
if (edges->size()<=0)
return true;
// initialize startLoc to location of last L side (if any)
int lastEdgeIndex=(int)edges->size()-1;
Label *startLabel=((*edgeList)[lastEdgeIndex])->getLabel();
int startLoc=startLabel->getLocation(geomIndex,Position::LEFT);
Assert::isTrue(startLoc!=Location::UNDEF, "Found unlabelled area edge");
int currLoc=startLoc;
for (vector<EdgeEnd*>::iterator it=getIterator();it<edgeList->end();it++) {
EdgeEnd *e=*it;
Label *eLabel=e->getLabel();
// we assume that we are only checking a area
Assert::isTrue(eLabel->isArea(geomIndex), "Found non-area edge");
int leftLoc=eLabel->getLocation(geomIndex,Position::LEFT);
int rightLoc=eLabel->getLocation(geomIndex,Position::RIGHT);
// check that edge is really a boundary between inside and outside!
if (leftLoc==rightLoc) {
return false;
}
// check side location conflict
//Assert.isTrue(rightLoc == currLoc, "side location conflict " + locStr);
if (rightLoc!=currLoc) {
return false;
}
currLoc=leftLoc;
}
return true;
}
void EdgeEndStar::propagateSideLabels(int geomIndex){
// Since edges are stored in CCW order around the node,
// As we move around the ring we move from the right to the left side of the edge
int startLoc=Location::UNDEF ;
// initialize loc to location of last L side (if any)
vector<EdgeEnd*>::iterator it;
for (it=getIterator();it<edgeList->end();it++) {
EdgeEnd *e=*it;
Label *label=e->getLabel();
if (label->isArea(geomIndex) && label->getLocation(geomIndex,Position::LEFT)!=Location::UNDEF)
startLoc=label->getLocation(geomIndex,Position::LEFT);
}
// no labelled sides found, so no labels to propagate
if (startLoc==Location::UNDEF) return;
int currLoc=startLoc;
for (it=getIterator();it<edgeList->end();it++) {
EdgeEnd *e=*it;
Label *label=e->getLabel();
// set null ON values to be in current location
if (label->getLocation(geomIndex,Position::ON)==Location::UNDEF)
label->setLocation(geomIndex,Position::ON,currLoc);
// set side labels (if any)
// if (label.isArea()) { //ORIGINAL
if (label->isArea(geomIndex)) {
int leftLoc=label->getLocation(geomIndex,Position::LEFT);
int rightLoc=label->getLocation(geomIndex,Position::RIGHT);
// if there is a right location, that is the next location to propagate
if (rightLoc!=Location::UNDEF) {
string locStr="(at " + (e->getCoordinate()).toString() + ")";
//Debug.print(rightLoc != currLoc, this);
Assert::isTrue(rightLoc==currLoc, "side location conflict " + locStr);
Assert::isTrue(leftLoc!=Location::UNDEF, "found single null side " + locStr);
currLoc=leftLoc;
} else {
/** RHS is null - LHS must be null too.
* This must be an edge from the other geometry, which has no location
* labelling for this geometry. This edge must lie wholly inside or outside
* the other geometry (which is determined by the current location).
* Assign both sides to be the current location.
*/
Assert::isTrue(label->getLocation(geomIndex,Position::LEFT)==Location::UNDEF, "found single null side");
label->setLocation(geomIndex,Position::RIGHT, currLoc);
label->setLocation(geomIndex,Position::LEFT, currLoc);
}
}
}
}
int EdgeEndStar::findIndex(EdgeEnd *eSearch){
getIterator(); // force edgelist to be computed
for (unsigned int i=0; i<edgeList->size(); i++ ) {
EdgeEnd *e=(*edgeList)[i];
if (e->compareTo(*eSearch)) return i;
}
return -1;
}
string EdgeEndStar::print(){
string out="EdgeEndStar: " + getCoordinate().toString()+"\n";
for (vector<EdgeEnd*>::iterator it=getIterator();it<edgeList->end();it++) {
EdgeEnd *e=*it;
out+=e->print();
}
return out;
}
<|endoftext|> |
<commit_before>#include "estimator/atmospheric_location_estimator.hpp"
#include "protocol/messages.hpp"
#include "unit_config.hpp"
AtmosphericLocationEstimator::AtmosphericLocationEstimator(Communicator& communicator)
: locationMessageStream(communicator, 5) {
}
LocationEstimate AtmosphericLocationEstimator::update(const SensorMeasurements& meas) {
makeEstimate(meas);
updateStream();
return loc;
}
LocationEstimate AtmosphericLocationEstimator::makeEstimate(const SensorMeasurements& meas) {
if(meas.gps) {
loc.lat = (*meas.gps).lat;
loc.lon = (*meas.gps).lat;
}
if(meas.bar) {
// TODO: Mix GPS and barometer readings to get an accuration altitude?
// TODO: Pressure != altitude.
loc.alt = (*meas.bar).pressure;
}
return loc;
}
void AtmosphericLocationEstimator::updateStream() {
if(locationMessageStream.ready()) {
protocol::message::location_message_t m {
.lat = loc.lat,
.lon = loc.lon,
.alt = loc.alt
};
locationMessageStream.publish(m);
}
}
<commit_msg>Initialize location.<commit_after>#include "estimator/atmospheric_location_estimator.hpp"
#include "protocol/messages.hpp"
#include "unit_config.hpp"
// TODO: Initial location is not valid. Maybe we should be able to mark the
// estimate as invalid until a GPS fix is found?
AtmosphericLocationEstimator::AtmosphericLocationEstimator(Communicator& communicator)
: loc{0.0, 0.0, 0.0}
locationMessageStream(communicator, 5) {
}
LocationEstimate AtmosphericLocationEstimator::update(const SensorMeasurements& meas) {
makeEstimate(meas);
updateStream();
return loc;
}
LocationEstimate AtmosphericLocationEstimator::makeEstimate(const SensorMeasurements& meas) {
if(meas.gps) {
loc.lat = (*meas.gps).lat;
loc.lon = (*meas.gps).lat;
}
if(meas.bar) {
// TODO: Mix GPS and barometer readings to get an accuration altitude?
// TODO: Pressure != altitude.
loc.alt = (*meas.bar).pressure;
}
return loc;
}
void AtmosphericLocationEstimator::updateStream() {
if(locationMessageStream.ready()) {
protocol::message::location_message_t m {
.lat = loc.lat,
.lon = loc.lon,
.alt = loc.alt
};
locationMessageStream.publish(m);
}
}
<|endoftext|> |
<commit_before>
//#include <OGRE/ExampleApplication.h>
//#include <OGRE/OgreLogManager.h>
#include "Actions/Action.h"
#include "Actions/ActionPump.h"
#include "Application/Application.h"
#include "Common/Common.h"
#include "Input/Input.h"
#include "Networking/Network.h"
#include "Graphics/Graphics.h"
#include <iostream>
#include <fstream>
#include <OGRE/ExampleApplication.h>
#include <OGRE/ExampleFrameListener.h>
using namespace std;
int main(int argc, char **argv)
{
/*Network* x = Network::instance();
x->connect("127.0.0.1");
// This is necessary to have the networking branch off on its own thread.
asio::thread t(boost::bind(&asio::io_service::run, &Network::service()));
Action a;
a["id"] = 4;
a["target"] = 300;
Network::instance()->send(a, UNKNOWN);
t.join();
*/
//Example app;
Application app2;
try {
//app.go();
app2.go();
}
catch( Ogre::Exception& e ) {
std::cerr << "An exception has occured: " << e.getFullDescription().c_str() << std::endl;
}
return 0;
}
<commit_msg>Uncomments main application in main.cpp<commit_after>
//#include <OGRE/ExampleApplication.h>
//#include <OGRE/OgreLogManager.h>
#include "Actions/Action.h"
#include "Actions/ActionPump.h"
#include "Application/Application.h"
#include "Common/Common.h"
#include "Input/Input.h"
#include "Networking/Network.h"
#include "Graphics/Graphics.h"
#include <iostream>
#include <fstream>
#include <OGRE/ExampleApplication.h>
#include <OGRE/ExampleFrameListener.h>
#include <btBulletDynamicsCommon.h>
using namespace std;
int main(int argc, char **argv)
{
btBroadphaseInterface* broadphase = new btDbvtBroadphase();
/*Network* x = Network::instance();
x->connect("127.0.0.1");
// This is necessary to have the networking branch off on its own thread.
asio::thread t(boost::bind(&asio::io_service::run, &Network::service()));
Action a;
a["id"] = 4;
a["target"] = 300;
Network::instance()->send(a, UNKNOWN);
t.join();*/
//Example app;
Application app2;
try {
//app.go();
app2.go();
}
catch( Ogre::Exception& e ) {
std::cerr << "An exception has occured: " << e.getFullDescription().c_str() << std::endl;
}
return 0;
}
<|endoftext|> |
<commit_before>/*============================================================================
The Medical Imaging Interaction Toolkit (MITK)
Copyright (c) German Cancer Research Center (DKFZ)
All rights reserved.
Use of this source code is governed by a 3-clause BSD license that can be
found in the LICENSE file.
============================================================================*/
#include "mitkCorrectorTool2D.h"
#include "mitkCorrectorAlgorithm.h"
#include "mitkAbstractTransformGeometry.h"
#include "mitkBaseRenderer.h"
#include "mitkImageReadAccessor.h"
#include "mitkLabelSetImage.h"
#include "mitkRenderingManager.h"
#include "mitkToolManager.h"
#include "mitkCorrectorTool2D.xpm"
#include "mitkLabelSetImage.h"
// us
#include <usGetModuleContext.h>
#include <usModule.h>
#include <usModuleContext.h>
#include <usModuleResource.h>
namespace mitk
{
MITK_TOOL_MACRO(MITKSEGMENTATION_EXPORT, CorrectorTool2D, "Correction tool");
}
mitk::CorrectorTool2D::CorrectorTool2D(int paintingPixelValue)
: FeedbackContourTool("PressMoveRelease"), m_PaintingPixelValue(paintingPixelValue)
{
GetFeedbackContour()->SetClosed(false); // don't close the contour to a polygon
}
mitk::CorrectorTool2D::~CorrectorTool2D()
{
}
void mitk::CorrectorTool2D::ConnectActionsAndFunctions()
{
CONNECT_FUNCTION("PrimaryButtonPressed", OnMousePressed);
CONNECT_FUNCTION("Move", OnMouseMoved);
CONNECT_FUNCTION("Release", OnMouseReleased);
}
const char **mitk::CorrectorTool2D::GetXPM() const
{
return mitkCorrectorTool2D_xpm;
}
us::ModuleResource mitk::CorrectorTool2D::GetIconResource() const
{
us::Module *module = us::GetModuleContext()->GetModule();
us::ModuleResource resource = module->GetResource("Correction_48x48.png");
return resource;
}
us::ModuleResource mitk::CorrectorTool2D::GetCursorIconResource() const
{
us::Module *module = us::GetModuleContext()->GetModule();
us::ModuleResource resource = module->GetResource("Correction_Cursor_32x32.png");
return resource;
}
const char *mitk::CorrectorTool2D::GetName() const
{
return "Correction";
}
void mitk::CorrectorTool2D::Activated()
{
Superclass::Activated();
}
void mitk::CorrectorTool2D::Deactivated()
{
Superclass::Deactivated();
}
void mitk::CorrectorTool2D::OnMousePressed(StateMachineAction *, InteractionEvent *interactionEvent)
{
auto *positionEvent = dynamic_cast<mitk::InteractionPositionEvent *>(interactionEvent);
if (!positionEvent)
return;
m_LastEventSender = positionEvent->GetSender();
m_LastEventSlice = m_LastEventSender->GetSlice();
int timestep = positionEvent->GetSender()->GetTimeStep();
ContourModel *contour = FeedbackContourTool::GetFeedbackContour();
contour->Initialize();
contour->Expand(timestep + 1);
contour->SetClosed(false, timestep);
mitk::Point3D point = positionEvent->GetPositionInWorld();
contour->AddVertex(point, timestep);
FeedbackContourTool::SetFeedbackContourVisible(true);
}
void mitk::CorrectorTool2D::OnMouseMoved(StateMachineAction *, InteractionEvent *interactionEvent)
{
auto *positionEvent = dynamic_cast<mitk::InteractionPositionEvent *>(interactionEvent);
if (!positionEvent)
return;
int timestep = positionEvent->GetSender()->GetTimeStep();
ContourModel *contour = FeedbackContourTool::GetFeedbackContour();
mitk::Point3D point = positionEvent->GetPositionInWorld();
contour->AddVertex(point, timestep);
assert(positionEvent->GetSender()->GetRenderWindow());
mitk::RenderingManager::GetInstance()->RequestUpdate(positionEvent->GetSender()->GetRenderWindow());
}
void mitk::CorrectorTool2D::OnMouseReleased(StateMachineAction *, InteractionEvent *interactionEvent)
{
// 1. Hide the feedback contour, find out which slice the user clicked, find out which slice of the toolmanager's
// working image corresponds to that
FeedbackContourTool::SetFeedbackContourVisible(false);
auto *positionEvent = dynamic_cast<mitk::InteractionPositionEvent *>(interactionEvent);
// const PositionEvent* positionEvent = dynamic_cast<const PositionEvent*>(stateEvent->GetEvent());
if (!positionEvent)
return;
assert(positionEvent->GetSender()->GetRenderWindow());
mitk::RenderingManager::GetInstance()->RequestUpdate(positionEvent->GetSender()->GetRenderWindow());
DataNode *workingNode(m_ToolManager->GetWorkingData(0));
if (!workingNode)
return;
auto *image = dynamic_cast<Image *>(workingNode->GetData());
const PlaneGeometry *planeGeometry((positionEvent->GetSender()->GetCurrentWorldPlaneGeometry()));
if (!image || !planeGeometry)
return;
const auto *abstractTransformGeometry(
dynamic_cast<const AbstractTransformGeometry *>(positionEvent->GetSender()->GetCurrentWorldPlaneGeometry()));
if (!image || abstractTransformGeometry)
return;
// 2. Slice is known, now we try to get it as a 2D image and project the contour into index coordinates of this slice
m_WorkingSlice = FeedbackContourTool::GetAffectedImageSliceAs2DImage(positionEvent, image);
if (m_WorkingSlice.IsNull())
{
MITK_ERROR << "Unable to extract slice." << std::endl;
return;
}
int timestep = positionEvent->GetSender()->GetTimeStep();
mitk::ContourModel::Pointer singleTimestepContour = mitk::ContourModel::New();
auto it = FeedbackContourTool::GetFeedbackContour()->Begin(timestep);
auto end = FeedbackContourTool::GetFeedbackContour()->End(timestep);
while (it != end)
{
singleTimestepContour->AddVertex((*it)->Coordinates);
it++;
}
CorrectorAlgorithm::Pointer algorithm = CorrectorAlgorithm::New();
algorithm->SetInput(m_WorkingSlice);
algorithm->SetContour(singleTimestepContour);
mitk::LabelSetImage::Pointer labelSetImage = dynamic_cast<LabelSetImage *>(workingNode->GetData());
int workingColorId(1);
if (labelSetImage.IsNotNull())
{
workingColorId = labelSetImage->GetActiveLabel()->GetValue();
algorithm->SetFillColor(workingColorId);
}
try
{
algorithm->UpdateLargestPossibleRegion();
}
catch (std::exception &e)
{
MITK_ERROR << "Caught exception '" << e.what() << "'" << std::endl;
}
mitk::Image::Pointer resultSlice = mitk::Image::New();
resultSlice->Initialize(algorithm->GetOutput());
if (labelSetImage.IsNotNull())
{
mitk::Image::Pointer erg1 = FeedbackContourTool::GetAffectedImageSliceAs2DImage(positionEvent, image);
SegTool2D::WritePreviewOnWorkingImage(erg1, algorithm->GetOutput(), image, workingColorId, 0);
SegTool2D::WriteBackSegmentationResult(positionEvent, erg1);
}
else
{
mitk::ImageReadAccessor imAccess(algorithm->GetOutput());
resultSlice->SetVolume(imAccess.GetData());
this->WriteBackSegmentationResult(positionEvent, resultSlice);
}
}
<commit_msg>Fix T28076 by using the new function for retrieving the active pixel value<commit_after>/*============================================================================
The Medical Imaging Interaction Toolkit (MITK)
Copyright (c) German Cancer Research Center (DKFZ)
All rights reserved.
Use of this source code is governed by a 3-clause BSD license that can be
found in the LICENSE file.
============================================================================*/
#include "mitkCorrectorTool2D.h"
#include "mitkCorrectorAlgorithm.h"
#include "mitkAbstractTransformGeometry.h"
#include "mitkBaseRenderer.h"
#include "mitkImageReadAccessor.h"
#include "mitkLabelSetImage.h"
#include "mitkRenderingManager.h"
#include "mitkToolManager.h"
#include "mitkCorrectorTool2D.xpm"
#include "mitkLabelSetImage.h"
// us
#include <usGetModuleContext.h>
#include <usModule.h>
#include <usModuleContext.h>
#include <usModuleResource.h>
namespace mitk
{
MITK_TOOL_MACRO(MITKSEGMENTATION_EXPORT, CorrectorTool2D, "Correction tool");
}
mitk::CorrectorTool2D::CorrectorTool2D(int paintingPixelValue)
: FeedbackContourTool("PressMoveRelease"), m_PaintingPixelValue(paintingPixelValue)
{
GetFeedbackContour()->SetClosed(false); // don't close the contour to a polygon
}
mitk::CorrectorTool2D::~CorrectorTool2D()
{
}
void mitk::CorrectorTool2D::ConnectActionsAndFunctions()
{
CONNECT_FUNCTION("PrimaryButtonPressed", OnMousePressed);
CONNECT_FUNCTION("Move", OnMouseMoved);
CONNECT_FUNCTION("Release", OnMouseReleased);
}
const char **mitk::CorrectorTool2D::GetXPM() const
{
return mitkCorrectorTool2D_xpm;
}
us::ModuleResource mitk::CorrectorTool2D::GetIconResource() const
{
us::Module *module = us::GetModuleContext()->GetModule();
us::ModuleResource resource = module->GetResource("Correction_48x48.png");
return resource;
}
us::ModuleResource mitk::CorrectorTool2D::GetCursorIconResource() const
{
us::Module *module = us::GetModuleContext()->GetModule();
us::ModuleResource resource = module->GetResource("Correction_Cursor_32x32.png");
return resource;
}
const char *mitk::CorrectorTool2D::GetName() const
{
return "Correction";
}
void mitk::CorrectorTool2D::Activated()
{
Superclass::Activated();
}
void mitk::CorrectorTool2D::Deactivated()
{
Superclass::Deactivated();
}
void mitk::CorrectorTool2D::OnMousePressed(StateMachineAction *, InteractionEvent *interactionEvent)
{
auto *positionEvent = dynamic_cast<mitk::InteractionPositionEvent *>(interactionEvent);
if (!positionEvent)
return;
m_LastEventSender = positionEvent->GetSender();
m_LastEventSlice = m_LastEventSender->GetSlice();
int timestep = positionEvent->GetSender()->GetTimeStep();
ContourModel *contour = FeedbackContourTool::GetFeedbackContour();
contour->Initialize();
contour->Expand(timestep + 1);
contour->SetClosed(false, timestep);
mitk::Point3D point = positionEvent->GetPositionInWorld();
contour->AddVertex(point, timestep);
FeedbackContourTool::SetFeedbackContourVisible(true);
}
void mitk::CorrectorTool2D::OnMouseMoved(StateMachineAction *, InteractionEvent *interactionEvent)
{
auto *positionEvent = dynamic_cast<mitk::InteractionPositionEvent *>(interactionEvent);
if (!positionEvent)
return;
int timestep = positionEvent->GetSender()->GetTimeStep();
ContourModel *contour = FeedbackContourTool::GetFeedbackContour();
mitk::Point3D point = positionEvent->GetPositionInWorld();
contour->AddVertex(point, timestep);
assert(positionEvent->GetSender()->GetRenderWindow());
mitk::RenderingManager::GetInstance()->RequestUpdate(positionEvent->GetSender()->GetRenderWindow());
}
void mitk::CorrectorTool2D::OnMouseReleased(StateMachineAction *, InteractionEvent *interactionEvent)
{
// 1. Hide the feedback contour, find out which slice the user clicked, find out which slice of the toolmanager's
// working image corresponds to that
FeedbackContourTool::SetFeedbackContourVisible(false);
auto *positionEvent = dynamic_cast<mitk::InteractionPositionEvent *>(interactionEvent);
// const PositionEvent* positionEvent = dynamic_cast<const PositionEvent*>(stateEvent->GetEvent());
if (!positionEvent)
return;
assert(positionEvent->GetSender()->GetRenderWindow());
mitk::RenderingManager::GetInstance()->RequestUpdate(positionEvent->GetSender()->GetRenderWindow());
DataNode *workingNode(m_ToolManager->GetWorkingData(0));
if (!workingNode)
return;
auto *workingImage = dynamic_cast<Image *>(workingNode->GetData());
const PlaneGeometry *planeGeometry((positionEvent->GetSender()->GetCurrentWorldPlaneGeometry()));
if (!workingImage || !planeGeometry)
return;
const auto *abstractTransformGeometry(
dynamic_cast<const AbstractTransformGeometry *>(positionEvent->GetSender()->GetCurrentWorldPlaneGeometry()));
if (!workingImage || abstractTransformGeometry)
return;
// 2. Slice is known, now we try to get it as a 2D image and project the contour into index coordinates of this slice
m_WorkingSlice = FeedbackContourTool::GetAffectedImageSliceAs2DImage(positionEvent, workingImage);
if (m_WorkingSlice.IsNull())
{
MITK_ERROR << "Unable to extract slice." << std::endl;
return;
}
int timestep = positionEvent->GetSender()->GetTimeStep();
mitk::ContourModel::Pointer singleTimestepContour = mitk::ContourModel::New();
auto it = FeedbackContourTool::GetFeedbackContour()->Begin(timestep);
auto end = FeedbackContourTool::GetFeedbackContour()->End(timestep);
while (it != end)
{
singleTimestepContour->AddVertex((*it)->Coordinates);
it++;
}
CorrectorAlgorithm::Pointer algorithm = CorrectorAlgorithm::New();
algorithm->SetInput(m_WorkingSlice);
algorithm->SetContour(singleTimestepContour);
int activePixelValue = ContourModelUtils::GetActivePixelValue(workingImage);
algorithm->SetFillColor(activePixelValue);
try
{
algorithm->UpdateLargestPossibleRegion();
}
catch (std::exception &e)
{
MITK_ERROR << "Caught exception '" << e.what() << "'" << std::endl;
}
mitk::Image::Pointer resultSlice = mitk::Image::New();
resultSlice->Initialize(algorithm->GetOutput());
auto* labelSetImage = dynamic_cast<LabelSetImage*>(workingImage);
if (nullptr != labelSetImage)
{
mitk::Image::Pointer erg1 = FeedbackContourTool::GetAffectedImageSliceAs2DImage(positionEvent, workingImage);
SegTool2D::WritePreviewOnWorkingImage(erg1, algorithm->GetOutput(), workingImage, activePixelValue, 0);
SegTool2D::WriteBackSegmentationResult(positionEvent, erg1);
}
else
{
mitk::ImageReadAccessor imAccess(algorithm->GetOutput());
resultSlice->SetVolume(imAccess.GetData());
this->WriteBackSegmentationResult(positionEvent, resultSlice);
}
}
<|endoftext|> |
<commit_before>/* -------------------------------------------------------------------------- *
* OpenSim: toyLeg_example.cpp *
* -------------------------------------------------------------------------- *
* The OpenSim API is a toolkit for musculoskeletal modeling and simulation. *
* See http://opensim.stanford.edu and the NOTICE file for more information. *
* OpenSim is developed at Stanford University and supported by the US *
* National Institutes of Health (U54 GM072970, R24 HD065690) and by DARPA *
* through the Warrior Web program. *
* *
* Copyright (c) 2005-2012 Stanford University and the Authors *
* Author(s): Matt S. DeMers *
* *
* 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. *
* -------------------------------------------------------------------------- */
/*
* Below is an example of an OpenSim application that provides its own
* main() routine. This application acts as an example for utilizing the
* ControllabeSpring actuator.
*/
// Author: Matt DeMers
//==============================================================================
//==============================================================================
#include "PistonActuator.h"
#include "ControllableSpring.h"
#include <OpenSim/OpenSim.h>
#include "OpenSim/Common/STOFileAdapter.h"
using namespace OpenSim;
using namespace SimTK;
//______________________________________________________________________________
/**
* Run a simulation of block sliding with contact on by two muscles sliding with contact
*/
int main()
{
try {
// Create a new OpenSim model
Model osimModel;
osimModel.setName("osimModel");
osimModel.setAuthors("Matt DeMers");
double Pi = SimTK::Pi;
// Get the ground body
Ground& ground = osimModel.updGround();
ground.attachMeshGeometry("checkered_floor.vtp");
// create linkage body
double linkageMass = 0.001, linkageLength = 0.5, linkageDiameter = 0.06;
Vec3 linkageDimensions(linkageDiameter, linkageLength, linkageDiameter);
Vec3 linkageMassCenter(0,linkageLength/2,0);
Inertia linkageInertia = Inertia::cylinderAlongY(linkageDiameter/2.0, linkageLength/2.0);
OpenSim::Body* linkage1 = new OpenSim::Body("linkage1", linkageMass, linkageMassCenter, linkageMass*linkageInertia);
// Graphical representation
Cylinder cyl;
cyl.set_scale_factors(linkageDimensions);
Frame* cyl1Frame = new PhysicalOffsetFrame(*linkage1, Transform(Vec3(0.0, linkageLength / 2.0, 0.0)));
cyl1Frame->setName("Cyl1_frame");
osimModel.addFrame(cyl1Frame);
cyl.setFrameName("Cyl1_frame");
linkage1->addGeometry(cyl);
linkage1->attachGeometry(Sphere(0.1));
// Create a second linkage body
OpenSim::Body* linkage2 = new OpenSim::Body(*linkage1);
linkage2->setName("linkage2");
Frame* cyl2Frame = new PhysicalOffsetFrame(*linkage2, Transform(Vec3(0.0, linkageLength / 2.0, 0.0)));
cyl2Frame->setName("Cyl2_frame");
osimModel.addFrame(cyl2Frame);
(linkage2->upd_geometry(0)).setFrameName("Cyl2_frame");
// Create a block to be the pelvis
double blockMass = 20.0, blockSideLength = 0.2;
Vec3 blockMassCenter(0);
Inertia blockInertia = blockMass*Inertia::brick(blockSideLength, blockSideLength, blockSideLength);
OpenSim::Body *block = new OpenSim::Body("block", blockMass, blockMassCenter, blockInertia);
block->attachGeometry(Brick(SimTK::Vec3(0.05, 0.05, 0.05)));
// Create 1 degree-of-freedom pin joints between the bodies to create a kinematic chain from ground through the block
Vec3 orientationInGround(0), locationInGround(0), locationInParent(0.0, linkageLength, 0.0), orientationInChild(0), locationInChild(0);
PinJoint *ankle = new PinJoint("ankle", ground, locationInGround, orientationInGround, *linkage1,
locationInChild, orientationInChild);
PinJoint *knee = new PinJoint("knee", *linkage1, locationInParent, orientationInChild, *linkage2,
locationInChild, orientationInChild);
PinJoint *hip = new PinJoint("hip", *linkage2, locationInParent, orientationInChild, *block,
locationInChild, orientationInChild);
double range[2] = {-SimTK::Pi*2, SimTK::Pi*2};
CoordinateSet& ankleCoordinateSet = ankle->upd_CoordinateSet();
ankleCoordinateSet[0].setName("q1");
ankleCoordinateSet[0].setRange(range);
CoordinateSet& kneeCoordinateSet = knee->upd_CoordinateSet();
kneeCoordinateSet[0].setName("q2");
kneeCoordinateSet[0].setRange(range);
CoordinateSet& hipCoordinateSet = hip->upd_CoordinateSet();
hipCoordinateSet[0].setName("q3");
hipCoordinateSet[0].setRange(range);
// Add the bodies to the model
osimModel.addBody(linkage1);
osimModel.addBody(linkage2);
osimModel.addBody(block);
// Add the joints to the model
osimModel.addJoint(ankle);
osimModel.addJoint(knee);
osimModel.addJoint(hip);
// Define constraints on the model
// Add a point on line constraint to limit the block to vertical motion
Vec3 lineDirection(0,1,0), pointOnLine(0,0,0), pointOnBlock(0);
PointOnLineConstraint *lineConstraint = new PointOnLineConstraint(ground, lineDirection, pointOnLine, *block, pointOnBlock);
osimModel.addConstraint(lineConstraint);
// Add PistonActuator between the first linkage and the block
Vec3 pointOnBodies(0);
PistonActuator *piston = new PistonActuator();
piston->setName("piston");
piston->setBodyA(linkage1);
piston->setBodyB(block);
piston->setPointA(pointOnBodies);
piston->setPointB(pointOnBodies);
piston->setOptimalForce(200.0);
piston->setPointsAreGlobal(false);
osimModel.addForce(piston);
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
// Added ControllableSpring between the first linkage and the second block
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
ControllableSpring *spring = new ControllableSpring;
spring->setName("spring");
spring->setBodyA(block);
spring->setBodyB(linkage1);
spring->setPointA(pointOnBodies);
spring->setPointB(pointOnBodies);
spring->setOptimalForce(2000.0);
spring->setPointsAreGlobal(false);
spring->setRestLength(0.8);
osimModel.addForce(spring);
// define the simulation times
double t0(0.0), tf(15);
// create a controller to control the piston and spring actuators
// the prescribed controller sets the controls as functions of time
PrescribedController *legController = new PrescribedController();
// give the legController control over all (two) model actuators
legController->setActuators(osimModel.updActuators());
// specify some control nodes for spring stiffness control
double t[] = {0.0, 4.0, 7.0, 10.0, 15.0};
double x[] = {1.0, 1.0, 0.25, 0.25, 5.0};
// specify the control function for each actuator
legController->prescribeControlForActuator("piston", new Constant(0.1));
legController->prescribeControlForActuator("spring", new PiecewiseLinearFunction(5, t, x));
// add the controller to the model
osimModel.addController(legController);
// define the acceleration due to gravity
osimModel.setGravity(Vec3(0, -9.80665, 0));
// enable the model visualizer see the model in action, which can be
// useful for debugging
osimModel.setUseVisualizer(false);
// Initialize system
SimTK::State& si = osimModel.initSystem();
// Pin joint initial states
double q1_i = -Pi/4;
double q2_i = - 2*q1_i;
CoordinateSet &coordinates = osimModel.updCoordinateSet();
coordinates[0].setValue(si, q1_i, true);
coordinates[1].setValue(si,q2_i, true);
// Setup integrator and manager
SimTK::RungeKuttaMersonIntegrator integrator(osimModel.getMultibodySystem());
integrator.setAccuracy(1.0e-3);
ForceReporter *forces = new ForceReporter(&osimModel);
osimModel.updAnalysisSet().adoptAndAppend(forces);
Manager manager(osimModel, integrator);
//Examine the model
osimModel.printDetailedInfo(si, std::cout);
// Save the model
osimModel.print("toyLeg.osim");
// Print out the initial position and velocity states
si.getQ().dump("Initial q's");
si.getU().dump("Initial u's");
std::cout << "Initial time: " << si.getTime() << std::endl;
// Integrate
manager.setInitialTime(t0);
manager.setFinalTime(tf);
std::cout<<"\n\nIntegrating from " << t0 << " to " << tf << std::endl;
manager.integrate(si);
// Save results
auto controlsTable = osimModel.getControlsTable();
STOFileAdapter::write(controlsTable, "SpringActuatedLeg_controls.sto");
auto statesTable = manager.getStatesTable();
osimModel.updSimbodyEngine().convertRadiansToDegrees(statesTable);
STOFileAdapter::write(statesTable,
"SpringActuatedLeg_states_degrees.sto");
auto forcesTable = forces->getForcesTable();
STOFileAdapter::write(forcesTable, "actuator_forces.sto");
}
catch (const std::exception& ex)
{
std::cout << "Exception in toyLeg_example: " << ex.what() << std::endl;
return 1;
}
std::cout << "Done." << std::endl;
return 0;
}
<commit_msg>update attachGeometry calls in toyLeg_example.cpp<commit_after>/* -------------------------------------------------------------------------- *
* OpenSim: toyLeg_example.cpp *
* -------------------------------------------------------------------------- *
* The OpenSim API is a toolkit for musculoskeletal modeling and simulation. *
* See http://opensim.stanford.edu and the NOTICE file for more information. *
* OpenSim is developed at Stanford University and supported by the US *
* National Institutes of Health (U54 GM072970, R24 HD065690) and by DARPA *
* through the Warrior Web program. *
* *
* Copyright (c) 2005-2012 Stanford University and the Authors *
* Author(s): Matt S. DeMers *
* *
* 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. *
* -------------------------------------------------------------------------- */
/*
* Below is an example of an OpenSim application that provides its own
* main() routine. This application acts as an example for utilizing the
* ControllabeSpring actuator.
*/
// Author: Matt DeMers
//==============================================================================
//==============================================================================
#include "PistonActuator.h"
#include "ControllableSpring.h"
#include <OpenSim/OpenSim.h>
#include "OpenSim/Common/STOFileAdapter.h"
using namespace OpenSim;
using namespace SimTK;
//______________________________________________________________________________
/**
* Run a simulation of block sliding with contact on by two muscles sliding with contact
*/
int main()
{
try {
// Create a new OpenSim model
Model osimModel;
osimModel.setName("osimModel");
osimModel.setAuthors("Matt DeMers");
double Pi = SimTK::Pi;
// Get the ground body
Ground& ground = osimModel.updGround();
ground.attachGeometry(new Mesh("checkered_floor.vtp"));
// create linkage body
double linkageMass = 0.001, linkageLength = 0.5, linkageDiameter = 0.06;
Vec3 linkageDimensions(linkageDiameter, linkageLength, linkageDiameter);
Vec3 linkageMassCenter(0,linkageLength/2,0);
Inertia linkageInertia = Inertia::cylinderAlongY(linkageDiameter/2.0, linkageLength/2.0);
OpenSim::Body* linkage1 = new OpenSim::Body("linkage1", linkageMass, linkageMassCenter, linkageMass*linkageInertia);
linkage1->attachGeometry(new Sphere(0.1));
// Graphical representation
Cylinder cyl(linkageDiameter/2, linkageLength);
Frame* cyl1Frame = new PhysicalOffsetFrame(*linkage1,
Transform(Vec3(0.0, linkageLength / 2.0, 0.0)));
cyl1Frame->setName("Cyl1_frame");
cyl1Frame->attachGeometry(cyl.clone());
osimModel.addFrame(cyl1Frame);
// Create a second linkage body as a clone of the first
OpenSim::Body* linkage2 = linkage1->clone();
linkage2->setName("linkage2");
Frame* cyl2Frame = new PhysicalOffsetFrame(*linkage2,
Transform(Vec3(0.0, linkageLength / 2.0, 0.0)));
cyl2Frame->setName("Cyl2_frame");
osimModel.addFrame(cyl2Frame);
(linkage2->upd_attached_geometry(0)).setFrameName("Cyl2_frame");
// Create a block to be the pelvis
double blockMass = 20.0, blockSideLength = 0.2;
Vec3 blockMassCenter(0);
Inertia blockInertia = blockMass*Inertia::brick(blockSideLength, blockSideLength, blockSideLength);
OpenSim::Body *block = new OpenSim::Body("block", blockMass, blockMassCenter, blockInertia);
block->attachGeometry(new Brick(SimTK::Vec3(0.05, 0.05, 0.05)));
// Create 1 degree-of-freedom pin joints between the bodies to create a kinematic chain from ground through the block
Vec3 orientationInGround(0), locationInGround(0), locationInParent(0.0, linkageLength, 0.0), orientationInChild(0), locationInChild(0);
PinJoint *ankle = new PinJoint("ankle", ground, locationInGround, orientationInGround, *linkage1,
locationInChild, orientationInChild);
PinJoint *knee = new PinJoint("knee", *linkage1, locationInParent, orientationInChild, *linkage2,
locationInChild, orientationInChild);
PinJoint *hip = new PinJoint("hip", *linkage2, locationInParent, orientationInChild, *block,
locationInChild, orientationInChild);
double range[2] = {-SimTK::Pi*2, SimTK::Pi*2};
CoordinateSet& ankleCoordinateSet = ankle->upd_CoordinateSet();
ankleCoordinateSet[0].setName("q1");
ankleCoordinateSet[0].setRange(range);
CoordinateSet& kneeCoordinateSet = knee->upd_CoordinateSet();
kneeCoordinateSet[0].setName("q2");
kneeCoordinateSet[0].setRange(range);
CoordinateSet& hipCoordinateSet = hip->upd_CoordinateSet();
hipCoordinateSet[0].setName("q3");
hipCoordinateSet[0].setRange(range);
// Add the bodies to the model
osimModel.addBody(linkage1);
osimModel.addBody(linkage2);
osimModel.addBody(block);
// Add the joints to the model
osimModel.addJoint(ankle);
osimModel.addJoint(knee);
osimModel.addJoint(hip);
// Define constraints on the model
// Add a point on line constraint to limit the block to vertical motion
Vec3 lineDirection(0,1,0), pointOnLine(0,0,0), pointOnBlock(0);
PointOnLineConstraint *lineConstraint = new PointOnLineConstraint(ground, lineDirection, pointOnLine, *block, pointOnBlock);
osimModel.addConstraint(lineConstraint);
// Add PistonActuator between the first linkage and the block
Vec3 pointOnBodies(0);
PistonActuator *piston = new PistonActuator();
piston->setName("piston");
piston->setBodyA(linkage1);
piston->setBodyB(block);
piston->setPointA(pointOnBodies);
piston->setPointB(pointOnBodies);
piston->setOptimalForce(200.0);
piston->setPointsAreGlobal(false);
osimModel.addForce(piston);
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
// Added ControllableSpring between the first linkage and the second block
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
ControllableSpring *spring = new ControllableSpring;
spring->setName("spring");
spring->setBodyA(block);
spring->setBodyB(linkage1);
spring->setPointA(pointOnBodies);
spring->setPointB(pointOnBodies);
spring->setOptimalForce(2000.0);
spring->setPointsAreGlobal(false);
spring->setRestLength(0.8);
osimModel.addForce(spring);
// define the simulation times
double t0(0.0), tf(15);
// create a controller to control the piston and spring actuators
// the prescribed controller sets the controls as functions of time
PrescribedController *legController = new PrescribedController();
// give the legController control over all (two) model actuators
legController->setActuators(osimModel.updActuators());
// specify some control nodes for spring stiffness control
double t[] = {0.0, 4.0, 7.0, 10.0, 15.0};
double x[] = {1.0, 1.0, 0.25, 0.25, 5.0};
// specify the control function for each actuator
legController->prescribeControlForActuator("piston", new Constant(0.1));
legController->prescribeControlForActuator("spring", new PiecewiseLinearFunction(5, t, x));
// add the controller to the model
osimModel.addController(legController);
// define the acceleration due to gravity
osimModel.setGravity(Vec3(0, -9.80665, 0));
// enable the model visualizer see the model in action, which can be
// useful for debugging
osimModel.setUseVisualizer(false);
// Initialize system
SimTK::State& si = osimModel.initSystem();
// Pin joint initial states
double q1_i = -Pi/4;
double q2_i = - 2*q1_i;
CoordinateSet &coordinates = osimModel.updCoordinateSet();
coordinates[0].setValue(si, q1_i, true);
coordinates[1].setValue(si,q2_i, true);
// Setup integrator and manager
SimTK::RungeKuttaMersonIntegrator integrator(osimModel.getMultibodySystem());
integrator.setAccuracy(1.0e-3);
ForceReporter *forces = new ForceReporter(&osimModel);
osimModel.updAnalysisSet().adoptAndAppend(forces);
Manager manager(osimModel, integrator);
//Examine the model
osimModel.printDetailedInfo(si, std::cout);
// Save the model
osimModel.print("toyLeg.osim");
// Print out the initial position and velocity states
si.getQ().dump("Initial q's");
si.getU().dump("Initial u's");
std::cout << "Initial time: " << si.getTime() << std::endl;
// Integrate
manager.setInitialTime(t0);
manager.setFinalTime(tf);
std::cout<<"\n\nIntegrating from " << t0 << " to " << tf << std::endl;
manager.integrate(si);
// Save results
auto controlsTable = osimModel.getControlsTable();
STOFileAdapter::write(controlsTable, "SpringActuatedLeg_controls.sto");
auto statesTable = manager.getStatesTable();
osimModel.updSimbodyEngine().convertRadiansToDegrees(statesTable);
STOFileAdapter::write(statesTable,
"SpringActuatedLeg_states_degrees.sto");
auto forcesTable = forces->getForcesTable();
STOFileAdapter::write(forcesTable, "actuator_forces.sto");
}
catch (const std::exception& ex)
{
std::cout << "Exception in toyLeg_example: " << ex.what() << std::endl;
return 1;
}
std::cout << "Done." << std::endl;
return 0;
}
<|endoftext|> |
<commit_before>/*
T0 DA for online calibration
Contact: [email protected]
Link: http://users.jyu.fi/~mioledzk/
Run Type: PHYSICS
DA Type: MON
Number of events needed: 500000
Input Files: inPhys.dat, external parameters
Output Files: daPhys.root, to be exported to the DAQ FXS
Trigger types used: PHYSICS_EVENT
------------------------------Alla
Now trigger type changed to CALICRATION_EVENT
to have data during test.
SOULD BE CHANGED BACK BEFORE BEAM
------------------------------- Alla
*/
#define FILE_OUT "daPhys.root"
#define FILE_IN "inPhys.dat"
#include <daqDA.h>
#include <event.h>
#include <monitor.h>
#include <Riostream.h>
#include <stdio.h>
#include <stdlib.h>
//AliRoot
#include <AliRawReaderDate.h>
#include <AliRawReader.h>
#include <AliT0RawReader.h>
//ROOT
#include "TROOT.h"
#include "TPluginManager.h"
#include "TFile.h"
#include "TKey.h"
#include "TObject.h"
#include "TBenchmark.h"
#include "TString.h"
#include "TH1.h"
int cbx, ccbx, t0bx, npmtA, npmtC;
float clx,cmx,cclx,ccmx, t0lx, t0hx;
/* Main routine
Arguments:
1- monitoring data source
*/
int main(int argc, char **argv) {
//int main(){
int status;
/* magic line */
gROOT->GetPluginManager()->AddHandler("TVirtualStreamerInfo",
"*",
"TStreamerInfo",
"RIO",
"TStreamerInfo()");
if(daqDA_DB_getFile(FILE_IN, FILE_IN)){
printf("Couldn't get input file >>inPhys.dat<< from DAQ_DB !!!\n");
return -1;
}
FILE *inp;
char c;
inp = fopen(FILE_IN, "r");
if(!inp){
printf("Input file >>inPhys.dat<< not found !!!\n");
return -1;
}
while((c=getc(inp))!=EOF) {
switch(c) {
case 'a': {fscanf(inp, "%d", &ccbx ); break;} //N of X bins hCFD1_CFD
case 'b': {fscanf(inp, "%f", &cclx ); break;} //Low x hCFD1_CFD
case 'c': {fscanf(inp, "%f", &ccmx ); break;} //High x hCFD1_CF
case 'd': {fscanf(inp, "%d", &npmtC ); break;} //number of reference PMTC
case 'e': {fscanf(inp, "%d", &npmtA ); break;} //number of reference PMTA
case 'f': {fscanf(inp, "%d", &t0bx ); break;} //N of X bins hT0
case 'g': {fscanf(inp, "%f", &t0lx ); break;} //Low x hT0
case 'k': {fscanf(inp, "%f", &t0hx ); break;} //High x hT0
}
}
fclose(inp);
if (argc!=2) {
printf("Wrong number of arguments\n");
return -1;
}
/* define data source : this is argument 1 */
status=monitorSetDataSource( argv[1] );
if (status!=0) {
printf("monitorSetDataSource() failed : %s\n",monitorDecodeError(status));
return -1;
}
/* declare monitoring program */
status=monitorDeclareMp( __FILE__ );
if (status!=0) {
printf("monitorDeclareMp() failed : %s\n",monitorDecodeError(status));
return -1;
}
/* define wait event timeout - 1s max */
monitorSetNowait();
monitorSetNoWaitNetworkTimeout(1000);
/* log start of process */
printf("T0 monitoring program started\n");
// Allocation of histograms - start
TH1F *hCFD1minCFD[24];
for(Int_t ic=0; ic<24; ic++) {
hCFD1minCFD[ic] = new TH1F(Form("CFD1minCFD%d",ic+1),"CFD-CFD",ccbx,cclx,ccmx);
}
TH1F *hVertex = new TH1F("hVertex","T0 time",t0bx,t0lx,t0hx);
// Allocation of histograms - end
Int_t iev=0;
/* main loop (infinite) */
for(;;) {
struct eventHeaderStruct *event;
eventTypeType eventT;
/* check shutdown condition */
if (daqDA_checkShutdown()) {break;}
/* get next event (blocking call until timeout) */
status=monitorGetEventDynamic((void **)&event);
if (status==(int)MON_ERR_EOF) {
printf ("End of File detected\n");
break; /* end of monitoring file has been reached */
}
if (status!=0) {
printf("monitorGetEventDynamic() failed : %s\n",monitorDecodeError(status));
break;
}
/* retry if got no event */
if (event==NULL) {
continue;
}
/* use event - here, just write event id to result file */
eventT=event->eventType;
switch (event->eventType){
case START_OF_RUN:
break;
case END_OF_RUN:
break;
case PHYSICS_EVENT:
// case CALIBRATION_EVENT:
iev++;
if(iev==1){
printf("First event - %i\n",iev);
}
// Initalize raw-data reading and decoding
AliRawReader *reader = new AliRawReaderDate((void*)event);
// Enable the following two lines in case of real-data
reader->RequireHeader(kTRUE);
AliT0RawReader *start = new AliT0RawReader(reader, kTRUE);
// Read raw data
Int_t allData[105][5];
for(Int_t i0=0;i0<105;i0++)
for(Int_t j0=0;j0<5;j0++)
allData[i0][j0] = 0;
if(start->Next()){
for (Int_t i=0; i<105; i++) {
for(Int_t iHit=0;iHit<5;iHit++){
allData[i][iHit]= start->GetData(i,iHit);
}
}
}
// Fill the histograms
Float_t besttimeA=9999999;
Float_t besttimeC=9999999;
Float_t time[24];
Float_t meanShift[24];
for (Int_t ik = 0; ik<24; ik++)
{
if(ik<12 && allData[ik+1][0]>0
&& (allData[ik+13][0]-allData[ik+1][0]) < 530 ){
hCFD1minCFD[ik]->Fill(allData[ik+1][0]-allData[npmtC][0]);
}
if(ik>11 && allData[ik+45][0]>0
&& (allData[ik+57][0]-allData[ik+45][0]) <530 ){
hCFD1minCFD[ik]->Fill(allData[ik+45][0]-allData[56+npmtA][0]);
}
if(iev == 10000) {
meanShift[ik] = hCFD1minCFD[ik]->GetMean();
}
}
//fill mean time _ fast reconstruction
if (iev > 10000 )
{
for (Int_t in=0; in<12; in++)
{
time[in] = allData[in+1][0] - meanShift[in] ;
time[in+12] = allData[in+56+1][0] ;
}
for (Int_t ipmt=0; ipmt<12; ipmt++){
if(time[ipmt] > 1 ) {
if(time[ipmt]<besttimeC)
besttimeC=time[ipmt]; //timeC
}
}
for ( Int_t ipmt=12; ipmt<24; ipmt++){
if(time[ipmt] > 1) {
if(time[ipmt]<besttimeA)
besttimeA=time[ipmt]; //timeA
}
}
if(besttimeA<9999999 &&besttimeC< 9999999) {
Float_t t0 =0.001* 24.4 * Float_t( besttimeA+besttimeC)/2.;
hVertex->Fill(t0);
}
}
delete start;
start = 0x0;
reader->Reset();
// End of fill histograms
}
/* free resources */
free(event);
/* exit when last event received, no need to wait for TERM signal */
if (eventT==END_OF_RUN) {
printf("EOR event detected\n");
printf("Number of events processed - %i\n ",iev);
break;
}
}
printf("After loop, before writing histos\n");
// write a file with the histograms
TFile *hist = new TFile(FILE_OUT,"RECREATE");
for(Int_t j=0;j<24;j++){
hCFD1minCFD[j]->Write();
}
hVertex->Write();
hist->Close();
delete hist;
status=0;
/* export file to FXS */
if (daqDA_FES_storeFile(FILE_OUT, "PHYSICS")) {
status=-2;
}
return status;
}
<commit_msg>DA with removing violations and tuned to coming data<commit_after>/*
T0 DA for online calibration
Contact: [email protected]
Link: http://users.jyu.fi/~mioledzk/
Run Type: PHYSICS
DA Type: MON
Number of events needed: 500000
Input Files: inPhys.dat, external parameters
Output Files: daPhys.root, to be exported to the DAQ FXS
Trigger types used: PHYSICS_EVENT
------------------------------Alla
Now trigger type changed to CALICRATION_EVENT
to have data during test.
SOULD BE CHANGED BACK BEFORE BEAM
------------------------------- Alla
*/
#define FILE_OUT "daPhys.root"
#define FILE_IN "inPhys.dat"
#include <daqDA.h>
#include <event.h>
#include <monitor.h>
#include <Riostream.h>
#include <stdio.h>
#include <stdlib.h>
//AliRoot
#include <AliRawReaderDate.h>
#include <AliRawReader.h>
#include <AliT0RawReader.h>
//ROOT
#include "TROOT.h"
#include "TPluginManager.h"
#include "TFile.h"
#include "TKey.h"
#include "TObject.h"
#include "TBenchmark.h"
#include "TString.h"
#include "TH1.h"
#include "TSpectrum.h"
#include "TMath.h"
int kbx, kcbx, kt0bx, knpmtA, knpmtC;
float klx,kmx,kclx,kcmx, kt0lx, kt0hx;
/* Main routine
Arguments:
1- monitoring data source
*/
int main(int argc, char **argv) {
//int main(){
int status;
/* magic line */
gROOT->GetPluginManager()->AddHandler("TVirtualStreamerInfo",
"*",
"TStreamerInfo",
"RIO",
"TStreamerInfo()");
if(daqDA_DB_getFile(FILE_IN, FILE_IN)){
printf("Couldn't get input file >>inPhys.dat<< from DAQ_DB !!!\n");
return -1;
}
FILE *inp;
char c;
inp = fopen(FILE_IN, "r");
if(!inp){
printf("Input file >>inPhys.dat<< not found !!!\n");
return -1;
}
while((c=getc(inp))!=EOF) {
switch(c) {
case 'a': {fscanf(inp, "%d", &kcbx ); break;} //N of X bins hCFD1_CFD
case 'b': {fscanf(inp, "%f", &kclx ); break;} //Low x hCFD1_CFD
case 'c': {fscanf(inp, "%f", &kcmx ); break;} //High x hCFD1_CF
case 'd': {fscanf(inp, "%d", &knpmtC ); break;} //number of reference PMTC
case 'e': {fscanf(inp, "%d", &knpmtA ); break;} //number of reference PMTA
case 'f': {fscanf(inp, "%d", &kt0bx ); break;} //N of X bins hT0
case 'g': {fscanf(inp, "%f", &kt0lx ); break;} //Low x hT0
case 'k': {fscanf(inp, "%f", &kt0hx ); break;} //High x hT0
}
}
fclose(inp);
if (argc!=2) {
printf("Wrong number of arguments\n");
return -1;
}
/* define data source : this is argument 1 */
status=monitorSetDataSource( argv[1] );
if (status!=0) {
printf("monitorSetDataSource() failed : %s\n",monitorDecodeError(status));
return -1;
}
/* declare monitoring program */
status=monitorDeclareMp( __FILE__ );
if (status!=0) {
printf("monitorDeclareMp() failed : %s\n",monitorDecodeError(status));
return -1;
}
/* define wait event timeout - 1s max */
monitorSetNowait();
monitorSetNoWaitNetworkTimeout(1000);
/* log start of process */
printf("T0 monitoring program started\n");
// Allocation of histograms - start
TH1F *hCFD1minCFD[24];
for(Int_t ic=0; ic<24; ic++) {
hCFD1minCFD[ic] = new TH1F(Form("CFD1minCFD%d",ic+1),"CFD-CFD",kcbx,kclx,kcmx);
}
TH1F *hVertex = new TH1F("hVertex","T0 time",kt0bx,kt0lx,kt0hx);
// Allocation of histograms - end
Int_t iev=0;
/* main loop (infinite) */
for(;;) {
struct eventHeaderStruct *event;
eventTypeType eventT;
/* check shutdown condition */
if (daqDA_checkShutdown()) {break;}
/* get next event (blocking call until timeout) */
status=monitorGetEventDynamic((void **)&event);
if (status==(int)MON_ERR_EOF) {
printf ("End of File detected\n");
break; /* end of monitoring file has been reached */
}
if (status!=0) {
printf("monitorGetEventDynamic() failed : %s\n",monitorDecodeError(status));
break;
}
/* retry if got no event */
if (event==NULL) {
continue;
}
/* use event - here, just write event id to result file */
eventT=event->eventType;
switch (event->eventType){
case START_OF_RUN:
break;
case END_OF_RUN:
break;
case PHYSICS_EVENT:
// case CALIBRATION_EVENT:
iev++;
if(iev==1){
printf("First event - %i\n",iev);
}
// Initalize raw-data reading and decoding
AliRawReader *reader = new AliRawReaderDate((void*)event);
// Enable the following two lines in case of real-data
reader->RequireHeader(kTRUE);
AliT0RawReader *start = new AliT0RawReader(reader, kTRUE);
// Read raw data
Int_t allData[105][5];
for(Int_t i0=0;i0<105;i0++)
for(Int_t j0=0;j0<5;j0++)
allData[i0][j0] = 0;
if(start->Next()){
for (Int_t i=0; i<105; i++) {
for(Int_t iHit=0;iHit<5;iHit++){
allData[i][iHit]= start->GetData(i,iHit);
}
}
}
// Fill the histograms
Float_t besttimeA=9999999;
Float_t besttimeC=9999999;
Float_t time[24];
Float_t meanShift[24];
for (Int_t ik = 0; ik<24; ik++)
{
if(ik<12 && allData[ik+1][0]>0 && allData[knpmtC][0]>0 ){
hCFD1minCFD[ik]->Fill(allData[ik+1][0]-allData[knpmtC][0]);
}
if(ik>11 && allData[ik+45][0]>0 && allData[56+knpmtA][0]>0 )
{
hCFD1minCFD[ik]->Fill(allData[ik+45][0]-allData[56+knpmtA][0]);
}
if(iev == 10000) {
meanShift[ik] = hCFD1minCFD[ik]->GetMean();
if(ik==knpmtC || ik==(56+knpmtA)) meanShift[ik]=0;
}
}
//fill mean time _ fast reconstruction
if (iev > 10000 )
{
for (Int_t in=0; in<12; in++)
{
time[in] = allData[in+1][0] - meanShift[in] ;
time[in+12] = allData[in+56+1][0] ;
}
for (Int_t ipmt=0; ipmt<12; ipmt++){
if(time[ipmt] > 1 ) {
if(time[ipmt]<besttimeC)
besttimeC=time[ipmt]; //timeC
}
}
for ( Int_t ipmt=12; ipmt<24; ipmt++){
if(time[ipmt] > 1) {
if(time[ipmt]<besttimeA)
besttimeA=time[ipmt]; //timeA
}
}
if(besttimeA<9999999 &&besttimeC< 9999999) {
Float_t t0 =0.001* 24.4 * Float_t( besttimeA+besttimeC)/2.;
hVertex->Fill(t0);
}
}
delete start;
start = 0x0;
reader->Reset();
// End of fill histograms
}
/* free resources */
free(event);
/* exit when last event received, no need to wait for TERM signal */
if (eventT==END_OF_RUN) {
printf("EOR event detected\n");
printf("Number of events processed - %i\n ",iev);
break;
}
}
printf("After loop, before writing histos\n");
// write a file with the histograms
TFile *hist = new TFile(FILE_OUT,"RECREATE");
for(Int_t j=0;j<24;j++){
hCFD1minCFD[j]->Write();
}
hVertex->Write();
hist->Close();
delete hist;
status=0;
/* export file to FXS */
if (daqDA_FES_storeFile(FILE_OUT, "PHYSICS")) {
status=-2;
}
return status;
}
<|endoftext|> |
<commit_before>#include "src/graphics.h"
#include "src/math.h"
#include <stdlib.h>
#include <sys/timeb.h>
typedef struct
{
Vector4f position;
Vector4f target;
Vector4f up;
Vector4f right;
Matrix4f view;
Matrix4f projection;
} Camera;
// Projection test
void testProjection(int scrWidth, int scrHeight)
{
unsigned short *keysPressed;
unsigned int elapsed, i,x,y;
struct timeb startTime, endTime;
Vector4f vs, rs;
Vector4f square[4];
Camera cam;
Matrix4f vp;
unsigned char *buffer = (unsigned char *)malloc(scrWidth*scrHeight);
cam.position.x = 0;
cam.position.y = 0;
cam.position.z = 1.f;
cam.position.w = 1.f;
cam.up.x = 0.f;
cam.up.y = 1.f;
cam.up.z = 0.f;
cam.up.w = 1.f;
cam.right.x = 1.f;
cam.right.y = 0.f;
cam.right.z = 0.f;
cam.right.w = 1.f;
cam.target.x = 0.f;
cam.target.y = 0.f;
cam.target.z = -1.f;
cam.target.w = 1.f;
if(!buffer)
{
printf("Out of memory!");
return;
}
keysPressed = translateInput();
while(!keysPressed[KEY_ESC])
{
for(i = 0; i < 4; i++)
{
square[i].x = 0 + 50*(i%2);
square[i].y = 0 + 50*(i > 1 ? 1 : 0);
square[i].z = -8.f;
square[i].w = 1.f;
}
matView(&cam.view, &cam.position, &cam.target, &cam.up);
matPerspective(&cam.projection, 75.f * M_PI /180.f, (float)scrWidth / (float)scrHeight, 0.1f, 5.f);
vp = matMul(&cam.view, &cam.projection);
matTranspose(&vp);
for(i = 0; i < 4; i++)
{
square[i] = matMulVec(&vp, &square[i]);
square[i].x /= square[i].w;
square[i].y /= square[i].w;
square[i].z /= square[i].w;
square[i].x = (square[i].x * (float)scrWidth) / (2.0f * square[i].w) + (scrWidth >> 1);
square[i].y = (square[i].y * (float)scrHeight) / (2.0f * square[i].w) + (scrHeight >> 1);
//printf("%.2f %.2f %.2f %.2f\n", square[i].x, square[i].y, square[i].z, square[i].w);
}
clrScrBuffer(buffer);
drawLine(square[0].x, square[0].y, square[1].x, square[1].y, 3, buffer);
drawLine(square[1].x, square[1].y, square[3].x, square[3].y, 3, buffer);
drawLine(square[0].x, square[0].y, square[2].x, square[2].y, 3, buffer);
drawLine(square[2].x, square[2].y, square[3].x, square[3].y, 3, buffer);
updateScreen(buffer);
keysPressed = translateInput();
vs = vecScale(&cam.target, 0.01f);
rs = vecScale(&cam.right, 0.1f);
if(keysPressed[KEY_W])
cam.position = vecAdd(&cam.position, &vs);
if(keysPressed[KEY_S])
cam.position = vecSub(&cam.position, &vs);
if(keysPressed[KEY_A])
cam.position = vecSub(&cam.position, &rs);
if(keysPressed[KEY_D])
cam.position = vecAdd(&cam.position, &rs);
if(keysPressed[KEY_LEFT])
{
rotateVecAxisAngle(&cam.target, 0.0001f, cam.up.x, cam.up.y, cam.up.z);
cam.right = crossProduct(&cam.target, &cam.up);
}
if(keysPressed[KEY_RIGHT])
{
rotateVecAxisAngle(&cam.target, -0.0001f, cam.up.x, cam.up.y, cam.up.z);
cam.right = crossProduct(&cam.target, &cam.up);
}
}
ftime(&startTime);
ftime(&endTime);
free(buffer);
elapsed = (endTime.time - startTime.time)*1000 + endTime.millitm - startTime.millitm;
do {
keysPressed = translateInput();
} while(keysPressed[KEY_ESC]);
}
<commit_msg>fixed perspective problems<commit_after>#include "src/graphics.h"
#include "src/math.h"
#include <stdlib.h>
#include <sys/timeb.h>
typedef struct
{
Vector4f position;
Vector4f target;
Vector4f up;
Vector4f right;
Matrix4f view;
Matrix4f projection;
} Camera;
// Projection test
void testProjection(int scrWidth, int scrHeight)
{
unsigned short *keysPressed;
unsigned int elapsed, i,x,y;
struct timeb startTime, endTime;
Vector4f vs, rs;
Vector4f square[4];
Camera cam;
Matrix4f vp;
unsigned char *buffer = (unsigned char *)malloc(scrWidth*scrHeight);
cam.position.x = 0;
cam.position.y = 0;
cam.position.z = 1.f;
cam.position.w = 1.f;
cam.up.x = 0.f;
cam.up.y = 1.f;
cam.up.z = 0.f;
cam.up.w = 1.f;
cam.right.x = 1.f;
cam.right.y = 0.f;
cam.right.z = 0.f;
cam.right.w = 1.f;
cam.target.x = 0.f;
cam.target.y = 0.f;
cam.target.z = -1.f;
cam.target.w = 1.f;
if(!buffer)
{
printf("Out of memory!");
return;
}
keysPressed = translateInput();
while(!keysPressed[KEY_ESC])
{
for(i = 0; i < 4; i++)
{
square[i].x = 0 + 50*(i%2);
square[i].y = 0 + 50*(i > 1 ? 1 : 0);
square[i].z = -80.f;
square[i].w = 1.f;
}
matView(&cam.view, &cam.position, &cam.target, &cam.up);
matPerspective(&cam.projection, 75.f * M_PI /180.f, (float)scrWidth / (float)scrHeight, 0.1f, 5.f);
vp = matMul(&cam.view, &cam.projection);
matTranspose(&vp);
for(i = 0; i < 4; i++)
{
square[i] = matMulVec(&vp, &square[i]);
// translate position to screen pixels
square[i].x = (square[i].x * (float)scrWidth) / (2.0f * square[i].w) + (scrWidth >> 1);
square[i].y = (square[i].y * (float)scrHeight) / (2.0f * square[i].w) + (scrHeight >> 1);
}
clrScrBuffer(buffer);
drawLine(square[0].x, square[0].y, square[1].x, square[1].y, 3, buffer);
drawLine(square[1].x, square[1].y, square[3].x, square[3].y, 3, buffer);
drawLine(square[0].x, square[0].y, square[2].x, square[2].y, 3, buffer);
drawLine(square[2].x, square[2].y, square[3].x, square[3].y, 3, buffer);
updateScreen(buffer);
keysPressed = translateInput();
vs = vecScale(&cam.target, 0.1f);
rs = vecScale(&cam.right, 0.1f);
if(keysPressed[KEY_W])
cam.position = vecAdd(&cam.position, &vs);
if(keysPressed[KEY_S])
cam.position = vecSub(&cam.position, &vs);
if(keysPressed[KEY_A])
cam.position = vecSub(&cam.position, &rs);
if(keysPressed[KEY_D])
cam.position = vecAdd(&cam.position, &rs);
if(keysPressed[KEY_LEFT])
{
rotateVecAxisAngle(&cam.target, 0.001f, cam.up.x, cam.up.y, cam.up.z);
cam.right = crossProduct(&cam.target, &cam.up);
}
if(keysPressed[KEY_RIGHT])
{
rotateVecAxisAngle(&cam.target, -0.001f, cam.up.x, cam.up.y, cam.up.z);
cam.right = crossProduct(&cam.target, &cam.up);
}
if(keysPressed[KEY_PGUP])
{
rotateVecAxisAngle(&cam.target, -0.001f, cam.right.x, cam.right.y, cam.right.z);
cam.right = crossProduct(&cam.target, &cam.up);
}
if(keysPressed[KEY_PGDN])
{
rotateVecAxisAngle(&cam.target, 0.001f, cam.right.x, cam.right.y, cam.right.z);
cam.up = crossProduct(&cam.right, &cam.target);
}
}
ftime(&startTime);
ftime(&endTime);
free(buffer);
elapsed = (endTime.time - startTime.time)*1000 + endTime.millitm - startTime.millitm;
do {
keysPressed = translateInput();
} while(keysPressed[KEY_ESC]);
}
<|endoftext|> |
<commit_before>#ifndef _CCTAG_DISTANCE_HPP_
#define _CCTAG_DISTANCE_HPP_
#include <cctag/geometry/Ellipse.hpp>
#include <boost/numeric/ublas/matrix.hpp>
#include <boost/math/special_functions/pow.hpp>
#include <boost/units/cmath.hpp>
#include <boost/foreach.hpp>
#include <boost/math/special_functions/pow.hpp>
namespace cctag {
namespace numerical {
namespace ublas = boost::numeric::ublas;
template<class T>
inline double distancePoints2D( const T& p1, const T& p2 ) // TODO modifier les accès, considérer p1, p2 comme des bounded_vector
{
return std::sqrt( (double)boost::math::pow<2>( p2.x() - p1.x() ) +
boost::math::pow<2>( p2.y() - p1.y() ) );
}
template<class T>
inline double powDistancePoints2D( const T& p1, const T& p2 ) // TODO modifier les accès, considérer p1, p2 comme des bounded_vector
{
return boost::math::pow<2>( p2.x() - p1.x() ) +
boost::math::pow<2>( p2.y() - p1.y() );
}
template<class T>
inline double distancePoints3D( const T& p1, const T& p2 ) // TODO modifier les accès, considérer p1, p2 comme des bounded_vector
{
return std::sqrt( (double)( p2.x() - p1.x() ) * ( p2.x() - p1.x() ) +
( p2.y() - p1.y() ) * ( p2.y() - p1.y() ) +
( p2.z() - p1.z() ) * ( p2.z() - p1.z() ) );
}
// Compute (point-polar) distance between a point and an ellipse represented by its 3x3 matrix.
inline double distancePointEllipse( const ublas::bounded_vector<double, 3>& p, const ublas::bounded_matrix<double, 3, 3> & Q, const double f )
{
ublas::bounded_vector<double, 6> aux( 6 );
aux( 0 ) = p( 0 ) * p( 0 );
aux( 1 ) = 2 * p( 0 ) * p( 1 );
aux( 2 ) = 2* f* p( 0 );
aux( 3 ) = p( 1 ) * p( 1 );
aux( 4 ) = 2* f* p( 1 );
aux( 5 ) = f * f;
//sdist = ([pts(:,1).*pts(:,1) 2*pts(:,1).*pts(:,2) pts(:,2).*pts(:,2) 2*f*pts(:,1) 2*f*pts(:,2) f*f*ones(n,1)]*Q([1;2;5;7;8;9])).^2./((pts*Q([1;2;3])).^2+(pts*Q([2;5;8])).^2);
double tmp1 = p( 0 ) * Q( 0, 0 ) + p( 1 ) * Q( 0, 1 ) + p( 2 ) * Q( 0, 2 );
double tmp2 = p( 0 ) * Q( 0, 1 ) + p( 1 ) * Q( 1, 1 ) + p( 2 ) * Q( 1, 2 );
double denom = tmp1 * tmp1 + tmp2 * tmp2;
ublas::bounded_vector<double, 6> qL;
qL( 0 ) = Q( 0, 0 ) ; qL( 1 ) = Q( 0, 1 ) ; qL( 2 ) = Q( 0, 2 ) ;
qL( 3 ) = Q( 1, 1 ) ; qL( 4 ) = Q( 1, 2 ) ;
qL( 5 ) = Q( 2, 2 );
return boost::math::pow<2>( ublas::inner_prod( aux, qL ) ) / denom;
}
inline double distancePointEllipse( const ublas::bounded_vector<double, 3>& p, const geometry::Ellipse& q, const double f )
{
const ublas::bounded_matrix<double, 3, 3>& Q = q.matrix();
return distancePointEllipse( p, Q, f );
}
// Compute the distance between points and an ellipse
//template<class T>
inline void distancePointEllipse( std::vector<double>& dist, const std::vector<ublas::bounded_vector<double, 3> >& pts, const geometry::Ellipse& q, const double f )
{
dist.clear();
dist.reserve( pts.size() );
typedef ublas::bounded_vector<double, 3> Point;
BOOST_FOREACH( const Point &p, pts )
{
dist.push_back( distancePointEllipse( p, q, f ) );
}
}
}
}
#endif
<commit_msg>Two template arguments for point to point distance.<commit_after>#ifndef _CCTAG_DISTANCE_HPP_
#define _CCTAG_DISTANCE_HPP_
#include <cctag/geometry/Ellipse.hpp>
#include <boost/numeric/ublas/matrix.hpp>
#include <boost/math/special_functions/pow.hpp>
#include <boost/units/cmath.hpp>
#include <boost/foreach.hpp>
#include <boost/math/special_functions/pow.hpp>
namespace cctag {
namespace numerical {
namespace ublas = boost::numeric::ublas;
template<class T, class U>
inline double distancePoints2D( const T& p1, const U& p2 ) // TODO modifier les accès, considérer p1, p2 comme des bounded_vector
{
return std::sqrt( (double)boost::math::pow<2>( p2.x() - p1.x() ) +
boost::math::pow<2>( p2.y() - p1.y() ) );
}
template<class T>
inline double powDistancePoints2D( const T& p1, const T& p2 ) // TODO modifier les accès, considérer p1, p2 comme des bounded_vector
{
return boost::math::pow<2>( p2.x() - p1.x() ) +
boost::math::pow<2>( p2.y() - p1.y() );
}
template<class T>
inline double distancePoints3D( const T& p1, const T& p2 ) // TODO modifier les accès, considérer p1, p2 comme des bounded_vector
{
return std::sqrt( (double)( p2.x() - p1.x() ) * ( p2.x() - p1.x() ) +
( p2.y() - p1.y() ) * ( p2.y() - p1.y() ) +
( p2.z() - p1.z() ) * ( p2.z() - p1.z() ) );
}
// Compute (point-polar) distance between a point and an ellipse represented by its 3x3 matrix.
inline double distancePointEllipse( const ublas::bounded_vector<double, 3>& p, const ublas::bounded_matrix<double, 3, 3> & Q, const double f )
{
ublas::bounded_vector<double, 6> aux( 6 );
aux( 0 ) = p( 0 ) * p( 0 );
aux( 1 ) = 2 * p( 0 ) * p( 1 );
aux( 2 ) = 2* f* p( 0 );
aux( 3 ) = p( 1 ) * p( 1 );
aux( 4 ) = 2* f* p( 1 );
aux( 5 ) = f * f;
//sdist = ([pts(:,1).*pts(:,1) 2*pts(:,1).*pts(:,2) pts(:,2).*pts(:,2) 2*f*pts(:,1) 2*f*pts(:,2) f*f*ones(n,1)]*Q([1;2;5;7;8;9])).^2./((pts*Q([1;2;3])).^2+(pts*Q([2;5;8])).^2);
double tmp1 = p( 0 ) * Q( 0, 0 ) + p( 1 ) * Q( 0, 1 ) + p( 2 ) * Q( 0, 2 );
double tmp2 = p( 0 ) * Q( 0, 1 ) + p( 1 ) * Q( 1, 1 ) + p( 2 ) * Q( 1, 2 );
double denom = tmp1 * tmp1 + tmp2 * tmp2;
ublas::bounded_vector<double, 6> qL;
qL( 0 ) = Q( 0, 0 ) ; qL( 1 ) = Q( 0, 1 ) ; qL( 2 ) = Q( 0, 2 ) ;
qL( 3 ) = Q( 1, 1 ) ; qL( 4 ) = Q( 1, 2 ) ;
qL( 5 ) = Q( 2, 2 );
return boost::math::pow<2>( ublas::inner_prod( aux, qL ) ) / denom;
}
inline double distancePointEllipse( const ublas::bounded_vector<double, 3>& p, const geometry::Ellipse& q, const double f )
{
const ublas::bounded_matrix<double, 3, 3>& Q = q.matrix();
return distancePointEllipse( p, Q, f );
}
// Compute the distance between points and an ellipse
//template<class T>
inline void distancePointEllipse( std::vector<double>& dist, const std::vector<ublas::bounded_vector<double, 3> >& pts, const geometry::Ellipse& q, const double f )
{
dist.clear();
dist.reserve( pts.size() );
typedef ublas::bounded_vector<double, 3> Point;
BOOST_FOREACH( const Point &p, pts )
{
dist.push_back( distancePointEllipse( p, q, f ) );
}
}
}
}
#endif
<|endoftext|> |
<commit_before>// Copyright 2018 The Ripple Authors
//
// 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 "init.h"
namespace mysql_ripple {
void Init(int argc, char** argv) {
}
} // namespace mysql_ripple
<commit_msg>Fix parsing of flags<commit_after>// Copyright 2018 The Ripple Authors
//
// 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 "init.h"
#include "flags.h"
namespace mysql_ripple {
void Init(int argc, char** argv) {
gflags::ParseCommandLineFlags(&argc, &argv, true);
}
} // namespace mysql_ripple
<|endoftext|> |
<commit_before>/****************** <VPR heading BEGIN do not edit this line> *****************
*
* VR Juggler Portable Runtime
*
* Original Authors:
* Allen Bierbaum, Patrick Hartling, Kevin Meinert, Carolina Cruz-Neira
*
* -----------------------------------------------------------------
* File: $RCSfile$
* Date modified: $Date$
* Version: $Revision$
* -----------------------------------------------------------------
*
****************** <VPR heading END do not edit this line> ******************/
/*************** <auto-copyright.pl BEGIN do not edit this line> **************
*
* VR Juggler is (C) Copyright 1998, 1999, 2000, 2001 by Iowa State University
*
* Original Authors:
* Allen Bierbaum, Christopher Just,
* Patrick Hartling, Kevin Meinert,
* Carolina Cruz-Neira, Albert Baker
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Library General Public
* License as published by the Free Software Foundation; either
* version 2 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
* Library General Public License for more details.
*
* You should have received a copy of the GNU Library 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.
*
*************** <auto-copyright.pl END do not edit this line> ***************/
#include <vpr/vprConfig.h>
#ifdef VPR_SIMULATOR
# include <vpr/md/SIM/Controller.h>
#endif
#include <vpr/Util/Interval.h>
#include <vpr/System.h>
const vpr::Interval vpr::Interval::NoWait(0,vpr::Interval::Base);
const vpr::Interval vpr::Interval::NoTimeout(0xffffffffUL, vpr::Interval::Base);
const vpr::Interval vpr::Interval::HalfPeriod((0xffffffffUL/2), vpr::Interval::Base);
namespace vpr
{
// Simulator-only version of vpr::Interval::setNow().
#ifdef VPR_SIMULATOR
void Interval::setNow()
{
mMicroSeconds = vpr::sim::Controller::instance()->getClock().getCurrentTime().getBaseVal();
}
#else
void Interval::setNow()
{
setNowReal();
}
#endif /* ifdef VPR_SIMULATOR */
//
// Real implementation of setNow that uses the real clock time from the system
//
void Interval::setNowReal()
{
#if defined(VPR_OS_Win32)
LARGE_INTEGER count;
LARGE_INTEGER counts_per_sec;
QueryPerformanceFrequency(&counts_per_sec);
vpr::Uint64 counts_per_sec64;
vpr::Uint64 counts_per_sec_high64;
counts_per_sec_high64 = counts_per_sec.HighPart;
counts_per_sec64 = counts_per_sec.LowPart;
counts_per_sec64 += (counts_per_sec_high64 << 32);
// XXX: Implement this
/* Sadly; nspr requires the interval to range from 1000 ticks per second
* to only 100000 ticks per second; QueryPerformanceCounter is too high
* resolution...
*/
if (QueryPerformanceCounter(&count))
{
const vpr::Uint64 microseconds_per_sec = 1000000u;
vpr::Uint64 low = count.LowPart;
vpr::Uint64 high = count.HighPart;
mMicroSeconds = low + (high << 32);
mMicroSeconds /= counts_per_sec64;
mMicroSeconds *= microseconds_per_sec;
// vpr::Int32 top = count.HighPart & _nt_highMask;
// top = top << (32 - _nt_bitShift);
// count.LowPart = count.LowPart >> _nt_bitShift;
// count.LowPart = count.LowPart + top;
// mMicroSeconds = count.LowPart;
}
/*
else
{
#if defined(__MINGW32__)
mMicroSeconds = time();
#elif defined(WIN16)
mMicroSeconds = clock(); // milliseconds since application start
#else
mMicroSeconds = GetTickCount(); // milliseconds since system start
#endif
}
*/
#else // Default to POSIX time setting
timeval cur_time;
vpr::System::gettimeofday(&cur_time);
mMicroSeconds = (cur_time.tv_usec + (1000000 * cur_time.tv_sec));
#endif
}
}; // namespace vpr
<commit_msg>Removed code copied from NSPR that we commented out.<commit_after>/****************** <VPR heading BEGIN do not edit this line> *****************
*
* VR Juggler Portable Runtime
*
* Original Authors:
* Allen Bierbaum, Patrick Hartling, Kevin Meinert, Carolina Cruz-Neira
*
* -----------------------------------------------------------------
* File: $RCSfile$
* Date modified: $Date$
* Version: $Revision$
* -----------------------------------------------------------------
*
****************** <VPR heading END do not edit this line> ******************/
/*************** <auto-copyright.pl BEGIN do not edit this line> **************
*
* VR Juggler is (C) Copyright 1998, 1999, 2000, 2001 by Iowa State University
*
* Original Authors:
* Allen Bierbaum, Christopher Just,
* Patrick Hartling, Kevin Meinert,
* Carolina Cruz-Neira, Albert Baker
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Library General Public
* License as published by the Free Software Foundation; either
* version 2 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
* Library General Public License for more details.
*
* You should have received a copy of the GNU Library 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.
*
*************** <auto-copyright.pl END do not edit this line> ***************/
#include <vpr/vprConfig.h>
#ifdef VPR_SIMULATOR
# include <vpr/md/SIM/Controller.h>
#endif
#include <vpr/Util/Interval.h>
#include <vpr/System.h>
const vpr::Interval vpr::Interval::NoWait(0,vpr::Interval::Base);
const vpr::Interval vpr::Interval::NoTimeout(0xffffffffUL, vpr::Interval::Base);
const vpr::Interval vpr::Interval::HalfPeriod((0xffffffffUL/2), vpr::Interval::Base);
namespace vpr
{
// Simulator-only version of vpr::Interval::setNow().
#ifdef VPR_SIMULATOR
void Interval::setNow()
{
mMicroSeconds = vpr::sim::Controller::instance()->getClock().getCurrentTime().getBaseVal();
}
#else
void Interval::setNow()
{
setNowReal();
}
#endif /* ifdef VPR_SIMULATOR */
//
// Real implementation of setNow that uses the real clock time from the system
//
void Interval::setNowReal()
{
#if defined(VPR_OS_Win32)
LARGE_INTEGER count;
LARGE_INTEGER counts_per_sec;
QueryPerformanceFrequency(&counts_per_sec);
vpr::Uint64 counts_per_sec64;
vpr::Uint64 counts_per_sec_high64;
counts_per_sec_high64 = counts_per_sec.HighPart;
counts_per_sec64 = counts_per_sec.LowPart;
counts_per_sec64 += (counts_per_sec_high64 << 32);
// XXX: Implement this
/* Sadly; nspr requires the interval to range from 1000 ticks per second
* to only 100000 ticks per second; QueryPerformanceCounter is too high
* resolution...
*/
if (QueryPerformanceCounter(&count))
{
const vpr::Uint64 microseconds_per_sec = 1000000u;
vpr::Uint64 low = count.LowPart;
vpr::Uint64 high = count.HighPart;
mMicroSeconds = low + (high << 32);
mMicroSeconds /= counts_per_sec64;
mMicroSeconds *= microseconds_per_sec;
}
/*
else
{
#if defined(__MINGW32__)
mMicroSeconds = time();
#elif defined(WIN16)
mMicroSeconds = clock(); // milliseconds since application start
#else
mMicroSeconds = GetTickCount(); // milliseconds since system start
#endif
}
*/
#else // Default to POSIX time setting
timeval cur_time;
vpr::System::gettimeofday(&cur_time);
mMicroSeconds = (cur_time.tv_usec + (1000000 * cur_time.tv_sec));
#endif
}
}; // namespace vpr
<|endoftext|> |
<commit_before>/**
* This file is part of the "FnordMetric" project
* Copyright (c) 2014 Paul Asmuth, Google Inc.
*
* FnordMetric is free software: you can redistribute it and/or modify it under
* the terms of the GNU General Public License v3.0. You should have received a
* copy of the GNU General Public License along with this program. If not, see
* <http://www.gnu.org/licenses/>.
*/
#include <stx/io/BufferedOutputStream.h>
#include <stx/io/fileutil.h>
#include <chartsql/runtime/groupby.h>
namespace csql {
GroupBy::GroupBy(
ScopedPtr<TableExpression> source,
const Vector<String>& column_names,
Vector<ScopedPtr<ValueExpression>> select_expressions,
Vector<ScopedPtr<ValueExpression>> group_expressions,
SHA1Hash qtree_fingerprint) :
source_(std::move(source)),
column_names_(column_names),
select_exprs_(std::move(select_expressions)),
group_exprs_(std::move(group_expressions)),
qtree_fingerprint_(qtree_fingerprint) {}
void GroupBy::execute(
ExecutionContext* context,
Function<bool (int argc, const SValue* argv)> fn) {
HashMap<String, Vector<VM::Instance >> groups;
ScratchMemory scratch;
try {
accumulate(&groups, &scratch, context);
getResult(&groups, fn);
} catch (...) {
freeResult(&groups);
throw;
}
freeResult(&groups);
}
void GroupBy::accumulate(
HashMap<String, Vector<VM::Instance >>* groups,
ScratchMemory* scratch,
ExecutionContext* context) {
auto cache_key = cacheKey();
String cache_filename;
bool from_cache = false;
auto cachedir = context->cacheDir();
if (!cache_key.isEmpty() && !cachedir.isEmpty()) {
cache_filename = FileUtil::joinPaths(
cachedir.get(),
cache_key.get().toString() + ".qcache");
if (FileUtil::exists(cache_filename)) {
auto fis = FileInputStream::openFile(cache_filename);
from_cache = decode(groups, scratch, fis.get());
}
}
if (!from_cache) {
source_->execute(
context,
std::bind(
&GroupBy::nextRow,
this,
groups,
scratch,
std::placeholders::_1,
std::placeholders::_2));
}
if (!from_cache && !cache_key.isEmpty() && !cachedir.isEmpty()) {
BufferedOutputStream fos(
FileOutputStream::fromFile(
File::openFile(
cache_filename + "~",
File::O_CREATEOROPEN | File::O_WRITE | File::O_TRUNCATE)));
encode(groups, &fos);
FileUtil::mv(cache_filename + "~", cache_filename);
}
}
void GroupBy::getResult(
const HashMap<String, Vector<VM::Instance >>* groups,
Function<bool (int argc, const SValue* argv)> fn) {
Vector<SValue> out_row(select_exprs_.size(), SValue{});
for (auto& group : *groups) {
for (size_t i = 0; i < select_exprs_.size(); ++i) {
select_exprs_[i]->result(&group.second[i], &out_row[i]);
}
if (!fn(out_row.size(), out_row.data())) {
return;
}
}
}
void GroupBy::freeResult(
HashMap<String, Vector<VM::Instance >>* groups) {
for (auto& group : (*groups)) {
for (size_t i = 0; i < select_exprs_.size(); ++i) {
select_exprs_[i]->freeInstance(&group.second[i]);
}
}
}
void GroupBy::mergeResult(
const HashMap<String, Vector<VM::Instance >>* src,
HashMap<String, Vector<VM::Instance >>* dst,
ScratchMemory* scratch) {
for (const auto& src_group : *src) {
auto& dst_group = (*dst)[src_group.first];
if (dst_group.size() == 0) {
for (const auto& e : select_exprs_) {
dst_group.emplace_back(e->allocInstance(scratch));
}
}
for (size_t i = 0; i < select_exprs_.size(); ++i) {
select_exprs_[i]->merge(&dst_group[i], &src_group.second[i]);
}
}
}
bool GroupBy::nextRow(
HashMap<String, Vector<VM::Instance >>* groups,
ScratchMemory* scratch,
int row_len, const SValue* row) {
Vector<SValue> gkey(group_exprs_.size(), SValue{});
for (size_t i = 0; i < group_exprs_.size(); ++i) {
group_exprs_[i]->evaluate(row_len, row, &gkey[i]);
}
auto group_key = SValue::makeUniqueKey(gkey.data(), gkey.size());
auto& group = (*groups)[group_key];
if (group.size() == 0) {
for (const auto& e : select_exprs_) {
group.emplace_back(e->allocInstance(scratch));
}
}
for (size_t i = 0; i < select_exprs_.size(); ++i) {
select_exprs_[i]->accumulate(&group[i], row_len, row);
}
return true;
}
Vector<String> GroupBy::columnNames() const {
return column_names_;
}
size_t GroupBy::numColumns() const {
return column_names_.size();
}
void GroupBy::encode(
const HashMap<String, Vector<VM::Instance >>* groups,
OutputStream* os) const {
os->appendVarUInt(groups->size());
os->appendVarUInt(select_exprs_.size());
for (auto& group : *groups) {
os->appendLenencString(group.first);
for (size_t i = 0; i < select_exprs_.size(); ++i) {
select_exprs_[i]->saveState(&group.second[i], os);
}
}
}
bool GroupBy::decode(
HashMap<String, Vector<VM::Instance >>* groups,
ScratchMemory* scratch,
InputStream* is) const {
auto ngroups = is->readVarUInt();
auto nexprs = is->readVarUInt();
if (select_exprs_.size() != nexprs) {
return false;
}
for (size_t j = 0; j < ngroups; ++j) {
auto group_key = is->readLenencString();
auto& group = (*groups)[group_key];
for (size_t i = 0; i < select_exprs_.size(); ++i) {
const auto& e = select_exprs_[i];
group.emplace_back(e->allocInstance(scratch));
e->loadState(&group[i], is);
}
}
return true;
}
Option<SHA1Hash> GroupBy::cacheKey() const {
auto source_key = source_->cacheKey();
if (source_key.isEmpty()) {
return None<SHA1Hash>();
}
return Some(
SHA1::compute(
StringUtil::format(
"$0~$1",
source_key.get().toString(),
qtree_fingerprint_.toString())));
}
}
<commit_msg>use new VM iface in GroupBy<commit_after>/**
* This file is part of the "FnordMetric" project
* Copyright (c) 2014 Paul Asmuth, Google Inc.
*
* FnordMetric is free software: you can redistribute it and/or modify it under
* the terms of the GNU General Public License v3.0. You should have received a
* copy of the GNU General Public License along with this program. If not, see
* <http://www.gnu.org/licenses/>.
*/
#include <stx/io/BufferedOutputStream.h>
#include <stx/io/fileutil.h>
#include <chartsql/runtime/groupby.h>
namespace csql {
GroupBy::GroupBy(
ScopedPtr<TableExpression> source,
const Vector<String>& column_names,
Vector<ScopedPtr<ValueExpression>> select_expressions,
Vector<ScopedPtr<ValueExpression>> group_expressions,
SHA1Hash qtree_fingerprint) :
source_(std::move(source)),
column_names_(column_names),
select_exprs_(std::move(select_expressions)),
group_exprs_(std::move(group_expressions)),
qtree_fingerprint_(qtree_fingerprint) {}
void GroupBy::execute(
ExecutionContext* context,
Function<bool (int argc, const SValue* argv)> fn) {
HashMap<String, Vector<VM::Instance >> groups;
ScratchMemory scratch;
try {
accumulate(&groups, &scratch, context);
getResult(&groups, fn);
} catch (...) {
freeResult(&groups);
throw;
}
freeResult(&groups);
}
void GroupBy::accumulate(
HashMap<String, Vector<VM::Instance >>* groups,
ScratchMemory* scratch,
ExecutionContext* context) {
auto cache_key = cacheKey();
String cache_filename;
bool from_cache = false;
auto cachedir = context->cacheDir();
if (!cache_key.isEmpty() && !cachedir.isEmpty()) {
cache_filename = FileUtil::joinPaths(
cachedir.get(),
cache_key.get().toString() + ".qcache");
if (FileUtil::exists(cache_filename)) {
auto fis = FileInputStream::openFile(cache_filename);
from_cache = decode(groups, scratch, fis.get());
}
}
if (!from_cache) {
source_->execute(
context,
std::bind(
&GroupBy::nextRow,
this,
groups,
scratch,
std::placeholders::_1,
std::placeholders::_2));
}
if (!from_cache && !cache_key.isEmpty() && !cachedir.isEmpty()) {
BufferedOutputStream fos(
FileOutputStream::fromFile(
File::openFile(
cache_filename + "~",
File::O_CREATEOROPEN | File::O_WRITE | File::O_TRUNCATE)));
encode(groups, &fos);
FileUtil::mv(cache_filename + "~", cache_filename);
}
}
void GroupBy::getResult(
const HashMap<String, Vector<VM::Instance >>* groups,
Function<bool (int argc, const SValue* argv)> fn) {
Vector<SValue> out_row(select_exprs_.size(), SValue{});
for (auto& group : *groups) {
for (size_t i = 0; i < select_exprs_.size(); ++i) {
VM::result(select_exprs_[i]->program(), &group.second[i], &out_row[i]);
}
if (!fn(out_row.size(), out_row.data())) {
return;
}
}
}
void GroupBy::freeResult(
HashMap<String, Vector<VM::Instance >>* groups) {
for (auto& group : (*groups)) {
for (size_t i = 0; i < select_exprs_.size(); ++i) {
VM::freeInstance(select_exprs_[i]->program(), &group.second[i]);
}
}
}
void GroupBy::mergeResult(
const HashMap<String, Vector<VM::Instance >>* src,
HashMap<String, Vector<VM::Instance >>* dst,
ScratchMemory* scratch) {
for (const auto& src_group : *src) {
auto& dst_group = (*dst)[src_group.first];
if (dst_group.size() == 0) {
for (const auto& e : select_exprs_) {
dst_group.emplace_back(VM::allocInstance(e->program(), scratch));
}
}
for (size_t i = 0; i < select_exprs_.size(); ++i) {
VM::merge(
select_exprs_[i]->program(),
&dst_group[i],
&src_group.second[i]);
}
}
}
bool GroupBy::nextRow(
HashMap<String, Vector<VM::Instance >>* groups,
ScratchMemory* scratch,
int row_len, const SValue* row) {
Vector<SValue> gkey(group_exprs_.size(), SValue{});
for (size_t i = 0; i < group_exprs_.size(); ++i) {
VM::evaluate(group_exprs_[i]->program(), row_len, row, &gkey[i]);
}
auto group_key = SValue::makeUniqueKey(gkey.data(), gkey.size());
auto& group = (*groups)[group_key];
if (group.size() == 0) {
for (const auto& e : select_exprs_) {
group.emplace_back(VM::allocInstance(e->program(), scratch));
}
}
for (size_t i = 0; i < select_exprs_.size(); ++i) {
VM::accumulate(select_exprs_[i]->program(), &group[i], row_len, row);
}
return true;
}
Vector<String> GroupBy::columnNames() const {
return column_names_;
}
size_t GroupBy::numColumns() const {
return column_names_.size();
}
void GroupBy::encode(
const HashMap<String, Vector<VM::Instance >>* groups,
OutputStream* os) const {
os->appendVarUInt(groups->size());
os->appendVarUInt(select_exprs_.size());
for (auto& group : *groups) {
os->appendLenencString(group.first);
for (size_t i = 0; i < select_exprs_.size(); ++i) {
VM::saveState(select_exprs_[i]->program(), &group.second[i], os);
}
}
}
bool GroupBy::decode(
HashMap<String, Vector<VM::Instance >>* groups,
ScratchMemory* scratch,
InputStream* is) const {
auto ngroups = is->readVarUInt();
auto nexprs = is->readVarUInt();
if (select_exprs_.size() != nexprs) {
return false;
}
for (size_t j = 0; j < ngroups; ++j) {
auto group_key = is->readLenencString();
auto& group = (*groups)[group_key];
for (size_t i = 0; i < select_exprs_.size(); ++i) {
const auto& e = select_exprs_[i];
group.emplace_back(VM::allocInstance(e->program(), scratch));
VM::loadState(e->program(), &group[i], is);
}
}
return true;
}
Option<SHA1Hash> GroupBy::cacheKey() const {
auto source_key = source_->cacheKey();
if (source_key.isEmpty()) {
return None<SHA1Hash>();
}
return Some(
SHA1::compute(
StringUtil::format(
"$0~$1",
source_key.get().toString(),
qtree_fingerprint_.toString())));
}
}
<|endoftext|> |
<commit_before>/*
* Copyright (C) 2015 Cloudius Systems, Ltd.
*/
#include <seastar/core/thread.hh>
#include "core/do_with.hh"
#include "cql_test_env.hh"
#include "cql3/query_processor.hh"
#include "cql3/query_options.hh"
#include "core/distributed.hh"
#include "core/shared_ptr.hh"
#include "utils/UUID_gen.hh"
#include "service/migration_manager.hh"
#include "message/messaging_service.hh"
#include "service/storage_service.hh"
#include "db/config.hh"
#include "db/batchlog_manager.hh"
#include "schema_builder.hh"
#include "init.hh"
class in_memory_cql_env : public cql_test_env {
public:
static auto constexpr ks_name = "ks";
private:
::shared_ptr<distributed<database>> _db;
::shared_ptr<distributed<cql3::query_processor>> _qp;
private:
struct core_local_state {
service::client_state client_state;
core_local_state()
: client_state(service::client_state::for_external_calls()) {
client_state.set_keyspace(ks_name);
}
future<> stop() {
return make_ready_future<>();
}
};
distributed<core_local_state> _core_local;
private:
auto make_query_state() {
return ::make_shared<service::query_state>(_core_local.local().client_state);
}
public:
in_memory_cql_env(
::shared_ptr<distributed<database>> db,
::shared_ptr<distributed<cql3::query_processor>> qp)
: _db(db)
, _qp(qp)
{ }
virtual future<::shared_ptr<transport::messages::result_message>> execute_cql(const sstring& text) override {
auto qs = make_query_state();
return _qp->local().process(text, *qs, cql3::query_options::DEFAULT).finally([qs] {});
}
virtual future<::shared_ptr<transport::messages::result_message>> execute_cql(
const sstring& text,
std::unique_ptr<cql3::query_options> qo) override
{
auto qs = make_query_state();
auto& lqo = *qo;
return _qp->local().process(text, *qs, lqo).finally([qs, qo = std::move(qo)] {});
}
virtual future<bytes> prepare(sstring query) override {
return _qp->invoke_on_all([query, this] (auto& local_qp) {
auto qs = this->make_query_state();
return local_qp.prepare(query, *qs).finally([qs] {}).discard_result();
}).then([query, this] {
return _qp->local().compute_id(query, ks_name);
});
}
virtual future<::shared_ptr<transport::messages::result_message>> execute_prepared(
bytes id,
std::vector<bytes_opt> values) override
{
auto prepared = _qp->local().get_prepared(id);
assert(bool(prepared));
auto stmt = prepared->statement;
assert(stmt->get_bound_terms() == values.size());
int32_t protocol_version = 3;
auto options = ::make_shared<cql3::query_options>(db::consistency_level::ONE, std::experimental::nullopt, std::move(values), std::move(std::vector<bytes_view_opt>{}), false,
cql3::query_options::specific_options::DEFAULT, protocol_version, serialization_format::use_32_bit());
options->prepare(prepared->bound_names);
auto qs = make_query_state();
return _qp->local().process_statement(stmt, *qs, *options)
.finally([options, qs] {});
}
virtual future<> create_table(std::function<schema(const sstring&)> schema_maker) override {
auto id = utils::UUID_gen::get_time_UUID();
return _db->invoke_on_all([schema_maker, id, this] (database& db) {
schema_builder builder(make_lw_shared(schema_maker(ks_name)));
builder.set_uuid(id);
auto cf_schema = builder.build(schema_builder::compact_storage::no);
auto& ks = db.find_keyspace(ks_name);
auto cfg = ks.make_column_family_config(*cf_schema);
db.add_column_family(std::move(cf_schema), std::move(cfg));
});
}
virtual future<> require_keyspace_exists(const sstring& ks_name) override {
auto& db = _db->local();
assert(db.has_keyspace(ks_name));
return make_ready_future<>();
}
virtual future<> require_table_exists(const sstring& ks_name, const sstring& table_name) override {
auto& db = _db->local();
assert(db.has_schema(ks_name, table_name));
return make_ready_future<>();
}
virtual future<> require_column_has_value(const sstring& table_name,
std::vector<boost::any> pk,
std::vector<boost::any> ck,
const sstring& column_name,
boost::any expected) override {
auto& db = _db->local();
auto& cf = db.find_column_family(ks_name, table_name);
auto schema = cf.schema();
auto pkey = partition_key::from_deeply_exploded(*schema, pk);
auto dk = dht::global_partitioner().decorate_key(*schema, pkey);
auto shard = db.shard_of(dk._token);
return _db->invoke_on(shard, [pkey = std::move(pkey),
ck = std::move(ck),
ks_name = std::move(ks_name),
column_name = std::move(column_name),
expected = std::move(expected),
table_name = std::move(table_name)] (database& db) mutable {
auto& cf = db.find_column_family(ks_name, table_name);
auto schema = cf.schema();
return cf.find_partition_slow(pkey).then([schema, ck, column_name, expected] (column_family::const_mutation_partition_ptr p) {
assert(p != nullptr);
auto row = p->find_row(clustering_key::from_deeply_exploded(*schema, ck));
assert(row != nullptr);
auto col_def = schema->get_column_definition(utf8_type->decompose(column_name));
assert(col_def != nullptr);
const atomic_cell_or_collection* cell = row->find_cell(col_def->id);
if (!cell) {
assert(((void)"column not set", 0));
}
bytes actual;
if (!col_def->type->is_multi_cell()) {
auto c = cell->as_atomic_cell();
assert(c.is_live());
actual = { c.value().begin(), c.value().end() };
} else {
auto c = cell->as_collection_mutation();
auto type = dynamic_pointer_cast<const collection_type_impl>(col_def->type);
actual = type->to_value(type->deserialize_mutation_form(c),
serialization_format::internal());
}
assert(col_def->type->equal(actual, col_def->type->decompose(expected)));
});
});
}
virtual database& local_db() override {
return _db->local();
}
cql3::query_processor& local_qp() override {
return _qp->local();
}
future<> start() {
return _core_local.start().then([this] () {
auto query = sprint("create keyspace %s with replication = { 'class' : 'org.apache.cassandra.locator.SimpleStrategy', 'replication_factor' : 1 };", sstring{ks_name});
return execute_cql(query).discard_result().then([] {
return make_ready_future<>();
});
});
}
virtual future<> stop() override {
return _core_local.stop().then([this] {
return db::get_batchlog_manager().stop().then([this] {
return _qp->stop().then([this] {
return service::get_migration_manager().stop().then([this] {
return service::get_storage_proxy().stop().then([this] {
return _db->stop().then([this] {
return locator::i_endpoint_snitch::stop_snitch();
});
});
});
});
});
});
}
};
future<> init_once(shared_ptr<distributed<database>> db) {
static bool done = false;
if (!done) {
done = true;
// FIXME: we leak db, since we're initializing the global storage_service with it.
new shared_ptr<distributed<database>>(db);
return init_storage_service(*db).then([] {
return init_ms_fd_gossiper("127.0.0.1", db::config::seed_provider_type());
});
} else {
return make_ready_future();
}
}
future<::shared_ptr<cql_test_env>> make_env_for_test() {
return locator::i_endpoint_snitch::create_snitch("SimpleSnitch").then([] {
auto db = ::make_shared<distributed<database>>();
return init_once(db).then([db] {
return seastar::async([db] {
auto cfg = make_lw_shared<db::config>();
cfg->data_file_directories() = {};
cfg->volatile_system_keyspace_for_testing() = true;
db->start(std::move(*cfg)).get();
distributed<service::storage_proxy>& proxy = service::get_storage_proxy();
distributed<service::migration_manager>& mm = service::get_migration_manager();
distributed<db::batchlog_manager>& bm = db::get_batchlog_manager();
auto qp = ::make_shared<distributed<cql3::query_processor>>();
proxy.start(std::ref(*db)).get();
mm.start().get();
qp->start(std::ref(proxy), std::ref(*db)).get();
db::system_keyspace::init_local_cache().get();
auto& ss = service::get_local_storage_service();
static bool storage_service_started = false;
if (!storage_service_started) {
storage_service_started = true;
ss.init_server().get();
}
bm.start(std::ref(*qp));
auto env = ::make_shared<in_memory_cql_env>(db, qp);
env->start().get();
return dynamic_pointer_cast<cql_test_env>(env);
});
});
});
}
future<> do_with_cql_env(std::function<future<>(cql_test_env&)> func) {
return make_env_for_test().then([func = std::move(func)] (auto e) mutable {
return do_with(std::move(func), [e] (auto& f) {
return f(*e);
}).finally([e] {
return e->stop().finally([e] {});
});
});
}
<commit_msg>tests/cql_env: make sure that value views are correct<commit_after>/*
* Copyright (C) 2015 Cloudius Systems, Ltd.
*/
#include <seastar/core/thread.hh>
#include "core/do_with.hh"
#include "cql_test_env.hh"
#include "cql3/query_processor.hh"
#include "cql3/query_options.hh"
#include "core/distributed.hh"
#include "core/shared_ptr.hh"
#include "utils/UUID_gen.hh"
#include "service/migration_manager.hh"
#include "message/messaging_service.hh"
#include "service/storage_service.hh"
#include "db/config.hh"
#include "db/batchlog_manager.hh"
#include "schema_builder.hh"
#include "init.hh"
class in_memory_cql_env : public cql_test_env {
public:
static auto constexpr ks_name = "ks";
private:
::shared_ptr<distributed<database>> _db;
::shared_ptr<distributed<cql3::query_processor>> _qp;
private:
struct core_local_state {
service::client_state client_state;
core_local_state()
: client_state(service::client_state::for_external_calls()) {
client_state.set_keyspace(ks_name);
}
future<> stop() {
return make_ready_future<>();
}
};
distributed<core_local_state> _core_local;
private:
auto make_query_state() {
return ::make_shared<service::query_state>(_core_local.local().client_state);
}
public:
in_memory_cql_env(
::shared_ptr<distributed<database>> db,
::shared_ptr<distributed<cql3::query_processor>> qp)
: _db(db)
, _qp(qp)
{ }
virtual future<::shared_ptr<transport::messages::result_message>> execute_cql(const sstring& text) override {
auto qs = make_query_state();
return _qp->local().process(text, *qs, cql3::query_options::DEFAULT).finally([qs] {});
}
virtual future<::shared_ptr<transport::messages::result_message>> execute_cql(
const sstring& text,
std::unique_ptr<cql3::query_options> qo) override
{
auto qs = make_query_state();
auto& lqo = *qo;
return _qp->local().process(text, *qs, lqo).finally([qs, qo = std::move(qo)] {});
}
virtual future<bytes> prepare(sstring query) override {
return _qp->invoke_on_all([query, this] (auto& local_qp) {
auto qs = this->make_query_state();
return local_qp.prepare(query, *qs).finally([qs] {}).discard_result();
}).then([query, this] {
return _qp->local().compute_id(query, ks_name);
});
}
virtual future<::shared_ptr<transport::messages::result_message>> execute_prepared(
bytes id,
std::vector<bytes_opt> values) override
{
auto prepared = _qp->local().get_prepared(id);
assert(bool(prepared));
auto stmt = prepared->statement;
assert(stmt->get_bound_terms() == values.size());
auto options = ::make_shared<cql3::query_options>(std::move(values));
options->prepare(prepared->bound_names);
auto qs = make_query_state();
return _qp->local().process_statement(stmt, *qs, *options)
.finally([options, qs] {});
}
virtual future<> create_table(std::function<schema(const sstring&)> schema_maker) override {
auto id = utils::UUID_gen::get_time_UUID();
return _db->invoke_on_all([schema_maker, id, this] (database& db) {
schema_builder builder(make_lw_shared(schema_maker(ks_name)));
builder.set_uuid(id);
auto cf_schema = builder.build(schema_builder::compact_storage::no);
auto& ks = db.find_keyspace(ks_name);
auto cfg = ks.make_column_family_config(*cf_schema);
db.add_column_family(std::move(cf_schema), std::move(cfg));
});
}
virtual future<> require_keyspace_exists(const sstring& ks_name) override {
auto& db = _db->local();
assert(db.has_keyspace(ks_name));
return make_ready_future<>();
}
virtual future<> require_table_exists(const sstring& ks_name, const sstring& table_name) override {
auto& db = _db->local();
assert(db.has_schema(ks_name, table_name));
return make_ready_future<>();
}
virtual future<> require_column_has_value(const sstring& table_name,
std::vector<boost::any> pk,
std::vector<boost::any> ck,
const sstring& column_name,
boost::any expected) override {
auto& db = _db->local();
auto& cf = db.find_column_family(ks_name, table_name);
auto schema = cf.schema();
auto pkey = partition_key::from_deeply_exploded(*schema, pk);
auto dk = dht::global_partitioner().decorate_key(*schema, pkey);
auto shard = db.shard_of(dk._token);
return _db->invoke_on(shard, [pkey = std::move(pkey),
ck = std::move(ck),
ks_name = std::move(ks_name),
column_name = std::move(column_name),
expected = std::move(expected),
table_name = std::move(table_name)] (database& db) mutable {
auto& cf = db.find_column_family(ks_name, table_name);
auto schema = cf.schema();
return cf.find_partition_slow(pkey).then([schema, ck, column_name, expected] (column_family::const_mutation_partition_ptr p) {
assert(p != nullptr);
auto row = p->find_row(clustering_key::from_deeply_exploded(*schema, ck));
assert(row != nullptr);
auto col_def = schema->get_column_definition(utf8_type->decompose(column_name));
assert(col_def != nullptr);
const atomic_cell_or_collection* cell = row->find_cell(col_def->id);
if (!cell) {
assert(((void)"column not set", 0));
}
bytes actual;
if (!col_def->type->is_multi_cell()) {
auto c = cell->as_atomic_cell();
assert(c.is_live());
actual = { c.value().begin(), c.value().end() };
} else {
auto c = cell->as_collection_mutation();
auto type = dynamic_pointer_cast<const collection_type_impl>(col_def->type);
actual = type->to_value(type->deserialize_mutation_form(c),
serialization_format::internal());
}
assert(col_def->type->equal(actual, col_def->type->decompose(expected)));
});
});
}
virtual database& local_db() override {
return _db->local();
}
cql3::query_processor& local_qp() override {
return _qp->local();
}
future<> start() {
return _core_local.start().then([this] () {
auto query = sprint("create keyspace %s with replication = { 'class' : 'org.apache.cassandra.locator.SimpleStrategy', 'replication_factor' : 1 };", sstring{ks_name});
return execute_cql(query).discard_result().then([] {
return make_ready_future<>();
});
});
}
virtual future<> stop() override {
return _core_local.stop().then([this] {
return db::get_batchlog_manager().stop().then([this] {
return _qp->stop().then([this] {
return service::get_migration_manager().stop().then([this] {
return service::get_storage_proxy().stop().then([this] {
return _db->stop().then([this] {
return locator::i_endpoint_snitch::stop_snitch();
});
});
});
});
});
});
}
};
future<> init_once(shared_ptr<distributed<database>> db) {
static bool done = false;
if (!done) {
done = true;
// FIXME: we leak db, since we're initializing the global storage_service with it.
new shared_ptr<distributed<database>>(db);
return init_storage_service(*db).then([] {
return init_ms_fd_gossiper("127.0.0.1", db::config::seed_provider_type());
});
} else {
return make_ready_future();
}
}
future<::shared_ptr<cql_test_env>> make_env_for_test() {
return locator::i_endpoint_snitch::create_snitch("SimpleSnitch").then([] {
auto db = ::make_shared<distributed<database>>();
return init_once(db).then([db] {
return seastar::async([db] {
auto cfg = make_lw_shared<db::config>();
cfg->data_file_directories() = {};
cfg->volatile_system_keyspace_for_testing() = true;
db->start(std::move(*cfg)).get();
distributed<service::storage_proxy>& proxy = service::get_storage_proxy();
distributed<service::migration_manager>& mm = service::get_migration_manager();
distributed<db::batchlog_manager>& bm = db::get_batchlog_manager();
auto qp = ::make_shared<distributed<cql3::query_processor>>();
proxy.start(std::ref(*db)).get();
mm.start().get();
qp->start(std::ref(proxy), std::ref(*db)).get();
db::system_keyspace::init_local_cache().get();
auto& ss = service::get_local_storage_service();
static bool storage_service_started = false;
if (!storage_service_started) {
storage_service_started = true;
ss.init_server().get();
}
bm.start(std::ref(*qp));
auto env = ::make_shared<in_memory_cql_env>(db, qp);
env->start().get();
return dynamic_pointer_cast<cql_test_env>(env);
});
});
});
}
future<> do_with_cql_env(std::function<future<>(cql_test_env&)> func) {
return make_env_for_test().then([func = std::move(func)] (auto e) mutable {
return do_with(std::move(func), [e] (auto& f) {
return f(*e);
}).finally([e] {
return e->stop().finally([e] {});
});
});
}
<|endoftext|> |
<commit_before>#ifndef CMDSTAN_WRITE_PROFILING_HPP
#define CMDSTAN_WRITE_PROFILING_HPP
#include <stan/math/rev/core/profiling.hpp>
#include <stan/callbacks/writer.hpp>
#include <stan/version.hpp>
#include <string>
#include <vector>
namespace cmdstan {
void write_profiling(stan::callbacks::writer& writer,
stan::math::profile_map& p) {
stan::math::profile_map::iterator it;
std::stringstream profile_csv_stream;
profile_csv_stream << "name,thread_id,time_total,forward_time,reverse_time,chain_stack_total,nochain_stack_total,autodiff_passes,no_autodiff_passes" << std::endl;
for (it = p.begin(); it != p.end(); it++) {
profile_csv_stream
// name
<< it->first.first << ","
// thread_id
<< it->first.second << "," //
// time_total
<< (it->second.get_fwd_time() + it->second.get_rev_time()) << ","
// forward_time
<< it->second.get_fwd_time() << ","
// reverse_time
<< it->second.get_rev_time() << ","
// chain_stack_total
<< it->second.get_chain_stack_used() << ","
// nochain_stack_total
<< it->second.get_nochain_stack_used() << ","
// autodiff_passes
<< it->second.get_num_rev_passes() << ","
// no_autodiff_passes
<< it->second.get_num_no_AD_fwd_passes()
<< std::endl;
}
writer(profile_csv_stream.str());
}
} // namespace cmdstan
#endif
<commit_msg>fix names<commit_after>#ifndef CMDSTAN_WRITE_PROFILING_HPP
#define CMDSTAN_WRITE_PROFILING_HPP
#include <stan/math/rev/core/profiling.hpp>
#include <stan/callbacks/writer.hpp>
#include <stan/version.hpp>
#include <string>
#include <vector>
namespace cmdstan {
void write_profiling(stan::callbacks::writer& writer,
stan::math::profile_map& p) {
stan::math::profile_map::iterator it;
std::stringstream profile_csv_stream;
profile_csv_stream << "name,thread_id,time,forward_time,reverse_time,chain_stack,no_chain_stack,autodiff_calls,no_autodiff_calls" << std::endl;
for (it = p.begin(); it != p.end(); it++) {
profile_csv_stream
// name
<< it->first.first << ","
// thread_id
<< it->first.second << "," //
// time_total
<< (it->second.get_fwd_time() + it->second.get_rev_time()) << ","
// forward_time
<< it->second.get_fwd_time() << ","
// reverse_time
<< it->second.get_rev_time() << ","
// chain_stack_total
<< it->second.get_chain_stack_used() << ","
// nochain_stack_total
<< it->second.get_nochain_stack_used() << ","
// autodiff_passes
<< it->second.get_num_rev_passes() << ","
// no_autodiff_passes
<< it->second.get_num_no_AD_fwd_passes()
<< std::endl;
}
writer(profile_csv_stream.str());
}
} // namespace cmdstan
#endif
<|endoftext|> |
<commit_before>#ifndef CMDSTAN_WRITE_PROFILING_HPP
#define CMDSTAN_WRITE_PROFILING_HPP
#include <stan/math/rev/core/profiling.hpp>
#include <stan/callbacks/writer.hpp>
#include <stan/version.hpp>
#include <string>
#include <vector>
namespace cmdstan {
/**
* Writes the data from the map of profiles in a CSV format
* to the supplied writer.
*
* @param writer object of a Stan writer class to write to.
* @param p reference to the map of profiles
*/
void write_profiling(stan::callbacks::writer& writer,
stan::math::profile_map& p) {
stan::math::profile_map::iterator it;
std::stringstream profile_csv_stream;
profile_csv_stream << "name,thread_id,time,forward_time,reverse_time,chain_"
"stack,no_chain_stack,autodiff_calls,no_autodiff_calls"
<< std::endl;
for (it = p.begin(); it != p.end(); it++) {
profile_csv_stream
<< it->first.first
<< ","
<< it->first.second
<< ","
<< (it->second.get_fwd_time() + it->second.get_rev_time())
<< ","
<< it->second.get_fwd_time()
<< ","
<< it->second.get_rev_time()
<< ","
<< it->second.get_chain_stack_used()
<< ","
<< it->second.get_nochain_stack_used()
<< ","
<< it->second.get_num_rev_passes()
<< ","
<< it->second.get_num_no_AD_fwd_passes() << std::endl;
}
writer(profile_csv_stream.str());
}
} // namespace cmdstan
#endif
<commit_msg>[Jenkins] auto-formatting by clang-format version 6.0.0-1ubuntu2~16.04.1 (tags/RELEASE_600/final)<commit_after>#ifndef CMDSTAN_WRITE_PROFILING_HPP
#define CMDSTAN_WRITE_PROFILING_HPP
#include <stan/math/rev/core/profiling.hpp>
#include <stan/callbacks/writer.hpp>
#include <stan/version.hpp>
#include <string>
#include <vector>
namespace cmdstan {
/**
* Writes the data from the map of profiles in a CSV format
* to the supplied writer.
*
* @param writer object of a Stan writer class to write to.
* @param p reference to the map of profiles
*/
void write_profiling(stan::callbacks::writer& writer,
stan::math::profile_map& p) {
stan::math::profile_map::iterator it;
std::stringstream profile_csv_stream;
profile_csv_stream << "name,thread_id,time,forward_time,reverse_time,chain_"
"stack,no_chain_stack,autodiff_calls,no_autodiff_calls"
<< std::endl;
for (it = p.begin(); it != p.end(); it++) {
profile_csv_stream << it->first.first << "," << it->first.second << ","
<< (it->second.get_fwd_time()
+ it->second.get_rev_time())
<< "," << it->second.get_fwd_time() << ","
<< it->second.get_rev_time() << ","
<< it->second.get_chain_stack_used() << ","
<< it->second.get_nochain_stack_used() << ","
<< it->second.get_num_rev_passes() << ","
<< it->second.get_num_no_AD_fwd_passes() << std::endl;
}
writer(profile_csv_stream.str());
}
} // namespace cmdstan
#endif
<|endoftext|> |
<commit_before>#ifndef VEXCL_UTIL_HPP
#define VEXCL_UTIL_HPP
/*
The MIT License
Copyright (c) 2012 Denis Demidov <[email protected]>
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.
*/
/**
* \file util.hpp
* \author Denis Demidov <[email protected]>
* \brief OpenCL general utilities.
*/
#ifdef WIN32
# pragma warning(push)
# pragma warning(disable : 4267 4290)
# define NOMINMAX
#endif
#ifndef __CL_ENABLE_EXCEPTIONS
# define __CL_ENABLE_EXCEPTIONS
#endif
#include <iostream>
#include <sstream>
#include <string>
#include <vector>
#include <map>
#include <algorithm>
#include <type_traits>
#include <functional>
#include <CL/cl.hpp>
#include <climits>
typedef unsigned int uint;
typedef unsigned char uchar;
namespace vex {
/// Convert typename to string.
template <class T> inline std::string type_name() { return "undefined_type"; }
template <> inline std::string type_name<float>() { return "float"; }
template <> inline std::string type_name<double>() { return "double"; }
template <> inline std::string type_name<int>() { return "int"; }
template <> inline std::string type_name<char>() { return "char"; }
template <> inline std::string type_name<bool>() { return "bool"; }
template <> inline std::string type_name<uint>() { return "unsigned int"; }
template <> inline std::string type_name<uchar>() { return "unsigned char"; }
#if (__WORDSIZE == 64) || defined(_WIN64)
template <> inline std::string type_name<size_t>() { return "ulong"; }
template <> inline std::string type_name<ptrdiff_t>() { return "long"; }
#endif
const std::string standard_kernel_header = std::string(
"#if defined(cl_khr_fp64)\n"
"# pragma OPENCL EXTENSION cl_khr_fp64: enable\n"
"#elif defined(cl_amd_fp64)\n"
"# pragma OPENCL EXTENSION cl_amd_fp64: enable\n"
"#endif\n"
);
/// \cond INTERNAL
/// Binary operations with their traits.
namespace binop {
enum kind {
Add,
Subtract,
Multiply,
Divide,
Remainder,
Greater,
Less,
GreaterEqual,
LessEqual,
Equal,
NotEqual,
BitwiseAnd,
BitwiseOr,
BitwiseXor,
LogicalAnd,
LogicalOr,
RightShift,
LeftShift
};
template <kind> struct traits {};
#define BOP_TRAITS(kind, op, nm) \
template <> struct traits<kind> { \
static std::string oper() { return op; } \
static std::string name() { return nm; } \
};
BOP_TRAITS(Add, "+", "Add_")
BOP_TRAITS(Subtract, "-", "Sub_")
BOP_TRAITS(Multiply, "*", "Mul_")
BOP_TRAITS(Divide, "/", "Div_")
BOP_TRAITS(Remainder, "%", "Mod_")
BOP_TRAITS(Greater, ">", "Gtr_")
BOP_TRAITS(Less, "<", "Lss_")
BOP_TRAITS(GreaterEqual, ">=", "Geq_")
BOP_TRAITS(LessEqual, "<=", "Leq_")
BOP_TRAITS(Equal, "==", "Equ_")
BOP_TRAITS(NotEqual, "!=", "Neq_")
BOP_TRAITS(BitwiseAnd, "&", "BAnd_")
BOP_TRAITS(BitwiseOr, "|", "BOr_")
BOP_TRAITS(BitwiseXor, "^", "BXor_")
BOP_TRAITS(LogicalAnd, "&&", "LAnd_")
BOP_TRAITS(LogicalOr, "||", "LOr_")
BOP_TRAITS(RightShift, ">>", "Rsh_")
BOP_TRAITS(LeftShift, "<<", "Lsh_")
#undef BOP_TRAITS
}
/// Return next power of 2.
inline size_t nextpow2(size_t x) {
--x;
x |= x >> 1U;
x |= x >> 2U;
x |= x >> 4U;
x |= x >> 8U;
x |= x >> 16U;
return ++x;
}
/// Align n to the next multiple of m.
inline size_t alignup(size_t n, size_t m = 16U) {
return n % m ? n - n % m + m : n;
}
/// Weights device wrt to vector performance.
/**
* Launches the following kernel on each device:
* \code
* a = b + c;
* \endcode
* where a, b and c are device vectors. Each device gets portion of the vector
* proportional to the performance of this operation.
*/
inline double device_vector_perf(
const cl::Context &context, const cl::Device &device
);
/// Weights device wrt to spmv performance.
/**
* Launches the following kernel on each device:
* \code
* y = A * x;
* \endcode
* where x and y are vectors, and A is matrix for 3D Poisson problem in square
* domain. Each device gets portion of the vector proportional to the
* performance of this operation.
*/
inline double device_spmv_perf(
const cl::Context &context, const cl::Device &device
);
/// Assigns equal weight to each device.
/**
* This results in equal partitioning.
*/
inline double equal_weights(
const cl::Context &context, const cl::Device &device
)
{
return 1;
}
/// Partitioning scheme for vectors and matrices.
/**
* Should be set once before any object of vector or matrix type is declared.
* Otherwise default parttioning function (partition_by_vector_perf) is
* selected.
*/
template <bool dummy = true>
struct partitioning_scheme {
typedef std::function<
double(const cl::Context&, const cl::Device&)
> weight_function;
static void set(weight_function f) {
if (!is_set) {
weight = f;
is_set = true;
} else {
std::cerr <<
"Warning: "
"device weighting function is already set and will be left as is."
<< std::endl;
}
}
static std::vector<size_t> get(size_t n, const std::vector<cl::CommandQueue> &queue);
private:
static bool is_set;
static weight_function weight;
static std::map<cl_device_id, double> device_weight;
};
template <bool dummy>
bool partitioning_scheme<dummy>::is_set = false;
template <bool dummy>
std::map<cl_device_id, double> partitioning_scheme<dummy>::device_weight;
template <bool dummy>
std::vector<size_t> partitioning_scheme<dummy>::get(size_t n,
const std::vector<cl::CommandQueue> &queue)
{
if (!is_set) {
weight = device_vector_perf;
is_set = true;
}
std::vector<size_t> part;
part.reserve(queue.size() + 1);
part.push_back(0);
if (queue.size() > 1) {
std::vector<double> cumsum;
cumsum.reserve(queue.size() + 1);
cumsum.push_back(0);
for(auto q = queue.begin(); q != queue.end(); q++) {
cl::Context context = q->getInfo<CL_QUEUE_CONTEXT>();
cl::Device device = q->getInfo<CL_QUEUE_DEVICE>();
auto dw = device_weight.find(device());
double w = (dw == device_weight.end()) ?
(device_weight[device()] = weight(context, device)) :
dw->second;
cumsum.push_back(cumsum.back() + w);
}
for(uint d = 1; d < queue.size(); d++)
part.push_back(
std::min(n,
alignup(static_cast<size_t>(n * cumsum[d] / cumsum.back()))
)
);
}
part.push_back(n);
return part;
}
template <bool dummy>
typename partitioning_scheme<dummy>::weight_function partitioning_scheme<dummy>::weight;
inline std::vector<size_t> partition(size_t n,
const std::vector<cl::CommandQueue> &queue)
{
return partitioning_scheme<true>::get(n, queue);
}
/// Create and build a program from source string.
inline cl::Program build_sources(
const cl::Context &context, const std::string &source
)
{
cl::Program program(context, cl::Program::Sources(
1, std::make_pair(source.c_str(), source.size())
));
auto device = context.getInfo<CL_CONTEXT_DEVICES>();
try {
program.build(device);
} catch(const cl::Error&) {
std::cerr << source
<< std::endl
<< program.getBuildInfo<CL_PROGRAM_BUILD_LOG>(device[0])
<< std::endl;
throw;
}
return program;
}
/// Get maximum possible workgroup size for given kernel.
inline uint kernel_workgroup_size(
const cl::Kernel &kernel,
const cl::Device &device
)
{
size_t wgsz = 1024U;
uint dev_wgsz = kernel.getWorkGroupInfo<CL_KERNEL_WORK_GROUP_SIZE>(device);
while(wgsz > dev_wgsz) wgsz /= 2;
return wgsz;
}
/// Shortcut for q.getInfo<CL_QUEUE_CONTEXT>()
inline cl::Context qctx(const cl::CommandQueue& q) {
cl::Context ctx;
q.getInfo(CL_QUEUE_CONTEXT, &ctx);
return ctx;
}
/// Shortcut for q.getInfo<CL_QUEUE_DEVICE>()
inline cl::Device qdev(const cl::CommandQueue& q) {
cl::Device dev;
q.getInfo(CL_QUEUE_DEVICE, &dev);
return dev;
}
} // namespace vex
/// Output description of an OpenCL error to a stream.
inline std::ostream& operator<<(std::ostream &os, const cl::Error &e) {
os << e.what() << "(";
switch (e.err()) {
case 0:
os << "Success";
break;
case -1:
os << "Device not found";
break;
case -2:
os << "Device not available";
break;
case -3:
os << "Compiler not available";
break;
case -4:
os << "Mem object allocation failure";
break;
case -5:
os << "Out of resources";
break;
case -6:
os << "Out of host memory";
break;
case -7:
os << "Profiling info not available";
break;
case -8:
os << "Mem copy overlap";
break;
case -9:
os << "Image format mismatch";
break;
case -10:
os << "Image format not supported";
break;
case -11:
os << "Build program failure";
break;
case -12:
os << "Map failure";
break;
case -13:
os << "Misaligned sub buffer offset";
break;
case -14:
os << "Exec status error for events in wait list";
break;
case -30:
os << "Invalid value";
break;
case -31:
os << "Invalid device type";
break;
case -32:
os << "Invalid platform";
break;
case -33:
os << "Invalid device";
break;
case -34:
os << "Invalid context";
break;
case -35:
os << "Invalid queue properties";
break;
case -36:
os << "Invalid command queue";
break;
case -37:
os << "Invalid host ptr";
break;
case -38:
os << "Invalid mem object";
break;
case -39:
os << "Invalid image format descriptor";
break;
case -40:
os << "Invalid image size";
break;
case -41:
os << "Invalid sampler";
break;
case -42:
os << "Invalid binary";
break;
case -43:
os << "Invalid build options";
break;
case -44:
os << "Invalid program";
break;
case -45:
os << "Invalid program executable";
break;
case -46:
os << "Invalid kernel name";
break;
case -47:
os << "Invalid kernel definition";
break;
case -48:
os << "Invalid kernel";
break;
case -49:
os << "Invalid arg index";
break;
case -50:
os << "Invalid arg value";
break;
case -51:
os << "Invalid arg size";
break;
case -52:
os << "Invalid kernel args";
break;
case -53:
os << "Invalid work dimension";
break;
case -54:
os << "Invalid work group size";
break;
case -55:
os << "Invalid work item size";
break;
case -56:
os << "Invalid global offset";
break;
case -57:
os << "Invalid event wait list";
break;
case -58:
os << "Invalid event";
break;
case -59:
os << "Invalid operation";
break;
case -60:
os << "Invalid gl object";
break;
case -61:
os << "Invalid buffer size";
break;
case -62:
os << "Invalid mip level";
break;
case -63:
os << "Invalid global work size";
break;
case -64:
os << "Invalid property";
break;
default:
os << "Unknown error";
break;
}
return os << ")";
}
#ifdef WIN32
# pragma warning(pop)
#endif
#endif
<commit_msg>doc update<commit_after>#ifndef VEXCL_UTIL_HPP
#define VEXCL_UTIL_HPP
/*
The MIT License
Copyright (c) 2012 Denis Demidov <[email protected]>
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.
*/
/**
* \file util.hpp
* \author Denis Demidov <[email protected]>
* \brief OpenCL general utilities.
*/
#ifdef WIN32
# pragma warning(push)
# pragma warning(disable : 4267 4290)
# define NOMINMAX
#endif
#ifndef __CL_ENABLE_EXCEPTIONS
# define __CL_ENABLE_EXCEPTIONS
#endif
#include <iostream>
#include <sstream>
#include <string>
#include <vector>
#include <map>
#include <algorithm>
#include <type_traits>
#include <functional>
#include <CL/cl.hpp>
#include <climits>
typedef unsigned int uint;
typedef unsigned char uchar;
namespace vex {
/// Convert typename to string.
template <class T> inline std::string type_name() { return "undefined_type"; }
template <> inline std::string type_name<float>() { return "float"; }
template <> inline std::string type_name<double>() { return "double"; }
template <> inline std::string type_name<int>() { return "int"; }
template <> inline std::string type_name<char>() { return "char"; }
template <> inline std::string type_name<bool>() { return "bool"; }
template <> inline std::string type_name<uint>() { return "unsigned int"; }
template <> inline std::string type_name<uchar>() { return "unsigned char"; }
#if (__WORDSIZE == 64) || defined(_WIN64)
template <> inline std::string type_name<size_t>() { return "ulong"; }
template <> inline std::string type_name<ptrdiff_t>() { return "long"; }
#endif
const std::string standard_kernel_header = std::string(
"#if defined(cl_khr_fp64)\n"
"# pragma OPENCL EXTENSION cl_khr_fp64: enable\n"
"#elif defined(cl_amd_fp64)\n"
"# pragma OPENCL EXTENSION cl_amd_fp64: enable\n"
"#endif\n"
);
/// \cond INTERNAL
/// Binary operations with their traits.
namespace binop {
enum kind {
Add,
Subtract,
Multiply,
Divide,
Remainder,
Greater,
Less,
GreaterEqual,
LessEqual,
Equal,
NotEqual,
BitwiseAnd,
BitwiseOr,
BitwiseXor,
LogicalAnd,
LogicalOr,
RightShift,
LeftShift
};
template <kind> struct traits {};
#define BOP_TRAITS(kind, op, nm) \
template <> struct traits<kind> { \
static std::string oper() { return op; } \
static std::string name() { return nm; } \
};
BOP_TRAITS(Add, "+", "Add_")
BOP_TRAITS(Subtract, "-", "Sub_")
BOP_TRAITS(Multiply, "*", "Mul_")
BOP_TRAITS(Divide, "/", "Div_")
BOP_TRAITS(Remainder, "%", "Mod_")
BOP_TRAITS(Greater, ">", "Gtr_")
BOP_TRAITS(Less, "<", "Lss_")
BOP_TRAITS(GreaterEqual, ">=", "Geq_")
BOP_TRAITS(LessEqual, "<=", "Leq_")
BOP_TRAITS(Equal, "==", "Equ_")
BOP_TRAITS(NotEqual, "!=", "Neq_")
BOP_TRAITS(BitwiseAnd, "&", "BAnd_")
BOP_TRAITS(BitwiseOr, "|", "BOr_")
BOP_TRAITS(BitwiseXor, "^", "BXor_")
BOP_TRAITS(LogicalAnd, "&&", "LAnd_")
BOP_TRAITS(LogicalOr, "||", "LOr_")
BOP_TRAITS(RightShift, ">>", "Rsh_")
BOP_TRAITS(LeftShift, "<<", "Lsh_")
#undef BOP_TRAITS
}
/// \endcond
/// Return next power of 2.
inline size_t nextpow2(size_t x) {
--x;
x |= x >> 1U;
x |= x >> 2U;
x |= x >> 4U;
x |= x >> 8U;
x |= x >> 16U;
return ++x;
}
/// Align n to the next multiple of m.
inline size_t alignup(size_t n, size_t m = 16U) {
return n % m ? n - n % m + m : n;
}
/// Weights device wrt to vector performance.
/**
* Launches the following kernel on each device:
* \code
* a = b + c;
* \endcode
* where a, b and c are device vectors. Each device gets portion of the vector
* proportional to the performance of this operation.
*/
inline double device_vector_perf(
const cl::Context &context, const cl::Device &device
);
/// Weights device wrt to spmv performance.
/**
* Launches the following kernel on each device:
* \code
* y = A * x;
* \endcode
* where x and y are vectors, and A is matrix for 3D Poisson problem in square
* domain. Each device gets portion of the vector proportional to the
* performance of this operation.
*/
inline double device_spmv_perf(
const cl::Context &context, const cl::Device &device
);
/// Assigns equal weight to each device.
/**
* This results in equal partitioning.
*/
inline double equal_weights(
const cl::Context &context, const cl::Device &device
)
{
return 1;
}
/// Partitioning scheme for vectors and matrices.
/**
* Should be set once before any object of vector or matrix type is declared.
* Otherwise default parttioning function (partition_by_vector_perf) is
* selected.
*/
template <bool dummy = true>
struct partitioning_scheme {
typedef std::function<
double(const cl::Context&, const cl::Device&)
> weight_function;
static void set(weight_function f) {
if (!is_set) {
weight = f;
is_set = true;
} else {
std::cerr <<
"Warning: "
"device weighting function is already set and will be left as is."
<< std::endl;
}
}
static std::vector<size_t> get(size_t n, const std::vector<cl::CommandQueue> &queue);
private:
static bool is_set;
static weight_function weight;
static std::map<cl_device_id, double> device_weight;
};
template <bool dummy>
bool partitioning_scheme<dummy>::is_set = false;
template <bool dummy>
std::map<cl_device_id, double> partitioning_scheme<dummy>::device_weight;
template <bool dummy>
std::vector<size_t> partitioning_scheme<dummy>::get(size_t n,
const std::vector<cl::CommandQueue> &queue)
{
if (!is_set) {
weight = device_vector_perf;
is_set = true;
}
std::vector<size_t> part;
part.reserve(queue.size() + 1);
part.push_back(0);
if (queue.size() > 1) {
std::vector<double> cumsum;
cumsum.reserve(queue.size() + 1);
cumsum.push_back(0);
for(auto q = queue.begin(); q != queue.end(); q++) {
cl::Context context = q->getInfo<CL_QUEUE_CONTEXT>();
cl::Device device = q->getInfo<CL_QUEUE_DEVICE>();
auto dw = device_weight.find(device());
double w = (dw == device_weight.end()) ?
(device_weight[device()] = weight(context, device)) :
dw->second;
cumsum.push_back(cumsum.back() + w);
}
for(uint d = 1; d < queue.size(); d++)
part.push_back(
std::min(n,
alignup(static_cast<size_t>(n * cumsum[d] / cumsum.back()))
)
);
}
part.push_back(n);
return part;
}
template <bool dummy>
typename partitioning_scheme<dummy>::weight_function partitioning_scheme<dummy>::weight;
inline std::vector<size_t> partition(size_t n,
const std::vector<cl::CommandQueue> &queue)
{
return partitioning_scheme<true>::get(n, queue);
}
/// Create and build a program from source string.
inline cl::Program build_sources(
const cl::Context &context, const std::string &source
)
{
cl::Program program(context, cl::Program::Sources(
1, std::make_pair(source.c_str(), source.size())
));
auto device = context.getInfo<CL_CONTEXT_DEVICES>();
try {
program.build(device);
} catch(const cl::Error&) {
std::cerr << source
<< std::endl
<< program.getBuildInfo<CL_PROGRAM_BUILD_LOG>(device[0])
<< std::endl;
throw;
}
return program;
}
/// Get maximum possible workgroup size for given kernel.
inline uint kernel_workgroup_size(
const cl::Kernel &kernel,
const cl::Device &device
)
{
size_t wgsz = 1024U;
uint dev_wgsz = kernel.getWorkGroupInfo<CL_KERNEL_WORK_GROUP_SIZE>(device);
while(wgsz > dev_wgsz) wgsz /= 2;
return wgsz;
}
/// Shortcut for q.getInfo<CL_QUEUE_CONTEXT>()
inline cl::Context qctx(const cl::CommandQueue& q) {
cl::Context ctx;
q.getInfo(CL_QUEUE_CONTEXT, &ctx);
return ctx;
}
/// Shortcut for q.getInfo<CL_QUEUE_DEVICE>()
inline cl::Device qdev(const cl::CommandQueue& q) {
cl::Device dev;
q.getInfo(CL_QUEUE_DEVICE, &dev);
return dev;
}
} // namespace vex
/// Output description of an OpenCL error to a stream.
inline std::ostream& operator<<(std::ostream &os, const cl::Error &e) {
os << e.what() << "(";
switch (e.err()) {
case 0:
os << "Success";
break;
case -1:
os << "Device not found";
break;
case -2:
os << "Device not available";
break;
case -3:
os << "Compiler not available";
break;
case -4:
os << "Mem object allocation failure";
break;
case -5:
os << "Out of resources";
break;
case -6:
os << "Out of host memory";
break;
case -7:
os << "Profiling info not available";
break;
case -8:
os << "Mem copy overlap";
break;
case -9:
os << "Image format mismatch";
break;
case -10:
os << "Image format not supported";
break;
case -11:
os << "Build program failure";
break;
case -12:
os << "Map failure";
break;
case -13:
os << "Misaligned sub buffer offset";
break;
case -14:
os << "Exec status error for events in wait list";
break;
case -30:
os << "Invalid value";
break;
case -31:
os << "Invalid device type";
break;
case -32:
os << "Invalid platform";
break;
case -33:
os << "Invalid device";
break;
case -34:
os << "Invalid context";
break;
case -35:
os << "Invalid queue properties";
break;
case -36:
os << "Invalid command queue";
break;
case -37:
os << "Invalid host ptr";
break;
case -38:
os << "Invalid mem object";
break;
case -39:
os << "Invalid image format descriptor";
break;
case -40:
os << "Invalid image size";
break;
case -41:
os << "Invalid sampler";
break;
case -42:
os << "Invalid binary";
break;
case -43:
os << "Invalid build options";
break;
case -44:
os << "Invalid program";
break;
case -45:
os << "Invalid program executable";
break;
case -46:
os << "Invalid kernel name";
break;
case -47:
os << "Invalid kernel definition";
break;
case -48:
os << "Invalid kernel";
break;
case -49:
os << "Invalid arg index";
break;
case -50:
os << "Invalid arg value";
break;
case -51:
os << "Invalid arg size";
break;
case -52:
os << "Invalid kernel args";
break;
case -53:
os << "Invalid work dimension";
break;
case -54:
os << "Invalid work group size";
break;
case -55:
os << "Invalid work item size";
break;
case -56:
os << "Invalid global offset";
break;
case -57:
os << "Invalid event wait list";
break;
case -58:
os << "Invalid event";
break;
case -59:
os << "Invalid operation";
break;
case -60:
os << "Invalid gl object";
break;
case -61:
os << "Invalid buffer size";
break;
case -62:
os << "Invalid mip level";
break;
case -63:
os << "Invalid global work size";
break;
case -64:
os << "Invalid property";
break;
default:
os << "Unknown error";
break;
}
return os << ")";
}
#ifdef WIN32
# pragma warning(pop)
#endif
#endif
<|endoftext|> |
<commit_before>//
// The MIT License (MIT)
//
// Copyright (c) 2016 Tag Games Limited
//
// 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 <CSBackend/Rendering/OpenGL/Material/GLMaterial.h>
#include <CSBackend/Rendering/OpenGL/Camera/GLCamera.h>
#include <CSBackend/Rendering/OpenGL/Shader/GLShader.h>
#include <ChilliSource/Core/Base/Colour.h>
#include <ChilliSource/Rendering/Base/BlendMode.h>
#include <ChilliSource/Rendering/Base/StencilOp.h>
#include <ChilliSource/Rendering/Base/TestFunc.h>
#include <ChilliSource/Rendering/Material/RenderMaterial.h>
namespace CSBackend
{
namespace OpenGL
{
namespace
{
const std::string k_uniformEmissive = "u_emissive";
const std::string k_uniformAmbient = "u_ambient";
const std::string k_uniformDiffuse = "u_diffuse";
const std::string k_uniformSpecular = "u_specular";
const std::string k_uniformTexturePrefix = "u_texture";
const std::string k_uniformCubemapPrefix = "u_cubemap";
/// Converts from a ChilliSource blend mode to an OpenGL blend mode.
///
/// @param blendMode
/// The ChilliSource blend mode.
///
/// @return The OpenGL blend mode.
///
GLenum ToGLBlendMode(ChilliSource::BlendMode blendMode)
{
switch(blendMode)
{
case ChilliSource::BlendMode::k_zero:
return GL_ZERO;
case ChilliSource::BlendMode::k_one:
return GL_ONE;
case ChilliSource::BlendMode::k_sourceCol:
return GL_SRC_COLOR;
case ChilliSource::BlendMode::k_oneMinusSourceCol:
return GL_ONE_MINUS_SRC_COLOR;
case ChilliSource::BlendMode::k_sourceAlpha:
return GL_SRC_ALPHA;
case ChilliSource::BlendMode::k_oneMinusSourceAlpha:
return GL_ONE_MINUS_SRC_ALPHA;
case ChilliSource::BlendMode::k_destCol:
return GL_DST_COLOR;
case ChilliSource::BlendMode::k_oneMinusDestCol:
return GL_ONE_MINUS_DST_COLOR;
case ChilliSource::BlendMode::k_destAlpha:
return GL_DST_ALPHA;
case ChilliSource::BlendMode::k_oneMinusDestAlpha:
return GL_ONE_MINUS_DST_ALPHA;
default:
CS_LOG_FATAL("Invalid blend mode.");
return GL_ZERO;
};
}
/// Converts from a ChilliSource stencil op to an OpenGL one
///
/// @param stencilOp
/// The ChilliSource stencil op
///
/// @return The OpenGL stencil op.
///
GLenum ToGLStencilOp(ChilliSource::StencilOp stencilOp)
{
switch(stencilOp)
{
case ChilliSource::StencilOp::k_keep:
return GL_KEEP;
case ChilliSource::StencilOp::k_zero:
return GL_ZERO;
case ChilliSource::StencilOp::k_replace:
return GL_REPLACE;
case ChilliSource::StencilOp::k_increment:
return GL_INCR;
case ChilliSource::StencilOp::k_incrementWrap:
return GL_INCR_WRAP;
case ChilliSource::StencilOp::k_decrement:
return GL_DECR;
case ChilliSource::StencilOp::k_decrementWrap:
return GL_DECR_WRAP;
case ChilliSource::StencilOp::k_invert:
return GL_INVERT;
default:
CS_LOG_FATAL("Invalid stencil op.");
return GL_KEEP;
};
}
/// Converts from a ChilliSource test func to an OpenGL one
///
/// @param testFunc
/// The ChilliSource test func
///
/// @return The OpenGL test func.
///
GLenum ToGLTestFunc(ChilliSource::TestFunc testFunc)
{
switch(testFunc)
{
case ChilliSource::TestFunc::k_never:
return GL_NEVER;
case ChilliSource::TestFunc::k_less:
return GL_LESS;
case ChilliSource::TestFunc::k_lessEqual:
return GL_LEQUAL;
case ChilliSource::TestFunc::k_greater:
return GL_GREATER;
case ChilliSource::TestFunc::k_greaterEqual:
return GL_GEQUAL;
case ChilliSource::TestFunc::k_equal:
return GL_EQUAL;
case ChilliSource::TestFunc::k_notEqual:
return GL_NOTEQUAL;
case ChilliSource::TestFunc::k_always:
return GL_ALWAYS;
default:
CS_LOG_FATAL("Invalid test func.");
return GL_ALWAYS;
};
}
/// Applies the given batch of custom shader variables to the given shader. If
/// any of the variables do not exist in the shader, this will assert.
///
/// @param renderShaderVariables
/// The shader variables to apply.
/// @param glShader
/// The shader to apply the variables to.
///
void ApplyCustomShaderVariables(const ChilliSource::RenderShaderVariables* renderShaderVariables, GLShader* glShader) noexcept
{
CS_ASSERT(renderShaderVariables, "Cannot apply null shader variables.");
CS_ASSERT(glShader, "Cannot apply shader variables to null shader.");
for (const auto& pair : renderShaderVariables->GetFloatVariables())
{
glShader->SetUniform(pair.first, pair.second);
}
for (const auto& pair : renderShaderVariables->GetVector2Variables())
{
glShader->SetUniform(pair.first, pair.second);
}
for (const auto& pair : renderShaderVariables->GetVector3Variables())
{
glShader->SetUniform(pair.first, pair.second);
}
for (const auto& pair : renderShaderVariables->GetVector4Variables())
{
glShader->SetUniform(pair.first, pair.second);
}
for (const auto& pair : renderShaderVariables->GetMatrix4Variables())
{
glShader->SetUniform(pair.first, pair.second);
}
for (const auto& pair : renderShaderVariables->GetColourVariables())
{
glShader->SetUniform(pair.first, pair.second);
}
}
}
//------------------------------------------------------------------------------
void GLMaterial::Apply(const ChilliSource::RenderMaterial* renderMaterial, GLShader* glShader) noexcept
{
renderMaterial->IsDepthWriteEnabled() ? glDepthMask(GL_TRUE) : glDepthMask(GL_FALSE);
renderMaterial->IsColourWriteEnabled() ? glColorMask(GL_TRUE, GL_TRUE, GL_TRUE, GL_TRUE) : glColorMask(GL_FALSE, GL_FALSE, GL_FALSE, GL_FALSE);
if(renderMaterial->IsDepthTestEnabled())
{
glEnable(GL_DEPTH_TEST);
glDepthFunc(ToGLTestFunc(renderMaterial->GetDepthTestFunc()));
}
else
{
glDisable(GL_DEPTH_TEST);
}
if (renderMaterial->IsFaceCullingEnabled())
{
glEnable(GL_CULL_FACE);
glCullFace(GL_BACK);
}
else
{
glDisable(GL_CULL_FACE);
}
if (renderMaterial->IsTransparencyEnabled())
{
glEnable(GL_BLEND);
glBlendFunc(ToGLBlendMode(renderMaterial->GetSourceBlendMode()), ToGLBlendMode(renderMaterial->GetDestinationBlendMode()));
}
else
{
glDisable(GL_BLEND);
}
if(renderMaterial->IsStencilTestEnabled())
{
glEnable(GL_STENCIL_TEST);
glStencilOp(ToGLStencilOp(renderMaterial->GetStencilFailOp()), ToGLStencilOp(renderMaterial->GetStencilDepthFailOp()), ToGLStencilOp(renderMaterial->GetStencilPassOp()));
glStencilFunc(ToGLTestFunc(renderMaterial->GetStencilTestFunc()), (GLint)renderMaterial->GetStencilTestFuncRef(), (GLuint)renderMaterial->GetStencilTestFuncMask());
}
else
{
glDisable(GL_STENCIL_TEST);
}
s32 samplerNumber = 0;
for (auto i = 0; i < renderMaterial->GetRenderTextures2D().size(); ++i, ++samplerNumber)
{
glShader->SetUniform(k_uniformTexturePrefix + ChilliSource::ToString(i), samplerNumber);
}
for (auto i = 0; i < renderMaterial->GetRenderTexturesCubemap().size(); ++i, ++samplerNumber)
{
glShader->SetUniform(k_uniformCubemapPrefix + ChilliSource::ToString(i), samplerNumber);
}
glShader->SetUniform(k_uniformEmissive, renderMaterial->GetEmissiveColour(), GLShader::FailurePolicy::k_silent);
glShader->SetUniform(k_uniformAmbient, renderMaterial->GetAmbientColour(), GLShader::FailurePolicy::k_silent);
glShader->SetUniform(k_uniformDiffuse, renderMaterial->GetDiffuseColour(), GLShader::FailurePolicy::k_silent);
glShader->SetUniform(k_uniformSpecular, renderMaterial->GetSpecularColour(), GLShader::FailurePolicy::k_silent);
if (renderMaterial->GetRenderShaderVariables())
{
ApplyCustomShaderVariables(renderMaterial->GetRenderShaderVariables(), glShader);
}
}
}
}
<commit_msg>Fixing issue where cull face was always set to back and ignoring the material<commit_after>//
// The MIT License (MIT)
//
// Copyright (c) 2016 Tag Games Limited
//
// 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 <CSBackend/Rendering/OpenGL/Material/GLMaterial.h>
#include <CSBackend/Rendering/OpenGL/Camera/GLCamera.h>
#include <CSBackend/Rendering/OpenGL/Shader/GLShader.h>
#include <ChilliSource/Core/Base/Colour.h>
#include <ChilliSource/Rendering/Base/BlendMode.h>
#include <ChilliSource/Rendering/Base/CullFace.h>
#include <ChilliSource/Rendering/Base/StencilOp.h>
#include <ChilliSource/Rendering/Base/TestFunc.h>
#include <ChilliSource/Rendering/Material/RenderMaterial.h>
namespace CSBackend
{
namespace OpenGL
{
namespace
{
const std::string k_uniformEmissive = "u_emissive";
const std::string k_uniformAmbient = "u_ambient";
const std::string k_uniformDiffuse = "u_diffuse";
const std::string k_uniformSpecular = "u_specular";
const std::string k_uniformTexturePrefix = "u_texture";
const std::string k_uniformCubemapPrefix = "u_cubemap";
/// Converts from a ChilliSource blend mode to an OpenGL blend mode.
///
/// @param blendMode
/// The ChilliSource blend mode.
///
/// @return The OpenGL blend mode.
///
GLenum ToGLBlendMode(ChilliSource::BlendMode blendMode)
{
switch(blendMode)
{
case ChilliSource::BlendMode::k_zero:
return GL_ZERO;
case ChilliSource::BlendMode::k_one:
return GL_ONE;
case ChilliSource::BlendMode::k_sourceCol:
return GL_SRC_COLOR;
case ChilliSource::BlendMode::k_oneMinusSourceCol:
return GL_ONE_MINUS_SRC_COLOR;
case ChilliSource::BlendMode::k_sourceAlpha:
return GL_SRC_ALPHA;
case ChilliSource::BlendMode::k_oneMinusSourceAlpha:
return GL_ONE_MINUS_SRC_ALPHA;
case ChilliSource::BlendMode::k_destCol:
return GL_DST_COLOR;
case ChilliSource::BlendMode::k_oneMinusDestCol:
return GL_ONE_MINUS_DST_COLOR;
case ChilliSource::BlendMode::k_destAlpha:
return GL_DST_ALPHA;
case ChilliSource::BlendMode::k_oneMinusDestAlpha:
return GL_ONE_MINUS_DST_ALPHA;
default:
CS_LOG_FATAL("Invalid blend mode.");
return GL_ZERO;
};
}
/// Converts from a ChilliSource stencil op to an OpenGL one
///
/// @param stencilOp
/// The ChilliSource stencil op
///
/// @return The OpenGL stencil op.
///
GLenum ToGLStencilOp(ChilliSource::StencilOp stencilOp)
{
switch(stencilOp)
{
case ChilliSource::StencilOp::k_keep:
return GL_KEEP;
case ChilliSource::StencilOp::k_zero:
return GL_ZERO;
case ChilliSource::StencilOp::k_replace:
return GL_REPLACE;
case ChilliSource::StencilOp::k_increment:
return GL_INCR;
case ChilliSource::StencilOp::k_incrementWrap:
return GL_INCR_WRAP;
case ChilliSource::StencilOp::k_decrement:
return GL_DECR;
case ChilliSource::StencilOp::k_decrementWrap:
return GL_DECR_WRAP;
case ChilliSource::StencilOp::k_invert:
return GL_INVERT;
default:
CS_LOG_FATAL("Invalid stencil op.");
return GL_KEEP;
};
}
/// Converts from a ChilliSource test func to an OpenGL one
///
/// @param testFunc
/// The ChilliSource test func
///
/// @return The OpenGL test func.
///
GLenum ToGLTestFunc(ChilliSource::TestFunc testFunc)
{
switch(testFunc)
{
case ChilliSource::TestFunc::k_never:
return GL_NEVER;
case ChilliSource::TestFunc::k_less:
return GL_LESS;
case ChilliSource::TestFunc::k_lessEqual:
return GL_LEQUAL;
case ChilliSource::TestFunc::k_greater:
return GL_GREATER;
case ChilliSource::TestFunc::k_greaterEqual:
return GL_GEQUAL;
case ChilliSource::TestFunc::k_equal:
return GL_EQUAL;
case ChilliSource::TestFunc::k_notEqual:
return GL_NOTEQUAL;
case ChilliSource::TestFunc::k_always:
return GL_ALWAYS;
default:
CS_LOG_FATAL("Invalid test func.");
return GL_ALWAYS;
};
}
/// Converts from a ChilliSource cull face to an OpenGL one
///
/// @param cullFace
/// The ChilliSource cull face
///
/// @return The OpenGL cull face.
///
GLenum ToGLCullFace(ChilliSource::CullFace cullFace)
{
switch(cullFace)
{
case ChilliSource::CullFace::k_front:
return GL_FRONT;
case ChilliSource::CullFace::k_back:
return GL_BACK;
}
}
/// Applies the given batch of custom shader variables to the given shader. If
/// any of the variables do not exist in the shader, this will assert.
///
/// @param renderShaderVariables
/// The shader variables to apply.
/// @param glShader
/// The shader to apply the variables to.
///
void ApplyCustomShaderVariables(const ChilliSource::RenderShaderVariables* renderShaderVariables, GLShader* glShader) noexcept
{
CS_ASSERT(renderShaderVariables, "Cannot apply null shader variables.");
CS_ASSERT(glShader, "Cannot apply shader variables to null shader.");
for (const auto& pair : renderShaderVariables->GetFloatVariables())
{
glShader->SetUniform(pair.first, pair.second);
}
for (const auto& pair : renderShaderVariables->GetVector2Variables())
{
glShader->SetUniform(pair.first, pair.second);
}
for (const auto& pair : renderShaderVariables->GetVector3Variables())
{
glShader->SetUniform(pair.first, pair.second);
}
for (const auto& pair : renderShaderVariables->GetVector4Variables())
{
glShader->SetUniform(pair.first, pair.second);
}
for (const auto& pair : renderShaderVariables->GetMatrix4Variables())
{
glShader->SetUniform(pair.first, pair.second);
}
for (const auto& pair : renderShaderVariables->GetColourVariables())
{
glShader->SetUniform(pair.first, pair.second);
}
}
}
//------------------------------------------------------------------------------
void GLMaterial::Apply(const ChilliSource::RenderMaterial* renderMaterial, GLShader* glShader) noexcept
{
renderMaterial->IsDepthWriteEnabled() ? glDepthMask(GL_TRUE) : glDepthMask(GL_FALSE);
renderMaterial->IsColourWriteEnabled() ? glColorMask(GL_TRUE, GL_TRUE, GL_TRUE, GL_TRUE) : glColorMask(GL_FALSE, GL_FALSE, GL_FALSE, GL_FALSE);
if(renderMaterial->IsDepthTestEnabled())
{
glEnable(GL_DEPTH_TEST);
glDepthFunc(ToGLTestFunc(renderMaterial->GetDepthTestFunc()));
}
else
{
glDisable(GL_DEPTH_TEST);
}
if (renderMaterial->IsFaceCullingEnabled())
{
glEnable(GL_CULL_FACE);
glCullFace(ToGLCullFace(renderMaterial->GetCullFace()));
}
else
{
glDisable(GL_CULL_FACE);
}
if (renderMaterial->IsTransparencyEnabled())
{
glEnable(GL_BLEND);
glBlendFunc(ToGLBlendMode(renderMaterial->GetSourceBlendMode()), ToGLBlendMode(renderMaterial->GetDestinationBlendMode()));
}
else
{
glDisable(GL_BLEND);
}
if(renderMaterial->IsStencilTestEnabled())
{
glEnable(GL_STENCIL_TEST);
glStencilOp(ToGLStencilOp(renderMaterial->GetStencilFailOp()), ToGLStencilOp(renderMaterial->GetStencilDepthFailOp()), ToGLStencilOp(renderMaterial->GetStencilPassOp()));
glStencilFunc(ToGLTestFunc(renderMaterial->GetStencilTestFunc()), (GLint)renderMaterial->GetStencilTestFuncRef(), (GLuint)renderMaterial->GetStencilTestFuncMask());
}
else
{
glDisable(GL_STENCIL_TEST);
}
s32 samplerNumber = 0;
for (auto i = 0; i < renderMaterial->GetRenderTextures2D().size(); ++i, ++samplerNumber)
{
glShader->SetUniform(k_uniformTexturePrefix + ChilliSource::ToString(i), samplerNumber);
}
for (auto i = 0; i < renderMaterial->GetRenderTexturesCubemap().size(); ++i, ++samplerNumber)
{
glShader->SetUniform(k_uniformCubemapPrefix + ChilliSource::ToString(i), samplerNumber);
}
glShader->SetUniform(k_uniformEmissive, renderMaterial->GetEmissiveColour(), GLShader::FailurePolicy::k_silent);
glShader->SetUniform(k_uniformAmbient, renderMaterial->GetAmbientColour(), GLShader::FailurePolicy::k_silent);
glShader->SetUniform(k_uniformDiffuse, renderMaterial->GetDiffuseColour(), GLShader::FailurePolicy::k_silent);
glShader->SetUniform(k_uniformSpecular, renderMaterial->GetSpecularColour(), GLShader::FailurePolicy::k_silent);
if (renderMaterial->GetRenderShaderVariables())
{
ApplyCustomShaderVariables(renderMaterial->GetRenderShaderVariables(), glShader);
}
}
}
}
<|endoftext|> |
<commit_before>#include "vm.hpp"
#include "console.hpp"
#include "object_utils.hpp"
#include "builtin/array.hpp"
#include "builtin/class.hpp"
#include "builtin/fsevent.hpp"
#include "builtin/string.hpp"
#include "builtin/thread.hpp"
#include "dtrace/dtrace.h"
#include "util/file.hpp"
#include "util/logger.hpp"
#include <fcntl.h>
#include <sys/file.h>
#include <stdio.h>
// read
#include <unistd.h>
#include <sys/uio.h>
#include <sys/types.h>
namespace rubinius {
using namespace utilities;
namespace console {
Object* console_request_trampoline(STATE) {
state->shared().console()->process_requests(state);
GCTokenImpl gct;
state->gc_dependent(gct, 0);
return cNil;
}
Object* console_response_trampoline(STATE) {
state->shared().console()->process_responses(state);
GCTokenImpl gct;
state->gc_dependent(gct, 0);
return cNil;
}
Console::Console(STATE)
: AuxiliaryThread()
, shared_(state->shared())
, request_vm_(NULL)
, response_vm_(NULL)
, request_(state)
, response_(state)
, console_(state)
, fsevent_(state)
, request_fd_(-1)
, response_fd_(-1)
, request_exit_(false)
, response_exit_(false)
, request_list_(0)
{
shared_.auxiliary_threads()->register_thread(this);
}
Console::~Console() {
shared_.auxiliary_threads()->unregister_thread(this);
}
void Console::wakeup() {
request_exit_ = true;
if(write(request_fd_, "x", 1) < 0) {
logger::error("%s: console: unable to wake request thread", strerror(errno));
}
}
void Console::cleanup(bool remove_files) {
if(request_fd_ > 0) {
close(request_fd_);
if(remove_files) unlink(request_path_.c_str());
request_fd_ = -1;
}
if(response_fd_ > 0) {
close(response_fd_);
if(remove_files) unlink(response_path_.c_str());
response_fd_ = -1;
}
if(request_list_) {
for(RequestList::const_iterator i = request_list_->begin();
i != request_list_->end();
++i)
{
delete[] *i;
}
delete request_list_;
request_list_ = NULL;
}
}
void Console::initialize(STATE) {
request_exit_ = false;
response_exit_ = false;
list_lock_.init();
response_lock_.init();
response_cond_.init();
std::string path(shared_.fsapi_path + "/console");
request_path_ = path + "-request";
response_path_ = path + "-response";
request_list_ = new RequestList;
Module* mod = as<Module>(G(rubinius)->get_const(state, "Console"));
Class* cls = as<Class>(mod->get_const(state, "Server"));
console_.set(cls->send(state, 0, state->symbol("new")));
cls->set_const(state, state->symbol("RequestPath"),
String::create(state, request_path_.c_str()));
cls->set_const(state, state->symbol("ResponsePath"),
String::create(state, response_path_.c_str()));
}
static int open_file(std::string path) {
int fd = ::open(path.c_str(), O_CREAT | O_TRUNC | O_RDWR, 0666);
if(fd < 0) {
logger::error("%s: console: unable to open: %s", strerror(errno), path.c_str());
}
return fd;
}
void Console::setup_files(STATE) {
request_fd_ = open_file(request_path_);
response_fd_ = open_file(response_path_);
FSEvent* fsevent = FSEvent::create(state);
fsevent->watch_file(state, request_fd_, request_path_.c_str());
fsevent_.set(fsevent);
}
void Console::start(STATE) {
initialize(state);
setup_files(state);
start_threads(state);
}
void Console::run(STATE) {
if(request_.get()->fork_attached(state)) {
rubinius::bug("Unable to start console request thread");
}
if(response_.get()->fork_attached(state)) {
rubinius::bug("Unable to start console response thread");
}
}
void Console::start_threads(STATE) {
SYNC(state);
// Don't start threads if we couldn't open communication channels.
if(request_fd_ < 0 || response_fd_ < 0) return;
if(!request_vm_) {
request_vm_ = state->shared().new_vm();
request_vm_->metrics()->init(metrics::eConsoleMetrics);
request_exit_ = false;
request_.set(Thread::create(state, request_vm_, G(thread),
console_request_trampoline, true));
}
if(!response_vm_) {
response_vm_ = state->shared().new_vm();
response_vm_->metrics()->init(metrics::eConsoleMetrics);
response_exit_ = false;
response_.set(Thread::create(state, response_vm_, G(thread),
console_response_trampoline, true));
}
if(request_vm_ && response_vm_) {
run(state);
}
}
void Console::stop_threads(STATE) {
SYNC(state);
if(request_vm_) {
file::LockGuard guard(request_fd_, LOCK_EX);
if(guard.status() == file::eLockSucceeded) {
logger::error("%s: console: unable to lock request file", strerror(errno));
return;
}
wakeup();
pthread_t os = request_vm_->os_thread();
request_exit_ = true;
void* return_value;
pthread_join(os, &return_value);
request_vm_ = NULL;
}
if(response_vm_) {
file::LockGuard guard(response_fd_, LOCK_EX);
if(guard.status() != file::eLockSucceeded) {
logger::error("%s: unable to lock response file", strerror(errno));
return;
}
pthread_t os = response_vm_->os_thread();
response_exit_ = true;
response_cond_.signal();
void* return_value;
pthread_join(os, &return_value);
response_vm_ = NULL;
}
}
void Console::shutdown(STATE) {
stop_threads(state);
cleanup(true);
}
void Console::before_exec(STATE) {
stop_threads(state);
cleanup(true);
}
void Console::after_exec(STATE) {
setup_files(state);
start_threads(state);
}
void Console::before_fork(STATE) {
stop_threads(state);
}
void Console::after_fork_parent(STATE) {
start_threads(state);
}
void Console::after_fork_child(STATE) {
if(request_vm_) {
VM::discard(state, request_vm_);
request_vm_ = NULL;
}
if(response_vm_) {
VM::discard(state, response_vm_);
response_vm_ = NULL;
}
cleanup(false);
start(state);
}
char* Console::read_request(STATE) {
file::LockGuard guard(request_fd_, LOCK_EX);
if(guard.status() != file::eLockSucceeded) {
logger::error("%s: console: unable to lock request file", strerror(errno));
return NULL;
}
char* buf[1024];
lseek(request_fd_, 0, SEEK_SET);
ssize_t bytes = ::read(request_fd_, buf, 1024);
char* req = NULL;
if(bytes > 0) {
req = new char[bytes+1];
memcpy(req, buf, bytes);
req[bytes] = 0;
request_vm_->metrics()->m.console_metrics.requests_received++;
} else if(bytes < 0) {
logger::error("%s: console: unable to read request", strerror(errno));
}
if(lseek(request_fd_, 0, SEEK_SET) < 0) {
logger::error("%s: console: unable to rewind request file", strerror(errno));
}
if(ftruncate(request_fd_, 0) < 0) {
logger::error("%s: console: unable to truncate request file", strerror(errno));
}
return req;
}
void Console::process_requests(STATE) {
GCTokenImpl gct;
RBX_DTRACE_CONST char* thread_name =
const_cast<RBX_DTRACE_CONST char*>("rbx.console.request");
request_vm_->set_name(thread_name);
RUBINIUS_THREAD_START(const_cast<RBX_DTRACE_CONST char*>(thread_name),
state->vm()->thread_id(), 1);
state->vm()->thread->hard_unlock(state, gct, 0);
state->gc_independent(gct, 0);
while(!request_exit_) {
Object* status = fsevent_.get()->wait_for_event(state);
if(request_exit_) break;
if(status->nil_p()) continue;
char* request = read_request(state);
if(request) {
utilities::thread::Mutex::LockGuard lg(list_lock_);
request_list_->push_back(request);
response_cond_.signal();
}
}
RUBINIUS_THREAD_STOP(const_cast<RBX_DTRACE_CONST char*>(thread_name),
state->vm()->thread_id(), 1);
}
void Console::write_response(STATE, const char* response, native_int size) {
file::LockGuard guard(response_fd_, LOCK_EX);
if(guard.status() != file::eLockSucceeded) {
logger::error("%s: unable to lock response file", strerror(errno));
return;
}
if(lseek(response_fd_, 0, SEEK_SET) < 0) {
logger::error("%s: console: unable to rewind response file", strerror(errno));
return;
}
if(ftruncate(response_fd_, 0) < 0) {
logger::error("%s: console: unable to truncate response file", strerror(errno));
return;
}
if(::write(response_fd_, response, size) < 0) {
logger::error("%s: console: unable to write response", strerror(errno));
}
response_vm_->metrics()->m.console_metrics.responses_sent++;
}
void Console::process_responses(STATE) {
GCTokenImpl gct;
RBX_DTRACE_CONST char* thread_name =
const_cast<RBX_DTRACE_CONST char*>("rbx.console.response");
response_vm_->set_name(thread_name);
RUBINIUS_THREAD_START(const_cast<RBX_DTRACE_CONST char*>(thread_name),
state->vm()->thread_id(), 1);
state->vm()->thread->hard_unlock(state, gct, 0);
state->gc_dependent(gct, 0);
char* request = NULL;
while(!response_exit_) {
{
utilities::thread::Mutex::LockGuard lg(list_lock_);
GCIndependent guard(state, 0);
if(request_list_->size() > 0) {
request = request_list_->back();
request_list_->pop_back();
}
}
if(response_exit_) break;
if(request) {
Array* args = Array::create(state, 1);
args->aset(state, 0, String::create(state, request));
Object* result = console_.get()->send(state, 0, state->symbol("evaluate"),
args, cNil);
if(String* response = try_as<String>(result)) {
GCIndependent guard(state, 0);
write_response(state,
reinterpret_cast<const char*>(response->byte_address()),
response->byte_size());
}
request = NULL;
} else {
utilities::thread::Mutex::LockGuard lg(response_lock_);
GCIndependent guard(state, 0);
response_cond_.wait(response_lock_);
}
}
RUBINIUS_THREAD_STOP(const_cast<RBX_DTRACE_CONST char*>(thread_name),
state->vm()->thread_id(), 1);
}
}
}
<commit_msg>Revert "Lock when calling Console::stop_threads()"<commit_after>#include "vm.hpp"
#include "console.hpp"
#include "object_utils.hpp"
#include "builtin/array.hpp"
#include "builtin/class.hpp"
#include "builtin/fsevent.hpp"
#include "builtin/string.hpp"
#include "builtin/thread.hpp"
#include "dtrace/dtrace.h"
#include "util/file.hpp"
#include "util/logger.hpp"
#include <fcntl.h>
#include <sys/file.h>
#include <stdio.h>
// read
#include <unistd.h>
#include <sys/uio.h>
#include <sys/types.h>
namespace rubinius {
using namespace utilities;
namespace console {
Object* console_request_trampoline(STATE) {
state->shared().console()->process_requests(state);
GCTokenImpl gct;
state->gc_dependent(gct, 0);
return cNil;
}
Object* console_response_trampoline(STATE) {
state->shared().console()->process_responses(state);
GCTokenImpl gct;
state->gc_dependent(gct, 0);
return cNil;
}
Console::Console(STATE)
: AuxiliaryThread()
, shared_(state->shared())
, request_vm_(NULL)
, response_vm_(NULL)
, request_(state)
, response_(state)
, console_(state)
, fsevent_(state)
, request_fd_(-1)
, response_fd_(-1)
, request_exit_(false)
, response_exit_(false)
, request_list_(0)
{
shared_.auxiliary_threads()->register_thread(this);
}
Console::~Console() {
shared_.auxiliary_threads()->unregister_thread(this);
}
void Console::wakeup() {
request_exit_ = true;
if(write(request_fd_, "x", 1) < 0) {
logger::error("%s: console: unable to wake request thread", strerror(errno));
}
}
void Console::cleanup(bool remove_files) {
if(request_fd_ > 0) {
close(request_fd_);
if(remove_files) unlink(request_path_.c_str());
request_fd_ = -1;
}
if(response_fd_ > 0) {
close(response_fd_);
if(remove_files) unlink(response_path_.c_str());
response_fd_ = -1;
}
if(request_list_) {
for(RequestList::const_iterator i = request_list_->begin();
i != request_list_->end();
++i)
{
delete[] *i;
}
delete request_list_;
request_list_ = NULL;
}
}
void Console::initialize(STATE) {
request_exit_ = false;
response_exit_ = false;
list_lock_.init();
response_lock_.init();
response_cond_.init();
std::string path(shared_.fsapi_path + "/console");
request_path_ = path + "-request";
response_path_ = path + "-response";
request_list_ = new RequestList;
Module* mod = as<Module>(G(rubinius)->get_const(state, "Console"));
Class* cls = as<Class>(mod->get_const(state, "Server"));
console_.set(cls->send(state, 0, state->symbol("new")));
cls->set_const(state, state->symbol("RequestPath"),
String::create(state, request_path_.c_str()));
cls->set_const(state, state->symbol("ResponsePath"),
String::create(state, response_path_.c_str()));
}
static int open_file(std::string path) {
int fd = ::open(path.c_str(), O_CREAT | O_TRUNC | O_RDWR, 0666);
if(fd < 0) {
logger::error("%s: console: unable to open: %s", strerror(errno), path.c_str());
}
return fd;
}
void Console::setup_files(STATE) {
request_fd_ = open_file(request_path_);
response_fd_ = open_file(response_path_);
FSEvent* fsevent = FSEvent::create(state);
fsevent->watch_file(state, request_fd_, request_path_.c_str());
fsevent_.set(fsevent);
}
void Console::start(STATE) {
initialize(state);
setup_files(state);
start_threads(state);
}
void Console::run(STATE) {
if(request_.get()->fork_attached(state)) {
rubinius::bug("Unable to start console request thread");
}
if(response_.get()->fork_attached(state)) {
rubinius::bug("Unable to start console response thread");
}
}
void Console::start_threads(STATE) {
SYNC(state);
// Don't start threads if we couldn't open communication channels.
if(request_fd_ < 0 || response_fd_ < 0) return;
if(!request_vm_) {
request_vm_ = state->shared().new_vm();
request_vm_->metrics()->init(metrics::eConsoleMetrics);
request_exit_ = false;
request_.set(Thread::create(state, request_vm_, G(thread),
console_request_trampoline, true));
}
if(!response_vm_) {
response_vm_ = state->shared().new_vm();
response_vm_->metrics()->init(metrics::eConsoleMetrics);
response_exit_ = false;
response_.set(Thread::create(state, response_vm_, G(thread),
console_response_trampoline, true));
}
if(request_vm_ && response_vm_) {
run(state);
}
}
void Console::stop_threads(STATE) {
SYNC(state);
if(request_vm_) {
wakeup();
pthread_t os = request_vm_->os_thread();
request_exit_ = true;
void* return_value;
pthread_join(os, &return_value);
request_vm_ = NULL;
}
if(response_vm_) {
pthread_t os = response_vm_->os_thread();
response_exit_ = true;
response_cond_.signal();
void* return_value;
pthread_join(os, &return_value);
response_vm_ = NULL;
}
}
void Console::shutdown(STATE) {
stop_threads(state);
cleanup(true);
}
void Console::before_exec(STATE) {
stop_threads(state);
cleanup(true);
}
void Console::after_exec(STATE) {
setup_files(state);
start_threads(state);
}
void Console::before_fork(STATE) {
stop_threads(state);
}
void Console::after_fork_parent(STATE) {
start_threads(state);
}
void Console::after_fork_child(STATE) {
if(request_vm_) {
VM::discard(state, request_vm_);
request_vm_ = NULL;
}
if(response_vm_) {
VM::discard(state, response_vm_);
response_vm_ = NULL;
}
cleanup(false);
start(state);
}
char* Console::read_request(STATE) {
file::LockGuard guard(request_fd_, LOCK_EX);
if(guard.status() != file::eLockSucceeded) {
logger::error("%s: console: unable to lock request file", strerror(errno));
return NULL;
}
char* buf[1024];
lseek(request_fd_, 0, SEEK_SET);
ssize_t bytes = ::read(request_fd_, buf, 1024);
char* req = NULL;
if(bytes > 0) {
req = new char[bytes+1];
memcpy(req, buf, bytes);
req[bytes] = 0;
request_vm_->metrics()->m.console_metrics.requests_received++;
} else if(bytes < 0) {
logger::error("%s: console: unable to read request", strerror(errno));
}
if(lseek(request_fd_, 0, SEEK_SET) < 0) {
logger::error("%s: console: unable to rewind request file", strerror(errno));
}
if(ftruncate(request_fd_, 0) < 0) {
logger::error("%s: console: unable to truncate request file", strerror(errno));
}
return req;
}
void Console::process_requests(STATE) {
GCTokenImpl gct;
RBX_DTRACE_CONST char* thread_name =
const_cast<RBX_DTRACE_CONST char*>("rbx.console.request");
request_vm_->set_name(thread_name);
RUBINIUS_THREAD_START(const_cast<RBX_DTRACE_CONST char*>(thread_name),
state->vm()->thread_id(), 1);
state->vm()->thread->hard_unlock(state, gct, 0);
state->gc_independent(gct, 0);
while(!request_exit_) {
Object* status = fsevent_.get()->wait_for_event(state);
if(request_exit_) break;
if(status->nil_p()) continue;
char* request = read_request(state);
if(request) {
utilities::thread::Mutex::LockGuard lg(list_lock_);
request_list_->push_back(request);
response_cond_.signal();
}
}
RUBINIUS_THREAD_STOP(const_cast<RBX_DTRACE_CONST char*>(thread_name),
state->vm()->thread_id(), 1);
}
void Console::write_response(STATE, const char* response, native_int size) {
file::LockGuard guard(response_fd_, LOCK_EX);
if(guard.status() != file::eLockSucceeded) {
logger::error("%s: unable to lock response file", strerror(errno));
return;
}
if(lseek(response_fd_, 0, SEEK_SET) < 0) {
logger::error("%s: console: unable to rewind response file", strerror(errno));
return;
}
if(ftruncate(response_fd_, 0) < 0) {
logger::error("%s: console: unable to truncate response file", strerror(errno));
return;
}
if(::write(response_fd_, response, size) < 0) {
logger::error("%s: console: unable to write response", strerror(errno));
}
response_vm_->metrics()->m.console_metrics.responses_sent++;
}
void Console::process_responses(STATE) {
GCTokenImpl gct;
RBX_DTRACE_CONST char* thread_name =
const_cast<RBX_DTRACE_CONST char*>("rbx.console.response");
response_vm_->set_name(thread_name);
RUBINIUS_THREAD_START(const_cast<RBX_DTRACE_CONST char*>(thread_name),
state->vm()->thread_id(), 1);
state->vm()->thread->hard_unlock(state, gct, 0);
state->gc_dependent(gct, 0);
char* request = NULL;
while(!response_exit_) {
{
utilities::thread::Mutex::LockGuard lg(list_lock_);
GCIndependent guard(state, 0);
if(request_list_->size() > 0) {
request = request_list_->back();
request_list_->pop_back();
}
}
if(response_exit_) break;
if(request) {
Array* args = Array::create(state, 1);
args->aset(state, 0, String::create(state, request));
Object* result = console_.get()->send(state, 0, state->symbol("evaluate"),
args, cNil);
if(String* response = try_as<String>(result)) {
GCIndependent guard(state, 0);
write_response(state,
reinterpret_cast<const char*>(response->byte_address()),
response->byte_size());
}
request = NULL;
} else {
utilities::thread::Mutex::LockGuard lg(response_lock_);
GCIndependent guard(state, 0);
response_cond_.wait(response_lock_);
}
}
RUBINIUS_THREAD_STOP(const_cast<RBX_DTRACE_CONST char*>(thread_name),
state->vm()->thread_id(), 1);
}
}
}
<|endoftext|> |
<commit_before>/**
* Copyright (c) 2014-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*/
#include <wdt/Wdt.h>
#include <wdt/Receiver.h>
#include <wdt/WdtResourceController.h>
#include <chrono>
#include <future>
#include <folly/String.h>
#include <gflags/gflags.h>
#include <glog/logging.h>
#include <iostream>
#include <fstream>
#include <signal.h>
#include <thread>
// Used in fbonly to add socket creator setup
#ifndef ADDITIONAL_SENDER_SETUP
#define ADDITIONAL_SENDER_SETUP
#endif
// This can be the fbonly (FbWdt) version (extended initialization, and options)
#ifndef WDTCLASS
#define WDTCLASS Wdt
#endif
// Flags not already in WdtOptions.h/WdtFlags.cpp.inc
DEFINE_bool(fork, false,
"If true, forks the receiver, if false, no forking/stay in fg");
DEFINE_bool(run_as_daemon, false,
"If true, run the receiver as never ending process");
DEFINE_string(directory, ".", "Source/Destination directory");
DEFINE_string(manifest, "",
"If specified, then we will read a list of files and optional "
"sizes from this file, use - for stdin");
DEFINE_string(
destination, "",
"empty is server (destination) mode, non empty is destination host");
DEFINE_bool(parse_transfer_log, false,
"If true, transfer log is parsed and fixed");
DEFINE_string(transfer_id, "",
"Transfer id. Receiver will generate one to be used (via URL) on"
" the sender if not set explicitly");
DEFINE_int32(
protocol_version, 0,
"Protocol version to use, this is used to simulate protocol negotiation");
DEFINE_string(connection_url, "",
"Provide the connection string to connect to receiver"
" (incl. transfer_id and other parameters)."
" Deprecated: use - arg instead for safe encryption key"
" transmission");
DECLARE_bool(logtostderr); // default of standard glog is off - let's set it on
DEFINE_int32(abort_after_seconds, 0,
"Abort transfer after given seconds. 0 means don't abort.");
DEFINE_string(recovery_id, "", "Recovery-id to use for download resumption");
DEFINE_bool(treat_fewer_port_as_error, false,
"If the receiver is unable to bind to all the ports, treat that as "
"an error.");
DEFINE_bool(print_options, false,
"If true, wdt prints the option values and exits. Option values "
"printed take into account option type and other command line "
"flags specified.");
DEFINE_bool(exit_on_bad_flags, true,
"If true, wdt exits on bad/unknown flag. Otherwise, an unknown "
"flags are ignored");
DEFINE_string(test_only_encryption_secret, "",
"Test only encryption secret, to test url encoding/decoding");
DEFINE_string(app_name, "wdt", "Identifier used for reporting (scuba, at fb)");
using namespace facebook::wdt;
// TODO: move this to some util and/or delete
template <typename T>
std::ostream &operator<<(std::ostream &os, const std::set<T> &v) {
std::copy(v.begin(), v.end(), std::ostream_iterator<T>(os, " "));
return os;
}
std::mutex abortMutex;
std::condition_variable abortCondVar;
bool isAbortCancelled = false;
std::shared_ptr<WdtAbortChecker> setupAbortChecker() {
int abortSeconds = FLAGS_abort_after_seconds;
if (abortSeconds <= 0) {
return nullptr;
}
LOG(INFO) << "Setting up abort " << abortSeconds << " seconds.";
static std::atomic<bool> abortTrigger{false};
auto res = std::make_shared<WdtAbortChecker>(abortTrigger);
auto lambda = [=] {
LOG(INFO) << "Will abort in " << abortSeconds << " seconds.";
std::unique_lock<std::mutex> lk(abortMutex);
bool isNotAbort =
abortCondVar.wait_for(lk, std::chrono::seconds(abortSeconds),
[&]() -> bool { return isAbortCancelled; });
if (isNotAbort) {
LOG(INFO) << "Already finished normally, no abort.";
} else {
LOG(INFO) << "Requesting abort.";
abortTrigger.store(true);
}
};
// Run this in a separate thread concurrently with sender/receiver
static auto f = std::async(std::launch::async, lambda);
return res;
}
void setAbortChecker(WdtBase &senderOrReceiver) {
senderOrReceiver.setAbortChecker(setupAbortChecker());
}
void cancelAbort() {
{
std::unique_lock<std::mutex> lk(abortMutex);
isAbortCancelled = true;
abortCondVar.notify_one();
}
std::this_thread::yield();
}
void readManifest(std::istream &fin, WdtTransferRequest &req) {
std::string line;
while (std::getline(fin, line)) {
std::vector<std::string> fields;
folly::split('\t', line, fields, true);
if (fields.empty() || fields.size() > 2) {
LOG(FATAL) << "Invalid input manifest: " << line;
}
int64_t filesize = fields.size() > 1 ? folly::to<int64_t>(fields[1]) : -1;
req.fileInfo.emplace_back(fields[0], filesize);
}
}
namespace google {
extern GFLAGS_DLL_DECL void (*gflags_exitfunc)(int);
}
bool badGflagFound = false;
static std::string usage;
void printUsage() {
std::cerr << usage << std::endl;
}
int main(int argc, char *argv[]) {
FLAGS_logtostderr = true;
// Ugliness in gflags' api; to be able to use program name
google::SetArgv(argc, const_cast<const char **>(argv));
google::SetVersionString(Protocol::getFullVersion());
usage.assign("WDT Warp-speed Data Transfer. v ");
usage.append(google::VersionString());
usage.append(". Sample usage:\nTo transfer from srchost to desthost:\n\t");
usage.append("ssh dsthost ");
usage.append(google::ProgramInvocationShortName());
usage.append(" -directory destdir | ssh srchost ");
usage.append(google::ProgramInvocationShortName());
usage.append(" -directory srcdir -");
usage.append(
"\nPassing - as the argument to wdt means start the sender and"
" read the");
usage.append(
"\nconnection URL produced by the receiver, including encryption"
" key, from stdin.");
usage.append("\nUse --help to see all the options.");
google::SetUsageMessage(usage);
google::gflags_exitfunc = [](int code) {
if (FLAGS_exit_on_bad_flags) {
printUsage();
exit(code);
}
badGflagFound = true;
};
google::ParseCommandLineFlags(&argc, &argv, true);
google::InitGoogleLogging(argv[0]);
if (badGflagFound) {
LOG(ERROR) << "Continuing despite bad flags";
}
// Only non -flag argument allowed so far is "-" meaning
// Read url from stdin and start a sender
if (argc > 2 || (argc == 2 && (argv[1][0] != '-' || argv[1][1] != '\0'))) {
printUsage();
std::cerr << "Error: argument should be - (to read url from stdin) "
<< "or no arguments" << std::endl;
exit(1);
}
signal(SIGPIPE, SIG_IGN);
std::string connectUrl;
if (argc == 2) {
std::getline(std::cin, connectUrl);
if (connectUrl.empty()) {
LOG(ERROR) << "Sender unable to read connection url from stdin - exiting";
return URI_PARSE_ERROR;
}
} else {
connectUrl = FLAGS_connection_url;
}
// Might be a sub class (fbonly wdtCmdLine.cpp)
Wdt &wdt = WDTCLASS::initializeWdt(FLAGS_app_name);
if (FLAGS_print_options) {
wdt.printWdtOptions(std::cout);
return 0;
}
ErrorCode retCode = OK;
// Odd ball case of log parsing
if (FLAGS_parse_transfer_log) {
// Log parsing mode
WdtOptions::getMutable().enable_download_resumption = true;
TransferLogManager transferLogManager;
transferLogManager.setRootDir(FLAGS_directory);
transferLogManager.openLog();
bool success = transferLogManager.parseAndPrint();
LOG_IF(ERROR, success) << "Transfer log parsing failed";
transferLogManager.closeLog();
return success ? OK : ERROR;
}
// General case : Sender or Receiver
const auto &options = WdtOptions::get();
std::unique_ptr<WdtTransferRequest> reqPtr;
if (connectUrl.empty()) {
reqPtr = folly::make_unique<WdtTransferRequest>(
options.start_port, options.num_ports, FLAGS_directory);
reqPtr->hostName = FLAGS_destination;
reqPtr->transferId = FLAGS_transfer_id;
if (!FLAGS_test_only_encryption_secret.empty()) {
reqPtr->encryptionData =
EncryptionParams(parseEncryptionType(options.encryption_type),
FLAGS_test_only_encryption_secret);
}
} else {
reqPtr = folly::make_unique<WdtTransferRequest>(connectUrl);
if (reqPtr->errorCode != OK) {
LOG(ERROR) << "Invalid url \"" << connectUrl
<< "\" : " << errorCodeToStr(reqPtr->errorCode);
return ERROR;
}
reqPtr->directory = FLAGS_directory;
LOG(INFO) << "Parsed url as " << reqPtr->getLogSafeString();
}
WdtTransferRequest &req = *reqPtr;
if (FLAGS_protocol_version > 0) {
req.protocolVersion = FLAGS_protocol_version;
}
if (FLAGS_destination.empty() && connectUrl.empty()) {
Receiver receiver(req);
if (!FLAGS_recovery_id.empty()) {
WdtOptions::getMutable().enable_download_resumption = true;
receiver.setRecoveryId(FLAGS_recovery_id);
}
WdtTransferRequest augmentedReq = receiver.init();
retCode = augmentedReq.errorCode;
if (retCode == FEWER_PORTS) {
if (FLAGS_treat_fewer_port_as_error) {
LOG(ERROR) << "Receiver could not bind to all the ports";
return FEWER_PORTS;
}
retCode = OK;
} else if (augmentedReq.errorCode != OK) {
LOG(ERROR) << "Error setting up receiver " << errorCodeToStr(retCode);
return retCode;
}
// In the log:
LOG(INFO) << "Starting receiver with connection url "
<< augmentedReq.getLogSafeString(); // The url without secret
// on stdout: the one with secret:
std::cout << augmentedReq.genWdtUrlWithSecret() << std::endl;
std::cout.flush();
if (FLAGS_fork) {
pid_t cpid = fork();
if (cpid == -1) {
perror("Failed to fork()");
exit(1);
}
if (cpid > 0) {
LOG(INFO) << "Detaching receiver";
exit(0);
}
close(0);
close(1);
}
setAbortChecker(receiver);
if (!FLAGS_run_as_daemon) {
retCode = receiver.transferAsync();
if (retCode == OK) {
std::unique_ptr<TransferReport> report = receiver.finish();
retCode = report->getSummary().getErrorCode();
}
} else {
retCode = receiver.runForever();
// not reached
}
} else {
// Sender mode
if (!FLAGS_manifest.empty()) {
// Each line should have the filename and optionally
// the filesize separated by a single space
if (FLAGS_manifest == "-") {
readManifest(std::cin, req);
} else {
std::ifstream fin(FLAGS_manifest);
readManifest(fin, req);
fin.close();
}
LOG(INFO) << "Using files lists, number of files " << req.fileInfo.size();
}
LOG(INFO) << "Making Sender with encryption set = "
<< req.encryptionData.isSet();
// TODO: find something more useful for namespace (userid ? directory?)
// (shardid at fb)
retCode = wdt.wdtSend(WdtResourceController::kGlobalNamespace, req,
setupAbortChecker());
}
cancelAbort();
if (retCode == OK) {
LOG(INFO) << "Returning with OK exit code";
} else {
LOG(ERROR) << "Returning with code " << retCode << " "
<< errorCodeToStr(retCode);
}
return retCode;
}
<commit_msg>fix --version and --help<commit_after>/**
* Copyright (c) 2014-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*/
#include <wdt/Wdt.h>
#include <wdt/Receiver.h>
#include <wdt/WdtResourceController.h>
#include <chrono>
#include <future>
#include <folly/String.h>
#include <gflags/gflags.h>
#include <glog/logging.h>
#include <iostream>
#include <fstream>
#include <signal.h>
#include <thread>
// Used in fbonly to add socket creator setup
#ifndef ADDITIONAL_SENDER_SETUP
#define ADDITIONAL_SENDER_SETUP
#endif
// This can be the fbonly (FbWdt) version (extended initialization, and options)
#ifndef WDTCLASS
#define WDTCLASS Wdt
#endif
// Flags not already in WdtOptions.h/WdtFlags.cpp.inc
DEFINE_bool(fork, false,
"If true, forks the receiver, if false, no forking/stay in fg");
DEFINE_bool(run_as_daemon, false,
"If true, run the receiver as never ending process");
DEFINE_string(directory, ".", "Source/Destination directory");
DEFINE_string(manifest, "",
"If specified, then we will read a list of files and optional "
"sizes from this file, use - for stdin");
DEFINE_string(
destination, "",
"empty is server (destination) mode, non empty is destination host");
DEFINE_bool(parse_transfer_log, false,
"If true, transfer log is parsed and fixed");
DEFINE_string(transfer_id, "",
"Transfer id. Receiver will generate one to be used (via URL) on"
" the sender if not set explicitly");
DEFINE_int32(
protocol_version, 0,
"Protocol version to use, this is used to simulate protocol negotiation");
DEFINE_string(connection_url, "",
"Provide the connection string to connect to receiver"
" (incl. transfer_id and other parameters)."
" Deprecated: use - arg instead for safe encryption key"
" transmission");
DECLARE_bool(logtostderr); // default of standard glog is off - let's set it on
DEFINE_int32(abort_after_seconds, 0,
"Abort transfer after given seconds. 0 means don't abort.");
DEFINE_string(recovery_id, "", "Recovery-id to use for download resumption");
DEFINE_bool(treat_fewer_port_as_error, false,
"If the receiver is unable to bind to all the ports, treat that as "
"an error.");
DEFINE_bool(print_options, false,
"If true, wdt prints the option values and exits. Option values "
"printed take into account option type and other command line "
"flags specified.");
DEFINE_bool(exit_on_bad_flags, true,
"If true, wdt exits on bad/unknown flag. Otherwise, an unknown "
"flags are ignored");
DEFINE_string(test_only_encryption_secret, "",
"Test only encryption secret, to test url encoding/decoding");
DEFINE_string(app_name, "wdt", "Identifier used for reporting (scuba, at fb)");
DECLARE_bool(help);
using namespace facebook::wdt;
// TODO: move this to some util and/or delete
template <typename T>
std::ostream &operator<<(std::ostream &os, const std::set<T> &v) {
std::copy(v.begin(), v.end(), std::ostream_iterator<T>(os, " "));
return os;
}
std::mutex abortMutex;
std::condition_variable abortCondVar;
bool isAbortCancelled = false;
std::shared_ptr<WdtAbortChecker> setupAbortChecker() {
int abortSeconds = FLAGS_abort_after_seconds;
if (abortSeconds <= 0) {
return nullptr;
}
LOG(INFO) << "Setting up abort " << abortSeconds << " seconds.";
static std::atomic<bool> abortTrigger{false};
auto res = std::make_shared<WdtAbortChecker>(abortTrigger);
auto lambda = [=] {
LOG(INFO) << "Will abort in " << abortSeconds << " seconds.";
std::unique_lock<std::mutex> lk(abortMutex);
bool isNotAbort =
abortCondVar.wait_for(lk, std::chrono::seconds(abortSeconds),
[&]() -> bool { return isAbortCancelled; });
if (isNotAbort) {
LOG(INFO) << "Already finished normally, no abort.";
} else {
LOG(INFO) << "Requesting abort.";
abortTrigger.store(true);
}
};
// Run this in a separate thread concurrently with sender/receiver
static auto f = std::async(std::launch::async, lambda);
return res;
}
void setAbortChecker(WdtBase &senderOrReceiver) {
senderOrReceiver.setAbortChecker(setupAbortChecker());
}
void cancelAbort() {
{
std::unique_lock<std::mutex> lk(abortMutex);
isAbortCancelled = true;
abortCondVar.notify_one();
}
std::this_thread::yield();
}
void readManifest(std::istream &fin, WdtTransferRequest &req) {
std::string line;
while (std::getline(fin, line)) {
std::vector<std::string> fields;
folly::split('\t', line, fields, true);
if (fields.empty() || fields.size() > 2) {
LOG(FATAL) << "Invalid input manifest: " << line;
}
int64_t filesize = fields.size() > 1 ? folly::to<int64_t>(fields[1]) : -1;
req.fileInfo.emplace_back(fields[0], filesize);
}
}
namespace google {
extern GFLAGS_DLL_DECL void (*gflags_exitfunc)(int);
}
bool badGflagFound = false;
static std::string usage;
void printUsage() {
std::cerr << usage << std::endl;
}
int main(int argc, char *argv[]) {
FLAGS_logtostderr = true;
// Ugliness in gflags' api; to be able to use program name
google::SetArgv(argc, const_cast<const char **>(argv));
google::SetVersionString(Protocol::getFullVersion());
usage.assign("WDT Warp-speed Data Transfer. v ");
usage.append(google::VersionString());
usage.append(". Sample usage:\nTo transfer from srchost to desthost:\n\t");
usage.append("ssh dsthost ");
usage.append(google::ProgramInvocationShortName());
usage.append(" -directory destdir | ssh srchost ");
usage.append(google::ProgramInvocationShortName());
usage.append(" -directory srcdir -");
usage.append(
"\nPassing - as the argument to wdt means start the sender and"
" read the");
usage.append(
"\nconnection URL produced by the receiver, including encryption"
" key, from stdin.");
usage.append("\nUse --help to see all the options.");
google::SetUsageMessage(usage);
google::gflags_exitfunc = [](int code) {
if (code == 0 || FLAGS_help) {
// By default gflags exit 1 with --help and 0 for --version (good)
// let's also exit(0) for --help to be like most gnu command line
exit(0);
}
// error cases:
if (FLAGS_exit_on_bad_flags) {
printUsage();
exit(code);
}
badGflagFound = true;
};
google::ParseCommandLineFlags(&argc, &argv, true);
google::InitGoogleLogging(argv[0]);
if (badGflagFound) {
LOG(ERROR) << "Continuing despite bad flags";
}
// Only non -flag argument allowed so far is "-" meaning
// Read url from stdin and start a sender
if (argc > 2 || (argc == 2 && (argv[1][0] != '-' || argv[1][1] != '\0'))) {
printUsage();
std::cerr << "Error: argument should be - (to read url from stdin) "
<< "or no arguments" << std::endl;
exit(1);
}
signal(SIGPIPE, SIG_IGN);
std::string connectUrl;
if (argc == 2) {
std::getline(std::cin, connectUrl);
if (connectUrl.empty()) {
LOG(ERROR) << "Sender unable to read connection url from stdin - exiting";
return URI_PARSE_ERROR;
}
} else {
connectUrl = FLAGS_connection_url;
}
// Might be a sub class (fbonly wdtCmdLine.cpp)
Wdt &wdt = WDTCLASS::initializeWdt(FLAGS_app_name);
if (FLAGS_print_options) {
wdt.printWdtOptions(std::cout);
return 0;
}
ErrorCode retCode = OK;
// Odd ball case of log parsing
if (FLAGS_parse_transfer_log) {
// Log parsing mode
WdtOptions::getMutable().enable_download_resumption = true;
TransferLogManager transferLogManager;
transferLogManager.setRootDir(FLAGS_directory);
transferLogManager.openLog();
bool success = transferLogManager.parseAndPrint();
LOG_IF(ERROR, success) << "Transfer log parsing failed";
transferLogManager.closeLog();
return success ? OK : ERROR;
}
// General case : Sender or Receiver
const auto &options = WdtOptions::get();
std::unique_ptr<WdtTransferRequest> reqPtr;
if (connectUrl.empty()) {
reqPtr = folly::make_unique<WdtTransferRequest>(
options.start_port, options.num_ports, FLAGS_directory);
reqPtr->hostName = FLAGS_destination;
reqPtr->transferId = FLAGS_transfer_id;
if (!FLAGS_test_only_encryption_secret.empty()) {
reqPtr->encryptionData =
EncryptionParams(parseEncryptionType(options.encryption_type),
FLAGS_test_only_encryption_secret);
}
} else {
reqPtr = folly::make_unique<WdtTransferRequest>(connectUrl);
if (reqPtr->errorCode != OK) {
LOG(ERROR) << "Invalid url \"" << connectUrl
<< "\" : " << errorCodeToStr(reqPtr->errorCode);
return ERROR;
}
reqPtr->directory = FLAGS_directory;
LOG(INFO) << "Parsed url as " << reqPtr->getLogSafeString();
}
WdtTransferRequest &req = *reqPtr;
if (FLAGS_protocol_version > 0) {
req.protocolVersion = FLAGS_protocol_version;
}
if (FLAGS_destination.empty() && connectUrl.empty()) {
Receiver receiver(req);
if (!FLAGS_recovery_id.empty()) {
WdtOptions::getMutable().enable_download_resumption = true;
receiver.setRecoveryId(FLAGS_recovery_id);
}
WdtTransferRequest augmentedReq = receiver.init();
retCode = augmentedReq.errorCode;
if (retCode == FEWER_PORTS) {
if (FLAGS_treat_fewer_port_as_error) {
LOG(ERROR) << "Receiver could not bind to all the ports";
return FEWER_PORTS;
}
retCode = OK;
} else if (augmentedReq.errorCode != OK) {
LOG(ERROR) << "Error setting up receiver " << errorCodeToStr(retCode);
return retCode;
}
// In the log:
LOG(INFO) << "Starting receiver with connection url "
<< augmentedReq.getLogSafeString(); // The url without secret
// on stdout: the one with secret:
std::cout << augmentedReq.genWdtUrlWithSecret() << std::endl;
std::cout.flush();
if (FLAGS_fork) {
pid_t cpid = fork();
if (cpid == -1) {
perror("Failed to fork()");
exit(1);
}
if (cpid > 0) {
LOG(INFO) << "Detaching receiver";
exit(0);
}
close(0);
close(1);
}
setAbortChecker(receiver);
if (!FLAGS_run_as_daemon) {
retCode = receiver.transferAsync();
if (retCode == OK) {
std::unique_ptr<TransferReport> report = receiver.finish();
retCode = report->getSummary().getErrorCode();
}
} else {
retCode = receiver.runForever();
// not reached
}
} else {
// Sender mode
if (!FLAGS_manifest.empty()) {
// Each line should have the filename and optionally
// the filesize separated by a single space
if (FLAGS_manifest == "-") {
readManifest(std::cin, req);
} else {
std::ifstream fin(FLAGS_manifest);
readManifest(fin, req);
fin.close();
}
LOG(INFO) << "Using files lists, number of files " << req.fileInfo.size();
}
LOG(INFO) << "Making Sender with encryption set = "
<< req.encryptionData.isSet();
// TODO: find something more useful for namespace (userid ? directory?)
// (shardid at fb)
retCode = wdt.wdtSend(WdtResourceController::kGlobalNamespace, req,
setupAbortChecker());
}
cancelAbort();
if (retCode == OK) {
LOG(INFO) << "Returning with OK exit code";
} else {
LOG(ERROR) << "Returning with code " << retCode << " "
<< errorCodeToStr(retCode);
}
return retCode;
}
<|endoftext|> |
<commit_before>/*
This file is part of KAddressbook.
Copyright (c) 2003 Tobias Koenig <[email protected]>
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., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
As a special exception, permission is given to link this program
with any edition of Qt, and distribute the resulting executable,
without including the source code for Qt in the source distribution.
*/
#include <qfile.h>
#include <kfiledialog.h>
#include <kio/netaccess.h>
#include <klocale.h>
#include <kmessagebox.h>
#include <ktempfile.h>
#include <kurl.h>
#include "csvimportdialog.h"
#include "csv_xxport.h"
class CSVXXPortFactory : public XXPortFactory
{
public:
XXPortObject *xxportObject( KABC::AddressBook *ab, QWidget *parent, const char *name )
{
return new CSVXXPort( ab, parent, name );
}
};
extern "C"
{
void *init_libkaddrbk_csv_xxport()
{
return ( new CSVXXPortFactory() );
}
}
CSVXXPort::CSVXXPort( KABC::AddressBook *ab, QWidget *parent, const char *name )
: XXPortObject( ab, parent, name )
{
createImportAction( i18n( "Import CSV List..." ) );
createExportAction( i18n( "Export CSV List..." ) );
}
bool CSVXXPort::exportContacts( const KABC::AddresseeList &list, const QString& )
{
KURL url = KFileDialog::getSaveURL( "addressbook.csv" );
if ( url.isEmpty() )
return true;
if ( !url.isLocalFile() ) {
KTempFile tmpFile;
if ( tmpFile.status() != 0 ) {
QString txt = i18n( "<qt>Unable to open file <b>%1</b>.%2.</qt>" );
KMessageBox::error( parentWidget(), txt.arg( url.url() )
.arg( strerror( tmpFile.status() ) ) );
return false;
}
doExport( tmpFile.file(), list );
tmpFile.close();
return KIO::NetAccess::upload( tmpFile.name(), url, parentWidget() );
} else {
QFile file( url.path() );
if ( !file.open( IO_WriteOnly ) ) {
QString txt = i18n( "<qt>Unable to open file <b>%1</b>.</qt>" );
KMessageBox::error( parentWidget(), txt.arg( url.path() ) );
return false;
}
doExport( &file, list );
file.close();
return true;
}
}
KABC::AddresseeList CSVXXPort::importContacts( const QString& ) const
{
CSVImportDialog dlg( addressBook(), parentWidget() );
if ( dlg.exec() )
return dlg.contacts();
else
return KABC::AddresseeList();
}
void CSVXXPort::doExport( QFile *fp, const KABC::AddresseeList &list )
{
QTextStream t( fp );
KABC::AddresseeList::ConstIterator iter;
KABC::Field::List fields = addressBook()->fields();
KABC::Field::List::Iterator fieldIter;
bool first = true;
// First output the column headings
for ( fieldIter = fields.begin(); fieldIter != fields.end(); ++fieldIter ) {
if ( !first )
t << ",";
t << "\"" << (*fieldIter)->label() << "\"";
first = false;
}
t << "\n";
// Then all the addressee objects
KABC::Addressee addr;
for ( iter = list.begin(); iter != list.end(); ++iter ) {
addr = *iter;
first = true;
for ( fieldIter = fields.begin(); fieldIter != fields.end(); ++fieldIter ) {
if ( !first )
t << ",";
t << "\"" << (*fieldIter)->value( addr ).replace( "\n", "\\n" ) << "\"";
first = false;
}
t << "\n";
}
}
#include "csv_xxport.moc"
<commit_msg>Export csv with QTextStream::Locale encoding.<commit_after>/*
This file is part of KAddressbook.
Copyright (c) 2003 Tobias Koenig <[email protected]>
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., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
As a special exception, permission is given to link this program
with any edition of Qt, and distribute the resulting executable,
without including the source code for Qt in the source distribution.
*/
#include <qfile.h>
#include <kfiledialog.h>
#include <kio/netaccess.h>
#include <klocale.h>
#include <kmessagebox.h>
#include <ktempfile.h>
#include <kurl.h>
#include "csvimportdialog.h"
#include "csv_xxport.h"
class CSVXXPortFactory : public XXPortFactory
{
public:
XXPortObject *xxportObject( KABC::AddressBook *ab, QWidget *parent, const char *name )
{
return new CSVXXPort( ab, parent, name );
}
};
extern "C"
{
void *init_libkaddrbk_csv_xxport()
{
return ( new CSVXXPortFactory() );
}
}
CSVXXPort::CSVXXPort( KABC::AddressBook *ab, QWidget *parent, const char *name )
: XXPortObject( ab, parent, name )
{
createImportAction( i18n( "Import CSV List..." ) );
createExportAction( i18n( "Export CSV List..." ) );
}
bool CSVXXPort::exportContacts( const KABC::AddresseeList &list, const QString& )
{
KURL url = KFileDialog::getSaveURL( "addressbook.csv" );
if ( url.isEmpty() )
return true;
if ( !url.isLocalFile() ) {
KTempFile tmpFile;
if ( tmpFile.status() != 0 ) {
QString txt = i18n( "<qt>Unable to open file <b>%1</b>.%2.</qt>" );
KMessageBox::error( parentWidget(), txt.arg( url.url() )
.arg( strerror( tmpFile.status() ) ) );
return false;
}
doExport( tmpFile.file(), list );
tmpFile.close();
return KIO::NetAccess::upload( tmpFile.name(), url, parentWidget() );
} else {
QFile file( url.path() );
if ( !file.open( IO_WriteOnly ) ) {
QString txt = i18n( "<qt>Unable to open file <b>%1</b>.</qt>" );
KMessageBox::error( parentWidget(), txt.arg( url.path() ) );
return false;
}
doExport( &file, list );
file.close();
return true;
}
}
KABC::AddresseeList CSVXXPort::importContacts( const QString& ) const
{
CSVImportDialog dlg( addressBook(), parentWidget() );
if ( dlg.exec() )
return dlg.contacts();
else
return KABC::AddresseeList();
}
void CSVXXPort::doExport( QFile *fp, const KABC::AddresseeList &list )
{
QTextStream t( fp );
t.setEncoding( QTextStream::Locale );
KABC::AddresseeList::ConstIterator iter;
KABC::Field::List fields = addressBook()->fields();
KABC::Field::List::Iterator fieldIter;
bool first = true;
// First output the column headings
for ( fieldIter = fields.begin(); fieldIter != fields.end(); ++fieldIter ) {
if ( !first )
t << ",";
t << "\"" << (*fieldIter)->label() << "\"";
first = false;
}
t << "\n";
// Then all the addressee objects
KABC::Addressee addr;
for ( iter = list.begin(); iter != list.end(); ++iter ) {
addr = *iter;
first = true;
for ( fieldIter = fields.begin(); fieldIter != fields.end(); ++fieldIter ) {
if ( !first )
t << ",";
t << "\"" << (*fieldIter)->value( addr ).replace( "\n", "\\n" ) << "\"";
first = false;
}
t << "\n";
}
}
#include "csv_xxport.moc"
<|endoftext|> |
<commit_before><commit_msg>[Backport] Aura: enable the touch events dispatch in DesktopRootWindowHostX11<commit_after><|endoftext|> |
<commit_before><commit_msg>ATO-418-Updated test macro<commit_after><|endoftext|> |
<commit_before>/*
-----------------------------------------------------------------------------
This source file is part of OGRE
(Object-oriented Graphics Rendering Engine)
For the latest info, see http://www.ogre3d.org/
Copyright (c) 2000-2014 Torus Knot Software Ltd
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 <OgreZip.h>
#include "SamplePlugin.h"
#include "CharacterSample.h"
#include <emscripten/html5.h>
#include "Context.h"
Context::Context()
: OgreBites::SampleContext("OGRE Emscripten Sample", false), mBuffer(NULL), mNode(NULL)
{
}
bool Context::mouseWheelRolled(const OgreBites::MouseWheelEvent& evt) {
OgreBites::MouseWheelEvent _evt = evt;
// chrome reports values of 53 here
_evt.y = std::min(3, std::max(-3, evt.y));
return OgreBites::SampleContext::mouseWheelRolled(evt);
}
void Context::_mainLoop(void* target)
{
Context* thizz = static_cast<Context*>(target);
if (thizz->mRoot->endRenderingQueued())
{
emscripten_cancel_main_loop();
}
else
{
try
{
//Pump messages in all registered RenderWindow windows
Ogre::WindowEventUtilities::messagePump();
if (!thizz->mRoot->renderOneFrame())
{
emscripten_cancel_main_loop();
}
}
catch (Ogre::Exception& e)
{
size_t length = emscripten_get_callstack(EM_LOG_C_STACK | EM_LOG_DEMANGLE | EM_LOG_NO_PATHS | EM_LOG_FUNC_PARAMS,0,0) + 50;
char* buffer = new char[length];
emscripten_get_callstack(EM_LOG_C_STACK | EM_LOG_DEMANGLE | EM_LOG_NO_PATHS | EM_LOG_FUNC_PARAMS, buffer, length);
Ogre::LogManager::getSingleton().logMessage(buffer);
delete[] buffer;
emscripten_pause_main_loop();
}
}
}
void Context::unloadResource(Ogre::ResourceManager* resMgr, const Ogre::String& resourceName)
{
Ogre::ResourcePtr rPtr = resMgr->getResourceByName(resourceName, "General");
if (!rPtr)
return;
rPtr->unload();
resMgr->remove(resourceName, "General");
}
void Context::destroyMaterials( const Ogre::String& resourceGroupID )
{
try
{
Ogre::MaterialManager* materialManager = Ogre::MaterialManager::getSingletonPtr();
Ogre::ResourceManager::ResourceMapIterator resourceIterator = materialManager->getResourceIterator();
std::vector< std::string > materialNamesToRemove;
while( resourceIterator.hasMoreElements() )
{
Ogre::ResourcePtr material = resourceIterator.getNext();
std::string matName = material->getName();
if( resourceGroupID == material->getGroup())
{
mShaderGenerator->removeAllShaderBasedTechniques( matName, material->getGroup() );
material->unload();
material.reset();
materialNamesToRemove.push_back( matName );
}
}
for( size_t i = 0; i < materialNamesToRemove.size(); ++i )
{
materialManager->remove( materialNamesToRemove[i], resourceGroupID );
}
materialManager->removeUnreferencedResources();
}
catch( ... )
{
Ogre::LogManager::getSingleton().logMessage("An Error occurred trying to destroy Materials in " + resourceGroupID);
}
}
void Context::destroyTextures( const Ogre::String& resourceGroupID )
{
try
{
Ogre::TextureManager* textureManager = Ogre::TextureManager::getSingletonPtr();
Ogre::ResourceManager::ResourceMapIterator resourceIterator = textureManager->getResourceIterator();
std::vector< std::string > textureNamesToRemove;
while( resourceIterator.hasMoreElements() )
{
Ogre::ResourcePtr texture = resourceIterator.getNext();
Ogre::String resourceName = texture->getName();
if( resourceGroupID == texture->getGroup())
{
texture->unload();
texture.reset();
textureNamesToRemove.push_back( resourceName );
}
}
for( size_t i = 0; i < textureNamesToRemove.size(); ++i )
{
textureManager->remove( textureNamesToRemove[i], resourceGroupID );
}
}
catch( ... )
{
Ogre::LogManager::getSingleton().logMessage("An Error occurred trying to destroy Textures in " + resourceGroupID);
}
}
void Context::clearScene()
{
if (mBuffer != NULL)
{
auto it = mNode->getAttachedObjectIterator();
while (it.hasMoreElements())
{
//mSceneMgr->destroyMovableObject(it.getNext());
}
mNode->detachAllObjects();
Ogre::MaterialManager* matMgr = Ogre::MaterialManager::getSingletonPtr();
matMgr->removeUnreferencedResources();
Ogre::MeshManager* meshMgr = Ogre::MeshManager::getSingletonPtr();
meshMgr->unloadUnreferencedResources();
Ogre::TextureManager* texMgr = Ogre::TextureManager::getSingletonPtr();
texMgr->removeUnreferencedResources();
if( Ogre::ResourceGroupManager::getSingleton().resourceGroupExists("Download") && Ogre::ResourceGroupManager::getSingleton().isResourceGroupInitialised("Download") )
{
destroyMaterials( "Download" );
destroyTextures( "Download" );
Ogre::ResourceGroupManager::getSingleton().removeResourceLocation( "download.zip" );
Ogre::ResourceGroupManager::getSingleton().destroyResourceGroup( "Download" );
}
Ogre::EmbeddedZipArchiveFactory::removeEmbbeddedFile("download.zip");
mShaderGenerator->removeAllShaderBasedTechniques();
mShaderGenerator->flushShaderCache();
//free(mBuffer);
mBuffer = NULL;
}
}
void Context::passAssetAsArrayBuffer(unsigned char* arr, int length) {
try {
clearScene();
Ogre::ResourceGroupManager::getSingleton().createResourceGroup("Download");
mBuffer = arr;
Ogre::EmbeddedZipArchiveFactory::addEmbbeddedFile("download.zip", mBuffer, length, NULL);
Ogre::ResourceGroupManager::getSingleton().addResourceLocation("download.zip","EmbeddedZip","Download");
Ogre::ResourceGroupManager::getSingleton().initialiseResourceGroup("Download");
Ogre::StringVectorPtr meshes = Ogre::ArchiveManager::getSingleton().load("download.zip","EmbeddedZip",true)->find("*.mesh");
for (auto i : *meshes)
{
//mNode->attachObject(mSceneMgr->createEntity(i));
}
} catch (Ogre::Exception& ex) {
Ogre::LogManager::getSingleton().logMessage(ex.what());
}
}
void Context::setup() {
OgreBites::ApplicationContext::setup();
mCurrentSample = new Sample_Character();
mCurrentSample->setShaderGenerator(mShaderGenerator);
mCurrentSample->_setup(mWindow, mFSLayer, mOverlaySystem);
}
<commit_msg>Samples: Emscripten - update to new Bites API<commit_after>/*
-----------------------------------------------------------------------------
This source file is part of OGRE
(Object-oriented Graphics Rendering Engine)
For the latest info, see http://www.ogre3d.org/
Copyright (c) 2000-2014 Torus Knot Software Ltd
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 <OgreZip.h>
#include "SamplePlugin.h"
#include "CharacterSample.h"
#include <emscripten/html5.h>
#include "Context.h"
Context::Context()
: OgreBites::SampleContext("OGRE Emscripten Sample", false), mBuffer(NULL), mNode(NULL)
{
}
bool Context::mouseWheelRolled(const OgreBites::MouseWheelEvent& evt) {
OgreBites::MouseWheelEvent _evt = evt;
// chrome reports values of 53 here
_evt.y = std::min(3, std::max(-3, evt.y));
return OgreBites::SampleContext::mouseWheelRolled(evt);
}
void Context::_mainLoop(void* target)
{
Context* thizz = static_cast<Context*>(target);
if (thizz->mRoot->endRenderingQueued())
{
emscripten_cancel_main_loop();
}
else
{
try
{
//Pump messages in all registered RenderWindow windows
Ogre::WindowEventUtilities::messagePump();
if (!thizz->mRoot->renderOneFrame())
{
emscripten_cancel_main_loop();
}
}
catch (Ogre::Exception& e)
{
size_t length = emscripten_get_callstack(EM_LOG_C_STACK | EM_LOG_DEMANGLE | EM_LOG_NO_PATHS | EM_LOG_FUNC_PARAMS,0,0) + 50;
char* buffer = new char[length];
emscripten_get_callstack(EM_LOG_C_STACK | EM_LOG_DEMANGLE | EM_LOG_NO_PATHS | EM_LOG_FUNC_PARAMS, buffer, length);
Ogre::LogManager::getSingleton().logMessage(buffer);
delete[] buffer;
emscripten_pause_main_loop();
}
}
}
void Context::unloadResource(Ogre::ResourceManager* resMgr, const Ogre::String& resourceName)
{
Ogre::ResourcePtr rPtr = resMgr->getResourceByName(resourceName, "General");
if (!rPtr)
return;
rPtr->unload();
resMgr->remove(resourceName, "General");
}
void Context::destroyMaterials( const Ogre::String& resourceGroupID )
{
try
{
Ogre::MaterialManager* materialManager = Ogre::MaterialManager::getSingletonPtr();
Ogre::ResourceManager::ResourceMapIterator resourceIterator = materialManager->getResourceIterator();
std::vector< std::string > materialNamesToRemove;
while( resourceIterator.hasMoreElements() )
{
Ogre::ResourcePtr material = resourceIterator.getNext();
std::string matName = material->getName();
if( resourceGroupID == material->getGroup())
{
mShaderGenerator->removeAllShaderBasedTechniques( matName, material->getGroup() );
material->unload();
material.reset();
materialNamesToRemove.push_back( matName );
}
}
for( size_t i = 0; i < materialNamesToRemove.size(); ++i )
{
materialManager->remove( materialNamesToRemove[i], resourceGroupID );
}
materialManager->removeUnreferencedResources();
}
catch( ... )
{
Ogre::LogManager::getSingleton().logMessage("An Error occurred trying to destroy Materials in " + resourceGroupID);
}
}
void Context::destroyTextures( const Ogre::String& resourceGroupID )
{
try
{
Ogre::TextureManager* textureManager = Ogre::TextureManager::getSingletonPtr();
Ogre::ResourceManager::ResourceMapIterator resourceIterator = textureManager->getResourceIterator();
std::vector< std::string > textureNamesToRemove;
while( resourceIterator.hasMoreElements() )
{
Ogre::ResourcePtr texture = resourceIterator.getNext();
Ogre::String resourceName = texture->getName();
if( resourceGroupID == texture->getGroup())
{
texture->unload();
texture.reset();
textureNamesToRemove.push_back( resourceName );
}
}
for( size_t i = 0; i < textureNamesToRemove.size(); ++i )
{
textureManager->remove( textureNamesToRemove[i], resourceGroupID );
}
}
catch( ... )
{
Ogre::LogManager::getSingleton().logMessage("An Error occurred trying to destroy Textures in " + resourceGroupID);
}
}
void Context::clearScene()
{
if (mBuffer != NULL)
{
auto it = mNode->getAttachedObjectIterator();
while (it.hasMoreElements())
{
//mSceneMgr->destroyMovableObject(it.getNext());
}
mNode->detachAllObjects();
Ogre::MaterialManager* matMgr = Ogre::MaterialManager::getSingletonPtr();
matMgr->removeUnreferencedResources();
Ogre::MeshManager* meshMgr = Ogre::MeshManager::getSingletonPtr();
meshMgr->unloadUnreferencedResources();
Ogre::TextureManager* texMgr = Ogre::TextureManager::getSingletonPtr();
texMgr->removeUnreferencedResources();
if( Ogre::ResourceGroupManager::getSingleton().resourceGroupExists("Download") && Ogre::ResourceGroupManager::getSingleton().isResourceGroupInitialised("Download") )
{
destroyMaterials( "Download" );
destroyTextures( "Download" );
Ogre::ResourceGroupManager::getSingleton().removeResourceLocation( "download.zip" );
Ogre::ResourceGroupManager::getSingleton().destroyResourceGroup( "Download" );
}
Ogre::EmbeddedZipArchiveFactory::removeEmbbeddedFile("download.zip");
mShaderGenerator->removeAllShaderBasedTechniques();
mShaderGenerator->flushShaderCache();
//free(mBuffer);
mBuffer = NULL;
}
}
void Context::passAssetAsArrayBuffer(unsigned char* arr, int length) {
try {
clearScene();
Ogre::ResourceGroupManager::getSingleton().createResourceGroup("Download");
mBuffer = arr;
Ogre::EmbeddedZipArchiveFactory::addEmbbeddedFile("download.zip", mBuffer, length, NULL);
Ogre::ResourceGroupManager::getSingleton().addResourceLocation("download.zip","EmbeddedZip","Download");
Ogre::ResourceGroupManager::getSingleton().initialiseResourceGroup("Download");
Ogre::StringVectorPtr meshes = Ogre::ArchiveManager::getSingleton().load("download.zip","EmbeddedZip",true)->find("*.mesh");
for (auto i : *meshes)
{
//mNode->attachObject(mSceneMgr->createEntity(i));
}
} catch (Ogre::Exception& ex) {
Ogre::LogManager::getSingleton().logMessage(ex.what());
}
}
void Context::setup() {
OgreBites::ApplicationContext::setup();
mWindow = getRenderWindow();
addInputListener(this);
mCurrentSample = new Sample_Character();
mCurrentSample->setShaderGenerator(mShaderGenerator);
mCurrentSample->_setup(mWindow, mFSLayer, mOverlaySystem);
}
<|endoftext|> |
<commit_before>/*
*
* Copyright 2018 gRPC authors.
*
* 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 <grpc/support/port_platform.h>
#include "src/core/lib/security/security_connector/local/local_security_connector.h"
#include <stdbool.h>
#include <string.h>
#include <grpc/grpc.h>
#include <grpc/support/alloc.h>
#include <grpc/support/log.h>
#include <grpc/support/string_util.h>
#include "src/core/ext/filters/client_channel/client_channel.h"
#include "src/core/lib/channel/channel_args.h"
#include "src/core/lib/gprpp/ref_counted_ptr.h"
#include "src/core/lib/iomgr/pollset.h"
#include "src/core/lib/iomgr/resolve_address.h"
#include "src/core/lib/iomgr/sockaddr.h"
#include "src/core/lib/iomgr/sockaddr_utils.h"
#include "src/core/lib/iomgr/socket_utils.h"
#include "src/core/lib/iomgr/unix_sockets_posix.h"
#include "src/core/lib/security/credentials/local/local_credentials.h"
#include "src/core/lib/security/transport/security_handshaker.h"
#include "src/core/tsi/local_transport_security.h"
#define GRPC_UDS_URI_PATTERN "unix:"
#define GRPC_LOCAL_TRANSPORT_SECURITY_TYPE "local"
namespace {
grpc_core::RefCountedPtr<grpc_auth_context> local_auth_context_create(
const tsi_peer* peer) {
/* Create auth context. */
grpc_core::RefCountedPtr<grpc_auth_context> ctx =
grpc_core::MakeRefCounted<grpc_auth_context>(nullptr);
grpc_auth_context_add_cstring_property(
ctx.get(), GRPC_TRANSPORT_SECURITY_TYPE_PROPERTY_NAME,
GRPC_LOCAL_TRANSPORT_SECURITY_TYPE);
GPR_ASSERT(grpc_auth_context_set_peer_identity_property_name(
ctx.get(), GRPC_TRANSPORT_SECURITY_TYPE_PROPERTY_NAME) == 1);
GPR_ASSERT(peer->property_count == 1);
const tsi_peer_property* prop = &peer->properties[0];
GPR_ASSERT(prop != nullptr);
GPR_ASSERT(strcmp(prop->name, TSI_SECURITY_LEVEL_PEER_PROPERTY) == 0);
grpc_auth_context_add_property(ctx.get(),
GRPC_TRANSPORT_SECURITY_LEVEL_PROPERTY_NAME,
prop->value.data, prop->value.length);
return ctx;
}
void local_check_peer(grpc_security_connector* sc, tsi_peer peer,
grpc_endpoint* ep,
grpc_core::RefCountedPtr<grpc_auth_context>* auth_context,
grpc_closure* on_peer_checked,
grpc_local_connect_type type) {
int fd = grpc_endpoint_get_fd(ep);
grpc_resolved_address resolved_addr;
memset(&resolved_addr, 0, sizeof(resolved_addr));
resolved_addr.len = GRPC_MAX_SOCKADDR_SIZE;
bool is_endpoint_local = false;
if (getsockname(fd, reinterpret_cast<grpc_sockaddr*>(resolved_addr.addr),
&resolved_addr.len) == 0) {
grpc_resolved_address addr_normalized;
grpc_resolved_address* addr =
grpc_sockaddr_is_v4mapped(&resolved_addr, &addr_normalized)
? &addr_normalized
: &resolved_addr;
grpc_sockaddr* sock_addr = reinterpret_cast<grpc_sockaddr*>(&addr->addr);
// UDS
if (type == UDS && grpc_is_unix_socket(addr)) {
is_endpoint_local = true;
// IPV4
} else if (type == LOCAL_TCP && sock_addr->sa_family == GRPC_AF_INET) {
const grpc_sockaddr_in* addr4 =
reinterpret_cast<const grpc_sockaddr_in*>(sock_addr);
if (grpc_htonl(addr4->sin_addr.s_addr) == INADDR_LOOPBACK) {
is_endpoint_local = true;
}
// IPv6
} else if (type == LOCAL_TCP && sock_addr->sa_family == GRPC_AF_INET6) {
const grpc_sockaddr_in6* addr6 =
reinterpret_cast<const grpc_sockaddr_in6*>(addr);
if (memcmp(&addr6->sin6_addr, &in6addr_loopback,
sizeof(in6addr_loopback)) == 0) {
is_endpoint_local = true;
}
}
}
grpc_error* error = GRPC_ERROR_NONE;
if (!is_endpoint_local) {
error = GRPC_ERROR_CREATE_FROM_STATIC_STRING(
"Endpoint is neither UDS or TCP loopback address.");
grpc_core::ExecCtx::Run(DEBUG_LOCATION, on_peer_checked, error);
return;
}
// Add TSI_SECURITY_LEVEL_PEER_PROPERTY type peer property.
size_t new_property_count = peer.property_count + 1;
tsi_peer_property* new_properties = static_cast<tsi_peer_property*>(
gpr_zalloc(sizeof(*new_properties) * new_property_count));
for (size_t i = 0; i < peer.property_count; i++) {
new_properties[i] = peer.properties[i];
}
if (peer.properties != nullptr) gpr_free(peer.properties);
peer.properties = new_properties;
// TODO(yihuazhang): Set security level of local TCP to TSI_SECURITY_NONE.
const char* security_level =
tsi_security_level_to_string(TSI_PRIVACY_AND_INTEGRITY);
tsi_result result = tsi_construct_string_peer_property_from_cstring(
TSI_SECURITY_LEVEL_PEER_PROPERTY, security_level,
&peer.properties[peer.property_count]);
if (result != TSI_OK) return;
peer.property_count++;
/* Create an auth context which is necessary to pass the santiy check in
* {client, server}_auth_filter that verifies if the peer's auth context is
* obtained during handshakes. The auth context is only checked for its
* existence and not actually used.
*/
*auth_context = local_auth_context_create(&peer);
tsi_peer_destruct(&peer);
error = *auth_context != nullptr ? GRPC_ERROR_NONE
: GRPC_ERROR_CREATE_FROM_STATIC_STRING(
"Could not create local auth context");
grpc_core::ExecCtx::Run(DEBUG_LOCATION, on_peer_checked, error);
}
class grpc_local_channel_security_connector final
: public grpc_channel_security_connector {
public:
grpc_local_channel_security_connector(
grpc_core::RefCountedPtr<grpc_channel_credentials> channel_creds,
grpc_core::RefCountedPtr<grpc_call_credentials> request_metadata_creds,
const char* target_name)
: grpc_channel_security_connector(nullptr, std::move(channel_creds),
std::move(request_metadata_creds)),
target_name_(gpr_strdup(target_name)) {}
~grpc_local_channel_security_connector() override { gpr_free(target_name_); }
void add_handshakers(
const grpc_channel_args* args, grpc_pollset_set* /*interested_parties*/,
grpc_core::HandshakeManager* handshake_manager) override {
tsi_handshaker* handshaker = nullptr;
GPR_ASSERT(local_tsi_handshaker_create(true /* is_client */, &handshaker) ==
TSI_OK);
handshake_manager->Add(
grpc_core::SecurityHandshakerCreate(handshaker, this, args));
}
int cmp(const grpc_security_connector* other_sc) const override {
auto* other =
reinterpret_cast<const grpc_local_channel_security_connector*>(
other_sc);
int c = channel_security_connector_cmp(other);
if (c != 0) return c;
return strcmp(target_name_, other->target_name_);
}
void check_peer(tsi_peer peer, grpc_endpoint* ep,
grpc_core::RefCountedPtr<grpc_auth_context>* auth_context,
grpc_closure* on_peer_checked) override {
grpc_local_credentials* creds =
reinterpret_cast<grpc_local_credentials*>(mutable_channel_creds());
local_check_peer(this, peer, ep, auth_context, on_peer_checked,
creds->connect_type());
}
bool check_call_host(grpc_core::StringView host,
grpc_auth_context* /*auth_context*/,
grpc_closure* /*on_call_host_checked*/,
grpc_error** error) override {
if (host.empty() || host != target_name_) {
*error = GRPC_ERROR_CREATE_FROM_STATIC_STRING(
"local call host does not match target name");
}
return true;
}
void cancel_check_call_host(grpc_closure* /*on_call_host_checked*/,
grpc_error* error) override {
GRPC_ERROR_UNREF(error);
}
const char* target_name() const { return target_name_; }
private:
char* target_name_;
};
class grpc_local_server_security_connector final
: public grpc_server_security_connector {
public:
grpc_local_server_security_connector(
grpc_core::RefCountedPtr<grpc_server_credentials> server_creds)
: grpc_server_security_connector(nullptr, std::move(server_creds)) {}
~grpc_local_server_security_connector() override = default;
void add_handshakers(
const grpc_channel_args* args, grpc_pollset_set* /*interested_parties*/,
grpc_core::HandshakeManager* handshake_manager) override {
tsi_handshaker* handshaker = nullptr;
GPR_ASSERT(local_tsi_handshaker_create(false /* is_client */,
&handshaker) == TSI_OK);
handshake_manager->Add(
grpc_core::SecurityHandshakerCreate(handshaker, this, args));
}
void check_peer(tsi_peer peer, grpc_endpoint* ep,
grpc_core::RefCountedPtr<grpc_auth_context>* auth_context,
grpc_closure* on_peer_checked) override {
grpc_local_server_credentials* creds =
static_cast<grpc_local_server_credentials*>(mutable_server_creds());
local_check_peer(this, peer, ep, auth_context, on_peer_checked,
creds->connect_type());
}
int cmp(const grpc_security_connector* other) const override {
return server_security_connector_cmp(
static_cast<const grpc_server_security_connector*>(other));
}
};
} // namespace
grpc_core::RefCountedPtr<grpc_channel_security_connector>
grpc_local_channel_security_connector_create(
grpc_core::RefCountedPtr<grpc_channel_credentials> channel_creds,
grpc_core::RefCountedPtr<grpc_call_credentials> request_metadata_creds,
const grpc_channel_args* args, const char* target_name) {
if (channel_creds == nullptr || target_name == nullptr) {
gpr_log(
GPR_ERROR,
"Invalid arguments to grpc_local_channel_security_connector_create()");
return nullptr;
}
// Perform sanity check on UDS address. For TCP local connection, the check
// will be done during check_peer procedure.
grpc_local_credentials* creds =
static_cast<grpc_local_credentials*>(channel_creds.get());
const grpc_arg* server_uri_arg =
grpc_channel_args_find(args, GRPC_ARG_SERVER_URI);
const char* server_uri_str = grpc_channel_arg_get_string(server_uri_arg);
if (creds->connect_type() == UDS &&
strncmp(GRPC_UDS_URI_PATTERN, server_uri_str,
strlen(GRPC_UDS_URI_PATTERN)) != 0) {
gpr_log(GPR_ERROR,
"Invalid UDS target name to "
"grpc_local_channel_security_connector_create()");
return nullptr;
}
return grpc_core::MakeRefCounted<grpc_local_channel_security_connector>(
channel_creds, request_metadata_creds, target_name);
}
grpc_core::RefCountedPtr<grpc_server_security_connector>
grpc_local_server_security_connector_create(
grpc_core::RefCountedPtr<grpc_server_credentials> server_creds) {
if (server_creds == nullptr) {
gpr_log(
GPR_ERROR,
"Invalid arguments to grpc_local_server_security_connector_create()");
return nullptr;
}
return grpc_core::MakeRefCounted<grpc_local_server_security_connector>(
std::move(server_creds));
}
<commit_msg>update local tcp security level<commit_after>/*
*
* Copyright 2018 gRPC authors.
*
* 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 <grpc/support/port_platform.h>
#include "src/core/lib/security/security_connector/local/local_security_connector.h"
#include <stdbool.h>
#include <string.h>
#include <grpc/grpc.h>
#include <grpc/support/alloc.h>
#include <grpc/support/log.h>
#include <grpc/support/string_util.h>
#include "src/core/ext/filters/client_channel/client_channel.h"
#include "src/core/lib/channel/channel_args.h"
#include "src/core/lib/gprpp/ref_counted_ptr.h"
#include "src/core/lib/iomgr/pollset.h"
#include "src/core/lib/iomgr/resolve_address.h"
#include "src/core/lib/iomgr/sockaddr.h"
#include "src/core/lib/iomgr/sockaddr_utils.h"
#include "src/core/lib/iomgr/socket_utils.h"
#include "src/core/lib/iomgr/unix_sockets_posix.h"
#include "src/core/lib/security/credentials/local/local_credentials.h"
#include "src/core/lib/security/transport/security_handshaker.h"
#include "src/core/tsi/local_transport_security.h"
#define GRPC_UDS_URI_PATTERN "unix:"
#define GRPC_LOCAL_TRANSPORT_SECURITY_TYPE "local"
namespace {
grpc_core::RefCountedPtr<grpc_auth_context> local_auth_context_create(
const tsi_peer* peer) {
/* Create auth context. */
grpc_core::RefCountedPtr<grpc_auth_context> ctx =
grpc_core::MakeRefCounted<grpc_auth_context>(nullptr);
grpc_auth_context_add_cstring_property(
ctx.get(), GRPC_TRANSPORT_SECURITY_TYPE_PROPERTY_NAME,
GRPC_LOCAL_TRANSPORT_SECURITY_TYPE);
GPR_ASSERT(grpc_auth_context_set_peer_identity_property_name(
ctx.get(), GRPC_TRANSPORT_SECURITY_TYPE_PROPERTY_NAME) == 1);
GPR_ASSERT(peer->property_count == 1);
const tsi_peer_property* prop = &peer->properties[0];
GPR_ASSERT(prop != nullptr);
GPR_ASSERT(strcmp(prop->name, TSI_SECURITY_LEVEL_PEER_PROPERTY) == 0);
grpc_auth_context_add_property(ctx.get(),
GRPC_TRANSPORT_SECURITY_LEVEL_PROPERTY_NAME,
prop->value.data, prop->value.length);
return ctx;
}
void local_check_peer(grpc_security_connector* sc, tsi_peer peer,
grpc_endpoint* ep,
grpc_core::RefCountedPtr<grpc_auth_context>* auth_context,
grpc_closure* on_peer_checked,
grpc_local_connect_type type) {
int fd = grpc_endpoint_get_fd(ep);
grpc_resolved_address resolved_addr;
memset(&resolved_addr, 0, sizeof(resolved_addr));
resolved_addr.len = GRPC_MAX_SOCKADDR_SIZE;
bool is_endpoint_local = false;
if (getsockname(fd, reinterpret_cast<grpc_sockaddr*>(resolved_addr.addr),
&resolved_addr.len) == 0) {
grpc_resolved_address addr_normalized;
grpc_resolved_address* addr =
grpc_sockaddr_is_v4mapped(&resolved_addr, &addr_normalized)
? &addr_normalized
: &resolved_addr;
grpc_sockaddr* sock_addr = reinterpret_cast<grpc_sockaddr*>(&addr->addr);
// UDS
if (type == UDS && grpc_is_unix_socket(addr)) {
is_endpoint_local = true;
// IPV4
} else if (type == LOCAL_TCP && sock_addr->sa_family == GRPC_AF_INET) {
const grpc_sockaddr_in* addr4 =
reinterpret_cast<const grpc_sockaddr_in*>(sock_addr);
if (grpc_htonl(addr4->sin_addr.s_addr) == INADDR_LOOPBACK) {
is_endpoint_local = true;
}
// IPv6
} else if (type == LOCAL_TCP && sock_addr->sa_family == GRPC_AF_INET6) {
const grpc_sockaddr_in6* addr6 =
reinterpret_cast<const grpc_sockaddr_in6*>(addr);
if (memcmp(&addr6->sin6_addr, &in6addr_loopback,
sizeof(in6addr_loopback)) == 0) {
is_endpoint_local = true;
}
}
}
grpc_error* error = GRPC_ERROR_NONE;
if (!is_endpoint_local) {
error = GRPC_ERROR_CREATE_FROM_STATIC_STRING(
"Endpoint is neither UDS or TCP loopback address.");
grpc_core::ExecCtx::Run(DEBUG_LOCATION, on_peer_checked, error);
return;
}
// Add TSI_SECURITY_LEVEL_PEER_PROPERTY type peer property.
size_t new_property_count = peer.property_count + 1;
tsi_peer_property* new_properties = static_cast<tsi_peer_property*>(
gpr_zalloc(sizeof(*new_properties) * new_property_count));
for (size_t i = 0; i < peer.property_count; i++) {
new_properties[i] = peer.properties[i];
}
if (peer.properties != nullptr) gpr_free(peer.properties);
peer.properties = new_properties;
const char* security_level =
type == LOCAL_TCP
? tsi_security_level_to_string(TSI_SECURITY_NONE)
: tsi_security_level_to_string(TSI_PRIVACY_AND_INTEGRITY);
tsi_result result = tsi_construct_string_peer_property_from_cstring(
TSI_SECURITY_LEVEL_PEER_PROPERTY, security_level,
&peer.properties[peer.property_count]);
if (result != TSI_OK) return;
peer.property_count++;
/* Create an auth context which is necessary to pass the santiy check in
* {client, server}_auth_filter that verifies if the peer's auth context is
* obtained during handshakes. The auth context is only checked for its
* existence and not actually used.
*/
*auth_context = local_auth_context_create(&peer);
tsi_peer_destruct(&peer);
error = *auth_context != nullptr ? GRPC_ERROR_NONE
: GRPC_ERROR_CREATE_FROM_STATIC_STRING(
"Could not create local auth context");
grpc_core::ExecCtx::Run(DEBUG_LOCATION, on_peer_checked, error);
}
class grpc_local_channel_security_connector final
: public grpc_channel_security_connector {
public:
grpc_local_channel_security_connector(
grpc_core::RefCountedPtr<grpc_channel_credentials> channel_creds,
grpc_core::RefCountedPtr<grpc_call_credentials> request_metadata_creds,
const char* target_name)
: grpc_channel_security_connector(nullptr, std::move(channel_creds),
std::move(request_metadata_creds)),
target_name_(gpr_strdup(target_name)) {}
~grpc_local_channel_security_connector() override { gpr_free(target_name_); }
void add_handshakers(
const grpc_channel_args* args, grpc_pollset_set* /*interested_parties*/,
grpc_core::HandshakeManager* handshake_manager) override {
tsi_handshaker* handshaker = nullptr;
GPR_ASSERT(local_tsi_handshaker_create(true /* is_client */, &handshaker) ==
TSI_OK);
handshake_manager->Add(
grpc_core::SecurityHandshakerCreate(handshaker, this, args));
}
int cmp(const grpc_security_connector* other_sc) const override {
auto* other =
reinterpret_cast<const grpc_local_channel_security_connector*>(
other_sc);
int c = channel_security_connector_cmp(other);
if (c != 0) return c;
return strcmp(target_name_, other->target_name_);
}
void check_peer(tsi_peer peer, grpc_endpoint* ep,
grpc_core::RefCountedPtr<grpc_auth_context>* auth_context,
grpc_closure* on_peer_checked) override {
grpc_local_credentials* creds =
reinterpret_cast<grpc_local_credentials*>(mutable_channel_creds());
local_check_peer(this, peer, ep, auth_context, on_peer_checked,
creds->connect_type());
}
bool check_call_host(grpc_core::StringView host,
grpc_auth_context* /*auth_context*/,
grpc_closure* /*on_call_host_checked*/,
grpc_error** error) override {
if (host.empty() || host != target_name_) {
*error = GRPC_ERROR_CREATE_FROM_STATIC_STRING(
"local call host does not match target name");
}
return true;
}
void cancel_check_call_host(grpc_closure* /*on_call_host_checked*/,
grpc_error* error) override {
GRPC_ERROR_UNREF(error);
}
const char* target_name() const { return target_name_; }
private:
char* target_name_;
};
class grpc_local_server_security_connector final
: public grpc_server_security_connector {
public:
grpc_local_server_security_connector(
grpc_core::RefCountedPtr<grpc_server_credentials> server_creds)
: grpc_server_security_connector(nullptr, std::move(server_creds)) {}
~grpc_local_server_security_connector() override = default;
void add_handshakers(
const grpc_channel_args* args, grpc_pollset_set* /*interested_parties*/,
grpc_core::HandshakeManager* handshake_manager) override {
tsi_handshaker* handshaker = nullptr;
GPR_ASSERT(local_tsi_handshaker_create(false /* is_client */,
&handshaker) == TSI_OK);
handshake_manager->Add(
grpc_core::SecurityHandshakerCreate(handshaker, this, args));
}
void check_peer(tsi_peer peer, grpc_endpoint* ep,
grpc_core::RefCountedPtr<grpc_auth_context>* auth_context,
grpc_closure* on_peer_checked) override {
grpc_local_server_credentials* creds =
static_cast<grpc_local_server_credentials*>(mutable_server_creds());
local_check_peer(this, peer, ep, auth_context, on_peer_checked,
creds->connect_type());
}
int cmp(const grpc_security_connector* other) const override {
return server_security_connector_cmp(
static_cast<const grpc_server_security_connector*>(other));
}
};
} // namespace
grpc_core::RefCountedPtr<grpc_channel_security_connector>
grpc_local_channel_security_connector_create(
grpc_core::RefCountedPtr<grpc_channel_credentials> channel_creds,
grpc_core::RefCountedPtr<grpc_call_credentials> request_metadata_creds,
const grpc_channel_args* args, const char* target_name) {
if (channel_creds == nullptr || target_name == nullptr) {
gpr_log(
GPR_ERROR,
"Invalid arguments to grpc_local_channel_security_connector_create()");
return nullptr;
}
// Perform sanity check on UDS address. For TCP local connection, the check
// will be done during check_peer procedure.
grpc_local_credentials* creds =
static_cast<grpc_local_credentials*>(channel_creds.get());
const grpc_arg* server_uri_arg =
grpc_channel_args_find(args, GRPC_ARG_SERVER_URI);
const char* server_uri_str = grpc_channel_arg_get_string(server_uri_arg);
if (creds->connect_type() == UDS &&
strncmp(GRPC_UDS_URI_PATTERN, server_uri_str,
strlen(GRPC_UDS_URI_PATTERN)) != 0) {
gpr_log(GPR_ERROR,
"Invalid UDS target name to "
"grpc_local_channel_security_connector_create()");
return nullptr;
}
return grpc_core::MakeRefCounted<grpc_local_channel_security_connector>(
channel_creds, request_metadata_creds, target_name);
}
grpc_core::RefCountedPtr<grpc_server_security_connector>
grpc_local_server_security_connector_create(
grpc_core::RefCountedPtr<grpc_server_credentials> server_creds) {
if (server_creds == nullptr) {
gpr_log(
GPR_ERROR,
"Invalid arguments to grpc_local_server_security_connector_create()");
return nullptr;
}
return grpc_core::MakeRefCounted<grpc_local_server_security_connector>(
std::move(server_creds));
}
<|endoftext|> |
<commit_before>// Copyright (c) 2017 The Khronos Group Inc.
// Copyright (c) 2017 Valve Corporation
// Copyright (c) 2017 LunarG, Inc.
//
// 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.
//
// Authors: Mark Young <[email protected]>
// Nat Brown <[email protected]>
//
#include <cstring>
#include "xr_dependencies.h"
#if defined DISABLE_STD_FILESYSTEM
#define USE_EXPERIMENTAL_FS 0
#define USE_FINAL_FS 0
#else
// If the C++ macro is set to the version containing C++17, it must support
// the final C++17 package
#if __cplusplus >= 201703L
#define USE_EXPERIMENTAL_FS 0
#define USE_FINAL_FS 1
#elif defined(_MSC_VER) && _MSC_VER >= 1900
#if defined(_HAS_CXX17) && _HAS_CXX17
// When MSC supports c++17 use <filesystem> package.
#define USE_EXPERIMENTAL_FS 0
#define USE_FINAL_FS 1
#else
// MSC before c++17 need to use <experimental/filesystem> package.
#define USE_EXPERIMENTAL_FS 1
#define USE_FINAL_FS 0
#endif // !_HAS_CXX17
// Right now, GCC still only supports the experimental filesystem items starting in GCC 6
#elif (__GNUC__ >= 6)
#define USE_EXPERIMENTAL_FS 1
#define USE_FINAL_FS 0
// If Clang, check for feature support
#elif defined(__clang__) && (__cpp_lib_filesystem || __cpp_lib_experimental_filesystem)
#if __cpp_lib_filesystem
#define USE_EXPERIMENTAL_FS 0
#define USE_FINAL_FS 1
#else
#define USE_EXPERIMENTAL_FS 1
#define USE_FINAL_FS 0
#endif
// If all above fails, fall back to standard C++ and OS-specific items
#else
#define USE_EXPERIMENTAL_FS 0
#define USE_FINAL_FS 0
#endif
#endif
#if USE_FINAL_FS == 1
#include <filesystem>
#define FS_PREFIX std::filesystem
#elif USE_EXPERIMENTAL_FS == 1
#if (WINAPI_FAMILY != WINAPI_FAMILY_DESKTOP_APP)
#error "Windows universal application doesn't support system::experimental::filesystem"
#endif
#include <experimental/filesystem>
#define FS_PREFIX std::experimental::filesystem
#elif defined(XR_USE_PLATFORM_WIN32)
// Windows fallback includes
#include <stdint.h>
#include <direct.h>
#include <shlwapi.h>
#else
// Linux/Apple fallback includes
#include <sys/stat.h>
#include <sys/param.h>
#include <unistd.h>
#include <limits.h>
#include <stdlib.h>
#include <dirent.h>
#endif
#include "filesystem_utils.hpp"
#if defined(XR_USE_PLATFORM_WIN32)
#define PATH_SEPARATOR ';'
#define DIRECTORY_SYMBOL '\\'
#else
#define PATH_SEPARATOR ':'
#define DIRECTORY_SYMBOL '/'
#endif
#if (USE_FINAL_FS == 1) || (USE_EXPERIMENTAL_FS == 1)
// We can use one of the C++ filesystem packages
bool FileSysUtilsIsRegularFile(const std::string& path) {
try {
return FS_PREFIX::is_regular_file(path);
} catch (...) {
return false;
}
}
bool FileSysUtilsIsDirectory(const std::string& path) {
try {
return FS_PREFIX::is_directory(path);
} catch (...) {
return false;
}
}
bool FileSysUtilsPathExists(const std::string& path) {
try {
return FS_PREFIX::exists(path);
} catch (...) {
return false;
}
}
bool FileSysUtilsIsAbsolutePath(const std::string& path) {
try {
FS_PREFIX::path file_path(path);
return file_path.is_absolute();
} catch (...) {
return false;
}
}
bool FileSysUtilsGetCurrentPath(std::string& path) {
try {
FS_PREFIX::path cur_path = FS_PREFIX::current_path();
path = cur_path.string();
return true;
} catch (...) {
}
return false;
}
bool FileSysUtilsGetParentPath(const std::string& file_path, std::string& parent_path) {
try {
FS_PREFIX::path path_var(file_path);
parent_path = path_var.parent_path().string();
return true;
} catch (...) {
}
return false;
}
bool FileSysUtilsGetAbsolutePath(const std::string& path, std::string& absolute) {
try {
absolute = FS_PREFIX::absolute(path).string();
return true;
} catch (...) {
}
return false;
}
bool FileSysUtilsCombinePaths(const std::string& parent, const std::string& child, std::string& combined) {
try {
FS_PREFIX::path parent_path(parent);
FS_PREFIX::path child_path(child);
FS_PREFIX::path full_path = parent_path / child_path;
combined = full_path.string();
return true;
} catch (...) {
}
return false;
}
bool FileSysUtilsParsePathList(std::string& path_list, std::vector<std::string>& paths) {
try {
std::string::size_type start = 0;
std::string::size_type location = path_list.find(PATH_SEPARATOR);
while (location != std::string::npos) {
paths.push_back(path_list.substr(start, location));
start = location + 1;
location = path_list.find(PATH_SEPARATOR, start);
}
paths.push_back(path_list.substr(start, location));
return true;
} catch (...) {
}
return false;
}
bool FileSysUtilsFindFilesInPath(const std::string& path, std::vector<std::string>& files) {
try {
for (auto& dir_iter : FS_PREFIX::directory_iterator(path)) {
files.push_back(dir_iter.path().filename().string());
}
return true;
} catch (...) {
}
return false;
}
#elif defined(XR_OS_WINDOWS)
// Workaround for MS VS 2010/2013 don't support the experimental filesystem
bool FileSysUtilsIsRegularFile(const std::string& path) {
try {
return (1 != PathIsDirectoryA(path.c_str()));
} catch (...) {
return false;
}
}
bool FileSysUtilsIsDirectory(const std::string& path) {
try {
return (1 == PathIsDirectoryA(path.c_str()));
} catch (...) {
return false;
}
}
bool FileSysUtilsPathExists(const std::string& path) {
try {
return (1 == PathFileExistsA(path.c_str()));
} catch (...) {
return false;
}
}
bool FileSysUtilsIsAbsolutePath(const std::string& path) {
try {
if ((path[0] == '\\') || (path[1] == ':' && (path[2] == '\\' || path[2] == '/'))) {
return true;
}
} catch (...) {
}
return false;
}
bool FileSysUtilsGetCurrentPath(std::string& path) {
try {
char tmp_path[MAX_PATH];
if (nullptr != _getcwd(tmp_path, MAX_PATH - 1)) {
path = tmp_path;
return true;
}
} catch (...) {
}
return false;
}
bool FileSysUtilsGetParentPath(const std::string& file_path, std::string& parent_path) {
try {
std::string full_path;
if (FileSysUtilsGetAbsolutePath(file_path, full_path)) {
std::string::size_type lastSeperator = full_path.find_last_of(DIRECTORY_SYMBOL);
parent_path = (lastSeperator == 0) ? full_path : full_path.substr(0, lastSeperator - 1);
return true;
}
} catch (...) {
}
return false;
}
bool FileSysUtilsGetAbsolutePath(const std::string& path, std::string& absolute) {
try {
char tmp_path[MAX_PATH];
if (0 != GetFullPathNameA(path.c_str(), MAX_PATH, tmp_path, NULL)) {
absolute = tmp_path;
return true;
}
} catch (...) {
}
return false;
}
bool FileSysUtilsCombinePaths(const std::string& parent, const std::string& child, std::string& combined) {
try {
std::string::size_type parent_len = parent.length();
if (0 == parent_len || "." == parent || ".\\" == parent || "./" == parent) {
combined = child;
return true;
}
char last_char = parent[parent_len - 1];
if (last_char == DIRECTORY_SYMBOL) {
parent_len--;
}
combined = parent.substr(0, parent_len) + DIRECTORY_SYMBOL + child;
return true;
} catch (...) {
}
return false;
}
bool FileSysUtilsParsePathList(std::string& path_list, std::vector<std::string>& paths) {
try {
std::string::size_type start = 0;
std::string::size_type location = path_list.find(PATH_SEPARATOR);
while (location != std::string::npos) {
paths.push_back(path_list.substr(start, location));
start = location + 1;
location = path_list.find(PATH_SEPARATOR, start);
}
paths.push_back(path_list.substr(start, location));
return true;
} catch (...) {
}
return false;
}
bool FileSysUtilsFindFilesInPath(const std::string& path, std::vector<std::string>& files) {
try {
WIN32_FIND_DATA file_data;
HANDLE file_handle = FindFirstFileA(path.c_str(), &file_data);
if (file_handle != INVALID_HANDLE_VALUE) {
do {
if (!(file_data.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)) {
files.push_back(file_data.cFileName);
}
} while (FindNextFile(file_handle, &file_data));
return true;
}
} catch (...) {
}
return false;
}
#else // XR_OS_LINUX/XR_OS_APPLE fallback
#include <sys/stat.h>
#include <sys/param.h>
#include <unistd.h>
#include <stdlib.h>
#include <dirent.h>
// simple POSIX-compatible implementation of the <filesystem> pieces used by OpenXR
bool FileSysUtilsIsRegularFile(const std::string& path) {
try {
struct stat path_stat;
stat(path.c_str(), &path_stat);
return S_ISREG(path_stat.st_mode);
} catch (...) {
}
return false;
}
bool FileSysUtilsIsDirectory(const std::string& path) {
try {
struct stat path_stat;
stat(path.c_str(), &path_stat);
return S_ISDIR(path_stat.st_mode);
} catch (...) {
}
return false;
}
bool FileSysUtilsPathExists(const std::string& path) {
try {
return (access(path.c_str(), F_OK) != -1);
} catch (...) {
}
return false;
}
bool FileSysUtilsIsAbsolutePath(const std::string& path) {
try {
return (path[0] == DIRECTORY_SYMBOL);
} catch (...) {
}
return false;
}
bool FileSysUtilsGetCurrentPath(std::string& path) {
try {
char tmp_path[PATH_MAX];
if (nullptr != getcwd(tmp_path, PATH_MAX - 1)) {
path = tmp_path;
return true;
}
} catch (...) {
}
return false;
}
bool FileSysUtilsGetParentPath(const std::string& file_path, std::string& parent_path) {
try {
std::string full_path;
if (FileSysUtilsGetAbsolutePath(file_path, full_path)) {
std::string::size_type lastSeperator = full_path.find_last_of(DIRECTORY_SYMBOL);
parent_path = (lastSeperator == 0) ? full_path : full_path.substr(0, lastSeperator - 1);
return true;
}
} catch (...) {
}
return false;
}
bool FileSysUtilsGetAbsolutePath(const std::string& path, std::string& absolute) {
try {
char buf[PATH_MAX];
if (nullptr != realpath(path.c_str(), buf)) {
absolute = buf;
return true;
}
} catch (...) {
}
return false;
}
bool FileSysUtilsCombinePaths(const std::string& parent, const std::string& child, std::string& combined) {
try {
std::string::size_type parent_len = parent.length();
if (0 == parent_len || "." == parent || "./" == parent) {
combined = child;
return true;
}
char last_char = parent[parent_len - 1];
if (last_char == DIRECTORY_SYMBOL) {
parent_len--;
}
combined = parent.substr(0, parent_len) + DIRECTORY_SYMBOL + child;
return true;
} catch (...) {
}
return false;
}
bool FileSysUtilsParsePathList(std::string& path_list, std::vector<std::string>& paths) {
try {
std::string::size_type start = 0;
std::string::size_type location = path_list.find(PATH_SEPARATOR);
while (location != std::string::npos) {
paths.push_back(path_list.substr(start, location));
start = location + 1;
location = path_list.find(PATH_SEPARATOR, start);
}
paths.push_back(path_list.substr(start, location));
return true;
} catch (...) {
}
return false;
}
bool FileSysUtilsFindFilesInPath(const std::string& path, std::vector<std::string>& files) {
try {
DIR* dir;
struct dirent* entry;
dir = opendir(path.c_str());
while (dir && (entry = readdir(dir))) {
files.push_back(entry->d_name);
}
closedir(dir);
return true;
} catch (...) {
}
return false;
}
#endif
<commit_msg>make filesystem_util unicode compatible when USE_EXPERIMENTAL_FS=0 and USE_FINAL_FS=0<commit_after>// Copyright (c) 2017 The Khronos Group Inc.
// Copyright (c) 2017 Valve Corporation
// Copyright (c) 2017 LunarG, Inc.
//
// 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.
//
// Authors: Mark Young <[email protected]>
// Nat Brown <[email protected]>
//
#include <cstring>
#include "xr_dependencies.h"
#if defined DISABLE_STD_FILESYSTEM
#define USE_EXPERIMENTAL_FS 0
#define USE_FINAL_FS 0
#else
// If the C++ macro is set to the version containing C++17, it must support
// the final C++17 package
#if __cplusplus >= 201703L
#define USE_EXPERIMENTAL_FS 0
#define USE_FINAL_FS 1
#elif defined(_MSC_VER) && _MSC_VER >= 1900
#if defined(_HAS_CXX17) && _HAS_CXX17
// When MSC supports c++17 use <filesystem> package.
#define USE_EXPERIMENTAL_FS 0
#define USE_FINAL_FS 1
#else
// MSC before c++17 need to use <experimental/filesystem> package.
#define USE_EXPERIMENTAL_FS 1
#define USE_FINAL_FS 0
#endif // !_HAS_CXX17
// Right now, GCC still only supports the experimental filesystem items starting in GCC 6
#elif (__GNUC__ >= 6)
#define USE_EXPERIMENTAL_FS 1
#define USE_FINAL_FS 0
// If Clang, check for feature support
#elif defined(__clang__) && (__cpp_lib_filesystem || __cpp_lib_experimental_filesystem)
#if __cpp_lib_filesystem
#define USE_EXPERIMENTAL_FS 0
#define USE_FINAL_FS 1
#else
#define USE_EXPERIMENTAL_FS 1
#define USE_FINAL_FS 0
#endif
// If all above fails, fall back to standard C++ and OS-specific items
#else
#define USE_EXPERIMENTAL_FS 0
#define USE_FINAL_FS 0
#endif
#endif
#if USE_FINAL_FS == 1
#include <filesystem>
#define FS_PREFIX std::filesystem
#elif USE_EXPERIMENTAL_FS == 1
#if (WINAPI_FAMILY != WINAPI_FAMILY_DESKTOP_APP)
#error "Windows universal application doesn't support system::experimental::filesystem"
#endif
#include <experimental/filesystem>
#define FS_PREFIX std::experimental::filesystem
#elif defined(XR_USE_PLATFORM_WIN32)
// Windows fallback includes
#include <stdint.h>
#include <direct.h>
#include <shlwapi.h>
#else
// Linux/Apple fallback includes
#include <sys/stat.h>
#include <sys/param.h>
#include <unistd.h>
#include <limits.h>
#include <stdlib.h>
#include <dirent.h>
#endif
#include "filesystem_utils.hpp"
#if defined(XR_USE_PLATFORM_WIN32)
#define PATH_SEPARATOR ';'
#define DIRECTORY_SYMBOL '\\'
#else
#define PATH_SEPARATOR ':'
#define DIRECTORY_SYMBOL '/'
#endif
#if (USE_FINAL_FS == 1) || (USE_EXPERIMENTAL_FS == 1)
// We can use one of the C++ filesystem packages
bool FileSysUtilsIsRegularFile(const std::string& path) {
try {
return FS_PREFIX::is_regular_file(path);
} catch (...) {
return false;
}
}
bool FileSysUtilsIsDirectory(const std::string& path) {
try {
return FS_PREFIX::is_directory(path);
} catch (...) {
return false;
}
}
bool FileSysUtilsPathExists(const std::string& path) {
try {
return FS_PREFIX::exists(path);
} catch (...) {
return false;
}
}
bool FileSysUtilsIsAbsolutePath(const std::string& path) {
try {
FS_PREFIX::path file_path(path);
return file_path.is_absolute();
} catch (...) {
return false;
}
}
bool FileSysUtilsGetCurrentPath(std::string& path) {
try {
FS_PREFIX::path cur_path = FS_PREFIX::current_path();
path = cur_path.string();
return true;
} catch (...) {
}
return false;
}
bool FileSysUtilsGetParentPath(const std::string& file_path, std::string& parent_path) {
try {
FS_PREFIX::path path_var(file_path);
parent_path = path_var.parent_path().string();
return true;
} catch (...) {
}
return false;
}
bool FileSysUtilsGetAbsolutePath(const std::string& path, std::string& absolute) {
try {
absolute = FS_PREFIX::absolute(path).string();
return true;
} catch (...) {
}
return false;
}
bool FileSysUtilsCombinePaths(const std::string& parent, const std::string& child, std::string& combined) {
try {
FS_PREFIX::path parent_path(parent);
FS_PREFIX::path child_path(child);
FS_PREFIX::path full_path = parent_path / child_path;
combined = full_path.string();
return true;
} catch (...) {
}
return false;
}
bool FileSysUtilsParsePathList(std::string& path_list, std::vector<std::string>& paths) {
try {
std::string::size_type start = 0;
std::string::size_type location = path_list.find(PATH_SEPARATOR);
while (location != std::string::npos) {
paths.push_back(path_list.substr(start, location));
start = location + 1;
location = path_list.find(PATH_SEPARATOR, start);
}
paths.push_back(path_list.substr(start, location));
return true;
} catch (...) {
}
return false;
}
bool FileSysUtilsFindFilesInPath(const std::string& path, std::vector<std::string>& files) {
try {
for (auto& dir_iter : FS_PREFIX::directory_iterator(path)) {
files.push_back(dir_iter.path().filename().string());
}
return true;
} catch (...) {
}
return false;
}
#elif defined(XR_OS_WINDOWS)
// Workaround for MS VS 2010/2013 don't support the experimental filesystem
std::vector<wchar_t> MultibyteToWChar(std::string str) {
const char* mbstr = str.c_str();
std::mbstate_t state = std::mbstate_t();
std::size_t len = 1 + std::mbsrtowcs(NULL, &mbstr, 0, &state);
std::vector<wchar_t> wstr(len);
std::mbsrtowcs(&wstr[0], &mbstr, wstr.size(), &state);
return wstr;
}
bool FileSysUtilsIsRegularFile(const std::string& path) {
try {
return (1 != PathIsDirectoryA(path.c_str()));
} catch (...) {
return false;
}
}
bool FileSysUtilsIsDirectory(const std::string& path) {
try {
return (1 == PathIsDirectoryA(path.c_str()));
} catch (...) {
return false;
}
}
bool FileSysUtilsPathExists(const std::string& path) {
try {
return (1 == PathFileExistsA(path.c_str()));
} catch (...) {
return false;
}
}
bool FileSysUtilsIsAbsolutePath(const std::string& path) {
try {
if ((path[0] == '\\') || (path[1] == ':' && (path[2] == '\\' || path[2] == '/'))) {
return true;
}
} catch (...) {
}
return false;
}
bool FileSysUtilsGetCurrentPath(std::string& path) {
try {
char tmp_path[MAX_PATH];
if (nullptr != _getcwd(tmp_path, MAX_PATH - 1)) {
path = tmp_path;
return true;
}
} catch (...) {
}
return false;
}
bool FileSysUtilsGetParentPath(const std::string& file_path, std::string& parent_path) {
try {
std::string full_path;
if (FileSysUtilsGetAbsolutePath(file_path, full_path)) {
std::string::size_type lastSeperator = full_path.find_last_of(DIRECTORY_SYMBOL);
parent_path = (lastSeperator == 0) ? full_path : full_path.substr(0, lastSeperator - 1);
return true;
}
} catch (...) {
}
return false;
}
bool FileSysUtilsGetAbsolutePath(const std::string& path, std::string& absolute) {
try {
char tmp_path[MAX_PATH];
if (0 != GetFullPathNameA(path.c_str(), MAX_PATH, tmp_path, NULL)) {
absolute = tmp_path;
return true;
}
} catch (...) {
}
return false;
}
bool FileSysUtilsCombinePaths(const std::string& parent, const std::string& child, std::string& combined) {
try {
std::string::size_type parent_len = parent.length();
if (0 == parent_len || "." == parent || ".\\" == parent || "./" == parent) {
combined = child;
return true;
}
char last_char = parent[parent_len - 1];
if (last_char == DIRECTORY_SYMBOL) {
parent_len--;
}
combined = parent.substr(0, parent_len) + DIRECTORY_SYMBOL + child;
return true;
} catch (...) {
}
return false;
}
bool FileSysUtilsParsePathList(std::string& path_list, std::vector<std::string>& paths) {
try {
std::string::size_type start = 0;
std::string::size_type location = path_list.find(PATH_SEPARATOR);
while (location != std::string::npos) {
paths.push_back(path_list.substr(start, location));
start = location + 1;
location = path_list.find(PATH_SEPARATOR, start);
}
paths.push_back(path_list.substr(start, location));
return true;
} catch (...) {
}
return false;
}
bool FileSysUtilsFindFilesInPath(const std::string& path, std::vector<std::string>& files) {
try {
WIN32_FIND_DATA file_data;
HANDLE file_handle = FindFirstFileA(path.c_str(), &file_data);
if (file_handle != INVALID_HANDLE_VALUE) {
do {
if (!(file_data.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)) {
const wchar_t* wstr = file_data.cFileName;
std::mbstate_t state = std::mbstate_t();
std::size_t len = 1 + std::wcsrtombs(nullptr, &wstr, 0, &state);
std::vector<char> mbstr(len);
std::wcsrtombs(&mbstr[0], &wstr, mbstr.size(), &state);
files.push_back(mbstr.data());
}
} while (FindNextFile(file_handle, &file_data));
return true;
}
} catch (...) {
}
return false;
}
#else // XR_OS_LINUX/XR_OS_APPLE fallback
#include <sys/stat.h>
#include <sys/param.h>
#include <unistd.h>
#include <stdlib.h>
#include <dirent.h>
// simple POSIX-compatible implementation of the <filesystem> pieces used by OpenXR
bool FileSysUtilsIsRegularFile(const std::string& path) {
try {
struct stat path_stat;
stat(path.c_str(), &path_stat);
return S_ISREG(path_stat.st_mode);
} catch (...) {
}
return false;
}
bool FileSysUtilsIsDirectory(const std::string& path) {
try {
struct stat path_stat;
stat(path.c_str(), &path_stat);
return S_ISDIR(path_stat.st_mode);
} catch (...) {
}
return false;
}
bool FileSysUtilsPathExists(const std::string& path) {
try {
return (access(path.c_str(), F_OK) != -1);
} catch (...) {
}
return false;
}
bool FileSysUtilsIsAbsolutePath(const std::string& path) {
try {
return (path[0] == DIRECTORY_SYMBOL);
} catch (...) {
}
return false;
}
bool FileSysUtilsGetCurrentPath(std::string& path) {
try {
char tmp_path[PATH_MAX];
if (nullptr != getcwd(tmp_path, PATH_MAX - 1)) {
path = tmp_path;
return true;
}
} catch (...) {
}
return false;
}
bool FileSysUtilsGetParentPath(const std::string& file_path, std::string& parent_path) {
try {
std::string full_path;
if (FileSysUtilsGetAbsolutePath(file_path, full_path)) {
std::string::size_type lastSeperator = full_path.find_last_of(DIRECTORY_SYMBOL);
parent_path = (lastSeperator == 0) ? full_path : full_path.substr(0, lastSeperator - 1);
return true;
}
} catch (...) {
}
return false;
}
bool FileSysUtilsGetAbsolutePath(const std::string& path, std::string& absolute) {
try {
char buf[PATH_MAX];
if (nullptr != realpath(path.c_str(), buf)) {
absolute = buf;
return true;
}
} catch (...) {
}
return false;
}
bool FileSysUtilsCombinePaths(const std::string& parent, const std::string& child, std::string& combined) {
try {
std::string::size_type parent_len = parent.length();
if (0 == parent_len || "." == parent || "./" == parent) {
combined = child;
return true;
}
char last_char = parent[parent_len - 1];
if (last_char == DIRECTORY_SYMBOL) {
parent_len--;
}
combined = parent.substr(0, parent_len) + DIRECTORY_SYMBOL + child;
return true;
} catch (...) {
}
return false;
}
bool FileSysUtilsParsePathList(std::string& path_list, std::vector<std::string>& paths) {
try {
std::string::size_type start = 0;
std::string::size_type location = path_list.find(PATH_SEPARATOR);
while (location != std::string::npos) {
paths.push_back(path_list.substr(start, location));
start = location + 1;
location = path_list.find(PATH_SEPARATOR, start);
}
paths.push_back(path_list.substr(start, location));
return true;
} catch (...) {
}
return false;
}
bool FileSysUtilsFindFilesInPath(const std::string& path, std::vector<std::string>& files) {
try {
DIR* dir;
struct dirent* entry;
dir = opendir(path.c_str());
while (dir && (entry = readdir(dir))) {
files.push_back(entry->d_name);
}
closedir(dir);
return true;
} catch (...) {
}
return false;
}
#endif
<|endoftext|> |
<commit_before>// Copyright 2013 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "base/basictypes.h"
#include "base/json/json_reader.h"
#include "base/memory/scoped_ptr.h"
#include "content/browser/devtools/renderer_overrides_handler.h"
#include "content/public/browser/devtools_agent_host.h"
#include "content/public/browser/web_contents.h"
#include "content/shell/browser/shell.h"
#include "content/test/content_browser_test.h"
#include "content/test/content_browser_test_utils.h"
namespace content {
class RendererOverridesHandlerTest : public ContentBrowserTest {
protected:
scoped_refptr<DevToolsProtocol::Response> SendCommand(
const std::string& method,
DictionaryValue* params) {
scoped_ptr<RendererOverridesHandler> handler(CreateHandler());
scoped_refptr<DevToolsProtocol::Command> command(
DevToolsProtocol::CreateCommand(1, method, params));
return handler->HandleCommand(command);
}
void SendAsyncCommand(const std::string& method, DictionaryValue* params) {
scoped_ptr<RendererOverridesHandler> handler(CreateHandler());
scoped_refptr<DevToolsProtocol::Command> command(
DevToolsProtocol::CreateCommand(1, method, params));
scoped_refptr<DevToolsProtocol::Response> response =
handler->HandleCommand(command);
EXPECT_TRUE(response->is_async_promise());
base::MessageLoop::current()->Run();
}
bool HasValue(const std::string& path) {
base::Value* value = 0;
return result_->Get(path, &value);
}
bool HasListItem(const std::string& path_to_list,
const std::string& name,
const std::string& value) {
base::ListValue* list;
if (!result_->GetList(path_to_list, &list))
return false;
for (size_t i = 0; i != list->GetSize(); i++) {
base::DictionaryValue* item;
if (!list->GetDictionary(i, &item))
return false;
std::string id;
if (!item->GetString(name, &id))
return false;
if (id == value)
return true;
}
return false;
}
scoped_ptr<base::DictionaryValue> result_;
private:
RendererOverridesHandler* CreateHandler() {
RenderViewHost* rvh = shell()->web_contents()->GetRenderViewHost();
DevToolsAgentHost* agent = DevToolsAgentHost::GetOrCreateFor(rvh).get();
scoped_ptr<RendererOverridesHandler> handler(
new RendererOverridesHandler(agent));
handler->SetNotifier(base::Bind(
&RendererOverridesHandlerTest::OnMessageSent, base::Unretained(this)));
return handler.release();
}
void OnMessageSent(const std::string& message) {
base::DictionaryValue* root =
static_cast<base::DictionaryValue*>(base::JSONReader::Read(message));
base::DictionaryValue* result;
root->GetDictionary("result", &result);
result_.reset(result);
base::MessageLoop::current()->QuitNow();
}
};
IN_PROC_BROWSER_TEST_F(RendererOverridesHandlerTest, QueryUsageAndQuota) {
DictionaryValue* params = new DictionaryValue();
params->SetString("securityOrigin", "http://example.com");
SendAsyncCommand("Page.queryUsageAndQuota", params);
EXPECT_TRUE(HasValue("quota.persistent"));
EXPECT_TRUE(HasValue("quota.temporary"));
EXPECT_TRUE(HasListItem("usage.temporary", "id", "appcache"));
EXPECT_TRUE(HasListItem("usage.temporary", "id", "database"));
EXPECT_TRUE(HasListItem("usage.temporary", "id", "indexeddatabase"));
EXPECT_TRUE(HasListItem("usage.temporary", "id", "filesystem"));
EXPECT_TRUE(HasListItem("usage.persistent", "id", "filesystem"));
}
} // namespace content
<commit_msg>Do not leak a DictionaryValue from RendererOverridesHandlerTest.QueryUsageAndQuota.<commit_after>// Copyright 2013 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "base/basictypes.h"
#include "base/json/json_reader.h"
#include "base/memory/scoped_ptr.h"
#include "content/browser/devtools/renderer_overrides_handler.h"
#include "content/public/browser/devtools_agent_host.h"
#include "content/public/browser/web_contents.h"
#include "content/shell/browser/shell.h"
#include "content/test/content_browser_test.h"
#include "content/test/content_browser_test_utils.h"
namespace content {
class RendererOverridesHandlerTest : public ContentBrowserTest {
protected:
scoped_refptr<DevToolsProtocol::Response> SendCommand(
const std::string& method,
DictionaryValue* params) {
scoped_ptr<RendererOverridesHandler> handler(CreateHandler());
scoped_refptr<DevToolsProtocol::Command> command(
DevToolsProtocol::CreateCommand(1, method, params));
return handler->HandleCommand(command);
}
void SendAsyncCommand(const std::string& method, DictionaryValue* params) {
scoped_ptr<RendererOverridesHandler> handler(CreateHandler());
scoped_refptr<DevToolsProtocol::Command> command(
DevToolsProtocol::CreateCommand(1, method, params));
scoped_refptr<DevToolsProtocol::Response> response =
handler->HandleCommand(command);
EXPECT_TRUE(response->is_async_promise());
base::MessageLoop::current()->Run();
}
bool HasValue(const std::string& path) {
base::Value* value = 0;
return result_->Get(path, &value);
}
bool HasListItem(const std::string& path_to_list,
const std::string& name,
const std::string& value) {
base::ListValue* list;
if (!result_->GetList(path_to_list, &list))
return false;
for (size_t i = 0; i != list->GetSize(); i++) {
base::DictionaryValue* item;
if (!list->GetDictionary(i, &item))
return false;
std::string id;
if (!item->GetString(name, &id))
return false;
if (id == value)
return true;
}
return false;
}
scoped_ptr<base::DictionaryValue> result_;
private:
RendererOverridesHandler* CreateHandler() {
RenderViewHost* rvh = shell()->web_contents()->GetRenderViewHost();
DevToolsAgentHost* agent = DevToolsAgentHost::GetOrCreateFor(rvh).get();
scoped_ptr<RendererOverridesHandler> handler(
new RendererOverridesHandler(agent));
handler->SetNotifier(base::Bind(
&RendererOverridesHandlerTest::OnMessageSent, base::Unretained(this)));
return handler.release();
}
void OnMessageSent(const std::string& message) {
scoped_ptr<base::DictionaryValue> root(
static_cast<base::DictionaryValue*>(base::JSONReader::Read(message)));
base::DictionaryValue* result;
root->GetDictionary("result", &result);
result_.reset(result->DeepCopy());
base::MessageLoop::current()->QuitNow();
}
};
IN_PROC_BROWSER_TEST_F(RendererOverridesHandlerTest, QueryUsageAndQuota) {
DictionaryValue* params = new DictionaryValue();
params->SetString("securityOrigin", "http://example.com");
SendAsyncCommand("Page.queryUsageAndQuota", params);
EXPECT_TRUE(HasValue("quota.persistent"));
EXPECT_TRUE(HasValue("quota.temporary"));
EXPECT_TRUE(HasListItem("usage.temporary", "id", "appcache"));
EXPECT_TRUE(HasListItem("usage.temporary", "id", "database"));
EXPECT_TRUE(HasListItem("usage.temporary", "id", "indexeddatabase"));
EXPECT_TRUE(HasListItem("usage.temporary", "id", "filesystem"));
EXPECT_TRUE(HasListItem("usage.persistent", "id", "filesystem"));
}
} // namespace content
<|endoftext|> |
<commit_before>// Copyright (c) 2011, Cornell University
// 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 HyperDex 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.
// POSIX
#include <netinet/in.h>
#include <signal.h>
#include <sys/socket.h>
// Google Log
#include <glog/logging.h>
// po6
#include <po6/net/location.h>
// HyperDex
#include <hyperdex/network_constants.h>
// HyperDaemon
#include "datalayer.h"
#include "logical.h"
#include "network_worker.h"
#include "replication_manager.h"
#include "searches.h"
using hyperdex::entityid;
using hyperdex::network_msgtype;
using hyperdex::network_returncode;
hyperdaemon :: network_worker :: network_worker(datalayer* data,
logical* comm,
searches* ssss,
replication_manager* repl)
: m_continue(true)
, m_data(data)
, m_comm(comm)
, m_ssss(ssss)
, m_repl(repl)
{
}
hyperdaemon :: network_worker :: ~network_worker()
{
if (m_continue)
{
m_continue = false;
LOG(INFO) << "Network worker object not cleanly shutdown.";
}
}
void
hyperdaemon :: network_worker :: run()
{
sigset_t ss;
if (sigfillset(&ss) < 0)
{
PLOG(ERROR) << "sigfillset";
return;
}
if (pthread_sigmask(SIG_BLOCK, &ss, NULL) < 0)
{
PLOG(ERROR) << "pthread_sigmask";
return;
}
entityid from;
entityid to;
network_msgtype type;
e::buffer msg;
uint32_t nonce;
while (m_continue && m_comm->recv(&from, &to, &type, &msg))
{
try
{
if (type == hyperdex::REQ_GET)
{
e::buffer key;
std::vector<e::buffer> value;
uint64_t version;
e::unpacker up(msg.unpack());
up >> nonce;
up.leftovers(&key);
network_returncode result;
switch (m_data->get(to.get_region(), key, &value, &version))
{
case hyperdisk::SUCCESS:
result = hyperdex::NET_SUCCESS;
break;
case hyperdisk::NOTFOUND:
result = hyperdex::NET_NOTFOUND;
break;
case hyperdisk::WRONGARITY:
result = hyperdex::NET_WRONGARITY;
break;
case hyperdisk::MISSINGDISK:
LOG(ERROR) << "GET caused a MISSINGDISK at the data layer.";
result = hyperdex::NET_SERVERERROR;
break;
case hyperdisk::HASHFULL:
case hyperdisk::DATAFULL:
case hyperdisk::SEARCHFULL:
case hyperdisk::SYNCFAILED:
case hyperdisk::DROPFAILED:
default:
LOG(ERROR) << "GET returned unacceptable error code.";
result = hyperdex::NET_SERVERERROR;
break;
}
msg.clear();
msg.pack() << nonce << static_cast<uint16_t>(result) << value;
m_comm->send(to, from, hyperdex::RESP_GET, msg);
}
else if (type == hyperdex::REQ_PUT)
{
e::buffer key;
std::vector<e::buffer> value;
msg.unpack() >> nonce >> key >> value;
m_repl->client_put(from, to.get_region(), nonce, key, value);
}
else if (type == hyperdex::REQ_DEL)
{
e::buffer key;
e::unpacker up(msg.unpack());
up >> nonce;
up.leftovers(&key);
m_repl->client_del(from, to.get_region(), nonce, key);
}
else if (type == hyperdex::REQ_UPDATE)
{
e::buffer key;
e::bitfield value_mask(0); // This will resize on unpack
std::vector<e::buffer> value;
msg.unpack() >> nonce >> key >> value_mask >> value;
m_repl->client_update(from, to.get_region(), nonce, key, value_mask, value);
}
else if (type == hyperdex::REQ_SEARCH_START)
{
hyperdex::search s;
msg.unpack() >> nonce >> s;
m_ssss->start(from, nonce, to.get_region(), s);
}
else if (type == hyperdex::REQ_SEARCH_NEXT)
{
msg.unpack() >> nonce;
m_ssss->next(from, nonce);
}
else if (type == hyperdex::REQ_SEARCH_STOP)
{
msg.unpack() >> nonce;
m_ssss->stop(from, nonce);
}
else if (type == hyperdex::CHAIN_PUT)
{
e::buffer key;
std::vector<e::buffer> value;
uint64_t version;
uint8_t fresh;
msg.unpack() >> version >> fresh >> key >> value;
m_repl->chain_put(from, to, version, fresh == 1, key, value);
}
else if (type == hyperdex::CHAIN_DEL)
{
e::buffer key;
uint64_t version;
msg.unpack() >> version >> key;
m_repl->chain_del(from, to, version, key);
}
else if (type == hyperdex::CHAIN_PENDING)
{
e::buffer key;
uint64_t version;
msg.unpack() >> version >> key;
m_repl->chain_pending(from, to, version, key);
}
else if (type == hyperdex::CHAIN_SUBSPACE)
{
uint64_t version;
e::buffer key;
std::vector<e::buffer> value;
uint64_t nextpoint;
msg.unpack() >> version >> key >> value >> nextpoint;
m_repl->chain_subspace(from, to, version, key, value, nextpoint);
}
else if (type == hyperdex::CHAIN_ACK)
{
e::buffer key;
uint64_t version;
msg.unpack() >> version >> key;
m_repl->chain_ack(from, to, version, key);
}
else if (type == hyperdex::XFER_MORE)
{
m_repl->region_transfer(from, to);
}
else if (type == hyperdex::XFER_DONE)
{
m_repl->region_transfer_done(from, to);
}
else if (type == hyperdex::XFER_DATA)
{
uint64_t xfer_num;
uint8_t op;
uint64_t version;
e::buffer key;
std::vector<e::buffer> value;
msg.unpack() >> xfer_num >> op >> version >> key >> value;
m_repl->region_transfer(from, to.subspace, xfer_num,
op == 1, version, key, value);
}
else
{
LOG(INFO) << "Message of unknown type received.";
}
}
catch (std::out_of_range& e)
{
// Unpack error
}
}
}
void
hyperdaemon :: network_worker :: shutdown()
{
// TODO: This is not the proper shutdown method. Proper shutdown is a
// two-stage process, and requires global coordination.
m_continue = false;
}
<commit_msg>Call trickle from network_workers.<commit_after>// Copyright (c) 2011, Cornell University
// 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 HyperDex 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.
// POSIX
#include <netinet/in.h>
#include <signal.h>
#include <sys/socket.h>
// Google Log
#include <glog/logging.h>
// po6
#include <po6/net/location.h>
// HyperDex
#include <hyperdex/network_constants.h>
// HyperDaemon
#include "datalayer.h"
#include "logical.h"
#include "network_worker.h"
#include "replication_manager.h"
#include "searches.h"
using hyperdex::entityid;
using hyperdex::network_msgtype;
using hyperdex::network_returncode;
hyperdaemon :: network_worker :: network_worker(datalayer* data,
logical* comm,
searches* ssss,
replication_manager* repl)
: m_continue(true)
, m_data(data)
, m_comm(comm)
, m_ssss(ssss)
, m_repl(repl)
{
}
hyperdaemon :: network_worker :: ~network_worker()
{
if (m_continue)
{
m_continue = false;
LOG(INFO) << "Network worker object not cleanly shutdown.";
}
}
void
hyperdaemon :: network_worker :: run()
{
sigset_t ss;
if (sigfillset(&ss) < 0)
{
PLOG(ERROR) << "sigfillset";
return;
}
if (pthread_sigmask(SIG_BLOCK, &ss, NULL) < 0)
{
PLOG(ERROR) << "pthread_sigmask";
return;
}
entityid from;
entityid to;
network_msgtype type;
e::buffer msg;
uint32_t nonce;
uint64_t count = 0;
while (m_continue && m_comm->recv(&from, &to, &type, &msg))
{
try
{
bool trickle = false;
if (type == hyperdex::REQ_GET)
{
e::buffer key;
std::vector<e::buffer> value;
uint64_t version;
e::unpacker up(msg.unpack());
up >> nonce;
up.leftovers(&key);
network_returncode result;
switch (m_data->get(to.get_region(), key, &value, &version))
{
case hyperdisk::SUCCESS:
result = hyperdex::NET_SUCCESS;
break;
case hyperdisk::NOTFOUND:
result = hyperdex::NET_NOTFOUND;
break;
case hyperdisk::WRONGARITY:
result = hyperdex::NET_WRONGARITY;
break;
case hyperdisk::MISSINGDISK:
LOG(ERROR) << "GET caused a MISSINGDISK at the data layer.";
result = hyperdex::NET_SERVERERROR;
break;
case hyperdisk::HASHFULL:
case hyperdisk::DATAFULL:
case hyperdisk::SEARCHFULL:
case hyperdisk::SYNCFAILED:
case hyperdisk::DROPFAILED:
default:
LOG(ERROR) << "GET returned unacceptable error code.";
result = hyperdex::NET_SERVERERROR;
break;
}
msg.clear();
msg.pack() << nonce << static_cast<uint16_t>(result) << value;
m_comm->send(to, from, hyperdex::RESP_GET, msg);
}
else if (type == hyperdex::REQ_PUT)
{
e::buffer key;
std::vector<e::buffer> value;
msg.unpack() >> nonce >> key >> value;
m_repl->client_put(from, to.get_region(), nonce, key, value);
}
else if (type == hyperdex::REQ_DEL)
{
e::buffer key;
e::unpacker up(msg.unpack());
up >> nonce;
up.leftovers(&key);
m_repl->client_del(from, to.get_region(), nonce, key);
}
else if (type == hyperdex::REQ_UPDATE)
{
e::buffer key;
e::bitfield value_mask(0); // This will resize on unpack
std::vector<e::buffer> value;
msg.unpack() >> nonce >> key >> value_mask >> value;
m_repl->client_update(from, to.get_region(), nonce, key, value_mask, value);
}
else if (type == hyperdex::REQ_SEARCH_START)
{
hyperdex::search s;
msg.unpack() >> nonce >> s;
m_ssss->start(from, nonce, to.get_region(), s);
}
else if (type == hyperdex::REQ_SEARCH_NEXT)
{
msg.unpack() >> nonce;
m_ssss->next(from, nonce);
}
else if (type == hyperdex::REQ_SEARCH_STOP)
{
msg.unpack() >> nonce;
m_ssss->stop(from, nonce);
}
else if (type == hyperdex::CHAIN_PUT)
{
e::buffer key;
std::vector<e::buffer> value;
uint64_t version;
uint8_t fresh;
msg.unpack() >> version >> fresh >> key >> value;
m_repl->chain_put(from, to, version, fresh == 1, key, value);
}
else if (type == hyperdex::CHAIN_DEL)
{
e::buffer key;
uint64_t version;
msg.unpack() >> version >> key;
m_repl->chain_del(from, to, version, key);
}
else if (type == hyperdex::CHAIN_PENDING)
{
e::buffer key;
uint64_t version;
msg.unpack() >> version >> key;
m_repl->chain_pending(from, to, version, key);
}
else if (type == hyperdex::CHAIN_SUBSPACE)
{
uint64_t version;
e::buffer key;
std::vector<e::buffer> value;
uint64_t nextpoint;
msg.unpack() >> version >> key >> value >> nextpoint;
m_repl->chain_subspace(from, to, version, key, value, nextpoint);
}
else if (type == hyperdex::CHAIN_ACK)
{
e::buffer key;
uint64_t version;
msg.unpack() >> version >> key;
m_repl->chain_ack(from, to, version, key);
trickle = true;
}
else if (type == hyperdex::XFER_MORE)
{
m_repl->region_transfer(from, to);
}
else if (type == hyperdex::XFER_DONE)
{
m_repl->region_transfer_done(from, to);
}
else if (type == hyperdex::XFER_DATA)
{
uint64_t xfer_num;
uint8_t op;
uint64_t version;
e::buffer key;
std::vector<e::buffer> value;
msg.unpack() >> xfer_num >> op >> version >> key >> value;
m_repl->region_transfer(from, to.subspace, xfer_num,
op == 1, version, key, value);
}
else
{
LOG(INFO) << "Message of unknown type received.";
}
if (trickle)
{
++count;
if (count % 100000 == 0)
{
m_data->trickle(to.get_region());
}
}
}
catch (std::out_of_range& e)
{
// Unpack error
}
}
}
void
hyperdaemon :: network_worker :: shutdown()
{
// TODO: This is not the proper shutdown method. Proper shutdown is a
// two-stage process, and requires global coordination.
m_continue = false;
}
<|endoftext|> |
<commit_before>#include "deconvolve.hpp"
#include "least-sq.hpp"
#include "util.hpp"
#include "regularizer.hpp"
#include <lbfgs.h>
namespace deconvolution{
template <int D>
struct DeconvolveData {
};
template <int D>
static double deconvolveEvaluate(
void* instance,
const double* dualVars,
double* grad,
const int n,
const double step) {
return 0;
}
static int deconvolveProgress(
void *instance,
const double *x,
const double *g,
const double fx,
const double xnorm,
const double gnorm,
const double step,
int n,
int k,
int ls) {
printf("Deconvolve Iteration %d:\n", k);
printf(" fx = %f", fx);
printf(" xnorm = %f, gnorm = %f, step = %f\n", xnorm, gnorm, step);
printf("\n");
return 0;
}
template <int D>
Array<D> Deconvolve(const Array<D>& y, const LinearSystem<D>& H, const LinearSystem<D>& Ht, const Regularizer<D>& R) {
Array<D> Ht_y = Ht(y);
Array<D> x = Ht_y;
int numPrimalVars = x.num_elements();
int numLambda = numPrimalVars*R.numSubproblems()*R.numLabels();
int numDualVars = numLambda + numPrimalVars; // Including all lambda vars + vector nu
auto dualVars = std::unique_ptr<double>(new double[numDualVars]);
double* lambda = dualVars.get();
double* nu = dualVars.get() + numLambda;
for (int i = 0; i < numLambda; ++i)
lambda[i] = 0;
for (int i = 0; i < numPrimalVars; ++i)
nu[i] = 0;
LinearSystem<D> Q = [&](const Array<D>& x) -> Array<D> { return Ht(H(x)) + 0.03*x; };
for (size_t i = 0; i < x.num_elements(); ++i) {
x.data()[i] = 0;
}
leastSquares<D>(Q, Ht_y, x);
lbfgs_parameter_t params;
double fVal = 0;
lbfgs_parameter_init(¶ms);
auto algData = DeconvolveData<D>{};
auto retCode = lbfgs(numDualVars, dualVars.get(), &fVal, deconvolveEvaluate<D>, deconvolveProgress, &algData, ¶ms);
std::cout << "Deconvolve finished: " << retCode << "\n";
return x;
}
#define INSTANTIATE_DECONVOLVE(d) \
template Array<d> Deconvolve<d>(const Array<d>& y, const LinearSystem<d>& H, const LinearSystem<d>& Q, const Regularizer<d>& R);
INSTANTIATE_DECONVOLVE(1)
INSTANTIATE_DECONVOLVE(2)
INSTANTIATE_DECONVOLVE(3)
#undef INSTANTIATE_DECONVOLVE
}
<commit_msg>More filling out definitions in Deconvolve<commit_after>#include "deconvolve.hpp"
#include "least-sq.hpp"
#include "util.hpp"
#include "regularizer.hpp"
#include <lbfgs.h>
namespace deconvolution{
template <int D>
struct DeconvolveData {
Array<D>& x;
const Array<D>& Ht_y;
const LinearSystem<D>& Q;
const Regularizer<D>& R;
int numLambda;
};
template <int D>
static double deconvolveEvaluate(
void* instance,
const double* dualVars,
double* grad,
const int n,
const double step) {
auto value = 0.0;
auto* data = static_cast<DeconvolveData<D>*>(instance);
const auto& R = data->R;
auto& x = data->x;
const auto numPrimalVars = x.num_elements();
const auto numPerSubproblem = numPrimalVars*R.numSubproblems();
for (int i = 0; i < n; ++i)
grad[i] = 0;
for (int i = 0; i < R.numSubproblems(); ++i)
value += R.evaluate(i, dualVars+i*numPerSubproblem, 0.001, grad+i*numPerSubproblem);
return value;
}
static int deconvolveProgress(
void *instance,
const double *x,
const double *g,
const double fx,
const double xnorm,
const double gnorm,
const double step,
int n,
int k,
int ls) {
printf("Deconvolve Iteration %d:\n", k);
printf(" fx = %f", fx);
printf(" xnorm = %f, gnorm = %f, step = %f\n", xnorm, gnorm, step);
printf("\n");
return 0;
}
template <int D>
Array<D> Deconvolve(const Array<D>& y, const LinearSystem<D>& H, const LinearSystem<D>& Ht, const Regularizer<D>& R) {
Array<D> Ht_y = Ht(y);
Array<D> x = Ht_y;
int numPrimalVars = x.num_elements();
int numLambda = numPrimalVars*R.numSubproblems()*R.numLabels();
int numDualVars = numLambda + numPrimalVars; // Including all lambda vars + vector nu
auto dualVars = std::unique_ptr<double>(new double[numDualVars]);
double* lambda = dualVars.get();
double* nu = dualVars.get() + numLambda;
for (int i = 0; i < numLambda; ++i)
lambda[i] = 0;
for (int i = 0; i < numPrimalVars; ++i)
nu[i] = 0;
LinearSystem<D> Q = [&](const Array<D>& x) -> Array<D> { return Ht(H(x)) + 0.03*x; };
for (size_t i = 0; i < x.num_elements(); ++i) {
x.data()[i] = 0;
}
leastSquares<D>(Q, Ht_y, x);
lbfgs_parameter_t params;
double fVal = 0;
lbfgs_parameter_init(¶ms);
auto algData = DeconvolveData<D>{x, Ht_y, Q, R, numLambda};
auto retCode = lbfgs(numDualVars, dualVars.get(), &fVal, deconvolveEvaluate<D>, deconvolveProgress, &algData, ¶ms);
std::cout << "Deconvolve finished: " << retCode << "\n";
return x;
}
#define INSTANTIATE_DECONVOLVE(d) \
template Array<d> Deconvolve<d>(const Array<d>& y, const LinearSystem<d>& H, const LinearSystem<d>& Q, const Regularizer<d>& R);
INSTANTIATE_DECONVOLVE(1)
INSTANTIATE_DECONVOLVE(2)
INSTANTIATE_DECONVOLVE(3)
#undef INSTANTIATE_DECONVOLVE
}
<|endoftext|> |
<commit_before>// Copyright (C) 2016 xaizek <[email protected]>
//
// This file is part of uncov.
//
// uncov is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// uncov 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 Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with uncov. If not, see <http://www.gnu.org/licenses/>.
#include "decoration.hpp"
#include <ostream>
#include "integration.hpp"
namespace {
class Colors
{
public:
void disable() { isAscii = false; }
const char * bold () { return isAscii ? "\033[1m" : ""; }
const char * inv () { return isAscii ? "\033[7m" : ""; }
const char * def () { return isAscii ? "\033[1m\033[0m" : ""; }
const char * black_fg () { return isAscii ? "\033[30m" : ""; }
const char * red_fg () { return isAscii ? "\033[31m" : ""; }
const char * green_fg () { return isAscii ? "\033[32m" : ""; }
const char * yellow_fg () { return isAscii ? "\033[33m" : ""; }
const char * blue_fg () { return isAscii ? "\033[34m" : ""; }
const char * magenta_fg () { return isAscii ? "\033[35m" : ""; }
const char * cyan_fg () { return isAscii ? "\033[36m" : ""; }
const char * white_fg () { return isAscii ? "\033[37m" : ""; }
const char * black_bg () { return isAscii ? "\033[40m" : ""; }
const char * red_bg () { return isAscii ? "\033[41m" : ""; }
const char * green_bg () { return isAscii ? "\033[42m" : ""; }
const char * yellow_bg () { return isAscii ? "\033[43m" : ""; }
const char * blue_bg () { return isAscii ? "\033[44m" : ""; }
const char * magenta_bg () { return isAscii ? "\033[45m" : ""; }
const char * cyan_bg () { return isAscii ? "\033[46m" : ""; }
const char * white_bg () { return isAscii ? "\033[47m" : ""; }
private:
bool isAscii = isOutputToTerminal();
} C;
}
// Shorten type name to fit into 80 columns limit.
using ostr = std::ostream;
using namespace decor;
const Decoration
decor::none,
decor::bold ([](ostr &os) -> ostr & { return os << C.bold(); }),
decor::inv ([](ostr &os) -> ostr & { return os << C.inv(); }),
decor::def ([](ostr &os) -> ostr & { return os << C.def(); }),
decor::black_fg ([](ostr &os) -> ostr & { return os << C.black_fg(); }),
decor::red_fg ([](ostr &os) -> ostr & { return os << C.red_fg(); }),
decor::green_fg ([](ostr &os) -> ostr & { return os << C.green_fg(); }),
decor::yellow_fg ([](ostr &os) -> ostr & { return os << C.yellow_fg(); }),
decor::blue_fg ([](ostr &os) -> ostr & { return os << C.blue_fg(); }),
decor::magenta_fg ([](ostr &os) -> ostr & { return os << C.magenta_fg(); }),
decor::cyan_fg ([](ostr &os) -> ostr & { return os << C.cyan_fg(); }),
decor::white_fg ([](ostr &os) -> ostr & { return os << C.white_fg(); }),
decor::black_bg ([](ostr &os) -> ostr & { return os << C.black_bg(); }),
decor::red_bg ([](ostr &os) -> ostr & { return os << C.red_bg(); }),
decor::green_bg ([](ostr &os) -> ostr & { return os << C.green_bg(); }),
decor::yellow_bg ([](ostr &os) -> ostr & { return os << C.yellow_bg(); }),
decor::blue_bg ([](ostr &os) -> ostr & { return os << C.blue_bg(); }),
decor::magenta_bg ([](ostr &os) -> ostr & { return os << C.magenta_bg(); }),
decor::cyan_bg ([](ostr &os) -> ostr & { return os << C.cyan_bg(); }),
decor::white_bg ([](ostr &os) -> ostr & { return os << C.white_bg(); });
Decoration::Decoration(const Decoration &rhs)
: decorator(rhs.decorator),
lhs(rhs.lhs == nullptr ? nullptr : new Decoration(*rhs.lhs)),
rhs(rhs.rhs == nullptr ? nullptr : new Decoration(*rhs.rhs))
{
}
Decoration::Decoration(decorFunc decorator) : decorator(decorator)
{
}
Decoration::Decoration(const Decoration &lhs, const Decoration &rhs)
: lhs(new Decoration(lhs)),
rhs(new Decoration(rhs))
{
}
std::ostream &
Decoration::decorate(std::ostream &os) const
{
if (decorator != nullptr) {
// Reset and preserve width field, so printing escape sequence doesn't
// mess up formatting.
const auto width = os.width({});
os << decorator;
static_cast<void>(os.width(width));
return os;
}
if (lhs != nullptr && rhs != nullptr) {
return os << *lhs << *rhs;
}
return os;
}
void
decor::disableDecorations()
{
C.disable();
}
<commit_msg>Simplify implementation in decoration.cpp<commit_after>// Copyright (C) 2016 xaizek <[email protected]>
//
// This file is part of uncov.
//
// uncov is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// uncov 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 Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with uncov. If not, see <http://www.gnu.org/licenses/>.
#include "decoration.hpp"
#include <ostream>
#include "integration.hpp"
namespace {
class ColorsState
{
public:
void disable() { isAscii = false; }
const char * operator()(const char text[]) const
{
return isAscii ? text : "";
}
private:
bool isAscii = isOutputToTerminal();
};
}
// Shorten type name to fit into 80 columns limit.
using ostr = std::ostream;
using namespace decor;
static ColorsState S;
const Decoration
decor::none,
decor::bold ([](ostr &os) -> ostr & { return os << S("\033[1m"); }),
decor::inv ([](ostr &os) -> ostr & { return os << S("\033[7m"); }),
decor::def ([](ostr &os) -> ostr & { return os << S("\033[0m"); }),
decor::black_fg ([](ostr &os) -> ostr & { return os << S("\033[30m"); }),
decor::red_fg ([](ostr &os) -> ostr & { return os << S("\033[31m"); }),
decor::green_fg ([](ostr &os) -> ostr & { return os << S("\033[32m"); }),
decor::yellow_fg ([](ostr &os) -> ostr & { return os << S("\033[33m"); }),
decor::blue_fg ([](ostr &os) -> ostr & { return os << S("\033[34m"); }),
decor::magenta_fg ([](ostr &os) -> ostr & { return os << S("\033[35m"); }),
decor::cyan_fg ([](ostr &os) -> ostr & { return os << S("\033[36m"); }),
decor::white_fg ([](ostr &os) -> ostr & { return os << S("\033[37m"); }),
decor::black_bg ([](ostr &os) -> ostr & { return os << S("\033[40m"); }),
decor::red_bg ([](ostr &os) -> ostr & { return os << S("\033[41m"); }),
decor::green_bg ([](ostr &os) -> ostr & { return os << S("\033[42m"); }),
decor::yellow_bg ([](ostr &os) -> ostr & { return os << S("\033[43m"); }),
decor::blue_bg ([](ostr &os) -> ostr & { return os << S("\033[44m"); }),
decor::magenta_bg ([](ostr &os) -> ostr & { return os << S("\033[45m"); }),
decor::cyan_bg ([](ostr &os) -> ostr & { return os << S("\033[46m"); }),
decor::white_bg ([](ostr &os) -> ostr & { return os << S("\033[47m"); });
Decoration::Decoration(const Decoration &rhs)
: decorator(rhs.decorator),
lhs(rhs.lhs == nullptr ? nullptr : new Decoration(*rhs.lhs)),
rhs(rhs.rhs == nullptr ? nullptr : new Decoration(*rhs.rhs))
{
}
Decoration::Decoration(decorFunc decorator) : decorator(decorator)
{
}
Decoration::Decoration(const Decoration &lhs, const Decoration &rhs)
: lhs(new Decoration(lhs)),
rhs(new Decoration(rhs))
{
}
std::ostream &
Decoration::decorate(std::ostream &os) const
{
if (decorator != nullptr) {
// Reset and preserve width field, so printing escape sequence doesn't
// mess up formatting.
const auto width = os.width({});
os << decorator;
static_cast<void>(os.width(width));
return os;
}
if (lhs != nullptr && rhs != nullptr) {
return os << *lhs << *rhs;
}
return os;
}
void
decor::disableDecorations()
{
S.disable();
}
<|endoftext|> |
<commit_before>/*
* Diameter.cpp
*
* Created on: 19.02.2014
* Author: Daniel Hoske, Christian Staudt
*/
#include <numeric>
#include "Diameter.h"
#include "Eccentricity.h"
#include "../graph/BFS.h"
#include "../graph/Dijkstra.h"
#include "../components/ConnectedComponents.h"
#include "../structures/Partition.h"
#include "../graph/BFS.h"
#include "../auxiliary/Parallel.h"
namespace NetworKit {
edgeweight Diameter::exactDiameter(const Graph& G) {
using namespace std;
Aux::SignalHandler handler;
edgeweight diameter = 0.0;
if (! G.isWeighted()) {
std::tie(diameter, std::ignore) = estimatedDiameterRange(G, 0);
} else {
G.forNodes([&](node v) {
handler.assureRunning();
Dijkstra dijkstra(G, v);
dijkstra.run();
auto distances = dijkstra.getDistances();
for (auto distance : distances) {
if (diameter < distance) {
diameter = distance;
}
}
// DEBUG("ecc(", v, "): ", *std::max_element(distances.begin(), distances.end()), " of ", distances);
});
}
if (diameter == std::numeric_limits<edgeweight>::max()) {
throw std::runtime_error("Graph not connected - diameter is infinite");
}
return diameter;
}
std::pair<edgeweight, edgeweight> Diameter::estimatedDiameterRange(const NetworKit::Graph &G, double error) {
// TODO: make abortable with ctrl+c using SignalHandling code
if (G.isDirected()) {
throw std::runtime_error("Error, the diameter of directed graphs cannot be computed yet.");
}
Aux::SignalHandler handler;
/*
* This is an implementation of a slightly modified version of the exactSumSweep algorithm as presented in
* Fast diameter and radius BFS-based computation in (weakly connected) real-world graphs: With an application to the six degrees of separation games
* by Michele Borassi, Pierluigi Crescenzi, Michel Habib, Walter A. Kosters, Andrea Marino, Frank W. Takes
* http://www.sciencedirect.com/science/article/pii/S0304397515001644
*/
std::vector<count> sum(G.upperNodeIdBound(), 0);
std::vector<count> eccLowerBound(G.upperNodeIdBound(), 0), eccUpperBound(G.upperNodeIdBound(), std::numeric_limits<count>::max());
#pragma omp parallel for
for (node u = 0; u < G.upperNodeIdBound(); ++u) {
if (!G.hasNode(u)) {
eccUpperBound[u] = 0;
}
}
std::vector<count> distances(G.upperNodeIdBound(), 0);
std::vector<bool> finished(G.upperNodeIdBound(), false);
count k = 4;
ConnectedComponents comp(G);
comp.run();
count numberOfComponents = comp.numberOfComponents();
std::vector<node> startNodes(numberOfComponents, 0), maxDist(numberOfComponents, 0);
std::vector<node> firstDeg2Node(numberOfComponents, none);
std::vector<node> distFirst(numberOfComponents, 0);
std::vector<node> ecc(numberOfComponents, 0);
auto updateBounds = [&]() {
G.parallelForNodes([&](node u) {
if (finished[u]) return;
auto c = comp.componentOfNode(u);
if (distances[u] <= distFirst[c]) {
eccUpperBound[u] = std::max(distances[u], ecc[c] - distances[u]);
eccLowerBound[u] = eccUpperBound[u];
finished[u] = true;
} else {
eccUpperBound[u] = std::min(distances[u] + ecc[c] - 2 * distFirst[c], eccUpperBound[u]);
eccLowerBound[u] = std::max(eccLowerBound[u], distances[u]);
finished[u] = (eccUpperBound[u] == eccLowerBound[u]);
}
});
ecc.clear();
ecc.resize(numberOfComponents, 0);
distFirst.clear();
distFirst.resize(numberOfComponents, 0);
};
auto diameterBounds = [&]() {
auto maxExact = *Aux::Parallel::max_element(eccLowerBound.begin(), eccLowerBound.end());
auto maxPotential = *Aux::Parallel::max_element(eccUpperBound.begin(), eccUpperBound.end());
return std::make_pair(maxExact, maxPotential);
};
auto visitNode = [&](node v, count dist) {
sum[v] += dist;
distances[v] = dist;
index c = comp.componentOfNode(v);
ecc[c] = std::max(dist, ecc[c]);
if (firstDeg2Node[c] == none && G.degree(v) > 1) {
firstDeg2Node[c] = v;
distFirst[c] = dist;
}
};
for (index i = 0; i < k; ++i) {
handler.assureRunning();
if (i == 0) {
std::vector<count> minDeg(numberOfComponents, G.numberOfNodes());
// for each component, find the node with the minimum degreee and add it as start node
G.forNodes([&](node v) {
count d = G.degree(v);
count c = comp.componentOfNode(v);
if (d < minDeg[c]) {
startNodes[c] = v;
minDeg[c] = d;
}
});
}
G.BFSfrom(startNodes, [&](node v, count dist) {
visitNode(v, dist);
index c = comp.componentOfNode(v);
if (sum[v] >= maxDist[c]) {
maxDist[c] = sum[v];
startNodes[c] = v;
}
});
updateBounds();
}
handler.assureRunning();
std::vector<count> minDist(numberOfComponents, G.numberOfNodes());
G.forNodes([&](node u) {
auto c = comp.componentOfNode(u);
if (sum[u] < minDist[c]) {
minDist[c] = sum[u];
startNodes[c] = u;
}
});
handler.assureRunning();
G.BFSfrom(startNodes, visitNode);
updateBounds();
count lb, ub;
std::tie(lb, ub) = diameterBounds();
for (index i = 0; i < G.numberOfNodes() && ub > (lb + error*lb); ++i) {
handler.assureRunning();
startNodes.clear();
startNodes.resize(numberOfComponents, none);
if ((i % 2) == 0) {
G.forNodes([&](node u) {
auto c = comp.componentOfNode(u);
if (startNodes[c] == none || std::tie(eccUpperBound[u], sum[u]) > std::tie(eccUpperBound[startNodes[c]], sum[startNodes[c]])) {
startNodes[c] = u;
}
});
} else {
G.forNodes([&](node u) {
auto c = comp.componentOfNode(u);
if (startNodes[c] == none || std::tie(eccLowerBound[u], sum[u]) < std::tie(eccLowerBound[startNodes[c]], sum[startNodes[c]])) {
startNodes[c] = u;
}
});
}
handler.assureRunning();
G.BFSfrom(startNodes, visitNode);
handler.assureRunning();
updateBounds();
std::tie(lb, ub) = diameterBounds();
}
return {lb, ub};
}
edgeweight Diameter::estimatedVertexDiameter(const Graph& G, count samples) {
edgeweight infDist = std::numeric_limits<edgeweight>::max();
// TODO: consider weights
auto estimateFrom = [&](node v) -> count {
BFS bfs(G, v);
bfs.run();
auto distances = bfs.getDistances();
// get two largest path lengths
edgeweight maxD = 0;
edgeweight maxD2 = 0; // second largest distance
for (auto d : distances) {
if ((d != infDist) && (d >= maxD)) {
maxD2 = maxD;
maxD = d;
}
}
edgeweight dMax = maxD + maxD2;
count vd = (count) dMax + 1; // count the nodes, not the edges
return vd;
};
edgeweight vdMax = 0;
#pragma omp parallel for
for (count i = 0; i < samples; ++i) {
node u = G.randomNode();
edgeweight vd = estimateFrom(u);
DEBUG("sampled vertex diameter from node ", u, ": ", vd);
#pragma omp critical
{
if (vd > vdMax) {
vdMax = vd;
}
}
}
return vdMax;
}
edgeweight Diameter::estimatedVertexDiameterPedantic(const Graph& G) {
count vd = 0;
if (!G.isWeighted()) {
std::vector<bool> visited(G.upperNodeIdBound(), false);
// perform breadth-first searches
G.forNodes([&](node u) {
if (visited[u] == false) {
count maxDist = 0, maxDist2 = 0;
G.BFSfrom(u, [&](node v, count dist) {
visited[v] = true;
if (dist > maxDist) {
maxDist2 = maxDist;
maxDist = dist;
}
else if (dist > maxDist2) {
maxDist2 = dist;
}
});
if (maxDist + maxDist2 > vd) {
vd = maxDist + maxDist2;
}
assert (visited[u] == true);
}
});
vd ++; //we need the number of nodes, not the number of edges
}
else {
ConnectedComponents cc(G);
DEBUG("finding connected components");
cc.run();
INFO("Number of components ", cc.numberOfComponents());
DEBUG("Estimating size of the largest component");
std::map<count, count> sizes = cc.getComponentSizes();
count largest_comp_size = 0;
for(auto it = sizes.cbegin(); it != sizes.cend(); ++it) {
DEBUG(it->second);
if (it->second > largest_comp_size) {
largest_comp_size = it->second;
}
}
INFO("Largest component size: ", largest_comp_size);
vd = largest_comp_size;
}
return vd;
}
} /* namespace NetworKit */
<commit_msg>Diameter: throw on weighted networks<commit_after>/*
* Diameter.cpp
*
* Created on: 19.02.2014
* Author: Daniel Hoske, Christian Staudt
*/
#include <numeric>
#include "Diameter.h"
#include "Eccentricity.h"
#include "../graph/BFS.h"
#include "../graph/Dijkstra.h"
#include "../components/ConnectedComponents.h"
#include "../structures/Partition.h"
#include "../graph/BFS.h"
#include "../auxiliary/Parallel.h"
namespace NetworKit {
edgeweight Diameter::exactDiameter(const Graph& G) {
using namespace std;
Aux::SignalHandler handler;
edgeweight diameter = 0.0;
if (! G.isWeighted()) {
std::tie(diameter, std::ignore) = estimatedDiameterRange(G, 0);
} else {
G.forNodes([&](node v) {
handler.assureRunning();
Dijkstra dijkstra(G, v);
dijkstra.run();
auto distances = dijkstra.getDistances();
for (auto distance : distances) {
if (diameter < distance) {
diameter = distance;
}
}
// DEBUG("ecc(", v, "): ", *std::max_element(distances.begin(), distances.end()), " of ", distances);
});
}
if (diameter == std::numeric_limits<edgeweight>::max()) {
throw std::runtime_error("Graph not connected - diameter is infinite");
}
return diameter;
}
std::pair<edgeweight, edgeweight> Diameter::estimatedDiameterRange(const NetworKit::Graph &G, double error) {
if (G.isDirected() || G.isWeighted()) {
throw std::runtime_error("Error, the diameter of directed or weighted graphs cannot be computed yet.");
}
Aux::SignalHandler handler;
/*
* This is an implementation of a slightly modified version of the exactSumSweep algorithm as presented in
* Fast diameter and radius BFS-based computation in (weakly connected) real-world graphs: With an application to the six degrees of separation games
* by Michele Borassi, Pierluigi Crescenzi, Michel Habib, Walter A. Kosters, Andrea Marino, Frank W. Takes
* http://www.sciencedirect.com/science/article/pii/S0304397515001644
*/
std::vector<count> sum(G.upperNodeIdBound(), 0);
std::vector<count> eccLowerBound(G.upperNodeIdBound(), 0), eccUpperBound(G.upperNodeIdBound(), std::numeric_limits<count>::max());
#pragma omp parallel for
for (node u = 0; u < G.upperNodeIdBound(); ++u) {
if (!G.hasNode(u)) {
eccUpperBound[u] = 0;
}
}
std::vector<count> distances(G.upperNodeIdBound(), 0);
std::vector<bool> finished(G.upperNodeIdBound(), false);
count k = 4;
ConnectedComponents comp(G);
comp.run();
count numberOfComponents = comp.numberOfComponents();
std::vector<node> startNodes(numberOfComponents, 0), maxDist(numberOfComponents, 0);
std::vector<node> firstDeg2Node(numberOfComponents, none);
std::vector<node> distFirst(numberOfComponents, 0);
std::vector<node> ecc(numberOfComponents, 0);
auto updateBounds = [&]() {
G.parallelForNodes([&](node u) {
if (finished[u]) return;
auto c = comp.componentOfNode(u);
if (distances[u] <= distFirst[c]) {
eccUpperBound[u] = std::max(distances[u], ecc[c] - distances[u]);
eccLowerBound[u] = eccUpperBound[u];
finished[u] = true;
} else {
eccUpperBound[u] = std::min(distances[u] + ecc[c] - 2 * distFirst[c], eccUpperBound[u]);
eccLowerBound[u] = std::max(eccLowerBound[u], distances[u]);
finished[u] = (eccUpperBound[u] == eccLowerBound[u]);
}
});
ecc.clear();
ecc.resize(numberOfComponents, 0);
distFirst.clear();
distFirst.resize(numberOfComponents, 0);
};
auto diameterBounds = [&]() {
auto maxExact = *Aux::Parallel::max_element(eccLowerBound.begin(), eccLowerBound.end());
auto maxPotential = *Aux::Parallel::max_element(eccUpperBound.begin(), eccUpperBound.end());
return std::make_pair(maxExact, maxPotential);
};
auto visitNode = [&](node v, count dist) {
sum[v] += dist;
distances[v] = dist;
index c = comp.componentOfNode(v);
ecc[c] = std::max(dist, ecc[c]);
if (firstDeg2Node[c] == none && G.degree(v) > 1) {
firstDeg2Node[c] = v;
distFirst[c] = dist;
}
};
for (index i = 0; i < k; ++i) {
handler.assureRunning();
if (i == 0) {
std::vector<count> minDeg(numberOfComponents, G.numberOfNodes());
// for each component, find the node with the minimum degreee and add it as start node
G.forNodes([&](node v) {
count d = G.degree(v);
count c = comp.componentOfNode(v);
if (d < minDeg[c]) {
startNodes[c] = v;
minDeg[c] = d;
}
});
}
G.BFSfrom(startNodes, [&](node v, count dist) {
visitNode(v, dist);
index c = comp.componentOfNode(v);
if (sum[v] >= maxDist[c]) {
maxDist[c] = sum[v];
startNodes[c] = v;
}
});
updateBounds();
}
handler.assureRunning();
std::vector<count> minDist(numberOfComponents, G.numberOfNodes());
G.forNodes([&](node u) {
auto c = comp.componentOfNode(u);
if (sum[u] < minDist[c]) {
minDist[c] = sum[u];
startNodes[c] = u;
}
});
handler.assureRunning();
G.BFSfrom(startNodes, visitNode);
updateBounds();
count lb, ub;
std::tie(lb, ub) = diameterBounds();
for (index i = 0; i < G.numberOfNodes() && ub > (lb + error*lb); ++i) {
handler.assureRunning();
startNodes.clear();
startNodes.resize(numberOfComponents, none);
if ((i % 2) == 0) {
G.forNodes([&](node u) {
auto c = comp.componentOfNode(u);
if (startNodes[c] == none || std::tie(eccUpperBound[u], sum[u]) > std::tie(eccUpperBound[startNodes[c]], sum[startNodes[c]])) {
startNodes[c] = u;
}
});
} else {
G.forNodes([&](node u) {
auto c = comp.componentOfNode(u);
if (startNodes[c] == none || std::tie(eccLowerBound[u], sum[u]) < std::tie(eccLowerBound[startNodes[c]], sum[startNodes[c]])) {
startNodes[c] = u;
}
});
}
handler.assureRunning();
G.BFSfrom(startNodes, visitNode);
handler.assureRunning();
updateBounds();
std::tie(lb, ub) = diameterBounds();
}
return {lb, ub};
}
edgeweight Diameter::estimatedVertexDiameter(const Graph& G, count samples) {
edgeweight infDist = std::numeric_limits<edgeweight>::max();
// TODO: consider weights
auto estimateFrom = [&](node v) -> count {
BFS bfs(G, v);
bfs.run();
auto distances = bfs.getDistances();
// get two largest path lengths
edgeweight maxD = 0;
edgeweight maxD2 = 0; // second largest distance
for (auto d : distances) {
if ((d != infDist) && (d >= maxD)) {
maxD2 = maxD;
maxD = d;
}
}
edgeweight dMax = maxD + maxD2;
count vd = (count) dMax + 1; // count the nodes, not the edges
return vd;
};
edgeweight vdMax = 0;
#pragma omp parallel for
for (count i = 0; i < samples; ++i) {
node u = G.randomNode();
edgeweight vd = estimateFrom(u);
DEBUG("sampled vertex diameter from node ", u, ": ", vd);
#pragma omp critical
{
if (vd > vdMax) {
vdMax = vd;
}
}
}
return vdMax;
}
edgeweight Diameter::estimatedVertexDiameterPedantic(const Graph& G) {
count vd = 0;
if (!G.isWeighted()) {
std::vector<bool> visited(G.upperNodeIdBound(), false);
// perform breadth-first searches
G.forNodes([&](node u) {
if (visited[u] == false) {
count maxDist = 0, maxDist2 = 0;
G.BFSfrom(u, [&](node v, count dist) {
visited[v] = true;
if (dist > maxDist) {
maxDist2 = maxDist;
maxDist = dist;
}
else if (dist > maxDist2) {
maxDist2 = dist;
}
});
if (maxDist + maxDist2 > vd) {
vd = maxDist + maxDist2;
}
assert (visited[u] == true);
}
});
vd ++; //we need the number of nodes, not the number of edges
}
else {
ConnectedComponents cc(G);
DEBUG("finding connected components");
cc.run();
INFO("Number of components ", cc.numberOfComponents());
DEBUG("Estimating size of the largest component");
std::map<count, count> sizes = cc.getComponentSizes();
count largest_comp_size = 0;
for(auto it = sizes.cbegin(); it != sizes.cend(); ++it) {
DEBUG(it->second);
if (it->second > largest_comp_size) {
largest_comp_size = it->second;
}
}
INFO("Largest component size: ", largest_comp_size);
vd = largest_comp_size;
}
return vd;
}
} /* namespace NetworKit */
<|endoftext|> |
<commit_before>// Copyright (c) 2014 GitHub, Inc.
// Use of this source code is governed by the MIT license that can be
// found in the LICENSE file.
#include "atom/browser/web_view_manager.h"
#include "atom/browser/atom_browser_context.h"
#include "content/public/browser/render_process_host.h"
namespace atom {
WebViewManager::WebViewManager() {
}
WebViewManager::~WebViewManager() {
}
void WebViewManager::AddGuest(int guest_instance_id,
int element_instance_id,
content::WebContents* embedder,
content::WebContents* web_contents) {
web_contents_embedder_map_[guest_instance_id] = { web_contents, embedder };
// Map the element in embedder to guest.
int owner_process_id = embedder->GetRenderProcessHost()->GetID();
ElementInstanceKey key(owner_process_id, element_instance_id);
element_instance_id_to_guest_map_[key] = guest_instance_id;
}
void WebViewManager::RemoveGuest(int guest_instance_id) {
if (!ContainsKey(web_contents_embedder_map_, guest_instance_id))
return;
web_contents_embedder_map_.erase(guest_instance_id);
// Remove the record of element in embedder too.
for (const auto& element : element_instance_id_to_guest_map_)
if (element.second == guest_instance_id) {
element_instance_id_to_guest_map_.erase(element.first);
break;
}
}
content::WebContents* WebViewManager::GetEmbedder(int guest_instance_id) {
if (ContainsKey(web_contents_embedder_map_, guest_instance_id))
return web_contents_embedder_map_[guest_instance_id].embedder;
else
return nullptr;
}
content::WebContents* WebViewManager::GetGuestByInstanceID(
int owner_process_id,
int element_instance_id) {
ElementInstanceKey key(owner_process_id, element_instance_id);
if (!ContainsKey(element_instance_id_to_guest_map_, key))
return nullptr;
int guest_instance_id = element_instance_id_to_guest_map_[key];
if (ContainsKey(web_contents_embedder_map_, guest_instance_id))
return web_contents_embedder_map_[guest_instance_id].web_contents;
else
return nullptr;
}
bool WebViewManager::ForEachGuest(content::WebContents* embedder_web_contents,
const GuestCallback& callback) {
for (auto& item : web_contents_embedder_map_)
if (item.second.embedder == embedder_web_contents &&
callback.Run(item.second.web_contents))
return true;
return false;
}
// static
WebViewManager* WebViewManager::GetWebViewManager(
content::WebContents* web_contents) {
auto context = web_contents->GetBrowserContext();
if (context) {
auto manager = context->GetGuestManager();
return static_cast<atom::WebViewManager*>(manager);
} else {
return nullptr;
}
}
} // namespace atom
<commit_msg>Remove redundant atom:: namespace use<commit_after>// Copyright (c) 2014 GitHub, Inc.
// Use of this source code is governed by the MIT license that can be
// found in the LICENSE file.
#include "atom/browser/web_view_manager.h"
#include "atom/browser/atom_browser_context.h"
#include "content/public/browser/render_process_host.h"
namespace atom {
WebViewManager::WebViewManager() {
}
WebViewManager::~WebViewManager() {
}
void WebViewManager::AddGuest(int guest_instance_id,
int element_instance_id,
content::WebContents* embedder,
content::WebContents* web_contents) {
web_contents_embedder_map_[guest_instance_id] = { web_contents, embedder };
// Map the element in embedder to guest.
int owner_process_id = embedder->GetRenderProcessHost()->GetID();
ElementInstanceKey key(owner_process_id, element_instance_id);
element_instance_id_to_guest_map_[key] = guest_instance_id;
}
void WebViewManager::RemoveGuest(int guest_instance_id) {
if (!ContainsKey(web_contents_embedder_map_, guest_instance_id))
return;
web_contents_embedder_map_.erase(guest_instance_id);
// Remove the record of element in embedder too.
for (const auto& element : element_instance_id_to_guest_map_)
if (element.second == guest_instance_id) {
element_instance_id_to_guest_map_.erase(element.first);
break;
}
}
content::WebContents* WebViewManager::GetEmbedder(int guest_instance_id) {
if (ContainsKey(web_contents_embedder_map_, guest_instance_id))
return web_contents_embedder_map_[guest_instance_id].embedder;
else
return nullptr;
}
content::WebContents* WebViewManager::GetGuestByInstanceID(
int owner_process_id,
int element_instance_id) {
ElementInstanceKey key(owner_process_id, element_instance_id);
if (!ContainsKey(element_instance_id_to_guest_map_, key))
return nullptr;
int guest_instance_id = element_instance_id_to_guest_map_[key];
if (ContainsKey(web_contents_embedder_map_, guest_instance_id))
return web_contents_embedder_map_[guest_instance_id].web_contents;
else
return nullptr;
}
bool WebViewManager::ForEachGuest(content::WebContents* embedder_web_contents,
const GuestCallback& callback) {
for (auto& item : web_contents_embedder_map_)
if (item.second.embedder == embedder_web_contents &&
callback.Run(item.second.web_contents))
return true;
return false;
}
// static
WebViewManager* WebViewManager::GetWebViewManager(
content::WebContents* web_contents) {
auto context = web_contents->GetBrowserContext();
if (context) {
auto manager = context->GetGuestManager();
return static_cast<WebViewManager*>(manager);
} else {
return nullptr;
}
}
} // namespace atom
<|endoftext|> |
<commit_before>/*
This file is part of KOrganizer.
Copyright (c) 2003 Cornelius Schumacher <[email protected]>
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., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
As a special exception, permission is given to link this program
with any edition of Qt, and distribute the resulting executable,
without including the source code for Qt in the source distribution.
*/
#include "koeditorattachments.h"
#include "kocore.h"
#include "urihandler.h"
#include <klocale.h>
#include <kdebug.h>
#include <kfiledialog.h>
#include <kmessagebox.h>
#include <qlayout.h>
#include <qlistview.h>
#include <qpushbutton.h>
KOEditorAttachments::KOEditorAttachments( int spacing, QWidget *parent,
const char *name )
: QWidget( parent, name )
{
QBoxLayout *topLayout = new QVBoxLayout( this );
topLayout->setSpacing( spacing );
mAttachments = new QListView( this );
mAttachments->addColumn( i18n("URI") );
mAttachments->addColumn( i18n("MIME Type") );
topLayout->addWidget( mAttachments );
connect( mAttachments, SIGNAL( doubleClicked( QListViewItem * ) ),
SLOT( showAttachment( QListViewItem * ) ) );
QBoxLayout *buttonLayout = new QHBoxLayout( topLayout );
QPushButton *button = new QPushButton( i18n("Add..."), this );
buttonLayout->addWidget( button );
connect( button, SIGNAL( clicked() ), SLOT( slotAdd() ) );
button = new QPushButton( i18n("Edit..."), this );
buttonLayout->addWidget( button );
connect( button, SIGNAL( clicked() ), SLOT( slotEdit() ) );
button = new QPushButton( i18n("Remove"), this );
buttonLayout->addWidget( button );
connect( button, SIGNAL( clicked() ), SLOT( slotRemove() ) );
button = new QPushButton( i18n("Show"), this );
buttonLayout->addWidget( button );
connect( button, SIGNAL( clicked() ), SLOT( slotShow() ) );
}
KOEditorAttachments::~KOEditorAttachments()
{
}
void KOEditorAttachments::showAttachment( QListViewItem *item )
{
if ( !item ) return;
QString uri = item->text( 0 );
UriHandler::process( uri );
}
void KOEditorAttachments::slotAdd()
{
QString uri = KFileDialog::getOpenFileName( QString::null, QString::null,
0, i18n("Add Attachment") );
if ( !uri.isEmpty() ) {
new QListViewItem( mAttachments, uri );
}
}
void KOEditorAttachments::slotEdit()
{
QListViewItem *item = mAttachments->currentItem();
if ( !item ) return;
QString uri = KFileDialog::getOpenFileName( item->text( 0 ), QString::null,
0, i18n("Edit Attachment") );
if ( !uri.isEmpty() ) item->setText( 0, uri );
}
void KOEditorAttachments::slotRemove()
{
QListViewItem *item = mAttachments->currentItem();
if ( !item ) return;
if ( KMessageBox::warningContinueCancel(this,
i18n("This item will be permanently deleted."),
i18n("KOrganizer Confirmation"),KGuiItem(i18n("Delete"),"editdelete")) == KMessageBox::Continue )
delete item;
}
void KOEditorAttachments::slotShow()
{
showAttachment( mAttachments->currentItem() );
}
void KOEditorAttachments::setDefaults()
{
mAttachments->clear();
}
void KOEditorAttachments::addAttachment( const QString &uri,
const QString &mimeType )
{
new QListViewItem( mAttachments, uri, mimeType );
}
void KOEditorAttachments::readIncidence( Incidence *i )
{
mAttachments->clear();
Attachment::List attachments = i->attachments();
Attachment::List::ConstIterator it;
for( it = attachments.begin(); it != attachments.end(); ++it ) {
QString uri;
if ( (*it)->isUri() ) uri = (*it)->uri();
else uri = i18n("[Binary data]");
addAttachment( uri, (*it)->mimeType() );
}
}
void KOEditorAttachments::writeIncidence( Incidence *i )
{
i->clearAttachments();
QListViewItem *item;
for( item = mAttachments->firstChild(); item; item = item->nextSibling() ) {
i->addAttachment( new Attachment( item->text( 0 ), item->text( 1 ) ) );
}
}
#include "koeditorattachments.moc"
<commit_msg>Use getOpenURL instead of getOpenFile, which makes it possible to attach remote files.<commit_after>/*
This file is part of KOrganizer.
Copyright (c) 2003 Cornelius Schumacher <[email protected]>
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., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
As a special exception, permission is given to link this program
with any edition of Qt, and distribute the resulting executable,
without including the source code for Qt in the source distribution.
*/
#include "koeditorattachments.h"
#include "kocore.h"
#include "urihandler.h"
#include <klocale.h>
#include <kdebug.h>
#include <kfiledialog.h>
#include <kmessagebox.h>
#include <qlayout.h>
#include <qlistview.h>
#include <qpushbutton.h>
KOEditorAttachments::KOEditorAttachments( int spacing, QWidget *parent,
const char *name )
: QWidget( parent, name )
{
QBoxLayout *topLayout = new QVBoxLayout( this );
topLayout->setSpacing( spacing );
mAttachments = new QListView( this );
mAttachments->addColumn( i18n("URI") );
mAttachments->addColumn( i18n("MIME Type") );
topLayout->addWidget( mAttachments );
connect( mAttachments, SIGNAL( doubleClicked( QListViewItem * ) ),
SLOT( showAttachment( QListViewItem * ) ) );
QBoxLayout *buttonLayout = new QHBoxLayout( topLayout );
QPushButton *button = new QPushButton( i18n("Add..."), this );
buttonLayout->addWidget( button );
connect( button, SIGNAL( clicked() ), SLOT( slotAdd() ) );
button = new QPushButton( i18n("Edit..."), this );
buttonLayout->addWidget( button );
connect( button, SIGNAL( clicked() ), SLOT( slotEdit() ) );
button = new QPushButton( i18n("Remove"), this );
buttonLayout->addWidget( button );
connect( button, SIGNAL( clicked() ), SLOT( slotRemove() ) );
button = new QPushButton( i18n("Show"), this );
buttonLayout->addWidget( button );
connect( button, SIGNAL( clicked() ), SLOT( slotShow() ) );
}
KOEditorAttachments::~KOEditorAttachments()
{
}
void KOEditorAttachments::showAttachment( QListViewItem *item )
{
if ( !item ) return;
QString uri = item->text( 0 );
UriHandler::process( uri );
}
void KOEditorAttachments::slotAdd()
{
KURL uri = KFileDialog::getOpenURL( QString::null, QString::null,
0, i18n("Add Attachment") );
if ( !uri.isEmpty() ) {
new QListViewItem( mAttachments, uri.url() );
}
}
void KOEditorAttachments::slotEdit()
{
QListViewItem *item = mAttachments->currentItem();
if ( !item ) return;
KURL uri = KFileDialog::getOpenURL( item->text( 0 ), QString::null,
0, i18n("Edit Attachment") );
if ( !uri.isEmpty() ) item->setText( 0, uri.url() );
}
void KOEditorAttachments::slotRemove()
{
QListViewItem *item = mAttachments->currentItem();
if ( !item ) return;
if ( KMessageBox::warningContinueCancel(this,
i18n("This item will be permanently deleted."),
i18n("KOrganizer Confirmation"),KGuiItem(i18n("Delete"),"editdelete")) == KMessageBox::Continue )
delete item;
}
void KOEditorAttachments::slotShow()
{
showAttachment( mAttachments->currentItem() );
}
void KOEditorAttachments::setDefaults()
{
mAttachments->clear();
}
void KOEditorAttachments::addAttachment( const QString &uri,
const QString &mimeType )
{
new QListViewItem( mAttachments, uri, mimeType );
}
void KOEditorAttachments::readIncidence( Incidence *i )
{
mAttachments->clear();
Attachment::List attachments = i->attachments();
Attachment::List::ConstIterator it;
for( it = attachments.begin(); it != attachments.end(); ++it ) {
QString uri;
if ( (*it)->isUri() ) uri = (*it)->uri();
else uri = i18n("[Binary data]");
addAttachment( uri, (*it)->mimeType() );
}
}
void KOEditorAttachments::writeIncidence( Incidence *i )
{
i->clearAttachments();
QListViewItem *item;
for( item = mAttachments->firstChild(); item; item = item->nextSibling() ) {
i->addAttachment( new Attachment( item->text( 0 ), item->text( 1 ) ) );
}
}
#include "koeditorattachments.moc"
<|endoftext|> |
<commit_before>
#pragma once
#include "gmock/gmock.h"
#include "ksp_plugin/manœuvre.hpp"
namespace principia {
namespace ksp_plugin {
template <typename InertialFrame, typename Frame>
class MockManœuvre : public Manœuvre<InertialFrame, Frame>{
public:
MockManœuvre(
Force const& thrust,
Mass const& initial_mass,
SpecificImpulse const& specific_impulse,
Vector<double, Frenet<Frame>> const& direction,
not_null<std::unique_ptr<DynamicFrame<InertialFrame, Frame> const>> frame)
: Manœuvre(thrust,
initial_mass,
specific_impulse,
direction,
std::move(frame)) {}
MOCK_CONST_METHOD0_T(InertialDirection, Vector<double, InertialFrame>());
MOCK_CONST_METHOD0_T(FrenetFrame,
OrthogonalMap<Frenet<Frame>, InertialFrame>());
};
} // namespace ksp_plugin
} // namespace principia
<commit_msg>standardize<commit_after>
#pragma once
#include "gmock/gmock.h"
#include "ksp_plugin/manœuvre.hpp"
namespace principia {
namespace ksp_plugin {
template <typename InertialFrame, typename Frame>
class MockManœuvre : public Manœuvre<InertialFrame, Frame>{
public:
MockManœuvre(
Force const& thrust,
Mass const& initial_mass,
SpecificImpulse const& specific_impulse,
Vector<double, Frenet<Frame>> const& direction,
not_null<std::unique_ptr<DynamicFrame<InertialFrame, Frame> const>> frame)
: Manœuvre<InertialFrame, Frame>(thrust,
initial_mass,
specific_impulse,
direction,
std::move(frame)) {}
MOCK_CONST_METHOD0_T(InertialDirection, Vector<double, InertialFrame>());
MOCK_CONST_METHOD0_T(FrenetFrame,
OrthogonalMap<Frenet<Frame>, InertialFrame>());
};
} // namespace ksp_plugin
} // namespace principia
<|endoftext|> |
<commit_before>#include <cmath>
#include <cstdlib>
#include <iostream>
#include <vector>
#include <map>
using namespace std;
const int element_shape_x = 5;
const int element_shape_y = 6;
const int mpi_shape_x = 4;
const int mpi_shape_y = 3;
const int shape_x = element_shape_x * mpi_shape_x;
const int shape_y = element_shape_y * mpi_shape_y;
const int shape_t = 30;
int wrap_x(const int x) {
return (x+shape_x)%shape_x;
}
int wrap_y(const int y) {
return (y+shape_y)%shape_y;
}
int irand(const int hi) {
return floor(rand()/double(RAND_MAX)*hi);
}
enum Direction{
TP,
XP,
XM,
YP,
YM
};
struct Region{
int t,x,y;
Region(int t,int x,int y) : t(t), x(wrap_x(x)), y(wrap_y(y)) {}
bool operator==(const Region &other) {
return other.t==t && other.x==x && other.y==y;
}
bool operator!=(const Region &other) {
return !(*this == other);
}
bool operator<(const Region &other) {
return t<other.t || (t==other.t && (x<other.x || (x==other.x && y<other.y)));
}
};
ostream& operator<<(ostream& ostr, const Region& r) {
ostr << "("
<< r.t << ","
<< r.x << ","
<< r.y << ")";
return ostr;
}
struct Facet{
Direction d;
int t,x,y;
Facet(Direction d,int t,int x,int y) : d(d), t(t), x(wrap_x(x)), y(wrap_y(y)) {}
};
Region random_region() {
return Region(irand(shape_t), irand(shape_x), irand(shape_y));
}
Region prev_region(const Facet &f) {
return Region(f.t, f.x, f.y);
}
Region next_region(const Facet &f) {
switch(f.d) {
case TP:
return Region(f.t + 1, f.x, f.y);
case XP:
return Region(f.t, f.x + 1, f.y);
case XM:
return Region(f.t, f.x - 1, f.y);
case YP:
return Region(f.t, f.x, f.y + 1);
case YM:
return Region(f.t, f.x, f.y - 1);
}
}
vector<Facet> prev_facets(const Region &r) {
vector<Facet> ret(1, Facet(TP, r.t-1, r.x, r.y));
if (r.t%2 != r.x%2) {
ret.push_back( Facet(XP, r.t, r.x-1, r.y) );
ret.push_back( Facet(XM, r.t, r.x+1, r.y) );
}
if (r.t%2 != r.y%2) {
ret.push_back( Facet(YP, r.t, r.x, r.y-1) );
ret.push_back( Facet(YM, r.t, r.x, r.y+1) );
}
return ret;
}
vector<Facet> next_facets(const Region &r) {
vector<Facet> ret(1, Facet(TP, r.t, r.x, r.y));
if (r.t%2 == r.x%2) {
ret.push_back( Facet(XP, r.t, r.x, r.y) );
ret.push_back( Facet(XM, r.t, r.x, r.y) );
}
if (r.t%2 == r.y%2) {
ret.push_back( Facet(YP, r.t, r.x, r.y) );
ret.push_back( Facet(YM, r.t, r.x, r.y) );
}
return ret;
}
int rank_assingment(const Region &r) {
int rx = r.x / element_shape_x;
int ry = r.y / element_shape_y;
return ry * mpi_shape_x + rx;
}
int main(){
cout << "ping" << endl;
cout << "pong" << endl;
cout << sizeof(Region) << endl;
cout << sizeof(Facet) << endl;
for(int i=0;i<1000000; ++i) {
Region r = random_region();
vector<Facet> fs = next_facets(r);
for (int j=0; j< fs.size(); ++j) {
Facet &f=fs[j];
if(prev_region(f) != r) {
cout << "wrong facet " << endl;
cout << r << endl;
}
}
}
for(int i=0;i<1000000; ++i) {
Region r = random_region();
vector<Facet> fs = prev_facets(r);
for (int j=0; j< fs.size(); ++j) {
Facet &f=fs[j];
if(next_region(f) != r) {
cout << "wrong facet " << endl;
cout << r << endl;
cout << next_region(f) << endl;
return -1;
}
}
}
{
map<int, int> ctr;
for(int j=0;j<shape_y; ++j) {
for(int i=0;i<shape_x; ++i) {
Region r(0,i,j);
ctr[rank_assingment(r)]++;
}
}
for(map<int,int>::iterator it=ctr.begin(); it!=ctr.end();++it) {
cout << it->first << " " << it->second << endl;
}
}
return 0;
}
<commit_msg>implemented tests.<commit_after>#include <cmath>
#include <cstdlib>
#include <iostream>
#include <string>
#include <vector>
#include <map>
using namespace std;
const int element_shape_x = 5;
const int element_shape_y = 6;
const int mpi_shape_x = 4;
const int mpi_shape_y = 3;
const int shape_x = element_shape_x * mpi_shape_x;
const int shape_y = element_shape_y * mpi_shape_y;
const int shape_t = 30;
int wrap_x(const int x) {
return (x+shape_x)%shape_x;
}
int wrap_y(const int y) {
return (y+shape_y)%shape_y;
}
int irand(const int hi) {
return floor(rand()/double(RAND_MAX)*hi);
}
enum Direction{
TP,
XP,
XM,
YP,
YM
};
struct Region{
int t,x,y;
Region(int t,int x,int y) : t(t), x(wrap_x(x)), y(wrap_y(y)) {}
bool operator==(const Region &other) {
return other.t==t && other.x==x && other.y==y;
}
bool operator!=(const Region &other) {
return !(*this == other);
}
bool operator<(const Region &other) {
return t<other.t || (t==other.t && (x<other.x || (x==other.x && y<other.y)));
}
};
ostream& operator<<(ostream& ostr, const Region& r) {
ostr << "("
<< r.t << ","
<< r.x << ","
<< r.y << ")";
return ostr;
}
struct Facet{
Direction d;
int t,x,y;
Facet(Direction d,int t,int x,int y) : d(d), t(t), x(wrap_x(x)), y(wrap_y(y)) {}
};
Region random_region() {
return Region(irand(shape_t), irand(shape_x), irand(shape_y));
}
Region prev_region(const Facet &f) {
return Region(f.t, f.x, f.y);
}
Region next_region(const Facet &f) {
switch(f.d) {
case TP:
return Region(f.t + 1, f.x, f.y);
case XP:
return Region(f.t, f.x + 1, f.y);
case XM:
return Region(f.t, f.x - 1, f.y);
case YP:
return Region(f.t, f.x, f.y + 1);
case YM:
return Region(f.t, f.x, f.y - 1);
}
}
vector<Facet> prev_facets(const Region &r) {
vector<Facet> ret;
if (r.t < shape_t) ret.push_back(Facet(TP, r.t - 1, r.x, r.y));
if (r.t%2 != r.x%2) {
ret.push_back( Facet(XP, r.t, r.x-1, r.y) );
ret.push_back( Facet(XM, r.t, r.x+1, r.y) );
}
if (r.t%2 != r.y%2) {
ret.push_back( Facet(YP, r.t, r.x, r.y-1) );
ret.push_back( Facet(YM, r.t, r.x, r.y+1) );
}
return ret;
}
vector<Facet> next_facets(const Region &r) {
vector<Facet> ret;
if (r.t < shape_t -1) ret.push_back(Facet(TP, r.t, r.x, r.y));
if (r.t%2 == r.x%2) {
ret.push_back( Facet(XP, r.t, r.x, r.y) );
ret.push_back( Facet(XM, r.t, r.x, r.y) );
}
if (r.t%2 == r.y%2) {
ret.push_back( Facet(YP, r.t, r.x, r.y) );
ret.push_back( Facet(YM, r.t, r.x, r.y) );
}
return ret;
}
int rank_assingment(const Region &r) {
int rx = r.x / element_shape_x;
int ry = r.y / element_shape_y;
return ry * mpi_shape_x + rx;
}
int test(){
cout << "ping" << endl;
cout << "pong" << endl;
cout << sizeof(Region) << endl;
cout << sizeof(Facet) << endl;
for(int i=0;i<1000000; ++i) {
Region r = random_region();
vector<Facet> fs = next_facets(r);
for (int j=0; j< fs.size(); ++j) {
Facet &f=fs[j];
if(prev_region(f) != r) {
cout << "wrong facet " << endl;
cout << r << endl;
}
}
}
for(int i=0;i<1000000; ++i) {
Region r = random_region();
vector<Facet> fs = prev_facets(r);
for (int j=0; j< fs.size(); ++j) {
Facet &f=fs[j];
if(next_region(f) != r) {
cout << "wrong facet " << endl;
cout << r << endl;
cout << next_region(f) << endl;
return -1;
}
}
}
{
map<int, int> ctr;
for(int j=0;j<shape_y; ++j) {
for(int i=0;i<shape_x; ++i) {
Region r(0,i,j);
ctr[rank_assingment(r)]++;
}
}
for(map<int,int>::iterator it=ctr.begin(); it!=ctr.end();++it) {
cout << it->first << " " << it->second << endl;
}
}
return 0;
}
int main(){
test();
}
<|endoftext|> |
<commit_before>/* This file is part of the KDE project
Copyright (C) 2006-2007 Matthias Kretz <[email protected]>
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License version 2
as published by the Free Software Foundation.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
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 "mediacontrols.h"
#include <QtCore/QTimer>
#include <QtGui/QAction>
#include <QtGui/QLabel>
#include <QtGui/QDockWidget>
#include <QtGui/QMainWindow>
#include <QtGui/QBoxLayout>
#include <QtGui/QCheckBox>
#include <QtGui/QComboBox>
#include <QtGui/QPushButton>
#include <QtGui/QSlider>
#include <phonon/audiooutput.h>
#include <phonon/backendcapabilities.h>
#include <phonon/effect.h>
#include <phonon/effectwidget.h>
#include <phonon/mediaobject.h>
#include <phonon/path.h>
#include <phonon/videowidget.h>
#include <kaboutdata.h>
#include <kdebug.h>
#include <kfiledialog.h>
#include <kapplication.h>
#include <kcmdlineargs.h>
#include <kicon.h>
#include <kurl.h>
#include <cstdlib>
using Phonon::MediaObject;
using Phonon::MediaSource;
using Phonon::AudioOutput;
using Phonon::VideoWidget;
using Phonon::MediaControls;
using Phonon::Effect;
using Phonon::EffectWidget;
class MediaPlayer : public QMainWindow
{
Q_OBJECT
public:
MediaPlayer();
void setUrl(const KUrl &url);
private Q_SLOTS:
void stateChanged(Phonon::State newstate);
void workaroundQtBug();
void getNextUrl();
void startupReady();
void openEffectWidget();
void toggleScaleMode(bool);
void switchAspectRatio(int x);
void setBrightness(int b);
private:
bool setNextSource();
QWidget *m_settingsWidget;
Phonon::MediaObject *m_media;
Phonon::Path m_apath;
Phonon::AudioOutput *m_aoutput;
Phonon::Path m_vpath;
Phonon::Effect *m_effect;
Phonon::VideoWidget *m_vwidget;
Phonon::MediaControls *m_controls;
Phonon::EffectWidget *m_effectWidget;
QAction *m_fullScreenAction;
};
MediaPlayer::MediaPlayer()
: QMainWindow(0), m_effectWidget(0)
{
QDockWidget *dock = new QDockWidget(this);
dock->setAllowedAreas(Qt::BottomDockWidgetArea);
m_settingsWidget = new QWidget(dock);
dock->setWidget(m_settingsWidget);
addDockWidget(Qt::BottomDockWidgetArea, dock);
QVBoxLayout *layout = new QVBoxLayout(m_settingsWidget);
m_vwidget = new VideoWidget(this);
setCentralWidget(m_vwidget);
m_fullScreenAction = new QAction(m_vwidget);
m_fullScreenAction->setShortcut(Qt::Key_F);
m_fullScreenAction->setCheckable(true);
m_fullScreenAction->setChecked(false);
this->addAction(m_fullScreenAction);
connect(m_fullScreenAction, SIGNAL(toggled(bool)), m_vwidget, SLOT(setFullScreen(bool)));
connect(m_fullScreenAction, SIGNAL(toggled(bool)), SLOT(workaroundQtBug()));
m_aoutput = new AudioOutput(Phonon::VideoCategory, this);
m_media = new MediaObject(this);
connect(m_media, SIGNAL(finished()), SLOT(getNextUrl()));
connect(m_media, SIGNAL(stateChanged(Phonon::State, Phonon::State)), SLOT(stateChanged(Phonon::State)));
createPath(m_media, m_vwidget);
m_apath = createPath(m_media, m_aoutput);
m_controls = new MediaControls(m_settingsWidget);
layout->addWidget(m_controls);
m_controls->setMediaObject(m_media);
m_controls->setAudioOutput(m_aoutput);
m_controls->setMaximumHeight(28);
/*
QList<AudioEffectDescription> effectList = BackendCapabilities::availableAudioEffects();
if (!effectList.isEmpty())
{
m_effect = new AudioEffect(BackendCapabilities::availableAudioEffects().first(), m_apath);
m_apath->insertEffect(m_effect);
QPushButton *button = new QPushButton(m_settingsWidget);
layout->addWidget(button);
button->setText("configure effect");
connect(button, SIGNAL(clicked()), SLOT(openEffectWidget()));
}
*/
QSlider *slider = new QSlider(m_settingsWidget);
layout->addWidget(slider);
slider->setOrientation(Qt::Horizontal);
slider->setRange(-100, 100);
slider->setValue(static_cast<int>(m_vwidget->brightness() * 100));
connect(slider, SIGNAL(valueChanged(int)), this, SLOT(setBrightness(int)));
QCheckBox *scaleModeCheck = new QCheckBox(m_settingsWidget);
layout->addWidget(scaleModeCheck);
connect(scaleModeCheck, SIGNAL(toggled(bool)), SLOT(toggleScaleMode(bool)));
QWidget *box = new QWidget(m_settingsWidget);
layout->addWidget(box);
QLabel *label = new QLabel("Aspect Ratio:", box);
label->setAlignment(Qt::AlignRight);
QComboBox *aspectRatioCombo = new QComboBox(box);
QHBoxLayout *hbox = new QHBoxLayout(box);
hbox->addWidget(label);
hbox->addWidget(aspectRatioCombo);
label->setBuddy(aspectRatioCombo);
connect(aspectRatioCombo, SIGNAL(currentIndexChanged(int)), SLOT(switchAspectRatio(int)));
aspectRatioCombo->addItem("auto");
aspectRatioCombo->addItem("fit");
aspectRatioCombo->addItem("4:3");
aspectRatioCombo->addItem("16:9");
this->resize(width(), height() + 240 - m_vwidget->height());
QTimer::singleShot(0, this, SLOT(startupReady()));
}
void MediaPlayer::stateChanged(Phonon::State newstate)
{
switch (newstate) {
case Phonon::ErrorState:
case Phonon::StoppedState:
getNextUrl();
break;
default:
break;
}
}
void MediaPlayer::workaroundQtBug()
{
kDebug();
if (m_vwidget->actions().contains(m_fullScreenAction)) {
m_vwidget->removeAction(m_fullScreenAction);
this->addAction(m_fullScreenAction);
} else {
this->removeAction(m_fullScreenAction);
m_vwidget->addAction(m_fullScreenAction);
}
}
bool MediaPlayer::setNextSource()
{
QWidget *extraWidget = new QWidget;
QHBoxLayout *layout = new QHBoxLayout(extraWidget);
layout->setMargin(0);
layout->addStretch();
QPushButton *dvdButton = new QPushButton(i18n("DVD"), extraWidget);
dvdButton->setCheckable(true);
dvdButton->setChecked(false);
layout->addWidget(dvdButton);
QPushButton *cdButton = new QPushButton(i18n("Audio CD"), extraWidget);
cdButton->setCheckable(true);
cdButton->setChecked(false);
layout->addWidget(cdButton);
KFileDialog dlg(KUrl(), QString(), 0, extraWidget);
connect(dvdButton, SIGNAL(toggled(bool)), &dlg, SLOT(accept()));
connect(cdButton, SIGNAL(toggled(bool)), &dlg, SLOT(accept()));
dlg.setOperationMode(KFileDialog::Opening);
dlg.setWindowTitle(i18n("Open"));
dlg.setMode(KFile::File);
dlg.exec();
KUrl url = dlg.selectedUrl();
if (dvdButton->isChecked()) {
if (url.isLocalFile()) {
m_media->setCurrentSource(MediaSource(Phonon::Dvd, url.path()));
} else {
m_media->setCurrentSource(Phonon::Dvd);
}
} else if (cdButton->isChecked()) {
m_media->setCurrentSource(Phonon::Cd);
} else if (url.isValid()) {
m_media->setCurrentSource(url);
} else {
QApplication::instance()->quit();
return false;
}
return true;
}
void MediaPlayer::getNextUrl()
{
static bool fileDialogAlreadyOpen = false;
if (fileDialogAlreadyOpen) {
return;
}
fileDialogAlreadyOpen = true;
if (!setNextSource()) {
return;
}
m_media->play();
fileDialogAlreadyOpen = false;
}
void MediaPlayer::startupReady()
{
if (m_media->currentSource().type() == MediaSource::Invalid) {
if (!setNextSource()) {
return;
}
}
m_media->play();
}
void MediaPlayer::setBrightness(int b)
{
m_vwidget->setBrightness(b * 0.01);
}
void MediaPlayer::switchAspectRatio(int x)
{
m_vwidget->setAspectRatio(static_cast<VideoWidget::AspectRatio>(x));
}
void MediaPlayer::toggleScaleMode(bool mode)
{
if (mode) {
m_vwidget->setScaleMode(VideoWidget::ScaleAndCrop);
} else {
m_vwidget->setScaleMode(VideoWidget::FitInView);
}
}
void MediaPlayer::openEffectWidget()
{
if (!m_effectWidget)
m_effectWidget = new EffectWidget(m_effect);
m_effectWidget->show();
m_effectWidget->raise();
}
void MediaPlayer::setUrl(const KUrl &url)
{
m_media->setCurrentSource(url);
//m_vwidget->setVisible(m_media->hasVideo());
}
int main(int argc, char ** argv)
{
KAboutData about("phononmediaplayer", 0, ki18n("Phonon Media Player"),
"0.1", ki18n("Media Player"),
KAboutData::License_GPL);
about.addAuthor(ki18n("Matthias Kretz"), KLocalizedString(), "[email protected]");
KCmdLineArgs::init(argc, argv, &about);
KCmdLineOptions options;
options.add("+[url]", ki18n("File to play"));
KCmdLineArgs::addCmdLineOptions( options );
KApplication app;
MediaPlayer foo;
foo.setWindowIcon(KIcon("phonon"));
foo.show();
KCmdLineArgs *args = KCmdLineArgs::parsedArgs();
if (args->count() == 1) {
KUrl url = args->url(0);
if (url.isValid()) {
foo.setUrl(url);
}
}
args->clear();
return app.exec();
}
#include "mediaplayer.moc"
#include "mediacontrols.cpp"
#include "moc_mediacontrols.cpp"
<commit_msg>Fixed test - had to create dummy QString and KUrl objects to pass to the KFileDialog constructor as file wouldn't compile otherwise.<commit_after>/* This file is part of the KDE project
Copyright (C) 2006-2007 Matthias Kretz <[email protected]>
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License version 2
as published by the Free Software Foundation.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
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 "mediacontrols.h"
#include <QtCore/QTimer>
#include <QtGui/QAction>
#include <QtGui/QLabel>
#include <QtGui/QDockWidget>
#include <QtGui/QMainWindow>
#include <QtGui/QBoxLayout>
#include <QtGui/QCheckBox>
#include <QtGui/QComboBox>
#include <QtGui/QPushButton>
#include <QtGui/QSlider>
#include <phonon/audiooutput.h>
#include <phonon/backendcapabilities.h>
#include <phonon/effect.h>
#include <phonon/effectwidget.h>
#include <phonon/mediaobject.h>
#include <phonon/path.h>
#include <phonon/videowidget.h>
#include <kaboutdata.h>
#include <kdebug.h>
#include <kfiledialog.h>
#include <kapplication.h>
#include <kcmdlineargs.h>
#include <kicon.h>
#include <kurl.h>
#include <cstdlib>
using Phonon::MediaObject;
using Phonon::MediaSource;
using Phonon::AudioOutput;
using Phonon::VideoWidget;
using Phonon::MediaControls;
using Phonon::Effect;
using Phonon::EffectWidget;
class MediaPlayer : public QMainWindow
{
Q_OBJECT
public:
MediaPlayer();
void setUrl(const KUrl &url);
private Q_SLOTS:
void stateChanged(Phonon::State newstate);
void workaroundQtBug();
void getNextUrl();
void startupReady();
void openEffectWidget();
void toggleScaleMode(bool);
void switchAspectRatio(int x);
void setBrightness(int b);
private:
bool setNextSource();
QWidget *m_settingsWidget;
Phonon::MediaObject *m_media;
Phonon::Path m_apath;
Phonon::AudioOutput *m_aoutput;
Phonon::Path m_vpath;
Phonon::Effect *m_effect;
Phonon::VideoWidget *m_vwidget;
Phonon::MediaControls *m_controls;
Phonon::EffectWidget *m_effectWidget;
QAction *m_fullScreenAction;
};
MediaPlayer::MediaPlayer()
: QMainWindow(0), m_effectWidget(0)
{
QDockWidget *dock = new QDockWidget(this);
dock->setAllowedAreas(Qt::BottomDockWidgetArea);
m_settingsWidget = new QWidget(dock);
dock->setWidget(m_settingsWidget);
addDockWidget(Qt::BottomDockWidgetArea, dock);
QVBoxLayout *layout = new QVBoxLayout(m_settingsWidget);
m_vwidget = new VideoWidget(this);
setCentralWidget(m_vwidget);
m_fullScreenAction = new QAction(m_vwidget);
m_fullScreenAction->setShortcut(Qt::Key_F);
m_fullScreenAction->setCheckable(true);
m_fullScreenAction->setChecked(false);
this->addAction(m_fullScreenAction);
connect(m_fullScreenAction, SIGNAL(toggled(bool)), m_vwidget, SLOT(setFullScreen(bool)));
connect(m_fullScreenAction, SIGNAL(toggled(bool)), SLOT(workaroundQtBug()));
m_aoutput = new AudioOutput(Phonon::VideoCategory, this);
m_media = new MediaObject(this);
connect(m_media, SIGNAL(finished()), SLOT(getNextUrl()));
connect(m_media, SIGNAL(stateChanged(Phonon::State, Phonon::State)), SLOT(stateChanged(Phonon::State)));
createPath(m_media, m_vwidget);
m_apath = createPath(m_media, m_aoutput);
m_controls = new MediaControls(m_settingsWidget);
layout->addWidget(m_controls);
m_controls->setMediaObject(m_media);
m_controls->setAudioOutput(m_aoutput);
m_controls->setMaximumHeight(28);
/*
QList<AudioEffectDescription> effectList = BackendCapabilities::availableAudioEffects();
if (!effectList.isEmpty())
{
m_effect = new AudioEffect(BackendCapabilities::availableAudioEffects().first(), m_apath);
m_apath->insertEffect(m_effect);
QPushButton *button = new QPushButton(m_settingsWidget);
layout->addWidget(button);
button->setText("configure effect");
connect(button, SIGNAL(clicked()), SLOT(openEffectWidget()));
}
*/
QSlider *slider = new QSlider(m_settingsWidget);
layout->addWidget(slider);
slider->setOrientation(Qt::Horizontal);
slider->setRange(-100, 100);
slider->setValue(static_cast<int>(m_vwidget->brightness() * 100));
connect(slider, SIGNAL(valueChanged(int)), this, SLOT(setBrightness(int)));
QCheckBox *scaleModeCheck = new QCheckBox(m_settingsWidget);
layout->addWidget(scaleModeCheck);
connect(scaleModeCheck, SIGNAL(toggled(bool)), SLOT(toggleScaleMode(bool)));
QWidget *box = new QWidget(m_settingsWidget);
layout->addWidget(box);
QLabel *label = new QLabel("Aspect Ratio:", box);
label->setAlignment(Qt::AlignRight);
QComboBox *aspectRatioCombo = new QComboBox(box);
QHBoxLayout *hbox = new QHBoxLayout(box);
hbox->addWidget(label);
hbox->addWidget(aspectRatioCombo);
label->setBuddy(aspectRatioCombo);
connect(aspectRatioCombo, SIGNAL(currentIndexChanged(int)), SLOT(switchAspectRatio(int)));
aspectRatioCombo->addItem("auto");
aspectRatioCombo->addItem("fit");
aspectRatioCombo->addItem("4:3");
aspectRatioCombo->addItem("16:9");
this->resize(width(), height() + 240 - m_vwidget->height());
QTimer::singleShot(0, this, SLOT(startupReady()));
}
void MediaPlayer::stateChanged(Phonon::State newstate)
{
switch (newstate) {
case Phonon::ErrorState:
case Phonon::StoppedState:
getNextUrl();
break;
default:
break;
}
}
void MediaPlayer::workaroundQtBug()
{
kDebug();
if (m_vwidget->actions().contains(m_fullScreenAction)) {
m_vwidget->removeAction(m_fullScreenAction);
this->addAction(m_fullScreenAction);
} else {
this->removeAction(m_fullScreenAction);
m_vwidget->addAction(m_fullScreenAction);
}
}
bool MediaPlayer::setNextSource()
{
QWidget *extraWidget = new QWidget;
QHBoxLayout *layout = new QHBoxLayout(extraWidget);
layout->setMargin(0);
layout->addStretch();
QPushButton *dvdButton = new QPushButton(i18n("DVD"), extraWidget);
dvdButton->setCheckable(true);
dvdButton->setChecked(false);
layout->addWidget(dvdButton);
QPushButton *cdButton = new QPushButton(i18n("Audio CD"), extraWidget);
cdButton->setCheckable(true);
cdButton->setChecked(false);
layout->addWidget(cdButton);
const QString dummyString;
const KUrl dummyUrl;
KFileDialog dlg(dummyUrl, dummyString, 0, extraWidget);
connect(dvdButton, SIGNAL(toggled(bool)), &dlg, SLOT(accept()));
connect(cdButton, SIGNAL(toggled(bool)), &dlg, SLOT(accept()));
dlg.setOperationMode(KFileDialog::Opening);
dlg.setWindowTitle(i18n("Open"));
dlg.setMode(KFile::File);
dlg.exec();
KUrl url = dlg.selectedUrl();
if (dvdButton->isChecked()) {
if (url.isLocalFile()) {
m_media->setCurrentSource(MediaSource(Phonon::Dvd, url.path()));
} else {
m_media->setCurrentSource(Phonon::Dvd);
}
} else if (cdButton->isChecked()) {
m_media->setCurrentSource(Phonon::Cd);
} else if (url.isValid()) {
m_media->setCurrentSource(url);
} else {
QApplication::instance()->quit();
return false;
}
return true;
}
void MediaPlayer::getNextUrl()
{
static bool fileDialogAlreadyOpen = false;
if (fileDialogAlreadyOpen) {
return;
}
fileDialogAlreadyOpen = true;
if (!setNextSource()) {
return;
}
m_media->play();
fileDialogAlreadyOpen = false;
}
void MediaPlayer::startupReady()
{
if (m_media->currentSource().type() == MediaSource::Invalid) {
if (!setNextSource()) {
return;
}
}
m_media->play();
}
void MediaPlayer::setBrightness(int b)
{
m_vwidget->setBrightness(b * 0.01);
}
void MediaPlayer::switchAspectRatio(int x)
{
m_vwidget->setAspectRatio(static_cast<VideoWidget::AspectRatio>(x));
}
void MediaPlayer::toggleScaleMode(bool mode)
{
if (mode) {
m_vwidget->setScaleMode(VideoWidget::ScaleAndCrop);
} else {
m_vwidget->setScaleMode(VideoWidget::FitInView);
}
}
void MediaPlayer::openEffectWidget()
{
if (!m_effectWidget)
m_effectWidget = new EffectWidget(m_effect);
m_effectWidget->show();
m_effectWidget->raise();
}
void MediaPlayer::setUrl(const KUrl &url)
{
m_media->setCurrentSource(url);
//m_vwidget->setVisible(m_media->hasVideo());
}
int main(int argc, char ** argv)
{
KAboutData about("phononmediaplayer", 0, ki18n("Phonon Media Player"),
"0.1", ki18n("Media Player"),
KAboutData::License_GPL);
about.addAuthor(ki18n("Matthias Kretz"), KLocalizedString(), "[email protected]");
KCmdLineArgs::init(argc, argv, &about);
KCmdLineOptions options;
options.add("+[url]", ki18n("File to play"));
KCmdLineArgs::addCmdLineOptions( options );
KApplication app;
MediaPlayer foo;
foo.setWindowIcon(KIcon("phonon"));
foo.show();
KCmdLineArgs *args = KCmdLineArgs::parsedArgs();
if (args->count() == 1) {
KUrl url = args->url(0);
if (url.isValid()) {
foo.setUrl(url);
}
}
args->clear();
return app.exec();
}
#include "mediaplayer.moc"
#include "mediacontrols.cpp"
#include "moc_mediacontrols.cpp"
<|endoftext|> |
<commit_before>/*
* Copyright 2015 Milian Wolff <[email protected]>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU Library 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 "parser.h"
#include <ThreadWeaver/ThreadWeaver>
#include <KFormat>
#include <KLocalizedString>
#include <QTextStream>
#include <QDebug>
#include "../accumulatedtracedata.h"
#include <vector>
using namespace std;
namespace {
struct ParserData final : public AccumulatedTraceData
{
ParserData()
{
chartData.push_back({0, 0, 0, 0});
}
void handleTimeStamp(uint64_t /*newStamp*/, uint64_t oldStamp)
{
maxLeakedSinceLastTimeStamp = max(maxLeakedSinceLastTimeStamp, leaked);
chartData.push_back({oldStamp, maxLeakedSinceLastTimeStamp, totalAllocations, totalAllocated});
maxLeakedSinceLastTimeStamp = 0;
}
void handleAllocation()
{
maxLeakedSinceLastTimeStamp = max(maxLeakedSinceLastTimeStamp, leaked);
}
void handleDebuggee(const char* command)
{
debuggee = command;
}
string debuggee;
ChartData chartData;
uint64_t maxLeakedSinceLastTimeStamp = 0;
};
QString generateSummary(const ParserData& data)
{
QString ret;
KFormat format;
QTextStream stream(&ret);
const double totalTimeS = 0.001 * data.totalTime;
stream << "<qt>"
<< i18n("<strong>debuggee</strong>: <code>%1</code>", QString::fromStdString(data.debuggee)) << "<br/>"
// xgettext:no-c-format
<< i18n("<strong>total runtime</strong>: %1s", totalTimeS) << "<br/>"
<< i18n("<strong>bytes allocated in total</strong> (ignoring deallocations): %1 (%2/s)",
format.formatByteSize(data.totalAllocated, 2), format.formatByteSize(data.totalAllocated / totalTimeS)) << "<br/>"
<< i18n("<strong>calls to allocation functions</strong>: %1 (%2/s)",
data.totalAllocations, quint64(data.totalAllocations / totalTimeS)) << "<br/>"
<< i18n("<strong>peak heap memory consumption</strong>: %1", format.formatByteSize(data.peak)) << "<br/>"
<< i18n("<strong>total memory leaked</strong>: %1", format.formatByteSize(data.leaked)) << "<br/>";
stream << "</qt>";
return ret;
}
struct StringCache
{
StringCache(const AccumulatedTraceData& data)
{
m_strings.resize(data.strings.size());
transform(data.strings.begin(), data.strings.end(),
m_strings.begin(), [] (const string& str) { return QString::fromStdString(str); });
}
QString func(const InstructionPointer& ip) const
{
if (ip.functionIndex) {
// TODO: support removal of template arguments
return stringify(ip.functionIndex);
} else {
return static_cast<QString>(QLatin1String("0x") + QString::number(ip.instructionPointer, 16));
}
}
QString file(const InstructionPointer& ip) const
{
if (ip.fileIndex) {
return stringify(ip.fileIndex);
} else {
return {};
}
}
QString module(const InstructionPointer& ip) const
{
return stringify(ip.moduleIndex);
}
QString stringify(const StringIndex index) const
{
if (!index || index.index > m_strings.size()) {
return {};
} else {
return m_strings.at(index.index - 1);
}
}
LocationData location(const InstructionPointer& ip) const
{
return {func(ip), file(ip), module(ip), ip.line};
}
vector<QString> m_strings;
};
void setParents(QVector<RowData>& children, const RowData* parent)
{
for (auto& row: children) {
row.parent = parent;
setParents(row.children, &row);
}
}
QVector<RowData> mergeAllocations(const AccumulatedTraceData& data)
{
QVector<RowData> topRows;
StringCache strings(data);
// merge allocations, leave parent pointers invalid (their location may change)
for (const auto& allocation : data.allocations) {
auto traceIndex = allocation.traceIndex;
auto rows = &topRows;
while (traceIndex) {
const auto& trace = data.findTrace(traceIndex);
const auto& ip = data.findIp(trace.ipIndex);
// TODO: only store the IpIndex and use that
auto location = strings.location(ip);
auto it = lower_bound(rows->begin(), rows->end(), location);
if (it != rows->end() && it->location == location) {
it->allocated += allocation.allocated;
it->allocations += allocation.allocations;
it->leaked += allocation.leaked;
it->peak = max(it->peak, static_cast<quint64>(allocation.peak));
} else {
it = rows->insert(it, {allocation.allocations, allocation.peak, allocation.leaked, allocation.allocated,
location, nullptr, {}});
}
traceIndex = trace.parentIndex;
rows = &it->children;
}
}
// now set the parents, the data is constant from here on
setParents(topRows, nullptr);
return topRows;
}
}
Parser::Parser(QObject* parent)
: QObject(parent)
{}
Parser::~Parser() = default;
static void buildFrameGraph(const QVector<RowData>& mergedAllocations, FlameGraphData::Stack* topStack)
{
foreach (const auto& row, mergedAllocations) {
if (row.children.isEmpty()) {
// leaf node found, bubble up the parent chain to build a top-down tree
auto node = &row;
auto stack = topStack;
while (node) {
auto& data = (*stack)[node->location.function];
// always use the leaf node's cost and propagate that one up the chain
// otherwise we'd count the cost of some nodes multiple times
data.cost += row.allocations;
stack = &data.children;
node = node->parent;
}
} else {
// recurse to find a leaf
buildFrameGraph(row.children, topStack);
}
}
}
void Parser::parse(const QString& path)
{
using namespace ThreadWeaver;
stream() << make_job([=]() {
ParserData data;
data.read(path.toStdString());
emit summaryAvailable(generateSummary(data));
const auto mergedAllocations = mergeAllocations(data);
emit bottomUpDataAvailable(mergedAllocations);
emit chartDataAvailable(data.chartData);
FlameGraphData::Stack stack;
buildFrameGraph(mergedAllocations, &stack);
emit flameGraphDataAvailable({stack});
emit finished();
});
}
<commit_msg>Exclude stop indices from GUI backtraces.<commit_after>/*
* Copyright 2015 Milian Wolff <[email protected]>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU Library 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 "parser.h"
#include <ThreadWeaver/ThreadWeaver>
#include <KFormat>
#include <KLocalizedString>
#include <QTextStream>
#include <QDebug>
#include "../accumulatedtracedata.h"
#include <vector>
using namespace std;
namespace {
struct ParserData final : public AccumulatedTraceData
{
ParserData()
{
chartData.push_back({0, 0, 0, 0});
}
void handleTimeStamp(uint64_t /*newStamp*/, uint64_t oldStamp)
{
maxLeakedSinceLastTimeStamp = max(maxLeakedSinceLastTimeStamp, leaked);
chartData.push_back({oldStamp, maxLeakedSinceLastTimeStamp, totalAllocations, totalAllocated});
maxLeakedSinceLastTimeStamp = 0;
}
void handleAllocation()
{
maxLeakedSinceLastTimeStamp = max(maxLeakedSinceLastTimeStamp, leaked);
}
void handleDebuggee(const char* command)
{
debuggee = command;
}
string debuggee;
ChartData chartData;
uint64_t maxLeakedSinceLastTimeStamp = 0;
};
QString generateSummary(const ParserData& data)
{
QString ret;
KFormat format;
QTextStream stream(&ret);
const double totalTimeS = 0.001 * data.totalTime;
stream << "<qt>"
<< i18n("<strong>debuggee</strong>: <code>%1</code>", QString::fromStdString(data.debuggee)) << "<br/>"
// xgettext:no-c-format
<< i18n("<strong>total runtime</strong>: %1s", totalTimeS) << "<br/>"
<< i18n("<strong>bytes allocated in total</strong> (ignoring deallocations): %1 (%2/s)",
format.formatByteSize(data.totalAllocated, 2), format.formatByteSize(data.totalAllocated / totalTimeS)) << "<br/>"
<< i18n("<strong>calls to allocation functions</strong>: %1 (%2/s)",
data.totalAllocations, quint64(data.totalAllocations / totalTimeS)) << "<br/>"
<< i18n("<strong>peak heap memory consumption</strong>: %1", format.formatByteSize(data.peak)) << "<br/>"
<< i18n("<strong>total memory leaked</strong>: %1", format.formatByteSize(data.leaked)) << "<br/>";
stream << "</qt>";
return ret;
}
struct StringCache
{
StringCache(const AccumulatedTraceData& data)
{
m_strings.resize(data.strings.size());
transform(data.strings.begin(), data.strings.end(),
m_strings.begin(), [] (const string& str) { return QString::fromStdString(str); });
}
QString func(const InstructionPointer& ip) const
{
if (ip.functionIndex) {
// TODO: support removal of template arguments
return stringify(ip.functionIndex);
} else {
return static_cast<QString>(QLatin1String("0x") + QString::number(ip.instructionPointer, 16));
}
}
QString file(const InstructionPointer& ip) const
{
if (ip.fileIndex) {
return stringify(ip.fileIndex);
} else {
return {};
}
}
QString module(const InstructionPointer& ip) const
{
return stringify(ip.moduleIndex);
}
QString stringify(const StringIndex index) const
{
if (!index || index.index > m_strings.size()) {
return {};
} else {
return m_strings.at(index.index - 1);
}
}
LocationData location(const InstructionPointer& ip) const
{
return {func(ip), file(ip), module(ip), ip.line};
}
vector<QString> m_strings;
};
void setParents(QVector<RowData>& children, const RowData* parent)
{
for (auto& row: children) {
row.parent = parent;
setParents(row.children, &row);
}
}
QVector<RowData> mergeAllocations(const AccumulatedTraceData& data)
{
QVector<RowData> topRows;
StringCache strings(data);
// merge allocations, leave parent pointers invalid (their location may change)
for (const auto& allocation : data.allocations) {
auto traceIndex = allocation.traceIndex;
auto rows = &topRows;
while (traceIndex) {
const auto& trace = data.findTrace(traceIndex);
const auto& ip = data.findIp(trace.ipIndex);
// TODO: only store the IpIndex and use that
auto location = strings.location(ip);
auto it = lower_bound(rows->begin(), rows->end(), location);
if (it != rows->end() && it->location == location) {
it->allocated += allocation.allocated;
it->allocations += allocation.allocations;
it->leaked += allocation.leaked;
it->peak = max(it->peak, static_cast<quint64>(allocation.peak));
} else {
it = rows->insert(it, {allocation.allocations, allocation.peak, allocation.leaked, allocation.allocated,
location, nullptr, {}});
}
if (data.isStopIndex(ip.functionIndex)) {
break;
}
traceIndex = trace.parentIndex;
rows = &it->children;
}
}
// now set the parents, the data is constant from here on
setParents(topRows, nullptr);
return topRows;
}
}
Parser::Parser(QObject* parent)
: QObject(parent)
{}
Parser::~Parser() = default;
static void buildFrameGraph(const QVector<RowData>& mergedAllocations, FlameGraphData::Stack* topStack)
{
foreach (const auto& row, mergedAllocations) {
if (row.children.isEmpty()) {
// leaf node found, bubble up the parent chain to build a top-down tree
auto node = &row;
auto stack = topStack;
while (node) {
auto& data = (*stack)[node->location.function];
// always use the leaf node's cost and propagate that one up the chain
// otherwise we'd count the cost of some nodes multiple times
data.cost += row.allocations;
stack = &data.children;
node = node->parent;
}
} else {
// recurse to find a leaf
buildFrameGraph(row.children, topStack);
}
}
}
void Parser::parse(const QString& path)
{
using namespace ThreadWeaver;
stream() << make_job([=]() {
ParserData data;
data.read(path.toStdString());
emit summaryAvailable(generateSummary(data));
const auto mergedAllocations = mergeAllocations(data);
emit bottomUpDataAvailable(mergedAllocations);
emit chartDataAvailable(data.chartData);
FlameGraphData::Stack stack;
buildFrameGraph(mergedAllocations, &stack);
emit flameGraphDataAvailable({stack});
emit finished();
});
}
<|endoftext|> |
<commit_before>/*
Copyright (c) 2015 Microsoft Corporation. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Author: Leonardo de Moura
*/
#include "kernel/declaration.h"
#include "kernel/type_checker.h"
#include "kernel/instantiate.h"
#include "library/trace.h"
#include "library/aux_recursors.h"
#include "library/user_recursors.h"
#include "library/util.h"
#include "compiler/util.h"
#include "compiler/compiler_step_visitor.h"
#include "compiler/comp_irrelevant.h"
#include "compiler/eta_expansion.h"
#include "compiler/simp_pr1_rec.h"
#include "compiler/inliner.h"
#include "compiler/elim_recursors.h"
#include "compiler/erase_irrelevant.h"
namespace lean {
class expand_aux_recursors_fn : public compiler_step_visitor {
enum class recursor_kind { Aux, CasesOn, NotRecursor };
/* We only expand auxiliary recursors and user-defined recursors.
However, we don't unfold recursors of the form C.cases_on. */
recursor_kind get_recursor_app_kind(expr const & e) const {
if (!is_app(e))
return recursor_kind::NotRecursor;
expr const & fn = get_app_fn(e);
if (!is_constant(fn))
return recursor_kind::NotRecursor;
name const & n = const_name(fn);
if (is_cases_on_recursor(env(), n)) {
return recursor_kind::CasesOn;
} else if (::lean::is_aux_recursor(env(), n) || is_user_defined_recursor(env(), n)) {
return recursor_kind::Aux;
} else {
return recursor_kind::NotRecursor;
}
}
bool is_aux_recursor(expr const & e) const {
return get_recursor_app_kind(e) == recursor_kind::Aux;
}
expr visit_cases_on(expr const & e) {
/* try to reduce cases_on */
if (auto r1 = ctx().reduce_aux_recursor(e)) {
if (auto r2 = ctx().norm_ext(*r1)) {
return compiler_step_visitor::visit(*r2);
}
}
return compiler_step_visitor::visit_app(e);
}
virtual expr visit_app(expr const & e) override {
switch (get_recursor_app_kind(e)) {
case recursor_kind::NotRecursor: {
expr new_e = ctx().whnf_pred(e, [&](expr const &) { return false; });
if (is_eqp(new_e, e))
return compiler_step_visitor::visit_app(new_e);
else
return compiler_step_visitor::visit(new_e);
}
case recursor_kind::CasesOn:
return visit_cases_on(e);
case recursor_kind::Aux:
return compiler_step_visitor::visit(ctx().whnf_pred(e, [&](expr const & e) { return is_aux_recursor(e); }));
}
lean_unreachable();
}
public:
expand_aux_recursors_fn(environment const & env):compiler_step_visitor(env) {}
};
static expr expand_aux_recursors(environment const & env, expr const & e) {
return expand_aux_recursors_fn(env)(e);
}
static name * g_tmp_prefix = nullptr;
class preprocess_rec_fn {
environment m_env;
bool check(declaration const & d, expr const & v) {
bool memoize = true;
bool trusted_only = false;
type_checker tc(m_env, memoize, trusted_only);
expr t = tc.check(v, d.get_univ_params());
if (!tc.is_def_eq(d.get_type(), t))
throw exception("preprocess_rec failed");
return true;
}
void display(buffer<pair<name, expr>> const & procs) {
for (auto const & p : procs) {
tout() << ">> " << p.first << "\n" << p.second << "\n";
}
}
void erase_irrelevant(buffer<pair<name, expr>> & procs) {
for (pair<name, expr> & p : procs) {
p.second = ::lean::erase_irrelevant(m_env, p.second);
}
}
public:
preprocess_rec_fn(environment const & env):
m_env(env) {}
void operator()(declaration const & d, buffer<pair<name, expr>> & procs) {
expr v = d.get_value();
v = expand_aux_recursors(m_env, v);
v = mark_comp_irrelevant_subterms(m_env, v);
v = eta_expand(m_env, v);
v = simp_pr1_rec(m_env, v);
v = inline_simple_definitions(m_env, v);
v = mark_comp_irrelevant_subterms(m_env, v);
buffer<name> aux_decls;
v = elim_recursors(m_env, v, aux_decls);
for (name const & n : aux_decls) {
declaration d = m_env.get(n);
procs.emplace_back(d.get_name(), d.get_value());
}
procs.emplace_back(d.get_name(), v);
erase_irrelevant(procs);
display(procs);
// TODO(Leo)
check(d, procs.back().second);
}
};
void preprocess_rec(environment const & env, declaration const & d, buffer<pair<name, expr>> & result) {
return preprocess_rec_fn(env)(d, result);
}
void initialize_preprocess_rec() {
g_tmp_prefix = new name(name::mk_internal_unique_name());
}
void finalize_preprocess_rec() {
delete g_tmp_prefix;
}
}
<commit_msg>fix(compiler/preprocess_rec): do not type check after erase_irrelevant<commit_after>/*
Copyright (c) 2015 Microsoft Corporation. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Author: Leonardo de Moura
*/
#include "kernel/declaration.h"
#include "kernel/type_checker.h"
#include "kernel/instantiate.h"
#include "library/trace.h"
#include "library/aux_recursors.h"
#include "library/user_recursors.h"
#include "library/util.h"
#include "compiler/util.h"
#include "compiler/compiler_step_visitor.h"
#include "compiler/comp_irrelevant.h"
#include "compiler/eta_expansion.h"
#include "compiler/simp_pr1_rec.h"
#include "compiler/inliner.h"
#include "compiler/elim_recursors.h"
#include "compiler/erase_irrelevant.h"
namespace lean {
class expand_aux_recursors_fn : public compiler_step_visitor {
enum class recursor_kind { Aux, CasesOn, NotRecursor };
/* We only expand auxiliary recursors and user-defined recursors.
However, we don't unfold recursors of the form C.cases_on. */
recursor_kind get_recursor_app_kind(expr const & e) const {
if (!is_app(e))
return recursor_kind::NotRecursor;
expr const & fn = get_app_fn(e);
if (!is_constant(fn))
return recursor_kind::NotRecursor;
name const & n = const_name(fn);
if (is_cases_on_recursor(env(), n)) {
return recursor_kind::CasesOn;
} else if (::lean::is_aux_recursor(env(), n) || is_user_defined_recursor(env(), n)) {
return recursor_kind::Aux;
} else {
return recursor_kind::NotRecursor;
}
}
bool is_aux_recursor(expr const & e) const {
return get_recursor_app_kind(e) == recursor_kind::Aux;
}
expr visit_cases_on(expr const & e) {
/* try to reduce cases_on */
if (auto r1 = ctx().reduce_aux_recursor(e)) {
if (auto r2 = ctx().norm_ext(*r1)) {
return compiler_step_visitor::visit(*r2);
}
}
return compiler_step_visitor::visit_app(e);
}
virtual expr visit_app(expr const & e) override {
switch (get_recursor_app_kind(e)) {
case recursor_kind::NotRecursor: {
expr new_e = ctx().whnf_pred(e, [&](expr const &) { return false; });
if (is_eqp(new_e, e))
return compiler_step_visitor::visit_app(new_e);
else
return compiler_step_visitor::visit(new_e);
}
case recursor_kind::CasesOn:
return visit_cases_on(e);
case recursor_kind::Aux:
return compiler_step_visitor::visit(ctx().whnf_pred(e, [&](expr const & e) { return is_aux_recursor(e); }));
}
lean_unreachable();
}
public:
expand_aux_recursors_fn(environment const & env):compiler_step_visitor(env) {}
};
static expr expand_aux_recursors(environment const & env, expr const & e) {
return expand_aux_recursors_fn(env)(e);
}
static name * g_tmp_prefix = nullptr;
class preprocess_rec_fn {
environment m_env;
bool check(declaration const & d, expr const & v) {
bool memoize = true;
bool trusted_only = false;
type_checker tc(m_env, memoize, trusted_only);
expr t = tc.check(v, d.get_univ_params());
if (!tc.is_def_eq(d.get_type(), t))
throw exception("preprocess_rec failed");
return true;
}
void display(buffer<pair<name, expr>> const & procs) {
for (auto const & p : procs) {
tout() << ">> " << p.first << "\n" << p.second << "\n";
}
}
void erase_irrelevant(buffer<pair<name, expr>> & procs) {
for (pair<name, expr> & p : procs) {
p.second = ::lean::erase_irrelevant(m_env, p.second);
}
}
public:
preprocess_rec_fn(environment const & env):
m_env(env) {}
void operator()(declaration const & d, buffer<pair<name, expr>> & procs) {
expr v = d.get_value();
v = expand_aux_recursors(m_env, v);
v = mark_comp_irrelevant_subterms(m_env, v);
v = eta_expand(m_env, v);
v = simp_pr1_rec(m_env, v);
v = inline_simple_definitions(m_env, v);
v = mark_comp_irrelevant_subterms(m_env, v);
buffer<name> aux_decls;
v = elim_recursors(m_env, v, aux_decls);
for (name const & n : aux_decls) {
declaration d = m_env.get(n);
procs.emplace_back(d.get_name(), d.get_value());
}
procs.emplace_back(d.get_name(), v);
check(d, procs.back().second);
erase_irrelevant(procs);
display(procs);
// TODO(Leo)
}
};
void preprocess_rec(environment const & env, declaration const & d, buffer<pair<name, expr>> & result) {
return preprocess_rec_fn(env)(d, result);
}
void initialize_preprocess_rec() {
g_tmp_prefix = new name(name::mk_internal_unique_name());
}
void finalize_preprocess_rec() {
delete g_tmp_prefix;
}
}
<|endoftext|> |
<commit_before>//
// IOSOpenGLContextManager.cpp
// MWorksCore
//
// Created by Christopher Stawarz on 2/14/17.
//
//
#include "IOSOpenGLContextManager.hpp"
#include "OpenGLUtilities.hpp"
//
// The technique for using a CAEAGLLayer-backed UIView for displaying OpenGL ES content is taken from
// Apple's "Real-time Video Processing Using AVPlayerItemVideoOutput" example project:
//
// https://developer.apple.com/library/content/samplecode/AVBasicVideoOutput/Introduction/Intro.html
//
@interface MWKEAGLView : UIView
@property(nonatomic, readonly) EAGLContext *context;
- (instancetype)initWithFrame:(CGRect)frame context:(EAGLContext *)context;
- (mw::OpenGLContextLock)lockContext;
- (BOOL)prepareGL;
- (void)bindDrawable;
- (void)display;
@end
@implementation MWKEAGLView {
mw::OpenGLContextLock::unique_lock::mutex_type mutex;
GLuint framebuffer;
GLuint renderbuffer;
}
+ (Class)layerClass {
return [CAEAGLLayer class];
}
- (instancetype)initWithFrame:(CGRect)frame context:(EAGLContext *)context {
self = [super initWithFrame:frame];
if (self) {
_context = [context retain];
self.layer.opaque = TRUE;
}
return self;
}
- (mw::OpenGLContextLock)lockContext {
return mw::OpenGLContextLock(mw::OpenGLContextLock::unique_lock(mutex));
}
- (BOOL)prepareGL {
glGenFramebuffers(1, &framebuffer);
mw::gl::FramebufferBinding<GL_FRAMEBUFFER> framebufferBinding(framebuffer);
glGenRenderbuffers(1, &renderbuffer);
mw::gl::RenderbufferBinding<GL_RENDERBUFFER> renderbufferBinding(renderbuffer);
[self.context renderbufferStorage:GL_RENDERBUFFER fromDrawable:static_cast<CAEAGLLayer *>(self.layer)];
GLint backingWidth, backingHeight;
glGetRenderbufferParameteriv(GL_RENDERBUFFER, GL_RENDERBUFFER_WIDTH, &backingWidth);
glGetRenderbufferParameteriv(GL_RENDERBUFFER, GL_RENDERBUFFER_HEIGHT, &backingHeight);
glViewport(0, 0, backingWidth, backingHeight);
glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_RENDERBUFFER, renderbuffer);
return (GL_FRAMEBUFFER_COMPLETE == glCheckFramebufferStatus(GL_FRAMEBUFFER));
}
- (void)bindDrawable {
glBindFramebuffer(GL_FRAMEBUFFER, framebuffer);
}
- (void)display {
mw::gl::RenderbufferBinding<GL_RENDERBUFFER> renderbufferBinding(renderbuffer);
[self.context presentRenderbuffer:GL_RENDERBUFFER];
}
- (void)dealloc {
[_context release];
[super dealloc];
}
@end
@interface MWKEAGLViewController : UIViewController
@end
@implementation MWKEAGLViewController
- (BOOL)prefersStatusBarHidden {
return YES;
}
- (BOOL)shouldAutorotate {
return NO;
}
@end
BEGIN_NAMESPACE_MW
IOSOpenGLContextManager::~IOSOpenGLContextManager() {
// Calling releaseContexts here causes the application to crash at exit. Since this class is
// used as a singleton, it doesn't matter, anyway.
//releaseContexts();
}
int IOSOpenGLContextManager::newFullscreenContext(int screen_number, bool render_at_full_resolution) {
@autoreleasepool {
if (screen_number < 0 || screen_number >= getNumDisplays()) {
throw SimpleException(M_DISPLAY_MESSAGE_DOMAIN,
(boost::format("Invalid screen number (%d)") % screen_number).str());
}
EAGLSharegroup *sharegroup = nil;
if (contexts.count > 0) {
sharegroup = static_cast<EAGLContext *>(contexts[0]).sharegroup;
}
EAGLContext *context = [[EAGLContext alloc] initWithAPI:kEAGLRenderingAPIOpenGLES3 sharegroup:sharegroup];
if (!context) {
throw SimpleException(M_DISPLAY_MESSAGE_DOMAIN, "Cannot create OpenGL ES context");
}
auto screen = UIScreen.screens[screen_number];
__block bool success = false;
dispatch_sync(dispatch_get_main_queue(), ^{
if (UIWindow *window = [[UIWindow alloc] initWithFrame:screen.bounds]) {
window.screen = screen;
if (MWKEAGLViewController *viewController = [[MWKEAGLViewController alloc] init]) {
window.rootViewController = viewController;
if (MWKEAGLView *view = [[MWKEAGLView alloc] initWithFrame:window.bounds context:context]) {
viewController.view = view;
view.contentScaleFactor = (render_at_full_resolution ? screen.scale : 1.0);
[EAGLContext setCurrentContext:context];
if ([view prepareGL]) {
[window makeKeyAndVisible];
[contexts addObject:context];
[views addObject:view];
[windows addObject:window];
success = true;
}
[EAGLContext setCurrentContext:nil];
[view release];
}
[viewController release];
}
[window release];
}
});
[context release];
if (!success) {
throw SimpleException(M_DISPLAY_MESSAGE_DOMAIN, "Cannot create fullscreen window");
}
return (contexts.count - 1);
}
}
int IOSOpenGLContextManager::newMirrorContext(bool render_at_full_resolution) {
throw SimpleException(M_DISPLAY_MESSAGE_DOMAIN, "Mirror windows are not supported on this OS");
}
void IOSOpenGLContextManager::releaseContexts() {
@autoreleasepool {
dispatch_sync(dispatch_get_main_queue(), ^{
for (UIWindow *window in windows) {
window.hidden = YES;
}
[windows removeAllObjects];
[views removeAllObjects];
});
[contexts removeAllObjects];
}
}
int IOSOpenGLContextManager::getNumDisplays() const {
// At present, we support only the main display
return 1;
}
OpenGLContextLock IOSOpenGLContextManager::setCurrent(int context_id) {
@autoreleasepool {
if (auto view = static_cast<MWKEAGLView *>(getView(context_id))) {
if ([EAGLContext setCurrentContext:view.context]) {
auto lock = [view lockContext];
[view bindDrawable];
return lock;
}
merror(M_DISPLAY_MESSAGE_DOMAIN, "Cannot set current OpenGL ES context");
}
return OpenGLContextLock();
}
}
void IOSOpenGLContextManager::clearCurrent() {
@autoreleasepool {
glBindFramebuffer(GL_FRAMEBUFFER, 0); // Unbind the view's drawable object
[EAGLContext setCurrentContext:nil];
}
}
void IOSOpenGLContextManager::bindDefaultFramebuffer(int context_id) {
@autoreleasepool {
if (auto view = static_cast<MWKEAGLView *>(getView(context_id))) {
[view bindDrawable];
}
}
}
void IOSOpenGLContextManager::flush(int context_id) {
@autoreleasepool {
if (auto view = static_cast<MWKEAGLView *>(getView(context_id))) {
[view display];
}
}
}
std::vector<float> IOSOpenGLContextManager::getColorConversionLUTData(int context_id, int numGridPoints) {
@autoreleasepool {
std::vector<float> lutData;
if (auto view = getView(context_id)) {
__block UIDisplayGamut displayGamut;
dispatch_sync(dispatch_get_main_queue(), ^{
displayGamut = view.window.screen.traitCollection.displayGamut;
});
switch (displayGamut) {
case UIDisplayGamutSRGB:
// No color conversion required
break;
case UIDisplayGamutP3: {
//
// According to "What's New in Metal, Part 2" (WWDC 2016, Session 605), applications should
// always render in the sRGB colorspace, even when the target device has a P3 display. To use
// colors outside of the sRGB gamut, the app needs to use a floating-point color buffer and
// encode the P3-only colors using component values less than 0 or greater than 1 (as in Apple's
// "extended sRGB" color space). Since StimulusDisplay uses an 8 bit per channel, integer color
// buffer, we're always limited to sRGB.
//
// Testing suggests that this approach is correct. If we draw an image with high color
// saturation and then display it both with and without a Mac-style, LUT-based conversion
// from sRGB to Display P3, the unconverted colors match what we see on a Mac, while the converted
// colors are noticeably duller. This makes sense, because converting, say, 100% red (255, 0, 0)
// in sRGB to the wider gamut of Display P3 results in smaller numerical values (234, 51, 35).
//
// https://developer.apple.com/videos/play/wwdc2016/605/
//
break;
}
default:
throw SimpleException(M_DISPLAY_MESSAGE_DOMAIN, "Unsupported display gamut");
}
}
return lutData;
}
}
boost::shared_ptr<OpenGLContextManager> OpenGLContextManager::createPlatformOpenGLContextManager() {
return boost::make_shared<IOSOpenGLContextManager>();
}
END_NAMESPACE_MW
<commit_msg>On iOS, use UIScreen.nativeScale to get the scale factor for the display<commit_after>//
// IOSOpenGLContextManager.cpp
// MWorksCore
//
// Created by Christopher Stawarz on 2/14/17.
//
//
#include "IOSOpenGLContextManager.hpp"
#include "OpenGLUtilities.hpp"
//
// The technique for using a CAEAGLLayer-backed UIView for displaying OpenGL ES content is taken from
// Apple's "Real-time Video Processing Using AVPlayerItemVideoOutput" example project:
//
// https://developer.apple.com/library/content/samplecode/AVBasicVideoOutput/Introduction/Intro.html
//
@interface MWKEAGLView : UIView
@property(nonatomic, readonly) EAGLContext *context;
- (instancetype)initWithFrame:(CGRect)frame context:(EAGLContext *)context;
- (mw::OpenGLContextLock)lockContext;
- (BOOL)prepareGL;
- (void)bindDrawable;
- (void)display;
@end
@implementation MWKEAGLView {
mw::OpenGLContextLock::unique_lock::mutex_type mutex;
GLuint framebuffer;
GLuint renderbuffer;
}
+ (Class)layerClass {
return [CAEAGLLayer class];
}
- (instancetype)initWithFrame:(CGRect)frame context:(EAGLContext *)context {
self = [super initWithFrame:frame];
if (self) {
_context = [context retain];
self.layer.opaque = TRUE;
}
return self;
}
- (mw::OpenGLContextLock)lockContext {
return mw::OpenGLContextLock(mw::OpenGLContextLock::unique_lock(mutex));
}
- (BOOL)prepareGL {
glGenFramebuffers(1, &framebuffer);
mw::gl::FramebufferBinding<GL_FRAMEBUFFER> framebufferBinding(framebuffer);
glGenRenderbuffers(1, &renderbuffer);
mw::gl::RenderbufferBinding<GL_RENDERBUFFER> renderbufferBinding(renderbuffer);
[self.context renderbufferStorage:GL_RENDERBUFFER fromDrawable:static_cast<CAEAGLLayer *>(self.layer)];
GLint backingWidth, backingHeight;
glGetRenderbufferParameteriv(GL_RENDERBUFFER, GL_RENDERBUFFER_WIDTH, &backingWidth);
glGetRenderbufferParameteriv(GL_RENDERBUFFER, GL_RENDERBUFFER_HEIGHT, &backingHeight);
glViewport(0, 0, backingWidth, backingHeight);
glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_RENDERBUFFER, renderbuffer);
return (GL_FRAMEBUFFER_COMPLETE == glCheckFramebufferStatus(GL_FRAMEBUFFER));
}
- (void)bindDrawable {
glBindFramebuffer(GL_FRAMEBUFFER, framebuffer);
}
- (void)display {
mw::gl::RenderbufferBinding<GL_RENDERBUFFER> renderbufferBinding(renderbuffer);
[self.context presentRenderbuffer:GL_RENDERBUFFER];
}
- (void)dealloc {
[_context release];
[super dealloc];
}
@end
@interface MWKEAGLViewController : UIViewController
@end
@implementation MWKEAGLViewController
- (BOOL)prefersStatusBarHidden {
return YES;
}
- (BOOL)shouldAutorotate {
return NO;
}
@end
BEGIN_NAMESPACE_MW
IOSOpenGLContextManager::~IOSOpenGLContextManager() {
// Calling releaseContexts here causes the application to crash at exit. Since this class is
// used as a singleton, it doesn't matter, anyway.
//releaseContexts();
}
int IOSOpenGLContextManager::newFullscreenContext(int screen_number, bool render_at_full_resolution) {
@autoreleasepool {
if (screen_number < 0 || screen_number >= getNumDisplays()) {
throw SimpleException(M_DISPLAY_MESSAGE_DOMAIN,
(boost::format("Invalid screen number (%d)") % screen_number).str());
}
EAGLSharegroup *sharegroup = nil;
if (contexts.count > 0) {
sharegroup = static_cast<EAGLContext *>(contexts[0]).sharegroup;
}
EAGLContext *context = [[EAGLContext alloc] initWithAPI:kEAGLRenderingAPIOpenGLES3 sharegroup:sharegroup];
if (!context) {
throw SimpleException(M_DISPLAY_MESSAGE_DOMAIN, "Cannot create OpenGL ES context");
}
auto screen = UIScreen.screens[screen_number];
__block bool success = false;
dispatch_sync(dispatch_get_main_queue(), ^{
if (UIWindow *window = [[UIWindow alloc] initWithFrame:screen.bounds]) {
window.screen = screen;
if (MWKEAGLViewController *viewController = [[MWKEAGLViewController alloc] init]) {
window.rootViewController = viewController;
if (MWKEAGLView *view = [[MWKEAGLView alloc] initWithFrame:window.bounds context:context]) {
viewController.view = view;
view.contentScaleFactor = (render_at_full_resolution ? screen.nativeScale : 1.0);
[EAGLContext setCurrentContext:context];
if ([view prepareGL]) {
[window makeKeyAndVisible];
[contexts addObject:context];
[views addObject:view];
[windows addObject:window];
success = true;
}
[EAGLContext setCurrentContext:nil];
[view release];
}
[viewController release];
}
[window release];
}
});
[context release];
if (!success) {
throw SimpleException(M_DISPLAY_MESSAGE_DOMAIN, "Cannot create fullscreen window");
}
return (contexts.count - 1);
}
}
int IOSOpenGLContextManager::newMirrorContext(bool render_at_full_resolution) {
throw SimpleException(M_DISPLAY_MESSAGE_DOMAIN, "Mirror windows are not supported on this OS");
}
void IOSOpenGLContextManager::releaseContexts() {
@autoreleasepool {
dispatch_sync(dispatch_get_main_queue(), ^{
for (UIWindow *window in windows) {
window.hidden = YES;
}
[windows removeAllObjects];
[views removeAllObjects];
});
[contexts removeAllObjects];
}
}
int IOSOpenGLContextManager::getNumDisplays() const {
// At present, we support only the main display
return 1;
}
OpenGLContextLock IOSOpenGLContextManager::setCurrent(int context_id) {
@autoreleasepool {
if (auto view = static_cast<MWKEAGLView *>(getView(context_id))) {
if ([EAGLContext setCurrentContext:view.context]) {
auto lock = [view lockContext];
[view bindDrawable];
return lock;
}
merror(M_DISPLAY_MESSAGE_DOMAIN, "Cannot set current OpenGL ES context");
}
return OpenGLContextLock();
}
}
void IOSOpenGLContextManager::clearCurrent() {
@autoreleasepool {
glBindFramebuffer(GL_FRAMEBUFFER, 0); // Unbind the view's drawable object
[EAGLContext setCurrentContext:nil];
}
}
void IOSOpenGLContextManager::bindDefaultFramebuffer(int context_id) {
@autoreleasepool {
if (auto view = static_cast<MWKEAGLView *>(getView(context_id))) {
[view bindDrawable];
}
}
}
void IOSOpenGLContextManager::flush(int context_id) {
@autoreleasepool {
if (auto view = static_cast<MWKEAGLView *>(getView(context_id))) {
[view display];
}
}
}
std::vector<float> IOSOpenGLContextManager::getColorConversionLUTData(int context_id, int numGridPoints) {
@autoreleasepool {
std::vector<float> lutData;
if (auto view = getView(context_id)) {
__block UIDisplayGamut displayGamut;
dispatch_sync(dispatch_get_main_queue(), ^{
displayGamut = view.window.screen.traitCollection.displayGamut;
});
switch (displayGamut) {
case UIDisplayGamutSRGB:
// No color conversion required
break;
case UIDisplayGamutP3: {
//
// According to "What's New in Metal, Part 2" (WWDC 2016, Session 605), applications should
// always render in the sRGB colorspace, even when the target device has a P3 display. To use
// colors outside of the sRGB gamut, the app needs to use a floating-point color buffer and
// encode the P3-only colors using component values less than 0 or greater than 1 (as in Apple's
// "extended sRGB" color space). Since StimulusDisplay uses an 8 bit per channel, integer color
// buffer, we're always limited to sRGB.
//
// Testing suggests that this approach is correct. If we draw an image with high color
// saturation and then display it both with and without a Mac-style, LUT-based conversion
// from sRGB to Display P3, the unconverted colors match what we see on a Mac, while the converted
// colors are noticeably duller. This makes sense, because converting, say, 100% red (255, 0, 0)
// in sRGB to the wider gamut of Display P3 results in smaller numerical values (234, 51, 35).
//
// https://developer.apple.com/videos/play/wwdc2016/605/
//
break;
}
default:
throw SimpleException(M_DISPLAY_MESSAGE_DOMAIN, "Unsupported display gamut");
}
}
return lutData;
}
}
boost::shared_ptr<OpenGLContextManager> OpenGLContextManager::createPlatformOpenGLContextManager() {
return boost::make_shared<IOSOpenGLContextManager>();
}
END_NAMESPACE_MW
<|endoftext|> |
<commit_before>/* packet_test.cpp -*- C++ -*-
Rémi Attab ([email protected]), 06 Dec 2013
FreeBSD-style copyright and disclaimer apply
Packet sending and timing test.
*/
#include "client.h"
#include "provider.h"
#include "test_utils.h"
#include <vector>
#include <string>
#include <cstdlib>
#include <cassert>
using namespace std;
using namespace slick;
/******************************************************************************/
/* MISC */
/******************************************************************************/
enum { PayloadSize = 32 };
string getStats(size_t value, size_t& oldValue)
{
string diff = fmtValue(value - oldValue);
oldValue = value;
return diff;
}
/******************************************************************************/
/* PROVIDER */
/******************************************************************************/
void runProvider(Port port)
{
size_t recv = 0, dropped = 0;
EndpointProvider provider(port);
provider.onNewConnection = [] (ConnectionHandle conn) {
fprintf(stderr, "\nprv: new %d\n", conn);;
};
provider.onLostConnection = [] (ConnectionHandle conn) {
fprintf(stderr, "\nprv: lost %d\n", conn);;
};
provider.onPayload = [&] (ConnectionHandle conn, Payload&& data) {
recv++;
provider.send(conn, move(data));
};
provider.onDroppedPayload = [&] (ConnectionHandle, Payload&&) {
dropped++;
};
thread pollTh([&] { while (true) provider.poll(); });
size_t oldRecv = 0;
while (true) {
slick::sleep(1000);
string diffRecv = getStats(recv, oldRecv);
fprintf(stderr, "\rrecv: %s", diffRecv.c_str());
}
}
/******************************************************************************/
/* CLIENT */
/******************************************************************************/
void runClient(vector<string> uris)
{
size_t sent = 0, recv = 0, dropped = 0;
EndpointClient client;
client.onNewConnection = [] (ConnectionHandle conn) {
fprintf(stderr, "\ncli: new %d\n", conn);;
};
client.onLostConnection = [] (ConnectionHandle conn) {
fprintf(stderr, "\ncli: lost %d\n", conn);;
};
client.onPayload = [&] (ConnectionHandle, Payload&&) {
recv++;
};
client.onDroppedPayload = [&] (ConnectionHandle, Payload&&) {
dropped++;
};
for (auto& uri : uris) client.connect(uri);
thread pollTh([&] { while (true) client.poll(); });
Payload payload = proto::fromString(string(PayloadSize, 'a'));
auto sendFn = [&] {
while (true) {
client.broadcast(payload); sent++;
}
};
thread sendTh(sendFn);
size_t oldSent = 0, oldRecv = 0;
while (true) {
slick::sleep(1000);
string diffSent = getStats(sent - dropped, oldSent);
string diffRecv = getStats(recv, oldRecv);
fprintf(stderr, "\rsent: %s, recv: %s, ",
diffSent.c_str(), diffRecv.c_str());
}
}
/******************************************************************************/
/* MAIN */
/******************************************************************************/
int main(int argc, char** argv)
{
assert(argc >= 2);
if (argv[1][0] == 'p') {
Port port = 20000;
if (argc >= 3) port = atoi(argv[2]);
runProvider(port);
}
else if (argv[1][0] == 'c') {
assert(argc >= 3);
vector<string> uris;
for (size_t i = 2; i < size_t(argc); ++i)
uris.emplace_back(argv[i]);
runClient(uris);
}
else assert(false);
return 0;
}
<commit_msg>Time output for the packet test.<commit_after>/* packet_test.cpp -*- C++ -*-
Rémi Attab ([email protected]), 06 Dec 2013
FreeBSD-style copyright and disclaimer apply
Packet sending and timing test.
*/
#include "client.h"
#include "provider.h"
#include "test_utils.h"
#include <vector>
#include <string>
#include <cstdlib>
#include <cassert>
using namespace std;
using namespace slick;
/******************************************************************************/
/* MISC */
/******************************************************************************/
enum {
PayloadSize = 32,
RefreshRate = 200,
};
string getStats(size_t value, size_t& oldValue)
{
size_t diff = value - oldValue;
diff *= 1000 / RefreshRate;
oldValue = value;
return fmtValue(diff);
}
/******************************************************************************/
/* PROVIDER */
/******************************************************************************/
void runProvider(Port port)
{
size_t recv = 0, dropped = 0;
EndpointProvider provider(port);
provider.onNewConnection = [] (ConnectionHandle conn) {
fprintf(stderr, "\nprv: new %d\n", conn);;
};
provider.onLostConnection = [] (ConnectionHandle conn) {
fprintf(stderr, "\nprv: lost %d\n", conn);;
};
provider.onPayload = [&] (ConnectionHandle conn, Payload&& data) {
recv++;
provider.send(conn, move(data));
};
provider.onDroppedPayload = [&] (ConnectionHandle, Payload&&) {
dropped++;
};
thread pollTh([&] { while (true) provider.poll(); });
double start = wall();
size_t oldRecv = 0;
while (true) {
slick::sleep(RefreshRate);
string diffRecv = getStats(recv, oldRecv);
string elapsed = fmtElapsed(wall() - start);
fprintf(stderr, "\r%s> recv: %s ", elapsed.c_str(), diffRecv.c_str());
}
}
/******************************************************************************/
/* CLIENT */
/******************************************************************************/
void runClient(vector<string> uris)
{
size_t sent = 0, recv = 0, dropped = 0;
EndpointClient client;
client.onNewConnection = [] (ConnectionHandle conn) {
fprintf(stderr, "\ncli: new %d\n", conn);;
};
client.onLostConnection = [] (ConnectionHandle conn) {
fprintf(stderr, "\ncli: lost %d\n", conn);;
};
client.onPayload = [&] (ConnectionHandle, Payload&&) {
recv++;
};
client.onDroppedPayload = [&] (ConnectionHandle, Payload&&) {
dropped++;
};
for (auto& uri : uris) client.connect(uri);
thread pollTh([&] { while (true) client.poll(); });
Payload payload = proto::fromString(string(PayloadSize, 'a'));
auto sendFn = [&] {
while (true) {
client.broadcast(payload);
sent++;
}
};
thread sendTh(sendFn);
double start = wall();
size_t oldSent = 0, oldRecv = 0;
while (true) {
slick::sleep(200);
string diffSent = getStats(sent - dropped, oldSent);
string diffRecv = getStats(recv, oldRecv);
string elapsed = fmtElapsed(wall() - start);
fprintf(stderr, "\r%s> sent: %s, recv: %s ",
elapsed.c_str(), diffSent.c_str(), diffRecv.c_str());
}
}
/******************************************************************************/
/* MAIN */
/******************************************************************************/
int main(int argc, char** argv)
{
assert(argc >= 2);
if (argv[1][0] == 'p') {
Port port = 20000;
if (argc >= 3) port = atoi(argv[2]);
runProvider(port);
}
else if (argv[1][0] == 'c') {
assert(argc >= 3);
vector<string> uris;
for (size_t i = 2; i < size_t(argc); ++i)
uris.emplace_back(argv[i]);
runClient(uris);
}
else assert(false);
return 0;
}
<|endoftext|> |
<commit_before>/**
* @file
*/
#pragma once
#include "numbirch/utility.hpp"
#include "numbirch/eigen/eigen.hpp"
#include "numbirch/numeric.hpp"
namespace numbirch {
template<class T, class>
Array<T,1> operator*(const Array<T,2>& A, const Array<T,1>& x) {
assert(columns(A) == length(x));
Array<T,1> y(make_shape(rows(A)));
auto A1 = make_eigen(A);
auto x1 = make_eigen(x);
auto y1 = make_eigen(y);
y1.noalias() = A1*x1;
return y;
}
template<class T, class>
Array<T,2> operator*(const Array<T,2>& A, const Array<T,2>& B) {
assert(columns(A) == rows(B));
Array<T,2> C(make_shape(rows(A), columns(B)));
auto A1 = make_eigen(A);
auto B1 = make_eigen(B);
auto C1 = make_eigen(C);
C1.noalias() = A1*B1;
return C;
}
template<class T, class>
Array<T,2> chol(const Array<T,2>& S) {
assert(rows(S) == columns(S));
Array<T,2> L(shape(S));
auto S1 = make_eigen(S);
auto L1 = make_eigen(L);
auto llt = S1.llt();
if (llt.info() == Eigen::Success) {
L1 = llt.matrixL();
} else {
L.fill(T(0.0/0.0));
}
return L;
}
template<class T, class>
Array<T,2> cholinv(const Array<T,2>& L) {
assert(rows(L) == columns(L));
Array<T,2> B(shape(L));
auto L1 = make_eigen(L).template triangularView<Eigen::Lower>();
auto U1 = make_eigen(L).transpose().template triangularView<Eigen::Upper>();
auto B1 = make_eigen(B);
auto I1 = B1.Identity(rows(B), columns(B));
B1.noalias() = U1.solve(L1.solve(I1));
return B;
}
template<class T, class>
Array<T,1> cholsolve(const Array<T,2>& L, const Array<T,1>& y) {
assert(rows(L) == columns(L));
assert(columns(L) == length(y));
Array<T,1> x(shape(y));
auto L1 = make_eigen(L).template triangularView<Eigen::Lower>();
auto U1 = make_eigen(L).transpose().template triangularView<Eigen::Upper>();
auto x1 = make_eigen(x);
auto y1 = make_eigen(y);
x1.noalias() = U1.solve(L1.solve(y1));
return x;
}
template<class T, class>
Array<T,2> cholsolve(const Array<T,2>& L, const Array<T,2>& C) {
assert(rows(L) == columns(L));
assert(columns(L) == rows(C));
Array<T,2> B(shape(C));
auto L1 = make_eigen(L).template triangularView<Eigen::Lower>();
auto U1 = make_eigen(L).transpose().template triangularView<Eigen::Upper>();
auto B1 = make_eigen(B);
auto C1 = make_eigen(C);
B1.noalias() = U1.solve(L1.solve(C1));
return B;
}
template<class T, class>
Array<T,0> dot(const Array<T,1>& x, const Array<T,1>& y) {
assert(length(x) == length(y));
Array<T,0> z;
auto x1 = make_eigen(x);
auto y1 = make_eigen(y);
z = x1.dot(y1);
return z;
}
template<class T, class>
Array<T,0> frobenius(const Array<T,2>& x, const Array<T,2>& y) {
Array<T,0> z;
auto x1 = make_eigen(x);
auto y1 = make_eigen(y);
z = (x1.array()*y1.array()).sum();
return z;
}
template<class T, class>
Array<T,1> inner(const Array<T,2>& A, const Array<T,1>& x) {
assert(rows(A) == length(x));
Array<T,1> y(make_shape(columns(A)));
auto A1 = make_eigen(A);
auto x1 = make_eigen(x);
auto y1 = make_eigen(y);
y1.noalias() = A1.transpose()*x1;
return y;
}
template<class T, class>
Array<T,2> inner(const Array<T,2>& A, const Array<T,2>& B) {
assert(rows(A) == rows(B));
Array<T,2> C(make_shape(columns(A), columns(B)));
auto A1 = make_eigen(A);
auto B1 = make_eigen(B);
auto C1 = make_eigen(C);
C1.noalias() = A1.transpose()*B1;
return C;
}
template<class T, class>
Array<T,2> inv(const Array<T,2>& A) {
assert(rows(A) == columns(A));
Array<T,2> B(shape(A));
auto A1 = make_eigen(A);
auto B1 = make_eigen(B);
B1.noalias() = A1.inverse();
return B;
}
template<class T, class>
Array<T,0> lcholdet(const Array<T,2>& L) {
auto L1 = make_eigen(L);
/* we have $S = LL^\top$; the determinant of $S$ is the square of the
* determinant of $L$, the determinant of $L$ is the product of the
* elements along the diagonal, as it is a triangular matrix; adjust for
* log-determinant */
return T(2.0)*L1.diagonal().array().log().sum();
}
template<class T, class>
Array<T,0> ldet(const Array<T,2>& A) {
auto A1 = make_eigen(A);
return A1.householderQr().logAbsDeterminant();
}
template<class T, class>
Array<T,2> outer(const Array<T,1>& x, const Array<T,1>& y) {
Array<T,2> A(make_shape(length(x), length(y)));
auto x1 = make_eigen(x);
auto y1 = make_eigen(y);
auto A1 = make_eigen(A);
A1.noalias() = x1*y1.transpose();
return A;
}
template<class T, class>
Array<T,2> outer(const Array<T,2>& A, const Array<T,2>& B) {
assert(columns(A) == columns(B));
Array<T,2> C(make_shape(rows(A), rows(B)));
auto A1 = make_eigen(A);
auto B1 = make_eigen(B);
auto C1 = make_eigen(C);
C1.noalias() = A1*B1.transpose();
return C;
}
template<class T, class>
Array<T,2> phi(const Array<T,2>& A) {
Array<T,2> L(make_shape(rows(A), columns(A)));
auto A1 = make_eigen(A).template triangularView<Eigen::Lower>();
auto L1 = make_eigen(L);
L1 = A1;
L1.diagonal() *= 0.5;
return L;
}
template<class T, class>
Array<T,2> transpose(const Array<T,2>& A) {
Array<T,2> B(make_shape(columns(A), rows(A)));
auto A1 = make_eigen(A);
auto B1 = make_eigen(B);
B1.noalias() = A1.transpose();
return B;
}
template<class T, class>
Array<T,2> tri(const Array<T,2>& A) {
Array<T,2> L(make_shape(rows(A), columns(A)));
auto A1 = make_eigen(A).template triangularView<Eigen::Lower>();
auto L1 = make_eigen(L);
L1 = A1;
return L;
}
template<class T, class>
Array<T,1> triinner(const Array<T,2>& L, const Array<T,1>& x) {
assert(rows(L) == length(x));
Array<T,1> y(make_shape(columns(L)));
auto U1 = make_eigen(L).transpose().template triangularView<Eigen::Upper>();
auto x1 = make_eigen(x);
auto y1 = make_eigen(y);
y1.noalias() = U1*x1;
return y;
}
template<class T, class>
Array<T,2> triinner(const Array<T,2>& L, const Array<T,2>& B) {
assert(rows(L) == rows(B));
Array<T,2> C(make_shape(columns(L), columns(B)));
auto U1 = make_eigen(L).transpose().template triangularView<Eigen::Upper>();
auto B1 = make_eigen(B);
auto C1 = make_eigen(C);
C1.noalias() = U1*B1;
return C;
}
template<class T, class>
Array<T,2> triinv(const Array<T,2>& L) {
assert(rows(L) == columns(L));
Array<T,2> B(shape(L));
auto L1 = make_eigen(L).template triangularView<Eigen::Lower>();
auto B1 = make_eigen(B);
B1.noalias() = L1.solve(B1.Identity(rows(B), columns(B)));
return B;
}
template<class T, class>
Array<T,1> trimul(const Array<T,2>& L, const Array<T,1>& x) {
assert(columns(L) == length(x));
Array<T,1> y(make_shape(rows(L)));
auto L1 = make_eigen(L).template triangularView<Eigen::Lower>();
auto x1 = make_eigen(x);
auto y1 = make_eigen(y);
y1.noalias() = L1*x1;
return y;
}
template<class T, class>
Array<T,2> trimul(const Array<T,2>& L, const Array<T,2>& B) {
assert(columns(L) == rows(B));
Array<T,2> C(make_shape(rows(L), columns(B)));
auto L1 = make_eigen(L).template triangularView<Eigen::Lower>();
auto B1 = make_eigen(B);
auto C1 = make_eigen(C);
C1.noalias() = L1*B1;
return C;
}
template<class T, class>
Array<T,2> triouter(const Array<T,2>& A, const Array<T,2>& L) {
assert(columns(A) == columns(L));
Array<T,2> C(make_shape(rows(A), rows(L)));
auto A1 = make_eigen(A);
auto U1 = make_eigen(L).transpose().template triangularView<Eigen::Upper>();
auto C1 = make_eigen(C);
C1.noalias() = A1*U1;
return C;
}
template<class T, class>
Array<T,1> trisolve(const Array<T,2>& L, const Array<T,1>& y) {
assert(rows(L) == columns(L));
assert(columns(L) == length(y));
Array<T,1> x(shape(y));
auto L1 = make_eigen(L).template triangularView<Eigen::Lower>();
auto x1 = make_eigen(x);
auto y1 = make_eigen(y);
x1.noalias() = L1.solve(y1);
return x;
}
template<class T, class>
Array<T,2> trisolve(const Array<T,2>& L, const Array<T,2>& C) {
assert(rows(L) == columns(L));
assert(columns(L) == rows(C));
Array<T,2> B(shape(C));
auto L1 = make_eigen(L).template triangularView<Eigen::Lower>();
auto B1 = make_eigen(B);
auto C1 = make_eigen(C);
B1.noalias() = L1.solve(C1);
return B;
}
}
<commit_msg>Replaced call to fill (now private) with scalar assign.<commit_after>/**
* @file
*/
#pragma once
#include "numbirch/utility.hpp"
#include "numbirch/eigen/eigen.hpp"
#include "numbirch/numeric.hpp"
namespace numbirch {
template<class T, class>
Array<T,1> operator*(const Array<T,2>& A, const Array<T,1>& x) {
assert(columns(A) == length(x));
Array<T,1> y(make_shape(rows(A)));
auto A1 = make_eigen(A);
auto x1 = make_eigen(x);
auto y1 = make_eigen(y);
y1.noalias() = A1*x1;
return y;
}
template<class T, class>
Array<T,2> operator*(const Array<T,2>& A, const Array<T,2>& B) {
assert(columns(A) == rows(B));
Array<T,2> C(make_shape(rows(A), columns(B)));
auto A1 = make_eigen(A);
auto B1 = make_eigen(B);
auto C1 = make_eigen(C);
C1.noalias() = A1*B1;
return C;
}
template<class T, class>
Array<T,2> chol(const Array<T,2>& S) {
assert(rows(S) == columns(S));
Array<T,2> L(shape(S));
auto S1 = make_eigen(S);
auto L1 = make_eigen(L);
auto llt = S1.llt();
if (llt.info() == Eigen::Success) {
L1 = llt.matrixL();
} else {
L = T(0.0/0.0);
}
return L;
}
template<class T, class>
Array<T,2> cholinv(const Array<T,2>& L) {
assert(rows(L) == columns(L));
Array<T,2> B(shape(L));
auto L1 = make_eigen(L).template triangularView<Eigen::Lower>();
auto U1 = make_eigen(L).transpose().template triangularView<Eigen::Upper>();
auto B1 = make_eigen(B);
auto I1 = B1.Identity(rows(B), columns(B));
B1.noalias() = U1.solve(L1.solve(I1));
return B;
}
template<class T, class>
Array<T,1> cholsolve(const Array<T,2>& L, const Array<T,1>& y) {
assert(rows(L) == columns(L));
assert(columns(L) == length(y));
Array<T,1> x(shape(y));
auto L1 = make_eigen(L).template triangularView<Eigen::Lower>();
auto U1 = make_eigen(L).transpose().template triangularView<Eigen::Upper>();
auto x1 = make_eigen(x);
auto y1 = make_eigen(y);
x1.noalias() = U1.solve(L1.solve(y1));
return x;
}
template<class T, class>
Array<T,2> cholsolve(const Array<T,2>& L, const Array<T,2>& C) {
assert(rows(L) == columns(L));
assert(columns(L) == rows(C));
Array<T,2> B(shape(C));
auto L1 = make_eigen(L).template triangularView<Eigen::Lower>();
auto U1 = make_eigen(L).transpose().template triangularView<Eigen::Upper>();
auto B1 = make_eigen(B);
auto C1 = make_eigen(C);
B1.noalias() = U1.solve(L1.solve(C1));
return B;
}
template<class T, class>
Array<T,0> dot(const Array<T,1>& x, const Array<T,1>& y) {
assert(length(x) == length(y));
Array<T,0> z;
auto x1 = make_eigen(x);
auto y1 = make_eigen(y);
z = x1.dot(y1);
return z;
}
template<class T, class>
Array<T,0> frobenius(const Array<T,2>& x, const Array<T,2>& y) {
Array<T,0> z;
auto x1 = make_eigen(x);
auto y1 = make_eigen(y);
z = (x1.array()*y1.array()).sum();
return z;
}
template<class T, class>
Array<T,1> inner(const Array<T,2>& A, const Array<T,1>& x) {
assert(rows(A) == length(x));
Array<T,1> y(make_shape(columns(A)));
auto A1 = make_eigen(A);
auto x1 = make_eigen(x);
auto y1 = make_eigen(y);
y1.noalias() = A1.transpose()*x1;
return y;
}
template<class T, class>
Array<T,2> inner(const Array<T,2>& A, const Array<T,2>& B) {
assert(rows(A) == rows(B));
Array<T,2> C(make_shape(columns(A), columns(B)));
auto A1 = make_eigen(A);
auto B1 = make_eigen(B);
auto C1 = make_eigen(C);
C1.noalias() = A1.transpose()*B1;
return C;
}
template<class T, class>
Array<T,2> inv(const Array<T,2>& A) {
assert(rows(A) == columns(A));
Array<T,2> B(shape(A));
auto A1 = make_eigen(A);
auto B1 = make_eigen(B);
B1.noalias() = A1.inverse();
return B;
}
template<class T, class>
Array<T,0> lcholdet(const Array<T,2>& L) {
auto L1 = make_eigen(L);
/* we have $S = LL^\top$; the determinant of $S$ is the square of the
* determinant of $L$, the determinant of $L$ is the product of the
* elements along the diagonal, as it is a triangular matrix; adjust for
* log-determinant */
return T(2.0)*L1.diagonal().array().log().sum();
}
template<class T, class>
Array<T,0> ldet(const Array<T,2>& A) {
auto A1 = make_eigen(A);
return A1.householderQr().logAbsDeterminant();
}
template<class T, class>
Array<T,2> outer(const Array<T,1>& x, const Array<T,1>& y) {
Array<T,2> A(make_shape(length(x), length(y)));
auto x1 = make_eigen(x);
auto y1 = make_eigen(y);
auto A1 = make_eigen(A);
A1.noalias() = x1*y1.transpose();
return A;
}
template<class T, class>
Array<T,2> outer(const Array<T,2>& A, const Array<T,2>& B) {
assert(columns(A) == columns(B));
Array<T,2> C(make_shape(rows(A), rows(B)));
auto A1 = make_eigen(A);
auto B1 = make_eigen(B);
auto C1 = make_eigen(C);
C1.noalias() = A1*B1.transpose();
return C;
}
template<class T, class>
Array<T,2> phi(const Array<T,2>& A) {
Array<T,2> L(make_shape(rows(A), columns(A)));
auto A1 = make_eigen(A).template triangularView<Eigen::Lower>();
auto L1 = make_eigen(L);
L1 = A1;
L1.diagonal() *= 0.5;
return L;
}
template<class T, class>
Array<T,2> transpose(const Array<T,2>& A) {
Array<T,2> B(make_shape(columns(A), rows(A)));
auto A1 = make_eigen(A);
auto B1 = make_eigen(B);
B1.noalias() = A1.transpose();
return B;
}
template<class T, class>
Array<T,2> tri(const Array<T,2>& A) {
Array<T,2> L(make_shape(rows(A), columns(A)));
auto A1 = make_eigen(A).template triangularView<Eigen::Lower>();
auto L1 = make_eigen(L);
L1 = A1;
return L;
}
template<class T, class>
Array<T,1> triinner(const Array<T,2>& L, const Array<T,1>& x) {
assert(rows(L) == length(x));
Array<T,1> y(make_shape(columns(L)));
auto U1 = make_eigen(L).transpose().template triangularView<Eigen::Upper>();
auto x1 = make_eigen(x);
auto y1 = make_eigen(y);
y1.noalias() = U1*x1;
return y;
}
template<class T, class>
Array<T,2> triinner(const Array<T,2>& L, const Array<T,2>& B) {
assert(rows(L) == rows(B));
Array<T,2> C(make_shape(columns(L), columns(B)));
auto U1 = make_eigen(L).transpose().template triangularView<Eigen::Upper>();
auto B1 = make_eigen(B);
auto C1 = make_eigen(C);
C1.noalias() = U1*B1;
return C;
}
template<class T, class>
Array<T,2> triinv(const Array<T,2>& L) {
assert(rows(L) == columns(L));
Array<T,2> B(shape(L));
auto L1 = make_eigen(L).template triangularView<Eigen::Lower>();
auto B1 = make_eigen(B);
B1.noalias() = L1.solve(B1.Identity(rows(B), columns(B)));
return B;
}
template<class T, class>
Array<T,1> trimul(const Array<T,2>& L, const Array<T,1>& x) {
assert(columns(L) == length(x));
Array<T,1> y(make_shape(rows(L)));
auto L1 = make_eigen(L).template triangularView<Eigen::Lower>();
auto x1 = make_eigen(x);
auto y1 = make_eigen(y);
y1.noalias() = L1*x1;
return y;
}
template<class T, class>
Array<T,2> trimul(const Array<T,2>& L, const Array<T,2>& B) {
assert(columns(L) == rows(B));
Array<T,2> C(make_shape(rows(L), columns(B)));
auto L1 = make_eigen(L).template triangularView<Eigen::Lower>();
auto B1 = make_eigen(B);
auto C1 = make_eigen(C);
C1.noalias() = L1*B1;
return C;
}
template<class T, class>
Array<T,2> triouter(const Array<T,2>& A, const Array<T,2>& L) {
assert(columns(A) == columns(L));
Array<T,2> C(make_shape(rows(A), rows(L)));
auto A1 = make_eigen(A);
auto U1 = make_eigen(L).transpose().template triangularView<Eigen::Upper>();
auto C1 = make_eigen(C);
C1.noalias() = A1*U1;
return C;
}
template<class T, class>
Array<T,1> trisolve(const Array<T,2>& L, const Array<T,1>& y) {
assert(rows(L) == columns(L));
assert(columns(L) == length(y));
Array<T,1> x(shape(y));
auto L1 = make_eigen(L).template triangularView<Eigen::Lower>();
auto x1 = make_eigen(x);
auto y1 = make_eigen(y);
x1.noalias() = L1.solve(y1);
return x;
}
template<class T, class>
Array<T,2> trisolve(const Array<T,2>& L, const Array<T,2>& C) {
assert(rows(L) == columns(L));
assert(columns(L) == rows(C));
Array<T,2> B(shape(C));
auto L1 = make_eigen(L).template triangularView<Eigen::Lower>();
auto B1 = make_eigen(B);
auto C1 = make_eigen(C);
B1.noalias() = L1.solve(C1);
return B;
}
}
<|endoftext|> |
<commit_before>#include <Matrix.hpp>
#include <catch.hpp>
#include <fstream>
SCENARIO("Matrix init", "[init]") {
GIVEN("The number of lines and columns") {
auto lines = 36;
auto columns = 39;
WHEN("Create instansce of Matrix") {
Matrix matrix(lines, columns);
THEN("The number of lines and columns must be preserved") {
REQUIRE(matrix.GetNumberOfLines() == lines);
REQUIRE(matrix.GetNumberOfColumns() == columns);
}
}
}
}
SCENARIO("Matrix InitFromFile", "[fill]") {
Matrix C(3, 1);
C.InitFromFile("C3x1.txt");
REQUIRE( C[0][0] == 1 );
REQUIRE( C[1][0] == 2 );
REQUIRE( C[2][0] == 0 );
}
SCENARIO("Matrix +", "[addition]") {
Matrix A(3, 3);
A.InitFromFile("A3x3.txt");
Matrix B(3, 3);
B.InitFromFile("B3x3.txt");
Matrix expected = Matrix(3, 3);
expected.InitFromFile("(A3x3)+(B3x3).txt");
Matrix result = A + B;
for (int i = 0; i < 3; i++){
for (int j = 0; j < 3; j++){
REQUIRE(result[i][j] == expected[i][j]);
}
}
}
SCENARIO("Matrix *", "[multiplication]") {
Matrix A = Matrix(3, 3);
A.InitFromFile("A3x3.txt");
Matrix C = Matrix(3, 1);
C.InitFromFile("C3x1.txt");
Matrix expected = Matrix(3, 1);
expected.InitFromFile("(A3x3)(C3x1).txt");
Matrix result = A * C;
for (int i = 0; i < 3; i++){
for (int j = 0; j < 3; j++){
REQUIRE(result[i][j] == expected[i][j]);
}
}
}
<commit_msg>Update init.cpp<commit_after>#include <Matrix.hpp>
#include <catch.hpp>
#include <fstream>
SCENARIO("Matrix init", "[init]") {
GIVEN("The number of lines and columns") {
auto lines = 36;
auto columns = 39;
WHEN("Create instansce of Matrix") {
Matrix matrix(lines, columns);
THEN("The number of lines and columns must be preserved") {
REQUIRE(matrix.GetNumberOfLines() == lines);
REQUIRE(matrix.GetNumberOfColumns() == columns);
}
}
}
}
SCENARIO("Matrix InitFromFile", "[fill]") {
Matrix C(3, 1);
C.InitFromFile("C3x1.txt");
REQUIRE( C[0][0] == 1 );
REQUIRE( C[1][0] == 2 );
REQUIRE( C[2][0] == 0 );
}
SCENARIO("Matrix +", "[addition]") {
Matrix A(3, 3);
A.InitFromFile("A3x3.txt");
Matrix B(3, 3);
B.InitFromFile("B3x3.txt");
Matrix expected = Matrix(3, 3);
expected.InitFromFile("(A3x3)+(B3x3).txt");
Matrix result = A + B;
for (int i = 0; i < 3; i++){
for (int j = 0; j < 3; j++){
REQUIRE(result[i][j] == expected[i][j]);
}
}
}
SCENARIO("Matrix *", "[multiplication]") {
Matrix A = Matrix(3, 3);
A.InitFromFile("A3x3.txt");
Matrix C = Matrix(3, 1);
C.InitFromFile("C3x1.txt");
Matrix expected = Matrix(3, 1);
expected.InitFromFile("(A3x3)(C3x1).txt");
Matrix result = A * C;
for (int i = 0; i < 3; i++){
REQUIRE(result[i][0] == expected[i][0]);
}
}
<|endoftext|> |
<commit_before>//
// Copyright (c) 2006-2017 Benjamin Kaufmann
//
// This file is part of Clasp. See http://www.cs.uni-potsdam.de/clasp/
//
// 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 <clasp/enumerator.h>
#include <clasp/solver.h>
#include <clasp/util/multi_queue.h>
#include <clasp/clause.h>
namespace Clasp {
/////////////////////////////////////////////////////////////////////////////////////////
// Enumerator - Shared Queue / Thread Queue
/////////////////////////////////////////////////////////////////////////////////////////
class Enumerator::SharedQueue : public mt::MultiQueue<SharedLiterals*, void (*)(SharedLiterals*)> {
public:
typedef mt::MultiQueue<SharedLiterals*, void (*)(SharedLiterals*)> BaseType;
explicit SharedQueue(uint32 m) : BaseType(m, releaseLits) { reserve(m + 1); }
bool pushRelaxed(SharedLiterals* clause) { unsafePublish(clause); return true; }
static void releaseLits(SharedLiterals* x){ x->release(); }
};
class Enumerator::ThreadQueue {
public:
explicit ThreadQueue(SharedQueue& q) : queue_(&q) { tail_ = q.addThread(); }
bool pop(SharedLiterals*& out){ return queue_->tryConsume(tail_, out); }
ThreadQueue* clone() { return new ThreadQueue(*queue_); }
private:
Enumerator::SharedQueue* queue_;
Enumerator::SharedQueue::ThreadId tail_;
};
/////////////////////////////////////////////////////////////////////////////////////////
// EnumerationConstraint
/////////////////////////////////////////////////////////////////////////////////////////
EnumerationConstraint::EnumerationConstraint() : mini_(0), root_(0), state_(0), upMode_(0), heuristic_(0), disjoint_(false) {
setDisjoint(false);
}
EnumerationConstraint::~EnumerationConstraint() { }
void EnumerationConstraint::init(Solver& s, SharedMinimizeData* m, QueuePtr p) {
mini_ = 0;
queue_ = p;
upMode_ = value_false;
heuristic_ = 0;
if (m) {
OptParams opt = s.sharedContext()->configuration()->solver(s.id()).opt;
mini_ = m->attach(s, opt);
if (optimize()) {
if (opt.type != OptParams::type_bb) { upMode_ |= value_true; }
else { heuristic_ |= 1; }
}
if (opt.hasOption(OptParams::heu_sign)) {
for (const WeightLiteral* it = m->lits; !isSentinel(it->first); ++it) {
s.setPref(it->first.var(), ValueSet::pref_value, falseValue(it->first));
}
}
if (opt.hasOption(OptParams::heu_model)) { heuristic_ |= 2; }
}
}
bool EnumerationConstraint::valid(Solver& s) { return !optimize() || mini_->valid(s); }
void EnumerationConstraint::add(Constraint* c) { if (c) { nogoods_.push_back(c); } }
bool EnumerationConstraint::integrateBound(Solver& s){ return !mini_ || mini_->integrate(s); }
bool EnumerationConstraint::optimize() const { return mini_ && mini_->shared()->optimize(); }
void EnumerationConstraint::setDisjoint(bool x) { disjoint_ = x; }
Constraint* EnumerationConstraint::cloneAttach(Solver& s) {
EnumerationConstraint* c = clone();
POTASSCO_REQUIRE(c != 0, "Cloning not supported by Enumerator");
c->init(s, mini_ ? const_cast<SharedMinimizeData*>(mini_->shared()) : 0, queue_.get() ? queue_->clone() : 0);
return c;
}
void EnumerationConstraint::end(Solver& s) {
if (mini_) { mini_->relax(s, disjointPath()); }
state_ = 0;
setDisjoint(false);
next_.clear();
if (s.rootLevel() > root_) { s.popRootLevel(s.rootLevel() - root_); }
}
bool EnumerationConstraint::start(Solver& s, const LitVec& path, bool disjoint) {
state_ = 0;
root_ = s.rootLevel();
setDisjoint(disjoint);
if (s.pushRoot(path) && s.pushRoot(s.sharedContext()->stepLiteral())) {
integrateBound(s);
return true;
}
return false;
}
bool EnumerationConstraint::update(Solver& s) {
ValueRep st = state();
if (st == value_true) {
if (s.restartOnModel()) { s.undoUntil(0); }
if (optimize()) { s.strengthenConditional(); }
}
else if (st == value_false && !s.pushRoot(next_)) {
if (!s.hasConflict()) { s.setStopConflict(); }
return false;
}
state_ = 0;
next_.clear();
do {
if (!s.hasConflict() && doUpdate(s) && integrateBound(s) && integrateNogoods(s)) {
if (st == value_true) { modelHeuristic(s); }
return true;
}
} while (st != value_free && s.hasConflict() && s.resolveConflict());
return false;
}
bool EnumerationConstraint::integrateNogoods(Solver& s) {
if (!queue_.get() || s.hasConflict()) { return !s.hasConflict(); }
const uint32 f = ClauseCreator::clause_no_add | ClauseCreator::clause_no_release | ClauseCreator::clause_explicit;
for (SharedLiterals* clause; queue_->pop(clause); ) {
ClauseCreator::Result res = ClauseCreator::integrate(s, clause, f);
if (res.local) { add(res.local);}
if (!res.ok()) { return false; }
}
return true;
}
void EnumerationConstraint::destroy(Solver* s, bool x) {
if (mini_) { mini_->destroy(s, x); mini_ = 0; }
queue_ = 0;
Clasp::destroyDB(nogoods_, s, x);
Constraint::destroy(s, x);
}
bool EnumerationConstraint::simplify(Solver& s, bool reinit) {
if (mini_) { mini_->simplify(s, reinit); }
simplifyDB(s, nogoods_, reinit);
return false;
}
bool EnumerationConstraint::commitModel(Enumerator& ctx, Solver& s) {
if (state() == value_true) { return !next_.empty() && (s.satPrepro()->extendModel(s.model, next_), true); }
if (mini_ && !mini_->handleModel(s)){ return false; }
if (!ctx.tentative()) { doCommitModel(ctx, s); }
next_ = s.symmetric();
state_ |= value_true;
return true;
}
bool EnumerationConstraint::commitUnsat(Enumerator& ctx, Solver& s) {
next_.clear();
state_ |= value_false;
if (mini_) {
mini_->handleUnsat(s, !disjointPath(), next_);
}
if (!ctx.tentative()) {
doCommitUnsat(ctx, s);
}
return !s.hasConflict() || s.decisionLevel() != s.rootLevel();
}
void EnumerationConstraint::modelHeuristic(Solver& s) {
const bool full = heuristic_ > 1;
const bool heuristic = full || (heuristic_ == 1 && s.queueSize() == 0 && s.decisionLevel() == s.rootLevel());
if (optimize() && heuristic && s.propagate()) {
for (const WeightLiteral* w = mini_->shared()->lits; !isSentinel(w->first); ++w) {
if (s.value(w->first.var()) == value_free) {
s.assume(~w->first);
if (!full || !s.propagate()) { break; }
}
}
}
}
/////////////////////////////////////////////////////////////////////////////////////////
// Enumerator
/////////////////////////////////////////////////////////////////////////////////////////
void Model::reset() { std::memset(this, 0, sizeof(Model)); }
Enumerator::Enumerator() : mini_(0), queue_(0) { model_.reset(); }
Enumerator::~Enumerator() { delete queue_; }
void Enumerator::setDisjoint(Solver& s, bool b)const { constraintRef(s).setDisjoint(b); }
void Enumerator::setIgnoreSymmetric(bool b) { model_.sym = static_cast<uint32>(b == false); }
void Enumerator::end(Solver& s) const { constraintRef(s).end(s); }
void Enumerator::doReset() {}
void Enumerator::reset() {
if (mini_) { mini_ = 0; }
if (queue_){ delete queue_; queue_ = 0; }
model_.reset();
model_.ctx = this;
model_.sym = 1;
model_.type = uint32(modelType());
model_.sId = 0;
doReset();
}
int Enumerator::init(SharedContext& ctx, OptMode oMode, int limit) {
ctx.master()->setEnumerationConstraint(0);
reset();
if (oMode != MinimizeMode_t::ignore){ mini_ = ctx.minimize(); }
limit = limit >= 0 ? limit : 1 - int(exhaustive());
if (limit != 1) { ctx.setPreserveModels(true); }
queue_ = new SharedQueue(ctx.concurrency());
ConPtr c = doInit(ctx, mini_, limit);
bool cons = model_.consequences();
if (tentative()) { model_.type = Model::Sat; }
else if (cons && optimize()) { ctx.warn("Optimization: Consequences may depend on enumeration order."); }
c->init(*ctx.master(), mini_, new ThreadQueue(*queue_));
ctx.master()->setEnumerationConstraint(c);
return limit;
}
Enumerator::ConRef Enumerator::constraintRef(const Solver& s) const {
POTASSCO_ASSERT(s.enumerationConstraint(), "Solver not attached");
return static_cast<ConRef>(*s.enumerationConstraint());
}
Enumerator::ConPtr Enumerator::constraint(const Solver& s) const {
return static_cast<ConPtr>(s.enumerationConstraint());
}
bool Enumerator::start(Solver& s, const LitVec& path, bool disjointPath) const {
return constraintRef(s).start(s, path, disjointPath);
}
ValueRep Enumerator::commit(Solver& s) {
if (s.hasConflict() && s.decisionLevel() == s.rootLevel()) { return commitUnsat(s) ? value_free : value_false; }
else if (s.numFreeVars() == 0 && s.queueSize() == 0 && !s.hasConflict()){ return commitModel(s) ? value_true : value_free; }
return value_free;
}
bool Enumerator::commitModel(Solver& s) {
assert(s.numFreeVars() == 0 && !s.hasConflict() && s.queueSize() == 0);
if (constraintRef(s).commitModel(*this, s)) {
s.stats.addModel(s.decisionLevel());
++model_.num;
model_.sId = s.id();
model_.values = &s.model;
model_.costs = 0;
model_.up = 0;
if (minimizer()) {
costs_.resize(minimizer()->numRules());
std::transform(minimizer()->adjust(), minimizer()->adjust()+costs_.size(), minimizer()->sum(), costs_.begin(), std::plus<wsum_t>());
model_.costs = &costs_;
}
return true;
}
return false;
}
bool Enumerator::commitSymmetric(Solver& s){ return model_.sym && !optimize() && commitModel(s); }
bool Enumerator::commitUnsat(Solver& s) { return constraintRef(s).commitUnsat(*this, s); }
bool Enumerator::commitClause(const LitVec& clause) const {
return queue_ && queue_->pushRelaxed(SharedLiterals::newShareable(clause, Constraint_t::Other));
}
bool Enumerator::commitComplete() {
if (enumerated()) {
if (tentative()) {
mini_->markOptimal();
model_.opt = 1;
model_.num = 0;
model_.type= uint32(modelType());
return false;
}
else if (model_.consequences() || (!model_.opt && optimize())) {
model_.opt = uint32(optimize());
model_.def = uint32(model_.consequences());
model_.num = 1;
}
}
return true;
}
bool Enumerator::update(Solver& s) const {
return constraintRef(s).update(s);
}
bool Enumerator::supportsSplitting(const SharedContext& ctx) const {
if (!optimize()) { return true; }
const Configuration* config = ctx.configuration();
bool ok = true;
for (uint32 i = 0; i != ctx.concurrency() && ok; ++i) {
if (ctx.hasSolver(i) && constraint(*ctx.solver(i))){ ok = constraint(*ctx.solver(i))->minimizer()->supportsSplitting(); }
else if (config && i < config->numSolver()) { ok = config->solver(i).opt.supportsSplitting(); }
}
return ok;
}
int Enumerator::unsatType() const {
return !optimize() ? unsat_stop : unsat_cont;
}
Model& Enumerator::model() {
return model_;
}
/////////////////////////////////////////////////////////////////////////////////////////
// EnumOptions
/////////////////////////////////////////////////////////////////////////////////////////
Enumerator* EnumOptions::createEnumerator(const EnumOptions& opts) {
if (opts.models()) { return createModelEnumerator(opts);}
else if (opts.consequences()){ return createConsEnumerator(opts); }
else { return nullEnumerator(); }
}
Enumerator* EnumOptions::nullEnumerator() {
struct NullEnum : Enumerator {
ConPtr doInit(SharedContext&, SharedMinimizeData*, int) {
struct Constraint : public EnumerationConstraint {
Constraint() : EnumerationConstraint() {}
ConPtr clone() { return new Constraint(); }
bool doUpdate(Solver&){ return true; }
};
return new Constraint();
}
};
return new NullEnum;
}
const char* modelType(const Model& m) {
switch (m.type) {
case Model::Sat : return "Model";
case Model::Brave : return "Brave";
case Model::Cautious: return "Cautious";
case Model::User : return "User";
default: return 0;
}
}
}
<commit_msg>Integrate nogoods on Enumerator::start().<commit_after>//
// Copyright (c) 2006-2017 Benjamin Kaufmann
//
// This file is part of Clasp. See http://www.cs.uni-potsdam.de/clasp/
//
// 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 <clasp/enumerator.h>
#include <clasp/solver.h>
#include <clasp/util/multi_queue.h>
#include <clasp/clause.h>
namespace Clasp {
/////////////////////////////////////////////////////////////////////////////////////////
// Enumerator - Shared Queue / Thread Queue
/////////////////////////////////////////////////////////////////////////////////////////
class Enumerator::SharedQueue : public mt::MultiQueue<SharedLiterals*, void (*)(SharedLiterals*)> {
public:
typedef mt::MultiQueue<SharedLiterals*, void (*)(SharedLiterals*)> BaseType;
explicit SharedQueue(uint32 m) : BaseType(m, releaseLits) { reserve(m + 1); }
bool pushRelaxed(SharedLiterals* clause) { unsafePublish(clause); return true; }
static void releaseLits(SharedLiterals* x){ x->release(); }
};
class Enumerator::ThreadQueue {
public:
explicit ThreadQueue(SharedQueue& q) : queue_(&q) { tail_ = q.addThread(); }
bool pop(SharedLiterals*& out){ return queue_->tryConsume(tail_, out); }
ThreadQueue* clone() { return new ThreadQueue(*queue_); }
private:
Enumerator::SharedQueue* queue_;
Enumerator::SharedQueue::ThreadId tail_;
};
/////////////////////////////////////////////////////////////////////////////////////////
// EnumerationConstraint
/////////////////////////////////////////////////////////////////////////////////////////
EnumerationConstraint::EnumerationConstraint() : mini_(0), root_(0), state_(0), upMode_(0), heuristic_(0), disjoint_(false) {
setDisjoint(false);
}
EnumerationConstraint::~EnumerationConstraint() { }
void EnumerationConstraint::init(Solver& s, SharedMinimizeData* m, QueuePtr p) {
mini_ = 0;
queue_ = p;
upMode_ = value_false;
heuristic_ = 0;
if (m) {
OptParams opt = s.sharedContext()->configuration()->solver(s.id()).opt;
mini_ = m->attach(s, opt);
if (optimize()) {
if (opt.type != OptParams::type_bb) { upMode_ |= value_true; }
else { heuristic_ |= 1; }
}
if (opt.hasOption(OptParams::heu_sign)) {
for (const WeightLiteral* it = m->lits; !isSentinel(it->first); ++it) {
s.setPref(it->first.var(), ValueSet::pref_value, falseValue(it->first));
}
}
if (opt.hasOption(OptParams::heu_model)) { heuristic_ |= 2; }
}
}
bool EnumerationConstraint::valid(Solver& s) { return !optimize() || mini_->valid(s); }
void EnumerationConstraint::add(Constraint* c) { if (c) { nogoods_.push_back(c); } }
bool EnumerationConstraint::integrateBound(Solver& s){ return !mini_ || mini_->integrate(s); }
bool EnumerationConstraint::optimize() const { return mini_ && mini_->shared()->optimize(); }
void EnumerationConstraint::setDisjoint(bool x) { disjoint_ = x; }
Constraint* EnumerationConstraint::cloneAttach(Solver& s) {
EnumerationConstraint* c = clone();
POTASSCO_REQUIRE(c != 0, "Cloning not supported by Enumerator");
c->init(s, mini_ ? const_cast<SharedMinimizeData*>(mini_->shared()) : 0, queue_.get() ? queue_->clone() : 0);
return c;
}
void EnumerationConstraint::end(Solver& s) {
if (mini_) { mini_->relax(s, disjointPath()); }
state_ = 0;
setDisjoint(false);
next_.clear();
if (s.rootLevel() > root_) { s.popRootLevel(s.rootLevel() - root_); }
}
bool EnumerationConstraint::start(Solver& s, const LitVec& path, bool disjoint) {
state_ = 0;
root_ = s.rootLevel();
setDisjoint(disjoint);
if (s.pushRoot(path) && s.pushRoot(s.sharedContext()->stepLiteral())) {
integrateBound(s);
integrateNogoods(s);
return true;
}
return false;
}
bool EnumerationConstraint::update(Solver& s) {
ValueRep st = state();
if (st == value_true) {
if (s.restartOnModel()) { s.undoUntil(0); }
if (optimize()) { s.strengthenConditional(); }
}
else if (st == value_false && !s.pushRoot(next_)) {
if (!s.hasConflict()) { s.setStopConflict(); }
return false;
}
state_ = 0;
next_.clear();
do {
if (!s.hasConflict() && doUpdate(s) && integrateBound(s) && integrateNogoods(s)) {
if (st == value_true) { modelHeuristic(s); }
return true;
}
} while (st != value_free && s.hasConflict() && s.resolveConflict());
return false;
}
bool EnumerationConstraint::integrateNogoods(Solver& s) {
if (!queue_.get() || s.hasConflict()) { return !s.hasConflict(); }
const uint32 f = ClauseCreator::clause_no_add | ClauseCreator::clause_no_release | ClauseCreator::clause_explicit;
for (SharedLiterals* clause; queue_->pop(clause); ) {
ClauseCreator::Result res = ClauseCreator::integrate(s, clause, f);
if (res.local) { add(res.local);}
if (!res.ok()) { return false; }
}
return true;
}
void EnumerationConstraint::destroy(Solver* s, bool x) {
if (mini_) { mini_->destroy(s, x); mini_ = 0; }
queue_ = 0;
Clasp::destroyDB(nogoods_, s, x);
Constraint::destroy(s, x);
}
bool EnumerationConstraint::simplify(Solver& s, bool reinit) {
if (mini_) { mini_->simplify(s, reinit); }
simplifyDB(s, nogoods_, reinit);
return false;
}
bool EnumerationConstraint::commitModel(Enumerator& ctx, Solver& s) {
if (state() == value_true) { return !next_.empty() && (s.satPrepro()->extendModel(s.model, next_), true); }
if (mini_ && !mini_->handleModel(s)){ return false; }
if (!ctx.tentative()) { doCommitModel(ctx, s); }
next_ = s.symmetric();
state_ |= value_true;
return true;
}
bool EnumerationConstraint::commitUnsat(Enumerator& ctx, Solver& s) {
next_.clear();
state_ |= value_false;
if (mini_) {
mini_->handleUnsat(s, !disjointPath(), next_);
}
if (!ctx.tentative()) {
doCommitUnsat(ctx, s);
}
return !s.hasConflict() || s.decisionLevel() != s.rootLevel();
}
void EnumerationConstraint::modelHeuristic(Solver& s) {
const bool full = heuristic_ > 1;
const bool heuristic = full || (heuristic_ == 1 && s.queueSize() == 0 && s.decisionLevel() == s.rootLevel());
if (optimize() && heuristic && s.propagate()) {
for (const WeightLiteral* w = mini_->shared()->lits; !isSentinel(w->first); ++w) {
if (s.value(w->first.var()) == value_free) {
s.assume(~w->first);
if (!full || !s.propagate()) { break; }
}
}
}
}
/////////////////////////////////////////////////////////////////////////////////////////
// Enumerator
/////////////////////////////////////////////////////////////////////////////////////////
void Model::reset() { std::memset(this, 0, sizeof(Model)); }
Enumerator::Enumerator() : mini_(0), queue_(0) { model_.reset(); }
Enumerator::~Enumerator() { delete queue_; }
void Enumerator::setDisjoint(Solver& s, bool b)const { constraintRef(s).setDisjoint(b); }
void Enumerator::setIgnoreSymmetric(bool b) { model_.sym = static_cast<uint32>(b == false); }
void Enumerator::end(Solver& s) const { constraintRef(s).end(s); }
void Enumerator::doReset() {}
void Enumerator::reset() {
if (mini_) { mini_ = 0; }
if (queue_){ delete queue_; queue_ = 0; }
model_.reset();
model_.ctx = this;
model_.sym = 1;
model_.type = uint32(modelType());
model_.sId = 0;
doReset();
}
int Enumerator::init(SharedContext& ctx, OptMode oMode, int limit) {
ctx.master()->setEnumerationConstraint(0);
reset();
if (oMode != MinimizeMode_t::ignore){ mini_ = ctx.minimize(); }
limit = limit >= 0 ? limit : 1 - int(exhaustive());
if (limit != 1) { ctx.setPreserveModels(true); }
queue_ = new SharedQueue(ctx.concurrency());
ConPtr c = doInit(ctx, mini_, limit);
bool cons = model_.consequences();
if (tentative()) { model_.type = Model::Sat; }
else if (cons && optimize()) { ctx.warn("Optimization: Consequences may depend on enumeration order."); }
c->init(*ctx.master(), mini_, new ThreadQueue(*queue_));
ctx.master()->setEnumerationConstraint(c);
return limit;
}
Enumerator::ConRef Enumerator::constraintRef(const Solver& s) const {
POTASSCO_ASSERT(s.enumerationConstraint(), "Solver not attached");
return static_cast<ConRef>(*s.enumerationConstraint());
}
Enumerator::ConPtr Enumerator::constraint(const Solver& s) const {
return static_cast<ConPtr>(s.enumerationConstraint());
}
bool Enumerator::start(Solver& s, const LitVec& path, bool disjointPath) const {
return constraintRef(s).start(s, path, disjointPath);
}
ValueRep Enumerator::commit(Solver& s) {
if (s.hasConflict() && s.decisionLevel() == s.rootLevel()) { return commitUnsat(s) ? value_free : value_false; }
else if (s.numFreeVars() == 0 && s.queueSize() == 0 && !s.hasConflict()){ return commitModel(s) ? value_true : value_free; }
return value_free;
}
bool Enumerator::commitModel(Solver& s) {
assert(s.numFreeVars() == 0 && !s.hasConflict() && s.queueSize() == 0);
if (constraintRef(s).commitModel(*this, s)) {
s.stats.addModel(s.decisionLevel());
++model_.num;
model_.sId = s.id();
model_.values = &s.model;
model_.costs = 0;
model_.up = 0;
if (minimizer()) {
costs_.resize(minimizer()->numRules());
std::transform(minimizer()->adjust(), minimizer()->adjust()+costs_.size(), minimizer()->sum(), costs_.begin(), std::plus<wsum_t>());
model_.costs = &costs_;
}
return true;
}
return false;
}
bool Enumerator::commitSymmetric(Solver& s){ return model_.sym && !optimize() && commitModel(s); }
bool Enumerator::commitUnsat(Solver& s) { return constraintRef(s).commitUnsat(*this, s); }
bool Enumerator::commitClause(const LitVec& clause) const {
return queue_ && queue_->pushRelaxed(SharedLiterals::newShareable(clause, Constraint_t::Other));
}
bool Enumerator::commitComplete() {
if (enumerated()) {
if (tentative()) {
mini_->markOptimal();
model_.opt = 1;
model_.num = 0;
model_.type= uint32(modelType());
return false;
}
else if (model_.consequences() || (!model_.opt && optimize())) {
model_.opt = uint32(optimize());
model_.def = uint32(model_.consequences());
model_.num = 1;
}
}
return true;
}
bool Enumerator::update(Solver& s) const {
return constraintRef(s).update(s);
}
bool Enumerator::supportsSplitting(const SharedContext& ctx) const {
if (!optimize()) { return true; }
const Configuration* config = ctx.configuration();
bool ok = true;
for (uint32 i = 0; i != ctx.concurrency() && ok; ++i) {
if (ctx.hasSolver(i) && constraint(*ctx.solver(i))){ ok = constraint(*ctx.solver(i))->minimizer()->supportsSplitting(); }
else if (config && i < config->numSolver()) { ok = config->solver(i).opt.supportsSplitting(); }
}
return ok;
}
int Enumerator::unsatType() const {
return !optimize() ? unsat_stop : unsat_cont;
}
Model& Enumerator::model() {
return model_;
}
/////////////////////////////////////////////////////////////////////////////////////////
// EnumOptions
/////////////////////////////////////////////////////////////////////////////////////////
Enumerator* EnumOptions::createEnumerator(const EnumOptions& opts) {
if (opts.models()) { return createModelEnumerator(opts);}
else if (opts.consequences()){ return createConsEnumerator(opts); }
else { return nullEnumerator(); }
}
Enumerator* EnumOptions::nullEnumerator() {
struct NullEnum : Enumerator {
ConPtr doInit(SharedContext&, SharedMinimizeData*, int) {
struct Constraint : public EnumerationConstraint {
Constraint() : EnumerationConstraint() {}
ConPtr clone() { return new Constraint(); }
bool doUpdate(Solver&){ return true; }
};
return new Constraint();
}
};
return new NullEnum;
}
const char* modelType(const Model& m) {
switch (m.type) {
case Model::Sat : return "Model";
case Model::Brave : return "Brave";
case Model::Cautious: return "Cautious";
case Model::User : return "User";
default: return 0;
}
}
}
<|endoftext|> |
<commit_before>#include <stack.cpp>
#include <catch.hpp>
#include <iostream>
//using namespace std;
SCENARIO("count", "[count]"){
stack<int> s;
s.push(1);
REQUIRE(s.count()==1);
}
SCENARIO("push", "[push]"){
stack<int> s;
s.push(1);
REQUIRE(s.count()==1);
REQUIRE(s.top()==1);
}
SCENARIO("top", "[top]"){
stack<int> s;
s.push(1);
REQUIRE(s.count()==1);
REQUIRE(s.top()==1);
}
SCENARIO("pop", "[pop]"){
stack<int> s;
s.push(1);
s.push(2);
s.pop();
REQUIRE(s.count()==1);
REQUIRE(s.top()==1);
}
SCENARIO("prisv", "[prisv]"){
stack<int> s;
s.push(1);
stack<int> s2;
s2=s;
REQUIRE(s.count()==1);
REQUIRE(s.top()==1);
}
SCENARIO("copy", "[copy]"){
stack<int> s;
s.push(1);
stack <int> a = s;
REQUIRE(a.count()==1);
REQUIRE(a.top()==1);
}
SCENARIO("test", "[test]"){
stack<int> s;
REQUIRE(s.count()==0);
}
SCENARIO("empty", "[empty]"){
stack<int> s;
REQUIRE(s.empty()==true);
}
<commit_msg>Delete init.cpp<commit_after><|endoftext|> |
<commit_before><commit_msg>Fix for param array support in effects for GL<commit_after><|endoftext|> |
<commit_before>#define _POSIX_SOURCE
#include "condor_common.h"
#include "condor_debug.h"
#include "directory.h"
static char *_FileName_ = __FILE__; /* Used by EXCEPT (see except.h) */
Directory::Directory( const char *name )
{
dirp = opendir( name );
if( dirp == NULL ) {
EXCEPT( "Can't open directory \"%s\"", name );
}
}
Directory::~Directory()
{
(void)closedir( dirp );
}
void
Directory::Rewind()
{
rewinddir( dirp );
}
char *
Directory::Next()
{
struct dirent *dirent;
while( dirent = readdir(dirp) ) {
if( strcmp(".",dirent->d_name) == MATCH ) {
continue;
}
if( strcmp("..",dirent->d_name) == MATCH ) {
continue;
}
return dirent->d_name;
}
return NULL;
}
<commit_msg>Included condor_constants.h for definition of the MATCH constant<commit_after>#define _POSIX_SOURCE
#include "condor_common.h"
#include "condor_constants.h"
#include "condor_debug.h"
#include "directory.h"
static char *_FileName_ = __FILE__; /* Used by EXCEPT (see except.h) */
Directory::Directory( const char *name )
{
dirp = opendir( name );
if( dirp == NULL ) {
EXCEPT( "Can't open directory \"%s\"", name );
}
}
Directory::~Directory()
{
(void)closedir( dirp );
}
void
Directory::Rewind()
{
rewinddir( dirp );
}
char *
Directory::Next()
{
struct dirent *dirent;
while( dirent = readdir(dirp) ) {
if( strcmp(".",dirent->d_name) == MATCH ) {
continue;
}
if( strcmp("..",dirent->d_name) == MATCH ) {
continue;
}
return dirent->d_name;
}
return NULL;
}
<|endoftext|> |
<commit_before>#include "circuits/circuit.h"
#include "matrix/matrix.h"
#include "gtest/gtest.h"
#include <iostream>
#include <stdio.h>
using namespace std;
TEST(ElementStampsTest, Resistor) {
// Arrange
Element resistor("R1", 4, 1, 2);
int numVariables = 2;
double matrix[MAX_NODES+1][MAX_NODES+2];
init(numVariables, matrix);
// Act
resistor.applyStamp(matrix, numVariables);
// Assert
double expected[MAX_NODES+1][MAX_NODES+2] = {
{0, 0, 0, 0},
{0, 0.25, -0.25, 0},
{0, -0.25, 0.25, 0}
};
for (int i=1; i<=numVariables; i++) {
for (int j=1; j<=numVariables+1; j++) {
EXPECT_EQ(expected[i][j], matrix[i][j]);
}
}
}
<commit_msg>Tests simple circuit stamps :princess:<commit_after>#include "circuits/circuit.h"
#include "matrix/matrix.h"
#include "gtest/gtest.h"
#include <iostream>
#include <stdio.h>
using namespace std;
TEST(ElementStampsTest, Resistor) {
// Arrange
Element resistor("R1", 4, 1, 2);
int numVariables = 2;
double matrix[MAX_NODES+1][MAX_NODES+2];
init(numVariables, matrix);
// Act
resistor.applyStamp(matrix, numVariables);
// Assert
double expected[MAX_NODES+1][MAX_NODES+2] = {
{0, 0, 0, 0},
{0, 0.25, -0.25, 0},
{0, -0.25, 0.25, 0}
};
for (int i=1; i<=numVariables; i++) {
for (int j=1; j<=numVariables+1; j++) {
EXPECT_EQ(expected[i][j], matrix[i][j]);
}
}
}
TEST(CircuitStampsTest, SimpleCircuit) {
// Arrange
int numNodes = 6;
int numElements = 9;
int numVariables = 9;
vector<Element> netlist(10);
double matrix[MAX_NODES+1][MAX_NODES+2];
init(numVariables, matrix);
// From netlist data/simples.net
// Changes order (not netlist parameters order)! Value first!
// ( name, val, a, b, ... )
netlist[1] = Element("R0102", 1, 1, 2);
netlist[2] = Element("R0301", 1, 3, 1);
netlist[3] = Element("R0403", 1, 4, 3);
netlist[4] = Element("R0004", 1, 0, 4);
netlist[5] = Element("R0502", 1, 5, 2);
netlist[6] = Element("R0605", 1, 6, 5);
netlist[7] = Element("O0300", 0, 3, 0, 1, 0); // OpAmps have value = 0!!!
netlist[8] = Element("O0600", 0, 6, 0, 5, 4);
netlist[9] = Element("V0200", 1, 2, 0);
// Bad smell about the need of this member function...
// Without it, only first part of matrix would be populated!
vector<string> dummyVariablesList(10);
int pivotNumVariables = numNodes;
netlist[7].addCurrentVariables(pivotNumVariables, dummyVariablesList);
netlist[8].addCurrentVariables(pivotNumVariables, dummyVariablesList);
netlist[9].addCurrentVariables(pivotNumVariables, dummyVariablesList);
// Act
applyStamps(numElements, numVariables, netlist, matrix);
// Assert
double expected[MAX_NODES+1][MAX_NODES+2] = {
{ 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 },
{ 0 , 2 , -1 , -1 , 0 , 0 , 0 , 0 , 0 , 0 , 0 },
{ 0 , -1 , 2 , 0 , 0 , -1 , 0 , 0 , 0 , 1 , 0 },
{ 0 , -1 , 0 , 2 , -1 , 0 , 0 , 1 , 0 , 0 , 0 },
{ 0 , 0 , 0 , -1 , 2 , 0 , 0 , 0 , 0 , 0 , 0 },
{ 0 , 0 , -1 , 0 , 0 , 2 , -1 , 0 , 0 , 0 , 0 },
{ 0 , 0 , 0 , 0 , 0 , -1 , 1 , 0 , 1 , 0 , 0 },
{ 0 , 1 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 },
{ 0 , 0 , 0 , 0 , -1 , 1 , 0 , 0 , 0 , 0 , 0 },
{ 0 , 0 , -1 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , -1 },
};
for (int i=1; i<=numVariables; i++) {
for (int j=1; j<=numVariables+1; j++) {
EXPECT_EQ(expected[i][j], matrix[i][j]);
}
}
}
<|endoftext|> |
<commit_before>// eigenfaces.cpp : eigenfaces alg for the face recognition
// - Some code is from OpenCV src
//
// @author wenlong
//
// The PCA finds a linear combination of features that maximizes the total variance in data;
// It doesn't consider any classes and so a lot of discriminative information may be lost when throwing components away.
//
#include "stdafx.h"
#include "eigenfaces.h"
//typedef vector<vector<Mat> > MatMatrix ;
//typedef vector<vector<int> > IntMatrix ;
using namespace cv;
using namespace std;
//namespace fs = boost::filesystem;
// dataset in each subject
const int SUBJECT_DATA = 12;
//Preparing the data
//These two functions are from Face Recognition src in OpenCV doc
static Mat norm_0_255(InputArray _src) {
Mat src = _src.getMat();
// Create and return normalized image:
Mat dst;
switch (src.channels()) {
case 1:
cv::normalize(_src, dst, 0, 255, NORM_MINMAX, CV_8UC1);
break;
case 3:
cv::normalize(_src, dst, 0, 255, NORM_MINMAX, CV_8UC3);
break;
default:
src.copyTo(dst);
break;
}
return dst;
}
static vector<string> split(const char *str, char c = '\\' )
{
vector<string> result;
do
{
const char *begin = str;
while (*str != c && *str)
str++;
result.push_back(string(begin, str));
} while (0 != *str++);
return result;
}
static string get_dir(const string& filename, const string& outpath)
{
//TODO: using the Boost for this function
/*
//int length = path.length();
//boost::regex replaceRegex("\\\\");
//string result = boost::regex_replace(path, replaceRegex, "/", boost::match_default | boost::format_all);
//result = result.substr(0, result.rfind("/"));
boost::filesystem::path p = path;
boost::filesystem::path p1 = p.parent_path();
boost::filesystem::path p2 = p1.filename();
cout << p2 << endl;
cout << p2.string() << endl;
fs::path file = filename;
string dir = file.parent_path().filename().string();
cout << outpath + dir << endl;
*/
//e:\wenlong\documents\code\opencv\eigenfaces\x64\Debug\input_\crop_00005\crop_00005fa010_930831-new.jpg
vector<string> s = split(filename.c_str());
//cout << s[9] << endl;
//get the full output name
string output = outpath + s[9] + "\\";
return output;
}
static void read_csv_(const string& filename, vector<Mat>& images, vector<int>& labels, char separator = ';') {
std::ifstream file(filename.c_str(), ifstream::in);
if (!file) {
string error_message = "No valid input file was given, please check the given filename.";
CV_Error(CV_StsBadArg, error_message);
}
string line, path, classlabel;
while (getline(file, line)) {
stringstream liness(line);
getline(liness, path, separator);
getline(liness, classlabel);
if (!path.empty() && !classlabel.empty()) {
//Mat im = imread(path, 0);
//images.push_back(imread(path, 0));
//Mat image = imread(path, CV_LOAD_IMAGE_GRAYSCALE);
images.push_back(imread(path, CV_LOAD_IMAGE_GRAYSCALE));
/*
Mat im1 = im.clone();
if ( !im1.isContinuous())
{
// .bmp files sometimes are 'padded' to multiples of 4
// * convert the images to png, pbm or
// * use im.clone() - the deep copy will force continuity
//
//Mat im = im.clone();
cout <<"out" << endl;
}
*/
labels.push_back(atoi(classlabel.c_str()));
}
}
}
static void get_result(vector<Mat>& images, vector<int>& labels, const string& output_folder)
{
// quit if there are not enough images (at least 2 images to work)
if (images.size() <= 1)
{
string error_message = " Needs more images to data set ...";
CV_Error(CV_StsError, error_message);
}
// get the height from the first image for the output
int height = images[0].rows;
// For eigen and fisherfaces, the images have to flatten it to one row; the lbp one doesn't
for (int index = 0; index < images.size(); ++index)
images[index] = images[index].reshape(1, 1);
// the last image in each dataset is the test data
Mat testSample = images[images.size() - 1];
int testLabel = labels[labels.size() - 1];
images.pop_back();
labels.pop_back();
// create an Eigenfaces model for face recognition and train it with the images and labels
// class FaceRecognizer : Algorithm
// TODO: the FaceRecognizer class, and the derived classes
Ptr<FaceRecognizer> model = createEigenFaceRecognizer();
model->train(images, labels);
// predicts the label of a given test image
//int predictedLabel = 0;
//double confidence = 0.0;
//model->predict(testSample, predictedLabel, confidence);
int predictedLabel = model->predict(testSample);
// the confidence
string result_message = format("Predicted class = %d / Actual class = %d .", predictedLabel, testLabel);
cout << result_message << endl;
// get the eigenvalues of this Eigenfaces model
Mat eigenvalues = model->getMat("eigenvalues");
// the Eigenvectors
Mat W = model->getMat("eigenvectors");
// the sample mean from the training data
Mat mean = model->getMat("mean");
// display the mean picture
//if (argc == 2)
//{
// imshow("mean", norm_0_255(mean.reshape(1, height)));
//} else {
imwrite(format("%s\\mean.png", output_folder.c_str()), norm_0_255(mean.reshape(1, height)));
//}
// display the Eigenfaces
for (int i = 0; i < min(10, W.cols); i++)
{
string msg = format("Eigenvalue #%d = %.5f", i, eigenvalues.at<double>(i));
cout << msg << endl;
// get eigenvector #i
Mat ev = W.col(i).clone();
// reshape to original size & normalize to [0...255] for imshow
//ev = ev.reshape(1, height);
Mat grayscale = norm_0_255(ev.reshape(1, height));
// show the image & apply a Jet colormap for better sensing
Mat cgrayscale;
applyColorMap(grayscale, cgrayscale, COLORMAP_JET);
// display or save
//if (argc == 2)
//{
// imshow(format("eigenface_%d", i), cgrayscale);
//} else {
imwrite(format("%s\\eigenface_%d.png", output_folder.c_str(), i), norm_0_255(cgrayscale));
//}
}
}
static void read_csv(const string& filename, const string& output_folder, char separator = ';') {
std::ifstream file(filename.c_str(), ifstream::in);
if (!file) {
string error_message = "No valid input file was given, please check the given filename.";
CV_Error(CV_StsBadArg, error_message);
}
// The vectors hold the images and corresponding labels based on the csv format
vector<Mat> images;
vector<int> labels;
//store the subjects
//vector<vector<Mat> > mat_matrix;
//vector<vector<int> > label_matrix;
int num = 1;
//the index of subject
int index = 1;
string line, path, classlabel;
while (getline(file, line)) {
stringstream liness(line);
getline(liness, path, separator);
getline(liness, classlabel);
if (!path.empty() && !classlabel.empty()) {
//Mat im = imread(path, 0);
//images.push_back(imread(path, 0));
Mat image = imread(path, CV_LOAD_IMAGE_GRAYSCALE);
images.push_back(image);
/*
Mat im1 = im.clone();
if ( !im1.isContinuous())
{
.bmp files sometimes are 'padded' to multiples of 4
* convert the images to png, pbm or
* use im.clone() - the deep copy will force continuity
Mat im = im.clone();
cout <<"out" << endl;
}
*/
labels.push_back(atoi(classlabel.c_str()));
// for each subject
if ((num % SUBJECT_DATA) == 0)
{
//mat_matrix.push_back(images);
//label_matrix.push_back(labels);
cout << "For the subject num: " << index << endl;
//mkdir
string dir = get_dir(path, output_folder);
_mkdir(dir.c_str());
// get the calculation results
get_result(images, labels, dir);
//
images.clear();
labels.clear();
cout << "-----------------------------"<< endl;
//next suject
index++;
}
num++;
}
}
/*
//print out
for (int i = 0; i < mat_matrix.size(); i++)
{
for (int j = 0; j < mat_matrix[i].size(); i++)
cout << mat_matrix[i][j] <<":"<< label_matrix[i][j] << " ";
cout << endl;
}
*/
}
int main(int argc, const char* argv[])
{
/*
if (argc < 2)
{
cout << "usage: " << argv[0] << " <csv.ext> <output_folder>" << endl;
exit(1);
}
*/
argv[1] = "e:\\wenlong\\documents\\code\\opencv\\eigenfaces\\x64\\Debug\\input_.txt";
argv[2] = "E:\\wenlong\\documents\\code\\opencv\\eigenfaces\\x64\\Debug\\output\\";
//string output_folder = ".";
string output_folder = argv[2];
/*
if (argc == 3)
{
output_folder = string(argv[2]);
}
*/
// get the path to the csv
string fn_csv = string(argv[1]);
// The vectors hold the images and corresponding labels based on the csv format
//vector<Mat> images;
//store the subjects
//vector<vector<Mat> > mat_matrix;
//vector<vector<int> > label_matrix;
// read the csv file
try {
read_csv(fn_csv, output_folder);
} catch (cv::Exception& e){
cerr << "Error opening file \"" << fn_csv << "\". Reason: " << e.msg << endl;
exit(1);
}
// display if we are not writing to an output folder
//if (argc == 2)
//{
waitKey(0);
//}
return 0;
}
<commit_msg>update<commit_after>// eigenfaces.cpp : eigenfaces alg for the face recognition
// - Some code is from OpenCV src
//
// @author wenlong
//
// The PCA finds a linear combination of features that maximizes the total variance in data;
// It doesn't consider any classes and so a lot of discriminative information may be lost when throwing components away.
//
// TODO:
// 1. Generalization
// - save the model of each subject
// - use the trained model to test the test dataset
//
// 2. Calculate verification rate and false accept rate
//
#include "stdafx.h"
#include "eigenfaces.h"
//typedef vector<vector<Mat> > MatMatrix ;
//typedef vector<vector<int> > IntMatrix ;
using namespace cv;
using namespace std;
//namespace fs = boost::filesystem;
// dataset in each subject
const int SUBJECT_DATASET = 12;
// size of the training dataset
const int TRAINING_DATASET = 6;
// test dataset
const int TEST_DATASET = 6;
// feature num
//The number of components(read: Eigenfaces) kept for this Prinicpal Component Analysis.
//As a hint : Theres no rule how many components(read : Eigenfaces) should be kept for good reconstruction capabilities.
//It is based on your input data, so experiment with the number.
//Keeping 80 components should almost always be sufficient.
const int FEATURE_NUM = 80;
// threshold
double THRESHOLD = 0.5;
//Preparing the data
//The function is from Face Recognition src in OpenCV doc
static Mat norm_0_255(InputArray _src) {
Mat src = _src.getMat();
// Create and return normalized image:
Mat dst;
switch (src.channels()) {
case 1:
cv::normalize(_src, dst, 0, 255, NORM_MINMAX, CV_8UC1);
break;
case 3:
cv::normalize(_src, dst, 0, 255, NORM_MINMAX, CV_8UC3);
break;
default:
src.copyTo(dst);
break;
}
return dst;
}
static vector<string> split(const char *str, char c = '\\' )
{
vector<string> result;
do
{
const char *begin = str;
while (*str != c && *str)
str++;
result.push_back(string(begin, str));
} while (0 != *str++);
return result;
}
static string get_dir(const string& filename, const string& outpath)
{
//TODO: using the Boost lib for this function
/*
//int length = path.length();
//boost::regex replaceRegex("\\\\");
//string result = boost::regex_replace(path, replaceRegex, "/", boost::match_default | boost::format_all);
//result = result.substr(0, result.rfind("/"));
boost::filesystem::path p = path;
boost::filesystem::path p1 = p.parent_path();
boost::filesystem::path p2 = p1.filename();
cout << p2 << endl;
cout << p2.string() << endl;
fs::path file = filename;
string dir = file.parent_path().filename().string();
cout << outpath + dir << endl;
*/
//e:\wenlong\documents\code\opencv\eigenfaces\x64\Debug\input_\crop_00005\crop_00005fa010_930831-new.jpg
vector<string> s = split(filename.c_str());
//cout << s[9] << endl;
//get the full output name
string output = outpath + s[9] + "\\";
return output;
}
static void read_csv_(const string& filename, vector<Mat>& images, vector<int>& labels, char separator = ';') {
std::ifstream file(filename.c_str(), ifstream::in);
if (!file) {
string error_message = "No valid input file was given, please check the given filename.";
CV_Error(CV_StsBadArg, error_message);
}
string line, path, classlabel;
while (getline(file, line)) {
stringstream liness(line);
getline(liness, path, separator);
getline(liness, classlabel);
if (!path.empty() && !classlabel.empty()) {
//Mat im = imread(path, 0);
//images.push_back(imread(path, 0));
//Mat image = imread(path, CV_LOAD_IMAGE_GRAYSCALE);
images.push_back(imread(path, CV_LOAD_IMAGE_GRAYSCALE));
/*
Mat im1 = im.clone();
if ( !im1.isContinuous())
{
// .bmp files sometimes are 'padded' to multiples of 4
// * convert the images to png, pbm or
// * use im.clone() - the deep copy will force continuity
//
//Mat im = im.clone();
cout <<"out" << endl;
}
*/
//The labels corresponding to the images
labels.push_back(atoi(classlabel.c_str()));
}
}
}
static int write_file(const string& output_folder, const string& str)
{
ofstream file;
file.open(output_folder + "rate.txt");
file << str << endl;
file.close();
}
static string get_result(ofstream& logstream, vector<Mat>& images, vector<int>& labels, const string& output_folder)
{
// quit if there are not enough images (at least 2 images to work)
if (images.size() <= 1)
{
string error_message = " Needs more images to data set ...";
CV_Error(CV_StsError, error_message);
}
// get the height from the first image for the output
int height = images[0].rows;
/*
// the last image in each dataset is the test data
Mat testSample = images[images.size() - 1];
int testLabel = labels[labels.size() - 1];
images.pop_back();
labels.pop_back();
*/
vector<Mat> trainingSamples, testSamples;
vector<int> trainingLabels, testLabels;
for (int i = 0; i < images.size(); ++i)
{
//THE EIGENFACES METHOD MAKES THE ASSUMPTION, THAT THE TRAINING AND TEST IMAGES ARE OF EQUAL SIZE
// For eigen and fisherfaces, the images have to flatten it to one row; the lbp one doesn't
//images[i] = images[i].reshape(1, 1);
// the traing dataset
if (i < TRAINING_DATASET)
{
trainingSamples.push_back(images[i].reshape(1, 1));
trainingLabels.push_back(labels[i]);
}
// the test dataset
if (i >= TEST_DATASET)
{
testSamples.push_back(images[i].reshape(1,1));
testLabels.push_back(labels[i]);
}
}
/* ----- train the model ----- */
// create an Eigenfaces model for face recognition and train it with the images and labels
// class FaceRecognizer : Algorithm
// TODO: the FaceRecognizer class, and the derived classes
//
// The features num
//The number of components (read: Eigenfaces) kept for this Prinicpal Component Analysis
//int FEATURE_NUM = 10;
// The threshold applied in the prediction.
// If the distance to the nearest neighbor is larger than the threshold, this method returns -1
//double threshold = 10.0;
Ptr<FaceRecognizer> model = createEigenFaceRecognizer(FEATURE_NUM, THRESHOLD);
model->train(trainingSamples, trainingLabels);
/* ----- test the model ----- */
int num = 0;
// test each image
for (int i = 0; i < testSamples.size(); ++i)
{
// predicts the label of a given test image;
// -1 as label, which indicates this face is unknown
int predictedLabel = -1;
// Associated confidence (e.g. distance) for the predicted label.
double confidence = 0.0;
model->predict(testSamples[i], predictedLabel, confidence);
//int predictedLabel = model->predict(testSample);
// the confidence
string result_message = format("Predicted class = %d / Actual class = %d .", predictedLabel, testLabels[i]);
cout << result_message << endl;
logstream << result_message << endl;
if ( predictedLabel == testLabels[i])
{
num++;
}
}
double confidence_rate = num / (double)TEST_DATASET;
string confidence_rate_message = format("%.2f", confidence_rate);
cout << confidence_rate_message << endl;
logstream << confidence_rate_message << endl;
/* ----- display the result ----- */
// get the eigenvalues of this Eigenfaces model in ordered descending
Mat eigenvalues = model->getMat("eigenvalues");
// the eigenvectors ordered by the eigenvalues
Mat W = model->getMat("eigenvectors");
// the sample mean from the training data
Mat mean = model->getMat("mean");
// display the mean picture
//if (argc == 2)
//{
// imshow("mean", norm_0_255(mean.reshape(1, height)));
//} else {
imwrite(format("%s\\mean.png", output_folder.c_str()), norm_0_255(mean.reshape(1, height)));
//}
// display the Eigenfaces
for (int i = 0; i < min(10, W.cols); i++)
{
string msg = format("Eigenvalue #%d = %.5f", i, eigenvalues.at<double>(i));
cout << msg << endl;
logstream << msg << endl;
// get eigenvector #i
Mat ev = W.col(i).clone();
// reshape to original size & normalize to [0...255] for imshow
//ev = ev.reshape(1, height);
Mat grayscale = norm_0_255(ev.reshape(1, height));
// show the image & apply a Jet colormap for better sensing
Mat cgrayscale;
applyColorMap(grayscale, cgrayscale, COLORMAP_JET);
// display or save
//if (argc == 2)
//{
// imshow(format("eigenface_%d", i), cgrayscale);
//} else {
imwrite(format("%s\\eigenface_%d.png", output_folder.c_str(), i), norm_0_255(cgrayscale));
//}
}
// write the file
//ofstream file;
//file.open(output_folder + "rate.txt");
string write_content = to_string(testLabels[0]) + ":" + confidence_rate_message;
//file << write_content << endl;
//file.close();
return write_content;
}
/*
read_csv -
- Load the dataset
*/
static void read_csv(ofstream& logstream, const string& filename, const string& output_folder, char separator = ';') {
std::ifstream file(filename.c_str(), ifstream::in);
if (!file) {
string error_message = "No valid input file was given, please check the given filename.";
CV_Error(CV_StsBadArg, error_message);
}
// open the file
ofstream fstream;
fstream.open(output_folder + "rate.txt");
// The vectors hold the images and corresponding labels based on the csv format
vector<Mat> images;
vector<int> labels;
//store the subjects
//vector<vector<Mat> > mat_matrix;
//vector<vector<int> > label_matrix;
int num = 1;
//the index of subject
int index = 0;
string line, path, classlabel;
while (getline(file, line)) {
stringstream liness(line);
getline(liness, path, separator);
getline(liness, classlabel);
if (!path.empty() && !classlabel.empty()) {
//Mat im = imread(path, 0);
//images.push_back(imread(path, 0));
Mat image = imread(path, CV_LOAD_IMAGE_GRAYSCALE);
images.push_back(image);
/*
Mat im1 = im.clone();
if ( !im1.isContinuous())
{
.bmp files sometimes are 'padded' to multiples of 4
* convert the images to png, pbm or
* use im.clone() - the deep copy will force continuity
Mat im = im.clone();
cout <<"out" << endl;
}
*/
labels.push_back(atoi(classlabel.c_str()));
// for each subject
if ((num % SUBJECT_DATASET) == 0)
{
//mat_matrix.push_back(images);
//label_matrix.push_back(labels);
cout << "For the subject num: " << index << endl;
logstream << "For the subject num: " + to_string(index) << endl;
//mkdir
string dir = get_dir(path, output_folder);
_mkdir(dir.c_str());
// get the calculation results
string str = get_result(logstream, images, labels, dir);
fstream << str << endl;
//
images.clear();
labels.clear();
cout << "-----------------------------" << endl;
logstream << "-----------------------------" << endl;
//next suject
index++;
}
num++;
}
}
/*
//print out
for (int i = 0; i < mat_matrix.size(); i++)
{
for (int j = 0; j < mat_matrix[i].size(); i++)
cout << mat_matrix[i][j] <<":"<< label_matrix[i][j] << " ";
cout << endl;
}
*/
fstream.close();
}
int main(int argc, const char* argv[])
{
/*
if (argc < 2)
{
cout << "usage: " << argv[0] << " <csv.ext> <output_folder>" << endl;
exit(1);
}
*/
argv[1] = "e:\\wenlong\\documents\\code\\opencv\\eigenfaces\\x64\\Debug\\input_.txt";
argv[2] = "E:\\wenlong\\documents\\code\\opencv\\eigenfaces\\x64\\Debug\\output\\";
//string output_folder = ".";
string output_folder = argv[2];
/*
if (argc == 3)
{
output_folder = string(argv[2]);
}
*/
// get the path to the csv
string fn_csv = string(argv[1]);
//open the log file
ofstream logstream;
logstream.open(output_folder + "log.txt");
// The vectors hold the images and corresponding labels based on the csv format
//vector<Mat> images;
//store the subjects
//vector<vector<Mat> > mat_matrix;
//vector<vector<int> > label_matrix;
// read the csv file
try {
read_csv(logstream, fn_csv, output_folder);
} catch (cv::Exception& e){
cerr << "Error opening file \"" << fn_csv << "\". Reason: " << e.msg << endl;
exit(1);
}
// display if we are not writing to an output folder
//if (argc == 2)
//{
waitKey(0);
//}
logstream.close();
return 0;
}
<|endoftext|> |
<commit_before>/* -*- mode: C++; c-basic-offset: 2; indent-tabs-mode: nil -*- */
/*
* Main authors:
* Guido Tack <[email protected]>
* Modified:
* Laurent Perron ([email protected])
*
* Copyright:
* Guido Tack, 2007
*
*
* This file is part of Gecode, the generic constraint
* development environment:
* http://www.gecode.org
*
* 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 <iostream>
#include <fstream>
#include <cstring>
#include "base/commandlineflags.h"
#include "base/commandlineflags.h"
#include "base/integral_types.h"
#include "base/logging.h"
#include "base/scoped_ptr.h"
#include "base/stringprintf.h"
#include "flatzinc/flatzinc.h"
DEFINE_int32(log_frequency, 100000, "Search log frequency");
DEFINE_bool(log, false, "Show search log");
DEFINE_bool(all, false, "Search for all solutions");
DEFINE_bool(free, false, "Ignore search annotations");
DEFINE_int32(num_solutions, 0, "Number of solution to search for");
DEFINE_int32(time_limit, 0, "time limit in ms");
DECLARE_bool(log_prefix);
namespace operations_research {
void Run(const std::string& file) {
FlatZincModel fz_model;
if (file == "-") {
fz_model.Parse(std::cin);
} else {
fz_model.Parse(file);
}
fz_model.Solve(FLAGS_log_frequency,
FLAGS_log,
FLAGS_all,
FLAGS_free,
FLAGS_num_solutions,
FLAGS_time_limit);
}
}
int main(int argc, char** argv) {
FLAGS_log_prefix=false;
google::ParseCommandLineFlags(&argc, &argv, true);
if (argc <= 1) {
LOG(ERROR) << "Usage: " << argv[0] << " <file>";
exit(EXIT_FAILURE);
}
operations_research::Run(argv[1]);
return 0;
}
<commit_msg>support official flags -p, -f, -a<commit_after>/* -*- mode: C++; c-basic-offset: 2; indent-tabs-mode: nil -*- */
/*
* Main authors:
* Guido Tack <[email protected]>
* Modified:
* Laurent Perron ([email protected])
*
* Copyright:
* Guido Tack, 2007
*
*
* This file is part of Gecode, the generic constraint
* development environment:
* http://www.gecode.org
*
* 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 <iostream>
#include <fstream>
#include <cstring>
#include "base/commandlineflags.h"
#include "base/commandlineflags.h"
#include "base/integral_types.h"
#include "base/logging.h"
#include "base/scoped_ptr.h"
#include "base/stringprintf.h"
#include "flatzinc/flatzinc.h"
DEFINE_int32(log_frequency, 100000, "Search log frequency");
DEFINE_bool(log, false, "Show search log");
DEFINE_bool(all, false, "Search for all solutions");
DEFINE_bool(free, false, "Ignore search annotations");
DEFINE_int32(num_solutions, 0, "Number of solution to search for");
DEFINE_int32(time_limit, 0, "time limit in ms");
DEFINE_int32(threads, 0, "threads");
DECLARE_bool(log_prefix);
namespace operations_research {
void Run(const std::string& file) {
FlatZincModel fz_model;
if (file == "-") {
fz_model.Parse(std::cin);
} else {
fz_model.Parse(file);
}
fz_model.Solve(FLAGS_log_frequency,
FLAGS_log,
FLAGS_all,
FLAGS_free,
FLAGS_num_solutions,
FLAGS_time_limit);
}
}
int main(int argc, char** argv) {
FLAGS_log_prefix=false;
for (int i = 1; i < argc; ++i) {
if (strcmp(argv[i], "-a") == 0) {
argv[i] = "--all";
}
if (strcmp(argv[i], "-f") == 0) {
argv[i] = "--free";
}
if (strcmp(argv[i], "-p") == 0) {
argv[i] = "--threads";
}
}
google::ParseCommandLineFlags(&argc, &argv, true);
if (argc <= 1) {
LOG(ERROR) << "Usage: " << argv[0] << " <file>";
exit(EXIT_FAILURE);
}
operations_research::Run(argv[1]);
return 0;
}
<|endoftext|> |
<commit_before>// =============================================================================
// This file is part of:
// Dynamic Adaptive System for Hierarchical Multipole Methods (DASHMM)
//
// Copyright (c) 2015-2016, Trustees of Indiana University,
// All rights reserved.
//
// DASHMM is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// DASHMM 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 DASHMM. If not, see <http://www.gnu.org/licenses/>.
//
// This software was created at the Indiana University Center for Research in
// Extreme Scale Technologies (CREST).
// =============================================================================
#include "builtins/fmm97distro.h"
#include <algorithm>
#include <map>
#include <limits>
namespace dashmm {
void FMM97Distro::compute_distribution(DAG &dag) {
// color all the DAG node
for (size_t i = 0; i < dag.source_leaves.size(); ++i) {
DAGNode *s = dag.source_leaves[i];
s->color = 0;
color(s);
}
// Confine M and I of the source tree
for (size_t i = 0; i < dag.source_leaves.size(); ++i) {
DAGNode *n = dag.source_leaves[i];
assert(n->locality != -1);
confine(n, 's');
}
// Confine L of the target tree
for (size_t i = 0; i < dag.target_leaves.size(); ++i) {
DAGNode *n = dag.target_leaves[i];
assert(n->locality != -1);
confine(n, 't');
}
// Make decision on I of the target tree
for (size_t i = 0; i < dag.target_nodes.size(); ++i) {
DAGNode *n = dag.target_nodes[i];
if (n->locality == -1)
assign(n);
}
}
void FMM97Distro::color(DAGNode *s) {
for (size_t i = 0; i < s->out_edges.size(); ++i) {
DAGNode *t = s->out_edges[i].target;
t->color = std::max(t->color, s->color + 1);
color(t);
}
}
void FMM97Distro::confine(DAGNode *n, char type) {
assert(type == 's' || type == 't');
// Note: there may be multiple times \param n is visited.
if (type == 's') {
for (size_t i = 0; i < n->out_edges.size(); ++i) {
DAGNode *target = n->out_edges[i].target;
Operation op = n->out_edges[i].op;
bool terminate = true;
if (target->locality == -1) {
if (op == Operation::MtoM || op == Operation::MtoI)
target->locality = n->locality;
if (op == Operation::MtoM)
terminate = false;
} else if (op == Operation::StoM) {
terminate = false;
}
if (terminate == false)
confine(target, type);
}
} else {
for (size_t i = 0; i < n->in_edges.size(); ++i) {
DAGNode *source = n->in_edges[i].source;
Operation op = n->in_edges[i].op;
bool terminate = true;
if (source->locality == -1) {
if (op == Operation::LtoL) {
source->locality = n->locality;
terminate = false;
}
} else if (op == Operation::LtoT) {
terminate = false;
}
if (terminate == false)
confine(source, type);
}
}
}
void FMM97Distro::assign(DAGNode *n) {
// \param n is the expansion LCO for an intermediate expansion of
// the target tree.
// Compute communication cost if \param n and the DAGNodes of its
// \param out_edges are placed on different localities.
int target_locality = n->out_edges[0].target->locality;
int out_weight = n->out_edges.size() * n->out_edges[0].weight;
// Categorize incoming edges
std::map<int, int> color;
std::map<int, int> weight;
int in_weight = 0;
for (size_t i = 0; i < n->in_edges.size(); ++i) {
int w = n->in_edges[i].weight;
int c = n->in_edges[i].source->color;
int source_locality = n->in_edges[i].source->locality;
color[source_locality] = std::max(color[source_locality], c);
weight[source_locality] += w;
in_weight += w;
}
int min_weight = std::numeric_limits<int>::max();
int max_color = std::numeric_limits<int>::min();
int locality = -1;
for (auto i = weight.begin(); i != weight.end(); ++i) {
int source_locality = i->first;
int w = i->second + out_weight * (source_locality != target_locality);
int c = color[source_locality];
if (w < min_weight) {
min_weight = w;
max_color = c;
locality = source_locality;
} else if (w == min_weight && c > max_color) {
max_color = c;
locality = source_locality;
}
}
n->locality = locality;
assert(locality != -1);
}
} // dashmm
<commit_msg>temporary fix<commit_after>// =============================================================================
// This file is part of:
// Dynamic Adaptive System for Hierarchical Multipole Methods (DASHMM)
//
// Copyright (c) 2015-2016, Trustees of Indiana University,
// All rights reserved.
//
// DASHMM is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// DASHMM 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 DASHMM. If not, see <http://www.gnu.org/licenses/>.
//
// This software was created at the Indiana University Center for Research in
// Extreme Scale Technologies (CREST).
// =============================================================================
#include <hpx/hpx.h>
#include "builtins/fmm97distro.h"
#include <algorithm>
#include <map>
#include <limits>
namespace dashmm {
void FMM97Distro::compute_distribution(DAG &dag) {
// color all the DAG node
for (size_t i = 0; i < dag.source_leaves.size(); ++i) {
DAGNode *s = dag.source_leaves[i];
s->color = 0;
color(s);
}
// Confine M and I of the source tree
for (size_t i = 0; i < dag.source_leaves.size(); ++i) {
DAGNode *n = dag.source_leaves[i];
assert(n->locality != -1);
confine(n, 's');
}
// Assert all the source nodes have their locality fixed
for (size_t i = 0; i < dag.source_nodes.size(); ++i) {
DAGNode *n = dag.source_nodes[i];
if (n->idx.level() < 3)
n->locality = 0;
assert(n->locality != -1);
}
// Confine L of the target tree
for (size_t i = 0; i < dag.target_leaves.size(); ++i) {
DAGNode *n = dag.target_leaves[i];
assert(n->locality != -1);
confine(n, 't');
}
for (size_t i = 0; i < dag.target_nodes.size(); ++i) {
DAGNode *n = dag.target_nodes[i];
if (n->idx.level() < 3)
n->locality = 0;
assert(n->locality != -1);
}
// Make decision on I of the target tree
for (size_t i = 0; i < dag.target_nodes.size(); ++i) {
DAGNode *n = dag.target_nodes[i];
if (n->locality == -1)
assign(n);
}
// Assert all the target nodes have their locality fixed
for (size_t i = 0; i < dag.target_nodes.size(); ++i) {
DAGNode *n = dag.target_nodes[i];
assert(n->locality != -1);
}
}
void FMM97Distro::color(DAGNode *s) {
for (size_t i = 0; i < s->out_edges.size(); ++i) {
DAGNode *t = s->out_edges[i].target;
t->color = std::max(t->color, s->color + 1);
color(t);
}
}
void FMM97Distro::confine(DAGNode *n, char type) {
assert(type == 's' || type == 't');
// Note: there may be multiple times \param n is visited.
if (type == 's') {
for (size_t i = 0; i < n->out_edges.size(); ++i) {
DAGNode *target = n->out_edges[i].target;
Operation op = n->out_edges[i].op;
bool terminate = true;
if (target->locality == -1) {
if (op == Operation::MtoM || op == Operation::MtoI)
target->locality = n->locality;
if (op == Operation::MtoM)
terminate = false;
} else if (op == Operation::StoM) {
terminate = false;
}
if (terminate == false)
confine(target, type);
}
} else {
for (size_t i = 0; i < n->in_edges.size(); ++i) {
DAGNode *source = n->in_edges[i].source;
Operation op = n->in_edges[i].op;
bool terminate = true;
if (source->locality == -1) {
if (op == Operation::LtoL) {
source->locality = n->locality;
terminate = false;
}
} else if (op == Operation::LtoT) {
terminate = false;
}
if (terminate == false)
confine(source, type);
}
}
/*
if (type == 's') {
for (size_t i = 0; i < n->out_edges.size(); ++i) {
DAGNode *target = n->out_edges[i].target;
Operation op = n->out_edges[i].op;
bool terminate = true;
if (op == Operation::MtoI) {
target->locality = n->locality;
}
if (op == Operation::MtoM) {
if (n->locality > target->locality) {
target->locality = n->locality;
terminate = false;
}
}
if (op == Operation::StoM)
terminate = false;
if (terminate == false)
confine(target, type);
}
} else {
for (size_t i = 0; i < n->in_edges.size(); ++i) {
DAGNode *source = n->in_edges[i].source;
Operation op = n->in_edges[i].op;
bool terminate = true;
if (op == Operation::LtoT)
terminate = false;
if (op == Operation::LtoL) {
if (n->locality > source->locality) {
source->locality = n->locality;
terminate = false;
}
}
if (terminate == false)
confine(source, type);
}
}
*/
}
void FMM97Distro::assign(DAGNode *n) {
// \param n is the expansion LCO for an intermediate expansion of
// the target tree.
// Compute communication cost if \param n and the DAGNodes of its
// \param out_edges are placed on different localities.
int target_locality = n->out_edges[0].target->locality;
int out_weight = n->out_edges.size() * n->out_edges[0].weight;
// Categorize incoming edges
std::map<int, int> color;
std::map<int, int> weight;
int in_weight = 0;
for (size_t i = 0; i < n->in_edges.size(); ++i) {
int w = n->in_edges[i].weight;
int c = n->in_edges[i].source->color;
int source_locality = n->in_edges[i].source->locality;
color[source_locality] = std::max(color[source_locality], c);
weight[source_locality] += w;
in_weight += w;
}
int min_weight = std::numeric_limits<int>::max();
int max_color = std::numeric_limits<int>::min();
int locality = -1;
for (auto i = weight.begin(); i != weight.end(); ++i) {
int source_locality = i->first;
int w = i->second + out_weight * (source_locality != target_locality);
int c = color[source_locality];
if (w < min_weight) {
min_weight = w;
max_color = c;
locality = source_locality;
} else if (w == min_weight && c > max_color) {
max_color = c;
locality = source_locality;
}
}
n->locality = locality;
assert(locality != -1);
}
} // dashmm
<|endoftext|> |
<commit_before>#include "amftest.hpp"
#include "deserializer.hpp"
#include "deserializationcontext.hpp"
#include "types/amfarray.hpp"
#include "types/amfbool.hpp"
#include "types/amfbytearray.hpp"
#include "types/amfdate.hpp"
#include "types/amfdictionary.hpp"
#include "types/amfdouble.hpp"
#include "types/amfinteger.hpp"
#include "types/amfnull.hpp"
#include "types/amfobject.hpp"
#include "types/amfstring.hpp"
#include "types/amfundefined.hpp"
#include "types/amfvector.hpp"
#include "types/amfxml.hpp"
#include "types/amfxmldocument.hpp"
#include "utils/amfitemptr.hpp"
template<typename T>
static void deserializesTo(const T& expected, v8 data, int left = 0) {
SCOPED_TRACE(::testing::PrintToString(expected) + " = " + ::testing::PrintToString(data));
auto it = data.cbegin();
try {
Deserializer d;
T i = d.deserialize(it, data.cend()).as<T>();
ASSERT_EQ(expected, i);
T j = *d.deserialize(data).asPtr<T>();
ASSERT_EQ(expected, j);
DeserializationContext ctx;
T k = Deserializer::deserialize(data, ctx).as<T>();
ASSERT_EQ(expected, k);
} catch(std::exception& e) {
FAIL() << "Deserialization threw exception:\n"
<< e.what() ;
}
ASSERT_EQ(left, data.cend() - it)
<< "Expected " << left
<< " bytes left, got " << (data.cend() - it)
<< " bytes left";
}
TEST(DeserializerTest, Undefined) {
deserializesTo(AmfUndefined(), { 0x00 });
deserializesTo(AmfUndefined(), { 0x00, 0x00 }, 1);
}
TEST(DeserializerTest, Null) {
deserializesTo(AmfNull(), { 0x01 });
deserializesTo(AmfNull(), { 0x01, 0x01 }, 1);
}
TEST(DeserializerTest, Bool) {
deserializesTo(AmfBool(false), { 0x02 });
deserializesTo(AmfBool(false), { 0x02, 0x02 }, 1);
deserializesTo(AmfBool(true), { 0x03 });
deserializesTo(AmfBool(true), { 0x03, 0x03 }, 1);
}
TEST(DeserializerTest, Integer) {
deserializesTo(AmfInteger(0x7e), { 0x04, 0x7e });
deserializesTo(AmfInteger(0x7e), { 0x04, 0x7e, 0x04 }, 1);
deserializesTo(AmfInteger(0xffffffe), { 0x04, 0xbf, 0xff, 0xff, 0xfe });
}
TEST(DeserializerTest, Double) {
deserializesTo(AmfDouble(0.5), { 0x05, 0x3F, 0xE0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 });
deserializesTo(AmfDouble(0.5), { 0x05, 0x3F, 0xE0, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00 }, 3);
}
TEST(DeserializerTest, String) {
deserializesTo(AmfString("foo"), { 0x06, 0x07, 0x66, 0x6f, 0x6f });
deserializesTo(AmfString("foo"), { 0x06, 0x07, 0x66, 0x6f, 0x6f, 0x06 }, 1);
}
TEST(DeserializerTest, XmlDoc) {
deserializesTo(AmfXmlDocument(""), { 0x07, 0x01 });
deserializesTo(AmfXmlDocument(""), { 0x07, 0x01, 0x07 }, 1);
deserializesTo(AmfXmlDocument("foo"), { 0x07, 0x07, 0x66, 0x6f, 0x6f });
}
TEST(DeserializerTest, Date) {
deserializesTo(AmfDate(136969002755210ll), { 0x08, 0x01, 0x42, 0xdf, 0x24,
0xa5, 0x30, 0x49, 0x22, 0x80 });
deserializesTo(AmfDate(136969002755210ll), { 0x08, 0x01, 0x42, 0xdf, 0x24,
0xa5, 0x30, 0x49, 0x22, 0x80, 0x08 }, 1);
}
TEST(DeserializerTest, Array) {
deserializesTo(AmfArray(), { 0x09, 0x01, 0x01 });
deserializesTo(AmfArray(std::vector<AmfInteger> { 1, 2, 3 } ), {
0x09, 0x07, 0x01, 0x04, 0x01, 0x04, 0x02, 0x04, 0x03, 0xff }, 1);
}
TEST(DeserializerTest, Xml) {
deserializesTo(AmfXml(""), { 0x0b, 0x01 });
deserializesTo(AmfXml(""), { 0x0b, 0x01, 0x0b }, 1);
deserializesTo(AmfXml("foo"), { 0x0b, 0x07, 0x66, 0x6f, 0x6f });
}
TEST(DeserializerTest, Object) {
deserializesTo(AmfObject("", false, false), { 0x0a, 0x03, 0x01 });
deserializesTo(AmfObject("", true, false), { 0x0a, 0x0b, 0x01, 0x01, 0xff }, 1);
}
TEST(DeserializerTest, ByteArray) {
deserializesTo(AmfByteArray(v8 { 1, 2, 3 }), { 0x0c, 0x07, 0x01, 0x02, 0x03 });
deserializesTo(AmfByteArray(v8 { 1, 2, 3 }), { 0x0c, 0x07, 0x01, 0x02, 0x03, 0x0c }, 1);
}
TEST(DeserializerTest, VectorInt) {
deserializesTo(AmfVector<int> { { 1 }, false}, { 0x0d, 0x03, 0x00,
0x00, 0x00, 0x00, 0x01 });
deserializesTo(AmfVector<int> { { 2, 3 }, true}, { 0x0d, 0x05, 0x01,
0x00, 0x00, 0x00, 0x02, 0x00, 0x00, 0x00, 0x03, 0xff }, 1);
}
TEST(DeserializerTest, VectorUint) {
deserializesTo(AmfVector<unsigned int> { { 1 }, false}, { 0x0e, 0x03, 0x00,
0x00, 0x00, 0x00, 0x01 });
deserializesTo(AmfVector<unsigned int> { { 2, 3 }, true}, { 0x0e, 0x05, 0x01,
0x00, 0x00, 0x00, 0x02, 0x00, 0x00, 0x00, 0x03, 0xff }, 1);
}
TEST(DeserializerTest, VectorDouble) {
deserializesTo(AmfVector<double> { { 0.5 }, false }, { 0x0f, 0x03, 0x00,
0x3f, 0xe0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 });
deserializesTo(AmfVector<double> { { -1.2 }, true }, { 0x0f, 0x03, 0x01,
0xbf, 0xf3, 0x33, 0x33, 0x33, 0x33, 0x33, 0x33, 0xff }, 1);
}
TEST(DeserializerTest, VectorAmfItem) {
AmfVector<AmfInteger> v({1, 2, 3}, "foo", false);
// Need to pass a AmfVector<AmfItem> to compare against, as that's what
// Deserializer::deserialize returns
AmfVector<AmfItem> vc = v;
v8 data {
0x10, 0x07, 0x00,
0x07, 0x66, 0x6f, 0x6f,
0x04, 0x01,
0x04, 0x02,
0x04, 0x03
};
deserializesTo(vc, data);
}
TEST(DeserializerTest, InstanceContext) {
AmfByteArray ba(v8 { 0x1 });
v8 data {
0x0c, 0x03, 0x01,
0x0c, 0x00,
};
Deserializer d;
auto it = data.cbegin();
auto end = data.cend();
ASSERT_EQ(ba, d.deserialize(it, end).as<AmfByteArray>());
ASSERT_EQ(data.cbegin() + 3, it);
ASSERT_EQ(ba, d.deserialize(it, end).as<AmfByteArray>());
ASSERT_EQ(end, it);
}
TEST(DeserializerTest, ClearContext) {
AmfByteArray ba(v8 { 0x1 });
v8 data {
0x0c, 0x03, 0x01,
0x0c, 0x00,
};
Deserializer d;
auto it = data.cbegin();
auto end = data.cend();
ASSERT_EQ(ba, d.deserialize(it, end).as<AmfByteArray>());
d.clearContext();
ASSERT_THROW(d.deserialize(it, end), std::out_of_range);
}
TEST(DeserializerTest, UnknownType) {
Deserializer d;
ASSERT_THROW(d.deserialize({ AMF_DICTIONARY + 1 }), std::invalid_argument);
ASSERT_THROW(d.deserialize({ 0xff }), std::invalid_argument);
}
<commit_msg>Add test for reference with incorrect type.<commit_after>#include "amftest.hpp"
#include "deserializer.hpp"
#include "deserializationcontext.hpp"
#include "types/amfarray.hpp"
#include "types/amfbool.hpp"
#include "types/amfbytearray.hpp"
#include "types/amfdate.hpp"
#include "types/amfdictionary.hpp"
#include "types/amfdouble.hpp"
#include "types/amfinteger.hpp"
#include "types/amfnull.hpp"
#include "types/amfobject.hpp"
#include "types/amfstring.hpp"
#include "types/amfundefined.hpp"
#include "types/amfvector.hpp"
#include "types/amfxml.hpp"
#include "types/amfxmldocument.hpp"
#include "utils/amfitemptr.hpp"
template<typename T>
static void deserializesTo(const T& expected, v8 data, int left = 0) {
SCOPED_TRACE(::testing::PrintToString(expected) + " = " + ::testing::PrintToString(data));
auto it = data.cbegin();
try {
Deserializer d;
T i = d.deserialize(it, data.cend()).as<T>();
ASSERT_EQ(expected, i);
T j = *d.deserialize(data).asPtr<T>();
ASSERT_EQ(expected, j);
DeserializationContext ctx;
T k = Deserializer::deserialize(data, ctx).as<T>();
ASSERT_EQ(expected, k);
} catch(std::exception& e) {
FAIL() << "Deserialization threw exception:\n"
<< e.what() ;
}
ASSERT_EQ(left, data.cend() - it)
<< "Expected " << left
<< " bytes left, got " << (data.cend() - it)
<< " bytes left";
}
TEST(DeserializerTest, Undefined) {
deserializesTo(AmfUndefined(), { 0x00 });
deserializesTo(AmfUndefined(), { 0x00, 0x00 }, 1);
}
TEST(DeserializerTest, Null) {
deserializesTo(AmfNull(), { 0x01 });
deserializesTo(AmfNull(), { 0x01, 0x01 }, 1);
}
TEST(DeserializerTest, Bool) {
deserializesTo(AmfBool(false), { 0x02 });
deserializesTo(AmfBool(false), { 0x02, 0x02 }, 1);
deserializesTo(AmfBool(true), { 0x03 });
deserializesTo(AmfBool(true), { 0x03, 0x03 }, 1);
}
TEST(DeserializerTest, Integer) {
deserializesTo(AmfInteger(0x7e), { 0x04, 0x7e });
deserializesTo(AmfInteger(0x7e), { 0x04, 0x7e, 0x04 }, 1);
deserializesTo(AmfInteger(0xffffffe), { 0x04, 0xbf, 0xff, 0xff, 0xfe });
}
TEST(DeserializerTest, Double) {
deserializesTo(AmfDouble(0.5), { 0x05, 0x3F, 0xE0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 });
deserializesTo(AmfDouble(0.5), { 0x05, 0x3F, 0xE0, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00 }, 3);
}
TEST(DeserializerTest, String) {
deserializesTo(AmfString("foo"), { 0x06, 0x07, 0x66, 0x6f, 0x6f });
deserializesTo(AmfString("foo"), { 0x06, 0x07, 0x66, 0x6f, 0x6f, 0x06 }, 1);
}
TEST(DeserializerTest, XmlDoc) {
deserializesTo(AmfXmlDocument(""), { 0x07, 0x01 });
deserializesTo(AmfXmlDocument(""), { 0x07, 0x01, 0x07 }, 1);
deserializesTo(AmfXmlDocument("foo"), { 0x07, 0x07, 0x66, 0x6f, 0x6f });
}
TEST(DeserializerTest, Date) {
deserializesTo(AmfDate(136969002755210ll), { 0x08, 0x01, 0x42, 0xdf, 0x24,
0xa5, 0x30, 0x49, 0x22, 0x80 });
deserializesTo(AmfDate(136969002755210ll), { 0x08, 0x01, 0x42, 0xdf, 0x24,
0xa5, 0x30, 0x49, 0x22, 0x80, 0x08 }, 1);
}
TEST(DeserializerTest, Array) {
deserializesTo(AmfArray(), { 0x09, 0x01, 0x01 });
deserializesTo(AmfArray(std::vector<AmfInteger> { 1, 2, 3 } ), {
0x09, 0x07, 0x01, 0x04, 0x01, 0x04, 0x02, 0x04, 0x03, 0xff }, 1);
}
TEST(DeserializerTest, Xml) {
deserializesTo(AmfXml(""), { 0x0b, 0x01 });
deserializesTo(AmfXml(""), { 0x0b, 0x01, 0x0b }, 1);
deserializesTo(AmfXml("foo"), { 0x0b, 0x07, 0x66, 0x6f, 0x6f });
}
TEST(DeserializerTest, Object) {
deserializesTo(AmfObject("", false, false), { 0x0a, 0x03, 0x01 });
deserializesTo(AmfObject("", true, false), { 0x0a, 0x0b, 0x01, 0x01, 0xff }, 1);
}
TEST(DeserializerTest, ByteArray) {
deserializesTo(AmfByteArray(v8 { 1, 2, 3 }), { 0x0c, 0x07, 0x01, 0x02, 0x03 });
deserializesTo(AmfByteArray(v8 { 1, 2, 3 }), { 0x0c, 0x07, 0x01, 0x02, 0x03, 0x0c }, 1);
}
TEST(DeserializerTest, VectorInt) {
deserializesTo(AmfVector<int> { { 1 }, false}, { 0x0d, 0x03, 0x00,
0x00, 0x00, 0x00, 0x01 });
deserializesTo(AmfVector<int> { { 2, 3 }, true}, { 0x0d, 0x05, 0x01,
0x00, 0x00, 0x00, 0x02, 0x00, 0x00, 0x00, 0x03, 0xff }, 1);
}
TEST(DeserializerTest, VectorUint) {
deserializesTo(AmfVector<unsigned int> { { 1 }, false}, { 0x0e, 0x03, 0x00,
0x00, 0x00, 0x00, 0x01 });
deserializesTo(AmfVector<unsigned int> { { 2, 3 }, true}, { 0x0e, 0x05, 0x01,
0x00, 0x00, 0x00, 0x02, 0x00, 0x00, 0x00, 0x03, 0xff }, 1);
}
TEST(DeserializerTest, VectorDouble) {
deserializesTo(AmfVector<double> { { 0.5 }, false }, { 0x0f, 0x03, 0x00,
0x3f, 0xe0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 });
deserializesTo(AmfVector<double> { { -1.2 }, true }, { 0x0f, 0x03, 0x01,
0xbf, 0xf3, 0x33, 0x33, 0x33, 0x33, 0x33, 0x33, 0xff }, 1);
}
TEST(DeserializerTest, VectorAmfItem) {
AmfVector<AmfInteger> v({1, 2, 3}, "foo", false);
// Need to pass a AmfVector<AmfItem> to compare against, as that's what
// Deserializer::deserialize returns
AmfVector<AmfItem> vc = v;
v8 data {
0x10, 0x07, 0x00,
0x07, 0x66, 0x6f, 0x6f,
0x04, 0x01,
0x04, 0x02,
0x04, 0x03
};
deserializesTo(vc, data);
}
TEST(DeserializerTest, InstanceContext) {
AmfByteArray ba(v8 { 0x1 });
v8 data {
0x0c, 0x03, 0x01,
0x0c, 0x00,
};
Deserializer d;
auto it = data.cbegin();
auto end = data.cend();
ASSERT_EQ(ba, d.deserialize(it, end).as<AmfByteArray>());
ASSERT_EQ(data.cbegin() + 3, it);
ASSERT_EQ(ba, d.deserialize(it, end).as<AmfByteArray>());
ASSERT_EQ(end, it);
}
TEST(DeserializerTest, ClearContext) {
AmfByteArray ba(v8 { 0x1 });
v8 data {
0x0c, 0x03, 0x01,
0x0c, 0x00,
};
Deserializer d;
auto it = data.cbegin();
auto end = data.cend();
ASSERT_EQ(ba, d.deserialize(it, end).as<AmfByteArray>());
d.clearContext();
ASSERT_THROW(d.deserialize(it, end), std::out_of_range);
}
TEST(DeserializerTest, UnknownType) {
Deserializer d;
ASSERT_THROW(d.deserialize({ AMF_DICTIONARY + 1 }), std::invalid_argument);
ASSERT_THROW(d.deserialize({ 0xff }), std::invalid_argument);
}
TEST(DeserializerTest, IncorrectTypeRef) {
Deserializer d;
ASSERT_EQ(AmfArray(), d.deserialize(v8 { 0x09, 0x01, 0x01 }).as<AmfArray>());
ASSERT_EQ(AmfArray(), d.deserialize(v8 { 0x09, 0x00 }).as<AmfArray>());
ASSERT_THROW(d.deserialize(v8 { 0x10, 0x00 }), std::invalid_argument);
}
<|endoftext|> |
<commit_before>#include <iostream>
int main() {
std::cout << "Fractalogy!\n";
return 0;
}
<commit_msg>Add the iteration function for the fractals<commit_after>#include <iostream>
#include <complex>
using std::cout;
using std::complex;
using std::exp;
using std::norm;
/// returns -1 on failing to escape
int iteration(complex<double> c, int limit = 1000) {
int i = 0;
double n;
complex<double> z(0, 0);
while ((n = norm(z)) < 4 && i < limit) {
z = exp(z) - c;
++i;
}
if (n < 4)
return -1;
else
return i;
}
int main() {
std::cout << "Fractalogy!\n";
double lower = -2, upper = 2;
int width = 100, height = 100;
for (int i = 0; i <= width; ++i) {
for (int j = 0; j <= height; ++j) {
complex<double> t;
t = complex<double>(lower + (upper - lower) * i / width, lower + (upper - lower) * j / height);
cout << iteration(t) << " ";
}
cout << std::endl;
}
return 0;
}
<|endoftext|> |
<commit_before>
/*
* Copyright 2011 Google Inc.
*
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*/
#include "SkBitmapProcShader.h"
#include "SkColorPriv.h"
#include "SkFlattenableBuffers.h"
#include "SkPixelRef.h"
bool SkBitmapProcShader::CanDo(const SkBitmap& bm, TileMode tx, TileMode ty) {
switch (bm.config()) {
case SkBitmap::kA8_Config:
case SkBitmap::kRGB_565_Config:
case SkBitmap::kIndex8_Config:
case SkBitmap::kARGB_8888_Config:
// if (tx == ty && (kClamp_TileMode == tx || kRepeat_TileMode == tx))
return true;
default:
break;
}
return false;
}
SkBitmapProcShader::SkBitmapProcShader(const SkBitmap& src,
TileMode tmx, TileMode tmy) {
fRawBitmap = src;
fState.fTileModeX = (uint8_t)tmx;
fState.fTileModeY = (uint8_t)tmy;
fFlags = 0; // computed in setContext
}
SkBitmapProcShader::SkBitmapProcShader(SkFlattenableReadBuffer& buffer)
: INHERITED(buffer) {
buffer.readBitmap(&fRawBitmap);
fRawBitmap.setImmutable();
fState.fTileModeX = buffer.readUInt();
fState.fTileModeY = buffer.readUInt();
fFlags = 0; // computed in setContext
}
SkShader::BitmapType SkBitmapProcShader::asABitmap(SkBitmap* texture,
SkMatrix* texM,
TileMode xy[]) const {
if (texture) {
*texture = fRawBitmap;
}
if (texM) {
texM->reset();
}
if (xy) {
xy[0] = (TileMode)fState.fTileModeX;
xy[1] = (TileMode)fState.fTileModeY;
}
return kDefault_BitmapType;
}
void SkBitmapProcShader::flatten(SkFlattenableWriteBuffer& buffer) const {
this->INHERITED::flatten(buffer);
buffer.writeBitmap(fRawBitmap);
buffer.writeUInt(fState.fTileModeX);
buffer.writeUInt(fState.fTileModeY);
}
static bool only_scale_and_translate(const SkMatrix& matrix) {
unsigned mask = SkMatrix::kTranslate_Mask | SkMatrix::kScale_Mask;
return (matrix.getType() & ~mask) == 0;
}
bool SkBitmapProcShader::isOpaque() const {
return fRawBitmap.isOpaque();
}
bool SkBitmapProcShader::setContext(const SkBitmap& device,
const SkPaint& paint,
const SkMatrix& matrix) {
// do this first, so we have a correct inverse matrix
if (!this->INHERITED::setContext(device, paint, matrix)) {
return false;
}
fState.fOrigBitmap = fRawBitmap;
fState.fOrigBitmap.lockPixels();
if (!fState.fOrigBitmap.getTexture() && !fState.fOrigBitmap.readyToDraw()) {
fState.fOrigBitmap.unlockPixels();
return false;
}
if (!fState.chooseProcs(this->getTotalInverse(), paint)) {
fState.fOrigBitmap.unlockPixels();
return false;
}
const SkBitmap& bitmap = *fState.fBitmap;
bool bitmapIsOpaque = bitmap.isOpaque();
// update fFlags
uint32_t flags = 0;
if (bitmapIsOpaque && (255 == this->getPaintAlpha())) {
flags |= kOpaqueAlpha_Flag;
}
switch (bitmap.config()) {
case SkBitmap::kRGB_565_Config:
flags |= (kHasSpan16_Flag | kIntrinsicly16_Flag);
break;
case SkBitmap::kIndex8_Config:
case SkBitmap::kARGB_8888_Config:
if (bitmapIsOpaque) {
flags |= kHasSpan16_Flag;
}
break;
case SkBitmap::kA8_Config:
break; // never set kHasSpan16_Flag
default:
break;
}
if (paint.isDither() && bitmap.config() != SkBitmap::kRGB_565_Config) {
// gradients can auto-dither in their 16bit sampler, but we don't so
// we clear the flag here.
flags &= ~kHasSpan16_Flag;
}
// if we're only 1-pixel heigh, and we don't rotate, then we can claim this
if (1 == bitmap.height() &&
only_scale_and_translate(this->getTotalInverse())) {
flags |= kConstInY32_Flag;
if (flags & kHasSpan16_Flag) {
flags |= kConstInY16_Flag;
}
}
fFlags = flags;
return true;
}
void SkBitmapProcShader::endContext() {
fState.fOrigBitmap.unlockPixels();
this->INHERITED::endContext();
}
#define BUF_MAX 128
#define TEST_BUFFER_OVERRITEx
#ifdef TEST_BUFFER_OVERRITE
#define TEST_BUFFER_EXTRA 32
#define TEST_PATTERN 0x88888888
#else
#define TEST_BUFFER_EXTRA 0
#endif
void SkBitmapProcShader::shadeSpan(int x, int y, SkPMColor dstC[], int count) {
const SkBitmapProcState& state = fState;
if (state.getShaderProc32()) {
state.getShaderProc32()(state, x, y, dstC, count);
return;
}
uint32_t buffer[BUF_MAX + TEST_BUFFER_EXTRA];
SkBitmapProcState::MatrixProc mproc = state.getMatrixProc();
SkBitmapProcState::SampleProc32 sproc = state.getSampleProc32();
int max = fState.maxCountForBufferSize(sizeof(buffer[0]) * BUF_MAX);
SkASSERT(state.fBitmap->getPixels());
SkASSERT(state.fBitmap->pixelRef() == NULL ||
state.fBitmap->pixelRef()->isLocked());
for (;;) {
int n = count;
if (n > max) {
n = max;
}
SkASSERT(n > 0 && n < BUF_MAX*2);
#ifdef TEST_BUFFER_OVERRITE
for (int i = 0; i < TEST_BUFFER_EXTRA; i++) {
buffer[BUF_MAX + i] = TEST_PATTERN;
}
#endif
mproc(state, buffer, n, x, y);
#ifdef TEST_BUFFER_OVERRITE
for (int j = 0; j < TEST_BUFFER_EXTRA; j++) {
SkASSERT(buffer[BUF_MAX + j] == TEST_PATTERN);
}
#endif
sproc(state, buffer, n, dstC);
if ((count -= n) == 0) {
break;
}
SkASSERT(count > 0);
x += n;
dstC += n;
}
}
SkShader::ShadeProc SkBitmapProcShader::asAShadeProc(void** ctx) {
if (fState.getShaderProc32()) {
*ctx = &fState;
return (ShadeProc)fState.getShaderProc32();
}
return NULL;
}
void SkBitmapProcShader::shadeSpan16(int x, int y, uint16_t dstC[], int count) {
const SkBitmapProcState& state = fState;
if (state.getShaderProc16()) {
state.getShaderProc16()(state, x, y, dstC, count);
return;
}
uint32_t buffer[BUF_MAX];
SkBitmapProcState::MatrixProc mproc = state.getMatrixProc();
SkBitmapProcState::SampleProc16 sproc = state.getSampleProc16();
int max = fState.maxCountForBufferSize(sizeof(buffer));
SkASSERT(state.fBitmap->getPixels());
SkASSERT(state.fBitmap->pixelRef() == NULL ||
state.fBitmap->pixelRef()->isLocked());
for (;;) {
int n = count;
if (n > max) {
n = max;
}
mproc(state, buffer, n, x, y);
sproc(state, buffer, n, dstC);
if ((count -= n) == 0) {
break;
}
x += n;
dstC += n;
}
}
///////////////////////////////////////////////////////////////////////////////
#include "SkUnPreMultiply.h"
#include "SkColorShader.h"
#include "SkEmptyShader.h"
// returns true and set color if the bitmap can be drawn as a single color
// (for efficiency)
static bool canUseColorShader(const SkBitmap& bm, SkColor* color) {
if (1 != bm.width() || 1 != bm.height()) {
return false;
}
SkAutoLockPixels alp(bm);
if (!bm.readyToDraw()) {
return false;
}
switch (bm.config()) {
case SkBitmap::kARGB_8888_Config:
*color = SkUnPreMultiply::PMColorToColor(*bm.getAddr32(0, 0));
return true;
case SkBitmap::kRGB_565_Config:
*color = SkPixel16ToColor(*bm.getAddr16(0, 0));
return true;
case SkBitmap::kIndex8_Config:
*color = SkUnPreMultiply::PMColorToColor(bm.getIndex8Color(0, 0));
return true;
default: // just skip the other configs for now
break;
}
return false;
}
#include "SkTemplatesPriv.h"
static bool bitmapIsTooBig(const SkBitmap& bm) {
// SkBitmapProcShader stores bitmap coordinates in a 16bit buffer, as it
// communicates between its matrix-proc and its sampler-proc. Until we can
// widen that, we have to reject bitmaps that are larger.
//
const int maxSize = 65535;
return bm.width() > maxSize || bm.height() > maxSize;
}
SkShader* SkShader::CreateBitmapShader(const SkBitmap& src,
TileMode tmx, TileMode tmy,
void* storage, size_t storageSize) {
SkShader* shader;
SkColor color;
if (src.isNull() || bitmapIsTooBig(src)) {
SK_PLACEMENT_NEW(shader, SkEmptyShader, storage, storageSize);
}
else if (canUseColorShader(src, &color)) {
SK_PLACEMENT_NEW_ARGS(shader, SkColorShader, storage, storageSize,
(color));
} else {
SK_PLACEMENT_NEW_ARGS(shader, SkBitmapProcShader, storage,
storageSize, (src, tmx, tmy));
}
return shader;
}
///////////////////////////////////////////////////////////////////////////////
static const char* gTileModeName[] = {
"clamp", "repeat", "mirror"
};
bool SkBitmapProcShader::toDumpString(SkString* str) const {
str->printf("BitmapShader: [%d %d %d",
fRawBitmap.width(), fRawBitmap.height(),
fRawBitmap.bytesPerPixel());
// add the pixelref
SkPixelRef* pr = fRawBitmap.pixelRef();
if (pr) {
const char* uri = pr->getURI();
if (uri) {
str->appendf(" \"%s\"", uri);
}
}
// add the (optional) matrix
{
if (this->hasLocalMatrix()) {
SkString info;
this->getLocalMatrix().toDumpString(&info);
str->appendf(" %s", info.c_str());
}
}
str->appendf(" [%s %s]]",
gTileModeName[fState.fTileModeX],
gTileModeName[fState.fTileModeY]);
return true;
}
///////////////////////////////////////////////////////////////////////////////
#if SK_SUPPORT_GPU
#include "GrTextureAccess.h"
#include "effects/GrSingleTextureEffect.h"
#include "SkGr.h"
GrEffect* SkBitmapProcShader::asNewEffect(GrContext* context, const SkPaint& paint) const {
SkMatrix matrix;
matrix.setIDiv(fRawBitmap.width(), fRawBitmap.height());
if (this->hasLocalMatrix()) {
SkMatrix inverse;
if (!this->getLocalMatrix().invert(&inverse)) {
return NULL;
}
matrix.preConcat(inverse);
}
SkShader::TileMode tm[] = {
(TileMode)fState.fTileModeX,
(TileMode)fState.fTileModeY,
};
// Must set wrap and filter on the sampler before requesting a texture.
GrTextureParams params(tm, paint.isFilterBitmap());
GrTexture* texture = GrLockCachedBitmapTexture(context, fRawBitmap, ¶ms);
if (NULL == texture) {
SkDebugf("Couldn't convert bitmap to texture.\n");
return NULL;
}
GrEffect* effect = SkNEW_ARGS(GrSingleTextureEffect, (texture, matrix, params));
GrUnlockCachedBitmapTexture(texture);
return effect;
}
#endif
<commit_msg>call endContext() if we have to return false from setContext(), to keep the debugging fInSetContext flag up-to-date.<commit_after>
/*
* Copyright 2011 Google Inc.
*
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*/
#include "SkBitmapProcShader.h"
#include "SkColorPriv.h"
#include "SkFlattenableBuffers.h"
#include "SkPixelRef.h"
bool SkBitmapProcShader::CanDo(const SkBitmap& bm, TileMode tx, TileMode ty) {
switch (bm.config()) {
case SkBitmap::kA8_Config:
case SkBitmap::kRGB_565_Config:
case SkBitmap::kIndex8_Config:
case SkBitmap::kARGB_8888_Config:
// if (tx == ty && (kClamp_TileMode == tx || kRepeat_TileMode == tx))
return true;
default:
break;
}
return false;
}
SkBitmapProcShader::SkBitmapProcShader(const SkBitmap& src,
TileMode tmx, TileMode tmy) {
fRawBitmap = src;
fState.fTileModeX = (uint8_t)tmx;
fState.fTileModeY = (uint8_t)tmy;
fFlags = 0; // computed in setContext
}
SkBitmapProcShader::SkBitmapProcShader(SkFlattenableReadBuffer& buffer)
: INHERITED(buffer) {
buffer.readBitmap(&fRawBitmap);
fRawBitmap.setImmutable();
fState.fTileModeX = buffer.readUInt();
fState.fTileModeY = buffer.readUInt();
fFlags = 0; // computed in setContext
}
SkShader::BitmapType SkBitmapProcShader::asABitmap(SkBitmap* texture,
SkMatrix* texM,
TileMode xy[]) const {
if (texture) {
*texture = fRawBitmap;
}
if (texM) {
texM->reset();
}
if (xy) {
xy[0] = (TileMode)fState.fTileModeX;
xy[1] = (TileMode)fState.fTileModeY;
}
return kDefault_BitmapType;
}
void SkBitmapProcShader::flatten(SkFlattenableWriteBuffer& buffer) const {
this->INHERITED::flatten(buffer);
buffer.writeBitmap(fRawBitmap);
buffer.writeUInt(fState.fTileModeX);
buffer.writeUInt(fState.fTileModeY);
}
static bool only_scale_and_translate(const SkMatrix& matrix) {
unsigned mask = SkMatrix::kTranslate_Mask | SkMatrix::kScale_Mask;
return (matrix.getType() & ~mask) == 0;
}
bool SkBitmapProcShader::isOpaque() const {
return fRawBitmap.isOpaque();
}
bool SkBitmapProcShader::setContext(const SkBitmap& device,
const SkPaint& paint,
const SkMatrix& matrix) {
// do this first, so we have a correct inverse matrix
if (!this->INHERITED::setContext(device, paint, matrix)) {
return false;
}
fState.fOrigBitmap = fRawBitmap;
fState.fOrigBitmap.lockPixels();
if (!fState.fOrigBitmap.getTexture() && !fState.fOrigBitmap.readyToDraw()) {
fState.fOrigBitmap.unlockPixels();
this->INHERITED::endContext();
return false;
}
if (!fState.chooseProcs(this->getTotalInverse(), paint)) {
fState.fOrigBitmap.unlockPixels();
this->INHERITED::endContext();
return false;
}
const SkBitmap& bitmap = *fState.fBitmap;
bool bitmapIsOpaque = bitmap.isOpaque();
// update fFlags
uint32_t flags = 0;
if (bitmapIsOpaque && (255 == this->getPaintAlpha())) {
flags |= kOpaqueAlpha_Flag;
}
switch (bitmap.config()) {
case SkBitmap::kRGB_565_Config:
flags |= (kHasSpan16_Flag | kIntrinsicly16_Flag);
break;
case SkBitmap::kIndex8_Config:
case SkBitmap::kARGB_8888_Config:
if (bitmapIsOpaque) {
flags |= kHasSpan16_Flag;
}
break;
case SkBitmap::kA8_Config:
break; // never set kHasSpan16_Flag
default:
break;
}
if (paint.isDither() && bitmap.config() != SkBitmap::kRGB_565_Config) {
// gradients can auto-dither in their 16bit sampler, but we don't so
// we clear the flag here.
flags &= ~kHasSpan16_Flag;
}
// if we're only 1-pixel heigh, and we don't rotate, then we can claim this
if (1 == bitmap.height() &&
only_scale_and_translate(this->getTotalInverse())) {
flags |= kConstInY32_Flag;
if (flags & kHasSpan16_Flag) {
flags |= kConstInY16_Flag;
}
}
fFlags = flags;
return true;
}
void SkBitmapProcShader::endContext() {
fState.fOrigBitmap.unlockPixels();
this->INHERITED::endContext();
}
#define BUF_MAX 128
#define TEST_BUFFER_OVERRITEx
#ifdef TEST_BUFFER_OVERRITE
#define TEST_BUFFER_EXTRA 32
#define TEST_PATTERN 0x88888888
#else
#define TEST_BUFFER_EXTRA 0
#endif
void SkBitmapProcShader::shadeSpan(int x, int y, SkPMColor dstC[], int count) {
const SkBitmapProcState& state = fState;
if (state.getShaderProc32()) {
state.getShaderProc32()(state, x, y, dstC, count);
return;
}
uint32_t buffer[BUF_MAX + TEST_BUFFER_EXTRA];
SkBitmapProcState::MatrixProc mproc = state.getMatrixProc();
SkBitmapProcState::SampleProc32 sproc = state.getSampleProc32();
int max = fState.maxCountForBufferSize(sizeof(buffer[0]) * BUF_MAX);
SkASSERT(state.fBitmap->getPixels());
SkASSERT(state.fBitmap->pixelRef() == NULL ||
state.fBitmap->pixelRef()->isLocked());
for (;;) {
int n = count;
if (n > max) {
n = max;
}
SkASSERT(n > 0 && n < BUF_MAX*2);
#ifdef TEST_BUFFER_OVERRITE
for (int i = 0; i < TEST_BUFFER_EXTRA; i++) {
buffer[BUF_MAX + i] = TEST_PATTERN;
}
#endif
mproc(state, buffer, n, x, y);
#ifdef TEST_BUFFER_OVERRITE
for (int j = 0; j < TEST_BUFFER_EXTRA; j++) {
SkASSERT(buffer[BUF_MAX + j] == TEST_PATTERN);
}
#endif
sproc(state, buffer, n, dstC);
if ((count -= n) == 0) {
break;
}
SkASSERT(count > 0);
x += n;
dstC += n;
}
}
SkShader::ShadeProc SkBitmapProcShader::asAShadeProc(void** ctx) {
if (fState.getShaderProc32()) {
*ctx = &fState;
return (ShadeProc)fState.getShaderProc32();
}
return NULL;
}
void SkBitmapProcShader::shadeSpan16(int x, int y, uint16_t dstC[], int count) {
const SkBitmapProcState& state = fState;
if (state.getShaderProc16()) {
state.getShaderProc16()(state, x, y, dstC, count);
return;
}
uint32_t buffer[BUF_MAX];
SkBitmapProcState::MatrixProc mproc = state.getMatrixProc();
SkBitmapProcState::SampleProc16 sproc = state.getSampleProc16();
int max = fState.maxCountForBufferSize(sizeof(buffer));
SkASSERT(state.fBitmap->getPixels());
SkASSERT(state.fBitmap->pixelRef() == NULL ||
state.fBitmap->pixelRef()->isLocked());
for (;;) {
int n = count;
if (n > max) {
n = max;
}
mproc(state, buffer, n, x, y);
sproc(state, buffer, n, dstC);
if ((count -= n) == 0) {
break;
}
x += n;
dstC += n;
}
}
///////////////////////////////////////////////////////////////////////////////
#include "SkUnPreMultiply.h"
#include "SkColorShader.h"
#include "SkEmptyShader.h"
// returns true and set color if the bitmap can be drawn as a single color
// (for efficiency)
static bool canUseColorShader(const SkBitmap& bm, SkColor* color) {
if (1 != bm.width() || 1 != bm.height()) {
return false;
}
SkAutoLockPixels alp(bm);
if (!bm.readyToDraw()) {
return false;
}
switch (bm.config()) {
case SkBitmap::kARGB_8888_Config:
*color = SkUnPreMultiply::PMColorToColor(*bm.getAddr32(0, 0));
return true;
case SkBitmap::kRGB_565_Config:
*color = SkPixel16ToColor(*bm.getAddr16(0, 0));
return true;
case SkBitmap::kIndex8_Config:
*color = SkUnPreMultiply::PMColorToColor(bm.getIndex8Color(0, 0));
return true;
default: // just skip the other configs for now
break;
}
return false;
}
#include "SkTemplatesPriv.h"
static bool bitmapIsTooBig(const SkBitmap& bm) {
// SkBitmapProcShader stores bitmap coordinates in a 16bit buffer, as it
// communicates between its matrix-proc and its sampler-proc. Until we can
// widen that, we have to reject bitmaps that are larger.
//
const int maxSize = 65535;
return bm.width() > maxSize || bm.height() > maxSize;
}
SkShader* SkShader::CreateBitmapShader(const SkBitmap& src,
TileMode tmx, TileMode tmy,
void* storage, size_t storageSize) {
SkShader* shader;
SkColor color;
if (src.isNull() || bitmapIsTooBig(src)) {
SK_PLACEMENT_NEW(shader, SkEmptyShader, storage, storageSize);
}
else if (canUseColorShader(src, &color)) {
SK_PLACEMENT_NEW_ARGS(shader, SkColorShader, storage, storageSize,
(color));
} else {
SK_PLACEMENT_NEW_ARGS(shader, SkBitmapProcShader, storage,
storageSize, (src, tmx, tmy));
}
return shader;
}
///////////////////////////////////////////////////////////////////////////////
static const char* gTileModeName[] = {
"clamp", "repeat", "mirror"
};
bool SkBitmapProcShader::toDumpString(SkString* str) const {
str->printf("BitmapShader: [%d %d %d",
fRawBitmap.width(), fRawBitmap.height(),
fRawBitmap.bytesPerPixel());
// add the pixelref
SkPixelRef* pr = fRawBitmap.pixelRef();
if (pr) {
const char* uri = pr->getURI();
if (uri) {
str->appendf(" \"%s\"", uri);
}
}
// add the (optional) matrix
{
if (this->hasLocalMatrix()) {
SkString info;
this->getLocalMatrix().toDumpString(&info);
str->appendf(" %s", info.c_str());
}
}
str->appendf(" [%s %s]]",
gTileModeName[fState.fTileModeX],
gTileModeName[fState.fTileModeY]);
return true;
}
///////////////////////////////////////////////////////////////////////////////
#if SK_SUPPORT_GPU
#include "GrTextureAccess.h"
#include "effects/GrSingleTextureEffect.h"
#include "SkGr.h"
GrEffect* SkBitmapProcShader::asNewEffect(GrContext* context, const SkPaint& paint) const {
SkMatrix matrix;
matrix.setIDiv(fRawBitmap.width(), fRawBitmap.height());
if (this->hasLocalMatrix()) {
SkMatrix inverse;
if (!this->getLocalMatrix().invert(&inverse)) {
return NULL;
}
matrix.preConcat(inverse);
}
SkShader::TileMode tm[] = {
(TileMode)fState.fTileModeX,
(TileMode)fState.fTileModeY,
};
// Must set wrap and filter on the sampler before requesting a texture.
GrTextureParams params(tm, paint.isFilterBitmap());
GrTexture* texture = GrLockCachedBitmapTexture(context, fRawBitmap, ¶ms);
if (NULL == texture) {
SkDebugf("Couldn't convert bitmap to texture.\n");
return NULL;
}
GrEffect* effect = SkNEW_ARGS(GrSingleTextureEffect, (texture, matrix, params));
GrUnlockCachedBitmapTexture(texture);
return effect;
}
#endif
<|endoftext|> |
<commit_before>/*
* Copyright 2011 Google Inc.
*
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*/
#include "SkBitmapProcShader.h"
#include "SkBitmapProcState.h"
#include "SkBitmapProvider.h"
#include "SkColorPriv.h"
#include "SkErrorInternals.h"
#include "SkPixelRef.h"
#include "SkReadBuffer.h"
#include "SkWriteBuffer.h"
#if SK_SUPPORT_GPU
#include "SkGrPriv.h"
#include "effects/GrBicubicEffect.h"
#include "effects/GrSimpleTextureEffect.h"
#endif
size_t SkBitmapProcShader::ContextSize() {
// The SkBitmapProcState is stored outside of the context object, with the context holding
// a pointer to it.
return sizeof(BitmapProcShaderContext) + sizeof(SkBitmapProcState);
}
SkBitmapProcShader::SkBitmapProcShader(const SkBitmap& src, TileMode tmx, TileMode tmy,
const SkMatrix* localMatrix)
: INHERITED(localMatrix) {
fRawBitmap = src;
fTileModeX = (uint8_t)tmx;
fTileModeY = (uint8_t)tmy;
}
bool SkBitmapProcShader::onIsABitmap(SkBitmap* texture, SkMatrix* texM, TileMode xy[]) const {
if (texture) {
*texture = fRawBitmap;
}
if (texM) {
texM->reset();
}
if (xy) {
xy[0] = (TileMode)fTileModeX;
xy[1] = (TileMode)fTileModeY;
}
return true;
}
SkFlattenable* SkBitmapProcShader::CreateProc(SkReadBuffer& buffer) {
SkMatrix lm;
buffer.readMatrix(&lm);
SkBitmap bm;
if (!buffer.readBitmap(&bm)) {
return nullptr;
}
bm.setImmutable();
TileMode mx = (TileMode)buffer.readUInt();
TileMode my = (TileMode)buffer.readUInt();
return SkShader::CreateBitmapShader(bm, mx, my, &lm);
}
void SkBitmapProcShader::flatten(SkWriteBuffer& buffer) const {
buffer.writeMatrix(this->getLocalMatrix());
buffer.writeBitmap(fRawBitmap);
buffer.writeUInt(fTileModeX);
buffer.writeUInt(fTileModeY);
}
bool SkBitmapProcShader::isOpaque() const {
return fRawBitmap.isOpaque();
}
SkShader::Context* SkBitmapProcShader::MakeContext(const SkShader& shader,
TileMode tmx, TileMode tmy,
const SkBitmapProvider& provider,
const ContextRec& rec, void* storage) {
SkMatrix totalInverse;
// Do this first, so we know the matrix can be inverted.
if (!shader.computeTotalInverse(rec, &totalInverse)) {
return nullptr;
}
void* stateStorage = (char*)storage + sizeof(BitmapProcShaderContext);
SkBitmapProcState* state = new (stateStorage) SkBitmapProcState(provider, tmx, tmy);
SkASSERT(state);
if (!state->chooseProcs(totalInverse, *rec.fPaint)) {
state->~SkBitmapProcState();
return nullptr;
}
return new (storage) BitmapProcShaderContext(shader, rec, state);
}
SkShader::Context* SkBitmapProcShader::onCreateContext(const ContextRec& rec, void* storage) const {
return MakeContext(*this, (TileMode)fTileModeX, (TileMode)fTileModeY,
SkBitmapProvider(fRawBitmap), rec, storage);
}
SkBitmapProcShader::BitmapProcShaderContext::BitmapProcShaderContext(const SkShader& shader,
const ContextRec& rec,
SkBitmapProcState* state)
: INHERITED(shader, rec)
, fState(state)
{
fFlags = 0;
if (fState->fPixmap.isOpaque() && (255 == this->getPaintAlpha())) {
fFlags |= kOpaqueAlpha_Flag;
}
}
SkBitmapProcShader::BitmapProcShaderContext::~BitmapProcShaderContext() {
// The bitmap proc state has been created outside of the context on memory that will be freed
// elsewhere. Only call the destructor but leave the freeing of the memory to the caller.
fState->~SkBitmapProcState();
}
#define BUF_MAX 128
#define TEST_BUFFER_OVERRITEx
#ifdef TEST_BUFFER_OVERRITE
#define TEST_BUFFER_EXTRA 32
#define TEST_PATTERN 0x88888888
#else
#define TEST_BUFFER_EXTRA 0
#endif
void SkBitmapProcShader::BitmapProcShaderContext::shadeSpan(int x, int y, SkPMColor dstC[],
int count) {
const SkBitmapProcState& state = *fState;
if (state.getShaderProc32()) {
state.getShaderProc32()(&state, x, y, dstC, count);
return;
}
uint32_t buffer[BUF_MAX + TEST_BUFFER_EXTRA];
SkBitmapProcState::MatrixProc mproc = state.getMatrixProc();
SkBitmapProcState::SampleProc32 sproc = state.getSampleProc32();
int max = state.maxCountForBufferSize(sizeof(buffer[0]) * BUF_MAX);
SkASSERT(state.fPixmap.addr());
for (;;) {
int n = count;
if (n > max) {
n = max;
}
SkASSERT(n > 0 && n < BUF_MAX*2);
#ifdef TEST_BUFFER_OVERRITE
for (int i = 0; i < TEST_BUFFER_EXTRA; i++) {
buffer[BUF_MAX + i] = TEST_PATTERN;
}
#endif
mproc(state, buffer, n, x, y);
#ifdef TEST_BUFFER_OVERRITE
for (int j = 0; j < TEST_BUFFER_EXTRA; j++) {
SkASSERT(buffer[BUF_MAX + j] == TEST_PATTERN);
}
#endif
sproc(state, buffer, n, dstC);
if ((count -= n) == 0) {
break;
}
SkASSERT(count > 0);
x += n;
dstC += n;
}
}
SkShader::Context::ShadeProc SkBitmapProcShader::BitmapProcShaderContext::asAShadeProc(void** ctx) {
if (fState->getShaderProc32()) {
*ctx = fState;
return (ShadeProc)fState->getShaderProc32();
}
return nullptr;
}
///////////////////////////////////////////////////////////////////////////////
#include "SkUnPreMultiply.h"
#include "SkColorShader.h"
#include "SkEmptyShader.h"
// returns true and set color if the bitmap can be drawn as a single color
// (for efficiency)
static bool can_use_color_shader(const SkBitmap& bm, SkColor* color) {
#ifdef SK_BUILD_FOR_ANDROID_FRAMEWORK
// HWUI does not support color shaders (see b/22390304)
return false;
#endif
if (1 != bm.width() || 1 != bm.height()) {
return false;
}
SkAutoLockPixels alp(bm);
if (!bm.readyToDraw()) {
return false;
}
switch (bm.colorType()) {
case kN32_SkColorType:
*color = SkUnPreMultiply::PMColorToColor(*bm.getAddr32(0, 0));
return true;
case kRGB_565_SkColorType:
*color = SkPixel16ToColor(*bm.getAddr16(0, 0));
return true;
case kIndex_8_SkColorType:
*color = SkUnPreMultiply::PMColorToColor(bm.getIndex8Color(0, 0));
return true;
default: // just skip the other configs for now
break;
}
return false;
}
static bool bitmap_is_too_big(const SkBitmap& bm) {
// SkBitmapProcShader stores bitmap coordinates in a 16bit buffer, as it
// communicates between its matrix-proc and its sampler-proc. Until we can
// widen that, we have to reject bitmaps that are larger.
//
static const int kMaxSize = 65535;
return bm.width() > kMaxSize || bm.height() > kMaxSize;
}
SkShader* SkCreateBitmapShader(const SkBitmap& src, SkShader::TileMode tmx,
SkShader::TileMode tmy, const SkMatrix* localMatrix,
SkTBlitterAllocator* allocator) {
SkShader* shader;
SkColor color;
if (src.isNull() || bitmap_is_too_big(src)) {
if (nullptr == allocator) {
shader = new SkEmptyShader;
} else {
shader = allocator->createT<SkEmptyShader>();
}
} else if (can_use_color_shader(src, &color)) {
if (nullptr == allocator) {
shader = new SkColorShader(color);
} else {
shader = allocator->createT<SkColorShader>(color);
}
} else {
if (nullptr == allocator) {
shader = new SkBitmapProcShader(src, tmx, tmy, localMatrix);
} else {
shader = allocator->createT<SkBitmapProcShader>(src, tmx, tmy, localMatrix);
}
}
return shader;
}
///////////////////////////////////////////////////////////////////////////////
#ifndef SK_IGNORE_TO_STRING
void SkBitmapProcShader::toString(SkString* str) const {
static const char* gTileModeName[SkShader::kTileModeCount] = {
"clamp", "repeat", "mirror"
};
str->append("BitmapShader: (");
str->appendf("(%s, %s)",
gTileModeName[fTileModeX],
gTileModeName[fTileModeY]);
str->append(" ");
fRawBitmap.toString(str);
this->INHERITED::toString(str);
str->append(")");
}
#endif
///////////////////////////////////////////////////////////////////////////////
#if SK_SUPPORT_GPU
#include "GrTextureAccess.h"
#include "SkGr.h"
#include "effects/GrSimpleTextureEffect.h"
const GrFragmentProcessor* SkBitmapProcShader::asFragmentProcessor(GrContext* context,
const SkMatrix& viewM, const SkMatrix* localMatrix,
SkFilterQuality filterQuality) const {
SkMatrix matrix;
matrix.setIDiv(fRawBitmap.width(), fRawBitmap.height());
SkMatrix lmInverse;
if (!this->getLocalMatrix().invert(&lmInverse)) {
return nullptr;
}
if (localMatrix) {
SkMatrix inv;
if (!localMatrix->invert(&inv)) {
return nullptr;
}
lmInverse.postConcat(inv);
}
matrix.preConcat(lmInverse);
SkShader::TileMode tm[] = {
(TileMode)fTileModeX,
(TileMode)fTileModeY,
};
// Must set wrap and filter on the sampler before requesting a texture. In two places below
// we check the matrix scale factors to determine how to interpret the filter quality setting.
// This completely ignores the complexity of the drawVertices case where explicit local coords
// are provided by the caller.
bool doBicubic;
GrTextureParams::FilterMode textureFilterMode =
GrSkFilterQualityToGrFilterMode(filterQuality, viewM, this->getLocalMatrix(),
&doBicubic);
GrTextureParams params(tm, textureFilterMode);
SkAutoTUnref<GrTexture> texture(GrRefCachedBitmapTexture(context, fRawBitmap, params));
if (!texture) {
SkErrorInternals::SetError( kInternalError_SkError,
"Couldn't convert bitmap to texture.");
return nullptr;
}
SkAutoTUnref<const GrFragmentProcessor> inner;
if (doBicubic) {
inner.reset(GrBicubicEffect::Create(texture, matrix, tm));
} else {
inner.reset(GrSimpleTextureEffect::Create(texture, matrix, params));
}
if (kAlpha_8_SkColorType == fRawBitmap.colorType()) {
return GrFragmentProcessor::MulOutputByInputUnpremulColor(inner);
}
return GrFragmentProcessor::MulOutputByInputAlpha(inner);
}
#endif
<commit_msg>restore lost optimization when the shader can report const_in_y<commit_after>/*
* Copyright 2011 Google Inc.
*
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*/
#include "SkBitmapProcShader.h"
#include "SkBitmapProcState.h"
#include "SkBitmapProvider.h"
#include "SkColorPriv.h"
#include "SkErrorInternals.h"
#include "SkPixelRef.h"
#include "SkReadBuffer.h"
#include "SkWriteBuffer.h"
#if SK_SUPPORT_GPU
#include "SkGrPriv.h"
#include "effects/GrBicubicEffect.h"
#include "effects/GrSimpleTextureEffect.h"
#endif
size_t SkBitmapProcShader::ContextSize() {
// The SkBitmapProcState is stored outside of the context object, with the context holding
// a pointer to it.
return sizeof(BitmapProcShaderContext) + sizeof(SkBitmapProcState);
}
SkBitmapProcShader::SkBitmapProcShader(const SkBitmap& src, TileMode tmx, TileMode tmy,
const SkMatrix* localMatrix)
: INHERITED(localMatrix) {
fRawBitmap = src;
fTileModeX = (uint8_t)tmx;
fTileModeY = (uint8_t)tmy;
}
bool SkBitmapProcShader::onIsABitmap(SkBitmap* texture, SkMatrix* texM, TileMode xy[]) const {
if (texture) {
*texture = fRawBitmap;
}
if (texM) {
texM->reset();
}
if (xy) {
xy[0] = (TileMode)fTileModeX;
xy[1] = (TileMode)fTileModeY;
}
return true;
}
SkFlattenable* SkBitmapProcShader::CreateProc(SkReadBuffer& buffer) {
SkMatrix lm;
buffer.readMatrix(&lm);
SkBitmap bm;
if (!buffer.readBitmap(&bm)) {
return nullptr;
}
bm.setImmutable();
TileMode mx = (TileMode)buffer.readUInt();
TileMode my = (TileMode)buffer.readUInt();
return SkShader::CreateBitmapShader(bm, mx, my, &lm);
}
void SkBitmapProcShader::flatten(SkWriteBuffer& buffer) const {
buffer.writeMatrix(this->getLocalMatrix());
buffer.writeBitmap(fRawBitmap);
buffer.writeUInt(fTileModeX);
buffer.writeUInt(fTileModeY);
}
bool SkBitmapProcShader::isOpaque() const {
return fRawBitmap.isOpaque();
}
SkShader::Context* SkBitmapProcShader::MakeContext(const SkShader& shader,
TileMode tmx, TileMode tmy,
const SkBitmapProvider& provider,
const ContextRec& rec, void* storage) {
SkMatrix totalInverse;
// Do this first, so we know the matrix can be inverted.
if (!shader.computeTotalInverse(rec, &totalInverse)) {
return nullptr;
}
void* stateStorage = (char*)storage + sizeof(BitmapProcShaderContext);
SkBitmapProcState* state = new (stateStorage) SkBitmapProcState(provider, tmx, tmy);
SkASSERT(state);
if (!state->chooseProcs(totalInverse, *rec.fPaint)) {
state->~SkBitmapProcState();
return nullptr;
}
return new (storage) BitmapProcShaderContext(shader, rec, state);
}
SkShader::Context* SkBitmapProcShader::onCreateContext(const ContextRec& rec, void* storage) const {
return MakeContext(*this, (TileMode)fTileModeX, (TileMode)fTileModeY,
SkBitmapProvider(fRawBitmap), rec, storage);
}
static bool only_scale_and_translate(const SkMatrix& matrix) {
unsigned mask = SkMatrix::kTranslate_Mask | SkMatrix::kScale_Mask;
return (matrix.getType() & ~mask) == 0;
}
SkBitmapProcShader::BitmapProcShaderContext::BitmapProcShaderContext(const SkShader& shader,
const ContextRec& rec,
SkBitmapProcState* state)
: INHERITED(shader, rec)
, fState(state)
{
fFlags = 0;
if (fState->fPixmap.isOpaque() && (255 == this->getPaintAlpha())) {
fFlags |= kOpaqueAlpha_Flag;
}
if (1 == fState->fPixmap.height() && only_scale_and_translate(this->getTotalInverse())) {
fFlags |= kConstInY32_Flag;
}
}
SkBitmapProcShader::BitmapProcShaderContext::~BitmapProcShaderContext() {
// The bitmap proc state has been created outside of the context on memory that will be freed
// elsewhere. Only call the destructor but leave the freeing of the memory to the caller.
fState->~SkBitmapProcState();
}
#define BUF_MAX 128
#define TEST_BUFFER_OVERRITEx
#ifdef TEST_BUFFER_OVERRITE
#define TEST_BUFFER_EXTRA 32
#define TEST_PATTERN 0x88888888
#else
#define TEST_BUFFER_EXTRA 0
#endif
void SkBitmapProcShader::BitmapProcShaderContext::shadeSpan(int x, int y, SkPMColor dstC[],
int count) {
const SkBitmapProcState& state = *fState;
if (state.getShaderProc32()) {
state.getShaderProc32()(&state, x, y, dstC, count);
return;
}
uint32_t buffer[BUF_MAX + TEST_BUFFER_EXTRA];
SkBitmapProcState::MatrixProc mproc = state.getMatrixProc();
SkBitmapProcState::SampleProc32 sproc = state.getSampleProc32();
int max = state.maxCountForBufferSize(sizeof(buffer[0]) * BUF_MAX);
SkASSERT(state.fPixmap.addr());
for (;;) {
int n = count;
if (n > max) {
n = max;
}
SkASSERT(n > 0 && n < BUF_MAX*2);
#ifdef TEST_BUFFER_OVERRITE
for (int i = 0; i < TEST_BUFFER_EXTRA; i++) {
buffer[BUF_MAX + i] = TEST_PATTERN;
}
#endif
mproc(state, buffer, n, x, y);
#ifdef TEST_BUFFER_OVERRITE
for (int j = 0; j < TEST_BUFFER_EXTRA; j++) {
SkASSERT(buffer[BUF_MAX + j] == TEST_PATTERN);
}
#endif
sproc(state, buffer, n, dstC);
if ((count -= n) == 0) {
break;
}
SkASSERT(count > 0);
x += n;
dstC += n;
}
}
SkShader::Context::ShadeProc SkBitmapProcShader::BitmapProcShaderContext::asAShadeProc(void** ctx) {
if (fState->getShaderProc32()) {
*ctx = fState;
return (ShadeProc)fState->getShaderProc32();
}
return nullptr;
}
///////////////////////////////////////////////////////////////////////////////
#include "SkUnPreMultiply.h"
#include "SkColorShader.h"
#include "SkEmptyShader.h"
// returns true and set color if the bitmap can be drawn as a single color
// (for efficiency)
static bool can_use_color_shader(const SkBitmap& bm, SkColor* color) {
#ifdef SK_BUILD_FOR_ANDROID_FRAMEWORK
// HWUI does not support color shaders (see b/22390304)
return false;
#endif
if (1 != bm.width() || 1 != bm.height()) {
return false;
}
SkAutoLockPixels alp(bm);
if (!bm.readyToDraw()) {
return false;
}
switch (bm.colorType()) {
case kN32_SkColorType:
*color = SkUnPreMultiply::PMColorToColor(*bm.getAddr32(0, 0));
return true;
case kRGB_565_SkColorType:
*color = SkPixel16ToColor(*bm.getAddr16(0, 0));
return true;
case kIndex_8_SkColorType:
*color = SkUnPreMultiply::PMColorToColor(bm.getIndex8Color(0, 0));
return true;
default: // just skip the other configs for now
break;
}
return false;
}
static bool bitmap_is_too_big(const SkBitmap& bm) {
// SkBitmapProcShader stores bitmap coordinates in a 16bit buffer, as it
// communicates between its matrix-proc and its sampler-proc. Until we can
// widen that, we have to reject bitmaps that are larger.
//
static const int kMaxSize = 65535;
return bm.width() > kMaxSize || bm.height() > kMaxSize;
}
SkShader* SkCreateBitmapShader(const SkBitmap& src, SkShader::TileMode tmx,
SkShader::TileMode tmy, const SkMatrix* localMatrix,
SkTBlitterAllocator* allocator) {
SkShader* shader;
SkColor color;
if (src.isNull() || bitmap_is_too_big(src)) {
if (nullptr == allocator) {
shader = new SkEmptyShader;
} else {
shader = allocator->createT<SkEmptyShader>();
}
} else if (can_use_color_shader(src, &color)) {
if (nullptr == allocator) {
shader = new SkColorShader(color);
} else {
shader = allocator->createT<SkColorShader>(color);
}
} else {
if (nullptr == allocator) {
shader = new SkBitmapProcShader(src, tmx, tmy, localMatrix);
} else {
shader = allocator->createT<SkBitmapProcShader>(src, tmx, tmy, localMatrix);
}
}
return shader;
}
///////////////////////////////////////////////////////////////////////////////
#ifndef SK_IGNORE_TO_STRING
void SkBitmapProcShader::toString(SkString* str) const {
static const char* gTileModeName[SkShader::kTileModeCount] = {
"clamp", "repeat", "mirror"
};
str->append("BitmapShader: (");
str->appendf("(%s, %s)",
gTileModeName[fTileModeX],
gTileModeName[fTileModeY]);
str->append(" ");
fRawBitmap.toString(str);
this->INHERITED::toString(str);
str->append(")");
}
#endif
///////////////////////////////////////////////////////////////////////////////
#if SK_SUPPORT_GPU
#include "GrTextureAccess.h"
#include "SkGr.h"
#include "effects/GrSimpleTextureEffect.h"
const GrFragmentProcessor* SkBitmapProcShader::asFragmentProcessor(GrContext* context,
const SkMatrix& viewM, const SkMatrix* localMatrix,
SkFilterQuality filterQuality) const {
SkMatrix matrix;
matrix.setIDiv(fRawBitmap.width(), fRawBitmap.height());
SkMatrix lmInverse;
if (!this->getLocalMatrix().invert(&lmInverse)) {
return nullptr;
}
if (localMatrix) {
SkMatrix inv;
if (!localMatrix->invert(&inv)) {
return nullptr;
}
lmInverse.postConcat(inv);
}
matrix.preConcat(lmInverse);
SkShader::TileMode tm[] = {
(TileMode)fTileModeX,
(TileMode)fTileModeY,
};
// Must set wrap and filter on the sampler before requesting a texture. In two places below
// we check the matrix scale factors to determine how to interpret the filter quality setting.
// This completely ignores the complexity of the drawVertices case where explicit local coords
// are provided by the caller.
bool doBicubic;
GrTextureParams::FilterMode textureFilterMode =
GrSkFilterQualityToGrFilterMode(filterQuality, viewM, this->getLocalMatrix(),
&doBicubic);
GrTextureParams params(tm, textureFilterMode);
SkAutoTUnref<GrTexture> texture(GrRefCachedBitmapTexture(context, fRawBitmap, params));
if (!texture) {
SkErrorInternals::SetError( kInternalError_SkError,
"Couldn't convert bitmap to texture.");
return nullptr;
}
SkAutoTUnref<const GrFragmentProcessor> inner;
if (doBicubic) {
inner.reset(GrBicubicEffect::Create(texture, matrix, tm));
} else {
inner.reset(GrSimpleTextureEffect::Create(texture, matrix, params));
}
if (kAlpha_8_SkColorType == fRawBitmap.colorType()) {
return GrFragmentProcessor::MulOutputByInputUnpremulColor(inner);
}
return GrFragmentProcessor::MulOutputByInputAlpha(inner);
}
#endif
<|endoftext|> |
<commit_before>/*********************************************************************************
*
* Inviwo - Interactive Visualization Workshop
*
* Copyright (c) 2017 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 <inviwo/core/io/imagewriterutil.h>
#include <inviwo/core/util/filesystem.h>
#include <inviwo/core/util/fileextension.h>
#include <inviwo/core/util/filedialog.h>
#include <inviwo/core/util/dialogfactory.h>
#include <inviwo/core/common/inviwoapplication.h>
#include <inviwo/core/io/datawriter.h>
#include <inviwo/core/io/datawriterfactory.h>
namespace inviwo {
namespace util {
void util::saveLayer(const Layer& layer, const std::string& path, const FileExtension& extension) {
auto factory = InviwoApplication::getPtr()->getDataWriterFactory();
auto writer = std::shared_ptr<DataWriterType<Layer>>(
factory->getWriterForTypeAndExtension<Layer>(extension));
if (!writer) {
// could not find a reader for the given extension, extension might be invalid
// try to get reader for the extension extracted from the file name, i.e. path
const auto ext = filesystem::getFileExtension(path);
writer = std::shared_ptr<DataWriterType<Layer>>(
factory->getWriterForTypeAndExtension<Layer>(ext));
if (!writer) {
LogInfoCustom(
"ImageWriterUtil",
"Could not find a writer for the specified file extension (\"" << ext << "\")");
return;
}
}
try {
writer->setOverwrite(true);
writer->writeData(&layer, path);
LogInfoCustom("ImageWriterUtil", "Canvas layer exported to disk: " << path);
} catch (DataWriterException const& e) {
LogErrorCustom("ImageWriterUtil", e.getMessage());
}
}
IVW_CORE_API void saveLayer(const Layer& layer) {
auto fileDialog = util::dynamic_unique_ptr_cast<FileDialog>(
InviwoApplication::getPtr()->getDialogFactory()->create("FileDialog"));
if (!fileDialog) {
return;
}
fileDialog->setTitle("Save Layer to File...");
fileDialog->setAcceptMode(AcceptMode::Save);
fileDialog->setFileMode(FileMode::AnyFile);
auto writerFactory = InviwoApplication::getPtr()->getDataWriterFactory();
fileDialog->addExtensions(writerFactory->getExtensionsForType<Layer>());
if (fileDialog->show()) {
saveLayer(layer, fileDialog->getSelectedFile(), fileDialog->getSelectedFileExtension());
}
}
} // namespace
} // namespace
<commit_msg>Core: typo fix<commit_after>/*********************************************************************************
*
* Inviwo - Interactive Visualization Workshop
*
* Copyright (c) 2017 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 <inviwo/core/io/imagewriterutil.h>
#include <inviwo/core/util/filesystem.h>
#include <inviwo/core/util/fileextension.h>
#include <inviwo/core/util/filedialog.h>
#include <inviwo/core/util/dialogfactory.h>
#include <inviwo/core/common/inviwoapplication.h>
#include <inviwo/core/io/datawriter.h>
#include <inviwo/core/io/datawriterfactory.h>
namespace inviwo {
namespace util {
void saveLayer(const Layer& layer, const std::string& path, const FileExtension& extension) {
auto factory = InviwoApplication::getPtr()->getDataWriterFactory();
auto writer = std::shared_ptr<DataWriterType<Layer>>(
factory->getWriterForTypeAndExtension<Layer>(extension));
if (!writer) {
// could not find a reader for the given extension, extension might be invalid
// try to get reader for the extension extracted from the file name, i.e. path
const auto ext = filesystem::getFileExtension(path);
writer = std::shared_ptr<DataWriterType<Layer>>(
factory->getWriterForTypeAndExtension<Layer>(ext));
if (!writer) {
LogInfoCustom(
"ImageWriterUtil",
"Could not find a writer for the specified file extension (\"" << ext << "\")");
return;
}
}
try {
writer->setOverwrite(true);
writer->writeData(&layer, path);
LogInfoCustom("ImageWriterUtil", "Canvas layer exported to disk: " << path);
} catch (DataWriterException const& e) {
LogErrorCustom("ImageWriterUtil", e.getMessage());
}
}
void saveLayer(const Layer& layer) {
auto fileDialog = util::dynamic_unique_ptr_cast<FileDialog>(
InviwoApplication::getPtr()->getDialogFactory()->create("FileDialog"));
if (!fileDialog) {
return;
}
fileDialog->setTitle("Save Layer to File...");
fileDialog->setAcceptMode(AcceptMode::Save);
fileDialog->setFileMode(FileMode::AnyFile);
auto writerFactory = InviwoApplication::getPtr()->getDataWriterFactory();
fileDialog->addExtensions(writerFactory->getExtensionsForType<Layer>());
if (fileDialog->show()) {
saveLayer(layer, fileDialog->getSelectedFile(), fileDialog->getSelectedFileExtension());
}
}
} // namespace
} // namespace
<|endoftext|> |
<commit_before>//
// QtMark JSON Library
//
// Copyright (C) 2015 Assured Information Security, Inc.
// Author: Rian Quinn <[email protected]>
// Author: Rodney Forbes <[email protected]>
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 2.1 of the License, or (at your option) any later version.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
// ============================================================================
// Includes
// ============================================================================
#include <qmjsontype_qstring.h>
// ============================================================================
// QMJsonType<QString> Implementation
// ============================================================================
template <>
QMPointer<QMJsonValue> QM_JSON_EXPORT QMJsonType<QString>::fromJson(const QString &json, int32_t &index)
{
auto result = QString();
index++;
while (1)
{
QMJsonValue::verifyIndex(json, index);
switch (json.at(index).toLatin1())
{
case '\\':
{
index++;
QMJsonValue::verifyIndex(json, index);
switch (json.at(index).toLatin1())
{
case '"': result += '"'; break;
case '\\': result += '\\'; break;
case '/': result += '/'; break;
case 'b': result += '\b'; break;
case 'f': result += '\f'; break;
case 'n': result += '\n'; break;
case 'r': result += '\r'; break;
case 't': result += '\t'; break;
// TODO: Need to add support for \u [number]
default:
break;
};
index++;
break;
}
case '"':
index++;
return QMPointer<QMJsonValue>(new QMJsonValue(result));
default:
result += json.at(index++);
break;
};
}
return QMPointer<QMJsonValue>();
}
template <>
QString QM_JSON_EXPORT QMJsonType<QString>::toJson(int32_t tab, QMJsonSort sort)
{
(void)tab;
(void)sort;
auto result = QString();
const auto &str = this->get();
result += '"';
for (int i = 0; i < str.length(); i++)
{
auto c = str.at(i).toLatin1();
switch (c)
{
case '\\':
result += "\\\\";
break;
case '"':
result += "\\\"";
break;
case '/':
result += "\\/";
break;
case '\b':
result += "\\b";
break;
case '\f':
result += "\\f";
break;
case '\n':
result += "\\n";
break;
case '\r':
result += "\\r";
break;
case '\t':
result += "\\t";
break;
default:
result += c;
break;
}
}
result += '"';
return result;
}
template <>
bool QM_JSON_EXPORT QMJsonType<QString>::isBaseType(void)
{
return true;
}
<commit_msg>Support \u escapes when converting from json.<commit_after>//
// QtMark JSON Library
//
// Copyright (C) 2015 Assured Information Security, Inc.
// Author: Rian Quinn <[email protected]>
// Author: Rodney Forbes <[email protected]>
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 2.1 of the License, or (at your option) any later version.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
// ============================================================================
// Includes
// ============================================================================
#include <qmjsontype_qstring.h>
// ============================================================================
// QMJsonType<QString> Implementation
// ============================================================================
template <>
QMPointer<QMJsonValue> QM_JSON_EXPORT QMJsonType<QString>::fromJson(const QString &json, int32_t &index)
{
auto result = QString();
index++;
while (1)
{
QMJsonValue::verifyIndex(json, index);
switch (json.at(index).toLatin1())
{
case '\\':
{
index++;
QMJsonValue::verifyIndex(json, index);
const int32_t CHARS_IN_UNICODE_ESCAPE = 4;
const int32_t HEX_BASE = 16;
switch (json.at(index).toLatin1())
{
case '"': result += '"'; break;
case '\\': result += '\\'; break;
case '/': result += '/'; break;
case 'b': result += '\b'; break;
case 'f': result += '\f'; break;
case 'n': result += '\n'; break;
case 'r': result += '\r'; break;
case 't': result += '\t'; break;
case 'u':
QMJsonValue::verifyIndex(json, index + CHARS_IN_UNICODE_ESCAPE);
result += json.mid(index + 1, CHARS_IN_UNICODE_ESCAPE).toUShort(Q_NULLPTR, HEX_BASE);
index += CHARS_IN_UNICODE_ESCAPE;
break;
default:
break;
};
index++;
break;
}
case '"':
index++;
return QMPointer<QMJsonValue>(new QMJsonValue(result));
default:
result += json.at(index++);
break;
};
}
return QMPointer<QMJsonValue>();
}
template <>
QString QM_JSON_EXPORT QMJsonType<QString>::toJson(int32_t tab, QMJsonSort sort)
{
(void)tab;
(void)sort;
auto result = QString();
const auto &str = this->get();
result += '"';
for (int i = 0; i < str.length(); i++)
{
auto c = str.at(i).toLatin1();
switch (c)
{
case '\\':
result += "\\\\";
break;
case '"':
result += "\\\"";
break;
case '/':
result += "\\/";
break;
case '\b':
result += "\\b";
break;
case '\f':
result += "\\f";
break;
case '\n':
result += "\\n";
break;
case '\r':
result += "\\r";
break;
case '\t':
result += "\\t";
break;
default:
result += c;
break;
}
}
result += '"';
return result;
}
template <>
bool QM_JSON_EXPORT QMJsonType<QString>::isBaseType(void)
{
return true;
}
<|endoftext|> |
<commit_before>/*
* GameKeeper Framework
*
* Copyright (C) 2013 Karol Herbst <[email protected]>
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
#include "pch.h"
#include "windowsinformation.h"
#include <cstdlib>
#include <windows.h>
#include <Shlobj.h>
#include <boost/locale/encoding_utf.hpp>
GAMEKEEPER_NAMESPACE_START(core)
using boost::locale::conv::utf_to_utf;
std::string
WindowsInformation::getEnv(const char * name)
{
wchar_t buffer[32767];
DWORD size = GetEnvironmentVariableW(utf_to_utf<wchar_t>(name).c_str(), buffer, 32767);
return utf_to_utf<char>(buffer, &buffer[size]);
}
void
WindowsInformation::setEnv(const char * name, const char * value)
{
SetEnvironmentVariableW(utf_to_utf<wchar_t>(name).c_str(), utf_to_utf<wchar_t>(value).c_str());
}
std::string
WindowsInformation::getEnvSeperator()
{
return ";";
}
boost::filesystem::path
WindowsInformation::getSystemRoot()
{
return "C:\\";
}
boost::filesystem::path
WindowsInformation::getUserPath()
{
TCHAR szPath[MAX_PATH];
SHGetFolderPath(NULL, CSIDL_PROFILE, NULL, 0, szPath);
return szPath;
}
GAMEKEEPER_NAMESPACE_END(core)
<commit_msg>core/windowsinformation: fix compile error while crosscompile<commit_after>/*
* GameKeeper Framework
*
* Copyright (C) 2013 Karol Herbst <[email protected]>
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
#include "pch.h"
#include "windowsinformation.h"
#include <cstdlib>
#include <windows.h>
#include <shlobj.h>
#include <boost/locale/encoding_utf.hpp>
GAMEKEEPER_NAMESPACE_START(core)
using boost::locale::conv::utf_to_utf;
std::string
WindowsInformation::getEnv(const char * name)
{
wchar_t buffer[32767];
DWORD size = GetEnvironmentVariableW(utf_to_utf<wchar_t>(name).c_str(), buffer, 32767);
return utf_to_utf<char>(buffer, &buffer[size]);
}
void
WindowsInformation::setEnv(const char * name, const char * value)
{
SetEnvironmentVariableW(utf_to_utf<wchar_t>(name).c_str(), utf_to_utf<wchar_t>(value).c_str());
}
std::string
WindowsInformation::getEnvSeperator()
{
return ";";
}
boost::filesystem::path
WindowsInformation::getSystemRoot()
{
return "C:\\";
}
boost::filesystem::path
WindowsInformation::getUserPath()
{
TCHAR szPath[MAX_PATH];
SHGetFolderPath(NULL, CSIDL_PROFILE, NULL, 0, szPath);
return szPath;
}
GAMEKEEPER_NAMESPACE_END(core)
<|endoftext|> |
<commit_before>#include "Camera.h"
#include <glm/gtc/matrix_transform.hpp>
#include <glm/gtx/quaternion.hpp>
#include <glm/gtc/quaternion.hpp>
#include <glm/gtx/rotate_vector.hpp>
#include <iostream>
Camera::Camera():
up({0, 1.0f, 0}),
pos({0, 0, 0}),
dir({0, 0, 1.0f}),
view_mat(glm::lookAt(pos, dir+pos, up))
{}
void Camera::translate(glm::vec3 pos) {
this->pos += pos;
}
void Camera::rotate(float angle, glm::vec3 axis) {
rot = glm::rotate(rot, angle, axis);
dir = glm::vec3(glm::vec4(0, 0, 1, 0.0f) * glm::mat4_cast(rot));
}
glm::mat4 Camera::get_view_mat() {
view_mat = glm::mat4{};
view_mat = glm::mat4_cast(rot) * view_mat;
view_mat = glm::translate(view_mat, pos);
return view_mat;
}
void Camera::move_forward(float dist) {
glm::vec3 temp = dir;
temp.y = 0;
temp = glm::normalize(temp);
this->translate(dist*temp);
}
void Camera::move_right(float dist) {
glm::vec3 left = glm::cross(up, dir);
this->translate(dist*left);
}
<commit_msg>Changed camera move direction<commit_after>#include "Camera.h"
#include <glm/gtc/matrix_transform.hpp>
#include <glm/gtx/quaternion.hpp>
#include <glm/gtc/quaternion.hpp>
#include <glm/gtx/rotate_vector.hpp>
#include <iostream>
Camera::Camera():
up({0, 1.0f, 0}),
pos({0, 0, 0}),
dir({0, 0, 1.0f}),
view_mat(glm::lookAt(pos, dir+pos, up))
{}
void Camera::translate(glm::vec3 pos) {
this->pos += pos;
}
void Camera::rotate(float angle, glm::vec3 axis) {
rot = glm::rotate(rot, angle, axis);
dir = glm::vec3(glm::vec4(0, 0, 1, 0.0f) * glm::mat4_cast(rot));
}
glm::mat4 Camera::get_view_mat() {
view_mat = glm::mat4{};
view_mat = glm::mat4_cast(rot) * view_mat;
view_mat = glm::translate(view_mat, pos);
return view_mat;
}
void Camera::move_forward(float dist) {
glm::vec3 temp = dir;
temp.y = 0;
temp = glm::normalize(temp);
this->translate(dist*temp);
}
void Camera::move_right(float dist) {
glm::vec3 left = glm::cross(up, dir);
this->translate(-dist*left);
}
<|endoftext|> |
<commit_before>#include "opt/mLibInclude.h"
#include "mLibCore.cpp"
#include "mLibLodePNG.cpp"
#include <gtest/gtest.h>
#include <kfusion/warp_field.hpp>
#include <string>
#include <vector>
#include "opt/main.h"
#include "opt/CombinedSolver.h"
#include "opt/OpenMesh.h"
#include <kfusion/warp_field.hpp>
TEST(OPT_WARP_FIELD, EnergyDataTest)
{
const float max_error = 1e-3;
kfusion::WarpField warpField;
std::vector<cv::Vec3f> warp_init;
warp_init.emplace_back(cv::Vec3f(1,1,1));
warp_init.emplace_back(cv::Vec3f(1,2,-1));
warp_init.emplace_back(cv::Vec3f(1,-2,1));
warp_init.emplace_back(cv::Vec3f(1,-1,-1));
warp_init.emplace_back(cv::Vec3f(-1,1,5));
warp_init.emplace_back(cv::Vec3f(-1,1,-1));
warp_init.emplace_back(cv::Vec3f(-1,-1,1));
warp_init.emplace_back(cv::Vec3f(-1,-1,-1));
warp_init.emplace_back(cv::Vec3f(2,-3,-1));
warpField.init(warp_init);
std::vector<cv::Vec3f> canonical_vertices;
canonical_vertices.emplace_back(cv::Vec3f(-3,-3,-3));
canonical_vertices.emplace_back(cv::Vec3f(-2,-2,-2));
canonical_vertices.emplace_back(cv::Vec3f(0,0,0));
canonical_vertices.emplace_back(cv::Vec3f(2,2,2));
canonical_vertices.emplace_back(cv::Vec3f(3,3,3));
canonical_vertices.emplace_back(cv::Vec3f(4,4,4));
std::vector<cv::Vec3f> canonical_normals;
canonical_normals.emplace_back(cv::Vec3f(0,0,1));
canonical_normals.emplace_back(cv::Vec3f(0,0,1));
canonical_normals.emplace_back(cv::Vec3f(0,0,1));
canonical_normals.emplace_back(cv::Vec3f(0,0,1));
canonical_normals.emplace_back(cv::Vec3f(0,0,1));
canonical_normals.emplace_back(cv::Vec3f(0,0,1));
std::vector<cv::Vec3f> live_vertices;
live_vertices.emplace_back(cv::Vec3f(-2.95f,-2.95f,-2.95f));
live_vertices.emplace_back(cv::Vec3f(-1.95f,-1.95f,-1.95f));
live_vertices.emplace_back(cv::Vec3f(0.05,0.05,0.05));
live_vertices.emplace_back(cv::Vec3f(2.05,2.05,2.05));
live_vertices.emplace_back(cv::Vec3f(3.05,3.05,3.05));
live_vertices.emplace_back(cv::Vec3f(4.5,4.05,6));
std::vector<cv::Vec3f> live_normals;
live_normals.emplace_back(cv::Vec3f(0,0,1));
live_normals.emplace_back(cv::Vec3f(0,0,1));
live_normals.emplace_back(cv::Vec3f(0,0,1));
live_normals.emplace_back(cv::Vec3f(0,0,1));
live_normals.emplace_back(cv::Vec3f(0,0,1));
live_normals.emplace_back(cv::Vec3f(0,0,1));
// CombinedSolverParameters params;
// params.numIter = 20;
// params.nonLinearIter = 15;
// params.linearIter = 250;
// params.useOpt = false;
// params.useOptLM = true;
//
// CombinedSolver solver(&warpField,
// canonical_vertices,
// canonical_normals,
// live_vertices,
// live_normals,
// params);
// solver.solveAll();
warpField.energy_data(canonical_vertices, canonical_normals, live_vertices, live_normals);
warpField.warp(canonical_vertices, canonical_normals);
for(size_t i = 0; i < canonical_vertices.size(); i++)
{
ASSERT_NEAR(canonical_vertices[i][0], live_vertices[i][0], max_error);
ASSERT_NEAR(canonical_vertices[i][1], live_vertices[i][1], max_error);
ASSERT_NEAR(canonical_vertices[i][2], live_vertices[i][2], max_error);
}
}
<commit_msg>Fixed Opt test<commit_after>#include "opt/mLibInclude.h"
#include "mLibCore.cpp"
#include "mLibLodePNG.cpp"
#include <gtest/gtest.h>
#include <kfusion/warp_field.hpp>
#include <kfusion/warp_field_optimiser.hpp>
#include <string>
#include <vector>
#include "opt/main.h"
#include "opt/CombinedSolver.h"
#include "opt/OpenMesh.h"
#include <kfusion/warp_field.hpp>
TEST(OPT_WARP_FIELD, EnergyDataTest)
{
const float max_error = 1e-3;
kfusion::WarpField warpField;
std::vector<cv::Vec3f> warp_init;
warp_init.emplace_back(cv::Vec3f(1,1,1));
warp_init.emplace_back(cv::Vec3f(1,2,-1));
warp_init.emplace_back(cv::Vec3f(1,-2,1));
warp_init.emplace_back(cv::Vec3f(1,-1,-1));
warp_init.emplace_back(cv::Vec3f(-1,1,5));
warp_init.emplace_back(cv::Vec3f(-1,1,-1));
warp_init.emplace_back(cv::Vec3f(-1,-1,1));
warp_init.emplace_back(cv::Vec3f(-1,-1,-1));
warp_init.emplace_back(cv::Vec3f(2,-3,-1));
warpField.init(warp_init);
std::vector<cv::Vec3f> canonical_vertices;
canonical_vertices.emplace_back(cv::Vec3f(-3,-3,-3));
canonical_vertices.emplace_back(cv::Vec3f(-2,-2,-2));
canonical_vertices.emplace_back(cv::Vec3f(0,0,0));
canonical_vertices.emplace_back(cv::Vec3f(2,2,2));
canonical_vertices.emplace_back(cv::Vec3f(3,3,3));
canonical_vertices.emplace_back(cv::Vec3f(4,4,4));
std::vector<cv::Vec3f> canonical_normals;
canonical_normals.emplace_back(cv::Vec3f(0,0,1));
canonical_normals.emplace_back(cv::Vec3f(0,0,1));
canonical_normals.emplace_back(cv::Vec3f(0,0,1));
canonical_normals.emplace_back(cv::Vec3f(0,0,1));
canonical_normals.emplace_back(cv::Vec3f(0,0,1));
canonical_normals.emplace_back(cv::Vec3f(0,0,1));
std::vector<cv::Vec3f> live_vertices;
live_vertices.emplace_back(cv::Vec3f(-2.95f,-2.95f,-2.95f));
live_vertices.emplace_back(cv::Vec3f(-1.95f,-1.95f,-1.95f));
live_vertices.emplace_back(cv::Vec3f(0.05,0.05,0.05));
live_vertices.emplace_back(cv::Vec3f(2.05,2.05,2.05));
live_vertices.emplace_back(cv::Vec3f(3.05,3.05,3.05));
live_vertices.emplace_back(cv::Vec3f(4.5,4.05,6));
std::vector<cv::Vec3f> live_normals;
live_normals.emplace_back(cv::Vec3f(0,0,1));
live_normals.emplace_back(cv::Vec3f(0,0,1));
live_normals.emplace_back(cv::Vec3f(0,0,1));
live_normals.emplace_back(cv::Vec3f(0,0,1));
live_normals.emplace_back(cv::Vec3f(0,0,1));
live_normals.emplace_back(cv::Vec3f(0,0,1));
CombinedSolverParameters params;
params.numIter = 20;
params.nonLinearIter = 15;
params.linearIter = 250;
params.useOpt = false;
params.useOptLM = true;
kfusion::WarpFieldOptimiser optimiser(&warpField, params);
optimiser.optimiseWarpData(canonical_vertices, canonical_normals, live_vertices, live_normals);
warpField.warp(canonical_vertices, canonical_normals);
for(size_t i = 0; i < canonical_vertices.size(); i++)
{
ASSERT_NEAR(canonical_vertices[i][0], live_vertices[i][0], max_error);
ASSERT_NEAR(canonical_vertices[i][1], live_vertices[i][1], max_error);
ASSERT_NEAR(canonical_vertices[i][2], live_vertices[i][2], max_error);
}
}
<|endoftext|> |
<commit_before>/*
* Copyright (C) 2014 Luke San Antonio
* All rights reserved.
*/
#include "object.h"
namespace survive
{
namespace gfx
{
Object create_object(gfx::IDriver& driver, std::string obj,
std::string mat) noexcept
{
auto ret = Object{};
ret.mesh = driver.prepare_mesh(Mesh::from_file(obj));
ret.material = load_material(mat);
return ret;
}
void object_render(Object const& obj) noexcept
{
if(obj.material) obj.material->use();
if(obj.mesh) obj.mesh->render();
}
}
}
<commit_msg>object_render should be render_object in gfx/object.cpp.<commit_after>/*
* Copyright (C) 2014 Luke San Antonio
* All rights reserved.
*/
#include "object.h"
namespace survive
{
namespace gfx
{
Object create_object(gfx::IDriver& driver, std::string obj,
std::string mat) noexcept
{
auto ret = Object{};
ret.mesh = driver.prepare_mesh(Mesh::from_file(obj));
ret.material = load_material(mat);
return ret;
}
void render_object(Object const& obj) noexcept
{
if(obj.material) obj.material->use();
if(obj.mesh) obj.mesh->render();
}
}
}
<|endoftext|> |
<commit_before>//
// $Id$
#include "script/Lexer.h"
Lexer::Lexer (const QString& expr, const QString& source) :
_expr(expr),
_source(source),
_idx(0),
_line(0),
_lineIdx(0)
{
}
/**
* Checks whether the specified character is a delimiter.
*/
static bool isDelimiter (QChar ch)
{
return ch.isSpace() || ch == ';' || ch == '#' || ch == '\"' ||
ch == '(' || ch == ')' || ch == '[' || ch == ']';
}
/**
* Creates the named character map.
*/
static QHash<QString, QChar> createNamedChars ()
{
QHash<QString, QChar> hash;
hash.insert("nul", 0x0);
hash.insert("alarm", 0x07);
hash.insert("backspace", 0x08);
hash.insert("tab", 0x09);
hash.insert("linefeed", 0x0A);
hash.insert("newline", 0x0A);
hash.insert("vtab", 0x0B);
hash.insert("page", 0x0C);
hash.insert("return", 0x0D);
hash.insert("esc", 0x1B);
hash.insert("space", 0x20);
hash.insert("delete", 0x7F);
return hash;
}
/**
* Returns a reference to the named character map.
*/
static const QHash<QString, QChar>& namedChars ()
{
static QHash<QString, QChar> namedChars = createNamedChars();
return namedChars;
}
int Lexer::nextLexeme ()
{
for (int nn = _expr.length(); _idx < nn; _idx++) {
QChar ch = _expr.at(_idx);
if (ch.isSpace()) {
if (ch == '\n') {
_line++;
_lineIdx = _idx + 1;
}
continue;
}
if (ch == ';') { // comment; ignore everything until the next line
for (_idx++; _idx < nn; _idx++) {
QChar ch = _expr.at(_idx);
if (ch == '\n') {
_line++;
_lineIdx = _idx + 1;
break;
}
}
continue;
}
_position = pos();
if (ch == '(' || ch == ')' || ch == '[' || ch == ']' || ch == '\'' || ch == '`') {
_idx++;
return ch.unicode();
}
if (ch == ',') {
_idx++;
if (_idx < nn && _expr.at(_idx) == '@') {
_idx++;
return UnquoteSplicing;
}
return ',';
}
if (ch == '\"') {
_string = "";
for (_idx++; _idx < nn; _idx++) {
QChar ch = _expr.at(_idx);
if (ch == '\\') {
if (++_idx == nn) {
break; // means the literal is unclosed
}
ch = _expr.at(_idx);
if (ch.isSpace()) { // continuation
for (; _idx < nn; _idx++) {
ch = _expr.at(_idx);
if (ch == '\n') {
_line++;
_lineIdx = _idx + 1;
break;
}
}
for (_idx++; _idx < nn; _idx++) {
ch = _expr.at(_idx);
if (!ch.isSpace() || ch == '\n') {
_idx--;
break;
}
}
continue;
}
switch (ch.unicode()) {
case '\"':
case '\\':
break;
case 'n':
ch = '\n';
break;
default:
throw ScriptError("Unrecognized escape.", pos());
}
} else if (ch == '\"') {
_idx++;
return String;
}
_string.append(ch);
}
throw ScriptError("Unclosed string literal.", _position);
}
if (ch == '#') {
if (_idx + 1 < nn) {
switch (_expr.at(_idx + 1).unicode()) {
case 't':
case 'T':
_boolValue = true;
_idx += 2;
return Boolean;
case 'f':
case 'F':
_boolValue = false;
_idx += 2;
return Boolean;
case '\\':
if (_idx + 2 < nn) {
QString string(_expr.at(_idx + 2));
for (_idx += 3; _idx < nn; _idx++) {
QChar ch = _expr.at(_idx);
if (isDelimiter(ch)) {
break;
}
string.append(ch);
}
if (string.size() == 1) {
_charValue = string.at(0);
return Char;
}
QHash<QString, QChar>::const_iterator it = namedChars().find(string);
if (it != namedChars().constEnd()) {
_charValue = it.value();
return Char;
}
if (string.at(0) != 'x') {
throw ScriptError("Unknown character.", _position);
}
bool ok;
int value = string.remove(0, 1).toInt(&ok, 16);
if (!ok || value < 0) {
throw ScriptError("Invalid character value.", _position);
}
_charValue = value;
return Char;
}
break;
case '(':
_idx += 2;
return Vector;
case 'v':
if (_idx + 4 < nn && _expr.mid(_idx + 2, 3) == "u8(") {
_idx += 5;
return ByteVector;
}
break;
case '\'':
_idx += 2;
return Syntax;
case '`':
_idx += 2;
return Quasisyntax;
case ',':
if (_idx + 2 < nn && _expr.at(_idx + 2) == '@') {
_idx += 3;
return UnsyntaxSplicing;
}
_idx += 2;
return Unsyntax;
case '!':
if (_idx + 5 < nn && _expr.mid(_idx + 2, 4) == "r6rs") {
_idx += 6;
continue;
}
break;
case '|': {
int depth = 1;
for (_idx += 2; _idx < nn; _idx++) {
QChar ch = _expr.at(_idx);
switch (ch.unicode()) {
case '\n':
_line++;
_lineIdx = _idx + 1;
break;
case '#':
if (_idx + 1 < nn && _expr.at(_idx + 1) == '|') {
_idx++;
depth++;
}
break;
case '|':
if (_idx + 1 < nn && _expr.at(_idx + 1) == '#') {
_idx++;
if (--depth == 0) {
goto outerContinue;
}
}
break;
}
}
break;
}
case ';':
_idx += 2;
return Comment;
}
}
} else if (ch == '+' || ch == '-') {
if (_idx + 1 < nn) {
QChar nch = _expr.at(_idx + 1);
if (nch.isDigit() || nch == '.') {
return readNumber();
}
}
} else if (ch == '.') {
if (_idx + 1 < nn) {
QChar nch = _expr.at(_idx + 1);
if (nch.isDigit()) {
return readNumber();
}
}
} else if (ch.isDigit()) {
return readNumber();
}
// assume it to be an identifier; search for first non-identifier character or end
_string = "";
for (; _idx < nn; _idx++) {
QChar ch = _expr.at(_idx);
if (isDelimiter(ch)) {
break;
}
_string.append(ch);
}
return Identifier;
// allow nested loops to continue
outerContinue: ;
}
return NoLexeme;
}
Lexer::LexemeType Lexer::readNumber ()
{
// read until we reach a non-number character, noting if we see a decimal
QString nstr;
bool decimal = false;
for (int nn = _expr.length(); _idx < nn; _idx++) {
QChar ch = _expr.at(_idx);
if (ch == '.') {
nstr.append(ch);
decimal = true;
continue;
}
if (!(ch.isLetter() || ch.isDigit() || ch == '+' || ch == '-')) {
break;
}
nstr.append(ch);
}
bool valid;
if (decimal) {
_floatValue = nstr.toFloat(&valid);
if (!valid) {
throw ScriptError("Invalid float literal.", _position);
}
return Float;
} else {
_intValue = nstr.toInt(&valid, 0); // allow 0x### for hex, 0### for octal
if (!valid) {
throw ScriptError("Invalid integer literal.", _position);
}
return Integer;
}
}
<commit_msg>Character codes in strings.<commit_after>//
// $Id$
#include "script/Lexer.h"
Lexer::Lexer (const QString& expr, const QString& source) :
_expr(expr),
_source(source),
_idx(0),
_line(0),
_lineIdx(0)
{
}
/**
* Checks whether the specified character is a delimiter.
*/
static bool isDelimiter (QChar ch)
{
return ch.isSpace() || ch == ';' || ch == '#' || ch == '\"' ||
ch == '(' || ch == ')' || ch == '[' || ch == ']';
}
/**
* Creates the named character map.
*/
static QHash<QString, QChar> createNamedChars ()
{
QHash<QString, QChar> hash;
hash.insert("nul", 0x0);
hash.insert("alarm", 0x07);
hash.insert("backspace", 0x08);
hash.insert("tab", 0x09);
hash.insert("linefeed", 0x0A);
hash.insert("newline", 0x0A);
hash.insert("vtab", 0x0B);
hash.insert("page", 0x0C);
hash.insert("return", 0x0D);
hash.insert("esc", 0x1B);
hash.insert("space", 0x20);
hash.insert("delete", 0x7F);
return hash;
}
/**
* Returns a reference to the named character map.
*/
static const QHash<QString, QChar>& namedChars ()
{
static QHash<QString, QChar> namedChars = createNamedChars();
return namedChars;
}
int Lexer::nextLexeme ()
{
for (int nn = _expr.length(); _idx < nn; _idx++) {
QChar ch = _expr.at(_idx);
if (ch.isSpace()) {
if (ch == '\n') {
_line++;
_lineIdx = _idx + 1;
}
continue;
}
if (ch == ';') { // comment; ignore everything until the next line
for (_idx++; _idx < nn; _idx++) {
QChar ch = _expr.at(_idx);
if (ch == '\n') {
_line++;
_lineIdx = _idx + 1;
break;
}
}
continue;
}
_position = pos();
if (ch == '(' || ch == ')' || ch == '[' || ch == ']' || ch == '\'' || ch == '`') {
_idx++;
return ch.unicode();
}
if (ch == ',') {
_idx++;
if (_idx < nn && _expr.at(_idx) == '@') {
_idx++;
return UnquoteSplicing;
}
return ',';
}
if (ch == '\"') {
_string = "";
for (_idx++; _idx < nn; _idx++) {
QChar ch = _expr.at(_idx);
if (ch == '\\') {
if (++_idx == nn) {
break; // means the literal is unclosed
}
ch = _expr.at(_idx);
if (ch.isSpace()) { // continuation
for (; _idx < nn; _idx++) {
ch = _expr.at(_idx);
if (ch == '\n') {
_line++;
_lineIdx = _idx + 1;
break;
}
}
for (_idx++; _idx < nn; _idx++) {
ch = _expr.at(_idx);
if (!ch.isSpace() || ch == '\n') {
_idx--;
break;
}
}
continue;
}
switch (ch.unicode()) {
case '\"':
case '\\':
break;
case 'a':
ch = '\a';
break;
case 'b':
ch = '\b';
break;
case 't':
ch = '\t';
break;
case 'n':
ch = '\n';
break;
case 'v':
ch = '\v';
break;
case 'f':
ch = '\f';
break;
case 'r':
ch = '\r';
break;
case 'x': {
QString string;
for (_idx++; _idx < nn; _idx++) {
QChar ch = _expr.at(_idx);
if (ch == ';') {
break;
}
string.append(ch);
}
bool ok;
ch = string.toInt(&ok, 16);
if (!ok) {
throw ScriptError("Invalid character code.", pos());
}
break;
}
default:
throw ScriptError("Unrecognized escape.", pos());
}
} else if (ch == '\"') {
_idx++;
return String;
}
_string.append(ch);
}
throw ScriptError("Unclosed string literal.", _position);
}
if (ch == '#') {
if (_idx + 1 < nn) {
switch (_expr.at(_idx + 1).unicode()) {
case 't':
case 'T':
_boolValue = true;
_idx += 2;
return Boolean;
case 'f':
case 'F':
_boolValue = false;
_idx += 2;
return Boolean;
case '\\':
if (_idx + 2 < nn) {
QString string(_expr.at(_idx + 2));
for (_idx += 3; _idx < nn; _idx++) {
QChar ch = _expr.at(_idx);
if (isDelimiter(ch)) {
break;
}
string.append(ch);
}
if (string.size() == 1) {
_charValue = string.at(0);
return Char;
}
QHash<QString, QChar>::const_iterator it = namedChars().find(string);
if (it != namedChars().constEnd()) {
_charValue = it.value();
return Char;
}
if (string.at(0) != 'x') {
throw ScriptError("Unknown character.", _position);
}
bool ok;
_charValue = string.remove(0, 1).toInt(&ok, 16);
if (!ok) {
throw ScriptError("Invalid character value.", _position);
}
return Char;
}
break;
case '(':
_idx += 2;
return Vector;
case 'v':
if (_idx + 4 < nn && _expr.mid(_idx + 2, 3) == "u8(") {
_idx += 5;
return ByteVector;
}
break;
case '\'':
_idx += 2;
return Syntax;
case '`':
_idx += 2;
return Quasisyntax;
case ',':
if (_idx + 2 < nn && _expr.at(_idx + 2) == '@') {
_idx += 3;
return UnsyntaxSplicing;
}
_idx += 2;
return Unsyntax;
case '!':
if (_idx + 5 < nn && _expr.mid(_idx + 2, 4) == "r6rs") {
_idx += 6;
continue;
}
break;
case '|': {
int depth = 1;
for (_idx += 2; _idx < nn; _idx++) {
QChar ch = _expr.at(_idx);
switch (ch.unicode()) {
case '\n':
_line++;
_lineIdx = _idx + 1;
break;
case '#':
if (_idx + 1 < nn && _expr.at(_idx + 1) == '|') {
_idx++;
depth++;
}
break;
case '|':
if (_idx + 1 < nn && _expr.at(_idx + 1) == '#') {
_idx++;
if (--depth == 0) {
goto outerContinue;
}
}
break;
}
}
break;
}
case ';':
_idx += 2;
return Comment;
}
}
} else if (ch == '+' || ch == '-') {
if (_idx + 1 < nn) {
QChar nch = _expr.at(_idx + 1);
if (nch.isDigit() || nch == '.') {
return readNumber();
}
}
} else if (ch == '.') {
if (_idx + 1 < nn) {
QChar nch = _expr.at(_idx + 1);
if (nch.isDigit()) {
return readNumber();
}
}
} else if (ch.isDigit()) {
return readNumber();
}
// assume it to be an identifier; search for first non-identifier character or end
_string = "";
for (; _idx < nn; _idx++) {
QChar ch = _expr.at(_idx);
if (isDelimiter(ch)) {
break;
}
_string.append(ch);
}
return Identifier;
// allow nested loops to continue
outerContinue: ;
}
return NoLexeme;
}
Lexer::LexemeType Lexer::readNumber ()
{
// read until we reach a non-number character, noting if we see a decimal
QString nstr;
bool decimal = false;
for (int nn = _expr.length(); _idx < nn; _idx++) {
QChar ch = _expr.at(_idx);
if (ch == '.') {
nstr.append(ch);
decimal = true;
continue;
}
if (!(ch.isLetter() || ch.isDigit() || ch == '+' || ch == '-')) {
break;
}
nstr.append(ch);
}
bool valid;
if (decimal) {
_floatValue = nstr.toFloat(&valid);
if (!valid) {
throw ScriptError("Invalid float literal.", _position);
}
return Float;
} else {
_intValue = nstr.toInt(&valid, 0); // allow 0x### for hex, 0### for octal
if (!valid) {
throw ScriptError("Invalid integer literal.", _position);
}
return Integer;
}
}
<|endoftext|> |
<commit_before>// Copyright (C) 2016 xaizek <[email protected]>
//
// This file is part of uncov.
//
// uncov is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// uncov 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 Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with uncov. If not, see <http://www.gnu.org/licenses/>.
#include "Catch/catch.hpp"
#include <cstdlib>
#include <iostream>
#include <stdexcept>
#include <string>
#include "BuildHistory.hpp"
#include "DB.hpp"
#include "Repository.hpp"
#include "SubCommand.hpp"
#include "TestUtils.hpp"
/**
* @brief Temporarily redirects specified stream from a string.
*/
class StreamSubstitute
{
public:
/**
* @brief Constructs instance that redirects @p is.
*
* @param is Stream to redirect.
* @param str Contents to splice into the stream.
*/
StreamSubstitute(std::istream &is, const std::string &str)
: is(is), iss(str)
{
rdbuf = is.rdbuf();
is.rdbuf(iss.rdbuf());
}
/**
* @brief Restores original state of the stream.
*/
~StreamSubstitute()
{
is.rdbuf(rdbuf);
}
private:
/**
* @brief Stream that is being redirected.
*/
std::istream &is;
/**
* @brief Temporary input buffer of the stream.
*/
std::istringstream iss;
/**
* @brief Original input buffer of the stream.
*/
std::streambuf *rdbuf;
};
static SubCommand * getCmd(const std::string &name);
TEST_CASE("Diff fails on wrong file path", "[subcommands][diff-subcommand]")
{
Repository repo("tests/test-repo/subdir");
DB db(repo.getGitPath() + "/uncover.sqlite");
BuildHistory bh(db);
StreamCapture coutCapture(std::cout), cerrCapture(std::cerr);
REQUIRE(getCmd("diff")->exec(bh, repo, { "no-such-path" }) == EXIT_FAILURE);
CHECK(coutCapture.get() == std::string());
CHECK(cerrCapture.get() != std::string());
}
TEST_CASE("New handles input gracefully", "[subcommands][new-subcommand]")
{
Repository repo("tests/test-repo/subdir");
DB db(repo.getGitPath() + "/uncover.sqlite");
BuildHistory bh(db);
StreamCapture coutCapture(std::cout), cerrCapture(std::cerr);
SECTION("Missing hashsum")
{
StreamSubstitute cinSubst(std::cin,
"8e354da4df664b71e06c764feb29a20d64351a01\n"
"master\n"
"test-file1.cpp\n"
"5\n"
"-1 1 -1 1 -1\n");
REQUIRE(getCmd("new")->exec(bh, repo, {}) == EXIT_FAILURE);
}
SECTION("Not number in coverage")
{
StreamSubstitute cinSubst(std::cin,
"8e354da4df664b71e06c764feb29a20d64351a01\n"
"master\n"
"test-file1.cpp\n"
"7e734c598d6ebdc19bbd660f6a7a6c73\n"
"5\n"
"-1 asdf -1 1 -1\n");
REQUIRE(getCmd("new")->exec(bh, repo, {}) == EXIT_FAILURE);
}
SECTION("Wrong file hash")
{
StreamSubstitute cinSubst(std::cin,
"8e354da4df664b71e06c764feb29a20d64351a01\n"
"master\n"
"test-file1.cpp\n"
"734c598d6ebdc19bbd660f6a7a6c73\n"
"5\n"
"-1 1 -1 1 -1\n");
REQUIRE(getCmd("new")->exec(bh, repo, {}) == EXIT_FAILURE);
}
CHECK(coutCapture.get() == std::string());
CHECK(cerrCapture.get() != std::string());
}
TEST_CASE("New creates new builds", "[subcommands][new-subcommand]")
{
Repository repo("tests/test-repo/subdir");
const std::string dbPath = repo.getGitPath() + "/uncover.sqlite";
FileRestorer databaseRestorer(dbPath, dbPath + "_original");
DB db(dbPath);
BuildHistory bh(db);
StreamCapture coutCapture(std::cout), cerrCapture(std::cerr);
SECTION("File missing from commit is just skipped")
{
auto sizeWas = bh.getBuilds().size();
StreamSubstitute cinSubst(std::cin,
"8e354da4df664b71e06c764feb29a20d64351a01\n"
"master\n"
"no-such-file\n"
"7e734c598d6ebdc19bbd660f6a7a6c73\n"
"5\n"
"-1 1 -1 1 -1\n");
REQUIRE(getCmd("new")->exec(bh, repo, {}) == EXIT_SUCCESS);
REQUIRE(bh.getBuilds().size() == sizeWas + 1);
REQUIRE(bh.getBuilds().back().getPaths() == vs({}));
CHECK(cerrCapture.get() != std::string());
}
SECTION("File path is normalized")
{
auto sizeWas = bh.getBuilds().size();
StreamSubstitute cinSubst(std::cin,
"8e354da4df664b71e06c764feb29a20d64351a01\n"
"master\n"
"././test-file1.cpp\n"
"7e734c598d6ebdc19bbd660f6a7a6c73\n"
"5\n"
"-1 1 -1 1 -1\n");
REQUIRE(getCmd("new")->exec(bh, repo, {}) == EXIT_SUCCESS);
REQUIRE(bh.getBuilds().size() == sizeWas + 1);
REQUIRE(bh.getBuilds().back().getPaths() != vs({}));
CHECK(cerrCapture.get() == std::string());
}
SECTION("Well-formed input is accepted")
{
auto sizeWas = bh.getBuilds().size();
StreamSubstitute cinSubst(std::cin,
"8e354da4df664b71e06c764feb29a20d64351a01\n"
"master\n"
"test-file1.cpp\n"
"7e734c598d6ebdc19bbd660f6a7a6c73\n"
"5\n"
"-1 1 -1 1 -1\n");
REQUIRE(getCmd("new")->exec(bh, repo, {}) == EXIT_SUCCESS);
REQUIRE(bh.getBuilds().size() == sizeWas + 1);
REQUIRE(bh.getBuilds().back().getPaths() != vs({}));
CHECK(cerrCapture.get() == std::string());
}
CHECK(coutCapture.get() != std::string());
}
static SubCommand *
getCmd(const std::string &name)
{
for (SubCommand *cmd : SubCommand::getAll()) {
if (cmd->getName() == name) {
return cmd;
}
}
throw std::invalid_argument("No such command: " + name);
}
<commit_msg>REQUIRE => CHECK in some sub_commands tests<commit_after>// Copyright (C) 2016 xaizek <[email protected]>
//
// This file is part of uncov.
//
// uncov is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// uncov 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 Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with uncov. If not, see <http://www.gnu.org/licenses/>.
#include "Catch/catch.hpp"
#include <cstdlib>
#include <iostream>
#include <stdexcept>
#include <string>
#include "BuildHistory.hpp"
#include "DB.hpp"
#include "Repository.hpp"
#include "SubCommand.hpp"
#include "TestUtils.hpp"
/**
* @brief Temporarily redirects specified stream from a string.
*/
class StreamSubstitute
{
public:
/**
* @brief Constructs instance that redirects @p is.
*
* @param is Stream to redirect.
* @param str Contents to splice into the stream.
*/
StreamSubstitute(std::istream &is, const std::string &str)
: is(is), iss(str)
{
rdbuf = is.rdbuf();
is.rdbuf(iss.rdbuf());
}
/**
* @brief Restores original state of the stream.
*/
~StreamSubstitute()
{
is.rdbuf(rdbuf);
}
private:
/**
* @brief Stream that is being redirected.
*/
std::istream &is;
/**
* @brief Temporary input buffer of the stream.
*/
std::istringstream iss;
/**
* @brief Original input buffer of the stream.
*/
std::streambuf *rdbuf;
};
static SubCommand * getCmd(const std::string &name);
TEST_CASE("Diff fails on wrong file path", "[subcommands][diff-subcommand]")
{
Repository repo("tests/test-repo/subdir");
DB db(repo.getGitPath() + "/uncover.sqlite");
BuildHistory bh(db);
StreamCapture coutCapture(std::cout), cerrCapture(std::cerr);
CHECK(getCmd("diff")->exec(bh, repo, { "no-such-path" }) == EXIT_FAILURE);
CHECK(coutCapture.get() == std::string());
CHECK(cerrCapture.get() != std::string());
}
TEST_CASE("New handles input gracefully", "[subcommands][new-subcommand]")
{
Repository repo("tests/test-repo/subdir");
DB db(repo.getGitPath() + "/uncover.sqlite");
BuildHistory bh(db);
StreamCapture coutCapture(std::cout), cerrCapture(std::cerr);
SECTION("Missing hashsum")
{
StreamSubstitute cinSubst(std::cin,
"8e354da4df664b71e06c764feb29a20d64351a01\n"
"master\n"
"test-file1.cpp\n"
"5\n"
"-1 1 -1 1 -1\n");
CHECK(getCmd("new")->exec(bh, repo, {}) == EXIT_FAILURE);
}
SECTION("Not number in coverage")
{
StreamSubstitute cinSubst(std::cin,
"8e354da4df664b71e06c764feb29a20d64351a01\n"
"master\n"
"test-file1.cpp\n"
"7e734c598d6ebdc19bbd660f6a7a6c73\n"
"5\n"
"-1 asdf -1 1 -1\n");
CHECK(getCmd("new")->exec(bh, repo, {}) == EXIT_FAILURE);
}
SECTION("Wrong file hash")
{
StreamSubstitute cinSubst(std::cin,
"8e354da4df664b71e06c764feb29a20d64351a01\n"
"master\n"
"test-file1.cpp\n"
"734c598d6ebdc19bbd660f6a7a6c73\n"
"5\n"
"-1 1 -1 1 -1\n");
CHECK(getCmd("new")->exec(bh, repo, {}) == EXIT_FAILURE);
}
CHECK(coutCapture.get() == std::string());
CHECK(cerrCapture.get() != std::string());
}
TEST_CASE("New creates new builds", "[subcommands][new-subcommand]")
{
Repository repo("tests/test-repo/subdir");
const std::string dbPath = repo.getGitPath() + "/uncover.sqlite";
FileRestorer databaseRestorer(dbPath, dbPath + "_original");
DB db(dbPath);
BuildHistory bh(db);
StreamCapture coutCapture(std::cout), cerrCapture(std::cerr);
SECTION("File missing from commit is just skipped")
{
auto sizeWas = bh.getBuilds().size();
StreamSubstitute cinSubst(std::cin,
"8e354da4df664b71e06c764feb29a20d64351a01\n"
"master\n"
"no-such-file\n"
"7e734c598d6ebdc19bbd660f6a7a6c73\n"
"5\n"
"-1 1 -1 1 -1\n");
CHECK(getCmd("new")->exec(bh, repo, {}) == EXIT_SUCCESS);
REQUIRE(bh.getBuilds().size() == sizeWas + 1);
REQUIRE(bh.getBuilds().back().getPaths() == vs({}));
CHECK(cerrCapture.get() != std::string());
}
SECTION("File path is normalized")
{
auto sizeWas = bh.getBuilds().size();
StreamSubstitute cinSubst(std::cin,
"8e354da4df664b71e06c764feb29a20d64351a01\n"
"master\n"
"././test-file1.cpp\n"
"7e734c598d6ebdc19bbd660f6a7a6c73\n"
"5\n"
"-1 1 -1 1 -1\n");
CHECK(getCmd("new")->exec(bh, repo, {}) == EXIT_SUCCESS);
REQUIRE(bh.getBuilds().size() == sizeWas + 1);
REQUIRE(bh.getBuilds().back().getPaths() != vs({}));
CHECK(cerrCapture.get() == std::string());
}
SECTION("Well-formed input is accepted")
{
auto sizeWas = bh.getBuilds().size();
StreamSubstitute cinSubst(std::cin,
"8e354da4df664b71e06c764feb29a20d64351a01\n"
"master\n"
"test-file1.cpp\n"
"7e734c598d6ebdc19bbd660f6a7a6c73\n"
"5\n"
"-1 1 -1 1 -1\n");
CHECK(getCmd("new")->exec(bh, repo, {}) == EXIT_SUCCESS);
REQUIRE(bh.getBuilds().size() == sizeWas + 1);
REQUIRE(bh.getBuilds().back().getPaths() != vs({}));
CHECK(cerrCapture.get() == std::string());
}
CHECK(coutCapture.get() != std::string());
}
static SubCommand *
getCmd(const std::string &name)
{
for (SubCommand *cmd : SubCommand::getAll()) {
if (cmd->getName() == name) {
return cmd;
}
}
throw std::invalid_argument("No such command: " + name);
}
<|endoftext|> |
<commit_before>#include "h2olog.h"
#include "json.h"
#include <cstdio>
#include <cstring>
#include <cinttypes>
extern "C" {
#include <sys/socket.h>
#include <netinet/in.h>
#include "h2o/socket.h"
}
using namespace std;
#define FPUTS_LIT(s, out) fwrite(s, 1, strlen(s), out)
static bool json_need_escape(char c)
{
return static_cast<unsigned char>(c) < 0x20 || c == 0x7f;
}
static void json_write_str_value(FILE *out, const char *str)
{
fputc('"', out);
while (*str) {
switch (*str) {
case '\"':
FPUTS_LIT("\\\"", out);
break;
case '\\':
FPUTS_LIT("\\\\", out);
break;
case '\b':
FPUTS_LIT("\\b", out);
break;
case '\f':
FPUTS_LIT("\\f", out);
break;
case '\n':
FPUTS_LIT("\\n", out);
break;
case '\r':
FPUTS_LIT("\\r", out);
break;
case '\t':
FPUTS_LIT("\\t", out);
break;
default:
if (!json_need_escape(*str)) {
fputc(*str, out);
} else {
auto u8 = static_cast<uint8_t>(*str);
fprintf(out, "\\u%04x", u8);
}
break;
}
str++;
}
fputc('"', out);
}
static void json_write_name_value(FILE *out, const char *name, size_t name_len)
{
fputc('"', out);
fwrite(name, 1, name_len, out);
fputc('"', out);
fputc(':', out);
}
void json_write_pair_n(FILE *out, const char *name, size_t name_len, const char *value)
{
json_write_name_value(out, name, name_len);
json_write_str_value(out, value);
}
void json_write_pair_c(FILE *out, const char *name, size_t name_len, const char *value)
{
fputc(',', out);
json_write_name_value(out, name, name_len);
json_write_str_value(out, value);
}
void json_write_pair_c(FILE *out, const char *name, size_t name_len, const void *value, size_t len)
{
fputc(',', out);
json_write_name_value(out, name, name_len);
fputc('"', out);
const uint8_t *bin = static_cast<const uint8_t *>(value);
for (size_t i = 0; i < len; i++) {
fputc("0123456789abcdef"[bin[i] >> 4], out);
fputc("0123456789abcdef"[bin[i] & 0xf], out);
}
fputc('"', out);
}
void json_write_pair_c(FILE *out, const char *name, size_t name_len, int32_t value)
{
json_write_pair_c(out, name, name_len, static_cast<int64_t>(value));
}
void json_write_pair_c(FILE *out, const char *name, size_t name_len, uint32_t value)
{
json_write_pair_c(out, name, name_len, static_cast<uint64_t>(value));
}
void json_write_pair_c(FILE *out, const char *name, size_t name_len, int64_t value)
{
fputc(',', out);
json_write_name_value(out, name, name_len);
fprintf(out, "%" PRId64, value);
}
void json_write_pair_c(FILE *out, const char *name, size_t name_len, uint64_t value)
{
fputc(',', out);
json_write_name_value(out, name, name_len);
fprintf(out, "%" PRIu64, value);
}
void json_write_pair_c(FILE *out, const char *name, size_t name_len, const h2olog_address_t &value)
{
const sockaddr *sa = &value.sa;
fputc(',', out);
json_write_name_value(out, name, name_len);
char addr[NI_MAXHOST];
size_t addr_len = h2o_socket_getnumerichost(sa, sizeof(h2olog_address_t), addr);
if (addr_len == SIZE_MAX) {
fprintf(out, "null");
return;
}
int32_t port = h2o_socket_getport(sa);
fputc('"', out);
if (sa->sa_family == AF_INET) {
// e.g. "1.2.3.4:12345"
fwrite(addr, 1, addr_len, out);
} else if (sa->sa_family == AF_INET6) {
// e.g. "[2001:0db8:85a3::8a2e:0370:7334]:12345"
fputc('[', out);
fwrite(addr, 1, addr_len, out);
fputc(']', out);
}
fputc(':', out);
fprintf(out, "%" PRId32, port);
fputc('"', out);
}
<commit_msg>include netdb.h for NI_MAXHOST<commit_after>#include "h2olog.h"
#include "json.h"
#include <cstdio>
#include <cstring>
#include <cinttypes>
extern "C" {
#include <sys/socket.h>
#include <netinet/in.h>
#include <netdb.h>
#include "h2o/socket.h"
}
using namespace std;
#define FPUTS_LIT(s, out) fwrite(s, 1, strlen(s), out)
static bool json_need_escape(char c)
{
return static_cast<unsigned char>(c) < 0x20 || c == 0x7f;
}
static void json_write_str_value(FILE *out, const char *str)
{
fputc('"', out);
while (*str) {
switch (*str) {
case '\"':
FPUTS_LIT("\\\"", out);
break;
case '\\':
FPUTS_LIT("\\\\", out);
break;
case '\b':
FPUTS_LIT("\\b", out);
break;
case '\f':
FPUTS_LIT("\\f", out);
break;
case '\n':
FPUTS_LIT("\\n", out);
break;
case '\r':
FPUTS_LIT("\\r", out);
break;
case '\t':
FPUTS_LIT("\\t", out);
break;
default:
if (!json_need_escape(*str)) {
fputc(*str, out);
} else {
auto u8 = static_cast<uint8_t>(*str);
fprintf(out, "\\u%04x", u8);
}
break;
}
str++;
}
fputc('"', out);
}
static void json_write_name_value(FILE *out, const char *name, size_t name_len)
{
fputc('"', out);
fwrite(name, 1, name_len, out);
fputc('"', out);
fputc(':', out);
}
void json_write_pair_n(FILE *out, const char *name, size_t name_len, const char *value)
{
json_write_name_value(out, name, name_len);
json_write_str_value(out, value);
}
void json_write_pair_c(FILE *out, const char *name, size_t name_len, const char *value)
{
fputc(',', out);
json_write_name_value(out, name, name_len);
json_write_str_value(out, value);
}
void json_write_pair_c(FILE *out, const char *name, size_t name_len, const void *value, size_t len)
{
fputc(',', out);
json_write_name_value(out, name, name_len);
fputc('"', out);
const uint8_t *bin = static_cast<const uint8_t *>(value);
for (size_t i = 0; i < len; i++) {
fputc("0123456789abcdef"[bin[i] >> 4], out);
fputc("0123456789abcdef"[bin[i] & 0xf], out);
}
fputc('"', out);
}
void json_write_pair_c(FILE *out, const char *name, size_t name_len, int32_t value)
{
json_write_pair_c(out, name, name_len, static_cast<int64_t>(value));
}
void json_write_pair_c(FILE *out, const char *name, size_t name_len, uint32_t value)
{
json_write_pair_c(out, name, name_len, static_cast<uint64_t>(value));
}
void json_write_pair_c(FILE *out, const char *name, size_t name_len, int64_t value)
{
fputc(',', out);
json_write_name_value(out, name, name_len);
fprintf(out, "%" PRId64, value);
}
void json_write_pair_c(FILE *out, const char *name, size_t name_len, uint64_t value)
{
fputc(',', out);
json_write_name_value(out, name, name_len);
fprintf(out, "%" PRIu64, value);
}
void json_write_pair_c(FILE *out, const char *name, size_t name_len, const h2olog_address_t &value)
{
const sockaddr *sa = &value.sa;
fputc(',', out);
json_write_name_value(out, name, name_len);
char addr[NI_MAXHOST];
size_t addr_len = h2o_socket_getnumerichost(sa, sizeof(h2olog_address_t), addr);
if (addr_len == SIZE_MAX) {
fprintf(out, "null");
return;
}
int32_t port = h2o_socket_getport(sa);
fputc('"', out);
if (sa->sa_family == AF_INET) {
// e.g. "1.2.3.4:12345"
fwrite(addr, 1, addr_len, out);
} else if (sa->sa_family == AF_INET6) {
// e.g. "[2001:0db8:85a3::8a2e:0370:7334]:12345"
fputc('[', out);
fwrite(addr, 1, addr_len, out);
fputc(']', out);
}
fputc(':', out);
fprintf(out, "%" PRId32, port);
fputc('"', out);
}
<|endoftext|> |
<commit_before>/**
* Copyright (c) 2016, Loic Blot <[email protected]>
* All rights reserved.
* Redistribution and use in source and binary forms, with or without modification,
* are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation and/or
* other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
* IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
* INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
* EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include "httpserver.h"
#include <cstring>
#include <cassert>
#include <iostream>
#include <sstream>
#include "utils/stringutils.h"
static const char* NOT_FOUND_PAGE = "<html><head><title>Not found</title></head><body><h1>No resource found at this address.</h1></body></html>";
static const char* BAD_REQUEST = "<html><head><title>Bad request</title></head><body><h1>Bad request</h1></body></html>";
HTTPServer::HTTPServer(const uint16_t http_port): m_http_port(http_port)
{
m_mhd_daemon = MHD_start_daemon(MHD_USE_THREAD_PER_CONNECTION, m_http_port, NULL,
NULL, &HTTPServer::request_handler, this, MHD_OPTION_NOTIFY_COMPLETED,
&HTTPServer::request_completed, NULL, MHD_OPTION_END);
}
HTTPServer::~HTTPServer()
{
if (m_mhd_daemon) {
MHD_stop_daemon(m_mhd_daemon);
}
}
struct HTTPRequestSession
{
std::string result = "";
bool data_handled = false;
uint32_t http_code = MHD_HTTP_OK;
};
int HTTPServer::request_handler(void *http_server, struct MHD_Connection *connection,
const char *url, const char *method, const char *version, const char *upload_data,
size_t *upload_data_size, void **con_cls)
{
HTTPServer *httpd = (HTTPServer *) http_server;
HTTPMethod http_method;
struct MHD_Response *response;
int ret;
if (strcmp(method, "GET") == 0) {
http_method = HTTP_METHOD_GET;
}
else if (strcmp(method, "POST") == 0) {
http_method = HTTP_METHOD_POST;
}
else if (strcmp(method, "PUT") == 0) {
http_method = HTTP_METHOD_PUT;
}
else if (strcmp(method, "PATCH") == 0) {
http_method = HTTP_METHOD_PATCH;
}
else if (strcmp(method, "PROPFIND") == 0) {
http_method = HTTP_METHOD_PROPFIND;
}
else if (strcmp(method, "DELETE") == 0) {
http_method = HTTP_METHOD_DELETE;
}
else if (strcmp(method, "HEAD") == 0) {
http_method = HTTP_METHOD_HEAD;
}
else {
return MHD_NO; /* unexpected method */
}
if (*con_cls == NULL) {
// The first time only the headers are valid,
// do not respond in the first round...
// Just init our response
HTTPRequestSession *session = new HTTPRequestSession();
*con_cls = session;
return MHD_YES;
}
// Handle request
HTTPRequestSession *session = (HTTPRequestSession *) *con_cls;
if (!session->data_handled && !httpd->handle_query(http_method, connection, std::string(url),
std::string(upload_data, *upload_data_size), session->result)) {
session->result = std::string(BAD_REQUEST);
session->http_code = MHD_HTTP_BAD_REQUEST;
}
// When post data is available, reinit the data_size because this function
// is called another time. And mark the current session as handled
if (*upload_data_size > 0) {
*upload_data_size = 0;
session->data_handled = true;
return MHD_YES;
}
response = MHD_create_response_from_buffer(session->result.length(),
(void *) session->result.c_str(), MHD_RESPMEM_MUST_COPY);
ret = MHD_queue_response(connection, session->http_code, response);
MHD_destroy_response(response);
// clear context pointer
delete session;
*con_cls = NULL;
return ret;
}
void HTTPServer::request_completed(void *cls, struct MHD_Connection *connection,
void **con_cls, MHD_RequestTerminationCode toe)
{
}
bool HTTPServer::handle_query(HTTPMethod m, MHD_Connection *conn, const std::string &url,
const std::string &upload_data, std::string &result)
{
assert(m < HTTP_METHOD_MAX);
HTTPServerReqHandlerMap::const_iterator url_handler = m_handlers[m].find(url);
if (url_handler == m_handlers[m].end()) {
return false;
}
HTTPQueryPtr q;
// Read which params we want and store them
const char* content_type = MHD_lookup_connection_value(conn, MHD_HEADER_KIND, "Content-Type");
if (!content_type) {
q = HTTPQueryPtr(new HTTPQuery());
}
else if (strcmp(content_type, "application/x-www-form-urlencoded") == 0) {
q = HTTPQueryPtr(new HTTPFormQuery());
if (!parse_post_data(upload_data, q)) {
return false;
}
}
else if (strcmp(content_type, "application/json") == 0) {
HTTPJsonQuery *jq = new HTTPJsonQuery();
q = HTTPQueryPtr(jq);
Json::Reader reader;
if (!reader.parse(upload_data, jq->json_query)) {
return false;
}
}
else {
q = HTTPQueryPtr(new HTTPQuery());
}
q->url = url;
MHD_get_connection_values(conn, MHD_HEADER_KIND, &HTTPServer::mhd_iter_headers, q.get());
MHD_get_connection_values(conn, MHD_GET_ARGUMENT_KIND, &HTTPServer::mhd_iter_getargs, q.get());
return url_handler->second(q, result);
}
int HTTPServer::mhd_iter_headers(void *cls, MHD_ValueKind, const char *key,
const char *value)
{
HTTPQuery *q = (HTTPQuery *) cls;
if (q && key && value) {
q->headers[std::string(key)] = std::string(value);
}
return MHD_YES; // continue iteration
}
int HTTPServer::mhd_iter_getargs(void *cls, MHD_ValueKind, const char *key,
const char *value)
{
HTTPQuery *q = (HTTPQuery *) cls;
if (q && key && value) {
q->get_params[std::string(key)] = std::string(value);
}
return MHD_YES; // continue iteration
}
bool HTTPServer::parse_post_data(const std::string &data, HTTPQueryPtr q)
{
HTTPFormQuery *qf = dynamic_cast<HTTPFormQuery *>(q.get());
assert(qf);
std::vector<std::string> first_split;
str_split(data, '&', first_split);
for (const auto &s: first_split) {
// If this post data is empty, abort
if (s.empty()) {
return false;
}
std::vector<std::string> kv;
str_split(s, '=', kv);
// If the key value pair is invalid, abort
if (kv.size() != 2 || kv[0].empty() || kv[1].empty()) {
return false;
}
qf->post_data[kv[0]] = kv[1];
}
return true;
}
<commit_msg>Properly create strings using strlen for length of strings<commit_after>/**
* Copyright (c) 2016, Loic Blot <[email protected]>
* All rights reserved.
* Redistribution and use in source and binary forms, with or without modification,
* are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation and/or
* other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
* IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
* INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
* EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include "httpserver.h"
#include <cstring>
#include <cassert>
#include <iostream>
#include <sstream>
#include "utils/stringutils.h"
static const char* NOT_FOUND_PAGE = "<html><head><title>Not found</title></head><body><h1>No resource found at this address.</h1></body></html>";
static const char* BAD_REQUEST = "<html><head><title>Bad request</title></head><body><h1>Bad request</h1></body></html>";
HTTPServer::HTTPServer(const uint16_t http_port): m_http_port(http_port)
{
m_mhd_daemon = MHD_start_daemon(MHD_USE_THREAD_PER_CONNECTION, m_http_port, NULL,
NULL, &HTTPServer::request_handler, this, MHD_OPTION_NOTIFY_COMPLETED,
&HTTPServer::request_completed, NULL, MHD_OPTION_END);
}
HTTPServer::~HTTPServer()
{
if (m_mhd_daemon) {
MHD_stop_daemon(m_mhd_daemon);
}
}
struct HTTPRequestSession
{
std::string result = "";
bool data_handled = false;
uint32_t http_code = MHD_HTTP_OK;
};
int HTTPServer::request_handler(void *http_server, struct MHD_Connection *connection,
const char *url, const char *method, const char *version, const char *upload_data,
size_t *upload_data_size, void **con_cls)
{
HTTPServer *httpd = (HTTPServer *) http_server;
HTTPMethod http_method;
struct MHD_Response *response;
int ret;
if (strcmp(method, "GET") == 0) {
http_method = HTTP_METHOD_GET;
}
else if (strcmp(method, "POST") == 0) {
http_method = HTTP_METHOD_POST;
}
else if (strcmp(method, "PUT") == 0) {
http_method = HTTP_METHOD_PUT;
}
else if (strcmp(method, "PATCH") == 0) {
http_method = HTTP_METHOD_PATCH;
}
else if (strcmp(method, "PROPFIND") == 0) {
http_method = HTTP_METHOD_PROPFIND;
}
else if (strcmp(method, "DELETE") == 0) {
http_method = HTTP_METHOD_DELETE;
}
else if (strcmp(method, "HEAD") == 0) {
http_method = HTTP_METHOD_HEAD;
}
else {
return MHD_NO; /* unexpected method */
}
if (*con_cls == NULL) {
// The first time only the headers are valid,
// do not respond in the first round...
// Just init our response
HTTPRequestSession *session = new HTTPRequestSession();
*con_cls = session;
return MHD_YES;
}
// Handle request
HTTPRequestSession *session = (HTTPRequestSession *) *con_cls;
if (!session->data_handled && !httpd->handle_query(http_method, connection, std::string(url),
std::string(upload_data, *upload_data_size), session->result)) {
session->result = std::string(BAD_REQUEST);
session->http_code = MHD_HTTP_BAD_REQUEST;
}
// When post data is available, reinit the data_size because this function
// is called another time. And mark the current session as handled
if (*upload_data_size > 0) {
*upload_data_size = 0;
session->data_handled = true;
return MHD_YES;
}
response = MHD_create_response_from_buffer(session->result.length(),
(void *) session->result.c_str(), MHD_RESPMEM_MUST_COPY);
ret = MHD_queue_response(connection, session->http_code, response);
MHD_destroy_response(response);
// clear context pointer
delete session;
*con_cls = NULL;
return ret;
}
void HTTPServer::request_completed(void *cls, struct MHD_Connection *connection,
void **con_cls, MHD_RequestTerminationCode toe)
{
}
bool HTTPServer::handle_query(HTTPMethod m, MHD_Connection *conn, const std::string &url,
const std::string &upload_data, std::string &result)
{
assert(m < HTTP_METHOD_MAX);
HTTPServerReqHandlerMap::const_iterator url_handler = m_handlers[m].find(url);
if (url_handler == m_handlers[m].end()) {
return false;
}
HTTPQueryPtr q;
// Read which params we want and store them
const char* content_type = MHD_lookup_connection_value(conn, MHD_HEADER_KIND, "Content-Type");
if (!content_type) {
q = HTTPQueryPtr(new HTTPQuery());
}
else if (strcmp(content_type, "application/x-www-form-urlencoded") == 0) {
q = HTTPQueryPtr(new HTTPFormQuery());
if (!parse_post_data(upload_data, q)) {
return false;
}
}
else if (strcmp(content_type, "application/json") == 0) {
HTTPJsonQuery *jq = new HTTPJsonQuery();
q = HTTPQueryPtr(jq);
Json::Reader reader;
if (!reader.parse(upload_data, jq->json_query)) {
return false;
}
}
else {
q = HTTPQueryPtr(new HTTPQuery());
}
q->url = url;
MHD_get_connection_values(conn, MHD_HEADER_KIND, &HTTPServer::mhd_iter_headers, q.get());
MHD_get_connection_values(conn, MHD_GET_ARGUMENT_KIND, &HTTPServer::mhd_iter_getargs, q.get());
return url_handler->second(q, result);
}
int HTTPServer::mhd_iter_headers(void *cls, MHD_ValueKind, const char *key,
const char *value)
{
HTTPQuery *q = (HTTPQuery *) cls;
if (q && key && value) {
q->headers[std::string(key, strlen(key))] = std::string(value, strlen(value));
}
return MHD_YES; // continue iteration
}
int HTTPServer::mhd_iter_getargs(void *cls, MHD_ValueKind, const char *key,
const char *value)
{
HTTPQuery *q = (HTTPQuery *) cls;
if (q && key && value) {
q->get_params[std::string(key, strlen(key))] = std::string(value, strlen(value));
}
return MHD_YES; // continue iteration
}
bool HTTPServer::parse_post_data(const std::string &data, HTTPQueryPtr q)
{
HTTPFormQuery *qf = dynamic_cast<HTTPFormQuery *>(q.get());
assert(qf);
std::vector<std::string> first_split;
str_split(data, '&', first_split);
for (const auto &s: first_split) {
// If this post data is empty, abort
if (s.empty()) {
return false;
}
std::vector<std::string> kv;
str_split(s, '=', kv);
// If the key value pair is invalid, abort
if (kv.size() != 2 || kv[0].empty() || kv[1].empty()) {
return false;
}
qf->post_data[kv[0]] = kv[1];
}
return true;
}
<|endoftext|> |
<commit_before>/**
* Copyright (c) 2016, Loic Blot <[email protected]>
* All rights reserved.
* Redistribution and use in source and binary forms, with or without modification,
* are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation and/or
* other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
* IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
* INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
* EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include "httpserver.h"
#include <cstring>
#include <cassert>
#include <iostream>
#include <stdlib.h>
#include <sstream>
#include "utils/stringutils.h"
static const char* NOT_FOUND_PAGE = "<html><head><title>Not found</title></head><body><h1>No resource found at this address.</h1></body></html>";
static const char* BAD_REQUEST = "<html><head><title>Bad request</title></head><body><h1>Bad request</h1></body></html>";
HTTPServer::HTTPServer(const uint16_t http_port): m_http_port(http_port)
{
m_mhd_daemon = MHD_start_daemon(MHD_USE_THREAD_PER_CONNECTION, m_http_port, NULL,
NULL, &HTTPServer::request_handler, this, MHD_OPTION_NOTIFY_COMPLETED,
&HTTPServer::request_completed, NULL, MHD_OPTION_END);
}
HTTPServer::~HTTPServer()
{
if (m_mhd_daemon) {
MHD_stop_daemon(m_mhd_daemon);
}
}
struct HTTPRequestSession
{
std::string result = "";
bool data_handled = false;
};
int HTTPServer::request_handler(void *http_server, struct MHD_Connection *connection,
const char *url, const char *method, const char *version, const char *upload_data,
size_t *upload_data_size, void **con_cls)
{
HTTPServer *httpd = (HTTPServer *) http_server;
HTTPMethod http_method;
struct MHD_Response *response;
int ret;
if (strcmp(method, "GET") == 0) {
http_method = HTTP_METHOD_GET;
}
else if (strcmp(method, "POST") == 0) {
http_method = HTTP_METHOD_POST;
}
else if (strcmp(method, "PUT") == 0) {
http_method = HTTP_METHOD_PUT;
}
else if (strcmp(method, "PATCH") == 0) {
http_method = HTTP_METHOD_PATCH;
}
else if (strcmp(method, "PROPFIND") == 0) {
http_method = HTTP_METHOD_PROPFIND;
}
else if (strcmp(method, "DELETE") == 0) {
http_method = HTTP_METHOD_DELETE;
}
else if (strcmp(method, "HEAD") == 0) {
http_method = HTTP_METHOD_HEAD;
}
else {
return MHD_NO; /* unexpected method */
}
if (*con_cls == NULL) {
/* The first time only the headers are valid,
do not respond in the first round...
Just init our response*/
HTTPRequestSession *session = new HTTPRequestSession();
*con_cls = session;
return MHD_YES;
}
// Handle request
HTTPRequestSession *session = (HTTPRequestSession *) *con_cls;
if (!session->data_handled && !httpd->handle_query(http_method, connection, std::string(url),
std::string(upload_data, *upload_data_size), session->result)) {
session->result = std::string(BAD_REQUEST);
}
// When post data is available, reinit the data_size because this function
// is called another time. And mark the current session as handled
if (*upload_data_size > 0) {
*upload_data_size = 0;
session->data_handled = true;
return MHD_YES;
}
response = MHD_create_response_from_buffer(session->result.length(),
(void *) session->result.c_str(), MHD_RESPMEM_MUST_COPY);
ret = MHD_queue_response(connection, MHD_HTTP_OK, response);
MHD_destroy_response(response);
delete session;
*con_cls = NULL; /* clear context pointer */
return ret;
}
void HTTPServer::request_completed(void *cls, struct MHD_Connection *connection,
void **con_cls, MHD_RequestTerminationCode toe)
{
}
bool HTTPServer::handle_query(HTTPMethod m, MHD_Connection *conn, const std::string &url,
const std::string &upload_data, std::string &result)
{
assert(m < HTTP_METHOD_MAX);
HTTPServerReqHandlerMap::const_iterator url_handler = m_handlers[m].find(url);
if (url_handler == m_handlers[m].end()) {
return false;
}
// Read which params we want and store them
HTTPQuery q;
q.url = url;
MHD_get_connection_values(conn, MHD_HEADER_KIND, &HTTPServer::mhd_iter_headers, &q);
MHD_get_connection_values(conn, MHD_GET_ARGUMENT_KIND, &HTTPServer::mhd_iter_getargs, &q);
const auto ct_itr = q.headers.find("Content-Type");
if (ct_itr != q.headers.end()) {
if (ct_itr->second == "application/x-www-form-urlencoded") {
// Abort if upload_data is invalid
if (!parse_post_data(upload_data, q)) {
return false;
}
}
}
return url_handler->second(q, result);
}
int HTTPServer::mhd_iter_headers(void *cls, MHD_ValueKind, const char *key,
const char *value)
{
HTTPQuery *q = (HTTPQuery *) cls;
if (q && key && value) {
q->headers[std::string(key)] = std::string(value);
}
return MHD_YES; // continue iteration
}
int HTTPServer::mhd_iter_getargs(void *cls, MHD_ValueKind, const char *key,
const char *value)
{
HTTPQuery *q = (HTTPQuery *) cls;
if (q && key && value) {
q->get_params[std::string(key)] = std::string(value);
}
return MHD_YES; // continue iteration
}
bool HTTPServer::parse_post_data(const std::string &data, HTTPQuery &q)
{
std::vector<std::string> first_split;
str_split(data, '&', first_split);
for (const auto &s: first_split) {
// If this post data is empty, abort
if (s.empty()) {
return false;
}
std::vector<std::string> kv;
str_split(s, '=', kv);
// If the key value pair is invalid, abort
if (kv.size() != 2 || kv[0].empty() || kv[1].empty()) {
return false;
}
q.post_data[kv[0]] = kv[1];
}
return true;
}
<commit_msg>Update comments<commit_after>/**
* Copyright (c) 2016, Loic Blot <[email protected]>
* All rights reserved.
* Redistribution and use in source and binary forms, with or without modification,
* are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation and/or
* other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
* IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
* INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
* EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include "httpserver.h"
#include <cstring>
#include <cassert>
#include <iostream>
#include <stdlib.h>
#include <sstream>
#include "utils/stringutils.h"
static const char* NOT_FOUND_PAGE = "<html><head><title>Not found</title></head><body><h1>No resource found at this address.</h1></body></html>";
static const char* BAD_REQUEST = "<html><head><title>Bad request</title></head><body><h1>Bad request</h1></body></html>";
HTTPServer::HTTPServer(const uint16_t http_port): m_http_port(http_port)
{
m_mhd_daemon = MHD_start_daemon(MHD_USE_THREAD_PER_CONNECTION, m_http_port, NULL,
NULL, &HTTPServer::request_handler, this, MHD_OPTION_NOTIFY_COMPLETED,
&HTTPServer::request_completed, NULL, MHD_OPTION_END);
}
HTTPServer::~HTTPServer()
{
if (m_mhd_daemon) {
MHD_stop_daemon(m_mhd_daemon);
}
}
struct HTTPRequestSession
{
std::string result = "";
bool data_handled = false;
};
int HTTPServer::request_handler(void *http_server, struct MHD_Connection *connection,
const char *url, const char *method, const char *version, const char *upload_data,
size_t *upload_data_size, void **con_cls)
{
HTTPServer *httpd = (HTTPServer *) http_server;
HTTPMethod http_method;
struct MHD_Response *response;
int ret;
if (strcmp(method, "GET") == 0) {
http_method = HTTP_METHOD_GET;
}
else if (strcmp(method, "POST") == 0) {
http_method = HTTP_METHOD_POST;
}
else if (strcmp(method, "PUT") == 0) {
http_method = HTTP_METHOD_PUT;
}
else if (strcmp(method, "PATCH") == 0) {
http_method = HTTP_METHOD_PATCH;
}
else if (strcmp(method, "PROPFIND") == 0) {
http_method = HTTP_METHOD_PROPFIND;
}
else if (strcmp(method, "DELETE") == 0) {
http_method = HTTP_METHOD_DELETE;
}
else if (strcmp(method, "HEAD") == 0) {
http_method = HTTP_METHOD_HEAD;
}
else {
return MHD_NO; /* unexpected method */
}
if (*con_cls == NULL) {
// The first time only the headers are valid,
// do not respond in the first round...
// Just init our response
HTTPRequestSession *session = new HTTPRequestSession();
*con_cls = session;
return MHD_YES;
}
// Handle request
HTTPRequestSession *session = (HTTPRequestSession *) *con_cls;
if (!session->data_handled && !httpd->handle_query(http_method, connection, std::string(url),
std::string(upload_data, *upload_data_size), session->result)) {
session->result = std::string(BAD_REQUEST);
}
// When post data is available, reinit the data_size because this function
// is called another time. And mark the current session as handled
if (*upload_data_size > 0) {
*upload_data_size = 0;
session->data_handled = true;
return MHD_YES;
}
response = MHD_create_response_from_buffer(session->result.length(),
(void *) session->result.c_str(), MHD_RESPMEM_MUST_COPY);
ret = MHD_queue_response(connection, MHD_HTTP_OK, response);
MHD_destroy_response(response);
// clear context pointer
delete session;
*con_cls = NULL;
return ret;
}
void HTTPServer::request_completed(void *cls, struct MHD_Connection *connection,
void **con_cls, MHD_RequestTerminationCode toe)
{
}
bool HTTPServer::handle_query(HTTPMethod m, MHD_Connection *conn, const std::string &url,
const std::string &upload_data, std::string &result)
{
assert(m < HTTP_METHOD_MAX);
HTTPServerReqHandlerMap::const_iterator url_handler = m_handlers[m].find(url);
if (url_handler == m_handlers[m].end()) {
return false;
}
// Read which params we want and store them
HTTPQuery q;
q.url = url;
MHD_get_connection_values(conn, MHD_HEADER_KIND, &HTTPServer::mhd_iter_headers, &q);
MHD_get_connection_values(conn, MHD_GET_ARGUMENT_KIND, &HTTPServer::mhd_iter_getargs, &q);
const auto ct_itr = q.headers.find("Content-Type");
if (ct_itr != q.headers.end()) {
if (ct_itr->second == "application/x-www-form-urlencoded") {
// Abort if upload_data is invalid
if (!parse_post_data(upload_data, q)) {
return false;
}
}
}
return url_handler->second(q, result);
}
int HTTPServer::mhd_iter_headers(void *cls, MHD_ValueKind, const char *key,
const char *value)
{
HTTPQuery *q = (HTTPQuery *) cls;
if (q && key && value) {
q->headers[std::string(key)] = std::string(value);
}
return MHD_YES; // continue iteration
}
int HTTPServer::mhd_iter_getargs(void *cls, MHD_ValueKind, const char *key,
const char *value)
{
HTTPQuery *q = (HTTPQuery *) cls;
if (q && key && value) {
q->get_params[std::string(key)] = std::string(value);
}
return MHD_YES; // continue iteration
}
bool HTTPServer::parse_post_data(const std::string &data, HTTPQuery &q)
{
std::vector<std::string> first_split;
str_split(data, '&', first_split);
for (const auto &s: first_split) {
// If this post data is empty, abort
if (s.empty()) {
return false;
}
std::vector<std::string> kv;
str_split(s, '=', kv);
// If the key value pair is invalid, abort
if (kv.size() != 2 || kv[0].empty() || kv[1].empty()) {
return false;
}
q.post_data[kv[0]] = kv[1];
}
return true;
}
<|endoftext|> |
<commit_before>/************************************************************************/
/* */
/* Copyright 1998-2000 by Ullrich Koethe */
/* Cognitive Systems Group, University of Hamburg, Germany */
/* */
/* This file is part of the VIGRA computer vision library. */
/* You may use, modify, and distribute this software according */
/* to the terms stated in the LICENSE file included in */
/* the VIGRA distribution. */
/* */
/* The VIGRA Website is */
/* http://kogs-www.informatik.uni-hamburg.de/~koethe/vigra/ */
/* Please direct questions, bug reports, and contributions to */
/* [email protected] */
/* */
/* THIS SOFTWARE IS PROVIDED AS IS AND WITHOUT ANY EXPRESS OR */
/* IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED */
/* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. */
/* */
/************************************************************************/
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% This file contains source code adapted from ImageMagick %
% %
% ImageMagick is Copyright 1998 E. I. du Pont de Nemours and Company %
% %
% Permission is hereby granted, free of charge, to any person obtaining a %
% copy of this software and associated documentation files ("ImageMagick"), %
% to deal in ImageMagick without restriction, including without limitation %
% the rights to use, copy, modify, merge, publish, distribute, sublicense, %
% and/or sell copies of ImageMagick, and to permit persons to whom the %
% ImageMagick 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 ImageMagick. %
% %
% 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 %
% E. I. du Pont de Nemours and Company 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 ImageMagick or the use or other %
% dealings in ImageMagick. %
% %
% Except as contained in this notice, the name of the E. I. du Pont de %
% Nemours and Company shall not be used in advertising or otherwise to %
% promote the sale, use or other dealings in ImageMagick without prior %
% written authorization from the E. I. du Pont de Nemours and Company. %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
*/
#if !defined(HasTIFF)
#include "vigra/error.hxx"
#include "vigra/tiff.h"
Export VigraImpexImage *vigraImpexReadTIFFImage( VigraImpexImageInfo *image_info)
{
fail( "TIFF library is not available");
return 0;
}
Export unsigned int vigraImpexWriteTIFFImage( VigraImpexImageInfo *image_info,VigraImpexImage *image)
{
fail( "TIFF library is not available");
return 0;
}
Export void TIFFClose(TiffImage*)
{
fail( "TIFF library is not available");
}
Export TiffImage* TIFFOpen(const char*, const char*)
{
fail( "TIFF library is not available");
return 0;
}
Export int TIFFGetField(TiffImage*, ttag_t, ...)
{
fail( "TIFF library is not available");
return 0;
}
Export int TIFFSetField(TiffImage*, ttag_t, ...)
{
fail( "TIFF library is not available");
return 0;
}
Export tsize_t TIFFScanlineSize(TiffImage*)
{
fail( "TIFF library is not available");
return 0;
}
Export int TIFFReadScanline(TiffImage*, tdata_t, uint32, tsample_t = 0)
{
fail( "TIFF library is not available");
return 0;
}
Export int TIFFWriteScanline(TiffImage*, tdata_t, uint32, tsample_t = 0)
{
fail( "TIFF library is not available");
return 0;
}
Export int TIFFReadRGBAImage(TiffImage*, uint32, uint32, uint32*, int = 0)
{
fail( "TIFF library is not available");
return 0;
}
#endif
<commit_msg>added missing include and changed "fail()" into "vigra_fail()" in order to make the file work when HasTiff is not defined.<commit_after>/************************************************************************/
/* */
/* Copyright 1998-2000 by Ullrich Koethe */
/* Cognitive Systems Group, University of Hamburg, Germany */
/* */
/* This file is part of the VIGRA computer vision library. */
/* ( Version 1.1.0, Dec 05 2000 ) */
/* You may use, modify, and distribute this software according */
/* to the terms stated in the LICENSE file included in */
/* the VIGRA distribution. */
/* */
/* The VIGRA Website is */
/* http://kogs-www.informatik.uni-hamburg.de/~koethe/vigra/ */
/* Please direct questions, bug reports, and contributions to */
/* [email protected] */
/* */
/* THIS SOFTWARE IS PROVIDED AS IS AND WITHOUT ANY EXPRESS OR */
/* IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED */
/* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. */
/* */
/************************************************************************/
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% This file contains source code adapted from ImageMagick %
% %
% ImageMagick is Copyright 1998 E. I. du Pont de Nemours and Company %
% %
% Permission is hereby granted, free of charge, to any person obtaining a %
% copy of this software and associated documentation files ("ImageMagick"), %
% to deal in ImageMagick without restriction, including without limitation %
% the rights to use, copy, modify, merge, publish, distribute, sublicense, %
% and/or sell copies of ImageMagick, and to permit persons to whom the %
% ImageMagick 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 ImageMagick. %
% %
% 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 %
% E. I. du Pont de Nemours and Company 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 ImageMagick or the use or other %
% dealings in ImageMagick. %
% %
% Except as contained in this notice, the name of the E. I. du Pont de %
% Nemours and Company shall not be used in advertising or otherwise to %
% promote the sale, use or other dealings in ImageMagick without prior %
% written authorization from the E. I. du Pont de Nemours and Company. %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
*/
#if !defined(HasTIFF)
#include "vigra/error.hxx"
#include "vigra/tiff.h"
#include "vigra/impex.h"
Export VigraImpexImage *vigraImpexReadTIFFImage( VigraImpexImageInfo *image_info)
{
vigra_fail( "TIFF library is not available");
return 0;
}
Export unsigned int vigraImpexWriteTIFFImage( VigraImpexImageInfo *image_info,VigraImpexImage *image)
{
vigra_fail( "TIFF library is not available");
return 0;
}
Export void TIFFClose(TiffImage*)
{
vigra_fail( "TIFF library is not available");
}
Export TiffImage* TIFFOpen(const char*, const char*)
{
vigra_fail( "TIFF library is not available");
return 0;
}
Export int TIFFGetField(TiffImage*, ttag_t, ...)
{
vigra_fail( "TIFF library is not available");
return 0;
}
Export int TIFFSetField(TiffImage*, ttag_t, ...)
{
vigra_fail( "TIFF library is not available");
return 0;
}
Export tsize_t TIFFScanlineSize(TiffImage*)
{
vigra_fail( "TIFF library is not available");
return 0;
}
Export int TIFFReadScanline(TiffImage*, tdata_t, uint32, tsample_t = 0)
{
vigra_fail( "TIFF library is not available");
return 0;
}
Export int TIFFWriteScanline(TiffImage*, tdata_t, uint32, tsample_t = 0)
{
vigra_fail( "TIFF library is not available");
return 0;
}
Export int TIFFReadRGBAImage(TiffImage*, uint32, uint32, uint32*, int = 0)
{
vigra_fail( "TIFF library is not available");
return 0;
}
#endif
<|endoftext|> |
<commit_before>#define NPY_NO_DEPRECATED_API NPY_1_7_API_VERSION
#include <numpy/arrayobject.h>
#include <omp.h>
#include <stdio.h>
#include <complex>
#include <boost/preprocessor/repetition/repeat.hpp>
#include "atomic_add.hpp"
template <typename DTYPE, typename ITYPE>
void sparse_matvec_template(PyArrayObject* inp, PyArrayObject* outp, npy_intp zsize, PyArrayObject* dz, PyArrayObject* bounds, PyArrayObject* col, PyArrayObject* row, PyArrayObject* coeff, int threads)
{
PyArrayObject* ops[3] = {col, row, coeff};
npy_uint32 flags = NPY_ITER_EXTERNAL_LOOP|NPY_ITER_GROWINNER|NPY_ITER_RANGED|NPY_ITER_BUFFERED|NPY_ITER_DELAY_BUFALLOC;
npy_uint32 op_flags[3] = {NPY_ITER_READONLY, NPY_ITER_READONLY, NPY_ITER_READONLY};
NpyIter* iter = NpyIter_MultiNew(3, ops , flags, NPY_KEEPORDER, NPY_NO_CASTING, op_flags, NULL);
npy_intp dz_size = PyArray_SIZE(dz);
npy_intp inp_zstride = PyArray_SIZE(inp)/zsize;
npy_intp outp_zstride = PyArray_SIZE(outp)/zsize;
ITYPE* dz_da = (ITYPE*) dz->data;
ITYPE* bounds_da = (ITYPE*) bounds->data;
DTYPE* inp_da = (DTYPE*) inp->data;
DTYPE* outp_da = (DTYPE*) outp->data;
DTYPE* inp_loc;
DTYPE* outp_loc;
NpyIter* local_iter;
NpyIter_IterNextFunc* iternext;
npy_intp loopsize;
ITYPE* loop_col;
ITYPE* loop_row;
DTYPE* loop_coeff;
npy_intp loop_col_stride;
npy_intp loop_row_stride;
npy_intp loop_coeff_stride;
npy_intp ib, ie, iz, idz, oz;
int i;
#pragma omp parallel num_threads(threads) private(local_iter, iternext)
{
#pragma omp critical
local_iter = NpyIter_Copy(iter);
iternext = NpyIter_GetIterNext(local_iter, NULL);
#pragma omp for collapse(2) private(iz, idz, oz, inp_loc, outp_loc, ib, ie, loopsize, loop_col, loop_row, loop_coeff, loop_col_stride, loop_row_stride, loop_coeff_stride, i)
for(iz=0; iz<zsize; iz++)
{
for(idz=0; idz<dz_size; idz++)
{
oz = iz + dz_da[idz];
if(oz>=0 && oz<zsize)
{
inp_loc = inp_da + iz*inp_zstride;
outp_loc = outp_da + oz*outp_zstride;
ib = bounds_da[idz];
ie = bounds_da[idz+1];
if(ie>ib)
{
NpyIter_ResetToIterIndexRange(local_iter, ib, ie, NULL);
do{
loopsize = NpyIter_GetInnerLoopSizePtr(local_iter)[0];
loop_col = (ITYPE*) NpyIter_GetDataPtrArray(local_iter)[0];
loop_row = (ITYPE*) NpyIter_GetDataPtrArray(local_iter)[1];
loop_coeff = (DTYPE*) NpyIter_GetDataPtrArray(local_iter)[2];
loop_col_stride = NpyIter_GetInnerStrideArray(local_iter)[0]/sizeof(ITYPE);
loop_row_stride = NpyIter_GetInnerStrideArray(local_iter)[1]/sizeof(ITYPE);
loop_coeff_stride = NpyIter_GetInnerStrideArray(local_iter)[2]/sizeof(DTYPE);
#pragma omp simd
for(i=0; i<loopsize; i++)
{
atomic_add(outp_loc + loop_row[0], (DTYPE) 1);//loop_coeff[0] * inp_loc[loop_col[0]]);
loop_col += loop_col_stride;
loop_row += loop_row_stride;
loop_coeff += loop_coeff_stride;
}
} while (iternext(local_iter));
}
}
}
}
NpyIter_Deallocate(local_iter);
}
NpyIter_Deallocate(iter);
}
#define DTYPES(I) DTYPES ## I
#define DTYPES0 npy_float32
#define DTYPES1 npy_float64
#define DTYPES2 std::complex<npy_float32>
#define DTYPES3 std::complex<npy_float64>
#define DTYPENAMES(I) DTYPENAMES ## I
#define DTYPENAMES0 NPY_FLOAT32
#define DTYPENAMES1 NPY_FLOAT64
#define DTYPENAMES2 NPY_COMPLEX64
#define DTYPENAMES3 NPY_COMPLEX128
#define DTYPES_CNT 4
#define ITYPES(I) ITYPES ## I
#define ITYPES0 npy_int16
#define ITYPES1 npy_int32
#define ITYPES2 npy_int64
#define ITYPES3 npy_uint16
#define ITYPES4 npy_uint32
#define ITYPES5 npy_uint64
#define ITYPENAMES(I) ITYPENAMES ## I
#define ITYPENAMES0 NPY_INT16
#define ITYPENAMES1 NPY_INT32
#define ITYPENAMES2 NPY_INT64
#define ITYPENAMES3 NPY_UINT16
#define ITYPENAMES4 NPY_UINT32
#define ITYPENAMES5 NPY_UINT64
#define ITYPES_CNT 6
#define DISPATCH_INNER_CASE(z, itype, dtype) \
case ITYPENAMES(itype): return sparse_matvec_template<DTYPES(dtype), ITYPES(itype)>;
#define DISPATCH_CASE(z, dtype, itype_num) \
case DTYPENAMES(dtype): switch(itype_num) { BOOST_PP_REPEAT(ITYPES_CNT, DISPATCH_INNER_CASE, dtype) };
void (*dispatch_sparse_matvec(int dtype_num, int itype_num))(PyArrayObject*, PyArrayObject*, npy_intp, PyArrayObject*, PyArrayObject*, PyArrayObject*, PyArrayObject*, PyArrayObject*, int)
{
switch(dtype_num){ BOOST_PP_REPEAT(DTYPES_CNT, DISPATCH_CASE, itype_num) };
}
#undef DISPATCH_INNER_CASE
#undef DISPATCH_CASE
void sparse_matvec(PyArrayObject* inp, PyArrayObject* outp, npy_intp zsize, PyArrayObject* dz, PyArrayObject* bounds, PyArrayObject* col, PyArrayObject* row, PyArrayObject* coeff, int threads)
{
dispatch_sparse_matvec(inp->descr->type_num, col->descr->type_num)(inp, outp, zsize, dz, bounds, col, row, coeff, threads);
}
<commit_msg>removed debugging change<commit_after>#define NPY_NO_DEPRECATED_API NPY_1_7_API_VERSION
#include <numpy/arrayobject.h>
#include <omp.h>
#include <stdio.h>
#include <complex>
#include <boost/preprocessor/repetition/repeat.hpp>
#include "atomic_add.hpp"
template <typename DTYPE, typename ITYPE>
void sparse_matvec_template(PyArrayObject* inp, PyArrayObject* outp, npy_intp zsize, PyArrayObject* dz, PyArrayObject* bounds, PyArrayObject* col, PyArrayObject* row, PyArrayObject* coeff, int threads)
{
PyArrayObject* ops[3] = {col, row, coeff};
npy_uint32 flags = NPY_ITER_EXTERNAL_LOOP|NPY_ITER_GROWINNER|NPY_ITER_RANGED|NPY_ITER_BUFFERED|NPY_ITER_DELAY_BUFALLOC;
npy_uint32 op_flags[3] = {NPY_ITER_READONLY, NPY_ITER_READONLY, NPY_ITER_READONLY};
NpyIter* iter = NpyIter_MultiNew(3, ops , flags, NPY_KEEPORDER, NPY_NO_CASTING, op_flags, NULL);
npy_intp dz_size = PyArray_SIZE(dz);
npy_intp inp_zstride = PyArray_SIZE(inp)/zsize;
npy_intp outp_zstride = PyArray_SIZE(outp)/zsize;
ITYPE* dz_da = (ITYPE*) dz->data;
ITYPE* bounds_da = (ITYPE*) bounds->data;
DTYPE* inp_da = (DTYPE*) inp->data;
DTYPE* outp_da = (DTYPE*) outp->data;
DTYPE* inp_loc;
DTYPE* outp_loc;
NpyIter* local_iter;
NpyIter_IterNextFunc* iternext;
npy_intp loopsize;
ITYPE* loop_col;
ITYPE* loop_row;
DTYPE* loop_coeff;
npy_intp loop_col_stride;
npy_intp loop_row_stride;
npy_intp loop_coeff_stride;
npy_intp ib, ie, iz, idz, oz;
int i;
#pragma omp parallel num_threads(threads) private(local_iter, iternext)
{
#pragma omp critical
local_iter = NpyIter_Copy(iter);
iternext = NpyIter_GetIterNext(local_iter, NULL);
#pragma omp for collapse(2) private(iz, idz, oz, inp_loc, outp_loc, ib, ie, loopsize, loop_col, loop_row, loop_coeff, loop_col_stride, loop_row_stride, loop_coeff_stride, i)
for(iz=0; iz<zsize; iz++)
{
for(idz=0; idz<dz_size; idz++)
{
oz = iz + dz_da[idz];
if(oz>=0 && oz<zsize)
{
inp_loc = inp_da + iz*inp_zstride;
outp_loc = outp_da + oz*outp_zstride;
ib = bounds_da[idz];
ie = bounds_da[idz+1];
if(ie>ib)
{
NpyIter_ResetToIterIndexRange(local_iter, ib, ie, NULL);
do{
loopsize = NpyIter_GetInnerLoopSizePtr(local_iter)[0];
loop_col = (ITYPE*) NpyIter_GetDataPtrArray(local_iter)[0];
loop_row = (ITYPE*) NpyIter_GetDataPtrArray(local_iter)[1];
loop_coeff = (DTYPE*) NpyIter_GetDataPtrArray(local_iter)[2];
loop_col_stride = NpyIter_GetInnerStrideArray(local_iter)[0]/sizeof(ITYPE);
loop_row_stride = NpyIter_GetInnerStrideArray(local_iter)[1]/sizeof(ITYPE);
loop_coeff_stride = NpyIter_GetInnerStrideArray(local_iter)[2]/sizeof(DTYPE);
#pragma omp simd
for(i=0; i<loopsize; i++)
{
atomic_add(outp_loc + loop_row[0], loop_coeff[0] * inp_loc[loop_col[0]]);
loop_col += loop_col_stride;
loop_row += loop_row_stride;
loop_coeff += loop_coeff_stride;
}
} while (iternext(local_iter));
}
}
}
}
NpyIter_Deallocate(local_iter);
}
NpyIter_Deallocate(iter);
}
#define DTYPES(I) DTYPES ## I
#define DTYPES0 npy_float32
#define DTYPES1 npy_float64
#define DTYPES2 std::complex<npy_float32>
#define DTYPES3 std::complex<npy_float64>
#define DTYPENAMES(I) DTYPENAMES ## I
#define DTYPENAMES0 NPY_FLOAT32
#define DTYPENAMES1 NPY_FLOAT64
#define DTYPENAMES2 NPY_COMPLEX64
#define DTYPENAMES3 NPY_COMPLEX128
#define DTYPES_CNT 4
#define ITYPES(I) ITYPES ## I
#define ITYPES0 npy_int16
#define ITYPES1 npy_int32
#define ITYPES2 npy_int64
#define ITYPES3 npy_uint16
#define ITYPES4 npy_uint32
#define ITYPES5 npy_uint64
#define ITYPENAMES(I) ITYPENAMES ## I
#define ITYPENAMES0 NPY_INT16
#define ITYPENAMES1 NPY_INT32
#define ITYPENAMES2 NPY_INT64
#define ITYPENAMES3 NPY_UINT16
#define ITYPENAMES4 NPY_UINT32
#define ITYPENAMES5 NPY_UINT64
#define ITYPES_CNT 6
#define DISPATCH_INNER_CASE(z, itype, dtype) \
case ITYPENAMES(itype): return sparse_matvec_template<DTYPES(dtype), ITYPES(itype)>;
#define DISPATCH_CASE(z, dtype, itype_num) \
case DTYPENAMES(dtype): switch(itype_num) { BOOST_PP_REPEAT(ITYPES_CNT, DISPATCH_INNER_CASE, dtype) };
void (*dispatch_sparse_matvec(int dtype_num, int itype_num))(PyArrayObject*, PyArrayObject*, npy_intp, PyArrayObject*, PyArrayObject*, PyArrayObject*, PyArrayObject*, PyArrayObject*, int)
{
switch(dtype_num){ BOOST_PP_REPEAT(DTYPES_CNT, DISPATCH_CASE, itype_num) };
}
#undef DISPATCH_INNER_CASE
#undef DISPATCH_CASE
void sparse_matvec(PyArrayObject* inp, PyArrayObject* outp, npy_intp zsize, PyArrayObject* dz, PyArrayObject* bounds, PyArrayObject* col, PyArrayObject* row, PyArrayObject* coeff, int threads)
{
dispatch_sparse_matvec(inp->descr->type_num, col->descr->type_num)(inp, outp, zsize, dz, bounds, col, row, coeff, threads);
}
<|endoftext|> |
<commit_before>#define BOOST_TEST_MODULE VectorView
#include <valarray>
#include <boost/test/unit_test.hpp>
#include "context_setup.hpp"
BOOST_AUTO_TEST_CASE(vector_view_1d)
{
const size_t N = 1024;
std::vector<cl::CommandQueue> queue(1, ctx.queue(0));
std::vector<double> x = random_vector<double>(2 * N);
vex::vector<double> X(queue, x);
vex::vector<double> Y(queue, N);
cl_ulong size = N;
cl_long stride = 2;
vex::gslice<1> slice(0, &size, &stride);
Y = slice(X);
check_sample(Y, [&](size_t idx, double v) { BOOST_CHECK(v == x[idx * 2]); });
}
BOOST_AUTO_TEST_CASE(vector_view_2)
{
const size_t N = 32;
std::vector<cl::CommandQueue> queue(1, ctx.queue(0));
std::valarray<double> x(N * N);
std::iota(&x[0], &x[N * N], 0);
// Select every even point from sub-block [(2,4) - (10,10)]:
size_t start = 2 * N + 4;
size_t size[] = {5, 4};
size_t stride[] = {2 * N, 2};
std::gslice std_slice(start, std::valarray<size_t>(size, 2), std::valarray<size_t>(stride, 2));
std::valarray<double> y = x[std_slice];
vex::vector<double> X(queue, N * N, &x[0]);
vex::vector<double> Y(queue, size[0] * size[1]);
vex::gslice<2> vex_slice(start, size, stride);
Y = vex_slice(X);
check_sample(Y, [&](size_t idx, double v) { BOOST_CHECK_EQUAL(v, y[idx]); });
}
BOOST_AUTO_TEST_CASE(vector_slicer_2d)
{
const size_t N = 32;
std::vector<cl::CommandQueue> queue(1, ctx.queue(0));
std::valarray<double> x(N * N);
std::iota(&x[0], &x[N * N], 0);
// Select every even point from sub-block [(2,4) - (10,10)]:
size_t start = 2 * N + 4;
size_t size[] = {5, 4};
size_t stride[] = {2 * N, 2};
std::gslice std_slice(start, std::valarray<size_t>(size, 2), std::valarray<size_t>(stride, 2));
std::valarray<double> y = x[std_slice];
vex::vector<double> X(queue, N * N, &x[0]);
vex::vector<double> Y(queue, size[0] * size[1]);
vex::vector<double> Z(queue, N);
size_t dim[2] = {N, N};
vex::slicer<2> slicer(dim);
auto slice = slicer[vex::range(2, 2, 11)][vex::range(4, 2, 11)];
Y = slice(X);
check_sample(Y, [&](size_t idx, double v) { BOOST_CHECK_EQUAL(v, y[idx]); });
Z = slicer[5](X); // Put fith row of X into Z;
check_sample(Z, [&](size_t idx, double v) { BOOST_CHECK_EQUAL(v, x[5 * N + idx]); });
Z = slicer[vex::range()][5](X); // Puth fith column of X into Z;
check_sample(Z, [&](size_t idx, double v) { BOOST_CHECK_EQUAL(v, x[5 + N * idx]); });
}
BOOST_AUTO_TEST_CASE(vector_permutation)
{
const size_t N = 1024;
std::vector<cl::CommandQueue> queue(1, ctx.queue(0));
std::vector<double> x = random_vector<double>(N);
vex::vector<double> X(queue, x);
vex::vector<double> Y(queue, N);
vex::vector<size_t> I(queue, N);
I = N - 1 - vex::element_index();
vex::permutation reverse(I);
Y = reverse(X);
check_sample(Y, [&](size_t idx, double v) { BOOST_CHECK_EQUAL(v, x[N - 1 - idx]); });
}
BOOST_AUTO_TEST_CASE(reduce_slice)
{
const size_t N = 1024;
std::vector<cl::CommandQueue> queue(1, ctx.queue(0));
vex::vector<int> X(queue, N);
vex::Reductor<int, vex::SUM> sum(queue);
vex::slicer<1> slice(&N);
X = 1;
BOOST_CHECK_EQUAL(N / 2, sum( slice[vex::range(0, 2, N)](X) ));
}
BOOST_AUTO_TEST_CASE(assign_to_view) {
const size_t m = 32;
const size_t n = m * m;
std::array<size_t, 2> dim = {{m, m}};
std::vector<cl::CommandQueue> queue(1, ctx.queue(0));
vex::vector<int> x(queue, n);
vex::slicer<1> slicer1(&n);
vex::slicer<2> slicer2(dim);
x = 1;
slicer1[vex::range(1, 2, n)](x) = 2;
check_sample(x, [&](size_t idx, int v) {
BOOST_CHECK_EQUAL(v, idx % 2 + 1);
});
for(size_t i = 0; i < m; ++i)
slicer2[vex::range()][i](x) = i;
check_sample(x, [&](size_t idx, int v) {
BOOST_CHECK_EQUAL(v, idx % m);
});
vex::vector<size_t> I(ctx, m);
I = vex::element_index() * m;
vex::permutation first_col(I);
first_col(x) = 42;
for(size_t i = 0; i < m; ++i)
BOOST_CHECK_EQUAL(x[i * m], 42);
}
BOOST_AUTO_TEST_SUITE_END()
<commit_msg>Fixed bug in tests/vector_view.cpp<commit_after>#define BOOST_TEST_MODULE VectorView
#include <valarray>
#include <boost/test/unit_test.hpp>
#include "context_setup.hpp"
BOOST_AUTO_TEST_CASE(vector_view_1d)
{
const size_t N = 1024;
std::vector<cl::CommandQueue> queue(1, ctx.queue(0));
std::vector<double> x = random_vector<double>(2 * N);
vex::vector<double> X(queue, x);
vex::vector<double> Y(queue, N);
cl_ulong size = N;
cl_long stride = 2;
vex::gslice<1> slice(0, &size, &stride);
Y = slice(X);
check_sample(Y, [&](size_t idx, double v) { BOOST_CHECK(v == x[idx * 2]); });
}
BOOST_AUTO_TEST_CASE(vector_view_2)
{
const size_t N = 32;
std::vector<cl::CommandQueue> queue(1, ctx.queue(0));
std::valarray<double> x(N * N);
std::iota(&x[0], &x[N * N], 0);
// Select every even point from sub-block [(2,4) - (10,10)]:
size_t start = 2 * N + 4;
size_t size[] = {5, 4};
size_t stride[] = {2 * N, 2};
std::gslice std_slice(start, std::valarray<size_t>(size, 2), std::valarray<size_t>(stride, 2));
std::valarray<double> y = x[std_slice];
vex::vector<double> X(queue, N * N, &x[0]);
vex::vector<double> Y(queue, size[0] * size[1]);
vex::gslice<2> vex_slice(start, size, stride);
Y = vex_slice(X);
check_sample(Y, [&](size_t idx, double v) { BOOST_CHECK_EQUAL(v, y[idx]); });
}
BOOST_AUTO_TEST_CASE(vector_slicer_2d)
{
const size_t N = 32;
std::vector<cl::CommandQueue> queue(1, ctx.queue(0));
std::valarray<double> x(N * N);
std::iota(&x[0], &x[N * N], 0);
// Select every even point from sub-block [(2,4) - (10,10)]:
size_t start = 2 * N + 4;
size_t size[] = {5, 4};
size_t stride[] = {2 * N, 2};
std::gslice std_slice(start, std::valarray<size_t>(size, 2), std::valarray<size_t>(stride, 2));
std::valarray<double> y = x[std_slice];
vex::vector<double> X(queue, N * N, &x[0]);
vex::vector<double> Y(queue, size[0] * size[1]);
vex::vector<double> Z(queue, N);
size_t dim[2] = {N, N};
vex::slicer<2> slicer(dim);
auto slice = slicer[vex::range(2, 2, 11)][vex::range(4, 2, 11)];
Y = slice(X);
check_sample(Y, [&](size_t idx, double v) { BOOST_CHECK_EQUAL(v, y[idx]); });
Z = slicer[5](X); // Put fith row of X into Z;
check_sample(Z, [&](size_t idx, double v) { BOOST_CHECK_EQUAL(v, x[5 * N + idx]); });
Z = slicer[vex::range()][5](X); // Puth fith column of X into Z;
check_sample(Z, [&](size_t idx, double v) { BOOST_CHECK_EQUAL(v, x[5 + N * idx]); });
}
BOOST_AUTO_TEST_CASE(vector_permutation)
{
const size_t N = 1024;
std::vector<cl::CommandQueue> queue(1, ctx.queue(0));
std::vector<double> x = random_vector<double>(N);
vex::vector<double> X(queue, x);
vex::vector<double> Y(queue, N);
vex::vector<size_t> I(queue, N);
I = N - 1 - vex::element_index();
vex::permutation reverse(I);
Y = reverse(X);
check_sample(Y, [&](size_t idx, double v) { BOOST_CHECK_EQUAL(v, x[N - 1 - idx]); });
}
BOOST_AUTO_TEST_CASE(reduce_slice)
{
const size_t N = 1024;
std::vector<cl::CommandQueue> queue(1, ctx.queue(0));
vex::vector<int> X(queue, N);
vex::Reductor<int, vex::SUM> sum(queue);
vex::slicer<1> slice(&N);
X = 1;
BOOST_CHECK_EQUAL(N / 2, sum( slice[vex::range(0, 2, N)](X) ));
}
BOOST_AUTO_TEST_CASE(assign_to_view) {
const size_t m = 32;
const size_t n = m * m;
std::array<size_t, 2> dim = {{m, m}};
std::vector<cl::CommandQueue> queue(1, ctx.queue(0));
vex::vector<int> x(queue, n);
vex::slicer<1> slicer1(&n);
vex::slicer<2> slicer2(dim);
x = 1;
slicer1[vex::range(1, 2, n)](x) = 2;
check_sample(x, [&](size_t idx, int v) {
BOOST_CHECK_EQUAL(v, idx % 2 + 1);
});
for(size_t i = 0; i < m; ++i)
slicer2[vex::range()][i](x) = i;
check_sample(x, [&](size_t idx, int v) {
BOOST_CHECK_EQUAL(v, idx % m);
});
vex::vector<size_t> I(queue, m);
I = vex::element_index() * m;
vex::permutation first_col(I);
first_col(x) = 42;
for(size_t i = 0; i < m; ++i)
BOOST_CHECK_EQUAL(x[i * m], 42);
}
BOOST_AUTO_TEST_SUITE_END()
<|endoftext|> |
<commit_before>#include "GameProcess.h"
#include "Object.h"
#include "Engine.h"
#include "World.h"
#include "App.h"
using namespace MathLib;
CGameProcess::CGameProcess(void)
{
}
CGameProcess::~CGameProcess(void)
{
}
int CGameProcess::Init()
{
g_Engine.pFileSystem->CacheFilesFormExt("char");
g_Engine.pFileSystem->CacheFilesFormExt("node");
g_Engine.pFileSystem->CacheFilesFormExt("smesh");
g_Engine.pFileSystem->CacheFilesFormExt("sanim");
g_Engine.pWorld->LoadWorld("data/scene/terrain/test/test.world");
//g_Engine.pWorld->LoadWorld("data/scene/terrain/cj/cj.world");
}<commit_msg>Signed-off-by: mrlitong <[email protected]><commit_after>#include "GameProcess.h"
#include "Object.h"
#include "Engine.h"
#include "World.h"
#include "App.h"
#include "ToolsCamera.h"
using namespace MathLib;
CGameProcess::CGameProcess(void)
{
}
CGameProcess::~CGameProcess(void)
{
}
int CGameProcess::Init()
{
g_Engine.pFileSystem->CacheFilesFormExt("char");
g_Engine.pFileSystem->CacheFilesFormExt("node");
g_Engine.pFileSystem->CacheFilesFormExt("smesh");
g_Engine.pFileSystem->CacheFilesFormExt("sanim");
g_Engine.pWorld->LoadWorld("data/scene/terrain/test/test.world");
//g_Engine.pWorld->LoadWorld("data/scene/terrain/cj/cj.world");
g_Engine.pControls->SetKeyPressFunc(KeyPress);
}<|endoftext|> |
<commit_before>#include <iostream>
#include <gtest/gtest.h>
#include "../pipeline.h"
#include "../channel.h"
#include "../scheduler.h"
#include "../shell.h"
#include <thread>
#include <asyncply/run.h>
class ChannelTest : testing::Test { };
using cmd = cu::pipeline<int>;
cmd::link generator()
{
return [](cmd::in&, cmd::out& yield)
{
for (auto& s : {100, 200, 300})
{
std::cout << "I am generator and push " << s << std::endl;
yield(s);
}
};
}
cmd::link link1()
{
return [](cmd::in& source, cmd::out& yield)
{
for (auto& s : source)
{
std::cout << "I am link1 and push " << s << std::endl;
yield(s);
}
};
}
cmd::link link2()
{
return [](cmd::in& source, cmd::out& yield)
{
for (auto& s : source)
{
std::cout << "I am link2 and push " << s << std::endl;
yield(s);
}
};
}
cmd::link link3()
{
return [](cmd::in& source, cmd::out& yield)
{
for (auto& s : source)
{
std::cout << "I am link3 and push " << s << std::endl;
yield(s);
}
};
}
TEST(ChannelTest, pipeline)
{
cmd(generator(), link1(), link2(), link3());
}
TEST(ChannelTest, goroutines_consumer)
{
cu::scheduler sch;
cu::channel<std::string> go(sch);
// go.connect(cu::quote("__^-^__"));
// go.connect(cu::quote("__\o/__"));
sch.spawn([&](auto& yield) {
// send
for(int i=1; i<=200; ++i)
{
std::cout << "sending: " << i << std::endl;
go(yield, std::to_string(i));
}
go.close(yield);
});
sch.spawn([&](auto& yield) {
// recv
for(;;)
{
auto data = go.get(yield);
if(!data)
{
std::cout << "channel closed" << std::endl;
break;
}
else
{
std::cout << "recving: " << *data << std::endl;
}
}
});
sch.run_until_complete();
}
TEST(CoroTest, TestScheduler)
{
cu::scheduler sch;
cu::semaphore person1(sch);
cu::semaphore person2(sch);
cu::semaphore other(sch);
// person2
sch.spawn("person2", [&](auto& yield) {
std::cout << "Hola person1" << std::endl;
person2.notify(yield);
//
person1.wait(yield);
std::cout << "que tal ?" << std::endl;
person2.notify(yield);
//
person1.wait(yield);
std::cout << "me alegro" << std::endl;
person2.notify(yield);
//
other.notify(yield);
});
// person1
sch.spawn("person1", [&](auto& yield) {
//
person2.wait(yield);
std::cout << "Hola person2" << std::endl;
person1.notify(yield);
//
person2.wait(yield);
std::cout << "bien!" << std::endl;
person1.notify(yield);
//
person2.wait(yield);
std::cout << "y yo ^^" << std::endl;
//
other.notify(yield);
});
// other
sch.spawn("other", [&](auto& yield) {
//
other.wait(yield);
other.wait(yield);
std::cout << "parar!!! tengo algo importante" << std::endl;
});
sch.run_until_complete();
}
<commit_msg>Update test_channel.cpp<commit_after>#include <iostream>
#include <gtest/gtest.h>
#include "../pipeline.h"
#include "../channel.h"
#include "../scheduler.h"
#include "../shell.h"
#include <thread>
#include <asyncply/run.h>
class ChannelTest : testing::Test { };
using cmd = cu::pipeline<int>;
cmd::link generator()
{
return [](cmd::in&, cmd::out& yield)
{
for (auto& s : {100, 200, 300})
{
std::cout << "I am generator and push " << s << std::endl;
yield(s);
}
};
}
cmd::link link1()
{
return [](cmd::in& source, cmd::out& yield)
{
for (auto& s : source)
{
std::cout << "I am link1 and push " << s << std::endl;
yield(s);
}
};
}
cmd::link link2()
{
return [](cmd::in& source, cmd::out& yield)
{
for (auto& s : source)
{
std::cout << "I am link2 and push " << s << std::endl;
yield(s);
}
};
}
cmd::link link3()
{
return [](cmd::in& source, cmd::out& yield)
{
for (auto& s : source)
{
std::cout << "I am link3 and push " << s << std::endl;
yield(s);
}
};
}
TEST(ChannelTest, pipeline)
{
cmd(generator(), link1(), link2(), link3());
}
TEST(ChannelTest, goroutines_consumer)
{
cu::scheduler sch;
cu::channel<std::string> go(sch, 5);
// go.connect(cu::quote("__^-^__"));
// go.connect(cu::quote("__\o/__"));
sch.spawn([&](auto& yield) {
// send
for(int i=1; i<=50; ++i)
{
std::cout << "sending: " << i << std::endl;
go(yield, std::to_string(i));
}
go.close(yield);
});
sch.spawn([&](auto& yield) {
// recv
for(;;)
{
auto data = go.get(yield);
if(!data)
{
std::cout << "channel closed" << std::endl;
break;
}
else
{
std::cout << "recving: " << *data << std::endl;
}
}
});
sch.run_until_complete();
}
TEST(CoroTest, TestScheduler)
{
cu::scheduler sch;
cu::semaphore person1(sch);
cu::semaphore person2(sch);
cu::semaphore other(sch);
// person2
sch.spawn([&](auto& yield) {
std::cout << "Hola person1" << std::endl;
person2.notify(yield);
//
person1.wait(yield);
std::cout << "que tal ?" << std::endl;
person2.notify(yield);
//
person1.wait(yield);
std::cout << "me alegro" << std::endl;
person2.notify(yield);
//
other.notify(yield);
});
// person1
sch.spawn([&](auto& yield) {
//
person2.wait(yield);
std::cout << "Hola person2" << std::endl;
person1.notify(yield);
//
person2.wait(yield);
std::cout << "bien!" << std::endl;
person1.notify(yield);
//
person2.wait(yield);
std::cout << "y yo ^^" << std::endl;
//
other.notify(yield);
});
// other
sch.spawn([&](auto& yield) {
//
other.wait(yield);
other.wait(yield);
std::cout << "parar!!! tengo algo importante" << std::endl;
});
sch.run_until_complete();
}
<|endoftext|> |
<commit_before>#include "GameProcess.h"
#include "Object.h"
#include "Engine.h"
#include "World.h"
#include "App.h"
#include "ToolsCamera.h"
#include "ControlsApp.h"
#include "MathLib.h"
#include "Game.h"
#include "Editor.h"
#include "Input.h"
#include "BlueRayUtils.h"
#include "World.h"
#include "Action.h"
#include "FPSRoleLocal.h"
using namespace MathLib;
CGameProcess::CGameProcess(void)
{
}
CGameProcess::~CGameProcess(void)
{
}
int CGameProcess::Init()
{
g_Engine.pFileSystem->CacheFilesFormExt("char");
g_Engine.pFileSystem->CacheFilesFormExt("node");
g_Engine.pFileSystem->CacheFilesFormExt("smesh");
g_Engine.pFileSystem->CacheFilesFormExt("sanim");
g_Engine.pWorld->LoadWorld("data/scene/terrain/test/test.world");
//g_Engine.pWorld->LoadWorld("data/scene/terrain/cj/cj.world");
g_Engine.pControls->SetKeyPressFunc(KeyPress);
g_Engine.pControls->SetKeyReleaseFunc(KeyRelease);
m_pRole = new CFPSRoleLocal();
m_pRole->Init(10001, "data/role/hero/FpsRole/fps.char");
m_pRole->SetActorPosition(vec3(0, 0, 0)); //设置角色初始位置。以门处作为原点,三维坐标系vec3是向量
m_pSkillSystem = new CSkillSystem(this);
m_pCameraBase = new CCameraBase();
m_pCameraBase->SetEnabled(1);
g_pSysControl->SetMouseGrab(1);
m_pStarControl = new CStarControl();
m_pRayControl = new CRayControl();
return 1;
}
int CGameProcess::ShutDown() //关闭游戏进程
{
delete m_pRole;
delete m_pSkillSystem;
delete m_pCameraBase;
delete m_pStarControl;
delete m_pRayControl;
DelAllListen();
return 0;
}
int CGameProcess::Update()
{
float ifps = g_Engine.pGame->GetIFps();
if (g_Engine.pInput->IsKeyDown('1'))
{
CAction* pAction = m_pRole->OrceAction("attack02");
if (pAction)
{
pAction->SetupSkillThrow(vec3_zero, -1.0f, 2.0f);
m_pRole->StopMove();
}
}
else if (g_Engine.pInput->IsKeyDown('2'))
{
CAction* pAction = m_pRole->OrceAction("skill01");
if (pAction)
{
m_pRole->StopMove();
}
}
else if (g_Engine.pInput->IsKeyDown('3'))
{
CAction* pAction = m_pRole->OrceAction("skill02");
if (pAction)
{
m_pRole->StopMove();
CRoleBase* pTarget = NULL;
for (int i = 0; i < 20; i++)
{
float l = (m_vAIList[i]->GetPosition() - m_pRole->GetPosition()).length();
if (l > 5.0f && l < 15.0f)
{
pTarget = m_vAIList[i];
break;
}
}
if (pTarget)
{
CVector<int> vTarget;
vTarget.Append(pTarget->GetRoleID());
pAction->SetupSkillBulletTarget(vTarget);
m_pRole->SetDirection((pTarget->GetPosition() - m_pRole->GetPosition()).normalize(), 1);
}
}
}
else if (g_Engine.pInput->IsKeyDown('4'))//多发子弹
{
CAction* pAction = m_pRole->OrceAction("skill02");
if (pAction)
{
m_pRole->StopMove();
CVector<int> vTarget;
for (int i = 0; i < 20; i++)
{
float l = (m_vAIList[i]->GetPosition() - m_pRole->GetPosition()).length();
if (l > 5.0f && l < 20.0f)
{
vTarget.Append(m_vAIList[i]->GetRoleID());
}
}
if (!vTarget.Empty())
{
pAction->SetupSkillBulletTarget(vTarget);
}
}
}
else if (g_Engine.pInput->IsKeyDown('5'))
{
CAction* pAction = m_pRole->OrceAction("skill03");
if (pAction)
{
m_pRole->StopMove();
CVector<vec3> vPos;
pAction->SetupSkillTargetPoint(vPos);
}
}
else if (g_Engine.pInput->IsKeyDown('6'))
{
CAction* pAction = m_pRole->OrceAction("skill06");
if (pAction)
{
m_pRole->StopMove();
CVector<vec3> vPos;
for (int i = 0; i < 20; i++)
{
float l = (m_vAIList[i]->GetPosition() - m_pRole->GetPosition()).length();
if (l > 5.0f && l < 20.0f)
vPos.Append(m_vAIList[i]->GetPosition());
}
pAction->SetupSkillTargetPoint(vPos);
}
}
else if (g_Engine.pInput->IsKeyDown('7'))
{
CAction* pAction = m_pRole->OrceAction("skill05");
if (pAction)
{
m_pRole->StopMove();
CVector<int> vTarget;
for (int i = 0; i < 20; i++)
{
float l = (m_vAIList[i]->GetPosition() - m_pRole->GetPosition()).length();
if (l > 5.0f && l < 20.0f)
vTarget.Append(m_vAIList[i]->GetRoleID());
}
if (!vTarget.Empty())
{
pAction->SetupSkillBulletTarget(vTarget);
}
}
}
else if (g_Engine.pInput->IsKeyDown('8'))
{
CAction* pAction = m_pRole->OrceAction("skill07");
if (pAction)
{
m_pRole->StopMove();
CVector<vec3> vPos;
for (int i = 0; i < 20; i++)
{
float l = (m_vAIList[i]->GetPosition() - m_pRole->GetPosition()).length();
if (l > 5.0f && l < 20.0f)
vPos.Append(m_vAIList[i]->GetPosition());
}
pAction->SetupSkillBulletPosition(vPos);
}
}
else if (g_Engine.pInput->IsKeyDown('9'))
{
CAction* pAction = m_pRole->OrceAction("skill08");
if (pAction)
{
m_pRole->StopMove();
pAction->SetupSkillBulletDirection(1);
}
}
else if (g_Engine.pInput->IsKeyUp(CInput::KEY_ESC))
{
g_Engine.pApp->Exit();
}
if(g_Engine.pInput->IsLBDown())
{
vec3 p0,p1;
BlueRay::GetPlayerMouseDirection(p0,p1);
vec3 vRetPoint,vRetNormal;
int nS = -1;
g_Engine.pWorld->GetIntersection(p0,p1,CBRObject::MASK_SCENE,vRetPoint,vRetNormal,nS);
if(-1 != nS)
{
m_pRole->MoveToPath(vRetPoint);
}
}
return 0;
}
<commit_msg>Signed-off-by: mrlitong <[email protected]><commit_after>#include "GameProcess.h"
#include "Object.h"
#include "Engine.h"
#include "World.h"
#include "App.h"
#include "ToolsCamera.h"
#include "ControlsApp.h"
#include "MathLib.h"
#include "Game.h"
#include "Editor.h"
#include "Input.h"
#include "BlueRayUtils.h"
#include "World.h"
#include "Action.h"
#include "FPSRoleLocal.h"
using namespace MathLib;
CGameProcess::CGameProcess(void)
{
}
CGameProcess::~CGameProcess(void)
{
}
int CGameProcess::Init()
{
g_Engine.pFileSystem->CacheFilesFormExt("char");
g_Engine.pFileSystem->CacheFilesFormExt("node");
g_Engine.pFileSystem->CacheFilesFormExt("smesh");
g_Engine.pFileSystem->CacheFilesFormExt("sanim");
g_Engine.pWorld->LoadWorld("data/scene/terrain/test/test.world");
//g_Engine.pWorld->LoadWorld("data/scene/terrain/cj/cj.world");
g_Engine.pControls->SetKeyPressFunc(KeyPress);
g_Engine.pControls->SetKeyReleaseFunc(KeyRelease);
m_pRole = new CFPSRoleLocal();
m_pRole->Init(10001, "data/role/hero/FpsRole/fps.char");
m_pRole->SetActorPosition(vec3(0, 0, 0)); //设置角色初始位置。以门处作为原点,三维坐标系vec3是向量
m_pSkillSystem = new CSkillSystem(this);
m_pCameraBase = new CCameraBase();
m_pCameraBase->SetEnabled(1);
g_pSysControl->SetMouseGrab(1);
m_pStarControl = new CStarControl();
m_pRayControl = new CRayControl();
return 1;
}
int CGameProcess::ShutDown() //关闭游戏进程
{
delete m_pRole;
delete m_pSkillSystem;
delete m_pCameraBase;
delete m_pStarControl;
delete m_pRayControl;
DelAllListen();
return 0;
}
int CGameProcess::Update()
{
float ifps = g_Engine.pGame->GetIFps();
if (g_Engine.pInput->IsKeyDown('1'))
{
CAction* pAction = m_pRole->OrceAction("attack02");
if (pAction)
{
pAction->SetupSkillThrow(vec3_zero, -1.0f, 2.0f);
m_pRole->StopMove();
}
}
else if (g_Engine.pInput->IsKeyDown('2'))
{
CAction* pAction = m_pRole->OrceAction("skill01");
if (pAction)
{
m_pRole->StopMove();
}
}
else if (g_Engine.pInput->IsKeyDown('3'))
{
CAction* pAction = m_pRole->OrceAction("skill02");
if (pAction)
{
m_pRole->StopMove();
CRoleBase* pTarget = NULL;
for (int i = 0; i < 20; i++)
{
float l = (m_vAIList[i]->GetPosition() - m_pRole->GetPosition()).length();
if (l > 5.0f && l < 15.0f)
{
pTarget = m_vAIList[i];
break;
}
}
if (pTarget)
{
CVector<int> vTarget;
vTarget.Append(pTarget->GetRoleID());
pAction->SetupSkillBulletTarget(vTarget);
m_pRole->SetDirection((pTarget->GetPosition() - m_pRole->GetPosition()).normalize(), 1);
}
}
}
else if (g_Engine.pInput->IsKeyDown('4'))//多发子弹
{
CAction* pAction = m_pRole->OrceAction("skill02");
if (pAction)
{
m_pRole->StopMove();
CVector<int> vTarget;
for (int i = 0; i < 20; i++)
{
float l = (m_vAIList[i]->GetPosition() - m_pRole->GetPosition()).length();
if (l > 5.0f && l < 20.0f)
{
vTarget.Append(m_vAIList[i]->GetRoleID());
}
}
if (!vTarget.Empty())
{
pAction->SetupSkillBulletTarget(vTarget);
}
}
}
else if (g_Engine.pInput->IsKeyDown('5'))
{
CAction* pAction = m_pRole->OrceAction("skill03");
if (pAction)
{
m_pRole->StopMove();
CVector<vec3> vPos;
pAction->SetupSkillTargetPoint(vPos);
}
}
else if (g_Engine.pInput->IsKeyDown('6'))
{
CAction* pAction = m_pRole->OrceAction("skill06");
if (pAction)
{
m_pRole->StopMove();
CVector<vec3> vPos;
for (int i = 0; i < 20; i++)
{
float l = (m_vAIList[i]->GetPosition() - m_pRole->GetPosition()).length();
if (l > 5.0f && l < 20.0f)
vPos.Append(m_vAIList[i]->GetPosition());
}
pAction->SetupSkillTargetPoint(vPos);
}
}
else if (g_Engine.pInput->IsKeyDown('7'))
{
CAction* pAction = m_pRole->OrceAction("skill05");
if (pAction)
{
m_pRole->StopMove();
CVector<int> vTarget;
for (int i = 0; i < 20; i++)
{
float l = (m_vAIList[i]->GetPosition() - m_pRole->GetPosition()).length();
if (l > 5.0f && l < 20.0f)
vTarget.Append(m_vAIList[i]->GetRoleID());
}
if (!vTarget.Empty())
{
pAction->SetupSkillBulletTarget(vTarget);
}
}
}
else if (g_Engine.pInput->IsKeyDown('8'))
{
CAction* pAction = m_pRole->OrceAction("skill07");
if (pAction)
{
m_pRole->StopMove();
CVector<vec3> vPos;
for (int i = 0; i < 20; i++)
{
float l = (m_vAIList[i]->GetPosition() - m_pRole->GetPosition()).length();
if (l > 5.0f && l < 20.0f)
vPos.Append(m_vAIList[i]->GetPosition());
}
pAction->SetupSkillBulletPosition(vPos);
}
}
else if (g_Engine.pInput->IsKeyDown('9'))
{
CAction* pAction = m_pRole->OrceAction("skill08");
if (pAction)
{
m_pRole->StopMove();
pAction->SetupSkillBulletDirection(1);
}
}
else if (g_Engine.pInput->IsKeyUp(CInput::KEY_ESC))
{
g_Engine.pApp->Exit();
}
if(g_Engine.pInput->IsLBDown())
{
vec3 p0,p1;
BlueRay::GetPlayerMouseDirection(p0,p1);
vec3 vRetPoint,vRetNormal;
int nS = -1;
g_Engine.pWorld->GetIntersection(p0,p1,CBRObject::MASK_SCENE,vRetPoint,vRetNormal,nS);
if(-1 != nS)
{
m_pRole->MoveToPath(vRetPoint);
}
}
for(int i = 0;i < 20;i++)
{
if(!m_vAIList[i]->IsMoveing())
{
vec3 vPos = vec3(g_Engine.pGame->GetRandomFloat(-20.0f,20.0f),g_Engine.pGame->GetRandomFloat(-20.0f,20.0f),1.1f);
m_vAIList[i]->MoveToPath(vPos);
}
m_vAIList[i]->Update(ifps);
}
return 0;
}
<|endoftext|> |
<commit_before>/* ======================================================================
File Name : HandGesture.cpp
Creation Time : 20141015 15:14:24
=========================================================================
Copyright (c),2014-, Po-Jen Hsu. Contact: [email protected]
See the README file in the top-level directory for license.
========================================================================= */
#include "CmdLine.h"
#include "CvRGBCamera.h"
#include "Distribution.h"
#include "VirtualInput.h"
#include "ScreenTool.h"
#include "XMLTool.h"
int main(int argc, char **argv)
{
module_XMLTool::XMLTool *pXMLTool = new module_XMLTool::XMLTool();
std::string dat_path = "dat/";
std::string VirtualInput_XML_file_name = dat_path;
VirtualInput_XML_file_name.append("0.xml");
std::vector<std::vector<int> > key_array(5, std::vector<int> (4) );
if(pXMLTool->setupVirtualInputKeyMap(VirtualInput_XML_file_name.c_str(), key_array) != 0) {
std::cerr << "Error! Cannot initial kep map" << std::endl;
exit(-1);
}
std::string BinaryFilter_XML_file_name = dat_path;
BinaryFilter_XML_file_name.append("BinaryFilter.xml");
std::vector<std::vector<int> > boundary_array(3, std::vector<int> (2) );
if(pXMLTool->setupBinaryFilter(BinaryFilter_XML_file_name.c_str(), boundary_array) != 0) {
std::cerr << "Error! Cannot load BinaryFilter parameters" << std::endl;
exit(-1);
}
std::string CvRGBCamera_XML_file_name = dat_path;
CvRGBCamera_XML_file_name.append("CvRGBCamera.xml");
std::vector<std::vector<int> > camera_array(1, std::vector<int> (6) );
if(pXMLTool->setupCvRGBCamera(CvRGBCamera_XML_file_name.c_str(), camera_array) != 0) {
std::cerr << "Error! Cannot load CvRGBCamera parameters" << std::endl;
exit(-1);
}
std::string GestureThreshold_XML_file_name = dat_path;
GestureThreshold_XML_file_name.append("GestureThreshold.xml");
std::vector<std::vector<int> > threshold_array(1, std::vector<int> (10) );
if(pXMLTool->setupGestureThreshold(GestureThreshold_XML_file_name.c_str(), threshold_array) != 0) {
std::cerr << "Error! Cannot load BinaryFilter parameters" << std::endl;
exit(-1);
}
std::string ROI_XML_file_name = dat_path;
ROI_XML_file_name.append("BinaryFilter.xml");
std::vector<std::vector<int> > ROI_array(1, std::vector<int> (5) );
if(pXMLTool->setupROI(ROI_XML_file_name.c_str(), ROI_array) != 0) {
std::cerr << "Error! Cannot load BinaryFilter parameters" << std::endl;
exit(-1);
}
int camera_id = camera_array[0][0];
int camera_x = camera_array[0][1];
int camera_y = camera_array[0][2];
int camera_fps = camera_array[0][3];
int camera_brightness = camera_array[0][4];
int camera_contrast = camera_array[0][5];
int cut_x_lower = ROI_array[0][0]; // 35;
int cut_x_upper = ROI_array[0][1]; // 35;
int cut_y_lower = ROI_array[0][2]; // 50;
int cut_y_upper = ROI_array[0][3]; // 20;
int ROI_x_lower = cut_x_lower*(camera_x/160);
int ROI_x_upper = camera_x - cut_x_upper*(camera_x/160);
int ROI_y_lower = cut_y_lower*(camera_y/120);
int ROI_y_upper = camera_y - cut_y_upper*(camera_y/120);
int ROI_x_length = ROI_x_upper - ROI_x_lower + 1;
int ROI_y_length = ROI_y_upper - ROI_y_lower + 1;
int ROI_sum_threshold = ROI_array[0][4];
int threshold_key_x_left = threshold_array[0][0];//6;
int threshold_key_x_right = threshold_array[0][1];
int threshold_key_y_up = threshold_array[0][2];//5;
int threshold_key_y_down = threshold_array[0][3] ;
int threshold_move_x = threshold_array[0][4];// 2;
int threshold_move_y = threshold_array[0][5];// 2;
int count_threshold_short = threshold_array[0][6];
int count_threshold_long = threshold_array[0][7];;
int move_factor = threshold_array[0][8];
// int move_step = threshold_array[0][9];
threshold_key_x_left = threshold_key_x_left * (camera_x/160);
threshold_key_x_right = threshold_key_x_right * (camera_x/160);
threshold_key_y_up = threshold_key_y_up * (camera_y/120);
threshold_key_y_down = threshold_key_y_down * (camera_y/120);
threshold_move_x = threshold_move_x * (camera_x/160);
threshold_move_y = threshold_move_y * (camera_y/120);
// int lower1 = 0;
// int upper1 = 50;
// int lower2 = 50;
// int upper2 = 173;
// int lower3 = 20; //20
// int upper3 = 230;//230;
int lower1 = boundary_array[0][0]; //H_upper H/2; 0-180
int upper1 = boundary_array[0][1]; //H_upper
int lower2 = boundary_array[1][0]; //S_lower S*255; 0-255
int upper2 = boundary_array[1][1]; //S_upper
int lower3 = boundary_array[2][0]; //V_lower V*255; 0-255
int upper3 = boundary_array[2][1]; //V_upper
module_CmdLine::CmdLine *pCmdLine = new module_CmdLine::CmdLine();
pCmdLine->setup(argc, argv);
module_CvRGBCamera::CvRGBCamera *pCvRGBCamera = new module_CvRGBCamera::CvRGBCamera(camera_id);
module_Distribution::Distribution *pDistribution = new module_Distribution::Distribution(camera_x, camera_y);
pDistribution->imageROI(ROI_x_lower, ROI_x_upper, ROI_y_lower, ROI_y_upper);
module_VirtualInput::VirtualInput *pVirtualInput = new module_VirtualInput::VirtualInput();
module_ScreenTool::ScreenTool *pScreenTool = new module_ScreenTool::ScreenTool();
pScreenTool->X11Screen();
int screen_x = pScreenTool->screenWidth();
int screen_y = pScreenTool->screenHeight();
int move_type = 1;
pVirtualInput->setup(screen_x, screen_y, move_type);
sleep(1);
if (pCvRGBCamera->setup(camera_x, camera_y, camera_fps, camera_brightness, camera_contrast) == 1) {
std::cerr << "Error!" << std::endl;
}
pCvRGBCamera->setupAutosizeWindow("frame");
// pCvRGBCamera->setupOpenGLWindow("hist_x");
// pCvRGBCamera->setupOpenGLWindow("pos_x");
// pCvRGBCamera->setupOpenGLWindow("hist_y");
// pCvRGBCamera->setupOpenGLWindow("pos_y");
int pos_x, pos_y, pos_pre_x = 0, pos_pre_y = 0, diff_x = 0, diff_y = 0;
cv::Mat dist_x = cv::Mat::zeros(1, camera_x, CV_32SC1);
cv::Mat dist_y = cv::Mat::zeros(camera_y, 1, CV_32SC1);
int left_count = 0, right_count = 0, up_count = 0, down_count = 0;
int no_move = -1;
int press = 1, release = 0;
int dx, dy;
int read_key = -1;
// char return_key[32];
// Display *display;
while (read_key != 27) {
read_key = cv::waitKey(15);
// XQueryKeymap(display, return_key);
// std::cout << "return_key = " << return_key << std::endl;
pDistribution->imageDist2d(pCvRGBCamera->HSVBinary(lower1, lower2, lower3, upper1, upper2, upper3), (int *)dist_x.data, (int *)dist_y.data);
pos_x = pDistribution->imageDistMean((int *)dist_x.data, 0, ROI_x_length, ROI_sum_threshold);
pos_y = pDistribution->imageDistMean((int *)dist_y.data, 0, ROI_y_length, ROI_sum_threshold);
pCvRGBCamera->showBinary("frame", ROI_x_lower, ROI_x_upper, ROI_y_lower, ROI_y_upper);
// pCvRGBCamera->showHistogram("hist_x", (int *)dist_x.data, 0, ROI_x_length);
// pCvRGBCamera->showHistogram("hist_y", (int *)dist_y.data, 0, ROI_y_length);
// pCvRGBCamera->showLine("pos_x",pos_x, ROI_x_lower, ROI_x_upper);
// pCvRGBCamera->showLine("pos_y",pos_y, ROI_y_lower, ROI_y_upper);
// std::cerr << "pos_x=" << pos_x << ",diff_x=" << diff_x << ",pos_y=" << pos_y << ",diff_y=" << diff_y << std::endl;
if (read_key > 47 && read_key < 58) { //"0" == 48, "1" == 49, ... , "9" == 57
VirtualInput_XML_file_name = dat_path;
VirtualInput_XML_file_name.append(std::to_string(read_key-48)).append(".xml");
if(pXMLTool->setupVirtualInputKeyMap(VirtualInput_XML_file_name.c_str(), key_array) == 0) {
pVirtualInput->setup(screen_x, screen_y, key_array[0][1]);
std::cout << "Loading " << VirtualInput_XML_file_name << std::endl;
} else {
std::cerr << "Error! Cannot find " << VirtualInput_XML_file_name << std::endl;
}
read_key = -1;
}
if (left_count > 0) {
left_count--;
}
if (right_count > 0) {
right_count--;
}
if (up_count > 0) {
up_count--;
}
if (down_count > 0) {
down_count--;
}
if (pos_x > -1 && pos_y > -1) {
if (key_array[0][0] > 0) {
dx = diff_x * move_factor;
dy = diff_y * move_factor;
} else {
dx = no_move;
dy = no_move;
}
if (diff_x < -threshold_key_x_left && left_count == 0) {
std::cout << "Detect Left!!" << std::endl;
pVirtualInput->control(press, key_array[1][0], key_array[2][0], key_array[3][0], key_array[4][0], dx, no_move);
if (key_array[0][0] == 0) {
usleep(100);
pVirtualInput->control(release, key_array[1][0], key_array[2][0], key_array[3][0], key_array[4][0], no_move, no_move);
up_count = count_threshold_long;
down_count = count_threshold_long;
}
left_count = count_threshold_short;
right_count = count_threshold_long;
}
if (diff_x > threshold_key_x_right && right_count == 0) {
std::cout << "Detect Right!!" << std::endl;
pVirtualInput->control(press, key_array[1][1], key_array[2][1], key_array[3][1], key_array[4][1], dx, no_move);
if (key_array[0][0] == 0) {
usleep(100);
pVirtualInput->control(release, key_array[1][1], key_array[2][1], key_array[3][1], key_array[4][1], no_move, no_move);
up_count = count_threshold_long;
down_count = count_threshold_long;
}
left_count = count_threshold_long;
right_count = count_threshold_short;
}
if (diff_y < -threshold_key_y_up && up_count == 0) {
std::cout << "Detect Up!!" << std::endl;
pVirtualInput->control(press, key_array[1][2], key_array[2][2], key_array[3][2], key_array[4][2], no_move, dy);
if (key_array[0][0] == 0) {
usleep(100);
pVirtualInput->control(release, key_array[1][2], key_array[2][2], key_array[3][2], key_array[4][2], no_move, no_move);
right_count = count_threshold_long;
left_count = count_threshold_long;
}
up_count = count_threshold_short;
down_count = count_threshold_long;
}
if (diff_y > threshold_key_y_down && down_count == 0) {
std::cout << "Detect Down!!" << std::endl;
pVirtualInput->control(press, key_array[1][3], key_array[2][3], key_array[3][3], key_array[4][3], no_move, dy);
if (key_array[0][0] == 0) {
usleep(100);
pVirtualInput->control(release, key_array[1][3], key_array[2][3], key_array[3][3], key_array[4][3], no_move, no_move);
right_count = count_threshold_long;
left_count = count_threshold_long;
}
up_count = count_threshold_long;
down_count = count_threshold_short;
}
diff_x = pos_pre_x - pos_x;
diff_y = pos_y - pos_pre_y;
pos_pre_x = pos_x;
pos_pre_y = pos_y;
// printf("%d %d %d %d %d %d %d %d\n", 0, -1, -1, -1, -1, 0, 0, 1);
}
}
delete pXMLTool;
delete pScreenTool;
delete pVirtualInput;
delete pDistribution;
delete pCvRGBCamera;
delete pCmdLine;
exit(0);
}
<commit_msg>HandGesture.cpp<commit_after><|endoftext|> |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.