text stringlengths 54 60.6k |
|---|
<commit_before><commit_msg>Ensure we have a Cocoa NSGraphicsContext when needed.<commit_after><|endoftext|> |
<commit_before>/*=========================================================================
Library: CTK
Copyright (c) Kitware 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.txt
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
=========================================================================*/
/// Qt includes
#include <QColor>
#include <QDebug>
/// CTK includes
#include "ctkVTKHistogram.h"
#include "ctkLogger.h"
/// VTK includes
#include <vtkDataArray.h>
#include <vtkIntArray.h>
#include <vtkMath.h>
#include <vtkSmartPointer.h>
/// STL include
#include <limits>
//--------------------------------------------------------------------------
static ctkLogger logger("org.commontk.libs.visualization.core.ctkVTKHistogram");
//--------------------------------------------------------------------------
//-----------------------------------------------------------------------------
class ctkVTKHistogramPrivate
{
public:
ctkVTKHistogramPrivate();
vtkSmartPointer<vtkDataArray> DataArray;
vtkSmartPointer<vtkIntArray> Bins;
int UserNumberOfBins;
int Component;
mutable double Range[2];
int MinBin;
int MaxBin;
int computeNumberOfBins()const;
};
//-----------------------------------------------------------------------------
ctkVTKHistogramPrivate::ctkVTKHistogramPrivate()
{
this->Bins = vtkSmartPointer<vtkIntArray>::New();
this->UserNumberOfBins = -1;
this->Component = 0;
this->Range[0] = this->Range[1] = 0.;
this->MinBin = 0;
this->MaxBin = 0;
}
//-----------------------------------------------------------------------------
int ctkVTKHistogramPrivate::computeNumberOfBins()const
{
if (this->DataArray.GetPointer() == 0)
{
return -1;
}
if (this->UserNumberOfBins > 0)
{
return this->UserNumberOfBins;
}
return static_cast<int>(this->Range[1] - this->Range[0]) + 1;
}
//-----------------------------------------------------------------------------
ctkVTKHistogram::ctkVTKHistogram(QObject* parentObject)
:ctkHistogram(parentObject)
, d_ptr(new ctkVTKHistogramPrivate)
{
}
//-----------------------------------------------------------------------------
ctkVTKHistogram::ctkVTKHistogram(vtkDataArray* dataArray,
QObject* parentObject)
:ctkHistogram(parentObject)
, d_ptr(new ctkVTKHistogramPrivate)
{
this->setDataArray(dataArray);
}
//-----------------------------------------------------------------------------
ctkVTKHistogram::~ctkVTKHistogram()
{
}
//-----------------------------------------------------------------------------
int ctkVTKHistogram::count()const
{
Q_D(const ctkVTKHistogram);
return d->Bins->GetNumberOfTuples();
}
//-----------------------------------------------------------------------------
void ctkVTKHistogram::setRange(qreal minRange, qreal maxRange)
{
Q_D(const ctkVTKHistogram);
if (d->DataArray.GetPointer() == 0)
{
//Q_ASSERT(d->DataArray.GetPointer());
logger.warn("no data array. range will be reset when setting array.");
minRange = 1.; // set incorrect values
maxRange = 0.;
return;
}
if (minRange >= maxRange)
{
//Q_ASSERT(d->DataArray.GetPointer());
logger.warn("minRange >= maxRange");
qreal pivot = minRange;
minRange = maxRange;
maxRange = pivot;
}
int numberOfBinsBefore = d->computeNumberOfBins();
d->Range[0] = minRange;
d->Range[1] = maxRange;
if (d->computeNumberOfBins() != numberOfBinsBefore)
{
this->build();
}
}
//-----------------------------------------------------------------------------
void ctkVTKHistogram::range(qreal& minRange, qreal& maxRange)const
{
Q_D(const ctkVTKHistogram);
if (d->DataArray.GetPointer() == 0)
{
//Q_ASSERT(d->DataArray.GetPointer());
logger.warn("no dataArray");
minRange = 1.; // set incorrect values
maxRange = 0.;
return;
}
minRange = d->Range[0];
maxRange = d->Range[1];
}
//-----------------------------------------------------------------------------
void ctkVTKHistogram::resetRange()
{
Q_D(ctkVTKHistogram);
if (d->DataArray.GetPointer() == 0)
{
//Q_ASSERT(d->DataArray.GetPointer());
logger.warn("no dataArray");
d->Range[0] = 1.; // set incorrect values
d->Range[1] = 0.;
return;
}
if (d->DataArray->GetDataType() == VTK_CHAR ||
d->DataArray->GetDataType() == VTK_SIGNED_CHAR ||
d->DataArray->GetDataType() == VTK_UNSIGNED_CHAR)
{
d->Range[0] = d->DataArray->GetDataTypeMin();
d->Range[1] = d->DataArray->GetDataTypeMax();
}
else
{
d->DataArray->GetRange(d->Range, d->Component);
if (d->DataArray->GetDataType() == VTK_FLOAT ||
d->DataArray->GetDataType() == VTK_DOUBLE)
{
d->Range[1] += 0.01;
}
//else
// {
// this->Range[1] += 1;
// }
}
}
//-----------------------------------------------------------------------------
QVariant ctkVTKHistogram::minValue()const
{
//Q_D(const ctkVTKHistogram);
return 0;//d->MinBin;
}
//-----------------------------------------------------------------------------
QVariant ctkVTKHistogram::maxValue()const
{
Q_D(const ctkVTKHistogram);
return d->MaxBin;
}
//-----------------------------------------------------------------------------
ctkControlPoint* ctkVTKHistogram::controlPoint(int index)const
{
Q_D(const ctkVTKHistogram);
ctkHistogramBar* cp = new ctkHistogramBar();
cp->P.X = this->indexToPos(index);
cp->P.Value = d->Bins->GetValue(index);
return cp;
}
//-----------------------------------------------------------------------------
QVariant ctkVTKHistogram::value(qreal pos)const
{
QSharedPointer<ctkControlPoint> point(this->controlPoint(this->posToIndex(pos)));
return point->value();
}
//-----------------------------------------------------------------------------
qreal ctkVTKHistogram::indexToPos(int index)const
{
qreal posRange[2];
this->range(posRange[0], posRange[1]);
return posRange[0] + index * ((posRange[1] - posRange[0]) / (this->count() - 1));
}
//-----------------------------------------------------------------------------
int ctkVTKHistogram::posToIndex(qreal pos)const
{
qreal posRange[2];
this->range(posRange[0], posRange[1]);
return (pos - posRange[0]) / ((posRange[1] - posRange[0]) / (this->count() - 1));
}
//-----------------------------------------------------------------------------
void ctkVTKHistogram::setDataArray(vtkDataArray* newDataArray)
{
Q_D(ctkVTKHistogram);
if (newDataArray == d->DataArray)
{
return;
}
d->DataArray = newDataArray;
this->resetRange();
this->qvtkReconnect(d->DataArray,vtkCommand::ModifiedEvent,
this, SIGNAL(changed()));
emit changed();
}
//-----------------------------------------------------------------------------
vtkDataArray* ctkVTKHistogram::dataArray()const
{
Q_D(const ctkVTKHistogram);
return d->DataArray;
}
//-----------------------------------------------------------------------------
void ctkVTKHistogram::setComponent(int component)
{
Q_D(ctkVTKHistogram);
d->Component = component;
// need rebuild
}
//-----------------------------------------------------------------------------
int ctkVTKHistogram::component()const
{
Q_D(const ctkVTKHistogram);
return d->Component;
}
//-----------------------------------------------------------------------------
int ctkVTKHistogram::numberOfBins()const
{
Q_D(const ctkVTKHistogram);
return d->UserNumberOfBins;
}
//-----------------------------------------------------------------------------
void ctkVTKHistogram::setNumberOfBins(int number)
{
Q_D(ctkVTKHistogram);
d->UserNumberOfBins = number;
}
//-----------------------------------------------------------------------------
template <class T>
void populateBins(vtkIntArray* bins, const ctkVTKHistogram* histogram)
{
vtkDataArray* scalars = histogram->dataArray();
int* binsPtr = bins->WritePointer(0, bins->GetNumberOfTuples());
// reset bins to 0
memset(binsPtr, 0, bins->GetNumberOfComponents()*bins->GetNumberOfTuples()*sizeof(int));
const vtkIdType componentNumber = scalars->GetNumberOfComponents();
const vtkIdType tupleNumber = scalars->GetNumberOfTuples();
int component = histogram->component();
double range[2];
histogram->range(range[0], range[1]);
T offset = static_cast<T>(range[0]);
T* ptr = static_cast<T*>(scalars->WriteVoidPointer(0, tupleNumber));
T* endPtr = ptr + tupleNumber * componentNumber;
ptr += component;
vtkIdType histogramSize = bins->GetNumberOfTuples();
for (; ptr < endPtr; ptr += componentNumber)
{
int index = static_cast<int>(*ptr - offset);
if (index < 0 || index >= histogramSize)
{
// This happens when scalar range is not computed correctly
// (scalar range may be read from file, so VTK does not have full control over it)
continue;
}
binsPtr[index]++;
}
}
//-----------------------------------------------------------------------------
template <class T>
void populateIrregularBins(vtkIntArray* bins, const ctkVTKHistogram* histogram)
{
vtkDataArray* scalars = histogram->dataArray();
int* binsPtr = bins->WritePointer(0, bins->GetNumberOfComponents()*bins->GetNumberOfTuples());
// reset bins to 0
memset(binsPtr, 0, bins->GetNumberOfTuples() * sizeof(int));
const vtkIdType componentNumber = scalars->GetNumberOfComponents();
const vtkIdType tupleNumber = scalars->GetNumberOfTuples();
int component = histogram->component();
double range[2];
histogram->range(range[0], range[1]);
double offset = range[0];
double binWidth = 1.;
if (range[1] != range[0])
{
binWidth = static_cast<double>(bins->GetNumberOfTuples()-1) / (range[1] - range[0]);
}
T* ptr = static_cast<T*>(scalars->WriteVoidPointer(0, tupleNumber));
T* endPtr = ptr + tupleNumber * componentNumber;
ptr += component;
vtkIdType histogramSize = bins->GetNumberOfTuples();
for (; ptr < endPtr; ptr += componentNumber)
{
if ((std::numeric_limits<T>::has_quiet_NaN &&
vtkMath::IsNan(*ptr)) || vtkMath::IsInf(*ptr))
{
continue;
}
int index = vtkMath::Floor((static_cast<double>(*ptr) - offset) * binWidth);
if (index < 0 || index >= histogramSize)
{
// This happens when scalar range is not computed correctly
// (scalar range may be read from file, so VTK does not have full control over it)
continue;
}
binsPtr[index]++;
}
}
//-----------------------------------------------------------------------------
void ctkVTKHistogram::build()
{
Q_D(ctkVTKHistogram);
if (d->DataArray.GetPointer() == 0)
{
d->MinBin = 0;
d->MaxBin = 0;
d->Bins->SetNumberOfTuples(0);
return;
}
const int binCount = d->computeNumberOfBins();
d->Bins->SetNumberOfComponents(1);
d->Bins->SetNumberOfTuples(binCount);
if (binCount <= 0)
{
d->MinBin = 0;
d->MaxBin = 0;
return;
}
// What is the type of the array, discrete or reals
if (static_cast<double>(binCount) != (d->Range[1] - d->Range[0] + 1))
{
switch(d->DataArray->GetDataType())
{
vtkTemplateMacro(populateIrregularBins<VTK_TT>(d->Bins, this));
}
}
else
{
switch(d->DataArray->GetDataType())
{
vtkTemplateMacro(populateBins<VTK_TT>(d->Bins, this));
}
}
// update Min/Max values
int* binPtr = d->Bins->GetPointer(0);
int* endPtr = d->Bins->GetPointer(binCount-1);
d->MinBin = *endPtr;
d->MaxBin = *endPtr;
for (;binPtr < endPtr; ++binPtr)
{
d->MinBin = qMin(*binPtr, d->MinBin);
d->MaxBin = qMax(*binPtr, d->MaxBin);
}
emit changed();
}
//-----------------------------------------------------------------------------
void ctkVTKHistogram::removeControlPoint( qreal pos )
{
Q_UNUSED(pos);
// TO BE IMPLEMENTED
}
<commit_msg>BUG: Fix unnecessary warning in ctkVTKHistogram::resetRange()<commit_after>/*=========================================================================
Library: CTK
Copyright (c) Kitware 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.txt
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
=========================================================================*/
/// Qt includes
#include <QColor>
#include <QDebug>
/// CTK includes
#include "ctkVTKHistogram.h"
#include "ctkLogger.h"
/// VTK includes
#include <vtkDataArray.h>
#include <vtkIntArray.h>
#include <vtkMath.h>
#include <vtkSmartPointer.h>
/// STL include
#include <limits>
//--------------------------------------------------------------------------
static ctkLogger logger("org.commontk.libs.visualization.core.ctkVTKHistogram");
//--------------------------------------------------------------------------
//-----------------------------------------------------------------------------
class ctkVTKHistogramPrivate
{
public:
ctkVTKHistogramPrivate();
vtkSmartPointer<vtkDataArray> DataArray;
vtkSmartPointer<vtkIntArray> Bins;
int UserNumberOfBins;
int Component;
mutable double Range[2];
int MinBin;
int MaxBin;
int computeNumberOfBins()const;
};
//-----------------------------------------------------------------------------
ctkVTKHistogramPrivate::ctkVTKHistogramPrivate()
{
this->Bins = vtkSmartPointer<vtkIntArray>::New();
this->UserNumberOfBins = -1;
this->Component = 0;
this->Range[0] = this->Range[1] = 0.;
this->MinBin = 0;
this->MaxBin = 0;
}
//-----------------------------------------------------------------------------
int ctkVTKHistogramPrivate::computeNumberOfBins()const
{
if (this->DataArray.GetPointer() == 0)
{
return -1;
}
if (this->UserNumberOfBins > 0)
{
return this->UserNumberOfBins;
}
return static_cast<int>(this->Range[1] - this->Range[0]) + 1;
}
//-----------------------------------------------------------------------------
ctkVTKHistogram::ctkVTKHistogram(QObject* parentObject)
:ctkHistogram(parentObject)
, d_ptr(new ctkVTKHistogramPrivate)
{
}
//-----------------------------------------------------------------------------
ctkVTKHistogram::ctkVTKHistogram(vtkDataArray* dataArray,
QObject* parentObject)
:ctkHistogram(parentObject)
, d_ptr(new ctkVTKHistogramPrivate)
{
this->setDataArray(dataArray);
}
//-----------------------------------------------------------------------------
ctkVTKHistogram::~ctkVTKHistogram()
{
}
//-----------------------------------------------------------------------------
int ctkVTKHistogram::count()const
{
Q_D(const ctkVTKHistogram);
return d->Bins->GetNumberOfTuples();
}
//-----------------------------------------------------------------------------
void ctkVTKHistogram::setRange(qreal minRange, qreal maxRange)
{
Q_D(const ctkVTKHistogram);
if (d->DataArray.GetPointer() == 0)
{
logger.warn("no data array. range will be reset when setting array.");
minRange = 1.; // set incorrect values
maxRange = 0.;
return;
}
if (minRange >= maxRange)
{
logger.warn("minRange >= maxRange");
qreal pivot = minRange;
minRange = maxRange;
maxRange = pivot;
}
int numberOfBinsBefore = d->computeNumberOfBins();
d->Range[0] = minRange;
d->Range[1] = maxRange;
if (d->computeNumberOfBins() != numberOfBinsBefore)
{
this->build();
}
}
//-----------------------------------------------------------------------------
void ctkVTKHistogram::range(qreal& minRange, qreal& maxRange)const
{
Q_D(const ctkVTKHistogram);
if (d->DataArray.GetPointer() == 0)
{
logger.warn("no dataArray");
minRange = 1.; // set incorrect values
maxRange = 0.;
return;
}
minRange = d->Range[0];
maxRange = d->Range[1];
}
//-----------------------------------------------------------------------------
void ctkVTKHistogram::resetRange()
{
Q_D(ctkVTKHistogram);
if (d->DataArray.GetPointer() == 0)
{
// Data array is empty (not an error case, will be displayed as an empty histogram)
d->Range[0] = 1.; // set incorrect values
d->Range[1] = 0.;
return;
}
if (d->DataArray->GetDataType() == VTK_CHAR ||
d->DataArray->GetDataType() == VTK_SIGNED_CHAR ||
d->DataArray->GetDataType() == VTK_UNSIGNED_CHAR)
{
d->Range[0] = d->DataArray->GetDataTypeMin();
d->Range[1] = d->DataArray->GetDataTypeMax();
}
else
{
d->DataArray->GetRange(d->Range, d->Component);
if (d->DataArray->GetDataType() == VTK_FLOAT ||
d->DataArray->GetDataType() == VTK_DOUBLE)
{
d->Range[1] += 0.01;
}
//else
// {
// this->Range[1] += 1;
// }
}
}
//-----------------------------------------------------------------------------
QVariant ctkVTKHistogram::minValue()const
{
//Q_D(const ctkVTKHistogram);
return 0;//d->MinBin;
}
//-----------------------------------------------------------------------------
QVariant ctkVTKHistogram::maxValue()const
{
Q_D(const ctkVTKHistogram);
return d->MaxBin;
}
//-----------------------------------------------------------------------------
ctkControlPoint* ctkVTKHistogram::controlPoint(int index)const
{
Q_D(const ctkVTKHistogram);
ctkHistogramBar* cp = new ctkHistogramBar();
cp->P.X = this->indexToPos(index);
cp->P.Value = d->Bins->GetValue(index);
return cp;
}
//-----------------------------------------------------------------------------
QVariant ctkVTKHistogram::value(qreal pos)const
{
QSharedPointer<ctkControlPoint> point(this->controlPoint(this->posToIndex(pos)));
return point->value();
}
//-----------------------------------------------------------------------------
qreal ctkVTKHistogram::indexToPos(int index)const
{
qreal posRange[2];
this->range(posRange[0], posRange[1]);
return posRange[0] + index * ((posRange[1] - posRange[0]) / (this->count() - 1));
}
//-----------------------------------------------------------------------------
int ctkVTKHistogram::posToIndex(qreal pos)const
{
qreal posRange[2];
this->range(posRange[0], posRange[1]);
return (pos - posRange[0]) / ((posRange[1] - posRange[0]) / (this->count() - 1));
}
//-----------------------------------------------------------------------------
void ctkVTKHistogram::setDataArray(vtkDataArray* newDataArray)
{
Q_D(ctkVTKHistogram);
if (newDataArray == d->DataArray)
{
return;
}
d->DataArray = newDataArray;
this->resetRange();
this->qvtkReconnect(d->DataArray,vtkCommand::ModifiedEvent,
this, SIGNAL(changed()));
emit changed();
}
//-----------------------------------------------------------------------------
vtkDataArray* ctkVTKHistogram::dataArray()const
{
Q_D(const ctkVTKHistogram);
return d->DataArray;
}
//-----------------------------------------------------------------------------
void ctkVTKHistogram::setComponent(int component)
{
Q_D(ctkVTKHistogram);
d->Component = component;
// need rebuild
}
//-----------------------------------------------------------------------------
int ctkVTKHistogram::component()const
{
Q_D(const ctkVTKHistogram);
return d->Component;
}
//-----------------------------------------------------------------------------
int ctkVTKHistogram::numberOfBins()const
{
Q_D(const ctkVTKHistogram);
return d->UserNumberOfBins;
}
//-----------------------------------------------------------------------------
void ctkVTKHistogram::setNumberOfBins(int number)
{
Q_D(ctkVTKHistogram);
d->UserNumberOfBins = number;
}
//-----------------------------------------------------------------------------
template <class T>
void populateBins(vtkIntArray* bins, const ctkVTKHistogram* histogram)
{
vtkDataArray* scalars = histogram->dataArray();
int* binsPtr = bins->WritePointer(0, bins->GetNumberOfTuples());
// reset bins to 0
memset(binsPtr, 0, bins->GetNumberOfComponents()*bins->GetNumberOfTuples()*sizeof(int));
const vtkIdType componentNumber = scalars->GetNumberOfComponents();
const vtkIdType tupleNumber = scalars->GetNumberOfTuples();
int component = histogram->component();
double range[2];
histogram->range(range[0], range[1]);
T offset = static_cast<T>(range[0]);
T* ptr = static_cast<T*>(scalars->WriteVoidPointer(0, tupleNumber));
T* endPtr = ptr + tupleNumber * componentNumber;
ptr += component;
vtkIdType histogramSize = bins->GetNumberOfTuples();
for (; ptr < endPtr; ptr += componentNumber)
{
int index = static_cast<int>(*ptr - offset);
if (index < 0 || index >= histogramSize)
{
// This happens when scalar range is not computed correctly
// (scalar range may be read from file, so VTK does not have full control over it)
continue;
}
binsPtr[index]++;
}
}
//-----------------------------------------------------------------------------
template <class T>
void populateIrregularBins(vtkIntArray* bins, const ctkVTKHistogram* histogram)
{
vtkDataArray* scalars = histogram->dataArray();
int* binsPtr = bins->WritePointer(0, bins->GetNumberOfComponents()*bins->GetNumberOfTuples());
// reset bins to 0
memset(binsPtr, 0, bins->GetNumberOfTuples() * sizeof(int));
const vtkIdType componentNumber = scalars->GetNumberOfComponents();
const vtkIdType tupleNumber = scalars->GetNumberOfTuples();
int component = histogram->component();
double range[2];
histogram->range(range[0], range[1]);
double offset = range[0];
double binWidth = 1.;
if (range[1] != range[0])
{
binWidth = static_cast<double>(bins->GetNumberOfTuples()-1) / (range[1] - range[0]);
}
T* ptr = static_cast<T*>(scalars->WriteVoidPointer(0, tupleNumber));
T* endPtr = ptr + tupleNumber * componentNumber;
ptr += component;
vtkIdType histogramSize = bins->GetNumberOfTuples();
for (; ptr < endPtr; ptr += componentNumber)
{
if ((std::numeric_limits<T>::has_quiet_NaN &&
vtkMath::IsNan(*ptr)) || vtkMath::IsInf(*ptr))
{
continue;
}
int index = vtkMath::Floor((static_cast<double>(*ptr) - offset) * binWidth);
if (index < 0 || index >= histogramSize)
{
// This happens when scalar range is not computed correctly
// (scalar range may be read from file, so VTK does not have full control over it)
continue;
}
binsPtr[index]++;
}
}
//-----------------------------------------------------------------------------
void ctkVTKHistogram::build()
{
Q_D(ctkVTKHistogram);
if (d->DataArray.GetPointer() == 0)
{
d->MinBin = 0;
d->MaxBin = 0;
d->Bins->SetNumberOfTuples(0);
return;
}
const int binCount = d->computeNumberOfBins();
d->Bins->SetNumberOfComponents(1);
d->Bins->SetNumberOfTuples(binCount);
if (binCount <= 0)
{
d->MinBin = 0;
d->MaxBin = 0;
return;
}
// What is the type of the array, discrete or reals
if (static_cast<double>(binCount) != (d->Range[1] - d->Range[0] + 1))
{
switch(d->DataArray->GetDataType())
{
vtkTemplateMacro(populateIrregularBins<VTK_TT>(d->Bins, this));
}
}
else
{
switch(d->DataArray->GetDataType())
{
vtkTemplateMacro(populateBins<VTK_TT>(d->Bins, this));
}
}
// update Min/Max values
int* binPtr = d->Bins->GetPointer(0);
int* endPtr = d->Bins->GetPointer(binCount-1);
d->MinBin = *endPtr;
d->MaxBin = *endPtr;
for (;binPtr < endPtr; ++binPtr)
{
d->MinBin = qMin(*binPtr, d->MinBin);
d->MaxBin = qMax(*binPtr, d->MaxBin);
}
emit changed();
}
//-----------------------------------------------------------------------------
void ctkVTKHistogram::removeControlPoint( qreal pos )
{
Q_UNUSED(pos);
// TO BE IMPLEMENTED
}
<|endoftext|> |
<commit_before>// -------------------------------------------------------------------------
// @FileName : NFCNPCRefreshModule.cpp
// @Author : LvSheng.Huang
// @Date : 2013-10-17
// @Module : NFCNPCRefreshModule
// -------------------------------------------------------------------------
#include "NFCNPCRefreshModule.h"
bool NFCNPCRefreshModule::Init()
{
return true;
}
bool NFCNPCRefreshModule::Shut()
{
return true;
}
bool NFCNPCRefreshModule::Execute()
{
return true;
}
bool NFCNPCRefreshModule::AfterInit()
{
m_pScheduleModule = pPluginManager->FindModule<NFIScheduleModule>();
m_pEventModule = pPluginManager->FindModule<NFIEventModule>();
m_pKernelModule = pPluginManager->FindModule<NFIKernelModule>();
m_pSceneProcessModule = pPluginManager->FindModule<NFISceneProcessModule>();
m_pElementModule = pPluginManager->FindModule<NFIElementModule>();
m_pPackModule = pPluginManager->FindModule<NFIPackModule>();
m_pLogModule = pPluginManager->FindModule<NFILogModule>();
m_pLevelModule = pPluginManager->FindModule<NFILevelModule>();
m_pHeroPropertyModule = pPluginManager->FindModule<NFIHeroPropertyModule>();
m_pKernelModule->AddClassCallBack(NFrame::NPC::ThisName(), this, &NFCNPCRefreshModule::OnObjectClassEvent);
return true;
}
int NFCNPCRefreshModule::OnObjectClassEvent( const NFGUID& self, const std::string& strClassName, const CLASS_OBJECT_EVENT eClassEvent, const NFIDataList& var )
{
NF_SHARE_PTR<NFIObject> pSelf = m_pKernelModule->GetObject(self);
if (nullptr == pSelf)
{
return 1;
}
if (strClassName == NFrame::NPC::ThisName())
{
if ( CLASS_OBJECT_EVENT::COE_CREATE_LOADDATA == eClassEvent )
{
const std::string& strConfigIndex = m_pKernelModule->GetPropertyString(self, NFrame::NPC::ConfigID());
const std::string& strPropertyID = m_pElementModule->GetPropertyString(strConfigIndex, NFrame::NPC::EffectData());
const int nNPCType = m_pElementModule->GetPropertyInt(strConfigIndex, NFrame::NPC::NPCType());
NF_SHARE_PTR<NFIPropertyManager> pSelfPropertyManager = pSelf->GetPropertyManager();
if (nNPCType == NFMsg::ENPCType::ENPCTYPE_HERO)
{
//hero
NFGUID xMasterID = m_pKernelModule->GetPropertyObject(self, NFrame::NPC::MasterID());
NF_SHARE_PTR<NFIRecord> pHeroPropertyRecord = m_pKernelModule->FindRecord(xMasterID, NFrame::Player::R_HeroPropertyValue());
if (pHeroPropertyRecord)
{
NFCDataList xHeroPropertyList;
if (m_pHeroPropertyModule->CalHeroAllProperty(xMasterID, self, xHeroPropertyList))
{
for (int i = 0; i < pHeroPropertyRecord->GetCols(); ++i)
{
const std::string& strColTag = pHeroPropertyRecord->GetColTag(i);
const int nValue = xHeroPropertyList.Int(i);
pSelfPropertyManager->SetPropertyInt(strColTag, nValue);
}
}
}
}
else
{
//normal npc
NF_SHARE_PTR<NFIPropertyManager> pConfigPropertyManager = m_pElementModule->GetPropertyManager(strPropertyID);
if (pConfigPropertyManager)
{
std::string strProperName;
for (NFIProperty* pProperty = pConfigPropertyManager->FirstNude(strProperName); pProperty != NULL; pProperty = pConfigPropertyManager->NextNude(strProperName))
{
if (pSelfPropertyManager && strProperName != NFrame::NPC::ID())
{
pSelfPropertyManager->SetProperty(pProperty->GetKey(), pProperty->GetValue());
}
}
}
}
}
else if ( CLASS_OBJECT_EVENT::COE_CREATE_HASDATA == eClassEvent )
{
const std::string& strConfigID = m_pKernelModule->GetPropertyString(self, NFrame::NPC::ConfigID());
int nHPMax = m_pElementModule->GetPropertyInt(strConfigID, NFrame::NPC::MAXHP());
m_pKernelModule->SetPropertyInt(self, NFrame::NPC::HP(), nHPMax);
m_pKernelModule->AddPropertyCallBack( self, NFrame::NPC::HP(), this, &NFCNPCRefreshModule::OnObjectHPEvent );
m_pEventModule->AddEventCallBack( self, NFED_ON_OBJECT_BE_KILLED, this, &NFCNPCRefreshModule::OnObjectBeKilled );
}
}
return 0;
}
int NFCNPCRefreshModule::OnObjectHPEvent( const NFGUID& self, const std::string& strPropertyName, const NFIDataList::TData& oldVar, const NFIDataList::TData& newVar)
{
if ( newVar.GetInt() <= 0 )
{
NFGUID identAttacker = m_pKernelModule->GetPropertyObject( self, NFrame::NPC::LastAttacker());
if (!identAttacker.IsNull())
{
m_pEventModule->DoEvent( self, NFED_ON_OBJECT_BE_KILLED, NFCDataList() << identAttacker );
m_pScheduleModule->AddSchedule( self, "OnDeadDestroyHeart", this, &NFCNPCRefreshModule::OnDeadDestroyHeart, 5.0f, 1 );
}
}
return 0;
}
int NFCNPCRefreshModule::OnDeadDestroyHeart( const NFGUID& self, const std::string& strHeartBeat, const float fTime, const int nCount)
{
//and create new object
const std::string& strClassName = m_pKernelModule->GetPropertyString( self, NFrame::NPC::ClassName());
const std::string& strSeedID = m_pKernelModule->GetPropertyString( self, NFrame::NPC::SeedID());
const std::string& strConfigID = m_pKernelModule->GetPropertyString( self, NFrame::NPC::ConfigID());
int nSceneID = m_pKernelModule->GetPropertyInt( self, NFrame::NPC::SceneID());
int nGroupID = m_pKernelModule->GetPropertyInt( self, NFrame::NPC::GroupID());
//m_pSceneProcessModule->ClearAll( nSceneID, nGroupID, strSeendID );
float fSeedX = m_pKernelModule->GetPropertyFloat( self, NFrame::NPC::X());
float fSeedY = m_pKernelModule->GetPropertyFloat( self, NFrame::NPC::Y());
float fSeedZ = m_pKernelModule->GetPropertyFloat( self, NFrame::NPC::Z());
m_pKernelModule->DestroyObject( self );
NFCDataList arg;
arg << NFrame::NPC::X() << fSeedX;
arg << NFrame::NPC::Y() << fSeedY;
arg << NFrame::NPC::Z() << fSeedZ;
arg << NFrame::NPC::SeedID() << strSeedID;
m_pKernelModule->CreateObject( NFGUID(), nSceneID, nGroupID, strClassName, strConfigID, arg );
return 0;
}
int NFCNPCRefreshModule::OnObjectBeKilled( const NFGUID& self, const NFEventDefine nEventID, const NFIDataList& var )
{
if ( var.GetCount() == 1 && var.Type( 0 ) == TDATA_OBJECT )
{
NFGUID identKiller = var.Object( 0 );
if ( m_pKernelModule->GetObject( identKiller ) )
{
const int nExp = m_pKernelModule->GetPropertyInt( self, NFrame::Player::EXP() );
m_pLevelModule->AddExp( identKiller, nExp);
m_pLogModule->LogNormal(NFILogModule::NLL_INFO_NORMAL, identKiller, "Add Exp for kill monster", nExp);
}
else
{
m_pLogModule->LogObject(NFILogModule::NLL_ERROR_NORMAL, identKiller, "There is no object", __FUNCTION__, __LINE__);
}
}
return 0;
}<commit_msg>remove unused code<commit_after>// -------------------------------------------------------------------------
// @FileName : NFCNPCRefreshModule.cpp
// @Author : LvSheng.Huang
// @Date : 2013-10-17
// @Module : NFCNPCRefreshModule
// -------------------------------------------------------------------------
#include "NFCNPCRefreshModule.h"
bool NFCNPCRefreshModule::Init()
{
return true;
}
bool NFCNPCRefreshModule::Shut()
{
return true;
}
bool NFCNPCRefreshModule::Execute()
{
return true;
}
bool NFCNPCRefreshModule::AfterInit()
{
m_pScheduleModule = pPluginManager->FindModule<NFIScheduleModule>();
m_pEventModule = pPluginManager->FindModule<NFIEventModule>();
m_pKernelModule = pPluginManager->FindModule<NFIKernelModule>();
m_pSceneProcessModule = pPluginManager->FindModule<NFISceneProcessModule>();
m_pElementModule = pPluginManager->FindModule<NFIElementModule>();
m_pPackModule = pPluginManager->FindModule<NFIPackModule>();
m_pLogModule = pPluginManager->FindModule<NFILogModule>();
m_pLevelModule = pPluginManager->FindModule<NFILevelModule>();
m_pHeroPropertyModule = pPluginManager->FindModule<NFIHeroPropertyModule>();
m_pKernelModule->AddClassCallBack(NFrame::NPC::ThisName(), this, &NFCNPCRefreshModule::OnObjectClassEvent);
return true;
}
int NFCNPCRefreshModule::OnObjectClassEvent( const NFGUID& self, const std::string& strClassName, const CLASS_OBJECT_EVENT eClassEvent, const NFIDataList& var )
{
NF_SHARE_PTR<NFIObject> pSelf = m_pKernelModule->GetObject(self);
if (nullptr == pSelf)
{
return 1;
}
if (strClassName == NFrame::NPC::ThisName())
{
if ( CLASS_OBJECT_EVENT::COE_CREATE_LOADDATA == eClassEvent )
{
const std::string& strConfigIndex = m_pKernelModule->GetPropertyString(self, NFrame::NPC::ConfigID());
const std::string& strPropertyID = m_pElementModule->GetPropertyString(strConfigIndex, NFrame::NPC::EffectData());
const int nNPCType = m_pElementModule->GetPropertyInt(strConfigIndex, NFrame::NPC::NPCType());
NF_SHARE_PTR<NFIPropertyManager> pSelfPropertyManager = pSelf->GetPropertyManager();
if (nNPCType == NFMsg::ENPCType::ENPCTYPE_HERO)
{
//hero
NFGUID xMasterID = m_pKernelModule->GetPropertyObject(self, NFrame::NPC::MasterID());
NF_SHARE_PTR<NFIRecord> pHeroPropertyRecord = m_pKernelModule->FindRecord(xMasterID, NFrame::Player::R_HeroPropertyValue());
if (pHeroPropertyRecord)
{
NFCDataList xHeroPropertyList;
if (m_pHeroPropertyModule->CalHeroAllProperty(xMasterID, self, xHeroPropertyList))
{
for (int i = 0; i < pHeroPropertyRecord->GetCols(); ++i)
{
const std::string& strColTag = pHeroPropertyRecord->GetColTag(i);
const int nValue = xHeroPropertyList.Int(i);
pSelfPropertyManager->SetPropertyInt(strColTag, nValue);
}
}
}
}
}
else if ( CLASS_OBJECT_EVENT::COE_CREATE_HASDATA == eClassEvent )
{
const std::string& strConfigID = m_pKernelModule->GetPropertyString(self, NFrame::NPC::ConfigID());
int nHPMax = m_pElementModule->GetPropertyInt(strConfigID, NFrame::NPC::MAXHP());
m_pKernelModule->SetPropertyInt(self, NFrame::NPC::HP(), nHPMax);
m_pKernelModule->AddPropertyCallBack( self, NFrame::NPC::HP(), this, &NFCNPCRefreshModule::OnObjectHPEvent );
m_pEventModule->AddEventCallBack( self, NFED_ON_OBJECT_BE_KILLED, this, &NFCNPCRefreshModule::OnObjectBeKilled );
}
}
return 0;
}
int NFCNPCRefreshModule::OnObjectHPEvent( const NFGUID& self, const std::string& strPropertyName, const NFIDataList::TData& oldVar, const NFIDataList::TData& newVar)
{
if ( newVar.GetInt() <= 0 )
{
NFGUID identAttacker = m_pKernelModule->GetPropertyObject( self, NFrame::NPC::LastAttacker());
if (!identAttacker.IsNull())
{
m_pEventModule->DoEvent( self, NFED_ON_OBJECT_BE_KILLED, NFCDataList() << identAttacker );
m_pScheduleModule->AddSchedule( self, "OnDeadDestroyHeart", this, &NFCNPCRefreshModule::OnDeadDestroyHeart, 5.0f, 1 );
}
}
return 0;
}
int NFCNPCRefreshModule::OnDeadDestroyHeart( const NFGUID& self, const std::string& strHeartBeat, const float fTime, const int nCount)
{
//and create new object
const std::string& strClassName = m_pKernelModule->GetPropertyString( self, NFrame::NPC::ClassName());
const std::string& strSeedID = m_pKernelModule->GetPropertyString( self, NFrame::NPC::SeedID());
const std::string& strConfigID = m_pKernelModule->GetPropertyString( self, NFrame::NPC::ConfigID());
int nSceneID = m_pKernelModule->GetPropertyInt( self, NFrame::NPC::SceneID());
int nGroupID = m_pKernelModule->GetPropertyInt( self, NFrame::NPC::GroupID());
//m_pSceneProcessModule->ClearAll( nSceneID, nGroupID, strSeendID );
float fSeedX = m_pKernelModule->GetPropertyFloat( self, NFrame::NPC::X());
float fSeedY = m_pKernelModule->GetPropertyFloat( self, NFrame::NPC::Y());
float fSeedZ = m_pKernelModule->GetPropertyFloat( self, NFrame::NPC::Z());
m_pKernelModule->DestroyObject( self );
NFCDataList arg;
arg << NFrame::NPC::X() << fSeedX;
arg << NFrame::NPC::Y() << fSeedY;
arg << NFrame::NPC::Z() << fSeedZ;
arg << NFrame::NPC::SeedID() << strSeedID;
m_pKernelModule->CreateObject( NFGUID(), nSceneID, nGroupID, strClassName, strConfigID, arg );
return 0;
}
int NFCNPCRefreshModule::OnObjectBeKilled( const NFGUID& self, const NFEventDefine nEventID, const NFIDataList& var )
{
if ( var.GetCount() == 1 && var.Type( 0 ) == TDATA_OBJECT )
{
NFGUID identKiller = var.Object( 0 );
if ( m_pKernelModule->GetObject( identKiller ) )
{
const int nExp = m_pKernelModule->GetPropertyInt( self, NFrame::Player::EXP() );
m_pLevelModule->AddExp( identKiller, nExp);
m_pLogModule->LogNormal(NFILogModule::NLL_INFO_NORMAL, identKiller, "Add Exp for kill monster", nExp);
}
else
{
m_pLogModule->LogObject(NFILogModule::NLL_ERROR_NORMAL, identKiller, "There is no object", __FUNCTION__, __LINE__);
}
}
return 0;
}<|endoftext|> |
<commit_before>#include <OpenSim/OpenSim.h>
using namespace OpenSim;
using namespace SimTK;
class ComplexResponse : public ModelComponent {
OpenSim_DECLARE_CONCRETE_OBJECT(ComplexResponse, ModelComponent);
public:
OpenSim_DECLARE_PROPERTY(strength, double, "per-coord param.");
ComplexResponse() {
constructInfrastructure();
constructProperty_strength(3.0);
}
double getTerm1(const State& s) const {
if (!isCacheVariableValid(s, "term_1")) {
const auto& coord = getConnectee<Coordinate>("coord");
const auto value = coord.getValue(s);
setCacheVariableValue(s, "term_1", get_strength() * value);
}
return getCacheVariableValue<double>(s, "term_1");
}
double getTerm2(const State& s) const {
if (!isCacheVariableValid(s, "term_2")) {
const auto& coord = getConnectee<Coordinate>("coord");
const auto speed = coord.getSpeedValue(s);
setCacheVariableValue(s, "term_2", 2.0 * speed);
}
return getCacheVariableValue<double>(s, "term_2");
}
double getTotal(const State& s) const {
if (!isCacheVariableValid(s, "sum")) {
const auto& coord = getConnectee<Coordinate>("coord");
const auto speed = coord.getSpeedValue(s);
setCacheVariableValue(s, "sum", getTerm1(s) + getTerm2(s));
}
return getCacheVariableValue<double>(s, "sum");
}
private:
void constructConnectors() override {
constructConnector<Coordinate>("coord");
}
void constructOutputs() override {
constructOutput<double>("term_1",
&ComplexResponse::getTerm1, SimTK::Stage::Position);
constructOutput<double>("term_2",
&ComplexResponse::getTerm2, SimTK::Stage::Velocity);
constructOutput<double>("sum", &ComplexResponse::getTotal,
SimTK::Stage::Velocity);
}
void extendAddToSystem(MultibodySystem& system) const override {
Super::extendAddToSystem(system);
addCacheVariable<double>("term_1",
0.0, SimTK::Stage::Velocity);
addCacheVariable<double>("term_2",
0.0, SimTK::Stage::Velocity);
addCacheVariable<double>("sum",
0.0, SimTK::Stage::Velocity);
}
};
class AggregateResponse : public ModelComponent {
OpenSim_DECLARE_CONCRETE_OBJECT(AggregateResponse, ModelComponent);
public:
AggregateResponse() { constructInfrastructure(); }
// TODO want to use list property, but that makes clones and inputs/outputs
// don't get copied yet.
// OpenSim_DECLARE_LIST_PROPERTY(responses, ComplexResponse,
// "for individual coordinates.");
// Temporary solution:
std::vector<std::shared_ptr<ComplexResponse>> responses;
// TODO propagate this scaling_factor to the ComplexResponses using
// Component::getParent.
OpenSim_DECLARE_PROPERTY(scaling_factor, double, "Affects each coord.");
double getTotalSum(const State& s) const {
const double basalRate = 1.0;
double totalSum = 1.0;
for (const auto& response : responses) {
totalSum += response->getOutputValue<double>(s, "sum");
}
return totalSum;
}
double getTotalTerm1(const State& s) const {
double totalTerm1=0;
for (const auto& response : responses) {
totalTerm1 += response->getOutputValue<double>(s, "term_1");
}
return totalTerm1;
}
double getTotalTerm2(const State& s) const {
double totalTerm2=0;
for (const auto& response : responses) {
totalTerm2 += response->getOutputValue<double>(s, "term_2");
}
return totalTerm2;
}
private:
void extendFinalizeFromProperties() {
Super::extendFinalizeFromProperties();
for (auto& response : responses) {
markAsSubcomponent(response.get());
}
}
void constructOutputs() override {
constructOutput<double>("total_sum",
&AggregateResponse::getTotalSum, SimTK::Stage::Position);
constructOutput<double>("total_term_1",
&AggregateResponse::getTotalTerm1, SimTK::Stage::Velocity);
constructOutput<double>("total_term_2",
&AggregateResponse::getTotalTerm2, SimTK::Stage::Velocity);
}
};
template <typename T>
class ConsoleReporter : public ModelComponent {
OpenSim_DECLARE_CONCRETE_OBJECT(ConsoleReporter, Component);
public:
ConsoleReporter() {
constructInfrastructure();
}
private:
void constructInputs() override {
constructInput<T>("input1", SimTK::Stage::Acceleration);
// constructInput<T>("input2", SimTK::Stage::Acceleration);
constructInput<T>("input3", SimTK::Stage::Acceleration);
// multi input: constructMultiInput<T>("input", SimTK::Stage::Acceleration);
}
void extendRealizeReport(const State& state) const override {
// multi input: loop through multi-inputs.
std::cout << std::setw(10) << state.getTime() << ": " <<
getInputValue<T>(state, "input1") << " " <<
// getInputValue<T>(state, "input2") << " " <<
getInputValue<T>(state, "input3") << std::endl;
}
};
void integrate(const System& system, Integrator& integrator,
const State& initialState,
Real finalTime) {
TimeStepper ts(system, integrator);
ts.initialize(initialState);
ts.setReportAllSignificantStates(true);
integrator.setReturnEveryInternalStep(true);
while (ts.getState().getTime() < finalTime) {
ts.stepTo(finalTime);
system.realize(ts.getState(), SimTK::Stage::Report);
}
}
void testComplexResponse() {
Model model;
auto b1 = new OpenSim::Body("b1", 1, Vec3(0), Inertia(0));
auto b2 = new OpenSim::Body("b2", 1, Vec3(0), Inertia(0));
auto b3 = new OpenSim::Body("b3", 1, Vec3(0), Inertia(0));
auto j1 = new PinJoint("j1", model.getGround(), Vec3(0), Vec3(0),
*b1, Vec3(0, 1, 0), Vec3(0));
auto j2 = new PinJoint("j2", *b1, Vec3(0), Vec3(0),
*b2, Vec3(0, 1, 0), Vec3(0));
auto j3 = new PinJoint("j3", *b2, Vec3(0), Vec3(0),
*b3, Vec3(0, 1, 0), Vec3(0));
auto aggregate = new AggregateResponse();
aggregate->setName("aggregate_response");
aggregate->responses.push_back(
std::shared_ptr<ComplexResponse>(new ComplexResponse()));
aggregate->responses[0]->setName("complex_response_j1");
aggregate->responses[0]->updConnector<Coordinate>("coord")
.set_connectee_name("j1_coord_0");
aggregate->responses.push_back(
std::shared_ptr<ComplexResponse>(new ComplexResponse()));
aggregate->responses[1]->setName("complex_response_j2");
aggregate->responses[1]->updConnector<Coordinate>("coord")
.set_connectee_name("j2_coord_0");
auto reporter = new ConsoleReporter<double>();
reporter->setName("reporter");
reporter->getInput("input1").connect(aggregate->responses[0]->getOutput("sum"));
//reporter->getInput("input2").connect(aggregate->responses[1]->getOutput("sum"));
reporter->getInput("input3").connect(aggregate->getOutput("total_sum"));
// TODO connect by path: reporter->getInput("input").connect("/complex_response/sum");
// multi input: reporter->getMultiInput("input").append_connect(cr->getOutput("sum"));
model.addBody(b1);
model.addBody(b2);
model.addBody(b3);
model.addJoint(j1);
model.addJoint(j2);
model.addJoint(j3);
model.addModelComponent(aggregate);
model.addModelComponent(reporter);
State& state = model.initSystem();
model.updCoordinateSet().get("j1_coord_0").setValue(state, 0.5 * Pi);
RungeKuttaMersonIntegrator integrator(model.getSystem());
integrate(model.getSystem(), integrator, state, 1);
}
int main() {
SimTK_START_TEST("futureMuscleMetabolicsResponse");
SimTK_SUBTEST(testComplexResponse);
SimTK_END_TEST();
}
<commit_msg>MuscleMetabolicsResponse sandbox works again.<commit_after>#include <OpenSim/OpenSim.h>
using namespace OpenSim;
using namespace SimTK;
class ComplexResponse : public ModelComponent {
OpenSim_DECLARE_CONCRETE_OBJECT(ComplexResponse, ModelComponent);
public:
OpenSim_DECLARE_PROPERTY(strength, double, "per-coord param.");
ComplexResponse() {
constructInfrastructure();
}
double getTerm1(const State& s) const {
if (!isCacheVariableValid(s, "term_1")) {
const auto& coord = getConnectee<Coordinate>("coord");
const auto value = coord.getValue(s);
setCacheVariableValue(s, "term_1", get_strength() * value);
}
return getCacheVariableValue<double>(s, "term_1");
}
double getTerm2(const State& s) const {
if (!isCacheVariableValid(s, "term_2")) {
const auto& coord = getConnectee<Coordinate>("coord");
const auto speed = coord.getSpeedValue(s);
setCacheVariableValue(s, "term_2", 2.0 * speed);
}
return getCacheVariableValue<double>(s, "term_2");
}
double getSum(const State& s) const {
if (!isCacheVariableValid(s, "sum")) {
setCacheVariableValue(s, "sum", getTerm1(s) + getTerm2(s));
}
return getCacheVariableValue<double>(s, "sum");
}
private:
void constructProperties() override {
constructProperty_strength(3.0);
}
void constructConnectors() override {
constructConnector<Coordinate>("coord");
}
void constructOutputs() override {
constructOutput<double>("term_1",
&ComplexResponse::getTerm1, SimTK::Stage::Position);
constructOutput<double>("term_2",
&ComplexResponse::getTerm2, SimTK::Stage::Velocity);
constructOutput<double>("sum", &ComplexResponse::getSum,
SimTK::Stage::Velocity);
}
void extendAddToSystem(MultibodySystem& system) const override {
Super::extendAddToSystem(system);
addCacheVariable<double>("term_1",
0.0, SimTK::Stage::Velocity);
addCacheVariable<double>("term_2",
0.0, SimTK::Stage::Velocity);
addCacheVariable<double>("sum",
0.0, SimTK::Stage::Velocity);
}
};
class AggregateResponse : public ModelComponent {
OpenSim_DECLARE_CONCRETE_OBJECT(AggregateResponse, ModelComponent);
public:
AggregateResponse() { constructInfrastructure(); }
/* TODO would prefer to use this, but waiting until the function within
outputs is copied correctly.
*/
OpenSim_DECLARE_LIST_PROPERTY(responses, ComplexResponse,
"for individual coordinates.");
void adopt(ComplexResponse* resp) {
updProperty_responses().adoptAndAppendValue(resp);
finalizeFromProperties();
}
// TODO propagate this scaling_factor to the ComplexResponses using
// Component::getParent.
OpenSim_DECLARE_PROPERTY(scaling_factor, double, "Affects each coord.");
double getTotalSum(const State& s) const {
const double basalRate(1.0);
double totalSum = basalRate;
for (int ir = 0; ir < getProperty_responses().size(); ++ir) {
const auto& response = get_responses(ir);
totalSum += response.getOutputValue<double>(s, "sum");
}
return totalSum;
}
double getTotalTerm1(const State& s) const {
double totalTerm1=0;
for (int ir = 0; ir < getProperty_responses().size(); ++ir) {
const auto& response = get_responses(ir);
totalTerm1 += response.getOutputValue<double>(s, "term_1");
}
return totalTerm1;
}
double getTotalTerm2(const State& s) const {
double totalTerm2=0;
for (int ir = 0; ir < getProperty_responses().size(); ++ir) {
const auto& response = get_responses(ir);
totalTerm2 += response.getOutputValue<double>(s, "term_2");
}
return totalTerm2;
}
/*
ComplexResponse cresponse1 { constructSubcomponent<ComplexResponse>("complex_response_j1"); }
*/
private:
/*void extendFinalizeFromProperties() {
Super::extendFinalizeFromProperties();
for (auto& response : responses) {
markAsSubcomponent(response.get());
}
}
*/
void constructProperties() override {
constructProperty_responses();
constructProperty_scaling_factor(1.0);
}
void constructOutputs() override {
constructOutput<double>("total_sum",
&AggregateResponse::getTotalSum, SimTK::Stage::Position);
constructOutput<double>("total_term_1",
&AggregateResponse::getTotalTerm1, SimTK::Stage::Velocity);
constructOutput<double>("total_term_2",
&AggregateResponse::getTotalTerm2, SimTK::Stage::Velocity);
}
};
template <typename T>
class ConsoleReporter : public ModelComponent {
OpenSim_DECLARE_CONCRETE_OBJECT(ConsoleReporter, Component);
public:
ConsoleReporter() {
constructInfrastructure();
}
private:
void constructProperties() override {}
void constructInputs() override {
constructInput<T>("input1", SimTK::Stage::Acceleration);
// constructInput<T>("input2", SimTK::Stage::Acceleration);
constructInput<T>("input3", SimTK::Stage::Acceleration);
// multi input: constructMultiInput<T>("input", SimTK::Stage::Acceleration);
}
void extendRealizeReport(const State& state) const override {
// multi input: loop through multi-inputs.
// Output::getNumberOfSignificantDigits().
std::cout << std::setw(10) << state.getTime() << ": " <<
getInputValue<T>(state, "input1") << " " <<
// getInputValue<T>(state, "input2") << " " <<
getInputValue<T>(state, "input3") << std::endl;
}
};
void integrate(const System& system, Integrator& integrator,
const State& initialState,
Real finalTime) {
TimeStepper ts(system, integrator);
ts.initialize(initialState);
ts.setReportAllSignificantStates(true);
integrator.setReturnEveryInternalStep(true);
while (ts.getState().getTime() < finalTime) {
ts.stepTo(finalTime);
system.realize(ts.getState(), SimTK::Stage::Report);
}
}
void testComplexResponse() {
Model model;
auto b1 = new OpenSim::Body("b1", 1, Vec3(0), Inertia(0));
auto b2 = new OpenSim::Body("b2", 1, Vec3(0), Inertia(0));
auto b3 = new OpenSim::Body("b3", 1, Vec3(0), Inertia(0));
auto j1 = new PinJoint("j1", model.getGround(), Vec3(0), Vec3(0),
*b1, Vec3(0, 1, 0), Vec3(0));
auto j2 = new PinJoint("j2", *b1, Vec3(0), Vec3(0),
*b2, Vec3(0, 1, 0), Vec3(0));
auto j3 = new PinJoint("j3", *b2, Vec3(0), Vec3(0),
*b3, Vec3(0, 1, 0), Vec3(0));
auto aggregate = new AggregateResponse();
aggregate->setName("aggregate_response");
// TODO must fix copying of an output's function first.
auto* complexResponse1 = new ComplexResponse();
complexResponse1->setName("complex_response_j1");
complexResponse1->updConnector<Coordinate>("coord").set_connectee_name("j1_coord_0");
aggregate->adopt(complexResponse1);
auto* complexResponse2 = new ComplexResponse();
complexResponse2->setName("complex_response_j2");
complexResponse2->updConnector<Coordinate>("coord").set_connectee_name("j2_coord_0");
aggregate->adopt(complexResponse2);
auto reporter = new ConsoleReporter<double>();
reporter->setName("reporter");
reporter->getInput("input1").connect(aggregate->get_responses(0).getOutput("sum"));
//reporter->getInput("input2").connect(aggregate->responses[1]->getOutput("sum"));
reporter->getInput("input3").connect(aggregate->getOutput("total_sum"));
// TODO connect by path: reporter->getInput("input").connect("/complex_response/sum");
// multi input: reporter->getMultiInput("input").append_connect(cr->getOutput("sum"));
model.addBody(b1);
model.addBody(b2);
model.addBody(b3);
model.addJoint(j1);
model.addJoint(j2);
model.addJoint(j3);
model.addModelComponent(aggregate);
model.addModelComponent(reporter);
State& state = model.initSystem();
model.updCoordinateSet().get("j1_coord_0").setValue(state, 0.5 * Pi);
RungeKuttaMersonIntegrator integrator(model.getSystem());
integrate(model.getSystem(), integrator, state, 1);
}
int main() {
// TODO SimTK_START_TEST("futureMuscleMetabolicsResponse");
SimTK_SUBTEST(testComplexResponse);
//SimTK_END_TEST();
}
<|endoftext|> |
<commit_before><commit_msg>Adding the task<commit_after><|endoftext|> |
<commit_before>// The MIT License (MIT)
// Copyright (c) 2016, Microsoft
// 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 <algorithm>
#include <iostream> // TODO: Remove this temporary include.
#include <limits> // NaN.
#include <math.h>
#include "BitFunnel/Index/Factories.h"
#include "BitFunnel/Term.h"
#include "TermTreatments.h"
namespace BitFunnel
{
//*************************************************************************
//
// Factory methods.
//
//*************************************************************************
std::unique_ptr<ITermTreatment> Factories::CreateTreatmentPrivateRank0()
{
return std::unique_ptr<ITermTreatment>(new TreatmentPrivateRank0());
}
std::unique_ptr<ITermTreatment>
Factories::CreateTreatmentPrivateSharedRank0(double density,
double snr)
{
return
std::unique_ptr<ITermTreatment>(
new TreatmentPrivateSharedRank0(density, snr));
}
std::unique_ptr<ITermTreatment>
Factories::CreateTreatmentPrivateSharedRank0And3(double density,
double snr)
{
return
std::unique_ptr<ITermTreatment>(
new TreatmentPrivateSharedRank0And3(density, snr));
}
std::unique_ptr<ITermTreatment>
Factories::CreateTreatmentPrivateSharedRank0ToN(double density,
double snr)
{
return
std::unique_ptr<ITermTreatment>(
new TreatmentPrivateSharedRank0ToN(density, snr));
}
std::unique_ptr<ITermTreatment>
Factories::CreateTreatmentExperimental(double density,
double snr)
{
return
std::unique_ptr<ITermTreatment>(
new TreatmentExperimental(density, snr));
}
//*************************************************************************
//
// TreatmentPrivateRank0
//
// All terms get the same treatment - a single, private, rank 0 row.
//
//*************************************************************************
TreatmentPrivateRank0::TreatmentPrivateRank0()
{
// Same configuration for all terms - one private rank 0 row.
m_configuration.push_front(RowConfiguration::Entry(0, 1, true));
//std::cout << "Single configuration: ";
//m_configuration.Write(std::cout);
//std::cout << std::endl;
}
RowConfiguration TreatmentPrivateRank0::GetTreatment(Term /*term*/) const
{
return m_configuration;
}
//*************************************************************************
//
// TreatmentPrivateSharedRank0
//
// Terms get one or more rank 0 rows that could be private or shared,
// depending on term frequency.
//
//*************************************************************************
TreatmentPrivateSharedRank0::TreatmentPrivateSharedRank0(double density, double snr)
{
// Fill up vector of RowConfigurations. GetTreatment() will use the
// IdfSum() value of the Term as an index into this vector.
for (Term::IdfX10 idf = 0; idf <= Term::c_maxIdfX10Value; ++idf)
{
RowConfiguration configuration;
double frequency = Term::IdfX10ToFrequency(idf);
if (frequency >= density)
{
// This term is so common that it must be assigned a private row.
configuration.push_front(RowConfiguration::Entry(0, 1, true));
}
else
{
int k = Term::ComputeRowCount(frequency, density, snr);
configuration.push_front(RowConfiguration::Entry(0, k, false));
}
m_configurations.push_back(configuration);
//std::cout << idf / 10.0 << ": ";
//m_configurations.back().Write(std::cout);
//std::cout << std::endl;
}
}
RowConfiguration TreatmentPrivateSharedRank0::GetTreatment(Term term) const
{
// DESIGN NOTE: we can't c_maxIdfX10Value directly to min because min
// takes a reference and the compiler has already turned it into a
// constant, which we can't take a reference to.
auto local = Term::c_maxIdfX10Value;
Term::IdfX10 idf = std::min(term.GetIdfSum(), local);
return m_configurations[idf];
}
//*************************************************************************
//
// TreatmentPrivateSharedRank0And3
//
// Terms get one or more rank 0 and rank 3 rows that could be private or
// shared, depending on term frequency.
//
//*************************************************************************
TreatmentPrivateSharedRank0And3::TreatmentPrivateSharedRank0And3(double density, double snr)
{
// Fill up vector of RowConfigurations. GetTreatment() will use the
// IdfSum() value of the Term as an index into this vector.
for (Term::IdfX10 idf = 0; idf <= Term::c_maxIdfX10Value; ++idf)
{
RowConfiguration configuration;
double frequency = Term::IdfX10ToFrequency(idf);
if (frequency > density)
{
// This term is so common that it must be assigned a private row.
configuration.push_front(RowConfiguration::Entry(0, 1, true));
}
else
{
// Determine the number of rows, k, required to reach the
// desired signal to noise ratio, snr, given a certain bit
// density.
// TODO: consider checking for overflow?
int k = Term::ComputeRowCount(frequency, density, snr);
configuration.push_front(RowConfiguration::Entry(0, 2, false));
if (k > 2)
{
Rank rank = 3;
double frequencyAtRank = Term::FrequencyAtRank(frequency, rank);
if (frequencyAtRank >= density)
{
configuration.push_front(RowConfiguration::Entry(rank, 1, true));
}
else
{
configuration.push_front(RowConfiguration::Entry(rank, k - 2, false));
}
}
}
m_configurations.push_back(configuration);
//std::cout << idf / 10.0 << ": ";
//m_configurations.back().Write(std::cout);
//std::cout << std::endl;
}
}
RowConfiguration TreatmentPrivateSharedRank0And3::GetTreatment(Term term) const
{
// DESIGN NOTE: we can't c_maxIdfX10Value directly to min because min
// takes a reference and the compiler has already turned it into a
// constant, which we can't take a reference to.
auto local = Term::c_maxIdfX10Value;
Term::IdfX10 idf = std::min(term.GetIdfSum(), local);
return m_configurations[idf];
}
//*************************************************************************
//
// TreatmentPrivateSharedRank0ToN
//
// Two rank 0 rows followed by rows of increasing rank until the bit density
// is > some threshold. Due to limitatons in other BitFunnel code, we also
// top out at rank 6.
//
//*************************************************************************
TreatmentPrivateSharedRank0ToN::TreatmentPrivateSharedRank0ToN(double density, double snr)
{
// TODO: what should maxDensity be? Note that this is different from the
// density liimt that's passed in.
const double maxDensity = 0.15;
// Fill up vector of RowConfigurations. GetTreatment() will use the
// IdfSum() value of the Term as an index into this vector.
//
// TODO: we should make sure we get "enough" rows if we end up with a
// high rank private row.
for (Term::IdfX10 idf = 0; idf <= Term::c_maxIdfX10Value; ++idf)
{
RowConfiguration configuration;
double frequency = Term::IdfX10ToFrequency(idf);
if (frequency > density)
{
// This term is so common that it must be assigned a private row.
configuration.push_front(RowConfiguration::Entry(0, 1, true));
}
else
{
// TODO: fix other limitations so this can be higher than 6?
const Rank maxRank = (std::min)(Term::ComputeMaxRank(frequency, maxDensity), static_cast<Rank>(6u));
int numRows = Term::ComputeRowCount(frequency, density, snr);
configuration.push_front(RowConfiguration::Entry(0, 2, false));
numRows -= 2;
Rank rank = 1;
while (rank < maxRank)
{
double frequencyAtRank = Term::FrequencyAtRank(frequency, rank);
if (frequencyAtRank >= density)
{
configuration.push_front(RowConfiguration::Entry(rank,
1,
true));
}
else
{
configuration.push_front(RowConfiguration::Entry(rank,
1,
false));
}
++rank;
--numRows;
}
double frequencyAtRank = Term::FrequencyAtRank(frequency, rank);
if (frequencyAtRank >= density)
{
configuration.push_front(RowConfiguration::Entry(rank,
1,
true));
}
else
{
if (numRows > 1)
{
configuration.push_front(RowConfiguration::Entry(rank,
numRows,
false));
}
else
{
configuration.push_front(RowConfiguration::Entry(rank,
1,
false));
}
}
}
m_configurations.push_back(configuration);
//std::cout << idf / 10.0 << ": ";
//m_configurations.back().Write(std::cout);
//std::cout << std::endl;
}
}
RowConfiguration TreatmentPrivateSharedRank0ToN::GetTreatment(Term term) const
{
// DESIGN NOTE: we can't c_maxIdfX10Value directly to min because min
// takes a reference and the compiler has already turned it into a
// constant, which we can't take a reference to.
auto local = Term::c_maxIdfX10Value;
Term::IdfX10 idf = std::min(term.GetIdfSum(), local);
return m_configurations[idf];
}
// Try to solve for the optimal TermTreatment. This is basically a recursive
// brute force solution that, for any rank, either does a RankDown or
// inserts another row at currentRank. Note that the cost function here
// assumes that the machine has qword-sized memory accesses and that needs
// to be updated. Furthermore, the code is basically untested and may have
// logical errors.
// TODO: need to ensure enough rows that we don't have too much noise. As
// is, it would be legal to have a bunch of rank 6 rows and 2 rank 0 rows,
// which probably isn't sufficient.
std::pair<double, std::vector<int>> Temp(double frequency, double density, double snr, int currentRank, std::vector<int> rows, int maxRowsPerRank)
{
if (currentRank == 0)
{
rows[0] += 2;
// TODO: change cost calculation to account for cacheline size.
double cost = 0;
int lastRank = -1;
double residualNoise = std::numeric_limits<double>::quiet_NaN();
double lastFrequencyAtRank = std::numeric_limits<double>::quiet_NaN();
double weight = 1.0; // probability that we don't have all 0s in a qword.
for (int i = static_cast<int>(rows.size()) - 1; i >= 0; --i)
{
if (rows[i] != 0)
{
double frequencyAtRank = Term::FrequencyAtRank(frequency, i);
double noiseAtRank = density - frequencyAtRank;
// double intersectedNoiseAtRank = pow(noiseAtRank, rows[i]);
double fullRowCost = 1.0 / (1 << i);
for (int j = 0; j < rows[i]; ++j)
{
if (j == 0)
{
if (lastRank != -1)
{
int rankDown = lastRank - i;
double rankDownBits = static_cast<double>(1 << rankDown);
residualNoise =
(lastFrequencyAtRank * (rankDownBits - 1) / rankDownBits * noiseAtRank)
+
(residualNoise * noiseAtRank);
}
else
{
residualNoise = noiseAtRank;
}
}
else
{
residualNoise *= noiseAtRank;
}
cost += weight * fullRowCost;
double densityAtRank = residualNoise + frequencyAtRank;
weight = 1 - pow(1 - densityAtRank, 64);
}
lastFrequencyAtRank = frequencyAtRank;
lastRank = i;
}
}
// TODO: if we wanted to enforce a snr bound, we could set the cost
// of anything that doesn't hit our snr to infinity. For something
// more nuance, we could add something to the cost function based on
// how much we missed our target by. That seems like a better idea.
return std::make_pair(cost, rows);
}
double frequencyAtRank = Term::FrequencyAtRank(frequency, currentRank);
if (frequencyAtRank > density)
{
// Add private row and rankDown.
++rows[currentRank];
return Temp(frequency, density, snr, currentRank - 1, rows, maxRowsPerRank);
}
else if (rows[currentRank] >= maxRowsPerRank)
{
// rankDown
return Temp(frequency, density, snr, currentRank - 1, rows, maxRowsPerRank);
}
else
{
auto rankDown = Temp(frequency, density, snr, currentRank - 1, rows, maxRowsPerRank);
++rows[currentRank];
auto newRow = Temp(frequency, density, snr, currentRank, rows, maxRowsPerRank);
return newRow.first < rankDown.first ? newRow : rankDown;
}
}
//*************************************************************************
//
// TreatmentExperimental
//
// Placeholder of experimental treatment.
//
//*************************************************************************
TreatmentExperimental::TreatmentExperimental(double density, double snr)
{
double maxDensity = 0.2;
const int c_maxRowsPerRank = 6;
std::vector<int> rowInputs(c_maxRankValue, 0);
for (Term::IdfX10 idf = 0; idf <= Term::c_maxIdfX10Value; ++idf)
{
double frequency = Term::IdfX10ToFrequency(idf);
const Rank maxRank = (std::min)(Term::ComputeMaxRank(frequency, maxDensity), static_cast<Rank>(c_maxRankValue));
RowConfiguration configuration;
auto costRows = Temp(frequency, density, snr, maxRank, rowInputs, c_maxRowsPerRank);
auto rows = costRows.second;
for (Rank rank = 0; rank < rows.size(); ++rank)
{
if (rows[rank] > 0)
{
double frequencyAtRank = Term::FrequencyAtRank(frequency, rank);
if (frequencyAtRank > density)
{
configuration.push_front(RowConfiguration::Entry(rank, 1, true));
// TODO: assert that our solver doesn't give us multiple
// private rows.
}
else
{
configuration.push_front(RowConfiguration::Entry(rank, rows[rank], false));
}
}
}
m_configurations.push_back(configuration);
}
}
RowConfiguration TreatmentExperimental::GetTreatment(Term term) const
{
// DESIGN NOTE: we can't c_maxIdfX10Value directly to min because min
// takes a reference and the compiler has already turned it into a
// constant, which we can't take a reference to.
auto local = Term::c_maxIdfX10Value;
Term::IdfX10 idf = std::min(term.GetIdfSum(), local);
return m_configurations[idf];
}
}
<commit_msg>Fix another VC++ warning.<commit_after>// The MIT License (MIT)
// Copyright (c) 2016, Microsoft
// 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 <algorithm>
#include <iostream> // TODO: Remove this temporary include.
#include <limits> // NaN.
#include <math.h>
#include "BitFunnel/Index/Factories.h"
#include "BitFunnel/Term.h"
#include "TermTreatments.h"
namespace BitFunnel
{
//*************************************************************************
//
// Factory methods.
//
//*************************************************************************
std::unique_ptr<ITermTreatment> Factories::CreateTreatmentPrivateRank0()
{
return std::unique_ptr<ITermTreatment>(new TreatmentPrivateRank0());
}
std::unique_ptr<ITermTreatment>
Factories::CreateTreatmentPrivateSharedRank0(double density,
double snr)
{
return
std::unique_ptr<ITermTreatment>(
new TreatmentPrivateSharedRank0(density, snr));
}
std::unique_ptr<ITermTreatment>
Factories::CreateTreatmentPrivateSharedRank0And3(double density,
double snr)
{
return
std::unique_ptr<ITermTreatment>(
new TreatmentPrivateSharedRank0And3(density, snr));
}
std::unique_ptr<ITermTreatment>
Factories::CreateTreatmentPrivateSharedRank0ToN(double density,
double snr)
{
return
std::unique_ptr<ITermTreatment>(
new TreatmentPrivateSharedRank0ToN(density, snr));
}
std::unique_ptr<ITermTreatment>
Factories::CreateTreatmentExperimental(double density,
double snr)
{
return
std::unique_ptr<ITermTreatment>(
new TreatmentExperimental(density, snr));
}
//*************************************************************************
//
// TreatmentPrivateRank0
//
// All terms get the same treatment - a single, private, rank 0 row.
//
//*************************************************************************
TreatmentPrivateRank0::TreatmentPrivateRank0()
{
// Same configuration for all terms - one private rank 0 row.
m_configuration.push_front(RowConfiguration::Entry(0, 1, true));
//std::cout << "Single configuration: ";
//m_configuration.Write(std::cout);
//std::cout << std::endl;
}
RowConfiguration TreatmentPrivateRank0::GetTreatment(Term /*term*/) const
{
return m_configuration;
}
//*************************************************************************
//
// TreatmentPrivateSharedRank0
//
// Terms get one or more rank 0 rows that could be private or shared,
// depending on term frequency.
//
//*************************************************************************
TreatmentPrivateSharedRank0::TreatmentPrivateSharedRank0(double density, double snr)
{
// Fill up vector of RowConfigurations. GetTreatment() will use the
// IdfSum() value of the Term as an index into this vector.
for (Term::IdfX10 idf = 0; idf <= Term::c_maxIdfX10Value; ++idf)
{
RowConfiguration configuration;
double frequency = Term::IdfX10ToFrequency(idf);
if (frequency >= density)
{
// This term is so common that it must be assigned a private row.
configuration.push_front(RowConfiguration::Entry(0, 1, true));
}
else
{
int k = Term::ComputeRowCount(frequency, density, snr);
configuration.push_front(RowConfiguration::Entry(0, k, false));
}
m_configurations.push_back(configuration);
//std::cout << idf / 10.0 << ": ";
//m_configurations.back().Write(std::cout);
//std::cout << std::endl;
}
}
RowConfiguration TreatmentPrivateSharedRank0::GetTreatment(Term term) const
{
// DESIGN NOTE: we can't c_maxIdfX10Value directly to min because min
// takes a reference and the compiler has already turned it into a
// constant, which we can't take a reference to.
auto local = Term::c_maxIdfX10Value;
Term::IdfX10 idf = std::min(term.GetIdfSum(), local);
return m_configurations[idf];
}
//*************************************************************************
//
// TreatmentPrivateSharedRank0And3
//
// Terms get one or more rank 0 and rank 3 rows that could be private or
// shared, depending on term frequency.
//
//*************************************************************************
TreatmentPrivateSharedRank0And3::TreatmentPrivateSharedRank0And3(double density, double snr)
{
// Fill up vector of RowConfigurations. GetTreatment() will use the
// IdfSum() value of the Term as an index into this vector.
for (Term::IdfX10 idf = 0; idf <= Term::c_maxIdfX10Value; ++idf)
{
RowConfiguration configuration;
double frequency = Term::IdfX10ToFrequency(idf);
if (frequency > density)
{
// This term is so common that it must be assigned a private row.
configuration.push_front(RowConfiguration::Entry(0, 1, true));
}
else
{
// Determine the number of rows, k, required to reach the
// desired signal to noise ratio, snr, given a certain bit
// density.
// TODO: consider checking for overflow?
int k = Term::ComputeRowCount(frequency, density, snr);
configuration.push_front(RowConfiguration::Entry(0, 2, false));
if (k > 2)
{
Rank rank = 3;
double frequencyAtRank = Term::FrequencyAtRank(frequency, rank);
if (frequencyAtRank >= density)
{
configuration.push_front(RowConfiguration::Entry(rank, 1, true));
}
else
{
configuration.push_front(RowConfiguration::Entry(rank, k - 2, false));
}
}
}
m_configurations.push_back(configuration);
//std::cout << idf / 10.0 << ": ";
//m_configurations.back().Write(std::cout);
//std::cout << std::endl;
}
}
RowConfiguration TreatmentPrivateSharedRank0And3::GetTreatment(Term term) const
{
// DESIGN NOTE: we can't c_maxIdfX10Value directly to min because min
// takes a reference and the compiler has already turned it into a
// constant, which we can't take a reference to.
auto local = Term::c_maxIdfX10Value;
Term::IdfX10 idf = std::min(term.GetIdfSum(), local);
return m_configurations[idf];
}
//*************************************************************************
//
// TreatmentPrivateSharedRank0ToN
//
// Two rank 0 rows followed by rows of increasing rank until the bit density
// is > some threshold. Due to limitatons in other BitFunnel code, we also
// top out at rank 6.
//
//*************************************************************************
TreatmentPrivateSharedRank0ToN::TreatmentPrivateSharedRank0ToN(double density, double snr)
{
// TODO: what should maxDensity be? Note that this is different from the
// density liimt that's passed in.
const double maxDensity = 0.15;
// Fill up vector of RowConfigurations. GetTreatment() will use the
// IdfSum() value of the Term as an index into this vector.
//
// TODO: we should make sure we get "enough" rows if we end up with a
// high rank private row.
for (Term::IdfX10 idf = 0; idf <= Term::c_maxIdfX10Value; ++idf)
{
RowConfiguration configuration;
double frequency = Term::IdfX10ToFrequency(idf);
if (frequency > density)
{
// This term is so common that it must be assigned a private row.
configuration.push_front(RowConfiguration::Entry(0, 1, true));
}
else
{
// TODO: fix other limitations so this can be higher than 6?
const Rank maxRank = (std::min)(Term::ComputeMaxRank(frequency, maxDensity), static_cast<Rank>(6u));
int numRows = Term::ComputeRowCount(frequency, density, snr);
configuration.push_front(RowConfiguration::Entry(0, 2, false));
numRows -= 2;
Rank rank = 1;
while (rank < maxRank)
{
double frequencyAtRank = Term::FrequencyAtRank(frequency, rank);
if (frequencyAtRank >= density)
{
configuration.push_front(RowConfiguration::Entry(rank,
1,
true));
}
else
{
configuration.push_front(RowConfiguration::Entry(rank,
1,
false));
}
++rank;
--numRows;
}
double frequencyAtRank = Term::FrequencyAtRank(frequency, rank);
if (frequencyAtRank >= density)
{
configuration.push_front(RowConfiguration::Entry(rank,
1,
true));
}
else
{
if (numRows > 1)
{
configuration.push_front(RowConfiguration::Entry(rank,
numRows,
false));
}
else
{
configuration.push_front(RowConfiguration::Entry(rank,
1,
false));
}
}
}
m_configurations.push_back(configuration);
//std::cout << idf / 10.0 << ": ";
//m_configurations.back().Write(std::cout);
//std::cout << std::endl;
}
}
RowConfiguration TreatmentPrivateSharedRank0ToN::GetTreatment(Term term) const
{
// DESIGN NOTE: we can't c_maxIdfX10Value directly to min because min
// takes a reference and the compiler has already turned it into a
// constant, which we can't take a reference to.
auto local = Term::c_maxIdfX10Value;
Term::IdfX10 idf = std::min(term.GetIdfSum(), local);
return m_configurations[idf];
}
// Try to solve for the optimal TermTreatment. This is basically a recursive
// brute force solution that, for any rank, either does a RankDown or
// inserts another row at currentRank. Note that the cost function here
// assumes that the machine has qword-sized memory accesses and that needs
// to be updated. Furthermore, the code is basically untested and may have
// logical errors.
// TODO: need to ensure enough rows that we don't have too much noise. As
// is, it would be legal to have a bunch of rank 6 rows and 2 rank 0 rows,
// which probably isn't sufficient.
// TODO: converts rank to Rank type.
std::pair<double, std::vector<int>> Temp(double frequency, double density, double snr, int currentRank, std::vector<int> rows, int maxRowsPerRank)
{
if (currentRank == 0)
{
rows[0] += 2;
// TODO: change cost calculation to account for cacheline size.
double cost = 0;
int lastRank = -1;
double residualNoise = std::numeric_limits<double>::quiet_NaN();
double lastFrequencyAtRank = std::numeric_limits<double>::quiet_NaN();
double weight = 1.0; // probability that we don't have all 0s in a qword.
for (int i = static_cast<int>(rows.size()) - 1; i >= 0; --i)
{
if (rows[i] != 0)
{
double frequencyAtRank = Term::FrequencyAtRank(frequency, i);
double noiseAtRank = density - frequencyAtRank;
// double intersectedNoiseAtRank = pow(noiseAtRank, rows[i]);
double fullRowCost = 1.0 / (1 << i);
for (int j = 0; j < rows[i]; ++j)
{
if (j == 0)
{
if (lastRank != -1)
{
int rankDown = lastRank - i;
double rankDownBits = static_cast<double>(1 << rankDown);
residualNoise =
(lastFrequencyAtRank * (rankDownBits - 1) / rankDownBits * noiseAtRank)
+
(residualNoise * noiseAtRank);
}
else
{
residualNoise = noiseAtRank;
}
}
else
{
residualNoise *= noiseAtRank;
}
cost += weight * fullRowCost;
double densityAtRank = residualNoise + frequencyAtRank;
weight = 1 - pow(1 - densityAtRank, 64);
}
lastFrequencyAtRank = frequencyAtRank;
lastRank = i;
}
}
// TODO: if we wanted to enforce a snr bound, we could set the cost
// of anything that doesn't hit our snr to infinity. For something
// more nuance, we could add something to the cost function based on
// how much we missed our target by. That seems like a better idea.
return std::make_pair(cost, rows);
}
double frequencyAtRank = Term::FrequencyAtRank(frequency, currentRank);
if (frequencyAtRank > density)
{
// Add private row and rankDown.
++rows[currentRank];
return Temp(frequency, density, snr, currentRank - 1, rows, maxRowsPerRank);
}
else if (rows[currentRank] >= maxRowsPerRank)
{
// rankDown
return Temp(frequency, density, snr, currentRank - 1, rows, maxRowsPerRank);
}
else
{
auto rankDown = Temp(frequency, density, snr, currentRank - 1, rows, maxRowsPerRank);
++rows[currentRank];
auto newRow = Temp(frequency, density, snr, currentRank, rows, maxRowsPerRank);
return newRow.first < rankDown.first ? newRow : rankDown;
}
}
//*************************************************************************
//
// TreatmentExperimental
//
// Placeholder of experimental treatment.
//
//*************************************************************************
TreatmentExperimental::TreatmentExperimental(double density, double snr)
{
double maxDensity = 0.2;
const int c_maxRowsPerRank = 6;
std::vector<int> rowInputs(c_maxRankValue, 0);
for (Term::IdfX10 idf = 0; idf <= Term::c_maxIdfX10Value; ++idf)
{
double frequency = Term::IdfX10ToFrequency(idf);
const Rank maxRank = (std::min)(Term::ComputeMaxRank(frequency, maxDensity), static_cast<Rank>(c_maxRankValue));
RowConfiguration configuration;
auto costRows = Temp(frequency, density, snr, static_cast<int>(maxRank), rowInputs, c_maxRowsPerRank);
auto rows = costRows.second;
for (Rank rank = 0; rank < rows.size(); ++rank)
{
if (rows[rank] > 0)
{
double frequencyAtRank = Term::FrequencyAtRank(frequency, rank);
if (frequencyAtRank > density)
{
configuration.push_front(RowConfiguration::Entry(rank, 1, true));
// TODO: assert that our solver doesn't give us multiple
// private rows.
}
else
{
configuration.push_front(RowConfiguration::Entry(rank, rows[rank], false));
}
}
}
m_configurations.push_back(configuration);
}
}
RowConfiguration TreatmentExperimental::GetTreatment(Term term) const
{
// DESIGN NOTE: we can't c_maxIdfX10Value directly to min because min
// takes a reference and the compiler has already turned it into a
// constant, which we can't take a reference to.
auto local = Term::c_maxIdfX10Value;
Term::IdfX10 idf = std::min(term.GetIdfSum(), local);
return m_configurations[idf];
}
}
<|endoftext|> |
<commit_before>/*******************************************************************************
* ALMA - Atacama Large Millimiter Array
* (c) Associated Universities Inc., 2002 *
* (c) European Southern Observatory, 2002
* Copyright by ESO (in the framework of the ALMA collaboration)
* and Cosylab 2002, All rights reserved
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
*
*
* "@(#) $Id: contLogTestImpl.cpp,v 1.4 2007/11/30 13:01:16 eallaert Exp $"
*
* who when what
* -------- ---------- ----------------------------------------------
* eallaert 2007-11-05 initial version
*
*/
#include <contLogTestImpl.h>
#include <ACSErrTypeCommon.h>
#include <iostream>
ACE_RCSID(contLogTest, contLogTestImpl, "$Id: contLogTestImpl.cpp,v 1.4 2007/11/30 13:01:16 eallaert Exp $")
/* ----------------------------------------------------------------*/
TestLogLevelsComp::TestLogLevelsComp(
const ACE_CString &name,
maci::ContainerServices * containerServices) :
ACSComponentImpl(name, containerServices)
{
// ACS_TRACE is used for debugging purposes
ACS_TRACE("::TestLogLevelsComp::TestLogLevelsComp");
}
/* ----------------------------------------------------------------*/
TestLogLevelsComp::~TestLogLevelsComp()
{
// ACS_TRACE is used for debugging purposes
ACS_TRACE("::TestLogLevelsComp::~TestLogLevelsComp");
ACS_DEBUG_PARAM("::TestLogLevelsComp::~TestLogLevelsComp", "Destroying %s...", name());
}
/* --------------------- [ CORBA interface ] ----------------------*/
::contLogTest::LongSeq*
TestLogLevelsComp::getLevels ()
throw (CORBA::SystemException, ACSErrTypeCommon::CouldntPerformActionEx)
{
std::cout << "Hi there!" << std::endl;
::contLogTest::LongSeq_var level = new ::contLogTest::LongSeq(5);
level->length(5);
// need the equivalent of Java's logConfig.getMinLogLevel() etc. in C++
for (int i = 0; i <5 ; i++)
level[i] = static_cast< CORBA::Long >(i);
std::cout << "Done filling levels." << std::endl;
return level._retn();
}
void
TestLogLevelsComp::logDummyMessages (const ::contLogTest::LongSeq & levels)
{
for (CORBA::ULong t=0; t<levels.length(); t++){
ACE_Log_Priority p = LoggingProxy::m_LogEntryCast[levels[t]];
ACS_SHORT_LOG((p, "dummy log message for core level %d", levels[t]));
}
}
/* --------------- [ MACI DLL support functions ] -----------------*/
#include <maciACSComponentDefines.h>
MACI_DLL_SUPPORT_FUNCTIONS(TestLogLevelsComp)
/* ----------------------------------------------------------------*/
/*___oOo___*/
<commit_msg>Change the use of the structure from the use of the object LogLevelDefinition<commit_after>/*******************************************************************************
* ALMA - Atacama Large Millimiter Array
* (c) Associated Universities Inc., 2002 *
* (c) European Southern Observatory, 2002
* Copyright by ESO (in the framework of the ALMA collaboration)
* and Cosylab 2002, All rights reserved
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
*
*
* "@(#) $Id: contLogTestImpl.cpp,v 1.5 2007/12/11 09:34:17 cparedes Exp $"
*
* who when what
* -------- ---------- ----------------------------------------------
* eallaert 2007-11-05 initial version
*
*/
#include <contLogTestImpl.h>
#include <ACSErrTypeCommon.h>
#include <loggingLogLevelDefinition.h>
#include <iostream>
ACE_RCSID(contLogTest, contLogTestImpl, "$Id: contLogTestImpl.cpp,v 1.5 2007/12/11 09:34:17 cparedes Exp $")
/* ----------------------------------------------------------------*/
TestLogLevelsComp::TestLogLevelsComp(
const ACE_CString &name,
maci::ContainerServices * containerServices) :
ACSComponentImpl(name, containerServices)
{
// ACS_TRACE is used for debugging purposes
ACS_TRACE("::TestLogLevelsComp::TestLogLevelsComp");
}
/* ----------------------------------------------------------------*/
TestLogLevelsComp::~TestLogLevelsComp()
{
// ACS_TRACE is used for debugging purposes
ACS_TRACE("::TestLogLevelsComp::~TestLogLevelsComp");
ACS_DEBUG_PARAM("::TestLogLevelsComp::~TestLogLevelsComp", "Destroying %s...", name());
}
/* --------------------- [ CORBA interface ] ----------------------*/
::contLogTest::LongSeq*
TestLogLevelsComp::getLevels ()
throw (CORBA::SystemException, ACSErrTypeCommon::CouldntPerformActionEx)
{
std::cout << "Hi there!" << std::endl;
::contLogTest::LongSeq_var level = new ::contLogTest::LongSeq(5);
level->length(5);
// need the equivalent of Java's logConfig.getMinLogLevel() etc. in C++
for (int i = 0; i <5 ; i++)
level[i] = static_cast< CORBA::Long >(i);
std::cout << "Done filling levels." << std::endl;
return level._retn();
}
void
TestLogLevelsComp::logDummyMessages (const ::contLogTest::LongSeq & levels)
{
for (CORBA::ULong t=0; t<levels.length(); t++){
ACE_Log_Priority p = LogLevelDefinition::getACELogPriority(levels[t]);
ACS_SHORT_LOG((p, "dummy log message for core level %d", levels[t]));
}
}
/* --------------- [ MACI DLL support functions ] -----------------*/
#include <maciACSComponentDefines.h>
MACI_DLL_SUPPORT_FUNCTIONS(TestLogLevelsComp)
/* ----------------------------------------------------------------*/
/*___oOo___*/
<|endoftext|> |
<commit_before>/*
* CityRegionImplementation.cpp
*
* Created on: Feb 9, 2012
* Author: xyborn
*/
#include "CityRegion.h"
#include "events/CityUpdateEvent.h"
#include "server/zone/Zone.h"
#include "server/zone/objects/area/ActiveArea.h"
#include "server/chat/StringIdChatParameter.h"
#include "server/zone/objects/scene/SceneObject.h"
#include "server/zone/objects/creature/CreatureObject.h"
#include "server/zone/objects/structure/StructureObject.h"
#include "server/zone/objects/region/Region.h"
#include "server/zone/managers/stringid/StringIdManager.h"
#include "server/ServerCore.h"
#include "server/zone/managers/city/CityManager.h"
#include "server/zone/managers/planet/PlanetManager.h"
#include "server/zone/managers/planet/PlanetTravelPoint.h"
#include "server/zone/managers/structure/StructureManager.h"
#include "server/zone/objects/building/BuildingObject.h"
#include "server/zone/objects/player/PlayerObject.h"
void CityRegionImplementation::initializeTransientMembers() {
ManagedObjectImplementation::initializeTransientMembers();
}
void CityRegionImplementation::notifyLoadFromDatabase() {
ManagedObjectImplementation::notifyLoadFromDatabase();
if (cityRank == CityManager::CLIENT)
return;
//if (zone !=)
Zone* zone = getZone();
if (zone == NULL)
return;
zone->addCityRegionToUpdate(_this);
if (isRegistered())
zone->getPlanetManager()->addRegion(_this);
/*
int seconds = -1 * round(nextUpdateTime.miliDifference() / 1000.f);
if (seconds < 0) //If the update occurred in the past, force an immediate update.
seconds = 0;
rescheduleUpdateEvent(seconds);
*/
if (hasShuttle){
CreatureObject* shuttle = cast<CreatureObject*>( zone->getZoneServer()->getObject(shuttleID, false));
if (shuttle == NULL) {
hasShuttle = false;
shuttleID = 0;
return;
}
float x = shuttle->getWorldPositionX();
float y = shuttle->getWorldPositionY();
float z = shuttle->getWorldPositionZ();
Vector3 arrivalVector(x, y, z);
PlanetTravelPoint* planetTravelPoint = new PlanetTravelPoint(zone->getZoneName(), getRegionName(), arrivalVector, arrivalVector, shuttle);
zone->getPlanetManager()->addPlayerCityTravelPoint(planetTravelPoint);
if (shuttle != NULL)
zone->getPlanetManager()->scheduleShuttle(shuttle);
}
}
void CityRegionImplementation::initialize() {
zoningEnabled = true;
registered = false;
cityTreasury = 0;
cityRank = RANK_CLIENT; //Default to client city
cityHall = NULL;
mayorID = 0;
shuttleID = 0;
hasShuttle = false;
zone = NULL;
cityUpdateEvent = NULL;
zoningRights.setAllowOverwriteInsertPlan();
zoningRights.setNullValue(0);
limitedPlacementStructures.setNoDuplicateInsertPlan();
cityStructureInventory.put(uint8(1), SortedVector<ManagedReference<SceneObject*> >());
cityStructureInventory.put(uint8(2), SortedVector<ManagedReference<SceneObject*> >());
cityStructureInventory.put(uint8(3), SortedVector<ManagedReference<SceneObject*> >());
cityStructureInventory.put(uint8(4), SortedVector<ManagedReference<SceneObject*> >());
cityStructureInventory.get(0).setNoDuplicateInsertPlan();
cityStructureInventory.get(1).setNoDuplicateInsertPlan();
cityStructureInventory.get(2).setNoDuplicateInsertPlan();
cityStructureInventory.get(3).setNoDuplicateInsertPlan();
cityMissionTerminals.setNoDuplicateInsertPlan();
cityDecorations.setNoDuplicateInsertPlan();
citySkillTrainers.setNoDuplicateInsertPlan();
setLoggingName("CityRegion");
setLogging(true);
}
Region* CityRegionImplementation::addRegion(float x, float y, float radius, bool persistent) {
if (zone == NULL) {
return NULL;
}
String temp = "object/region_area.iff";
SceneObject* obj = zone->getZoneServer()->createObject(temp.hashCode(), persistent ? 1 : 0);
if (obj == NULL || !obj->isRegion()) {
return NULL;
}
ManagedReference<Region*> region = cast<Region*>(obj);
region->setCityRegion(_this);
region->setRadius(radius);
region->initializePosition(x, 0, y);
region->setObjectName(regionName);
if (isClientRegion())
region->setNoBuildArea(true);
zone->transferObject(region, -1, false);
regions.put(region);
return region;
}
void CityRegionImplementation::rescheduleUpdateEvent(uint32 seconds) {
if (cityRank == CityManager::CLIENT)
return;
if (cityUpdateEvent == NULL) {
cityUpdateEvent = new CityUpdateEvent(_this, ServerCore::getZoneServer());
} else if (cityUpdateEvent->isScheduled()) {
cityUpdateEvent->cancel();
}
cityUpdateEvent->schedule(seconds * 1000);
Core::getTaskManager()->getNextExecutionTime(cityUpdateEvent, nextUpdateTime);
}
int CityRegionImplementation::getTimeToUpdate() {
return round(nextUpdateTime.miliDifference() / -1000.f);
}
void CityRegionImplementation::notifyEnter(SceneObject* object) {
object->setCityRegion(_this);
if (isClientRegion())
return;
if (object->isCreatureObject()){
CreatureObject* creature = cast<CreatureObject*>(object);
StringIdChatParameter params("city/city", "city_enter_city"); //You have entered %TT (%TO).
params.setTT(getRegionName());
UnicodeString strRank = StringIdManager::instance()->getStringId(String("@city/city:rank" + String::valueOf(cityRank)).hashCode());
if (citySpecialization.isEmpty()) {
params.setTO(strRank);
}
else {
UnicodeString citySpec = StringIdManager::instance()->getStringId(citySpecialization.hashCode());
params.setTO(strRank + ", " + citySpec);
}
creature->sendSystemMessage(params);
}
if (object->isBuildingObject()){
BuildingObject* building = cast<BuildingObject*>(object);
CreatureObject* owner = building->getOwnerCreatureObject();
if (owner != NULL) {
PlayerObject* playerObject = owner->getPlayerObject();
if (playerObject != NULL && playerObject->getDeclaredResidence() == building) {
uint64 creatureID = owner->getObjectID();
if (!citizenList.contains(creatureID))
addCitizen(creatureID);
}
}
}
//Apply skillmods for specialization
}
void CityRegionImplementation::notifyExit(SceneObject* object) {
object->setCityRegion(NULL);
if (isClientRegion())
return;
if (object->isCreatureObject()){
CreatureObject* creature = cast<CreatureObject*>(object);
StringIdChatParameter params("city/city", "city_leave_city"); //You have left %TO.
params.setTO(getRegionName());
creature->sendSystemMessage(params);
//Remove skillmods for specialization
}
if (object->isBuildingObject()){
float x = object->getWorldPositionX();
float y = object->getWorldPositionY();
//StructureObject* structure = cast<StructureObject*>(object);
BuildingObject* building = cast<BuildingObject*>(object);
CreatureObject* owner = building->getOwnerCreatureObject();
if (owner != NULL) {
PlayerObject* playerObject = owner->getPlayerObject();
if (playerObject != NULL && playerObject->getDeclaredResidence() == building){
uint64 creatureID = owner->getObjectID();
if (citizenList.contains(creatureID))
removeCitizen(creatureID);
}
}
}
}
void CityRegionImplementation::setRegionName(const StringId& name) {
regionName = name;
}
Vector<ManagedReference<SceneObject*> >* CityRegionImplementation::getVendorsInCity() {
Vector<ManagedReference<SceneObject*> >* vendors = new Vector<ManagedReference<SceneObject*> >();
return vendors;
}
void CityRegionImplementation::addZoningRights(uint64 objectid, uint32 duration) {
Time now;
zoningRights.put(objectid, duration + now.getTime());
}
bool CityRegionImplementation::hasZoningRights(uint64 objectid) {
if (isMilitiaMember(objectid))
return true;
uint32 timestamp = zoningRights.get(objectid);
if (timestamp == 0)
return false;
Time now;
return (now.getTime() <= timestamp);
}
void CityRegionImplementation::setZone(Zone* zne) {
zone = zne;
}
void CityRegionImplementation::setRadius(float rad) {
if (regions.size() <= 0)
return;
ManagedReference<ActiveArea*> aa = regions.get(0).get();
aa->setRadius(rad);
zone->removeObject(aa, NULL, false);
zone->transferObject(aa, -1, false);
}
void CityRegionImplementation::destroyActiveAreas() {
for (int i = 0; i < regions.size(); ++i) {
ManagedReference<Region*> aa = regions.get(i);
if (aa != NULL) {
aa->destroyObjectFromWorld(false);
aa->destroyObjectFromDatabase(true);
regions.drop(aa);
}
}
}
String CityRegionImplementation::getRegionName() {
if(!customRegionName.isEmpty())
return customRegionName;
return regionName.getFullPath();
}
void CityRegionImplementation::addToCityStructureInventory(uint8 rankRequired, SceneObject* structure){
Locker locker(_this);
if(cityStructureInventory.contains(rankRequired)){
cityStructureInventory.get(rankRequired).put(structure);
}
}
void CityRegionImplementation::removeFromCityStructureInventory(SceneObject* structure){
Locker locker(_this);
if(cityStructureInventory.get(uint8(1)).contains(structure))
cityStructureInventory.get(uint8(1)).drop(structure);
else if(cityStructureInventory.get(uint8(2)).contains(structure))
cityStructureInventory.get(uint8(2)).drop(structure);
else if(cityStructureInventory.get(uint8(3)).contains(structure))
cityStructureInventory.get(uint8(3)).drop(structure);
else if(cityStructureInventory.get(uint8(4)).contains(structure))
cityStructureInventory.get(uint8(4)).drop(structure);
}
bool CityRegionImplementation::checkLimitedPlacementStucture(uint32 id){
Locker locker(_this);
if (limitedPlacementStructures.contains(id))
return true;
return false;
}
bool CityRegionImplementation::addLimitedPlacementStructure(uint32 id){
Locker locker(_this);
if (!limitedPlacementStructures.contains(id)){
limitedPlacementStructures.put(id);
return true;
}
return false;
}
void CityRegionImplementation::removeLimitedPlacementStructure(uint32 id){
Locker locker(_this);
limitedPlacementStructures.drop(id);
}
void CityRegionImplementation::destroyAllStructuresForRank(uint8 rank){
Locker locker(_this);
SortedVector<ManagedReference<SceneObject*> >* sceneObjects = &cityStructureInventory.get(rank);
int structureCount = sceneObjects->size();
int i;
if (structureCount > 0) {
for (i = structureCount - 1; i >= 0; i--) {
ManagedReference<SceneObject*> sceo = sceneObjects->get(i);
Locker locker(sceo, _this);
Zone* zoneObject = sceo->getZone();
if (zoneObject != NULL) {
StructureManager* manager = zoneObject->getStructureManager();
if (manager != NULL) {
if (sceo->isStructureObject()) {
manager->destroyStructure(cast<StructureObject*>(sceo.get()));
} else {
sceo->destroyObjectFromWorld(true);
sceo->destroyObjectFromDatabase(true);
}
}
}
sceneObjects->drop(sceo);
}
}
}
void CityRegionImplementation::updateMilitia(){
Locker locker (_this);
uint64 objectID;
for (int i = militiaMembers.size() - 1;i >= 0; --i){
objectID = militiaMembers.get(i);
if (!isCitizen(objectID))
removeMilitiaMember(objectID);
}
}
void CityRegionImplementation::removeAllTerminals(){
for (int i = 0; i < cityMissionTerminals.size(); i++){
cityMissionTerminals.get(i)->destroyObjectFromWorld(false);
cityMissionTerminals.get(i)->destroyObjectFromDatabase(false);
}
cityMissionTerminals.removeAll();
}
void CityRegionImplementation::removeAllSkillTrainers(){
for (int i = 0; i < citySkillTrainers.size(); i++){
citySkillTrainers.get(i)->destroyObjectFromWorld(false);
citySkillTrainers.get(i)->destroyObjectFromDatabase(false);
}
citySkillTrainers.removeAll();
}
<commit_msg>[updated] CityRegion::notifyEnter/Exit<commit_after>/*
* CityRegionImplementation.cpp
*
* Created on: Feb 9, 2012
* Author: xyborn
*/
#include "CityRegion.h"
#include "events/CityUpdateEvent.h"
#include "server/zone/Zone.h"
#include "server/zone/objects/area/ActiveArea.h"
#include "server/chat/StringIdChatParameter.h"
#include "server/zone/objects/scene/SceneObject.h"
#include "server/zone/objects/creature/CreatureObject.h"
#include "server/zone/objects/structure/StructureObject.h"
#include "server/zone/objects/region/Region.h"
#include "server/zone/managers/stringid/StringIdManager.h"
#include "server/ServerCore.h"
#include "server/zone/managers/city/CityManager.h"
#include "server/zone/managers/planet/PlanetManager.h"
#include "server/zone/managers/planet/PlanetTravelPoint.h"
#include "server/zone/managers/structure/StructureManager.h"
#include "server/zone/objects/building/BuildingObject.h"
#include "server/zone/objects/player/PlayerObject.h"
void CityRegionImplementation::initializeTransientMembers() {
ManagedObjectImplementation::initializeTransientMembers();
}
void CityRegionImplementation::notifyLoadFromDatabase() {
ManagedObjectImplementation::notifyLoadFromDatabase();
if (cityRank == CityManager::CLIENT)
return;
//if (zone !=)
Zone* zone = getZone();
if (zone == NULL)
return;
zone->addCityRegionToUpdate(_this);
if (isRegistered())
zone->getPlanetManager()->addRegion(_this);
/*
int seconds = -1 * round(nextUpdateTime.miliDifference() / 1000.f);
if (seconds < 0) //If the update occurred in the past, force an immediate update.
seconds = 0;
rescheduleUpdateEvent(seconds);
*/
if (hasShuttle){
CreatureObject* shuttle = cast<CreatureObject*>( zone->getZoneServer()->getObject(shuttleID, false));
if (shuttle == NULL) {
hasShuttle = false;
shuttleID = 0;
return;
}
float x = shuttle->getWorldPositionX();
float y = shuttle->getWorldPositionY();
float z = shuttle->getWorldPositionZ();
Vector3 arrivalVector(x, y, z);
PlanetTravelPoint* planetTravelPoint = new PlanetTravelPoint(zone->getZoneName(), getRegionName(), arrivalVector, arrivalVector, shuttle);
zone->getPlanetManager()->addPlayerCityTravelPoint(planetTravelPoint);
if (shuttle != NULL)
zone->getPlanetManager()->scheduleShuttle(shuttle);
}
}
void CityRegionImplementation::initialize() {
zoningEnabled = true;
registered = false;
cityTreasury = 0;
cityRank = RANK_CLIENT; //Default to client city
cityHall = NULL;
mayorID = 0;
shuttleID = 0;
hasShuttle = false;
zone = NULL;
cityUpdateEvent = NULL;
zoningRights.setAllowOverwriteInsertPlan();
zoningRights.setNullValue(0);
limitedPlacementStructures.setNoDuplicateInsertPlan();
cityStructureInventory.put(uint8(1), SortedVector<ManagedReference<SceneObject*> >());
cityStructureInventory.put(uint8(2), SortedVector<ManagedReference<SceneObject*> >());
cityStructureInventory.put(uint8(3), SortedVector<ManagedReference<SceneObject*> >());
cityStructureInventory.put(uint8(4), SortedVector<ManagedReference<SceneObject*> >());
cityStructureInventory.get(0).setNoDuplicateInsertPlan();
cityStructureInventory.get(1).setNoDuplicateInsertPlan();
cityStructureInventory.get(2).setNoDuplicateInsertPlan();
cityStructureInventory.get(3).setNoDuplicateInsertPlan();
cityMissionTerminals.setNoDuplicateInsertPlan();
cityDecorations.setNoDuplicateInsertPlan();
citySkillTrainers.setNoDuplicateInsertPlan();
setLoggingName("CityRegion");
setLogging(true);
}
Region* CityRegionImplementation::addRegion(float x, float y, float radius, bool persistent) {
if (zone == NULL) {
return NULL;
}
String temp = "object/region_area.iff";
SceneObject* obj = zone->getZoneServer()->createObject(temp.hashCode(), persistent ? 1 : 0);
if (obj == NULL || !obj->isRegion()) {
return NULL;
}
ManagedReference<Region*> region = cast<Region*>(obj);
region->setCityRegion(_this);
region->setRadius(radius);
region->initializePosition(x, 0, y);
region->setObjectName(regionName);
if (isClientRegion())
region->setNoBuildArea(true);
zone->transferObject(region, -1, false);
regions.put(region);
return region;
}
void CityRegionImplementation::rescheduleUpdateEvent(uint32 seconds) {
if (cityRank == CityManager::CLIENT)
return;
if (cityUpdateEvent == NULL) {
cityUpdateEvent = new CityUpdateEvent(_this, ServerCore::getZoneServer());
} else if (cityUpdateEvent->isScheduled()) {
cityUpdateEvent->cancel();
}
cityUpdateEvent->schedule(seconds * 1000);
Core::getTaskManager()->getNextExecutionTime(cityUpdateEvent, nextUpdateTime);
}
int CityRegionImplementation::getTimeToUpdate() {
return round(nextUpdateTime.miliDifference() / -1000.f);
}
void CityRegionImplementation::notifyEnter(SceneObject* object) {
object->setCityRegion(_this);
if (isClientRegion())
return;
if (object->isCreatureObject()){
CreatureObject* creature = cast<CreatureObject*>(object);
StringIdChatParameter params("city/city", "city_enter_city"); //You have entered %TT (%TO).
params.setTT(getRegionName());
UnicodeString strRank = StringIdManager::instance()->getStringId(String("@city/city:rank" + String::valueOf(cityRank)).hashCode());
if (citySpecialization.isEmpty()) {
params.setTO(strRank);
}
else {
UnicodeString citySpec = StringIdManager::instance()->getStringId(citySpecialization.hashCode());
params.setTO(strRank + ", " + citySpec);
}
creature->sendSystemMessage(params);
}
if (object->isBuildingObject()){
BuildingObject* building = cast<BuildingObject*>(object);
uint64 creatureID = building->getOwnerObjectID();
if (!citizenList.contains(creatureID)) {
CreatureObject* owner = building->getOwnerCreatureObject();
if (owner != NULL) {
PlayerObject* playerObject = owner->getPlayerObject();
if (playerObject != NULL && playerObject->getDeclaredResidence() == building) {
addCitizen(creatureID);
}
}
}
}
//Apply skillmods for specialization
}
void CityRegionImplementation::notifyExit(SceneObject* object) {
object->setCityRegion(NULL);
if (isClientRegion())
return;
if (object->isCreatureObject()){
CreatureObject* creature = cast<CreatureObject*>(object);
StringIdChatParameter params("city/city", "city_leave_city"); //You have left %TO.
params.setTO(getRegionName());
creature->sendSystemMessage(params);
//Remove skillmods for specialization
}
if (object->isBuildingObject()){
float x = object->getWorldPositionX();
float y = object->getWorldPositionY();
//StructureObject* structure = cast<StructureObject*>(object);
BuildingObject* building = cast<BuildingObject*>(object);
uint64 creatureID = building->getOwnerObjectID();
if (citizenList.contains(creatureID)) {
CreatureObject* owner = building->getOwnerCreatureObject();
if (owner != NULL) {
PlayerObject* playerObject = owner->getPlayerObject();
if (playerObject != NULL && playerObject->getDeclaredResidence() == building){
removeCitizen(creatureID);
}
}
}
}
}
void CityRegionImplementation::setRegionName(const StringId& name) {
regionName = name;
}
Vector<ManagedReference<SceneObject*> >* CityRegionImplementation::getVendorsInCity() {
Vector<ManagedReference<SceneObject*> >* vendors = new Vector<ManagedReference<SceneObject*> >();
return vendors;
}
void CityRegionImplementation::addZoningRights(uint64 objectid, uint32 duration) {
Time now;
zoningRights.put(objectid, duration + now.getTime());
}
bool CityRegionImplementation::hasZoningRights(uint64 objectid) {
if (isMilitiaMember(objectid))
return true;
uint32 timestamp = zoningRights.get(objectid);
if (timestamp == 0)
return false;
Time now;
return (now.getTime() <= timestamp);
}
void CityRegionImplementation::setZone(Zone* zne) {
zone = zne;
}
void CityRegionImplementation::setRadius(float rad) {
if (regions.size() <= 0)
return;
ManagedReference<ActiveArea*> aa = regions.get(0).get();
aa->setRadius(rad);
zone->removeObject(aa, NULL, false);
zone->transferObject(aa, -1, false);
}
void CityRegionImplementation::destroyActiveAreas() {
for (int i = 0; i < regions.size(); ++i) {
ManagedReference<Region*> aa = regions.get(i);
if (aa != NULL) {
aa->destroyObjectFromWorld(false);
aa->destroyObjectFromDatabase(true);
regions.drop(aa);
}
}
}
String CityRegionImplementation::getRegionName() {
if(!customRegionName.isEmpty())
return customRegionName;
return regionName.getFullPath();
}
void CityRegionImplementation::addToCityStructureInventory(uint8 rankRequired, SceneObject* structure){
Locker locker(_this);
if(cityStructureInventory.contains(rankRequired)){
cityStructureInventory.get(rankRequired).put(structure);
}
}
void CityRegionImplementation::removeFromCityStructureInventory(SceneObject* structure){
Locker locker(_this);
if(cityStructureInventory.get(uint8(1)).contains(structure))
cityStructureInventory.get(uint8(1)).drop(structure);
else if(cityStructureInventory.get(uint8(2)).contains(structure))
cityStructureInventory.get(uint8(2)).drop(structure);
else if(cityStructureInventory.get(uint8(3)).contains(structure))
cityStructureInventory.get(uint8(3)).drop(structure);
else if(cityStructureInventory.get(uint8(4)).contains(structure))
cityStructureInventory.get(uint8(4)).drop(structure);
}
bool CityRegionImplementation::checkLimitedPlacementStucture(uint32 id){
Locker locker(_this);
if (limitedPlacementStructures.contains(id))
return true;
return false;
}
bool CityRegionImplementation::addLimitedPlacementStructure(uint32 id){
Locker locker(_this);
if (!limitedPlacementStructures.contains(id)){
limitedPlacementStructures.put(id);
return true;
}
return false;
}
void CityRegionImplementation::removeLimitedPlacementStructure(uint32 id){
Locker locker(_this);
limitedPlacementStructures.drop(id);
}
void CityRegionImplementation::destroyAllStructuresForRank(uint8 rank){
Locker locker(_this);
SortedVector<ManagedReference<SceneObject*> >* sceneObjects = &cityStructureInventory.get(rank);
int structureCount = sceneObjects->size();
int i;
if (structureCount > 0) {
for (i = structureCount - 1; i >= 0; i--) {
ManagedReference<SceneObject*> sceo = sceneObjects->get(i);
Locker locker(sceo, _this);
Zone* zoneObject = sceo->getZone();
if (zoneObject != NULL) {
StructureManager* manager = zoneObject->getStructureManager();
if (manager != NULL) {
if (sceo->isStructureObject()) {
manager->destroyStructure(cast<StructureObject*>(sceo.get()));
} else {
sceo->destroyObjectFromWorld(true);
sceo->destroyObjectFromDatabase(true);
}
}
}
sceneObjects->drop(sceo);
}
}
}
void CityRegionImplementation::updateMilitia(){
Locker locker (_this);
uint64 objectID;
for (int i = militiaMembers.size() - 1;i >= 0; --i){
objectID = militiaMembers.get(i);
if (!isCitizen(objectID))
removeMilitiaMember(objectID);
}
}
void CityRegionImplementation::removeAllTerminals(){
for (int i = 0; i < cityMissionTerminals.size(); i++){
cityMissionTerminals.get(i)->destroyObjectFromWorld(false);
cityMissionTerminals.get(i)->destroyObjectFromDatabase(false);
}
cityMissionTerminals.removeAll();
}
void CityRegionImplementation::removeAllSkillTrainers(){
for (int i = 0; i < citySkillTrainers.size(); i++){
citySkillTrainers.get(i)->destroyObjectFromWorld(false);
citySkillTrainers.get(i)->destroyObjectFromDatabase(false);
}
citySkillTrainers.removeAll();
}
<|endoftext|> |
<commit_before>#include "session.h"
#include <algorithm>
namespace nng {
session::session()
: _dialer_eps()
, _listener_eps()
, _pair_sockets()
, _push_sockets()
, _pull_sockets() {
}
template<class Type_>
void __release_all(std::vector<std::shared_ptr<Type_>>& values) {
for (auto & x : values) {
x.reset();
}
values.clear();
}
session::~session() {
__release_all(_dialer_eps);
__release_all(_listener_eps);
__release_all(_pair_sockets);
__release_all(_push_sockets);
__release_all(_pull_sockets);
::nng_fini();
}
template<class Type_, typename ...Args_>
std::shared_ptr<Type_> __create(std::vector<std::shared_ptr<Type_>>& values, Args_ &&...args) {
auto sp = std::make_shared<Type_>(args...);
values.push_back(sp);
return sp;
}
template<class Type_>
void __remove(std::vector<std::shared_ptr<Type_>>& values, const Type_* const valuep) {
const auto __where = [&](std::shared_ptr<Type_> x) {
return x.get() == valuep;
};
std::remove_if(values.begin(), values.end(), __where);
}
std::shared_ptr<dialer> session::create_dialer_ep() {
return __create(_dialer_eps);
}
std::shared_ptr<dialer> session::create_dialer_ep(const socket& s, const std::string& addr) {
return __create(_dialer_eps, s, addr);
}
std::shared_ptr<listener> session::create_listener_ep() {
return __create(_listener_eps);
}
std::shared_ptr<listener> session::create_listener_ep(const socket& s, const std::string& addr) {
return __create(_listener_eps, s, addr);
}
void session::remove_dialer_ep(const dialer* const dp) {
// Yes, in fact, we do not need the full smart pointer in this instance.
__remove(_dialer_eps, dp);
}
void session::remove_listener_ep(const listener* const lp) {
// Ditto smart pointers.
__remove(_listener_eps, lp);
}
std::shared_ptr<protocol::latest_pair_socket> session::create_pair_socket() {
return __create(_pair_sockets);
}
void session::remove_pair_socket(const protocol::latest_pair_socket* const sp) {
__remove(_pair_sockets, sp);
}
std::shared_ptr<protocol::latest_push_socket> session::create_push_socket() {
return __create(_push_sockets);
}
std::shared_ptr<protocol::latest_pull_socket> session::create_pull_socket() {
return __create(_pull_sockets);
}
}
<commit_msg>the previous approach should have been fine but we will make it more concise<commit_after>#include "session.h"
#include <algorithm>
namespace nng {
session::session()
: _dialer_eps()
, _listener_eps()
, _pair_sockets()
, _push_sockets()
, _pull_sockets() {
}
template<class Type_>
void __release_all(std::vector<std::shared_ptr<Type_>>& values) {
for (auto & x : values) {
x.reset();
}
values.clear();
}
session::~session() {
__release_all(_dialer_eps);
__release_all(_listener_eps);
__release_all(_pair_sockets);
__release_all(_push_sockets);
__release_all(_pull_sockets);
::nng_fini();
}
template<class Type_, typename ...Args_>
std::shared_ptr<Type_> __create(std::vector<std::shared_ptr<Type_>>& values, Args_ &&...args) {
auto sp = std::make_shared<Type_>(args...);
values.push_back(sp);
return sp;
}
template<class Type_>
void __remove(std::vector<std::shared_ptr<Type_>>& values, const Type_* const valuep) {
std::remove_if(values.begin(), values.end(), [&](const std::shared_ptr<Type_>& sp) {
return sp.get() == valuep;
});
}
std::shared_ptr<dialer> session::create_dialer_ep() {
return __create(_dialer_eps);
}
std::shared_ptr<dialer> session::create_dialer_ep(const socket& s, const std::string& addr) {
return __create(_dialer_eps, s, addr);
}
std::shared_ptr<listener> session::create_listener_ep() {
return __create(_listener_eps);
}
std::shared_ptr<listener> session::create_listener_ep(const socket& s, const std::string& addr) {
return __create(_listener_eps, s, addr);
}
void session::remove_dialer_ep(const dialer* const dp) {
// Yes, in fact, we do not need the full smart pointer in this instance.
__remove(_dialer_eps, dp);
}
void session::remove_listener_ep(const listener* const lp) {
// Ditto smart pointers.
__remove(_listener_eps, lp);
}
std::shared_ptr<protocol::latest_pair_socket> session::create_pair_socket() {
return __create(_pair_sockets);
}
void session::remove_pair_socket(const protocol::latest_pair_socket* const sp) {
__remove(_pair_sockets, sp);
}
std::shared_ptr<protocol::latest_push_socket> session::create_push_socket() {
return __create(_push_sockets);
}
std::shared_ptr<protocol::latest_pull_socket> session::create_pull_socket() {
return __create(_pull_sockets);
}
}
<|endoftext|> |
<commit_before>/*=========================================================================
Program: ORFEO Toolbox
Language: C++
Date: $Date$
Version: $Revision$
Copyright (c) Centre National d'Etudes Spatiales. All rights reserved.
See OTBCopyright.txt for details.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE. See the above copyright notices for more information.
=========================================================================*/
#include "otbNeuralNetworkMachineLearningModel.h"
typedef float PrecisionType;
typedef otb::MachineLearningModel<PrecisionType,PrecisionType> MachineLearningModelRegressionType;
typedef MachineLearningModelRegressionType::InputValueType InputValueRegressionType;
typedef MachineLearningModelRegressionType::InputSampleType InputSampleRegressionType;
typedef MachineLearningModelRegressionType::InputListSampleType InputListSampleRegressionType;
typedef MachineLearningModelRegressionType::TargetValueType TargetValueRegressionType;
typedef MachineLearningModelRegressionType::TargetSampleType TargetSampleRegressionType;
typedef MachineLearningModelRegressionType::TargetListSampleType TargetListSampleRegressionType;
template <typename TPrecision>
struct LinearFunctionSampleGenerator
{
LinearFunctionSampleGenerator(TPrecision a, TPrecision b)
: m_a(a), m_b(b), m_NbInputVars(1), m_NbOutputVars(1) {
m_isl = InputListSampleRegressionType::New();
m_tsl = TargetListSampleRegressionType::New();
};
void GenerateSamples(TPrecision sMin, TPrecision sMax, size_t nbSamples)
{
m_isl->SetMeasurementVectorSize(m_NbInputVars);
m_tsl->SetMeasurementVectorSize(m_NbOutputVars);
TPrecision sampleStep = (sMax-sMin)/nbSamples;
for(size_t i=0; i<nbSamples; ++i)
{
InputSampleRegressionType inputSample;
inputSample.Reserve(m_NbInputVars);
TPrecision inputValue = sMin+ i*sampleStep;
TPrecision outputValue = m_a*inputValue+m_b;
m_isl->PushBack(inputSample);
m_tsl->PushBack(outputValue);
}
}
InputListSampleRegressionType* GetInputSampleList()
{
return m_isl;
}
TargetListSampleRegressionType* GetTargetSampleList()
{
return m_tsl;
}
TPrecision m_a;
TPrecision m_b;
const size_t m_NbInputVars;
const size_t m_NbOutputVars;
InputListSampleRegressionType::Pointer m_isl;
TargetListSampleRegressionType::Pointer m_tsl;
};
int otbNeuralNetworkRegressionLinearMonovariate(int itkNotUsed(argc),
char * itkNotUsed(argv) [])
{
LinearFunctionSampleGenerator<PrecisionType> lfsg(1.0, 0.0);
lfsg.GenerateSamples(0.0, 1.0, 100);
typedef otb::NeuralNetworkMachineLearningModel<InputValueRegressionType,
TargetValueRegressionType>
NeuralNetworkType;
NeuralNetworkType::Pointer regression = NeuralNetworkType::New();
regression->SetRegressionMode(1);
regression->SetTrainMethod(CvANN_MLP_TrainParams::BACKPROP);
std::vector<unsigned int> layerSizes;
layerSizes.push_back(1);
layerSizes.push_back(5);
layerSizes.push_back(1);
regression->SetLayerSizes(layerSizes);
regression->SetActivateFunction(CvANN_MLP::SIGMOID_SYM);
regression->SetAlpha(1.0);
regression->SetBeta(0.01);
regression->SetBackPropDWScale(0.1);
regression->SetBackPropMomentScale(0.1);
regression->SetRegPropDW0(0.1);
regression->SetRegPropDWMin(1e-7);
regression->SetTermCriteriaType(CV_TERMCRIT_ITER + CV_TERMCRIT_EPS);
regression->SetEpsilon(1e-10);
regression->SetMaxIter(1e7);
regression->SetInputListSample(lfsg.GetInputSampleList());
regression->SetTargetListSample(lfsg.GetTargetSampleList());
regression->Train();
return EXIT_SUCCESS;
}
<commit_msg>TEST: add test for ANN regression prediction<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 "otbNeuralNetworkMachineLearningModel.h"
typedef float PrecisionType;
typedef otb::MachineLearningModel<PrecisionType,PrecisionType> MachineLearningModelRegressionType;
typedef MachineLearningModelRegressionType::InputValueType InputValueRegressionType;
typedef MachineLearningModelRegressionType::InputSampleType InputSampleRegressionType;
typedef MachineLearningModelRegressionType::InputListSampleType InputListSampleRegressionType;
typedef MachineLearningModelRegressionType::TargetValueType TargetValueRegressionType;
typedef MachineLearningModelRegressionType::TargetSampleType TargetSampleRegressionType;
typedef MachineLearningModelRegressionType::TargetListSampleType TargetListSampleRegressionType;
const double epsilon = 0.1;
template <typename TPrecision>
struct LinearFunctionSampleGenerator
{
LinearFunctionSampleGenerator(TPrecision a, TPrecision b)
: m_a(a), m_b(b), m_NbInputVars(1), m_NbOutputVars(1) {
m_isl = InputListSampleRegressionType::New();
m_tsl = TargetListSampleRegressionType::New();
};
void GenerateSamples(TPrecision sMin, TPrecision sMax, size_t nbSamples)
{
m_isl->SetMeasurementVectorSize(m_NbInputVars);
m_tsl->SetMeasurementVectorSize(m_NbOutputVars);
TPrecision sampleStep = (sMax-sMin)/nbSamples;
for(size_t i=0; i<nbSamples; ++i)
{
InputSampleRegressionType inputSample;
inputSample.Reserve(m_NbInputVars);
TPrecision x = std::rand()/static_cast<TPrecision>(RAND_MAX)*nbSamples;
TPrecision inputValue = sMin+ x*sampleStep;
inputSample[0] = inputValue;
TPrecision outputValue = m_a*inputValue+m_b;
m_isl->PushBack(inputSample);
m_tsl->PushBack(outputValue);
}
}
TPrecision m_a;
TPrecision m_b;
const size_t m_NbInputVars;
const size_t m_NbOutputVars;
InputListSampleRegressionType::Pointer m_isl;
TargetListSampleRegressionType::Pointer m_tsl;
};
int otbNeuralNetworkRegressionLinearMonovariate(int itkNotUsed(argc),
char * itkNotUsed(argv) [])
{
LinearFunctionSampleGenerator<PrecisionType> lfsg(1.0, 0.0);
std::cout << "Generating samples\n";
lfsg.GenerateSamples(-0.5, 0.5, 20000);
typedef otb::NeuralNetworkMachineLearningModel<InputValueRegressionType,
TargetValueRegressionType>
NeuralNetworkType;
NeuralNetworkType::Pointer regression = NeuralNetworkType::New();
regression->SetRegressionMode(1);
regression->SetTrainMethod(CvANN_MLP_TrainParams::BACKPROP);
std::vector<unsigned int> layerSizes;
layerSizes.push_back(1);
layerSizes.push_back(5);
layerSizes.push_back(1);
regression->SetLayerSizes(layerSizes);
regression->SetActivateFunction(CvANN_MLP::SIGMOID_SYM);
regression->SetAlpha(1.0);
regression->SetBeta(1.0);
regression->SetBackPropDWScale(0.1);
regression->SetBackPropMomentScale(0.1);
regression->SetRegPropDW0(0.1);
regression->SetRegPropDWMin(1e-7);
regression->SetTermCriteriaType(CV_TERMCRIT_EPS);
regression->SetEpsilon(1e-5);
regression->SetMaxIter(1e20);
regression->SetInputListSample(lfsg.m_isl);
regression->SetTargetListSample(lfsg.m_tsl);
std::cout << "Training\n";
regression->Train();
std::cout << "Validation\n";
//Check the prediction accuracy
typename InputListSampleRegressionType::Iterator sampleIt = lfsg.m_isl->Begin();
typename TargetListSampleRegressionType::Iterator resultIt = lfsg.m_tsl->Begin();
typename InputListSampleRegressionType::Iterator sampleLast = lfsg.m_isl->End();
typename TargetListSampleRegressionType::Iterator resultLast = lfsg.m_tsl->End();
PrecisionType rmse = 0.0;
size_t nbSamples = 0;
while(sampleIt != sampleLast && resultIt != resultLast)
{
PrecisionType invalue = sampleIt.GetMeasurementVector()[0];
PrecisionType prediction = regression->Predict(sampleIt.GetMeasurementVector())[0];
PrecisionType expected = resultIt.GetMeasurementVector()[0];
rmse += pow(prediction - expected, 2.0);
++sampleIt;
++resultIt;
++nbSamples;
}
rmse /= nbSamples;
if(rmse > epsilon)
return EXIT_FAILURE;
return EXIT_SUCCESS;
}
<|endoftext|> |
<commit_before>#include "ros/ros.h"
#include "scr_proto/DiffCommand.h"
#include "scr_proto/SpeedCommand.h"
#include "std_msgs/Int32.h"
#include "std_msgs/Float64.h"
double PI = 3.141592654;
double pulses_per_rev = 3200;
// CONTROL VARIABLES
double Kp = 0.5;
double Kd = 0.12;
double Ki = 0.0;
double last_control_time;
double lw_prev_error=0, rw_prev_error=0;
double lw_int_error=0, rw_int_error=0;
double int_error_max = 500.0;
// ROS Pub-Sub for node
ros::Publisher motor_cmd_pub;
ros::Publisher lw_pub;
ros::Publisher rw_pub;
ros::Subscriber left_enc_sub;
ros::Subscriber right_enc_sub;
ros::Subscriber motor_cmd_sub;
scr_proto::DiffCommand diff_msg;
std_msgs::Float64 lw_msg;
std_msgs::Float64 rw_msg;
// Store Last command time so we can shut down if not receiving direction
ros::Time last_command_time;
// Global Variables for left and right encoders
double left_enc_count, left_enc_prev_count, right_enc_count, right_enc_prev_count;
double left_prev_enc_time, right_prev_enc_time;
// Global Variables for Observed Wheel Velocities
double lw_omega, rw_omega;
// Global Variables for Commanded Wheel Speeds
double rw_spd_cmd, lw_spd_cmd;
// Output variables
double rw_output, lw_output;
// Callbacks to store data coming from Arduino
void leftEncoderCallback(const std_msgs::Int32::ConstPtr& msg){
double l_count = msg->data;
left_enc_count = .9 * left_enc_count + .1 * l_count;
}
void rightEncoderCallback(const std_msgs::Int32::ConstPtr& msg){
double r_count = msg->data;
right_enc_count = .9 * right_enc_count + .1 * r_count;
}
// Gets current wheel velocity in rad/s
// ToDo : implement low pass filter on data?
void updateWheelVels(){
// Get the current time
double enc_time = ros::Time::now().toSec();
double time_diff = enc_time - left_prev_enc_time;
// Calculate unfiltered encoder velocity in pulses per sec
lw_omega = (left_enc_count - left_enc_prev_count) /
(enc_time - left_prev_enc_time);
rw_omega = (right_enc_count - right_enc_prev_count) /
(enc_time - right_prev_enc_time);
// Convert from pulses per sec to rads per sec
lw_omega = lw_omega/(pulses_per_rev) * 2.0 * 3.14159;
rw_omega = rw_omega/(pulses_per_rev) * 2.0 * 3.14159;
// Update Previous Values
left_enc_prev_count = left_enc_count;
left_prev_enc_time = enc_time;
right_enc_prev_count = right_enc_count;
right_prev_enc_time = enc_time;
}
// Write values to Pololu motor Driver by publishing to motor_node
void assign(int rw_pmd_cmd, int lw_pmd_cmd){
diff_msg.left_motor = lw_pmd_cmd;
diff_msg.right_motor = rw_pmd_cmd;
motor_cmd_pub.publish(diff_msg);
}
// Takes a command velocity in rad/s and uses PID to control
// motor to that speed
void control(double lw_cmd, double rw_cmd){
// Get most current wheel velocities
updateWheelVels();
// Calculate Current Error
double lw_cur_error = lw_omega - lw_cmd;
double rw_cur_error = rw_omega - rw_cmd;
//ROS_INFO("lw cur error = [%f]", lw_cur_error);
// Get time difference between now and last control time
double dt = ros::Time::now().toSec() - last_control_time;
// Derivative of Error
double lw_dedt = (lw_cur_error - lw_prev_error) / dt;
double rw_dedt = (rw_cur_error - rw_prev_error) / dt;
// Calculate PID Output
rw_output += Kp * rw_cur_error + Kd * rw_dedt + Ki * rw_int_error;
lw_output += Kp * lw_cur_error + Kd * lw_dedt + Ki * lw_int_error;
ROS_INFO("lw_output = [%g]", lw_output);
ROS_INFO("rw_output = [%g]", rw_output);
// Write value to Motor Driver
assign(rw_output, lw_output);
// Update Error Values
lw_int_error += (lw_cur_error + lw_prev_error) / 2.0 * dt;
lw_int_error = std::min(lw_int_error, int_error_max);
rw_int_error += (rw_cur_error + rw_prev_error) / 2.0 * dt;
rw_int_error = std::min(rw_int_error, int_error_max);
last_control_time = ros::Time::now().toSec();
lw_prev_error = lw_cur_error;
rw_prev_error = rw_cur_error;
}
// Callback to respond to new command velocity
void commandCallback(const scr_proto::SpeedCommand::ConstPtr& msg){
lw_spd_cmd = msg->left_motor_w;
rw_spd_cmd = msg->right_motor_w;
last_command_time = ros::Time::now();
}
int main(int argc, char **argv){
// Initialize Node
ros::init(argc, argv, "speed_controller");
// Get nodehandle
ros::NodeHandle n;
// Initializes Publisher/Subscriber
motor_cmd_pub = n.advertise<scr_proto::DiffCommand>("/motor_command", 1000);
lw_pub = n.advertise<std_msgs::Float64>("lw_speed", 1000);
rw_pub = n.advertise<std_msgs::Float64>("rw_speed", 1000);
motor_cmd_sub = n.subscribe("speed_command", 1000, commandCallback);
left_enc_sub = n.subscribe("left_encoder", 1000, leftEncoderCallback);
right_enc_sub = n.subscribe("right_encoder", 1000, rightEncoderCallback);
last_command_time = ros::Time::now();
// Loop Rate
ros::Rate loop_rate(10);
while(ros::ok()){
if((ros::Time::now()-last_command_time) > ros::Duration(10, 0)){
lw_spd_cmd = 0.0;
rw_spd_cmd = 0.0;
ROS_INFO("Stale Speed Command, shutting off motors");
last_command_time = ros::Time::now();
}
else{
control(lw_spd_cmd, rw_spd_cmd);
}
lw_msg.data = lw_omega;
rw_msg.data = rw_omega;
lw_pub.publish(lw_msg);
rw_pub.publish(rw_msg);
ros::spinOnce();
loop_rate.sleep();
}
}
<commit_msg>Added rosparam calls to speed controller so control gains are tweakable on command line.<commit_after>#include "ros/ros.h"
#include "scr_proto/DiffCommand.h"
#include "scr_proto/SpeedCommand.h"
#include "std_msgs/Int32.h"
#include "std_msgs/Float64.h"
double PI = 3.141592654;
double pulses_per_rev = 3200;
// CONTROL VARIABLES
double Kp = 0.0 ;//.5;
double Kd = 0.0 ;//.12;
double Ki = 0.0;
double last_control_time;
double lw_prev_error=0, rw_prev_error=0;
double lw_int_error=0, rw_int_error=0;
double int_error_max = 500.0;
// ROS Pub-Sub for node
ros::Publisher motor_cmd_pub;
ros::Publisher lw_pub;
ros::Publisher rw_pub;
ros::Subscriber left_enc_sub;
ros::Subscriber right_enc_sub;
ros::Subscriber motor_cmd_sub;
scr_proto::DiffCommand diff_msg;
std_msgs::Float64 lw_msg;
std_msgs::Float64 rw_msg;
// Store Last command time so we can shut down if not receiving direction
ros::Time last_command_time;
// Global Variables for left and right encoders
double left_enc_count, left_enc_prev_count, right_enc_count, right_enc_prev_count;
double left_prev_enc_time, right_prev_enc_time;
// Global Variables for Observed Wheel Velocities
double lw_omega, rw_omega;
// Global Variables for Commanded Wheel Speeds
double rw_spd_cmd, lw_spd_cmd;
// Output variables
double rw_output, lw_output;
// Callbacks to store data coming from Arduino
void leftEncoderCallback(const std_msgs::Int32::ConstPtr& msg){
double l_count = msg->data;
left_enc_count = .9 * left_enc_count + .1 * l_count;
}
void rightEncoderCallback(const std_msgs::Int32::ConstPtr& msg){
double r_count = msg->data;
right_enc_count = .9 * right_enc_count + .1 * r_count;
}
// Gets current wheel velocity in rad/s
// ToDo : implement low pass filter on data?
void updateWheelVels(){
// Get the current time
double enc_time = ros::Time::now().toSec();
double time_diff = enc_time - left_prev_enc_time;
// Calculate unfiltered encoder velocity in pulses per sec
lw_omega = (left_enc_count - left_enc_prev_count) /
(enc_time - left_prev_enc_time);
rw_omega = (right_enc_count - right_enc_prev_count) /
(enc_time - right_prev_enc_time);
// Convert from pulses per sec to rads per sec
lw_omega = lw_omega/(pulses_per_rev) * 2.0 * 3.14159;
rw_omega = rw_omega/(pulses_per_rev) * 2.0 * 3.14159;
// Update Previous Values
left_enc_prev_count = left_enc_count;
left_prev_enc_time = enc_time;
right_enc_prev_count = right_enc_count;
right_prev_enc_time = enc_time;
}
// Write values to Pololu motor Driver by publishing to motor_node
void assign(int rw_pmd_cmd, int lw_pmd_cmd){
diff_msg.left_motor = lw_pmd_cmd;
diff_msg.right_motor = rw_pmd_cmd;
motor_cmd_pub.publish(diff_msg);
}
// Takes a command velocity in rad/s and uses PID to control
// motor to that speed
void control(double lw_cmd, double rw_cmd){
// Get most current wheel velocities
updateWheelVels();
// Calculate Current Error
double lw_cur_error = lw_omega - lw_cmd;
double rw_cur_error = rw_omega - rw_cmd;
//ROS_INFO("lw cur error = [%f]", lw_cur_error);
// Get time difference between now and last control time
double dt = ros::Time::now().toSec() - last_control_time;
// Derivative of Error
double lw_dedt = (lw_cur_error - lw_prev_error) / dt;
double rw_dedt = (rw_cur_error - rw_prev_error) / dt;
// Calculate PID Output
rw_output += Kp * rw_cur_error + Kd * rw_dedt + Ki * rw_int_error;
lw_output += Kp * lw_cur_error + Kd * lw_dedt + Ki * lw_int_error;
ROS_INFO("lw_output = [%g]", lw_output);
ROS_INFO("rw_output = [%g]", rw_output);
// Write value to Motor Driver
assign(rw_output, lw_output);
// Update Error Values
lw_int_error += (lw_cur_error + lw_prev_error) / 2.0 * dt;
lw_int_error = std::min(lw_int_error, int_error_max);
rw_int_error += (rw_cur_error + rw_prev_error) / 2.0 * dt;
rw_int_error = std::min(rw_int_error, int_error_max);
last_control_time = ros::Time::now().toSec();
lw_prev_error = lw_cur_error;
rw_prev_error = rw_cur_error;
}
// Callback to respond to new command velocity
void commandCallback(const scr_proto::SpeedCommand::ConstPtr& msg){
lw_spd_cmd = msg->left_motor_w;
rw_spd_cmd = msg->right_motor_w;
last_command_time = ros::Time::now();
}
int main(int argc, char **argv){
// Initialize Node
ros::init(argc, argv, "speed_controller");
// Get nodehandle
ros::NodeHandle n;
// Initializes Publisher/Subscriber
motor_cmd_pub = n.advertise<scr_proto::DiffCommand>("/motor_command", 1000);
lw_pub = n.advertise<std_msgs::Float64>("lw_speed", 1000);
rw_pub = n.advertise<std_msgs::Float64>("rw_speed", 1000);
motor_cmd_sub = n.subscribe("speed_command", 1000, commandCallback);
left_enc_sub = n.subscribe("left_encoder", 1000, leftEncoderCallback);
right_enc_sub = n.subscribe("right_encoder", 1000, rightEncoderCallback);
double kp, ki, kd;
last_command_time = ros::Time::now();
// Loop Rate
ros::Rate loop_rate(10);
while(ros::ok()){
// Pull parameters out of rosparam for dynamic control changes
if(n.getParam("gains/kp", kp)){ Kp = kp; }
if(n.getParam("gains/kd", kd)){ Kd = kd; }
if(n.getParam("gains/ki", ki)){ Ki = ki; }
if((ros::Time::now()-last_command_time) > ros::Duration(10, 0)){
lw_spd_cmd = 0.0;
rw_spd_cmd = 0.0;
ROS_INFO("Stale Speed Command, shutting off motors");
last_command_time = ros::Time::now();
}
else{
control(lw_spd_cmd, rw_spd_cmd);
}
lw_msg.data = lw_omega;
rw_msg.data = rw_omega;
lw_pub.publish(lw_msg);
rw_pub.publish(rw_msg);
ros::spinOnce();
loop_rate.sleep();
}
}
<|endoftext|> |
<commit_before>/////////////////////////////////////////////////////////////////////////////
//
// FILE NAME
// atrixGenerator.cc
//
// AUTHOR
// Andrei Shishlo
//
// TIME
// 03/18/2008
//
// DESCRIPTION
// A generator of the linear transport matrix from the bunch tracking.
// It solves the system of equations with respect to a,b,c:
// y0 = a*x0^2 + b*x0 + c
// y1 = a*x1^2 + b*x1 + c
// y2 = a*x2^2 + b*x2 + c
// for x0 = 0., we need only b coefficient.
// Solution:
// b = ((y1-y0)*x2^2 - (y2-y0)*x1^2)/(x1*x2*(x2 -x1))
//
/////////////////////////////////////////////////////////////////////////////
#include "orbit_mpi.hh"
#include "MatrixGenerator.hh"
using namespace OrbitUtils;
namespace teapot_base{
MatrixGenerator::MatrixGenerator(){
step_arr = new double[6];
step_arr[0] = 0.000001;
step_arr[1] = 0.000001;
step_arr[2] = 0.000001;
step_arr[3] = 0.000001;
step_arr[4] = 0.000001;
step_arr[5] = 0.000001;
step_reduce = 20.;
}
MatrixGenerator::~MatrixGenerator(){
delete [] step_arr;
}
double& MatrixGenerator::step(int index){
return step_arr[index];
}
void MatrixGenerator::initBunch(Bunch* bunch){
bunch->deleteAllParticles();
bunch->addParticle(0.,0.,0.,0.,0.,0.);
bunch->addParticle(step_arr[0]/step_reduce,0.,0.,0.,0.,0.);
bunch->addParticle(0.,step_arr[1]/step_reduce,0.,0.,0.,0.);
bunch->addParticle(0.,0.,step_arr[2]/step_reduce,0.,0.,0.);
bunch->addParticle(0.,0.,0.,step_arr[3]/step_reduce,0.,0.);
bunch->addParticle(0.,0.,0.,0.,step_arr[4]/step_reduce,0.);
bunch->addParticle(0.,0.,0.,0.,0.,step_arr[5]/step_reduce);
bunch->addParticle(step_arr[0],0.,0.,0.,0.,0.);
bunch->addParticle(0.,step_arr[1],0.,0.,0.,0.);
bunch->addParticle(0.,0.,step_arr[2],0.,0.,0.);
bunch->addParticle(0.,0.,0.,step_arr[3],0.,0.);
bunch->addParticle(0.,0.,0.,0.,step_arr[4],0.);
bunch->addParticle(0.,0.,0.,0.,0.,step_arr[5]);
}
void MatrixGenerator::calculateMatrix(Bunch* bunch,Matrix* mtrx){
if(mtrx->rows() != mtrx->columns() || mtrx->rows() < 6){
ORBIT_MPI_Finalize("MatrixGenerator::calculateMatrix: Matrix has a wrong size.");
}
if(bunch->getSize() != 13){
ORBIT_MPI_Finalize("MatrixGenerator::calculateMatrix: Bunch should have 7 macro-particles.");
}
double x1,x2,y1,y2,y0;
double** coord_arr = bunch->coordArr();
double** arr = mtrx->getArray();
for(int i = 0; i < 6; i++){
for(int j = 0; j < 6; j++){
x1 = step_arr[j]/step_reduce;
x2 = step_arr[j];
y0 = coord_arr[0][j];
y1 = coord_arr[i+1][j];
y2 = coord_arr[i+1+6][j];
arr[j][i] = ((y1-y0)*x2*x2 - (y2-y0)*x1*x1)/(x1*x2*(x2 -x1));
}
}
if(mtrx->rows() == 7){
for(int i = 0; i < 6; i++){
arr[i][6] = coord_arr[0][i];
arr[6][i] = 0.;
}
arr[6][6] = 1.0;
}
}
} //end of namespace teapot_base
<commit_msg>The error in the message fixed<commit_after>/////////////////////////////////////////////////////////////////////////////
//
// FILE NAME
// atrixGenerator.cc
//
// AUTHOR
// Andrei Shishlo
//
// TIME
// 03/18/2008
//
// DESCRIPTION
// A generator of the linear transport matrix from the bunch tracking.
// It solves the system of equations with respect to a,b,c:
// y0 = a*x0^2 + b*x0 + c
// y1 = a*x1^2 + b*x1 + c
// y2 = a*x2^2 + b*x2 + c
// for x0 = 0., we need only b coefficient.
// Solution:
// b = ((y1-y0)*x2^2 - (y2-y0)*x1^2)/(x1*x2*(x2 -x1))
//
/////////////////////////////////////////////////////////////////////////////
#include "orbit_mpi.hh"
#include "MatrixGenerator.hh"
using namespace OrbitUtils;
namespace teapot_base{
MatrixGenerator::MatrixGenerator(){
step_arr = new double[6];
step_arr[0] = 0.000001;
step_arr[1] = 0.000001;
step_arr[2] = 0.000001;
step_arr[3] = 0.000001;
step_arr[4] = 0.000001;
step_arr[5] = 0.000001;
step_reduce = 20.;
}
MatrixGenerator::~MatrixGenerator(){
delete [] step_arr;
}
double& MatrixGenerator::step(int index){
return step_arr[index];
}
void MatrixGenerator::initBunch(Bunch* bunch){
bunch->deleteAllParticles();
bunch->addParticle(0.,0.,0.,0.,0.,0.);
bunch->addParticle(step_arr[0]/step_reduce,0.,0.,0.,0.,0.);
bunch->addParticle(0.,step_arr[1]/step_reduce,0.,0.,0.,0.);
bunch->addParticle(0.,0.,step_arr[2]/step_reduce,0.,0.,0.);
bunch->addParticle(0.,0.,0.,step_arr[3]/step_reduce,0.,0.);
bunch->addParticle(0.,0.,0.,0.,step_arr[4]/step_reduce,0.);
bunch->addParticle(0.,0.,0.,0.,0.,step_arr[5]/step_reduce);
bunch->addParticle(step_arr[0],0.,0.,0.,0.,0.);
bunch->addParticle(0.,step_arr[1],0.,0.,0.,0.);
bunch->addParticle(0.,0.,step_arr[2],0.,0.,0.);
bunch->addParticle(0.,0.,0.,step_arr[3],0.,0.);
bunch->addParticle(0.,0.,0.,0.,step_arr[4],0.);
bunch->addParticle(0.,0.,0.,0.,0.,step_arr[5]);
}
void MatrixGenerator::calculateMatrix(Bunch* bunch,Matrix* mtrx){
if(mtrx->rows() != mtrx->columns() || mtrx->rows() < 6){
ORBIT_MPI_Finalize("MatrixGenerator::calculateMatrix: Matrix has a wrong size.");
}
if(bunch->getSize() != 13){
ORBIT_MPI_Finalize("MatrixGenerator::calculateMatrix: Bunch should have 13 macro-particles.");
}
double x1,x2,y1,y2,y0;
double** coord_arr = bunch->coordArr();
double** arr = mtrx->getArray();
for(int i = 0; i < 6; i++){
for(int j = 0; j < 6; j++){
x1 = step_arr[j]/step_reduce;
x2 = step_arr[j];
y0 = coord_arr[0][j];
y1 = coord_arr[i+1][j];
y2 = coord_arr[i+1+6][j];
arr[j][i] = ((y1-y0)*x2*x2 - (y2-y0)*x1*x1)/(x1*x2*(x2 -x1));
}
}
if(mtrx->rows() == 7){
for(int i = 0; i < 6; i++){
arr[i][6] = coord_arr[0][i];
arr[6][i] = 0.;
}
arr[6][6] = 1.0;
}
}
} //end of namespace teapot_base
<|endoftext|> |
<commit_before>// Copyright (c) 2012 Nokia, Inc.
// Copyright (c) 2013-2014 Quanta Research Cambridge, 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.
#include "portal.h"
#include "sock_utils.h"
#include <string.h>
#include <poll.h>
#include <errno.h>
#include <pthread.h>
#include <fcntl.h>
static int trace_poller;//=1;
#ifndef NO_CPP_PORTAL_CODE
PortalPoller *defaultPoller = new PortalPoller();
uint64_t poll_enter_time, poll_return_time; // for performance measurement
PortalPoller::PortalPoller(int autostart)
: startThread(autostart), numWrappers(0), numFds(0), inPoll(0), stopping(0)
{
memset(portal_fds, 0, sizeof(portal_fds));
memset(portal_wrappers, 0, sizeof(portal_wrappers));
int rc = pipe(pipefd);
if (rc != 0)
fprintf(stderr, "[%s:%d] pipe error %d:%s\n", __FUNCTION__, __LINE__, errno, strerror(errno));
sem_init(&sem_startup, 0, 0);
pthread_mutex_init(&mutex, NULL);
fcntl(pipefd[0], F_SETFL, O_NONBLOCK);
addFd(pipefd[0]);
timeout = -1;
#if defined(SIMULATION)
timeout = 100;
#endif
}
int PortalPoller::unregisterInstance(Portal *portal)
{
int i = 0;
pthread_mutex_lock(&mutex);
while(i < numWrappers){
if(portal_wrappers[i]->pint.fpga_number == portal->pint.fpga_number) {
//fprintf(stderr, "PortalPoller::unregisterInstance %d %d\n", i, portal->pint.fpga_number);
break;
}
i++;
}
while(i < numWrappers-1){
portal_wrappers[i] = portal_wrappers[i+1];
i++;
}
numWrappers--;
i = 0;
while(i < numFds){
if(portal_fds[i].fd == portal->pint.fpga_fd)
break;
i++;
}
while(i < numFds-1){
portal_fds[i] = portal_fds[i+1];
i++;
}
numFds--;
pthread_mutex_unlock(&mutex);
return 0;
}
void PortalPoller::addFd(int fd)
{
/* this internal function assumes mutex locked by caller.
* since it can be called from addFdToPoller(), which was called under mutex lock
* event().
*/
numFds++;
struct pollfd *pollfd = &portal_fds[numFds-1];
memset(pollfd, 0, sizeof(struct pollfd));
pollfd->fd = fd;
pollfd->events = POLLIN;
}
int PortalPoller::registerInstance(Portal *portal)
{
uint8_t ch = 0;
pthread_mutex_lock(&mutex);
int rc = write(pipefd[1], &ch, 1); // get poll to return, so that it will try again with the new file descriptor
if (rc < 0)
fprintf(stderr, "[%s:%d] write error %d\n", __FUNCTION__, __LINE__, errno);
numWrappers++;
if (trace_poller)
fprintf(stderr, "Poller: registerInstance fpga%d fd %d clients %d\n", portal->pint.fpga_number, portal->pint.fpga_fd, portal->pint.client_fd_number);
while(inPoll)
usleep(1000);
portal_wrappers[numWrappers-1] = portal;
if (portal->pint.fpga_fd != -1)
addFd(portal->pint.fpga_fd);
for (int i = 0; i < portal->pint.client_fd_number; i++)
addFd(portal->pint.client_fd[i]);
portal->pint.transport->enableint(&portal->pint, 1);
pthread_mutex_unlock(&mutex);
start();
return 0;
}
void* PortalPoller::init(void)
{
#ifdef SIMULATION
if (global_sockfd != -1) {
pthread_mutex_lock(&mutex);
addFd(global_sockfd);
pthread_mutex_unlock(&mutex);
}
#endif
//fprintf(stderr, "Poller: about to enter loop, numFds=%d\n", numFds);
return NULL;
}
void PortalPoller::stop(void)
{
uint8_t ch = 0;
int rc;
stopping = 1;
startThread = 0;
rc = write(pipefd[1], &ch, 1);
if (rc < 0)
fprintf(stderr, "[%s:%d] write error %d\n", __FUNCTION__, __LINE__, errno);
}
void PortalPoller::end(void)
{
stopping = 1;
fprintf(stderr, "%s: don't disable interrupts when stopping\n", __FUNCTION__);
return;
pthread_mutex_lock(&mutex);
for (int i = 0; i < numWrappers; i++) {
Portal *instance = portal_wrappers[i];
fprintf(stderr, "Poller::disabling interrupts portal %d fpga%d\n", i, instance->pint.fpga_number);
instance->pint.transport->enableint(&instance->pint, 0);
}
pthread_mutex_unlock(&mutex);
}
void* PortalPoller::pollFn(int timeout)
{
long rc = 0;
//printf("[%s:%d] before poll %d numFds %d\n", __FUNCTION__, __LINE__, timeout, numFds);
//for (int i = 0; i < numFds; i++)
//printf("%s: fd %d events %x\n", __FUNCTION__, portal_fds[i].fd, portal_fds[i].events);
inPoll = 1;
if (timeout != 0)
rc = poll(portal_fds, numFds, timeout);
inPoll = 0;
if(rc < 0) {
// return only in error case
fprintf(stderr, "Poller: poll returned rc=%ld errno=%d:%s\n", rc, errno, strerror(errno));
}
return (void*)rc;
}
void* PortalPoller::event(void)
{
uint8_t ch;
pthread_mutex_lock(&mutex);
size_t rc = read(pipefd[0], &ch, 1);
if (rc < 0)
fprintf(stderr, "[%s:%d] read error %d\n", __FUNCTION__, __LINE__, errno);
for (int i = 0; i < numWrappers; i++) {
if (!portal_wrappers)
fprintf(stderr, "Poller: No portal_instances revents=%d\n", portal_fds[i].revents);
Portal *instance = portal_wrappers[i];
if (trace_poller)
fprintf(stderr, "Poller: event tile %d fpga%d fd %d handler %p parent %p\n",
instance->pint.fpga_tile, instance->pint.fpga_number, instance->pint.fpga_fd, instance->pint.handler, instance->pint.parent);
instance->pint.transport->event(&instance->pint);
if (instance->pint.handler) {
// re-enable interrupt which was disabled by portal_isr
instance->pint.transport->enableint(&instance->pint, 1);
}
}
pthread_mutex_unlock(&mutex);
return NULL;
}
extern "C" void addFdToPoller(struct PortalPoller *poller, int fd)
{
poller->addFd(fd);
}
void* PortalPoller::threadFn(void* __x)
{
void *rc = init();
sem_post(&sem_startup);
while (!rc && !stopping) {
rc = pollFn(timeout);
if ((long) rc >= 0)
rc = event();
}
end();
fprintf(stderr, "[%s] thread ending\n", __FUNCTION__);
return rc;
}
static void *pthread_worker(void *__x)
{
((PortalPoller *)__x)->threadFn(__x);
return 0;
}
void PortalPoller::start()
{
pthread_t threaddata;
pthread_mutex_lock(&mutex);
if (!startThread) {
pthread_mutex_unlock(&mutex);
return;
}
startThread = 0;
pthread_mutex_unlock(&mutex);
pthread_create(&threaddata, NULL, &pthread_worker, (void *)this);
sem_wait(&sem_startup);
}
#endif // NO_CPP_PORTAL_CODE
<commit_msg>we do not seem to be getting interrupts on nfsume<commit_after>// Copyright (c) 2012 Nokia, Inc.
// Copyright (c) 2013-2014 Quanta Research Cambridge, 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.
#include "portal.h"
#include "sock_utils.h"
#include <string.h>
#include <poll.h>
#include <errno.h>
#include <pthread.h>
#include <fcntl.h>
static int trace_poller;//=1;
#ifndef NO_CPP_PORTAL_CODE
PortalPoller *defaultPoller = new PortalPoller();
uint64_t poll_enter_time, poll_return_time; // for performance measurement
PortalPoller::PortalPoller(int autostart)
: startThread(autostart), numWrappers(0), numFds(0), inPoll(0), stopping(0)
{
memset(portal_fds, 0, sizeof(portal_fds));
memset(portal_wrappers, 0, sizeof(portal_wrappers));
int rc = pipe(pipefd);
if (rc != 0)
fprintf(stderr, "[%s:%d] pipe error %d:%s\n", __FUNCTION__, __LINE__, errno, strerror(errno));
sem_init(&sem_startup, 0, 0);
pthread_mutex_init(&mutex, NULL);
fcntl(pipefd[0], F_SETFL, O_NONBLOCK);
addFd(pipefd[0]);
timeout = -1;
#if defined(SIMULATION)
timeout = 100;
#endif
#if defined(BOARD_nfsume)
timeout = 100;
#endif
}
int PortalPoller::unregisterInstance(Portal *portal)
{
int i = 0;
pthread_mutex_lock(&mutex);
while(i < numWrappers){
if(portal_wrappers[i]->pint.fpga_number == portal->pint.fpga_number) {
//fprintf(stderr, "PortalPoller::unregisterInstance %d %d\n", i, portal->pint.fpga_number);
break;
}
i++;
}
while(i < numWrappers-1){
portal_wrappers[i] = portal_wrappers[i+1];
i++;
}
numWrappers--;
i = 0;
while(i < numFds){
if(portal_fds[i].fd == portal->pint.fpga_fd)
break;
i++;
}
while(i < numFds-1){
portal_fds[i] = portal_fds[i+1];
i++;
}
numFds--;
pthread_mutex_unlock(&mutex);
return 0;
}
void PortalPoller::addFd(int fd)
{
/* this internal function assumes mutex locked by caller.
* since it can be called from addFdToPoller(), which was called under mutex lock
* event().
*/
numFds++;
struct pollfd *pollfd = &portal_fds[numFds-1];
memset(pollfd, 0, sizeof(struct pollfd));
pollfd->fd = fd;
pollfd->events = POLLIN;
}
int PortalPoller::registerInstance(Portal *portal)
{
uint8_t ch = 0;
pthread_mutex_lock(&mutex);
int rc = write(pipefd[1], &ch, 1); // get poll to return, so that it will try again with the new file descriptor
if (rc < 0)
fprintf(stderr, "[%s:%d] write error %d\n", __FUNCTION__, __LINE__, errno);
numWrappers++;
if (trace_poller)
fprintf(stderr, "Poller: registerInstance fpga%d fd %d clients %d\n", portal->pint.fpga_number, portal->pint.fpga_fd, portal->pint.client_fd_number);
while(inPoll)
usleep(1000);
portal_wrappers[numWrappers-1] = portal;
if (portal->pint.fpga_fd != -1)
addFd(portal->pint.fpga_fd);
for (int i = 0; i < portal->pint.client_fd_number; i++)
addFd(portal->pint.client_fd[i]);
portal->pint.transport->enableint(&portal->pint, 1);
pthread_mutex_unlock(&mutex);
start();
return 0;
}
void* PortalPoller::init(void)
{
#ifdef SIMULATION
if (global_sockfd != -1) {
pthread_mutex_lock(&mutex);
addFd(global_sockfd);
pthread_mutex_unlock(&mutex);
}
#endif
//fprintf(stderr, "Poller: about to enter loop, numFds=%d\n", numFds);
return NULL;
}
void PortalPoller::stop(void)
{
uint8_t ch = 0;
int rc;
stopping = 1;
startThread = 0;
rc = write(pipefd[1], &ch, 1);
if (rc < 0)
fprintf(stderr, "[%s:%d] write error %d\n", __FUNCTION__, __LINE__, errno);
}
void PortalPoller::end(void)
{
stopping = 1;
fprintf(stderr, "%s: don't disable interrupts when stopping\n", __FUNCTION__);
return;
pthread_mutex_lock(&mutex);
for (int i = 0; i < numWrappers; i++) {
Portal *instance = portal_wrappers[i];
fprintf(stderr, "Poller::disabling interrupts portal %d fpga%d\n", i, instance->pint.fpga_number);
instance->pint.transport->enableint(&instance->pint, 0);
}
pthread_mutex_unlock(&mutex);
}
void* PortalPoller::pollFn(int timeout)
{
long rc = 0;
//printf("[%s:%d] before poll %d numFds %d\n", __FUNCTION__, __LINE__, timeout, numFds);
//for (int i = 0; i < numFds; i++)
//printf("%s: fd %d events %x\n", __FUNCTION__, portal_fds[i].fd, portal_fds[i].events);
inPoll = 1;
if (timeout != 0)
rc = poll(portal_fds, numFds, timeout);
inPoll = 0;
if(rc < 0) {
// return only in error case
fprintf(stderr, "Poller: poll returned rc=%ld errno=%d:%s\n", rc, errno, strerror(errno));
}
return (void*)rc;
}
void* PortalPoller::event(void)
{
uint8_t ch;
pthread_mutex_lock(&mutex);
size_t rc = read(pipefd[0], &ch, 1);
if (rc < 0)
fprintf(stderr, "[%s:%d] read error %d\n", __FUNCTION__, __LINE__, errno);
for (int i = 0; i < numWrappers; i++) {
if (!portal_wrappers)
fprintf(stderr, "Poller: No portal_instances revents=%d\n", portal_fds[i].revents);
Portal *instance = portal_wrappers[i];
if (trace_poller)
fprintf(stderr, "Poller: event tile %d fpga%d fd %d handler %p parent %p\n",
instance->pint.fpga_tile, instance->pint.fpga_number, instance->pint.fpga_fd, instance->pint.handler, instance->pint.parent);
instance->pint.transport->event(&instance->pint);
if (instance->pint.handler) {
// re-enable interrupt which was disabled by portal_isr
instance->pint.transport->enableint(&instance->pint, 1);
}
}
pthread_mutex_unlock(&mutex);
return NULL;
}
extern "C" void addFdToPoller(struct PortalPoller *poller, int fd)
{
poller->addFd(fd);
}
void* PortalPoller::threadFn(void* __x)
{
void *rc = init();
sem_post(&sem_startup);
while (!rc && !stopping) {
rc = pollFn(timeout);
if ((long) rc >= 0)
rc = event();
}
end();
fprintf(stderr, "[%s] thread ending\n", __FUNCTION__);
return rc;
}
static void *pthread_worker(void *__x)
{
((PortalPoller *)__x)->threadFn(__x);
return 0;
}
void PortalPoller::start()
{
pthread_t threaddata;
pthread_mutex_lock(&mutex);
if (!startThread) {
pthread_mutex_unlock(&mutex);
return;
}
startThread = 0;
pthread_mutex_unlock(&mutex);
pthread_create(&threaddata, NULL, &pthread_worker, (void *)this);
sem_wait(&sem_startup);
}
#endif // NO_CPP_PORTAL_CODE
<|endoftext|> |
<commit_before>#define GLEW_STATIC
#include <GL/glew.h>
#include <GLFW/glfw3.h>
#define STB_IMAGE_IMPLEMENTATION
#include "stb_image.h" // for .png loading
#include "../../imgui.h"
#ifdef _MSC_VER
#pragma warning (disable: 4996) // 'This function or variable may be unsafe': strcpy, strdup, sprintf, vsnprintf, sscanf, fopen
#endif
static GLFWwindow* window;
static GLuint fontTex;
// This is the main rendering function that you have to implement and provide to ImGui (via setting up 'RenderDrawListsFn' in the ImGuiIO structure)
// If text or lines are blurry when integrating ImGui in your engine:
// - try adjusting ImGui::GetIO().PixelCenterOffset to 0.0f or 0.5f
// - in your Render function, try translating your projection matrix by (0.5f,0.5f) or (0.375f,0.375f)
static void ImImpl_RenderDrawLists(ImDrawList** const cmd_lists, int cmd_lists_count)
{
if (cmd_lists_count == 0)
return;
// We are using the OpenGL fixed pipeline to make the example code simpler to read!
// A probable faster way to render would be to collate all vertices from all cmd_lists into a single vertex buffer.
// Setup render state: alpha-blending enabled, no face culling, no depth testing, scissor enabled, vertex/texcoord/color pointers.
glEnable(GL_BLEND);
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
glDisable(GL_CULL_FACE);
glDisable(GL_DEPTH_TEST);
glEnable(GL_SCISSOR_TEST);
glEnableClientState(GL_VERTEX_ARRAY);
glEnableClientState(GL_TEXTURE_COORD_ARRAY);
glEnableClientState(GL_COLOR_ARRAY);
// Setup texture
glBindTexture(GL_TEXTURE_2D, fontTex);
glEnable(GL_TEXTURE_2D);
// Setup orthographic projection matrix
const float width = ImGui::GetIO().DisplaySize.x;
const float height = ImGui::GetIO().DisplaySize.y;
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
glOrtho(0.0f, width, height, 0.0f, -1.0f, +1.0f);
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
// Render command lists
for (int n = 0; n < cmd_lists_count; n++)
{
const ImDrawList* cmd_list = cmd_lists[n];
const unsigned char* vtx_buffer = (const unsigned char*)cmd_list->vtx_buffer.begin();
glVertexPointer(2, GL_FLOAT, sizeof(ImDrawVert), (void*)(vtx_buffer));
glTexCoordPointer(2, GL_FLOAT, sizeof(ImDrawVert), (void*)(vtx_buffer+8));
glColorPointer(4, GL_UNSIGNED_BYTE, sizeof(ImDrawVert), (void*)(vtx_buffer+16));
int vtx_offset = 0;
const ImDrawCmd* pcmd_end = cmd_list->commands.end();
for (const ImDrawCmd* pcmd = cmd_list->commands.begin(); pcmd != pcmd_end; pcmd++)
{
glScissor((int)pcmd->clip_rect.x, (int)(height - pcmd->clip_rect.w), (int)(pcmd->clip_rect.z - pcmd->clip_rect.x), (int)(pcmd->clip_rect.w - pcmd->clip_rect.y));
glDrawArrays(GL_TRIANGLES, vtx_offset, pcmd->vtx_count);
vtx_offset += pcmd->vtx_count;
}
}
glDisable(GL_SCISSOR_TEST);
glDisableClientState(GL_COLOR_ARRAY);
glDisableClientState(GL_TEXTURE_COORD_ARRAY);
glDisableClientState(GL_VERTEX_ARRAY);
}
static const char* ImImpl_GetClipboardTextFn()
{
return glfwGetClipboardString(window);
}
static void ImImpl_SetClipboardTextFn(const char* text, const char* text_end)
{
if (!text_end)
text_end = text + strlen(text);
if (*text_end == 0)
{
// Already got a zero-terminator at 'text_end', we don't need to add one
glfwSetClipboardString(window, text);
}
else
{
// Add a zero-terminator because glfw function doesn't take a size
char* buf = (char*)malloc(text_end - text + 1);
memcpy(buf, text, text_end-text);
buf[text_end-text] = '\0';
glfwSetClipboardString(window, buf);
free(buf);
}
}
// GLFW callbacks to get events
static void glfw_error_callback(int error, const char* description)
{
fputs(description, stderr);
}
static void glfw_scroll_callback(GLFWwindow* window, double xoffset, double yoffset)
{
ImGuiIO& io = ImGui::GetIO();
io.MouseWheel = (yoffset != 0.0f) ? yoffset > 0.0f ? 1 : - 1 : 0; // Mouse wheel: -1,0,+1
}
static void glfw_key_callback(GLFWwindow* window, int key, int scancode, int action, int mods)
{
ImGuiIO& io = ImGui::GetIO();
if (action == GLFW_PRESS)
io.KeysDown[key] = true;
if (action == GLFW_RELEASE)
io.KeysDown[key] = false;
io.KeyCtrl = (mods & GLFW_MOD_CONTROL) != 0;
io.KeyShift = (mods & GLFW_MOD_SHIFT) != 0;
}
static void glfw_char_callback(GLFWwindow* window, unsigned int c)
{
if (c > 0 && c <= 255)
ImGui::GetIO().AddInputCharacter((char)c);
}
// OpenGL code based on http://open.gl tutorials
void InitGL()
{
glfwSetErrorCallback(glfw_error_callback);
if (!glfwInit())
exit(1);
glfwWindowHint(GLFW_RESIZABLE, GL_FALSE);
window = glfwCreateWindow(1280, 720, "ImGui OpenGL example", NULL, NULL);
glfwMakeContextCurrent(window);
glfwSetKeyCallback(window, glfw_key_callback);
glfwSetScrollCallback(window, glfw_scroll_callback);
glfwSetCharCallback(window, glfw_char_callback);
glewInit();
}
void InitImGui()
{
int w, h;
glfwGetWindowSize(window, &w, &h);
ImGuiIO& io = ImGui::GetIO();
io.DisplaySize = ImVec2((float)w, (float)h); // Display size, in pixels. For clamping windows positions.
io.DeltaTime = 1.0f/60.0f; // Time elapsed since last frame, in seconds (in this sample app we'll override this every frame because our timestep is variable)
io.PixelCenterOffset = 0.5f; // Align OpenGL texels
io.KeyMap[ImGuiKey_Tab] = GLFW_KEY_TAB; // Keyboard mapping. ImGui will use those indices to peek into the io.KeyDown[] array.
io.KeyMap[ImGuiKey_LeftArrow] = GLFW_KEY_LEFT;
io.KeyMap[ImGuiKey_RightArrow] = GLFW_KEY_RIGHT;
io.KeyMap[ImGuiKey_UpArrow] = GLFW_KEY_UP;
io.KeyMap[ImGuiKey_DownArrow] = GLFW_KEY_DOWN;
io.KeyMap[ImGuiKey_Home] = GLFW_KEY_HOME;
io.KeyMap[ImGuiKey_End] = GLFW_KEY_END;
io.KeyMap[ImGuiKey_Delete] = GLFW_KEY_DELETE;
io.KeyMap[ImGuiKey_Backspace] = GLFW_KEY_BACKSPACE;
io.KeyMap[ImGuiKey_Enter] = GLFW_KEY_ENTER;
io.KeyMap[ImGuiKey_Escape] = GLFW_KEY_ESCAPE;
io.KeyMap[ImGuiKey_A] = GLFW_KEY_A;
io.KeyMap[ImGuiKey_C] = GLFW_KEY_C;
io.KeyMap[ImGuiKey_V] = GLFW_KEY_V;
io.KeyMap[ImGuiKey_X] = GLFW_KEY_X;
io.KeyMap[ImGuiKey_Y] = GLFW_KEY_Y;
io.KeyMap[ImGuiKey_Z] = GLFW_KEY_Z;
io.RenderDrawListsFn = ImImpl_RenderDrawLists;
io.SetClipboardTextFn = ImImpl_SetClipboardTextFn;
io.GetClipboardTextFn = ImImpl_GetClipboardTextFn;
// Load font texture
glGenTextures(1, &fontTex);
glBindTexture(GL_TEXTURE_2D, fontTex);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
const void* png_data;
unsigned int png_size;
ImGui::GetDefaultFontData(NULL, NULL, &png_data, &png_size);
int tex_x, tex_y, tex_comp;
void* tex_data = stbi_load_from_memory((const unsigned char*)png_data, (int)png_size, &tex_x, &tex_y, &tex_comp, 0);
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, tex_x, tex_y, 0, GL_RGBA, GL_UNSIGNED_BYTE, tex_data);
stbi_image_free(tex_data);
}
void UpdateImGui()
{
ImGuiIO& io = ImGui::GetIO();
// Setup timestep
static double time = 0.0f;
const double current_time = glfwGetTime();
io.DeltaTime = (float)(current_time - time);
time = current_time;
// Setup inputs
// (we already got mouse wheel, keyboard keys & characters from glfw callbacks polled in glfwPollEvents())
double mouse_x, mouse_y;
glfwGetCursorPos(window, &mouse_x, &mouse_y);
io.MousePos = ImVec2((float)mouse_x, (float)mouse_y); // Mouse position, in pixels (set to -1,-1 if no mouse / on another screen, etc.)
io.MouseDown[0] = glfwGetMouseButton(window, GLFW_MOUSE_BUTTON_LEFT) != 0;
io.MouseDown[1] = glfwGetMouseButton(window, GLFW_MOUSE_BUTTON_RIGHT) != 0;
// Start the frame
ImGui::NewFrame();
}
// Application code
int main(int argc, char** argv)
{
InitGL();
InitImGui();
while (!glfwWindowShouldClose(window))
{
ImGuiIO& io = ImGui::GetIO();
io.MouseWheel = 0;
glfwPollEvents();
UpdateImGui();
// Create a simple window
// Tip: if we don't call ImGui::Begin()/ImGui::End() the widgets appears in a window automatically called "Debug"
static bool show_test_window = true;
static bool show_another_window = false;
static float f;
ImGui::Text("Hello, world!");
ImGui::SliderFloat("float", &f, 0.0f, 1.0f);
show_test_window ^= ImGui::Button("Test Window");
show_another_window ^= ImGui::Button("Another Window");
// Calculate and show framerate
static float ms_per_frame[120] = { 0 };
static int ms_per_frame_idx = 0;
static float ms_per_frame_accum = 0.0f;
ms_per_frame_accum -= ms_per_frame[ms_per_frame_idx];
ms_per_frame[ms_per_frame_idx] = ImGui::GetIO().DeltaTime * 1000.0f;
ms_per_frame_accum += ms_per_frame[ms_per_frame_idx];
ms_per_frame_idx = (ms_per_frame_idx + 1) % 120;
const float ms_per_frame_avg = ms_per_frame_accum / 120;
ImGui::Text("Application average %.3f ms/frame (%.1f FPS)", ms_per_frame_avg, 1000.0f / ms_per_frame_avg);
// Show the ImGui test window
// Most of user example code is in ImGui::ShowTestWindow()
if (show_test_window)
{
ImGui::SetNewWindowDefaultPos(ImVec2(650, 20)); // Normally user code doesn't need/want to call it because positions are saved in .ini file anyway. Here we just want to make the demo initial state a bit more friendly!
ImGui::ShowTestWindow(&show_test_window);
}
// Show another simple window
if (show_another_window)
{
ImGui::Begin("Another Window", &show_another_window, ImVec2(200,100));
ImGui::Text("Hello");
ImGui::End();
}
// Rendering
glViewport(0, 0, (int)io.DisplaySize.x, (int)io.DisplaySize.y);
glClearColor(0.8f, 0.6f, 0.6f, 1.0f);
glClear(GL_COLOR_BUFFER_BIT);
ImGui::Render();
glfwSwapBuffers(window);
}
ImGui::Shutdown();
glfwTerminate();
return 0;
}
<commit_msg>Minor text alignment<commit_after>#define GLEW_STATIC
#include <GL/glew.h>
#include <GLFW/glfw3.h>
#define STB_IMAGE_IMPLEMENTATION
#include "stb_image.h" // for .png loading
#include "../../imgui.h"
#ifdef _MSC_VER
#pragma warning (disable: 4996) // 'This function or variable may be unsafe': strcpy, strdup, sprintf, vsnprintf, sscanf, fopen
#endif
static GLFWwindow* window;
static GLuint fontTex;
// This is the main rendering function that you have to implement and provide to ImGui (via setting up 'RenderDrawListsFn' in the ImGuiIO structure)
// If text or lines are blurry when integrating ImGui in your engine:
// - try adjusting ImGui::GetIO().PixelCenterOffset to 0.0f or 0.5f
// - in your Render function, try translating your projection matrix by (0.5f,0.5f) or (0.375f,0.375f)
static void ImImpl_RenderDrawLists(ImDrawList** const cmd_lists, int cmd_lists_count)
{
if (cmd_lists_count == 0)
return;
// We are using the OpenGL fixed pipeline to make the example code simpler to read!
// A probable faster way to render would be to collate all vertices from all cmd_lists into a single vertex buffer.
// Setup render state: alpha-blending enabled, no face culling, no depth testing, scissor enabled, vertex/texcoord/color pointers.
glEnable(GL_BLEND);
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
glDisable(GL_CULL_FACE);
glDisable(GL_DEPTH_TEST);
glEnable(GL_SCISSOR_TEST);
glEnableClientState(GL_VERTEX_ARRAY);
glEnableClientState(GL_TEXTURE_COORD_ARRAY);
glEnableClientState(GL_COLOR_ARRAY);
// Setup texture
glBindTexture(GL_TEXTURE_2D, fontTex);
glEnable(GL_TEXTURE_2D);
// Setup orthographic projection matrix
const float width = ImGui::GetIO().DisplaySize.x;
const float height = ImGui::GetIO().DisplaySize.y;
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
glOrtho(0.0f, width, height, 0.0f, -1.0f, +1.0f);
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
// Render command lists
for (int n = 0; n < cmd_lists_count; n++)
{
const ImDrawList* cmd_list = cmd_lists[n];
const unsigned char* vtx_buffer = (const unsigned char*)cmd_list->vtx_buffer.begin();
glVertexPointer(2, GL_FLOAT, sizeof(ImDrawVert), (void*)(vtx_buffer));
glTexCoordPointer(2, GL_FLOAT, sizeof(ImDrawVert), (void*)(vtx_buffer+8));
glColorPointer(4, GL_UNSIGNED_BYTE, sizeof(ImDrawVert), (void*)(vtx_buffer+16));
int vtx_offset = 0;
const ImDrawCmd* pcmd_end = cmd_list->commands.end();
for (const ImDrawCmd* pcmd = cmd_list->commands.begin(); pcmd != pcmd_end; pcmd++)
{
glScissor((int)pcmd->clip_rect.x, (int)(height - pcmd->clip_rect.w), (int)(pcmd->clip_rect.z - pcmd->clip_rect.x), (int)(pcmd->clip_rect.w - pcmd->clip_rect.y));
glDrawArrays(GL_TRIANGLES, vtx_offset, pcmd->vtx_count);
vtx_offset += pcmd->vtx_count;
}
}
glDisable(GL_SCISSOR_TEST);
glDisableClientState(GL_COLOR_ARRAY);
glDisableClientState(GL_TEXTURE_COORD_ARRAY);
glDisableClientState(GL_VERTEX_ARRAY);
}
static const char* ImImpl_GetClipboardTextFn()
{
return glfwGetClipboardString(window);
}
static void ImImpl_SetClipboardTextFn(const char* text, const char* text_end)
{
if (!text_end)
text_end = text + strlen(text);
if (*text_end == 0)
{
// Already got a zero-terminator at 'text_end', we don't need to add one
glfwSetClipboardString(window, text);
}
else
{
// Add a zero-terminator because glfw function doesn't take a size
char* buf = (char*)malloc(text_end - text + 1);
memcpy(buf, text, text_end-text);
buf[text_end-text] = '\0';
glfwSetClipboardString(window, buf);
free(buf);
}
}
// GLFW callbacks to get events
static void glfw_error_callback(int error, const char* description)
{
fputs(description, stderr);
}
static void glfw_scroll_callback(GLFWwindow* window, double xoffset, double yoffset)
{
ImGuiIO& io = ImGui::GetIO();
io.MouseWheel = (yoffset != 0.0f) ? yoffset > 0.0f ? 1 : - 1 : 0; // Mouse wheel: -1,0,+1
}
static void glfw_key_callback(GLFWwindow* window, int key, int scancode, int action, int mods)
{
ImGuiIO& io = ImGui::GetIO();
if (action == GLFW_PRESS)
io.KeysDown[key] = true;
if (action == GLFW_RELEASE)
io.KeysDown[key] = false;
io.KeyCtrl = (mods & GLFW_MOD_CONTROL) != 0;
io.KeyShift = (mods & GLFW_MOD_SHIFT) != 0;
}
static void glfw_char_callback(GLFWwindow* window, unsigned int c)
{
if (c > 0 && c <= 255)
ImGui::GetIO().AddInputCharacter((char)c);
}
// OpenGL code based on http://open.gl tutorials
void InitGL()
{
glfwSetErrorCallback(glfw_error_callback);
if (!glfwInit())
exit(1);
glfwWindowHint(GLFW_RESIZABLE, GL_FALSE);
window = glfwCreateWindow(1280, 720, "ImGui OpenGL example", NULL, NULL);
glfwMakeContextCurrent(window);
glfwSetKeyCallback(window, glfw_key_callback);
glfwSetScrollCallback(window, glfw_scroll_callback);
glfwSetCharCallback(window, glfw_char_callback);
glewInit();
}
void InitImGui()
{
int w, h;
glfwGetWindowSize(window, &w, &h);
ImGuiIO& io = ImGui::GetIO();
io.DisplaySize = ImVec2((float)w, (float)h); // Display size, in pixels. For clamping windows positions.
io.DeltaTime = 1.0f/60.0f; // Time elapsed since last frame, in seconds (in this sample app we'll override this every frame because our timestep is variable)
io.PixelCenterOffset = 0.5f; // Align OpenGL texels
io.KeyMap[ImGuiKey_Tab] = GLFW_KEY_TAB; // Keyboard mapping. ImGui will use those indices to peek into the io.KeyDown[] array.
io.KeyMap[ImGuiKey_LeftArrow] = GLFW_KEY_LEFT;
io.KeyMap[ImGuiKey_RightArrow] = GLFW_KEY_RIGHT;
io.KeyMap[ImGuiKey_UpArrow] = GLFW_KEY_UP;
io.KeyMap[ImGuiKey_DownArrow] = GLFW_KEY_DOWN;
io.KeyMap[ImGuiKey_Home] = GLFW_KEY_HOME;
io.KeyMap[ImGuiKey_End] = GLFW_KEY_END;
io.KeyMap[ImGuiKey_Delete] = GLFW_KEY_DELETE;
io.KeyMap[ImGuiKey_Backspace] = GLFW_KEY_BACKSPACE;
io.KeyMap[ImGuiKey_Enter] = GLFW_KEY_ENTER;
io.KeyMap[ImGuiKey_Escape] = GLFW_KEY_ESCAPE;
io.KeyMap[ImGuiKey_A] = GLFW_KEY_A;
io.KeyMap[ImGuiKey_C] = GLFW_KEY_C;
io.KeyMap[ImGuiKey_V] = GLFW_KEY_V;
io.KeyMap[ImGuiKey_X] = GLFW_KEY_X;
io.KeyMap[ImGuiKey_Y] = GLFW_KEY_Y;
io.KeyMap[ImGuiKey_Z] = GLFW_KEY_Z;
io.RenderDrawListsFn = ImImpl_RenderDrawLists;
io.SetClipboardTextFn = ImImpl_SetClipboardTextFn;
io.GetClipboardTextFn = ImImpl_GetClipboardTextFn;
// Load font texture
glGenTextures(1, &fontTex);
glBindTexture(GL_TEXTURE_2D, fontTex);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
const void* png_data;
unsigned int png_size;
ImGui::GetDefaultFontData(NULL, NULL, &png_data, &png_size);
int tex_x, tex_y, tex_comp;
void* tex_data = stbi_load_from_memory((const unsigned char*)png_data, (int)png_size, &tex_x, &tex_y, &tex_comp, 0);
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, tex_x, tex_y, 0, GL_RGBA, GL_UNSIGNED_BYTE, tex_data);
stbi_image_free(tex_data);
}
void UpdateImGui()
{
ImGuiIO& io = ImGui::GetIO();
// Setup timestep
static double time = 0.0f;
const double current_time = glfwGetTime();
io.DeltaTime = (float)(current_time - time);
time = current_time;
// Setup inputs
// (we already got mouse wheel, keyboard keys & characters from glfw callbacks polled in glfwPollEvents())
double mouse_x, mouse_y;
glfwGetCursorPos(window, &mouse_x, &mouse_y);
io.MousePos = ImVec2((float)mouse_x, (float)mouse_y); // Mouse position, in pixels (set to -1,-1 if no mouse / on another screen, etc.)
io.MouseDown[0] = glfwGetMouseButton(window, GLFW_MOUSE_BUTTON_LEFT) != 0;
io.MouseDown[1] = glfwGetMouseButton(window, GLFW_MOUSE_BUTTON_RIGHT) != 0;
// Start the frame
ImGui::NewFrame();
}
// Application code
int main(int argc, char** argv)
{
InitGL();
InitImGui();
while (!glfwWindowShouldClose(window))
{
ImGuiIO& io = ImGui::GetIO();
io.MouseWheel = 0;
glfwPollEvents();
UpdateImGui();
// Create a simple window
// Tip: if we don't call ImGui::Begin()/ImGui::End() the widgets appears in a window automatically called "Debug"
static bool show_test_window = true;
static bool show_another_window = false;
static float f;
ImGui::Text("Hello, world!");
ImGui::SliderFloat("float", &f, 0.0f, 1.0f);
show_test_window ^= ImGui::Button("Test Window");
show_another_window ^= ImGui::Button("Another Window");
// Calculate and show framerate
static float ms_per_frame[120] = { 0 };
static int ms_per_frame_idx = 0;
static float ms_per_frame_accum = 0.0f;
ms_per_frame_accum -= ms_per_frame[ms_per_frame_idx];
ms_per_frame[ms_per_frame_idx] = ImGui::GetIO().DeltaTime * 1000.0f;
ms_per_frame_accum += ms_per_frame[ms_per_frame_idx];
ms_per_frame_idx = (ms_per_frame_idx + 1) % 120;
const float ms_per_frame_avg = ms_per_frame_accum / 120;
ImGui::Text("Application average %.3f ms/frame (%.1f FPS)", ms_per_frame_avg, 1000.0f / ms_per_frame_avg);
// Show the ImGui test window
// Most of user example code is in ImGui::ShowTestWindow()
if (show_test_window)
{
ImGui::SetNewWindowDefaultPos(ImVec2(650, 20)); // Normally user code doesn't need/want to call it because positions are saved in .ini file anyway. Here we just want to make the demo initial state a bit more friendly!
ImGui::ShowTestWindow(&show_test_window);
}
// Show another simple window
if (show_another_window)
{
ImGui::Begin("Another Window", &show_another_window, ImVec2(200,100));
ImGui::Text("Hello");
ImGui::End();
}
// Rendering
glViewport(0, 0, (int)io.DisplaySize.x, (int)io.DisplaySize.y);
glClearColor(0.8f, 0.6f, 0.6f, 1.0f);
glClear(GL_COLOR_BUFFER_BIT);
ImGui::Render();
glfwSwapBuffers(window);
}
ImGui::Shutdown();
glfwTerminate();
return 0;
}
<|endoftext|> |
<commit_before>/* Copyright (C) 2008 The goocanvasmm Development Team
*
* 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., 675 Mass Ave, Cambridge, MA 02139, USA.
*/
#include "examplewindow.h"
#include <cairomm/cairomm.h>
#include <iostream>
ExampleWindow::ExampleWindow()
{
set_title("goocanvasmm - Simple Example");
m_canvas.set_size_request(640, 480);
m_canvas.set_bounds(0, 0, 1000, 1000);
auto root = m_canvas.get_root_item();
auto rect = Goocanvas::Rect::create(100, 100, 400, 400);
root->add_child(rect);
#ifdef GLIBMM_PROPERTIES_ENABLED
rect->property_line_width() = 10.0;
rect->property_radius_x() = 20.0;
rect->property_radius_y() = 20.0;
rect->property_stroke_color() = "yellow";
rect->property_fill_color() = "red";
#else
rect->set_property("line_width", 10.0);
rect->set_property("radius_x", 20.0);
rect->set_property("radius_y", 20.0);
rect->set_property("stroke_color", Glib::ustring("yellow"));
rect->set_property("fill_color", Glib::ustring("red"));
#endif //GLIBMM_PROPERTIES_ENABLED
rect->signal_button_press_event ().connect (sigc::mem_fun (this,
&ExampleWindow::on_rect_button_press));
auto text = Goocanvas::Text::create("Hello World", 300, 300, -1, Goocanvas::ANCHOR_CENTER);
root->add_child(text);
#ifdef GLIBMM_PROPERTIES_ENABLED
text->property_font() = "Sans 24";
#else
text->set_property("font=", Glib::ustring("Sans 24"));
#endif //GLIBMM_PROPERTIES_ENABLED
text->rotate(45, 300, 300);
auto sw = Gtk::manage(new Gtk::ScrolledWindow());
sw->add(m_canvas);
add(*sw);
show_all_children();
}
bool
ExampleWindow::on_rect_button_press(const Glib::RefPtr<Goocanvas::Item>& /* item */, GdkEventButton* /* event */)
{
std::cout << "You clicked the rectangle." << std::endl ;
return true ;
}
<commit_msg>Use the newer sigc::mem_fun() syntax.<commit_after>/* Copyright (C) 2008 The goocanvasmm Development Team
*
* 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., 675 Mass Ave, Cambridge, MA 02139, USA.
*/
#include "examplewindow.h"
#include <cairomm/cairomm.h>
#include <iostream>
ExampleWindow::ExampleWindow()
{
set_title("goocanvasmm - Simple Example");
m_canvas.set_size_request(640, 480);
m_canvas.set_bounds(0, 0, 1000, 1000);
auto root = m_canvas.get_root_item();
auto rect = Goocanvas::Rect::create(100, 100, 400, 400);
root->add_child(rect);
#ifdef GLIBMM_PROPERTIES_ENABLED
rect->property_line_width() = 10.0;
rect->property_radius_x() = 20.0;
rect->property_radius_y() = 20.0;
rect->property_stroke_color() = "yellow";
rect->property_fill_color() = "red";
#else
rect->set_property("line_width", 10.0);
rect->set_property("radius_x", 20.0);
rect->set_property("radius_y", 20.0);
rect->set_property("stroke_color", Glib::ustring("yellow"));
rect->set_property("fill_color", Glib::ustring("red"));
#endif //GLIBMM_PROPERTIES_ENABLED
rect->signal_button_press_event ().connect (sigc::mem_fun(*this,
&ExampleWindow::on_rect_button_press));
auto text = Goocanvas::Text::create("Hello World", 300, 300, -1, Goocanvas::ANCHOR_CENTER);
root->add_child(text);
#ifdef GLIBMM_PROPERTIES_ENABLED
text->property_font() = "Sans 24";
#else
text->set_property("font=", Glib::ustring("Sans 24"));
#endif //GLIBMM_PROPERTIES_ENABLED
text->rotate(45, 300, 300);
auto sw = Gtk::manage(new Gtk::ScrolledWindow());
sw->add(m_canvas);
add(*sw);
show_all_children();
}
bool
ExampleWindow::on_rect_button_press(const Glib::RefPtr<Goocanvas::Item>& /* item */, GdkEventButton* /* event */)
{
std::cout << "You clicked the rectangle." << std::endl ;
return true ;
}
<|endoftext|> |
<commit_before>/*
* This program is just for personal experiments here on AVR features and C++ stuff
* to check compilation and link of FastArduino port and pin API.
* It does not do anything interesting as far as hardware is concerned.
*/
// Imperial march tones thanks:
// http://processors.wiki.ti.com/index.php/Playing_The_Imperial_March
// Example of square wave generation, using CTC mode and COM toggle
#include <fastarduino/time.h>
#include <fastarduino/devices/tone_player.h>
// Board-dependent settings
// static constexpr const board::Timer NTIMER = board::Timer::TIMER1;
// static constexpr const board::DigitalPin OUTPUT = board::PWMPin::D9_PB1_OC1A;
static constexpr const board::Timer NTIMER = board::Timer::TIMER0;
static constexpr const board::DigitalPin OUTPUT = board::PWMPin::D6_PD6_OC0A;
using devices::audio::Tone;
using namespace devices::audio::SpecialTone;
using GENERATOR = devices::audio::ToneGenerator<NTIMER, OUTPUT>;
using PLAYER = devices::audio::TonePlayer<NTIMER, OUTPUT>;
using QTONEPLAY = PLAYER::QTonePlay;
static QTONEPLAY music[] =
{
// First part
QTONEPLAY{Tone::A1, 500},
QTONEPLAY{Tone::A1, 500},
QTONEPLAY{Tone::A1, 500},
QTONEPLAY{Tone::F1, 350},
QTONEPLAY{Tone::C2, 150},
QTONEPLAY{Tone::A1, 500},
QTONEPLAY{Tone::F1, 350},
QTONEPLAY{Tone::C2, 150},
QTONEPLAY{Tone::A1, 650},
QTONEPLAY{Tone::SILENCE, 150},
// Second part
QTONEPLAY{Tone::E2, 500},
QTONEPLAY{Tone::E2, 500},
QTONEPLAY{Tone::E2, 500},
QTONEPLAY{Tone::F2, 350},
QTONEPLAY{Tone::C2, 150},
QTONEPLAY{Tone::Gs1, 500},
QTONEPLAY{Tone::F1, 350},
QTONEPLAY{Tone::C2, 150},
QTONEPLAY{Tone::A1, 650},
QTONEPLAY{Tone::SILENCE, 150},
// Third part (repeated once)
QTONEPLAY{REPEAT_START},
QTONEPLAY{Tone::A2, 500},
QTONEPLAY{Tone::A1, 300},
QTONEPLAY{Tone::A1, 150},
QTONEPLAY{Tone::A2, 400},
QTONEPLAY{Tone::Gs2, 200},
QTONEPLAY{Tone::G2, 200},
QTONEPLAY{Tone::Fs2, 125},
QTONEPLAY{Tone::F2, 125},
QTONEPLAY{Tone::Fs2, 250},
QTONEPLAY{Tone::SILENCE, 250},
QTONEPLAY{Tone::As1, 250},
QTONEPLAY{Tone::Ds2, 400},
QTONEPLAY{Tone::D2, 200},
QTONEPLAY{Tone::Cs2, 200},
QTONEPLAY{Tone::C2, 125},
QTONEPLAY{Tone::B1, 125},
QTONEPLAY{Tone::C2, 250},
QTONEPLAY{Tone::SILENCE, 250},
QTONEPLAY{Tone::F1, 125},
QTONEPLAY{Tone::Gs1, 500},
QTONEPLAY{Tone::F1, 375},
QTONEPLAY{Tone::A1, 125},
QTONEPLAY{Tone::C2, 500},
QTONEPLAY{Tone::A1, 375},
QTONEPLAY{Tone::C2, 125},
QTONEPLAY{Tone::E2, 650},
QTONEPLAY{Tone::SILENCE, 250},
QTONEPLAY{REPEAT_END, 1},
QTONEPLAY{END, 0}
};
int main() __attribute__((OS_main));
int main()
{
sei();
time::delay_ms(5000);
GENERATOR generator;
PLAYER player{generator};
player.play(music);
}
<commit_msg>Update example comments.<commit_after>// Copyright 2016-2018 Jean-Francois Poilpret
//
// 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.
/*
* Frequency generator example, used to play the Imperial March.
*
* Wiring:
* - on Arduino UNO and Arduino MEGA:
* - D6: connect to a 5V piezo buzzer with the othe lead connected to ground
*/
// Imperial march tones thanks:
// http://processors.wiki.ti.com/index.php/Playing_The_Imperial_March
// Example of square wave generation, using CTC mode and COM toggle
#include <fastarduino/time.h>
#include <fastarduino/devices/tone_player.h>
// Board-dependent settings
// static constexpr const board::Timer NTIMER = board::Timer::TIMER1;
// static constexpr const board::DigitalPin OUTPUT = board::PWMPin::D9_PB1_OC1A;
static constexpr const board::Timer NTIMER = board::Timer::TIMER0;
static constexpr const board::DigitalPin OUTPUT = board::PWMPin::D6_PD6_OC0A;
using devices::audio::Tone;
using namespace devices::audio::SpecialTone;
using GENERATOR = devices::audio::ToneGenerator<NTIMER, OUTPUT>;
using PLAYER = devices::audio::TonePlayer<NTIMER, OUTPUT>;
using QTONEPLAY = PLAYER::QTonePlay;
static QTONEPLAY music[] =
{
// First part
QTONEPLAY{Tone::A1, 500},
QTONEPLAY{Tone::A1, 500},
QTONEPLAY{Tone::A1, 500},
QTONEPLAY{Tone::F1, 350},
QTONEPLAY{Tone::C2, 150},
QTONEPLAY{Tone::A1, 500},
QTONEPLAY{Tone::F1, 350},
QTONEPLAY{Tone::C2, 150},
QTONEPLAY{Tone::A1, 650},
QTONEPLAY{Tone::SILENCE, 150},
// Second part
QTONEPLAY{Tone::E2, 500},
QTONEPLAY{Tone::E2, 500},
QTONEPLAY{Tone::E2, 500},
QTONEPLAY{Tone::F2, 350},
QTONEPLAY{Tone::C2, 150},
QTONEPLAY{Tone::Gs1, 500},
QTONEPLAY{Tone::F1, 350},
QTONEPLAY{Tone::C2, 150},
QTONEPLAY{Tone::A1, 650},
QTONEPLAY{Tone::SILENCE, 150},
// Third part (repeated once)
QTONEPLAY{REPEAT_START},
QTONEPLAY{Tone::A2, 500},
QTONEPLAY{Tone::A1, 300},
QTONEPLAY{Tone::A1, 150},
QTONEPLAY{Tone::A2, 400},
QTONEPLAY{Tone::Gs2, 200},
QTONEPLAY{Tone::G2, 200},
QTONEPLAY{Tone::Fs2, 125},
QTONEPLAY{Tone::F2, 125},
QTONEPLAY{Tone::Fs2, 250},
QTONEPLAY{Tone::SILENCE, 250},
QTONEPLAY{Tone::As1, 250},
QTONEPLAY{Tone::Ds2, 400},
QTONEPLAY{Tone::D2, 200},
QTONEPLAY{Tone::Cs2, 200},
QTONEPLAY{Tone::C2, 125},
QTONEPLAY{Tone::B1, 125},
QTONEPLAY{Tone::C2, 250},
QTONEPLAY{Tone::SILENCE, 250},
QTONEPLAY{Tone::F1, 125},
QTONEPLAY{Tone::Gs1, 500},
QTONEPLAY{Tone::F1, 375},
QTONEPLAY{Tone::A1, 125},
QTONEPLAY{Tone::C2, 500},
QTONEPLAY{Tone::A1, 375},
QTONEPLAY{Tone::C2, 125},
QTONEPLAY{Tone::E2, 650},
QTONEPLAY{Tone::SILENCE, 250},
QTONEPLAY{REPEAT_END, 1},
QTONEPLAY{END, 0}
};
int main() __attribute__((OS_main));
int main()
{
sei();
time::delay_ms(5000);
GENERATOR generator;
PLAYER player{generator};
player.play(music);
}
<|endoftext|> |
<commit_before>/**
* \file
* \brief semaphoreTestCases object definition
*
* \author Copyright (C) 2014 Kamil Szczygiel http://www.distortec.com http://www.freddiechopin.info
*
* \par License
* This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0. If a copy of the MPL was not
* distributed with this file, You can obtain one at http://mozilla.org/MPL/2.0/.
*
* \date 2014-11-19
*/
#include "semaphoreTestCases.hpp"
#include "SemaphorePriorityTestCase.hpp"
namespace distortos
{
namespace test
{
namespace
{
/*---------------------------------------------------------------------------------------------------------------------+
| local objects
+---------------------------------------------------------------------------------------------------------------------*/
/// SemaphorePriorityTestCase::Implementation instance
const SemaphorePriorityTestCase::Implementation priorityTestCaseImplementation;
/// SemaphorePriorityTestCase instance
const SemaphorePriorityTestCase priorityTestCase {priorityTestCaseImplementation};
/// array with references to TestCase objects related to semaphores
const TestCaseRange::value_type semaphoreTestCases_[]
{
TestCaseRange::value_type{priorityTestCase},
};
} // namespace
/*---------------------------------------------------------------------------------------------------------------------+
| global objects
+---------------------------------------------------------------------------------------------------------------------*/
const TestCaseRange semaphoreTestCases {semaphoreTestCases_};
} // namespace test
} // namespace distortos
<commit_msg>test: add SemaphoreOperationsTestCase to executed test cases<commit_after>/**
* \file
* \brief semaphoreTestCases object definition
*
* \author Copyright (C) 2014 Kamil Szczygiel http://www.distortec.com http://www.freddiechopin.info
*
* \par License
* This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0. If a copy of the MPL was not
* distributed with this file, You can obtain one at http://mozilla.org/MPL/2.0/.
*
* \date 2014-11-19
*/
#include "semaphoreTestCases.hpp"
#include "SemaphorePriorityTestCase.hpp"
#include "SemaphoreOperationsTestCase.hpp"
namespace distortos
{
namespace test
{
namespace
{
/*---------------------------------------------------------------------------------------------------------------------+
| local objects
+---------------------------------------------------------------------------------------------------------------------*/
/// SemaphorePriorityTestCase::Implementation instance
const SemaphorePriorityTestCase::Implementation priorityTestCaseImplementation;
/// SemaphorePriorityTestCase instance
const SemaphorePriorityTestCase priorityTestCase {priorityTestCaseImplementation};
/// SemaphoreOperationsTestCase instance
const SemaphoreOperationsTestCase operationsTestCase;
/// array with references to TestCase objects related to semaphores
const TestCaseRange::value_type semaphoreTestCases_[]
{
TestCaseRange::value_type{priorityTestCase},
TestCaseRange::value_type{operationsTestCase},
};
} // namespace
/*---------------------------------------------------------------------------------------------------------------------+
| global objects
+---------------------------------------------------------------------------------------------------------------------*/
const TestCaseRange semaphoreTestCases {semaphoreTestCases_};
} // namespace test
} // namespace distortos
<|endoftext|> |
<commit_before>/*
*
* Copyright 2015, Google Inc.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following disclaimer
* in the documentation and/or other materials provided with the
* distribution.
* * Neither the name of Google Inc. nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
*/
#include <thread>
#include "test/core/util/port.h"
#include "test/core/util/test_config.h"
#include "test/cpp/util/echo_duplicate.grpc.pb.h"
#include "test/cpp/util/echo.grpc.pb.h"
#include "src/cpp/server/thread_pool.h"
#include <grpc++/channel_arguments.h>
#include <grpc++/channel_interface.h>
#include <grpc++/client_context.h>
#include <grpc++/create_channel.h>
#include <grpc++/credentials.h>
#include <grpc++/server.h>
#include <grpc++/server_builder.h>
#include <grpc++/server_context.h>
#include <grpc++/server_credentials.h>
#include <grpc++/status.h>
#include <grpc++/stream.h>
#include <grpc++/time.h>
#include <gtest/gtest.h>
#include <grpc/grpc.h>
#include <grpc/support/thd.h>
#include <grpc/support/time.h>
#include "test/cpp/util/subprocess.h"
using grpc::cpp::test::util::EchoRequest;
using grpc::cpp::test::util::EchoResponse;
using std::chrono::system_clock;
static std::string g_root;
namespace grpc {
namespace testing {
namespace {
class CrashTest : public ::testing::Test {
protected:
CrashTest() {}
std::unique_ptr<grpc::cpp::test::util::TestService::Stub>
CreateServerAndStub() {
auto port = grpc_pick_unused_port_or_die();
std::ostringstream addr_stream;
addr_stream << "localhost:" << port;
auto addr = addr_stream.str();
server_.reset(new SubProcess({
g_root + "/client_crash_test_server",
"--address=" + addr,
}));
GPR_ASSERT(server_);
return grpc::cpp::test::util::TestService::NewStub(
CreateChannel(addr, InsecureCredentials(), ChannelArguments()));
}
void KillServer() {
server_.reset();
// give some time for the TCP connection to drop
gpr_sleep_until(gpr_time_add(gpr_now(), gpr_time_from_seconds(1)));
}
private:
std::unique_ptr<SubProcess> server_;
};
TEST_F(CrashTest, KillAfterWrite) {
auto stub = CreateServerAndStub();
EchoRequest request;
EchoResponse response;
ClientContext context;
auto stream = stub->BidiStream(&context);
request.set_message("Hello");
EXPECT_TRUE(stream->Write(request));
EXPECT_TRUE(stream->Read(&response));
EXPECT_EQ(response.message(), request.message());
request.set_message("I'm going to kill you");
EXPECT_TRUE(stream->Write(request));
KillServer();
EXPECT_FALSE(stream->Read(&response));
EXPECT_FALSE(stream->Finish().IsOk());
}
TEST_F(CrashTest, KillBeforeWrite) {
auto stub = CreateServerAndStub();
EchoRequest request;
EchoResponse response;
ClientContext context;
auto stream = stub->BidiStream(&context);
request.set_message("Hello");
EXPECT_TRUE(stream->Write(request));
EXPECT_TRUE(stream->Read(&response));
EXPECT_EQ(response.message(), request.message());
KillServer();
request.set_message("You should be dead");
EXPECT_FALSE(stream->Write(request));
EXPECT_FALSE(stream->Read(&response));
EXPECT_FALSE(stream->Finish().IsOk());
}
} // namespace
} // namespace testing
} // namespace grpc
int main(int argc, char** argv) {
std::string me = argv[0];
auto lslash = me.rfind('/');
if (lslash != std::string::npos) {
g_root = me.substr(0, lslash);
} else {
g_root = ".";
}
grpc_test_init(argc, argv);
::testing::InitGoogleTest(&argc, argv);
return RUN_ALL_TESTS();
}
<commit_msg>Make test more robust<commit_after>/*
*
* Copyright 2015, Google Inc.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following disclaimer
* in the documentation and/or other materials provided with the
* distribution.
* * Neither the name of Google Inc. nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
*/
#include <thread>
#include "test/core/util/port.h"
#include "test/core/util/test_config.h"
#include "test/cpp/util/echo_duplicate.grpc.pb.h"
#include "test/cpp/util/echo.grpc.pb.h"
#include "src/cpp/server/thread_pool.h"
#include <grpc++/channel_arguments.h>
#include <grpc++/channel_interface.h>
#include <grpc++/client_context.h>
#include <grpc++/create_channel.h>
#include <grpc++/credentials.h>
#include <grpc++/server.h>
#include <grpc++/server_builder.h>
#include <grpc++/server_context.h>
#include <grpc++/server_credentials.h>
#include <grpc++/status.h>
#include <grpc++/stream.h>
#include <grpc++/time.h>
#include <gtest/gtest.h>
#include <grpc/grpc.h>
#include <grpc/support/thd.h>
#include <grpc/support/time.h>
#include "test/cpp/util/subprocess.h"
using grpc::cpp::test::util::EchoRequest;
using grpc::cpp::test::util::EchoResponse;
using std::chrono::system_clock;
static std::string g_root;
namespace grpc {
namespace testing {
namespace {
class CrashTest : public ::testing::Test {
protected:
CrashTest() {}
std::unique_ptr<grpc::cpp::test::util::TestService::Stub>
CreateServerAndStub() {
auto port = grpc_pick_unused_port_or_die();
std::ostringstream addr_stream;
addr_stream << "localhost:" << port;
auto addr = addr_stream.str();
server_.reset(new SubProcess({
g_root + "/client_crash_test_server",
"--address=" + addr,
}));
GPR_ASSERT(server_);
return grpc::cpp::test::util::TestService::NewStub(
CreateChannel(addr, InsecureCredentials(), ChannelArguments()));
}
void KillServer() {
server_.reset();
}
private:
std::unique_ptr<SubProcess> server_;
};
TEST_F(CrashTest, KillBeforeWrite) {
auto stub = CreateServerAndStub();
EchoRequest request;
EchoResponse response;
ClientContext context;
auto stream = stub->BidiStream(&context);
request.set_message("Hello");
EXPECT_TRUE(stream->Write(request));
EXPECT_TRUE(stream->Read(&response));
EXPECT_EQ(response.message(), request.message());
KillServer();
request.set_message("You should be dead");
// This may succeed or fail depending on the state of the TCP connection
stream->Write(request);
// But the read will definitely fail
EXPECT_FALSE(stream->Read(&response));
EXPECT_FALSE(stream->Finish().IsOk());
}
TEST_F(CrashTest, KillAfterWrite) {
auto stub = CreateServerAndStub();
EchoRequest request;
EchoResponse response;
ClientContext context;
auto stream = stub->BidiStream(&context);
request.set_message("Hello");
EXPECT_TRUE(stream->Write(request));
EXPECT_TRUE(stream->Read(&response));
EXPECT_EQ(response.message(), request.message());
request.set_message("I'm going to kill you");
EXPECT_TRUE(stream->Write(request));
KillServer();
EXPECT_FALSE(stream->Read(&response));
EXPECT_FALSE(stream->Finish().IsOk());
}
} // namespace
} // namespace testing
} // namespace grpc
int main(int argc, char** argv) {
std::string me = argv[0];
auto lslash = me.rfind('/');
if (lslash != std::string::npos) {
g_root = me.substr(0, lslash);
} else {
g_root = ".";
}
grpc_test_init(argc, argv);
::testing::InitGoogleTest(&argc, argv);
// Order seems to matter on these tests: run three times to eliminate that
for (int i = 0; i < 3; i++) {
if (RUN_ALL_TESTS() != 0) {
return 1;
}
}
return 0;
}
<|endoftext|> |
<commit_before>#include "xchainer/cuda/cuda_conv.h"
#include <algorithm>
#include <cstdint>
#include <gtest/gtest.h>
#include "xchainer/array.h"
#include "xchainer/constant.h"
#include "xchainer/cuda/cuda_device.h"
#include "xchainer/device_id.h"
#include "xchainer/routines/connection.h"
#include "xchainer/shape.h"
#include "xchainer/stack_vector.h"
#include "xchainer/testing/array.h"
#include "xchainer/testing/array_check.h"
#include "xchainer/testing/device_session.h"
namespace xchainer {
namespace cuda {
namespace internal {
class CudaConvTest {
public:
static size_t GetFwdAlgoCacheMapSize(const CudaConv& cuda_conv) { return cuda_conv.fwd_algo_cache_map_.size(); }
static size_t GetBwdDataAlgoCacheMapSize(const CudaConv& cuda_conv) { return cuda_conv.bwd_data_algo_cache_map_.size(); }
static size_t GetBwdFilterAlgoCacheMapSize(const CudaConv& cuda_conv) { return cuda_conv.bwd_filter_algo_cache_map_.size(); }
static CudaConv& GetCudaConv(CudaDevice& cuda_device) { return cuda_device.cuda_conv_; }
};
} // namespace internal
TEST(CudaConvTest, FwdAlgoCache) {
testing::DeviceSession device_session{DeviceId{"cuda", 0}};
auto& device = dynamic_cast<CudaDevice&>(device_session.device());
internal::CudaConv& cuda_conv = internal::CudaConvTest::GetCudaConv(device);
int64_t batch_size = 2;
int64_t in_channels = 3;
int64_t out_channels = 2;
Shape in_dims{10, 7};
StackVector<int64_t, kMaxNdim> kernel_size{2, 3};
Shape x_shape{batch_size, in_channels};
std::copy(in_dims.begin(), in_dims.end(), std::back_inserter(x_shape));
Shape w_shape{out_channels, in_channels};
std::copy(kernel_size.begin(), kernel_size.end(), std::back_inserter(w_shape));
Shape b_shape{out_channels};
Array x = testing::BuildArray(x_shape).WithLinearData<float>(-x_shape.GetTotalSize() / 2, 1.0f).WithPadding(1);
Array w = testing::BuildArray(w_shape).WithLinearData<float>(-w_shape.GetTotalSize() / 2, 1.0f);
Array b = testing::BuildArray(b_shape).WithData<float>({-0.2f, 1.3f});
// New parameters should create new auto tuning caches, and same parameters should not.
{
StackVector<int64_t, kMaxNdim> stride{3, 2};
StackVector<int64_t, kMaxNdim> pad{2, 0};
bool cover_all = false;
EXPECT_EQ(size_t{0}, internal::CudaConvTest::GetFwdAlgoCacheMapSize(cuda_conv));
cuda_conv.Conv(device, x, w, b, stride, pad, cover_all);
EXPECT_EQ(size_t{1}, internal::CudaConvTest::GetFwdAlgoCacheMapSize(cuda_conv));
cuda_conv.Conv(device, x, w, b, stride, pad, cover_all);
EXPECT_EQ(size_t{1}, internal::CudaConvTest::GetFwdAlgoCacheMapSize(cuda_conv));
}
{
StackVector<int64_t, kMaxNdim> stride{1, 1};
StackVector<int64_t, kMaxNdim> pad{0, 0};
bool cover_all = false;
EXPECT_EQ(size_t{1}, internal::CudaConvTest::GetFwdAlgoCacheMapSize(cuda_conv));
Conv(x, w, b, stride, pad, cover_all);
EXPECT_EQ(size_t{2}, internal::CudaConvTest::GetFwdAlgoCacheMapSize(cuda_conv));
Conv(x, w, b, stride, pad, cover_all);
EXPECT_EQ(size_t{2}, internal::CudaConvTest::GetFwdAlgoCacheMapSize(cuda_conv));
}
}
TEST(CudaConvTest, BwdDatadAlgoCache) {
testing::DeviceSession device_session{DeviceId{"cuda", 0}};
auto& device = dynamic_cast<CudaDevice&>(device_session.device());
internal::CudaConv& cuda_conv = internal::CudaConvTest::GetCudaConv(device);
int64_t batch_size = 2;
int64_t in_channels = 3;
int64_t out_channels = 2;
Shape in_dims{5, 3};
StackVector<int64_t, kMaxNdim> kernel_size{2, 3};
Shape x_shape{batch_size, in_channels};
std::copy(in_dims.begin(), in_dims.end(), std::back_inserter(x_shape));
Shape w_shape{in_channels, out_channels};
std::copy(kernel_size.begin(), kernel_size.end(), std::back_inserter(w_shape));
Shape b_shape{out_channels};
Array x = testing::BuildArray(x_shape).WithLinearData<float>(-x_shape.GetTotalSize() / 2, 1.0f).WithPadding(1);
Array w = testing::BuildArray(w_shape).WithLinearData<float>(-w_shape.GetTotalSize() / 2, 1.0f);
Array b = testing::BuildArray(b_shape).WithData<float>({-0.2f, 1.3f});
// New parameters should create new auto tuning caches, and same parameters should not.
{
StackVector<int64_t, kMaxNdim> stride{3, 2};
StackVector<int64_t, kMaxNdim> pad{2, 0};
EXPECT_EQ(size_t{0}, internal::CudaConvTest::GetBwdDataAlgoCacheMapSize(cuda_conv));
ConvTranspose(x, w, b, stride, pad);
EXPECT_EQ(size_t{1}, internal::CudaConvTest::GetBwdDataAlgoCacheMapSize(cuda_conv));
ConvTranspose(x, w, b, stride, pad);
EXPECT_EQ(size_t{1}, internal::CudaConvTest::GetBwdDataAlgoCacheMapSize(cuda_conv));
}
{
StackVector<int64_t, kMaxNdim> stride{1, 1};
StackVector<int64_t, kMaxNdim> pad{0, 0};
EXPECT_EQ(size_t{1}, internal::CudaConvTest::GetBwdDataAlgoCacheMapSize(cuda_conv));
ConvTranspose(x, w, b, stride, pad);
EXPECT_EQ(size_t{2}, internal::CudaConvTest::GetBwdDataAlgoCacheMapSize(cuda_conv));
ConvTranspose(x, w, b, stride, pad);
EXPECT_EQ(size_t{2}, internal::CudaConvTest::GetBwdDataAlgoCacheMapSize(cuda_conv));
}
}
TEST(CudaConvTest, BwdFilterAlgoCache) {
testing::DeviceSession device_session{DeviceId{"cuda", 0}};
auto& device = dynamic_cast<CudaDevice&>(device_session.device());
internal::CudaConv& cuda_conv = internal::CudaConvTest::GetCudaConv(device);
int64_t batch_size = 2;
int64_t in_channels = 3;
int64_t out_channels = 2;
Shape in_dims{10, 7};
StackVector<int64_t, kMaxNdim> kernel_size{2, 3};
Dtype w_dtype = Dtype::kFloat32;
Shape x_shape{batch_size, in_channels};
std::copy(in_dims.begin(), in_dims.end(), std::back_inserter(x_shape));
Shape w_shape{out_channels, in_channels};
std::copy(kernel_size.begin(), kernel_size.end(), std::back_inserter(w_shape));
Array x = testing::BuildArray(x_shape).WithLinearData<float>(-x_shape.GetTotalSize() / 2, 1.0f).WithPadding(1);
// New parameters should create new auto tuning caches, and same parameters should not.
// ConvGradW is not exposed as routines function, so call CudaDevice::ConvGradWeight directly.
{
StackVector<int64_t, kMaxNdim> stride{3, 2};
StackVector<int64_t, kMaxNdim> pad{2, 0};
bool cover_all = false;
Shape out_dims{5, 3};
Shape out_shape{batch_size, out_channels};
std::copy(out_dims.begin(), out_dims.end(), std::back_inserter(out_shape));
Array gy = testing::BuildArray(out_shape).WithLinearData(-0.3f, 0.1f).WithPadding(1);
EXPECT_EQ(size_t{0}, internal::CudaConvTest::GetBwdFilterAlgoCacheMapSize(cuda_conv));
device.ConvGradWeight(w_dtype, w_shape, x, gy, stride, pad, cover_all);
EXPECT_EQ(size_t{1}, internal::CudaConvTest::GetBwdFilterAlgoCacheMapSize(cuda_conv));
device.ConvGradWeight(w_dtype, w_shape, x, gy, stride, pad, cover_all);
EXPECT_EQ(size_t{1}, internal::CudaConvTest::GetBwdFilterAlgoCacheMapSize(cuda_conv));
}
{
StackVector<int64_t, kMaxNdim> stride{1, 1};
StackVector<int64_t, kMaxNdim> pad{0, 0};
bool cover_all = false;
Shape out_dims{9, 5};
Shape out_shape{batch_size, out_channels};
std::copy(out_dims.begin(), out_dims.end(), std::back_inserter(out_shape));
Array gy = testing::BuildArray(out_shape).WithLinearData(-0.3f, 0.1f).WithPadding(1);
EXPECT_EQ(size_t{1}, internal::CudaConvTest::GetBwdFilterAlgoCacheMapSize(cuda_conv));
device.ConvGradWeight(w_dtype, w_shape, x, gy, stride, pad, cover_all);
EXPECT_EQ(size_t{2}, internal::CudaConvTest::GetBwdFilterAlgoCacheMapSize(cuda_conv));
device.ConvGradWeight(w_dtype, w_shape, x, gy, stride, pad, cover_all);
EXPECT_EQ(size_t{2}, internal::CudaConvTest::GetBwdFilterAlgoCacheMapSize(cuda_conv));
}
}
} // namespace cuda
} // namespace xchainer
<commit_msg>NOLINT downcast that is known to succeed<commit_after>#include "xchainer/cuda/cuda_conv.h"
#include <algorithm>
#include <cstdint>
#include <gtest/gtest.h>
#include "xchainer/array.h"
#include "xchainer/constant.h"
#include "xchainer/cuda/cuda_device.h"
#include "xchainer/device_id.h"
#include "xchainer/routines/connection.h"
#include "xchainer/shape.h"
#include "xchainer/stack_vector.h"
#include "xchainer/testing/array.h"
#include "xchainer/testing/array_check.h"
#include "xchainer/testing/device_session.h"
namespace xchainer {
namespace cuda {
namespace internal {
class CudaConvTest {
public:
static size_t GetFwdAlgoCacheMapSize(const CudaConv& cuda_conv) { return cuda_conv.fwd_algo_cache_map_.size(); }
static size_t GetBwdDataAlgoCacheMapSize(const CudaConv& cuda_conv) { return cuda_conv.bwd_data_algo_cache_map_.size(); }
static size_t GetBwdFilterAlgoCacheMapSize(const CudaConv& cuda_conv) { return cuda_conv.bwd_filter_algo_cache_map_.size(); }
static CudaConv& GetCudaConv(CudaDevice& cuda_device) { return cuda_device.cuda_conv_; }
};
} // namespace internal
TEST(CudaConvTest, FwdAlgoCache) {
testing::DeviceSession device_session{DeviceId{"cuda", 0}};
auto& device = static_cast<CudaDevice&>(device_session.device()); // NOLINT
internal::CudaConv& cuda_conv = internal::CudaConvTest::GetCudaConv(device);
int64_t batch_size = 2;
int64_t in_channels = 3;
int64_t out_channels = 2;
Shape in_dims{10, 7};
StackVector<int64_t, kMaxNdim> kernel_size{2, 3};
Shape x_shape{batch_size, in_channels};
std::copy(in_dims.begin(), in_dims.end(), std::back_inserter(x_shape));
Shape w_shape{out_channels, in_channels};
std::copy(kernel_size.begin(), kernel_size.end(), std::back_inserter(w_shape));
Shape b_shape{out_channels};
Array x = testing::BuildArray(x_shape).WithLinearData<float>(-x_shape.GetTotalSize() / 2, 1.0f).WithPadding(1);
Array w = testing::BuildArray(w_shape).WithLinearData<float>(-w_shape.GetTotalSize() / 2, 1.0f);
Array b = testing::BuildArray(b_shape).WithData<float>({-0.2f, 1.3f});
// New parameters should create new auto tuning caches, and same parameters should not.
{
StackVector<int64_t, kMaxNdim> stride{3, 2};
StackVector<int64_t, kMaxNdim> pad{2, 0};
bool cover_all = false;
EXPECT_EQ(size_t{0}, internal::CudaConvTest::GetFwdAlgoCacheMapSize(cuda_conv));
cuda_conv.Conv(device, x, w, b, stride, pad, cover_all);
EXPECT_EQ(size_t{1}, internal::CudaConvTest::GetFwdAlgoCacheMapSize(cuda_conv));
cuda_conv.Conv(device, x, w, b, stride, pad, cover_all);
EXPECT_EQ(size_t{1}, internal::CudaConvTest::GetFwdAlgoCacheMapSize(cuda_conv));
}
{
StackVector<int64_t, kMaxNdim> stride{1, 1};
StackVector<int64_t, kMaxNdim> pad{0, 0};
bool cover_all = false;
EXPECT_EQ(size_t{1}, internal::CudaConvTest::GetFwdAlgoCacheMapSize(cuda_conv));
Conv(x, w, b, stride, pad, cover_all);
EXPECT_EQ(size_t{2}, internal::CudaConvTest::GetFwdAlgoCacheMapSize(cuda_conv));
Conv(x, w, b, stride, pad, cover_all);
EXPECT_EQ(size_t{2}, internal::CudaConvTest::GetFwdAlgoCacheMapSize(cuda_conv));
}
}
TEST(CudaConvTest, BwdDatadAlgoCache) {
testing::DeviceSession device_session{DeviceId{"cuda", 0}};
auto& device = static_cast<CudaDevice&>(device_session.device()); // NOLINT
internal::CudaConv& cuda_conv = internal::CudaConvTest::GetCudaConv(device);
int64_t batch_size = 2;
int64_t in_channels = 3;
int64_t out_channels = 2;
Shape in_dims{5, 3};
StackVector<int64_t, kMaxNdim> kernel_size{2, 3};
Shape x_shape{batch_size, in_channels};
std::copy(in_dims.begin(), in_dims.end(), std::back_inserter(x_shape));
Shape w_shape{in_channels, out_channels};
std::copy(kernel_size.begin(), kernel_size.end(), std::back_inserter(w_shape));
Shape b_shape{out_channels};
Array x = testing::BuildArray(x_shape).WithLinearData<float>(-x_shape.GetTotalSize() / 2, 1.0f).WithPadding(1);
Array w = testing::BuildArray(w_shape).WithLinearData<float>(-w_shape.GetTotalSize() / 2, 1.0f);
Array b = testing::BuildArray(b_shape).WithData<float>({-0.2f, 1.3f});
// New parameters should create new auto tuning caches, and same parameters should not.
{
StackVector<int64_t, kMaxNdim> stride{3, 2};
StackVector<int64_t, kMaxNdim> pad{2, 0};
EXPECT_EQ(size_t{0}, internal::CudaConvTest::GetBwdDataAlgoCacheMapSize(cuda_conv));
ConvTranspose(x, w, b, stride, pad);
EXPECT_EQ(size_t{1}, internal::CudaConvTest::GetBwdDataAlgoCacheMapSize(cuda_conv));
ConvTranspose(x, w, b, stride, pad);
EXPECT_EQ(size_t{1}, internal::CudaConvTest::GetBwdDataAlgoCacheMapSize(cuda_conv));
}
{
StackVector<int64_t, kMaxNdim> stride{1, 1};
StackVector<int64_t, kMaxNdim> pad{0, 0};
EXPECT_EQ(size_t{1}, internal::CudaConvTest::GetBwdDataAlgoCacheMapSize(cuda_conv));
ConvTranspose(x, w, b, stride, pad);
EXPECT_EQ(size_t{2}, internal::CudaConvTest::GetBwdDataAlgoCacheMapSize(cuda_conv));
ConvTranspose(x, w, b, stride, pad);
EXPECT_EQ(size_t{2}, internal::CudaConvTest::GetBwdDataAlgoCacheMapSize(cuda_conv));
}
}
TEST(CudaConvTest, BwdFilterAlgoCache) {
testing::DeviceSession device_session{DeviceId{"cuda", 0}};
auto& device = static_cast<CudaDevice&>(device_session.device()); // NOLINT
internal::CudaConv& cuda_conv = internal::CudaConvTest::GetCudaConv(device);
int64_t batch_size = 2;
int64_t in_channels = 3;
int64_t out_channels = 2;
Shape in_dims{10, 7};
StackVector<int64_t, kMaxNdim> kernel_size{2, 3};
Dtype w_dtype = Dtype::kFloat32;
Shape x_shape{batch_size, in_channels};
std::copy(in_dims.begin(), in_dims.end(), std::back_inserter(x_shape));
Shape w_shape{out_channels, in_channels};
std::copy(kernel_size.begin(), kernel_size.end(), std::back_inserter(w_shape));
Array x = testing::BuildArray(x_shape).WithLinearData<float>(-x_shape.GetTotalSize() / 2, 1.0f).WithPadding(1);
// New parameters should create new auto tuning caches, and same parameters should not.
// ConvGradW is not exposed as routines function, so call CudaDevice::ConvGradWeight directly.
{
StackVector<int64_t, kMaxNdim> stride{3, 2};
StackVector<int64_t, kMaxNdim> pad{2, 0};
bool cover_all = false;
Shape out_dims{5, 3};
Shape out_shape{batch_size, out_channels};
std::copy(out_dims.begin(), out_dims.end(), std::back_inserter(out_shape));
Array gy = testing::BuildArray(out_shape).WithLinearData(-0.3f, 0.1f).WithPadding(1);
EXPECT_EQ(size_t{0}, internal::CudaConvTest::GetBwdFilterAlgoCacheMapSize(cuda_conv));
device.ConvGradWeight(w_dtype, w_shape, x, gy, stride, pad, cover_all);
EXPECT_EQ(size_t{1}, internal::CudaConvTest::GetBwdFilterAlgoCacheMapSize(cuda_conv));
device.ConvGradWeight(w_dtype, w_shape, x, gy, stride, pad, cover_all);
EXPECT_EQ(size_t{1}, internal::CudaConvTest::GetBwdFilterAlgoCacheMapSize(cuda_conv));
}
{
StackVector<int64_t, kMaxNdim> stride{1, 1};
StackVector<int64_t, kMaxNdim> pad{0, 0};
bool cover_all = false;
Shape out_dims{9, 5};
Shape out_shape{batch_size, out_channels};
std::copy(out_dims.begin(), out_dims.end(), std::back_inserter(out_shape));
Array gy = testing::BuildArray(out_shape).WithLinearData(-0.3f, 0.1f).WithPadding(1);
EXPECT_EQ(size_t{1}, internal::CudaConvTest::GetBwdFilterAlgoCacheMapSize(cuda_conv));
device.ConvGradWeight(w_dtype, w_shape, x, gy, stride, pad, cover_all);
EXPECT_EQ(size_t{2}, internal::CudaConvTest::GetBwdFilterAlgoCacheMapSize(cuda_conv));
device.ConvGradWeight(w_dtype, w_shape, x, gy, stride, pad, cover_all);
EXPECT_EQ(size_t{2}, internal::CudaConvTest::GetBwdFilterAlgoCacheMapSize(cuda_conv));
}
}
} // namespace cuda
} // namespace xchainer
<|endoftext|> |
<commit_before>#include <cstdlib>
#include <cstdio>
#include <vector>
#include <array>
#include <string>
#include <unistd.h>
#include <complex>
#include "dir1/debuggee.h"
#include "dir2/debuggee.h"
void deepstack(int levelsToGo) {
if (levelsToGo > 0) {
deepstack(levelsToGo-1);
}
} // #BP2
void inf_loop() {
long long i = 0;
for (;;) {
printf("\r%lld ", i);
fflush(stdout);
sleep(1);
i += 1;
}
}
void threads(int num_threads) {
}
bool check_env(const char* env_name, const char* expected) {
const char* val = getenv(env_name);
printf("%s=%s\n", env_name, val);
return val && std::string(val) == std::string(expected);
}
void echo() {
char buffer[1024];
do {
fgets(buffer, sizeof(buffer), stdin);
fputs(buffer, stdout);
} while (buffer[0] != '\n'); // till empty line is read
}
void vars() {
struct Struct {
int a;
char b;
float c;
};
int a = 10;
int b = 20;
for (int i = 0; i < 10; i++)
{
int a = 30;
int b = 40;
static int sss = 555;
const char c[] = "foobar";
char buffer[10240] = {0};
int array_int[10] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
std::vector<std::vector<int>> vec_int(10, {i*1, i*2, i*3, i*4, i*5});
std::vector<std::vector<int>> empty_vec;
Struct s = { i+1, 'a', 3.0f };
std::vector<Struct> vec_struct(3, { i*2, 'b', 4.0f});
std::array<int, 5> stdarr_int;
Struct array_struct[5] = { { i*2, 'b', 4.0f} };
std::string str1 = "The quick brown fox";
std::string empty_str;
std::string* str_ptr = &str1;
std::string& str_ref = str1;
int zzz = i; // #BP3
}
}
void mandelbrot() {
const int xdim = 500;
const int ydim = 500;
const int max_iter = 100;
int image[xdim * ydim] = {0};
for (int y = 0; y < ydim; ++y) {
for (int x = 0; x < xdim; ++x) {
std::complex<float> xy(-2.05 + x * 3.0 / xdim, -1.5 + y * 3.0 / ydim);
std::complex<float> z(0, 0);
int count = max_iter;
for (int i = 0; i < max_iter; ++i) {
z = z * z + xy;
if (std::abs(z) >= 2) {
count = i;
break;
}
}
image[y * xdim + x] = count;
}
}
for (int y = 0; y < ydim; y += 10) {
for (int x = 0; x < xdim; x += 5) {
putchar(image[y * xdim + x] < max_iter ? '.' : '#');
}
putchar('\n');
}
}
int main(int argc, char* argv[]) {
if (argc < 2) { // #BP1
return -1;
}
std::string testcase = argv[1];
if (testcase == "crash") {
*(volatile int*)0 = 42;
} else if (testcase == "deepstack") {
deepstack(50);
} else if (testcase == "threads") {
threads(15);
} else if (testcase == "check_env") {
if (argc < 4) {
return -1;
}
return (int)check_env(argv[2], argv[3]);
} else if (testcase == "inf_loop") {
inf_loop();
} else if (testcase == "echo") {
echo();
} else if (testcase == "vars") {
vars();
} else if (testcase == "header") {
header_fn1(1);
header_fn2(2);
} else if (testcase == "mandelbrot") {
mandelbrot();
}
return 0;
}
<commit_msg>Document breakpoint condition.<commit_after>#include <cstdlib>
#include <cstdio>
#include <vector>
#include <array>
#include <string>
#include <unistd.h>
#include <complex>
#include "dir1/debuggee.h"
#include "dir2/debuggee.h"
void deepstack(int levelsToGo) {
if (levelsToGo > 0) {
deepstack(levelsToGo-1);
}
} // #BP2
void inf_loop() {
long long i = 0;
for (;;) {
printf("\r%lld ", i);
fflush(stdout);
sleep(1);
i += 1;
}
}
void threads(int num_threads) {
}
bool check_env(const char* env_name, const char* expected) {
const char* val = getenv(env_name);
printf("%s=%s\n", env_name, val);
return val && std::string(val) == std::string(expected);
}
void echo() {
char buffer[1024];
do {
fgets(buffer, sizeof(buffer), stdin);
fputs(buffer, stdout);
} while (buffer[0] != '\n'); // till empty line is read
}
void vars() {
struct Struct {
int a;
char b;
float c;
};
int a = 10;
int b = 20;
for (int i = 0; i < 10; i++)
{
int a = 30;
int b = 40;
static int sss = 555;
const char c[] = "foobar";
char buffer[10240] = {0};
int array_int[10] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
std::vector<std::vector<int>> vec_int(10, {i*1, i*2, i*3, i*4, i*5});
std::vector<std::vector<int>> empty_vec;
Struct s = { i+1, 'a', 3.0f };
std::vector<Struct> vec_struct(3, { i*2, 'b', 4.0f});
std::array<int, 5> stdarr_int;
Struct array_struct[5] = { { i*2, 'b', 4.0f} };
std::string str1 = "The quick brown fox";
std::string empty_str;
std::string* str_ptr = &str1;
std::string& str_ref = str1;
int zzz = i; // #BP3
}
}
void mandelbrot() {
const int xdim = 500;
const int ydim = 500;
const int max_iter = 100;
int image[xdim * ydim] = {0};
for (int y = 0; y < ydim; ++y) {
// /py debugvis.plot_image($image, $xdim, $ydim) if $y % 50 == 0 else False
for (int x = 0; x < xdim; ++x) {
std::complex<float> xy(-2.05 + x * 3.0 / xdim, -1.5 + y * 3.0 / ydim);
std::complex<float> z(0, 0);
int count = max_iter;
for (int i = 0; i < max_iter; ++i) {
z = z * z + xy;
if (std::abs(z) >= 2) {
count = i;
break;
}
}
image[y * xdim + x] = count;
}
}
for (int y = 0; y < ydim; y += 10) {
for (int x = 0; x < xdim; x += 5) {
putchar(image[y * xdim + x] < max_iter ? '.' : '#');
}
putchar('\n');
}
}
int main(int argc, char* argv[]) {
if (argc < 2) { // #BP1
return -1;
}
std::string testcase = argv[1];
if (testcase == "crash") {
*(volatile int*)0 = 42;
} else if (testcase == "deepstack") {
deepstack(50);
} else if (testcase == "threads") {
threads(15);
} else if (testcase == "check_env") {
if (argc < 4) {
return -1;
}
return (int)check_env(argv[2], argv[3]);
} else if (testcase == "inf_loop") {
inf_loop();
} else if (testcase == "echo") {
echo();
} else if (testcase == "vars") {
vars();
} else if (testcase == "header") {
header_fn1(1);
header_fn2(2);
} else if (testcase == "mandelbrot") {
mandelbrot();
}
return 0;
}
<|endoftext|> |
<commit_before>#ifndef CALLBACK_HPP
#define CALLBACK_HPP
#include "noncopyable.hpp"
#include <type_traits>
#include <cstring>
struct callback_t : private noncopyable_t
{
enum {INTERNAL_STORAGE_SIZE = 64};
callback_t()
: m_object_ptr(nullptr)
, m_method_ptr(nullptr)
, m_delete_ptr(nullptr)
{}
template <typename T>
callback_t(T &&object)
{
typedef typename std::remove_reference<T>::type unref_type;
static_assert(sizeof(unref_type) < INTERNAL_STORAGE_SIZE,
"functional object don't fit into internal storage");
m_object_ptr = new (m_storage) unref_type(std::forward<T>(object));
m_method_ptr = &method_stub<unref_type>;
m_delete_ptr = &delete_stub<unref_type>;
}
callback_t(callback_t &&o)
{
move_from_other(o);
}
callback_t & operator=(callback_t &&o)
{
move_from_other(o);
return *this;
}
~callback_t()
{
if (m_delete_ptr)
{
(*m_delete_ptr)(m_object_ptr);
}
}
void operator()() const
{
if (m_method_ptr)
{
(*m_method_ptr)(m_object_ptr);
}
}
private:
typedef void (*method_type)(void *);
void *m_object_ptr;
method_type m_method_ptr;
method_type m_delete_ptr;
alignas(INTERNAL_STORAGE_SIZE) char m_storage[INTERNAL_STORAGE_SIZE];
void move_from_other(callback_t &o)
{
m_object_ptr = m_storage;
m_method_ptr = o.m_method_ptr;
m_delete_ptr = o.m_delete_ptr;
memcpy(m_storage, o.m_storage, INTERNAL_STORAGE_SIZE);
o.m_method_ptr = nullptr;
o.m_delete_ptr = nullptr;
}
template <class T>
static void method_stub(void *object_ptr)
{
T *p = static_cast<T *>(object_ptr);
p->operator()();
}
template <class T>
static void delete_stub(void *object_ptr)
{
T *p = static_cast<T *>(object_ptr);
p->~T();
}
};
#endif // CALLBACK_HPP
<commit_msg>add alignment in callback<commit_after>#ifndef CALLBACK_HPP
#define CALLBACK_HPP
#include "noncopyable.hpp"
#include <type_traits>
#include <cstring>
struct callback_t : private noncopyable_t
{
enum {INTERNAL_STORAGE_SIZE = 64};
template <typename T>
callback_t(T &&object)
{
typedef typename std::remove_reference<T>::type unref_type;
const size_t alignment = std::alignment_of<unref_type>::value;
static_assert(sizeof(unref_type) + alignment < INTERNAL_STORAGE_SIZE,
"functional object don't fit into internal storage");
m_object_ptr = new (m_storage + alignment) unref_type(std::forward<T>(object));
m_method_ptr = &method_stub<unref_type>;
m_delete_ptr = &delete_stub<unref_type>;
}
callback_t(callback_t &&o)
{
move_from_other(o);
}
callback_t & operator=(callback_t &&o)
{
move_from_other(o);
return *this;
}
~callback_t()
{
if (m_delete_ptr)
{
(*m_delete_ptr)(m_object_ptr);
}
}
void operator()() const
{
if (m_method_ptr)
{
(*m_method_ptr)(m_object_ptr);
}
}
private:
char m_storage[INTERNAL_STORAGE_SIZE];
void *m_object_ptr = m_storage;
typedef void (*method_type)(void *);
method_type m_method_ptr = nullptr;
method_type m_delete_ptr = nullptr;
void move_from_other(callback_t &o)
{
size_t o_alignment = o.m_method_ptr - o.m_storage;
m_object_ptr = m_storage + o_alignment;
m_method_ptr = o.m_method_ptr;
m_delete_ptr = o.m_delete_ptr;
memcpy(m_storage, o.m_storage, INTERNAL_STORAGE_SIZE);
o.m_method_ptr = nullptr;
o.m_delete_ptr = nullptr;
}
template <class T>
static void method_stub(void *object_ptr)
{
static_cast<T *>(object_ptr)->operator()();
}
template <class T>
static void delete_stub(void *object_ptr)
{
static_cast<T *>(object_ptr)->~T();
}
};
#endif // CALLBACK_HPP
<|endoftext|> |
<commit_before>//
// yas_db_entity.cpp
//
#include "yas_db_additional_protocol.h"
#include "yas_db_attribute.h"
#include "yas_db_entity.h"
#include "yas_db_relation.h"
#include "yas_db_sql_utils.h"
#include "yas_stl_utils.h"
using namespace yas;
namespace yas {
static db::attribute_map_t make_attributes(std::vector<db::attribute_args> const &args_vec) {
db::attribute_map_t attributes;
for (db::attribute_args const &args : args_vec) {
attributes.emplace(args.name, db::attribute{args});
}
return attributes;
}
static db::attribute_map_t make_all_attributes(std::vector<db::attribute_args> const &args_vec) {
db::attribute_map_t attributes = make_attributes(args_vec);
attributes.reserve(args_vec.size() + 4);
db::attribute const &id_attr = db::attribute::id_attribute();
attributes.emplace(id_attr.name, id_attr);
db::attribute const &obj_id_attr = db::attribute::object_id_attribute();
attributes.emplace(obj_id_attr.name, obj_id_attr);
db::attribute const &save_id_attr = db::attribute::save_id_attribute();
attributes.emplace(save_id_attr.name, save_id_attr);
db::attribute const &action_attr = db::attribute::action_attribute();
attributes.emplace(action_attr.name, action_attr);
return attributes;
}
static db::attribute_map_t filter_custom_attributes(db::attribute_map_t const &attributes) {
return filter(attributes, [](auto const &pair) {
std::string const &attr_name = pair.first;
if (attr_name == db::pk_id_field || attr_name == db::object_id_field || attr_name == db::save_id_field ||
attr_name == db::action_field) {
return false;
}
return true;
});
}
static db::relation_map_t make_relations(std::vector<db::relation_args> &&args_vec, std::string const &source) {
db::relation_map_t relations;
relations.reserve(args_vec.size());
for (db::relation_args &args : args_vec) {
std::string name = args.name;
relations.emplace(std::move(name), db::relation{std::move(args), source});
}
return relations;
}
}
db::entity::entity(entity_args args, db::string_set_map_t inv_rel_names)
: name(std::move(args.name)),
all_attributes(make_all_attributes(args.attributes)),
custom_attributes(make_attributes(args.attributes)),
relations(make_relations(std::move(args.relations), this->name)),
inverse_relation_names(std::move(inv_rel_names)) {
}
std::string db::entity::sql_for_create() const {
auto mapped_attrs =
to_vector<std::string>(this->all_attributes, [](auto const &pair) { return pair.second.sql(); });
return db::create_table_sql(this->name, mapped_attrs);
}
std::string db::entity::sql_for_update() const {
auto mapped_fields = to_vector<std::string>(this->all_attributes, [](auto const &pair) { return pair.first; });
return db::update_sql(this->name, mapped_fields, db::equal_field_expr(db::pk_id_field));
}
std::string db::entity::sql_for_insert() const {
std::vector<std::string> mapped_fields;
for (auto const &pair : this->all_attributes) {
std::string const &field_name = pair.first;
if (field_name != db::pk_id_field) {
mapped_fields.push_back(field_name);
}
}
return db::insert_sql(this->name, mapped_fields);
}
<commit_msg>remove filter_custom_attributes<commit_after>//
// yas_db_entity.cpp
//
#include "yas_db_additional_protocol.h"
#include "yas_db_attribute.h"
#include "yas_db_entity.h"
#include "yas_db_relation.h"
#include "yas_db_sql_utils.h"
#include "yas_stl_utils.h"
using namespace yas;
namespace yas {
static db::attribute_map_t make_attributes(std::vector<db::attribute_args> const &args_vec) {
db::attribute_map_t attributes;
for (db::attribute_args const &args : args_vec) {
attributes.emplace(args.name, db::attribute{args});
}
return attributes;
}
static db::attribute_map_t make_all_attributes(std::vector<db::attribute_args> const &args_vec) {
db::attribute_map_t attributes = make_attributes(args_vec);
attributes.reserve(args_vec.size() + 4);
db::attribute const &id_attr = db::attribute::id_attribute();
attributes.emplace(id_attr.name, id_attr);
db::attribute const &obj_id_attr = db::attribute::object_id_attribute();
attributes.emplace(obj_id_attr.name, obj_id_attr);
db::attribute const &save_id_attr = db::attribute::save_id_attribute();
attributes.emplace(save_id_attr.name, save_id_attr);
db::attribute const &action_attr = db::attribute::action_attribute();
attributes.emplace(action_attr.name, action_attr);
return attributes;
}
static db::relation_map_t make_relations(std::vector<db::relation_args> &&args_vec, std::string const &source) {
db::relation_map_t relations;
relations.reserve(args_vec.size());
for (db::relation_args &args : args_vec) {
std::string name = args.name;
relations.emplace(std::move(name), db::relation{std::move(args), source});
}
return relations;
}
}
db::entity::entity(entity_args args, db::string_set_map_t inv_rel_names)
: name(std::move(args.name)),
all_attributes(make_all_attributes(args.attributes)),
custom_attributes(make_attributes(args.attributes)),
relations(make_relations(std::move(args.relations), this->name)),
inverse_relation_names(std::move(inv_rel_names)) {
}
std::string db::entity::sql_for_create() const {
auto mapped_attrs =
to_vector<std::string>(this->all_attributes, [](auto const &pair) { return pair.second.sql(); });
return db::create_table_sql(this->name, mapped_attrs);
}
std::string db::entity::sql_for_update() const {
auto mapped_fields = to_vector<std::string>(this->all_attributes, [](auto const &pair) { return pair.first; });
return db::update_sql(this->name, mapped_fields, db::equal_field_expr(db::pk_id_field));
}
std::string db::entity::sql_for_insert() const {
std::vector<std::string> mapped_fields;
for (auto const &pair : this->all_attributes) {
std::string const &field_name = pair.first;
if (field_name != db::pk_id_field) {
mapped_fields.push_back(field_name);
}
}
return db::insert_sql(this->name, mapped_fields);
}
<|endoftext|> |
<commit_before>#define WIN32_LEAN_AND_MEAN
#pragma comment (lib, "Shlwapi.lib")
#include <Windows.h>
#include <Shlwapi.h>
#include <unordered_map>
#include <queue>
using namespace std;
#define BUF_SIZE MAX_PATH * 3
long long CurrentTime()
{
long long t;
GetSystemTimeAsFileTime((LPFILETIME) &t);
return t;
}
BOOL unhook_by_code(LPCTSTR szDllName, LPCTSTR szFuncName, PBYTE pOrgBytes)
{
FARPROC pFunc;
DWORD dwOldProtect;
// API ּ Ѵ
pFunc = GetProcAddress(GetModuleHandle(szDllName), szFuncName);
// ڵ (5 byte) WRITE Ӽ ߰
VirtualProtect((LPVOID) pFunc, 5, PAGE_EXECUTE_READWRITE, &dwOldProtect);
// Unhook
memcpy(pFunc, pOrgBytes, 5);
// Ӽ
VirtualProtect((LPVOID) pFunc, 5, dwOldProtect, &dwOldProtect);
return TRUE;
}
BOOL hook_by_code(LPCTSTR szDllName, LPCTSTR szFuncName, PROC pfnNew, PBYTE pOrgBytes)
{
FARPROC pfnOrg;
DWORD dwOldProtect, dwAddress;
BYTE pBuf[5] = { 0xE9, 0, };
PBYTE pByte;
// ŷ API ּҸ Ѵ
pfnOrg = (FARPROC) GetProcAddress(GetModuleHandle(szDllName), szFuncName);
pByte = (PBYTE) pfnOrg;
// ̹ ŷǾ ִٸ return FALSE
if (pByte[0] == 0xE9)
return FALSE;
// 5 byte ġ Ͽ WRITE Ӽ ߰
VirtualProtect((LPVOID) pfnOrg, 5, PAGE_EXECUTE_READWRITE, &dwOldProtect);
// ڵ (5 byte)
memcpy(pOrgBytes, pfnOrg, 5);
// JMP ּҰ (E9 XXXX)
// => XXXX = pfnNew - pfnOrg - 5
dwAddress = (DWORD) pfnNew - (DWORD) pfnOrg - 5;
memcpy(&pBuf[1], &dwAddress, 4);
// Hook - 5 byte ġ(JMP XXXX)
memcpy(pfnOrg, pBuf, 5);
// Ӽ
VirtualProtect((LPVOID) pfnOrg, 5, dwOldProtect, &dwOldProtect);
return TRUE;
}
HANDLE hPipe;
queue<string> pipeQueue;
BOOL bCancelPipeThread = FALSE;
DWORD WINAPI PipeManager(LPVOID lParam)
{
hPipe = CreateNamedPipe("\\\\.\\pipe\\osu!Lyrics", PIPE_ACCESS_OUTBOUND,
PIPE_TYPE_MESSAGE | PIPE_WAIT, 1, BUF_SIZE * 5, 0, INFINITE, NULL);
// Ŭ̾Ʈ
while (!bCancelPipeThread)
{
if (ConnectNamedPipe(hPipe, NULL) || GetLastError() == ERROR_PIPE_CONNECTED)
{
if (pipeQueue.empty())
{
Sleep(100);
continue;
}
string message = pipeQueue.front();
OVERLAPPED overlapped = {};
if (WriteFileEx(hPipe, message.c_str(), message.length(), &overlapped, [](DWORD, DWORD, LPOVERLAPPED) {}))
{
pipeQueue.pop();
continue;
}
}
// ť ٽ
DisconnectNamedPipe(hPipe);
pipeQueue = {};
}
// Ŭ̾Ʈ
DisconnectNamedPipe(hPipe);
CloseHandle(hPipe);
return 0;
}
typedef BOOL (WINAPI *tReadFile)(HANDLE, LPVOID, DWORD, LPDWORD, LPOVERLAPPED);
tReadFile pReadFile;
BYTE pReadFileJMP[5];
CRITICAL_SECTION hMutex;
unordered_map<string, string> audioInfo;
// osu! ReadFile ȣϸ osu!Lyrics
BOOL WINAPI hkReadFile(HANDLE hFile, LPVOID lpBuffer, DWORD nNumberOfBytesToRead, LPDWORD lpNumberOfBytesRead, LPOVERLAPPED lpOverlapped)
{
long long calledAt = CurrentTime();
BOOL result = FALSE;
EnterCriticalSection(&hMutex);
{
unhook_by_code("kernel32.dll", "ReadFile", pReadFileJMP);
result = pReadFile(hFile, lpBuffer, nNumberOfBytesToRead, lpNumberOfBytesRead, lpOverlapped);
hook_by_code("kernel32.dll", "ReadFile", (PROC) hkReadFile, pReadFileJMP);
}
LeaveCriticalSection(&hMutex);
if (!result)
{
// ReadFile ϴ osu ...
return FALSE;
}
char path[MAX_PATH];
DWORD pathLength = GetFinalPathNameByHandle(hFile, path, MAX_PATH, VOLUME_NAME_DOS);
// 1: \\?\D:\Games\osu!\...
DWORD seekPosition = SetFilePointer(hFile, 0, NULL, FILE_CURRENT) - *lpNumberOfBytesRead;
// д Ʈ ̰ պκ оٸ:
// AudioFilename պκп / ڵ !
if (strnicmp(".osu", &path[pathLength - 4], 4) == 0 && seekPosition == 0)
{
// strtok ҽ ϹǷ ϴ
char *buffer = strdup((char *) lpBuffer);
char *line = strtok(buffer, "\n");
while (line != NULL)
{
// Ʈ
if (strnicmp(line, "AudioFilename:", 14) == 0)
{
char *beatmapDir = strdup(path);
PathRemoveFileSpec(beatmapDir);
char audioPath[MAX_PATH];
// get value & trim
int i = 14;
for (; line[i] == ' '; i++);
buffer[0] = '\0';
strncat(buffer, &line[i], strlen(line) - i - 1);
PathCombine(audioPath, beatmapDir, buffer);
// ˻ ҹ ϹǷ
WIN32_FIND_DATA fdata;
FindClose(FindFirstFile(audioPath, &fdata));
PathRemoveFileSpec(audioPath);
PathCombine(audioPath, audioPath, fdata.cFileName);
audioInfo.insert(make_pair(string(audioPath), string(path)));
free(beatmapDir);
break;
}
line = strtok(NULL, "\n");
}
free(buffer);
}
else
{
// [ audioPath, beatmapPath ]
unordered_map<string, string>::iterator it = audioInfo.find(string(path));
if (it != audioInfo.end())
{
char buffer[BUF_SIZE];
sprintf(buffer, "%llx|%s|%lx|%s\n", calledAt, &path[4], seekPosition, &it->second[4]);
pipeQueue.push(string(buffer));
}
}
return TRUE;
}
HANDLE hPipeThread;
BOOL WINAPI DllMain(HINSTANCE hinstDLL, DWORD fdwReason, LPVOID lpvReserved)
{
if (fdwReason == DLL_PROCESS_ATTACH)
{
hPipeThread = CreateThread(NULL, 0, PipeManager, NULL, 0, NULL);
InitializeCriticalSection(&hMutex);
EnterCriticalSection(&hMutex);
{
pReadFile = (tReadFile) GetProcAddress(GetModuleHandle("kernel32.dll"), "ReadFile");
hook_by_code("kernel32.dll", "ReadFile", (PROC) hkReadFile, pReadFileJMP);
}
LeaveCriticalSection(&hMutex);
}
else if (fdwReason == DLL_PROCESS_DETACH)
{
bCancelPipeThread = TRUE;
DisconnectNamedPipe(hPipe);
WaitForSingleObject(hPipeThread, INFINITE);
CloseHandle(hPipeThread);
EnterCriticalSection(&hMutex);
{
unhook_by_code("kernel32.dll", "ReadFile", pReadFileJMP);
}
LeaveCriticalSection(&hMutex);
DeleteCriticalSection(&hMutex);
}
return TRUE;
}<commit_msg>시큐티리 워닝 메세지(신함수) 안 뜨게 수정했습니다.<commit_after>#define WIN32_LEAN_AND_MEAN
#pragma comment (lib, "Shlwapi.lib")
#pragma warning (disable:4996)
#include <Windows.h>
#include <Shlwapi.h>
#include <unordered_map>
#include <queue>
using namespace std;
#define BUF_SIZE MAX_PATH * 3
long long CurrentTime()
{
long long t;
GetSystemTimeAsFileTime((LPFILETIME) &t);
return t;
}
BOOL unhook_by_code(LPCTSTR szDllName, LPCTSTR szFuncName, PBYTE pOrgBytes)
{
FARPROC pFunc;
DWORD dwOldProtect;
// API 주소 구한다
pFunc = GetProcAddress(GetModuleHandle(szDllName), szFuncName);
// 원래 코드 (5 byte)를 덮어쓰기 위해 메모리에 WRITE 속성 추가
VirtualProtect((LPVOID) pFunc, 5, PAGE_EXECUTE_READWRITE, &dwOldProtect);
// Unhook
memcpy(pFunc, pOrgBytes, 5);
// 메모리 속성 복원
VirtualProtect((LPVOID) pFunc, 5, dwOldProtect, &dwOldProtect);
return TRUE;
}
BOOL hook_by_code(LPCTSTR szDllName, LPCTSTR szFuncName, PROC pfnNew, PBYTE pOrgBytes)
{
FARPROC pfnOrg;
DWORD dwOldProtect, dwAddress;
BYTE pBuf[5] = { 0xE9, 0, };
PBYTE pByte;
// 후킹대상 API 주소를 구한다
pfnOrg = (FARPROC) GetProcAddress(GetModuleHandle(szDllName), szFuncName);
pByte = (PBYTE) pfnOrg;
// 만약 이미 후킹되어 있다면 return FALSE
if (pByte[0] == 0xE9)
return FALSE;
// 5 byte 패치를 위하여 메모리에 WRITE 속성 추가
VirtualProtect((LPVOID) pfnOrg, 5, PAGE_EXECUTE_READWRITE, &dwOldProtect);
// 기존코드 (5 byte) 백업
memcpy(pOrgBytes, pfnOrg, 5);
// JMP 주소계산 (E9 XXXX)
// => XXXX = pfnNew - pfnOrg - 5
dwAddress = (DWORD) pfnNew - (DWORD) pfnOrg - 5;
memcpy(&pBuf[1], &dwAddress, 4);
// Hook - 5 byte 패치(JMP XXXX)
memcpy(pfnOrg, pBuf, 5);
// 메모리 속성 복원
VirtualProtect((LPVOID) pfnOrg, 5, dwOldProtect, &dwOldProtect);
return TRUE;
}
HANDLE hPipe;
queue<string> pipeQueue;
BOOL bCancelPipeThread = FALSE;
DWORD WINAPI PipeManager(LPVOID lParam)
{
hPipe = CreateNamedPipe("\\\\.\\pipe\\osu!Lyrics", PIPE_ACCESS_OUTBOUND,
PIPE_TYPE_MESSAGE | PIPE_WAIT, 1, BUF_SIZE * 5, 0, INFINITE, NULL);
// 클라이언트가 연결할 때까지 무한 대기
while (!bCancelPipeThread)
{
if (ConnectNamedPipe(hPipe, NULL) || GetLastError() == ERROR_PIPE_CONNECTED)
{
if (pipeQueue.empty())
{
Sleep(100);
continue;
}
string message = pipeQueue.front();
OVERLAPPED overlapped = {};
if (WriteFileEx(hPipe, message.c_str(), message.length(), &overlapped, [](DWORD, DWORD, LPOVERLAPPED) {}))
{
pipeQueue.pop();
continue;
}
}
// 연결 끊겼으면 큐를 비우고 다시 연결 대기
DisconnectNamedPipe(hPipe);
pipeQueue = {};
}
// 클라이언트 연결 종료
DisconnectNamedPipe(hPipe);
CloseHandle(hPipe);
return 0;
}
typedef BOOL (WINAPI *tReadFile)(HANDLE, LPVOID, DWORD, LPDWORD, LPOVERLAPPED);
tReadFile pReadFile;
BYTE pReadFileJMP[5];
CRITICAL_SECTION hMutex;
unordered_map<string, string> audioInfo;
// osu!에서 ReadFile을 호출하면 정보를 빼내서 osu!Lyrics로 보냄
BOOL WINAPI hkReadFile(HANDLE hFile, LPVOID lpBuffer, DWORD nNumberOfBytesToRead, LPDWORD lpNumberOfBytesRead, LPOVERLAPPED lpOverlapped)
{
long long calledAt = CurrentTime();
BOOL result = FALSE;
EnterCriticalSection(&hMutex);
{
unhook_by_code("kernel32.dll", "ReadFile", pReadFileJMP);
result = pReadFile(hFile, lpBuffer, nNumberOfBytesToRead, lpNumberOfBytesRead, lpOverlapped);
hook_by_code("kernel32.dll", "ReadFile", (PROC) hkReadFile, pReadFileJMP);
}
LeaveCriticalSection(&hMutex);
if (!result)
{
// 통상 ReadFile이 실패하는 경우는 osu 프로토콜 읽을 때...
return FALSE;
}
char path[MAX_PATH];
DWORD pathLength = GetFinalPathNameByHandle(hFile, path, MAX_PATH, VOLUME_NAME_DOS);
// 1: \\?\D:\Games\osu!\...
DWORD seekPosition = SetFilePointer(hFile, 0, NULL, FILE_CURRENT) - *lpNumberOfBytesRead;
// 지금 읽는 파일이 비트맵 파일이고 앞부분을 읽었다면:
// AudioFilename은 앞부분에 있음 / 파일 핸들 또 열지 말고 일 한 번만 하자!
if (strnicmp(".osu", &path[pathLength - 4], 4) == 0 && seekPosition == 0)
{
// strtok은 소스를 변형하므로 일단 백업
char *buffer = strdup((char *) lpBuffer);
char *line = strtok(buffer, "\n");
while (line != NULL)
{
// 비트맵의 음악 파일 경로 얻기
if (strnicmp(line, "AudioFilename:", 14) == 0)
{
char *beatmapDir = strdup(path);
PathRemoveFileSpec(beatmapDir);
char audioPath[MAX_PATH];
// get value & trim
int i = 14;
for (; line[i] == ' '; i++);
buffer[0] = '\0';
strncat(buffer, &line[i], strlen(line) - i - 1);
PathCombine(audioPath, beatmapDir, buffer);
// 검색할 때 대소문자 구분하므로 제대로 된 파일 경로 얻기
WIN32_FIND_DATA fdata;
FindClose(FindFirstFile(audioPath, &fdata));
PathRemoveFileSpec(audioPath);
PathCombine(audioPath, audioPath, fdata.cFileName);
audioInfo.insert(make_pair(string(audioPath), string(path)));
free(beatmapDir);
break;
}
line = strtok(NULL, "\n");
}
free(buffer);
}
else
{
// [ audioPath, beatmapPath ]
unordered_map<string, string>::iterator it = audioInfo.find(string(path));
if (it != audioInfo.end())
{
char buffer[BUF_SIZE];
sprintf(buffer, "%llx|%s|%lx|%s\n", calledAt, &path[4], seekPosition, &it->second[4]);
pipeQueue.push(string(buffer));
}
}
return TRUE;
}
HANDLE hPipeThread;
BOOL WINAPI DllMain(HINSTANCE hinstDLL, DWORD fdwReason, LPVOID lpvReserved)
{
if (fdwReason == DLL_PROCESS_ATTACH)
{
hPipeThread = CreateThread(NULL, 0, PipeManager, NULL, 0, NULL);
InitializeCriticalSection(&hMutex);
EnterCriticalSection(&hMutex);
{
pReadFile = (tReadFile) GetProcAddress(GetModuleHandle("kernel32.dll"), "ReadFile");
hook_by_code("kernel32.dll", "ReadFile", (PROC) hkReadFile, pReadFileJMP);
}
LeaveCriticalSection(&hMutex);
}
else if (fdwReason == DLL_PROCESS_DETACH)
{
bCancelPipeThread = TRUE;
DisconnectNamedPipe(hPipe);
WaitForSingleObject(hPipeThread, INFINITE);
CloseHandle(hPipeThread);
EnterCriticalSection(&hMutex);
{
unhook_by_code("kernel32.dll", "ReadFile", pReadFileJMP);
}
LeaveCriticalSection(&hMutex);
DeleteCriticalSection(&hMutex);
}
return TRUE;
}
<|endoftext|> |
<commit_before>// Copyright (c) 2014-2015 Dr. Colin Hirsch and Daniel Frey
// Please see LICENSE for license or visit https://github.com/ColinH/PEGTL/
#ifndef PEGTL_CONTRIB_HTTP_HH
#define PEGTL_CONTRIB_HTTP_HH
#include "../rules.hh"
#include "../ascii.hh"
#include "../utf8.hh"
#include "abnf.hh"
#include "uri.hh"
namespace pegtl
{
namespace http
{
// HTTP 1.1 grammar according to RFC 7230.
// This grammar is a direct PEG translation of the original HTTP grammar.
// It should be considered experimental -- in case of any issues, in particular
// missing anchor rules for actions, please contact the developers.
using namespace abnf;
using OWS = star< WSP >; // optional whitespace
using RWS = plus< WSP >; // required whitespace
using BWS = OWS; // "bad" whitespace
using obs_text = not_range< 0x00, 0x7F >;
using obs_fold = seq< CRLF, plus< WSP > >;
struct tchar : sor< ALPHA, DIGIT, one< '!', '#', '$', '%', '&', '\'', '*', '+', '-', '.', '^', '_', '`', '|', '~' > > {};
struct token : plus< tchar > {};
struct field_name : token {};
struct field_vchar : sor< VCHAR, obs_text > {};
struct field_content : list_must< field_vchar, plus< WSP > > {};
struct field_value : star< sor< field_content, obs_fold > > {};
struct header_field : seq< field_name, one< ':' >, OWS, field_value, OWS > {};
struct method : token {};
struct absolute_path : plus< one< '/' >, uri::segment > {};
struct origin_form : seq< absolute_path, uri::opt_query > {};
struct absolute_form : uri::absolute_URI {};
struct authority_form : uri::authority {};
struct asterisk_form : one< '*' > {};
struct request_target : sor< origin_form, absolute_form, authority_form, asterisk_form > {};
struct status_code : rep< 3, DIGIT > {};
struct reason_phrase : star< sor< VCHAR, obs_text, WSP > > {};
struct HTTP_version : if_must< pegtl_string_t( "HTTP/" ), DIGIT, one< '.' >, DIGIT > {};
struct request_line : if_must< method, SP, request_target, SP, HTTP_version, CRLF > {};
struct status_line : if_must< HTTP_version, SP, status_code, SP, reason_phrase, CRLF > {};
struct start_line : sor< request_line, status_line > {};
struct message_body : star< OCTET > {};
struct HTTP_message : seq< start_line, star< header_field, CRLF >, CRLF, opt< message_body > > {};
struct Content_Length : plus< DIGIT > {};
struct uri_host : uri::host {};
struct port : uri::port {};
struct Host : seq< uri_host, opt< one< ':' >, port > > {};
// PEG are different from CFGs! (this replaces ctext and qdtext)
using text = sor< HTAB, range< 0x20, 0x7E >, obs_text >;
struct quoted_pair : if_must< one< '\\' >, sor< VCHAR, obs_text, WSP > > {};
struct quoted_string : if_must< DQUOTE, until< DQUOTE, sor< quoted_pair, text > > > {};
struct transfer_parameter : seq< token, BWS, one< '=' >, BWS, sor< token, quoted_string > > {};
struct transfer_extension : seq< token, star< OWS, one< ';' >, OWS, transfer_parameter > > {};
struct transfer_coding : sor< pegtl_istring_t( "chunked" ),
pegtl_istring_t( "compress" ),
pegtl_istring_t( "deflate" ),
pegtl_istring_t( "gzip" ),
transfer_extension > {};
struct rank : sor< seq< one< '0' >, opt< one< '.' >, rep_opt< 3, DIGIT > > >,
seq< one< '1' >, opt< one< '.' >, rep_opt< 3, one< '0' > > > > > {};
struct t_ranking : seq< OWS, one< ';' >, OWS, one< 'q', 'Q' >, one< '=' >, rank > {};
struct t_codings : sor< pegtl_istring_t( "trailers" ), seq< transfer_coding, opt< t_ranking > > > {};
struct TE : opt< sor< one< ',' >, t_codings >, star< OWS, one< ',' >, opt< OWS, t_codings > > > {};
template< typename T >
using make_comma_list = seq< star< one< ',' >, OWS >, T, star< OWS, one< ',' >, opt< OWS, T > > >;
struct connection_option : token {};
struct Connection : make_comma_list< connection_option > {};
struct Trailer : make_comma_list< field_name > {};
struct Transfer_Encoding : make_comma_list< transfer_coding > {};
struct protocol_name : token {};
struct protocol_version : token {};
struct protocol : seq< protocol_name, opt< one< '/' >, protocol_version > > {};
struct Upgrade : make_comma_list< protocol > {};
struct pseudonym : token {};
struct received_protocol : seq< opt< protocol_name, one< '/' > >, protocol_version > {};
struct received_by : sor< seq< uri_host, opt< one< ':' >, port > >, pseudonym > {};
struct comment : if_must< one< '(' >, until< one< ')' >, sor< comment, quoted_pair, text > > > {};
struct Via : make_comma_list< seq< received_protocol, RWS, received_by, opt< RWS, comment > > > {};
struct http_URI : if_must< pegtl_istring_t( "http://" ), uri::authority, uri::path_abempty, uri::opt_query, uri::opt_fragment > {};
struct https_URI : if_must< pegtl_istring_t( "https://" ), uri::authority, uri::path_abempty, uri::opt_query, uri::opt_fragment > {};
struct partial_URI : seq< uri::relative_part, uri::opt_query > {};
struct chunk_size : plus< HEXDIG > {};
struct chunk_ext_name : token {};
struct chunk_ext_val : sor< quoted_string, token > {};
struct chunk_ext : star< if_must< one< ';' >, chunk_ext_name, if_must< one< '=' >, chunk_ext_val > > > {};
struct chunk_data : until< at< CRLF >, OCTET > {};
struct chunk : seq< chunk_size, opt< chunk_ext >, CRLF, chunk_data, CRLF > {};
struct last_chunk : seq< plus< one< '0' > >, opt< chunk_ext >, CRLF > {};
struct trailer_part : star< header_field, CRLF > {};
struct chunked_body : seq< until< last_chunk, chunk >, trailer_part, CRLF > {};
} // http
} // pegtl
#endif
<commit_msg>Fix bug in HTTP grammar.<commit_after>// Copyright (c) 2014-2015 Dr. Colin Hirsch and Daniel Frey
// Please see LICENSE for license or visit https://github.com/ColinH/PEGTL/
#ifndef PEGTL_CONTRIB_HTTP_HH
#define PEGTL_CONTRIB_HTTP_HH
#include "../rules.hh"
#include "../ascii.hh"
#include "../utf8.hh"
#include "abnf.hh"
#include "uri.hh"
namespace pegtl
{
namespace http
{
// HTTP 1.1 grammar according to RFC 7230.
// This grammar is a direct PEG translation of the original HTTP grammar.
// It should be considered experimental -- in case of any issues, in particular
// missing anchor rules for actions, please contact the developers.
using namespace abnf;
using OWS = star< WSP >; // optional whitespace
using RWS = plus< WSP >; // required whitespace
using BWS = OWS; // "bad" whitespace
using obs_text = not_range< 0x00, 0x7F >;
using obs_fold = seq< CRLF, plus< WSP > >;
struct tchar : sor< ALPHA, DIGIT, one< '!', '#', '$', '%', '&', '\'', '*', '+', '-', '.', '^', '_', '`', '|', '~' > > {};
struct token : plus< tchar > {};
struct field_name : token {};
struct field_vchar : sor< VCHAR, obs_text > {};
struct field_content : list< field_vchar, plus< WSP > > {};
struct field_value : star< sor< field_content, obs_fold > > {};
struct header_field : seq< field_name, one< ':' >, OWS, field_value, OWS > {};
struct method : token {};
struct absolute_path : plus< one< '/' >, uri::segment > {};
struct origin_form : seq< absolute_path, uri::opt_query > {};
struct absolute_form : uri::absolute_URI {};
struct authority_form : uri::authority {};
struct asterisk_form : one< '*' > {};
struct request_target : sor< origin_form, absolute_form, authority_form, asterisk_form > {};
struct status_code : rep< 3, DIGIT > {};
struct reason_phrase : star< sor< VCHAR, obs_text, WSP > > {};
struct HTTP_version : if_must< pegtl_string_t( "HTTP/" ), DIGIT, one< '.' >, DIGIT > {};
struct request_line : if_must< method, SP, request_target, SP, HTTP_version, CRLF > {};
struct status_line : if_must< HTTP_version, SP, status_code, SP, reason_phrase, CRLF > {};
struct start_line : sor< request_line, status_line > {};
struct message_body : star< OCTET > {};
struct HTTP_message : seq< start_line, star< header_field, CRLF >, CRLF, opt< message_body > > {};
struct Content_Length : plus< DIGIT > {};
struct uri_host : uri::host {};
struct port : uri::port {};
struct Host : seq< uri_host, opt< one< ':' >, port > > {};
// PEG are different from CFGs! (this replaces ctext and qdtext)
using text = sor< HTAB, range< 0x20, 0x7E >, obs_text >;
struct quoted_pair : if_must< one< '\\' >, sor< VCHAR, obs_text, WSP > > {};
struct quoted_string : if_must< DQUOTE, until< DQUOTE, sor< quoted_pair, text > > > {};
struct transfer_parameter : seq< token, BWS, one< '=' >, BWS, sor< token, quoted_string > > {};
struct transfer_extension : seq< token, star< OWS, one< ';' >, OWS, transfer_parameter > > {};
struct transfer_coding : sor< pegtl_istring_t( "chunked" ),
pegtl_istring_t( "compress" ),
pegtl_istring_t( "deflate" ),
pegtl_istring_t( "gzip" ),
transfer_extension > {};
struct rank : sor< seq< one< '0' >, opt< one< '.' >, rep_opt< 3, DIGIT > > >,
seq< one< '1' >, opt< one< '.' >, rep_opt< 3, one< '0' > > > > > {};
struct t_ranking : seq< OWS, one< ';' >, OWS, one< 'q', 'Q' >, one< '=' >, rank > {};
struct t_codings : sor< pegtl_istring_t( "trailers" ), seq< transfer_coding, opt< t_ranking > > > {};
struct TE : opt< sor< one< ',' >, t_codings >, star< OWS, one< ',' >, opt< OWS, t_codings > > > {};
template< typename T >
using make_comma_list = seq< star< one< ',' >, OWS >, T, star< OWS, one< ',' >, opt< OWS, T > > >;
struct connection_option : token {};
struct Connection : make_comma_list< connection_option > {};
struct Trailer : make_comma_list< field_name > {};
struct Transfer_Encoding : make_comma_list< transfer_coding > {};
struct protocol_name : token {};
struct protocol_version : token {};
struct protocol : seq< protocol_name, opt< one< '/' >, protocol_version > > {};
struct Upgrade : make_comma_list< protocol > {};
struct pseudonym : token {};
struct received_protocol : seq< opt< protocol_name, one< '/' > >, protocol_version > {};
struct received_by : sor< seq< uri_host, opt< one< ':' >, port > >, pseudonym > {};
struct comment : if_must< one< '(' >, until< one< ')' >, sor< comment, quoted_pair, text > > > {};
struct Via : make_comma_list< seq< received_protocol, RWS, received_by, opt< RWS, comment > > > {};
struct http_URI : if_must< pegtl_istring_t( "http://" ), uri::authority, uri::path_abempty, uri::opt_query, uri::opt_fragment > {};
struct https_URI : if_must< pegtl_istring_t( "https://" ), uri::authority, uri::path_abempty, uri::opt_query, uri::opt_fragment > {};
struct partial_URI : seq< uri::relative_part, uri::opt_query > {};
struct chunk_size : plus< HEXDIG > {};
struct chunk_ext_name : token {};
struct chunk_ext_val : sor< quoted_string, token > {};
struct chunk_ext : star< if_must< one< ';' >, chunk_ext_name, if_must< one< '=' >, chunk_ext_val > > > {};
struct chunk_data : until< at< CRLF >, OCTET > {};
struct chunk : seq< chunk_size, opt< chunk_ext >, CRLF, chunk_data, CRLF > {};
struct last_chunk : seq< plus< one< '0' > >, opt< chunk_ext >, CRLF > {};
struct trailer_part : star< header_field, CRLF > {};
struct chunked_body : seq< until< last_chunk, chunk >, trailer_part, CRLF > {};
} // http
} // pegtl
#endif
<|endoftext|> |
<commit_before>/*
* tt.overdrive~
* External object for Max/MSP
*
* Example project for TTBlue
* Copyright © 2008 by Timothy Place
*
* License: This code is licensed under the terms of the GNU LGPL
* http://www.gnu.org/licenses/lgpl.html
*/
#include "TTClassWrapperMax.h"
#include "TTOverdrive.h"
// For the tt.overdrive~ object, we wish to use the class wrapper to make the process of turning the object into a Max class easy.
// However, we also need to maintain backward compatibility, which means that we need to support some older names for attributes in Max.
// We do this by subclassing TTOverdrive and adding some new attribute/message bindings to the existing parent class.
// Then the class wrapper will use this subclass to create the Max object.
class TTOverdriveExtended : public TTOverdrive {
public:
// Constructor
TTOverdriveExtended(TTUInt16 newMaxNumChannels)
: TTOverdrive(newMaxNumChannels)
{
registerAttribute(TT("overdrive"), kTypeFloat64, &drive, (TTSetterMethod)&TTOverdrive::setdrive);
registerAttribute(TT("/saturation"), kTypeFloat64, &drive, (TTSetterMethod)&TTOverdrive::setdrive);
registerAttribute(TT("bypass_dcblocker"), kTypeBoolean, &dcBlocker, (TTSetterMethod)&TTOverdrive::setdcBlocker);
registerAttribute(TT("/dcblocker/bypass"), kTypeBoolean, &dcBlocker, (TTSetterMethod)&TTOverdrive::setdcBlocker);
registerAttribute(TT("/preamp"), kTypeFloat64, &preamp, (TTGetterMethod)&TTOverdrive::getpreamp, (TTSetterMethod)&TTOverdrive::setpreamp);
registerAttribute(TT("/mode"), kTypeUInt8, &mode, (TTSetterMethod)&TTOverdrive::setmode);
registerAttribute(TT("/audio/mute"), kTypeBoolean, &attrMute, (TTSetterMethod)&TTAudioObject::setMute);
}
// Destructor
virtual ~TTOverdriveExtended()
{
;
}
};
// Because we have created this overdriveExtended class outside of the main TTBlue framework,
// we have to define our own factory method that is used to create a new instance of our object.
TTObject* instantiateOverdriveExtended(TTSymbolPtr className, TTValue& arguments)
{
return new TTOverdriveExtended(arguments);
}
int main(void)
{
// First, we have to register our custom subclass with the TTBlue framework.
TTBlueInit();
TTClassRegister(TT("overdriveExtended"), "audio, processor, effect, MSP", &instantiateOverdriveExtended);
// Then we are able to wrap it as a Max class.
return wrapTTClassAsMaxClass(TT("overdriveExtended"), "tt.overdrive~", NULL);
}
<commit_msg>Making this object compatible as a replacement for the old jcom.saturation~ external in Jamoma.<commit_after>/*
* tt.overdrive~
* External object for Max/MSP
*
* Example project for TTBlue
* Copyright © 2008 by Timothy Place
*
* License: This code is licensed under the terms of the GNU LGPL
* http://www.gnu.org/licenses/lgpl.html
*/
#include "TTClassWrapperMax.h"
#include "TTOverdrive.h"
#define thisTTClass TTOverdriveExtended
// For the tt.overdrive~ object, we wish to use the class wrapper to make the process of turning the object into a Max class easy.
// However, we also need to maintain backward compatibility, which means that we need to support some older names for attributes in Max.
// We do this by subclassing TTOverdrive and adding some new attribute/message bindings to the existing parent class.
// Then the class wrapper will use this subclass to create the Max object.
class TTOverdriveExtended : public TTOverdrive {
public:
// Constructor
TTOverdriveExtended(TTUInt16 newMaxNumChannels)
: TTOverdrive(newMaxNumChannels)
{
registerAttribute(TT("overdrive"), kTypeFloat64, &drive, (TTSetterMethod)&TTOverdrive::setdrive);
registerAttribute(TT("/saturation"), kTypeFloat64, &drive, (TTSetterMethod)&TTOverdrive::setdrive);
registerAttribute(TT("/depth"), kTypeFloat64, &drive, (TTSetterMethod)&TTOverdrive::setdrive);
registerAttribute(TT("bypass_dcblocker"), kTypeBoolean, &dcBlocker, (TTSetterMethod)&TTOverdrive::setdcBlocker);
registerAttribute(TT("/dcblocker/bypass"), kTypeBoolean, &dcBlocker, (TTSetterMethod)&TTOverdrive::setdcBlocker);
registerAttribute(TT("/preamp"), kTypeFloat64, &preamp, (TTGetterMethod)&TTOverdrive::getpreamp, (TTSetterMethod)&TTOverdrive::setpreamp);
registerAttribute(TT("/mode"), kTypeUInt8, &mode, (TTSetterMethod)&TTOverdrive::setmode);
registerAttribute(TT("/audio/mute"), kTypeBoolean, &attrMute, (TTSetterMethod)&TTAudioObject::setMute);
registerMessageSimple(anything);
}
// Destructor
virtual ~TTOverdriveExtended()
{
;
}
TTErr anything()
{
return kTTErrNone;
}
};
// Because we have created this overdriveExtended class outside of the main TTBlue framework,
// we have to define our own factory method that is used to create a new instance of our object.
TTObject* instantiateOverdriveExtended(TTSymbolPtr className, TTValue& arguments)
{
return new TTOverdriveExtended(arguments);
}
int main(void)
{
// First, we have to register our custom subclass with the TTBlue framework.
TTBlueInit();
TTClassRegister(TT("overdriveExtended"), "audio, processor, effect, MSP", &instantiateOverdriveExtended);
// Then we are able to wrap it as a Max class.
return wrapTTClassAsMaxClass(TT("overdriveExtended"), "tt.overdrive~", NULL);
}
<|endoftext|> |
<commit_before>/*
* Copyright 2013 Google Inc.
*
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*/
#include "SkPdfDiffEncoder.h"
#include "SkPdfNativeTokenizer.h"
#ifdef PDF_TRACE_DIFF_IN_PNG
#include "SkBitmap.h"
#include "SkBitmapDevice.h"
#include "SkCanvas.h"
#include "SkClipStack.h"
#include "SkColor.h"
#include "SkImageEncoder.h"
#include "SkPaint.h"
#include "SkPath.h"
#include "SkRegion.h"
#include "SkScalar.h"
#include "SkString.h"
extern "C" SkBitmap* gDumpBitmap;
extern "C" SkCanvas* gDumpCanvas;
SkBitmap* gDumpBitmap = NULL;
SkCanvas* gDumpCanvas = NULL;
static int gReadOp;
static int gOpCounter;
static SkString gLastKeyword;
#endif // PDF_TRACE_DIFF_IN_PNG
void SkPdfDiffEncoder::WriteToFile(PdfToken* token) {
#ifdef PDF_TRACE_DIFF_IN_PNG
gReadOp++;
gOpCounter++;
// Only attempt to write if the dump bitmap and canvas are non NULL. They are set by
// pdf_viewer_main.cpp
if (NULL == gDumpBitmap || NULL == gDumpCanvas) {
return;
}
// TODO(edisonn): this code is used to make a step by step history of all the draw operations
// so we could find the step where something is wrong.
if (!gLastKeyword.isEmpty()) {
gDumpCanvas->flush();
// Copy the existing drawing. Then we will draw the difference caused by this command,
// highlighted with a blue border.
SkBitmap bitmap;
if (gDumpBitmap->copyTo(&bitmap, SkBitmap::kARGB_8888_Config)) {
SkAutoTUnref<SkBaseDevice> device(SkNEW_ARGS(SkBitmapDevice, (bitmap)));
SkCanvas canvas(device);
// draw context stuff here
SkPaint blueBorder;
blueBorder.setColor(SK_ColorBLUE);
blueBorder.setStyle(SkPaint::kStroke_Style);
blueBorder.setTextSize(SkDoubleToScalar(20));
SkString str;
const SkClipStack* clipStack = gDumpCanvas->getClipStack();
if (clipStack) {
SkClipStack::Iter iter(*clipStack, SkClipStack::Iter::kBottom_IterStart);
const SkClipStack::Element* elem;
double y = 0;
int total = 0;
while ((elem = iter.next()) != NULL) {
total++;
y += 30;
switch (elem->getType()) {
case SkClipStack::Element::kRect_Type:
canvas.drawRect(elem->getRect(), blueBorder);
canvas.drawText("Rect Clip", strlen("Rect Clip"),
SkDoubleToScalar(10), SkDoubleToScalar(y), blueBorder);
break;
case SkClipStack::Element::kPath_Type:
canvas.drawPath(elem->getPath(), blueBorder);
canvas.drawText("Path Clip", strlen("Path Clip"),
SkDoubleToScalar(10), SkDoubleToScalar(y), blueBorder);
break;
case SkClipStack::Element::kEmpty_Type:
canvas.drawText("Empty Clip!!!", strlen("Empty Clip!!!"),
SkDoubleToScalar(10), SkDoubleToScalar(y), blueBorder);
break;
default:
canvas.drawText("Unknown Clip!!!", strlen("Unknown Clip!!!"),
SkDoubleToScalar(10), SkDoubleToScalar(y), blueBorder);
break;
}
}
y += 30;
str.printf("Number of clips in stack: %i", total);
canvas.drawText(str.c_str(), str.size(),
SkDoubleToScalar(10), SkDoubleToScalar(y), blueBorder);
}
const SkRegion& clipRegion = gDumpCanvas->getTotalClip();
SkPath clipPath;
if (clipRegion.getBoundaryPath(&clipPath)) {
SkPaint redBorder;
redBorder.setColor(SK_ColorRED);
redBorder.setStyle(SkPaint::kStroke_Style);
canvas.drawPath(clipPath, redBorder);
}
canvas.flush();
SkString out;
// TODO(edisonn): overlay on top of image inf about the clip , grafic state, the stack
out.appendf("/tmp/log_step_by_step/step-%i-%s.png", gOpCounter, gLastKeyword.c_str());
SkImageEncoder::EncodeFile(out.c_str(), bitmap, SkImageEncoder::kPNG_Type, 100);
}
}
if (token->fType == kKeyword_TokenType && token->fKeyword && token->fKeywordLength > 0) {
gLastKeyword.set(token->fKeyword, token->fKeywordLength);
} else {
gLastKeyword.reset();
}
#endif
}
<commit_msg>Sanitizing source files in Housekeeper-Nightly<commit_after>/*
* Copyright 2013 Google Inc.
*
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*/
#include "SkPdfDiffEncoder.h"
#include "SkPdfNativeTokenizer.h"
#ifdef PDF_TRACE_DIFF_IN_PNG
#include "SkBitmap.h"
#include "SkBitmapDevice.h"
#include "SkCanvas.h"
#include "SkClipStack.h"
#include "SkColor.h"
#include "SkImageEncoder.h"
#include "SkPaint.h"
#include "SkPath.h"
#include "SkRegion.h"
#include "SkScalar.h"
#include "SkString.h"
extern "C" SkBitmap* gDumpBitmap;
extern "C" SkCanvas* gDumpCanvas;
SkBitmap* gDumpBitmap = NULL;
SkCanvas* gDumpCanvas = NULL;
static int gReadOp;
static int gOpCounter;
static SkString gLastKeyword;
#endif // PDF_TRACE_DIFF_IN_PNG
void SkPdfDiffEncoder::WriteToFile(PdfToken* token) {
#ifdef PDF_TRACE_DIFF_IN_PNG
gReadOp++;
gOpCounter++;
// Only attempt to write if the dump bitmap and canvas are non NULL. They are set by
// pdf_viewer_main.cpp
if (NULL == gDumpBitmap || NULL == gDumpCanvas) {
return;
}
// TODO(edisonn): this code is used to make a step by step history of all the draw operations
// so we could find the step where something is wrong.
if (!gLastKeyword.isEmpty()) {
gDumpCanvas->flush();
// Copy the existing drawing. Then we will draw the difference caused by this command,
// highlighted with a blue border.
SkBitmap bitmap;
if (gDumpBitmap->copyTo(&bitmap, SkBitmap::kARGB_8888_Config)) {
SkAutoTUnref<SkBaseDevice> device(SkNEW_ARGS(SkBitmapDevice, (bitmap)));
SkCanvas canvas(device);
// draw context stuff here
SkPaint blueBorder;
blueBorder.setColor(SK_ColorBLUE);
blueBorder.setStyle(SkPaint::kStroke_Style);
blueBorder.setTextSize(SkDoubleToScalar(20));
SkString str;
const SkClipStack* clipStack = gDumpCanvas->getClipStack();
if (clipStack) {
SkClipStack::Iter iter(*clipStack, SkClipStack::Iter::kBottom_IterStart);
const SkClipStack::Element* elem;
double y = 0;
int total = 0;
while ((elem = iter.next()) != NULL) {
total++;
y += 30;
switch (elem->getType()) {
case SkClipStack::Element::kRect_Type:
canvas.drawRect(elem->getRect(), blueBorder);
canvas.drawText("Rect Clip", strlen("Rect Clip"),
SkDoubleToScalar(10), SkDoubleToScalar(y), blueBorder);
break;
case SkClipStack::Element::kPath_Type:
canvas.drawPath(elem->getPath(), blueBorder);
canvas.drawText("Path Clip", strlen("Path Clip"),
SkDoubleToScalar(10), SkDoubleToScalar(y), blueBorder);
break;
case SkClipStack::Element::kEmpty_Type:
canvas.drawText("Empty Clip!!!", strlen("Empty Clip!!!"),
SkDoubleToScalar(10), SkDoubleToScalar(y), blueBorder);
break;
default:
canvas.drawText("Unknown Clip!!!", strlen("Unknown Clip!!!"),
SkDoubleToScalar(10), SkDoubleToScalar(y), blueBorder);
break;
}
}
y += 30;
str.printf("Number of clips in stack: %i", total);
canvas.drawText(str.c_str(), str.size(),
SkDoubleToScalar(10), SkDoubleToScalar(y), blueBorder);
}
const SkRegion& clipRegion = gDumpCanvas->getTotalClip();
SkPath clipPath;
if (clipRegion.getBoundaryPath(&clipPath)) {
SkPaint redBorder;
redBorder.setColor(SK_ColorRED);
redBorder.setStyle(SkPaint::kStroke_Style);
canvas.drawPath(clipPath, redBorder);
}
canvas.flush();
SkString out;
// TODO(edisonn): overlay on top of image inf about the clip , grafic state, the stack
out.appendf("/tmp/log_step_by_step/step-%i-%s.png", gOpCounter, gLastKeyword.c_str());
SkImageEncoder::EncodeFile(out.c_str(), bitmap, SkImageEncoder::kPNG_Type, 100);
}
}
if (token->fType == kKeyword_TokenType && token->fKeyword && token->fKeywordLength > 0) {
gLastKeyword.set(token->fKeyword, token->fKeywordLength);
} else {
gLastKeyword.reset();
}
#endif
}
<|endoftext|> |
<commit_before>#include <stdint.h>
#include <stdlib.h>
#include <sys/types.h>
#include <inttypes.h>
#include "jansson.h"
static int enable_diags;
#define FUZZ_DEBUG(FMT, ...) \
if (enable_diags) \
{ \
fprintf(stderr, FMT, ##__VA_ARGS__); \
fprintf(stderr, "\n"); \
}
static int json_dump_counter(const char *buffer, size_t size, void *data)
{
uint64_t *counter = reinterpret_cast<uint64_t *>(data);
*counter += size;
return 0;
}
extern "C" int LLVMFuzzerTestOneInput(const uint8_t *data, size_t size)
{
json_error_t error;
// Enable or disable diagnostics based on the FUZZ_VERBOSE environment flag.
enable_diags = (getenv("FUZZ_VERBOSE") != NULL);
FUZZ_DEBUG("Input data length: %zd", size);
if (size < sizeof(size_t) + sizeof(size_t))
{
return 0;
}
// Use the first sizeof(size_t) bytes as load flags.
size_t load_flags = *(const size_t*)data;
data += sizeof(size_t);
size -= sizeof(size_t);
FUZZ_DEBUG("load_flags: 0x%zx\n"
"& JSON_REJECT_DUPLICATES = 0x%zx\n"
"& JSON_DECODE_ANY = 0x%zx\n"
"& JSON_DISABLE_EOF_CHECK = 0x%zx\n"
"& JSON_DECODE_INT_AS_REAL = 0x%zx\n"
"& JSON_ALLOW_NUL = 0x%zx\n",
load_flags,
load_flags & JSON_REJECT_DUPLICATES,
load_flags & JSON_DECODE_ANY,
load_flags & JSON_DISABLE_EOF_CHECK,
load_flags & JSON_DECODE_INT_AS_REAL,
load_flags & JSON_ALLOW_NUL);
// Use the next sizeof(size_t) bytes as dump flags.
size_t dump_flags = *(const size_t*)data;
data += sizeof(size_t);
size -= sizeof(size_t);
FUZZ_DEBUG("dump_flags: 0x%zx\n"
"& JSON_MAX_INDENT = 0x%zx\n"
"& JSON_COMPACT = 0x%zx\n"
"& JSON_ENSURE_ASCII = 0x%zx\n"
"& JSON_SORT_KEYS = 0x%zx\n"
"& JSON_PRESERVE_ORDER = 0x%zx\n"
"& JSON_ENCODE_ANY = 0x%zx\n"
"& JSON_ESCAPE_SLASH = 0x%zx\n"
"& JSON_REAL_PRECISION = 0x%zx\n"
"& JSON_EMBED = 0x%zx\n",
dump_flags,
dump_flags & JSON_MAX_INDENT,
dump_flags & JSON_COMPACT,
dump_flags & JSON_ENSURE_ASCII,
dump_flags & JSON_SORT_KEYS,
dump_flags & JSON_PRESERVE_ORDER,
dump_flags & JSON_ENCODE_ANY,
dump_flags & JSON_ESCAPE_SLASH,
((dump_flags >> 11) & 0x1F) << 11,
dump_flags & JSON_EMBED);
// Attempt to load the remainder of the data with the given load flags.
const char* text = reinterpret_cast<const char *>(data);
json_t* jobj = json_loadb(text, size, load_flags, &error);
if (jobj == NULL)
{
return 0;
}
// Attempt to dump the loaded json object with the given dump flags.
uint64_t counter = 0;
json_dump_callback(jobj, json_dump_counter, &counter, dump_flags);
FUZZ_DEBUG("Counter function counted %" PRIu64 " bytes.", counter);
if (jobj)
{
json_decref(jobj);
}
return 0;
}
<commit_msg>Depending on the dump_mode byte, dump out as a string or as a callback.<commit_after>#include <stdint.h>
#include <stdlib.h>
#include <sys/types.h>
#include <inttypes.h>
#include "jansson.h"
static int enable_diags;
#define FUZZ_DEBUG(FMT, ...) \
if (enable_diags) \
{ \
fprintf(stderr, FMT, ##__VA_ARGS__); \
fprintf(stderr, "\n"); \
}
static int json_dump_counter(const char *buffer, size_t size, void *data)
{
uint64_t *counter = reinterpret_cast<uint64_t *>(data);
*counter += size;
return 0;
}
#define NUM_COMMAND_BYTES (sizeof(size_t) + sizeof(size_t) + 1)
#define FUZZ_DUMP_CALLBACK 0x00
#define FUZZ_DUMP_STRING 0x01
extern "C" int LLVMFuzzerTestOneInput(const uint8_t *data, size_t size)
{
json_error_t error;
unsigned char dump_mode;
// Enable or disable diagnostics based on the FUZZ_VERBOSE environment flag.
enable_diags = (getenv("FUZZ_VERBOSE") != NULL);
FUZZ_DEBUG("Input data length: %zd", size);
if (size < NUM_COMMAND_BYTES)
{
return 0;
}
// Use the first sizeof(size_t) bytes as load flags.
size_t load_flags = *(const size_t*)data;
data += sizeof(size_t);
FUZZ_DEBUG("load_flags: 0x%zx\n"
"& JSON_REJECT_DUPLICATES = 0x%zx\n"
"& JSON_DECODE_ANY = 0x%zx\n"
"& JSON_DISABLE_EOF_CHECK = 0x%zx\n"
"& JSON_DECODE_INT_AS_REAL = 0x%zx\n"
"& JSON_ALLOW_NUL = 0x%zx\n",
load_flags,
load_flags & JSON_REJECT_DUPLICATES,
load_flags & JSON_DECODE_ANY,
load_flags & JSON_DISABLE_EOF_CHECK,
load_flags & JSON_DECODE_INT_AS_REAL,
load_flags & JSON_ALLOW_NUL);
// Use the next sizeof(size_t) bytes as dump flags.
size_t dump_flags = *(const size_t*)data;
data += sizeof(size_t);
FUZZ_DEBUG("dump_flags: 0x%zx\n"
"& JSON_MAX_INDENT = 0x%zx\n"
"& JSON_COMPACT = 0x%zx\n"
"& JSON_ENSURE_ASCII = 0x%zx\n"
"& JSON_SORT_KEYS = 0x%zx\n"
"& JSON_PRESERVE_ORDER = 0x%zx\n"
"& JSON_ENCODE_ANY = 0x%zx\n"
"& JSON_ESCAPE_SLASH = 0x%zx\n"
"& JSON_REAL_PRECISION = 0x%zx\n"
"& JSON_EMBED = 0x%zx\n",
dump_flags,
dump_flags & JSON_MAX_INDENT,
dump_flags & JSON_COMPACT,
dump_flags & JSON_ENSURE_ASCII,
dump_flags & JSON_SORT_KEYS,
dump_flags & JSON_PRESERVE_ORDER,
dump_flags & JSON_ENCODE_ANY,
dump_flags & JSON_ESCAPE_SLASH,
((dump_flags >> 11) & 0x1F) << 11,
dump_flags & JSON_EMBED);
// Use the next byte as the dump mode.
dump_mode = data[0];
data++;
FUZZ_DEBUG("dump_mode: 0x%x", (unsigned int)dump_mode);
// Remove the command bytes from the size total.
size -= NUM_COMMAND_BYTES;
// Attempt to load the remainder of the data with the given load flags.
const char* text = reinterpret_cast<const char *>(data);
json_t* jobj = json_loadb(text, size, load_flags, &error);
if (jobj == NULL)
{
return 0;
}
if (dump_mode & FUZZ_DUMP_STRING)
{
// Dump as a string. Remove indents so that we don't run out of memory.
char *out = json_dumps(jobj, dump_flags & ~JSON_MAX_INDENT);
if (out != NULL)
{
free(out);
}
}
else
{
// Default is callback mode.
//
// Attempt to dump the loaded json object with the given dump flags.
uint64_t counter = 0;
json_dump_callback(jobj, json_dump_counter, &counter, dump_flags);
FUZZ_DEBUG("Counter function counted %" PRIu64 " bytes.", counter);
}
if (jobj)
{
json_decref(jobj);
}
return 0;
}
<|endoftext|> |
<commit_before>/* IBM_PROLOG_BEGIN_TAG */
/* This is an automatically generated prolog. */
/* */
/* $Source: $ */
/* */
/* OpenPOWER HostBoot Project */
/* */
/* Contributors Listed Below - COPYRIGHT 2012,2014 */
/* [+] International Business Machines Corp. */
/* */
/* */
/* 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. */
/* */
/* IBM_PROLOG_END_TAG */
/**
* @file buffer_traits.H
* @brief trait definitions for fapi2 buffer base class
*/
#ifndef __FAPI2_BUFFER_TRAITS__
#define __FAPI2_BUFFER_TRAITS__
#include <stdint.h>
#include <vector>
#include <algorithm>
#include <buffer_parameters.H>
#ifdef FAPI2_DEBUG
#include <iostream>
#endif
#include <iterator>
namespace fapi2
{
/// @cond
/// Types representing a container of bits. Used to create
/// variable_buffer. container_unit must remain 32-bits
/// for now - there will be a lot of code to change if it
/// changes. There are assertions helping to enforce this
/// in places in the code.
typedef uint32_t container_unit;
typedef std::vector<container_unit> bits_container;
/// @brief Traits of buffers
// In general, we try to give buffers traits reflecting integral types. If
// this fails, the compiler will let someone know.
///
/// @tparam T is the type of iv_data (std::vector, etc)
/// @tparam B is the type of the bit-specifier, typically uint32_t
template<typename T, typename B = uint32_t>
class bufferTraits
{
public:
#if !defined(DOXYGEN) && defined(FAPI2_DEBUG)
///
/// @brief Print a container of bits
/// @param[in] i_data the container of bits
///
static inline void print(const T& i_data)
{
// convert to uint64_t to prevent uint8_t from being
// printed as a char.
std::cout << "\tdata is "
<< std::hex
<< static_cast<uint64_t>(i_data)
<< std::dec << std::endl;
}
#endif
///
/// @brief Return the size of the buffer in E units
/// @tparam E, the element size.
/// @param[in] io_buffer the buffer which to size
/// @return The size of the buffer in E's rounded up
///
template<typename E>
constexpr static B size(const T& i_buffer)
{
return (bit_length(i_buffer) +
(parameterTraits<E>::bit_length() - 1)) /
parameterTraits<E>::bit_length();
}
///
/// @brief Return the size of the buffer itself
/// @param[in] io_buffer the buffer which to size
/// @return The size of the buffer in bits (not units)
///
constexpr static B bit_length(const T&)
{ return sizeof(T) * 8; }
///
/// @brief Clear the buffer
/// @param[in,out] io_buffer the buffer which to clear
///
static inline void clear(T& io_buffer)
{ io_buffer = static_cast<T>(0); }
///
/// @brief Set the buffer
/// @param[in,out] io_buffer the buffer which to set
///
static inline void set(T& io_buffer)
{ io_buffer = static_cast<T>(~0); }
///
/// @brief Invert the buffer
/// @param[in,out] io_buffer the buffer which to invert
///
static inline void invert(T& io_buffer)
{ io_buffer = ~io_buffer; }
///
/// @brief Reverse the buffer
/// @param[in,out] io_buffer the buffer which to reverse
///
static inline void reverse(T& io_buffer)
{
io_buffer =
((io_buffer & 0xAAAAAAAAAAAAAAAA) >> 1) |
((io_buffer & 0x5555555555555555) << 1);
}
///
/// @brief Get the address of the buffer as an array
/// @param[in] i_buffer the buffer which to invert
/// @return The address of the first element of the buffer
///
static inline void* get_address(T& i_buffer)
{ return (void*)&i_buffer; }
typedef B bits_type;
typedef T unit_type;
constexpr static uint32_t bits_per_unit(void)
{ return sizeof(unit_type) * 8; }
};
//
//
/// @brief Traits for buffers which are a container of bits
//
//
template<>
class bufferTraits<bits_container, uint32_t>
{
public:
#if !defined(DOXYGEN) && defined(FAPI2_DEBUG)
///
/// @brief Print a container of bits
/// @param[in] i_data the container of bits
///
static inline void print(const bits_container& i_data)
{
std::cout << "\tdata is " << std::hex;
std::copy(i_data.begin(), i_data.end(),
std::ostream_iterator<container_unit>(std::cout, " "));
std::cout << std::dec << std::endl;
}
#endif
///
/// @brief Return the size of the buffer in E units
/// @tparam E, the element size.
/// @param[in] io_buffer the buffer which to size
/// @return The size of the buffer in E's rounded up
///
template<typename E>
constexpr static uint32_t size(const bits_container& i_buffer)
{
return (bit_length(i_buffer) +
(parameterTraits<E>::bit_length() - 1)) /
parameterTraits<E>::bit_length();
}
///
/// @brief Return the size of the buffer itself
/// @param[in,out] io_buffer the buffer which to size
/// @return The size of the buffer in bits (not units)
///
static inline uint32_t bit_length(const bits_container& i_buffer)
{ return i_buffer.size() * sizeof(container_unit) * 8; }
///
/// @brief Clear the buffer
/// @param[in,out] io_buffer the buffer which to clear
///
static inline void clear(bits_container& io_buffer)
{ io_buffer.assign(io_buffer.size(), 0); }
///
/// @brief Set the buffer
/// @param[in,out] io_buffer the buffer which to set
///
static inline void set(bits_container& io_buffer)
{ io_buffer.assign(io_buffer.size(), ~0); }
///
/// @brief Invert the buffer
/// @param[in,out] io_buffer the buffer which to invert
///
static inline void invert(bits_container& io_buffer)
{
std::transform(io_buffer.begin(), io_buffer.end(),
io_buffer.begin(),
[](container_unit u) { return ~u; });
}
///
/// @brief Get the address of the buffer as an array
/// @param[in] i_buffer the buffer which to invert
/// @return The address of the first element of the buffer
///
static inline void* get_address(bits_container& i_buffer)
{
return (void*)&(i_buffer[0]);
}
typedef uint32_t bits_type;
typedef container_unit unit_type;
constexpr static uint32_t bits_per_unit(void)
{ return sizeof(unit_type) * 8; }
};
/// @endcond
}
#endif
<commit_msg>buffer reverse not working correctly<commit_after>/* IBM_PROLOG_BEGIN_TAG */
/* This is an automatically generated prolog. */
/* */
/* $Source: hwpf/fapi2/include/buffer_traits.H $ */
/* */
/* IBM CONFIDENTIAL */
/* */
/* EKB Project */
/* */
/* COPYRIGHT 2012,2015 */
/* [+] International Business Machines Corp. */
/* */
/* */
/* The source code for this program is not published or otherwise */
/* divested of its trade secrets, irrespective of what has been */
/* deposited with the U.S. Copyright Office. */
/* */
/* IBM_PROLOG_END_TAG */
/**
* @file buffer_traits.H
* @brief trait definitions for fapi2 buffer base class
*/
#ifndef __FAPI2_BUFFER_TRAITS__
#define __FAPI2_BUFFER_TRAITS__
#include <stdint.h>
#include <vector>
#include <algorithm>
#include <buffer_parameters.H>
#ifdef FAPI2_DEBUG
#include <iostream>
#endif
#include <iterator>
namespace fapi2
{
/// @cond
/// Types representing a container of bits. Used to create
/// variable_buffer. container_unit must remain 32-bits
/// for now - there will be a lot of code to change if it
/// changes. There are assertions helping to enforce this
/// in places in the code.
typedef uint32_t container_unit;
typedef std::vector<container_unit> bits_container;
/// @brief Traits of buffers
// In general, we try to give buffers traits reflecting integral types. If
// this fails, the compiler will let someone know.
///
/// @tparam T is the type of iv_data (std::vector, etc)
/// @tparam B is the type of the bit-specifier, typically uint32_t
template<typename T, typename B = uint32_t>
class bufferTraits
{
public:
#if !defined(DOXYGEN) && defined(FAPI2_DEBUG)
///
/// @brief Print a container of bits
/// @param[in] i_data the container of bits
///
static inline void print(const T& i_data)
{
// convert to uint64_t to prevent uint8_t from being
// printed as a char.
std::cout << "\tdata is "
<< std::hex
<< static_cast<uint64_t>(i_data)
<< std::dec << std::endl;
}
#endif
///
/// @brief Return the size of the buffer in E units
/// @tparam E, the element size.
/// @param[in] io_buffer the buffer which to size
/// @return The size of the buffer in E's rounded up
///
template<typename E>
constexpr static B size(const T& i_buffer)
{
return (bit_length(i_buffer) +
(parameterTraits<E>::bit_length() - 1)) /
parameterTraits<E>::bit_length();
}
///
/// @brief Return the size of the buffer itself
/// @param[in] io_buffer the buffer which to size
/// @return The size of the buffer in bits (not units)
///
constexpr static B bit_length(const T&)
{
return sizeof(T) * 8;
}
///
/// @brief Clear the buffer
/// @param[in,out] io_buffer the buffer which to clear
///
static inline void clear(T& io_buffer)
{
io_buffer = static_cast<T>(0);
}
///
/// @brief Set the buffer
/// @param[in,out] io_buffer the buffer which to set
///
static inline void set(T& io_buffer)
{
io_buffer = static_cast<T>(~0);
}
///
/// @brief Invert the buffer
/// @param[in,out] io_buffer the buffer which to invert
///
static inline void invert(T& io_buffer)
{
io_buffer = ~io_buffer;
}
///
/// @brief Reverse the buffer
/// @param[in,out] io_buffer the buffer which to reverse
//
// @note from
// http://stackoverflow.com/questions/746171/best-algorithm-for-bit-reversal-from-msb-lsb-to-lsb-msb-in-c
///
static inline void reverse( T& io_buffer)
{
T l_result = io_buffer;
size_t l_s = sizeof(T) * 8 - 1;
for( io_buffer >>= 1; io_buffer; io_buffer >>= 1)
{
l_result <<= 1;
l_result |= io_buffer & 1;
l_s--;
}
l_result <<= l_s;
io_buffer = l_result;
}
///
/// @brief Get the address of the buffer as an array
/// @param[in] i_buffer the buffer which to invert
/// @return The address of the first element of the buffer
///
static inline void* get_address(T& i_buffer)
{
return (void*)&i_buffer;
}
typedef B bits_type;
typedef T unit_type;
constexpr static uint32_t bits_per_unit(void)
{
return sizeof(unit_type) * 8;
}
};
//
//
/// @brief Traits for buffers which are a container of bits
//
//
template<>
class bufferTraits<bits_container, uint32_t>
{
public:
#if !defined(DOXYGEN) && defined(FAPI2_DEBUG)
///
/// @brief Print a container of bits
/// @param[in] i_data the container of bits
///
static inline void print(const bits_container& i_data)
{
std::cout << "\tdata is " << std::hex;
std::copy(i_data.begin(), i_data.end(),
std::ostream_iterator<container_unit>(std::cout, " "));
std::cout << std::dec << std::endl;
}
#endif
///
/// @brief Return the size of the buffer in E units
/// @tparam E, the element size.
/// @param[in] io_buffer the buffer which to size
/// @return The size of the buffer in E's rounded up
///
template<typename E>
constexpr static uint32_t size(const bits_container& i_buffer)
{
return (bit_length(i_buffer) +
(parameterTraits<E>::bit_length() - 1)) /
parameterTraits<E>::bit_length();
}
///
/// @brief Return the size of the buffer itself
/// @param[in,out] io_buffer the buffer which to size
/// @return The size of the buffer in bits (not units)
///
static inline uint32_t bit_length(const bits_container& i_buffer)
{
return i_buffer.size() * sizeof(container_unit) * 8;
}
///
/// @brief Clear the buffer
/// @param[in,out] io_buffer the buffer which to clear
///
static inline void clear(bits_container& io_buffer)
{
io_buffer.assign(io_buffer.size(), 0);
}
///
/// @brief Set the buffer
/// @param[in,out] io_buffer the buffer which to set
///
static inline void set(bits_container& io_buffer)
{
io_buffer.assign(io_buffer.size(), ~0);
}
///
/// @brief Invert the buffer
/// @param[in,out] io_buffer the buffer which to invert
///
static inline void invert(bits_container& io_buffer)
{
std::transform(io_buffer.begin(), io_buffer.end(),
io_buffer.begin(),
[](container_unit u)
{
return ~u;
});
}
///
/// @brief Get the address of the buffer as an array
/// @param[in] i_buffer the buffer which to invert
/// @return The address of the first element of the buffer
///
static inline void* get_address(bits_container& i_buffer)
{
return (void*) & (i_buffer[0]);
}
typedef uint32_t bits_type;
typedef container_unit unit_type;
constexpr static uint32_t bits_per_unit(void)
{
return sizeof(unit_type) * 8;
}
};
/// @endcond
}
#endif
<|endoftext|> |
<commit_before>/**
* Copyright (c) 2016-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 <gtest/gtest.h>
#include "ConstantPropagation.h"
#include "IRAssembler.h"
static void do_const_prop(IRCode* code, const ConstPropConfig& config) {
code->build_cfg();
IntraProcConstantPropagation rcp(code->cfg(), config);
rcp.run(ConstPropEnvironment());
rcp.simplify();
rcp.apply_changes(code);
}
TEST(ConstantPropagation, IfToGoto) {
auto code = assembler::ircode_from_string(R"(
(
(const v0 0)
(if-eqz v0 :if-true-label)
(const v0 1)
:if-true-label
(const v0 2)
)
)");
ConstPropConfig config;
config.propagate_conditions = true;
do_const_prop(code.get(), config);
auto expected_code = assembler::ircode_from_string(R"(
(
(const v0 0)
(goto :if-true-label)
(const v0 1)
:if-true-label
(const v0 2)
)
)");
EXPECT_EQ(assembler::to_s_expr(code.get()),
assembler::to_s_expr(expected_code.get()));
}
TEST(ConstantPropagation, ConditionalConstant_EqualsAlwaysTrue) {
auto code = assembler::ircode_from_string(R"(
(
(const v0 0)
(const v1 0)
(if-eqz v0 :if-true-label-1)
(const v1 1) ; the preceding opcode always jumps, so this is unreachable
:if-true-label-1
(if-eqz v1 :if-true-label-2) ; therefore this is always true
(const v1 2)
:if-true-label-2
(return-void)
)
)");
ConstPropConfig config;
config.propagate_conditions = true;
do_const_prop(code.get(), config);
auto expected_code = assembler::ircode_from_string(R"(
(
(const v0 0)
(const v1 0)
(goto :if-true-label-1)
(const v1 1)
:if-true-label-1
(goto :if-true-label-2)
(const v1 2)
:if-true-label-2
(return-void)
)
)");
EXPECT_EQ(assembler::to_s_expr(code.get()),
assembler::to_s_expr(expected_code.get()));
}
TEST(ConstantPropagation, ConditionalConstant_EqualsAlwaysFalse) {
auto code = assembler::ircode_from_string(R"(
(
(const v0 1)
(const v1 1)
(if-eqz v0 :if-true-label-1)
(const v1 0) ; the preceding opcode never jumps, so this is always
; executed
:if-true-label-1
(if-eqz v1 :if-true-label-2) ; therefore this is always true
(const v1 2)
:if-true-label-2
(return-void)
)
)");
ConstPropConfig config;
config.propagate_conditions = true;
do_const_prop(code.get(), config);
auto expected_code = assembler::ircode_from_string(R"(
(
(const v0 1)
(const v1 1)
(const v1 0)
(goto :if-true-label-2)
(const v1 2)
:if-true-label-2
(return-void)
)
)");
EXPECT_EQ(assembler::to_s_expr(code.get()),
assembler::to_s_expr(expected_code.get()));
}
TEST(ConstantPropagation, ConditionalConstant_LessThanAlwaysTrue) {
auto code = assembler::ircode_from_string(R"(
(
(const v0 0)
(const v1 1)
(if-lt v0 v1 :if-true-label-1)
(const v1 0) ; the preceding opcode always jumps, so this is never
; executed
:if-true-label-1
(if-eqz v1 :if-true-label-2) ; therefore this is never true
(const v1 2)
:if-true-label-2
(return-void)
)
)");
ConstPropConfig config;
config.propagate_conditions = true;
do_const_prop(code.get(), config);
auto expected_code = assembler::ircode_from_string(R"(
(
(const v0 0)
(const v1 1)
(goto :if-true-label-1)
(const v1 0)
:if-true-label-1
(const v1 2)
(return-void)
)
)");
EXPECT_EQ(assembler::to_s_expr(code.get()),
assembler::to_s_expr(expected_code.get()));
}
TEST(ConstantPropagation, ConditionalConstant_LessThanAlwaysFalse) {
auto code = assembler::ircode_from_string(R"(
(
(const v0 1)
(const v1 0)
(if-lt v0 v1 :if-true-label-1)
(const v0 0) ; the preceding opcode never jumps, so this is always
; executed
:if-true-label-1
(if-eqz v0 :if-true-label-2) ; therefore this is always true
(const v1 2)
:if-true-label-2
(return-void)
)
)");
ConstPropConfig config;
config.propagate_conditions = true;
do_const_prop(code.get(), config);
auto expected_code = assembler::ircode_from_string(R"(
(
(const v0 1)
(const v1 0)
(const v0 0)
(goto :if-true-label-2)
(const v1 2)
:if-true-label-2
(return-void)
)
)");
EXPECT_EQ(assembler::to_s_expr(code.get()),
assembler::to_s_expr(expected_code.get()));
}
TEST(ConstantPropagation, ConditionalConstantInferZero) {
auto code = assembler::ircode_from_string(R"(
(
(load-param v0) ; some unknown value
(if-nez v0 :exit)
(if-eqz v0 :exit) ; we know v0 must be zero here, so this is always true
(const v0 1)
:exit
(return-void)
)
)");
ConstPropConfig config;
config.propagate_conditions = true;
do_const_prop(code.get(), config);
auto expected_code = assembler::ircode_from_string(R"(
(
(load-param v0)
(if-nez v0 :exit)
(goto :exit)
(const v0 1)
:exit
(return-void)
)
)");
EXPECT_EQ(assembler::to_s_expr(code.get()),
assembler::to_s_expr(expected_code.get()));
}
TEST(ConstantPropagation, ConditionalConstantInferInterval) {
auto code = assembler::ircode_from_string(R"(
(
(load-param v0) ; some unknown value
(if-lez v0 :exit)
(if-gtz v0 :exit) ; we know v0 must be > 0 here, so this is always true
(const v0 1)
:exit
(return-void)
)
)");
ConstPropConfig config;
config.propagate_conditions = true;
do_const_prop(code.get(), config);
auto expected_code = assembler::ircode_from_string(R"(
(
(load-param v0)
(if-lez v0 :exit)
(goto :exit)
(const v0 1)
:exit
(return-void)
)
)");
EXPECT_EQ(assembler::to_s_expr(code.get()),
assembler::to_s_expr(expected_code.get()));
}
TEST(ConstantPropagation, JumpToImmediateNext) {
auto code = assembler::ircode_from_string(R"(
(
(load-param v0)
(if-eqz v0 :next) ; This jumps to the next opcode regardless of whether
; the test is true or false. So in this case we cannot
; conclude that v0 == 0 in the 'true' block, since that
; is identical to the 'false' block.
:next
(if-eqz v0 :end)
(const v0 1)
:end
(return-void)
)
)");
ConstPropConfig config;
config.propagate_conditions = true;
do_const_prop(code.get(), config);
auto expected_code = assembler::ircode_from_string(R"(
(
(load-param v0)
(if-eqz v0 :next)
:next
(if-eqz v0 :end)
(const v0 1)
:end
(return-void)
)
)");
EXPECT_EQ(assembler::to_s_expr(code.get()),
assembler::to_s_expr(expected_code.get()));
}
TEST(ConstantPropagation, SignedConstantDomainOperations) {
using namespace sign_domain;
auto one = SignedConstantDomain(1, ConstantValue::ConstantType::NARROW);
auto minus_one =
SignedConstantDomain(-1, ConstantValue::ConstantType::NARROW);
auto zero = SignedConstantDomain(0, ConstantValue::ConstantType::NARROW);
auto max_val = SignedConstantDomain(std::numeric_limits<int64_t>::max(),
ConstantValue::ConstantType::WIDE);
auto min_val = SignedConstantDomain(std::numeric_limits<int64_t>::min(),
ConstantValue::ConstantType::WIDE);
EXPECT_EQ(one.interval(), Interval::GTZ);
EXPECT_EQ(minus_one.interval(), Interval::LTZ);
EXPECT_EQ(zero.interval(), Interval::EQZ);
EXPECT_EQ(max_val.interval(), Interval::GTZ);
EXPECT_EQ(min_val.interval(), Interval::LTZ);
EXPECT_EQ(one.join(minus_one).interval(), Interval::ALL);
EXPECT_EQ(one.join(zero).interval(), Interval::GEZ);
EXPECT_EQ(minus_one.join(zero).interval(), Interval::LEZ);
EXPECT_EQ(max_val.join(zero).interval(), Interval::GEZ);
EXPECT_EQ(min_val.join(zero).interval(), Interval::LEZ);
auto positive = SignedConstantDomain(Interval::GTZ);
auto negative = SignedConstantDomain(Interval::LTZ);
EXPECT_EQ(one.join(positive), positive);
EXPECT_TRUE(one.join(negative).is_top());
EXPECT_EQ(max_val.join(positive), positive);
EXPECT_TRUE(max_val.join(negative).is_top());
EXPECT_EQ(minus_one.join(negative), negative);
EXPECT_TRUE(minus_one.join(positive).is_top());
EXPECT_EQ(min_val.join(negative), negative);
EXPECT_TRUE(min_val.join(positive).is_top());
EXPECT_EQ(zero.join(positive).interval(), Interval::GEZ);
EXPECT_EQ(zero.join(negative).interval(), Interval::LEZ);
EXPECT_EQ(one.meet(positive), one);
EXPECT_TRUE(one.meet(negative).is_bottom());
EXPECT_EQ(max_val.meet(positive), max_val);
EXPECT_TRUE(max_val.meet(negative).is_bottom());
EXPECT_EQ(minus_one.meet(negative), minus_one);
EXPECT_TRUE(minus_one.meet(positive).is_bottom());
EXPECT_EQ(min_val.meet(negative), min_val);
EXPECT_TRUE(min_val.meet(positive).is_bottom());
}
TEST(ConstantPropagation, WhiteBox1) {
auto code = assembler::ircode_from_string(R"(
(
(load-param v0)
(const v1 0)
(const v2 1)
(move v3 v1)
(if-eqz v0 :if-true-label)
(const v2 0)
(if-gez v0 :if-true-label)
:if-true-label
(return-void)
)
)");
ConstPropConfig config;
config.propagate_conditions = true;
code->build_cfg();
auto& cfg = code->cfg();
cfg.calculate_exit_block();
IntraProcConstantPropagation rcp(cfg, config);
rcp.run(ConstPropEnvironment());
auto exit_state = rcp.get_exit_state_at(cfg.exit_block());
EXPECT_EQ(exit_state.get(0), SignedConstantDomain::top());
EXPECT_EQ(exit_state.get(1),
SignedConstantDomain(0, ConstantValue::ConstantType::NARROW));
// v2 can contain either the value 0 or 1
EXPECT_EQ(exit_state.get(2),
SignedConstantDomain(sign_domain::Interval::GEZ));
EXPECT_EQ(exit_state.get(3),
SignedConstantDomain(0, ConstantValue::ConstantType::NARROW));
}
TEST(ConstantPropagation, WhiteBox2) {
auto code = assembler::ircode_from_string(R"(
(
(load-param v0)
:loop
(const v1 0)
(if-gez v0 :if-true-label)
(goto :loop)
; if we get here, that means v0 >= 0
:if-true-label
(return-void)
)
)");
ConstPropConfig config;
config.propagate_conditions = true;
code->build_cfg();
auto& cfg = code->cfg();
cfg.calculate_exit_block();
IntraProcConstantPropagation rcp(cfg, config);
rcp.run(ConstPropEnvironment());
auto exit_state = rcp.get_exit_state_at(cfg.exit_block());
EXPECT_EQ(exit_state.get(0),
SignedConstantDomain(sign_domain::Interval::GEZ));
EXPECT_EQ(exit_state.get(1),
SignedConstantDomain(0, ConstantValue::ConstantType::NARROW));
}
<commit_msg>constprop: Add more unit tests<commit_after>/**
* Copyright (c) 2016-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 <gtest/gtest.h>
#include "ConstantPropagation.h"
#include "IRAssembler.h"
static void do_const_prop(IRCode* code, const ConstPropConfig& config) {
code->build_cfg();
IntraProcConstantPropagation rcp(code->cfg(), config);
rcp.run(ConstPropEnvironment());
rcp.simplify();
rcp.apply_changes(code);
}
TEST(ConstantPropagation, IfToGoto) {
auto code = assembler::ircode_from_string(R"(
(
(const v0 0)
(if-eqz v0 :if-true-label)
(const v0 1)
:if-true-label
(const v0 2)
)
)");
ConstPropConfig config;
config.propagate_conditions = true;
do_const_prop(code.get(), config);
auto expected_code = assembler::ircode_from_string(R"(
(
(const v0 0)
(goto :if-true-label)
(const v0 1)
:if-true-label
(const v0 2)
)
)");
EXPECT_EQ(assembler::to_s_expr(code.get()),
assembler::to_s_expr(expected_code.get()));
}
TEST(ConstantPropagation, ConditionalConstant_EqualsAlwaysTrue) {
auto code = assembler::ircode_from_string(R"(
(
(const v0 0)
(const v1 0)
(if-eqz v0 :if-true-label-1)
(const v1 1) ; the preceding opcode always jumps, so this is unreachable
:if-true-label-1
(if-eqz v1 :if-true-label-2) ; therefore this is always true
(const v1 2)
:if-true-label-2
(return-void)
)
)");
ConstPropConfig config;
config.propagate_conditions = true;
do_const_prop(code.get(), config);
auto expected_code = assembler::ircode_from_string(R"(
(
(const v0 0)
(const v1 0)
(goto :if-true-label-1)
(const v1 1)
:if-true-label-1
(goto :if-true-label-2)
(const v1 2)
:if-true-label-2
(return-void)
)
)");
EXPECT_EQ(assembler::to_s_expr(code.get()),
assembler::to_s_expr(expected_code.get()));
}
TEST(ConstantPropagation, ConditionalConstant_EqualsAlwaysFalse) {
auto code = assembler::ircode_from_string(R"(
(
(const v0 1)
(const v1 1)
(if-eqz v0 :if-true-label-1)
(const v1 0) ; the preceding opcode never jumps, so this is always
; executed
:if-true-label-1
(if-eqz v1 :if-true-label-2) ; therefore this is always true
(const v1 2)
:if-true-label-2
(return-void)
)
)");
ConstPropConfig config;
config.propagate_conditions = true;
do_const_prop(code.get(), config);
auto expected_code = assembler::ircode_from_string(R"(
(
(const v0 1)
(const v1 1)
(const v1 0)
(goto :if-true-label-2)
(const v1 2)
:if-true-label-2
(return-void)
)
)");
EXPECT_EQ(assembler::to_s_expr(code.get()),
assembler::to_s_expr(expected_code.get()));
}
TEST(ConstantPropagation, ConditionalConstant_LessThanAlwaysTrue) {
auto code = assembler::ircode_from_string(R"(
(
(const v0 0)
(const v1 1)
(if-lt v0 v1 :if-true-label-1)
(const v1 0) ; the preceding opcode always jumps, so this is never
; executed
:if-true-label-1
(if-eqz v1 :if-true-label-2) ; therefore this is never true
(const v1 2)
:if-true-label-2
(return-void)
)
)");
ConstPropConfig config;
config.propagate_conditions = true;
do_const_prop(code.get(), config);
auto expected_code = assembler::ircode_from_string(R"(
(
(const v0 0)
(const v1 1)
(goto :if-true-label-1)
(const v1 0)
:if-true-label-1
(const v1 2)
(return-void)
)
)");
EXPECT_EQ(assembler::to_s_expr(code.get()),
assembler::to_s_expr(expected_code.get()));
}
TEST(ConstantPropagation, ConditionalConstant_LessThanAlwaysFalse) {
auto code = assembler::ircode_from_string(R"(
(
(const v0 1)
(const v1 0)
(if-lt v0 v1 :if-true-label-1)
(const v0 0) ; the preceding opcode never jumps, so this is always
; executed
:if-true-label-1
(if-eqz v0 :if-true-label-2) ; therefore this is always true
(const v1 2)
:if-true-label-2
(return-void)
)
)");
ConstPropConfig config;
config.propagate_conditions = true;
do_const_prop(code.get(), config);
auto expected_code = assembler::ircode_from_string(R"(
(
(const v0 1)
(const v1 0)
(const v0 0)
(goto :if-true-label-2)
(const v1 2)
:if-true-label-2
(return-void)
)
)");
EXPECT_EQ(assembler::to_s_expr(code.get()),
assembler::to_s_expr(expected_code.get()));
}
TEST(ConstantPropagation, ConditionalConstantInferZero) {
auto code = assembler::ircode_from_string(R"(
(
(load-param v0) ; some unknown value
(if-nez v0 :exit)
(if-eqz v0 :exit) ; we know v0 must be zero here, so this is always true
(const v0 1)
:exit
(return-void)
)
)");
ConstPropConfig config;
config.propagate_conditions = true;
do_const_prop(code.get(), config);
auto expected_code = assembler::ircode_from_string(R"(
(
(load-param v0)
(if-nez v0 :exit)
(goto :exit)
(const v0 1)
:exit
(return-void)
)
)");
EXPECT_EQ(assembler::to_s_expr(code.get()),
assembler::to_s_expr(expected_code.get()));
}
TEST(ConstantPropagation, ConditionalConstantInferInterval) {
auto code = assembler::ircode_from_string(R"(
(
(load-param v0) ; some unknown value
(if-lez v0 :exit)
(if-gtz v0 :exit) ; we know v0 must be > 0 here, so this is always true
(const v0 1)
:exit
(return-void)
)
)");
ConstPropConfig config;
config.propagate_conditions = true;
do_const_prop(code.get(), config);
auto expected_code = assembler::ircode_from_string(R"(
(
(load-param v0)
(if-lez v0 :exit)
(goto :exit)
(const v0 1)
:exit
(return-void)
)
)");
EXPECT_EQ(assembler::to_s_expr(code.get()),
assembler::to_s_expr(expected_code.get()));
}
TEST(ConstantPropagation, JumpToImmediateNext) {
auto code = assembler::ircode_from_string(R"(
(
(load-param v0)
(if-eqz v0 :next) ; This jumps to the next opcode regardless of whether
; the test is true or false. So in this case we cannot
; conclude that v0 == 0 in the 'true' block, since that
; is identical to the 'false' block.
:next
(if-eqz v0 :end)
(const v0 1)
:end
(return-void)
)
)");
ConstPropConfig config;
config.propagate_conditions = true;
do_const_prop(code.get(), config);
auto expected_code = assembler::ircode_from_string(R"(
(
(load-param v0)
(if-eqz v0 :next)
:next
(if-eqz v0 :end)
(const v0 1)
:end
(return-void)
)
)");
EXPECT_EQ(assembler::to_s_expr(code.get()),
assembler::to_s_expr(expected_code.get()));
}
TEST(ConstantPropagation, FoldArithmeticAddLit) {
auto code = assembler::ircode_from_string(R"(
(
(const v0 2147483646)
(add-int/lit8 v0 v0 1) ; this should be converted to a const opcode
(const v1 2147483647)
(if-eq v0 v1 :end)
(const v0 2147483647)
(add-int/lit8 v0 v0 1) ; we don't handle overflows, so this should be
; unchanged
:end
(return-void)
)
)");
ConstPropConfig config;
config.propagate_conditions = true;
config.fold_arithmetic = true;
do_const_prop(code.get(), config);
auto expected_code = assembler::ircode_from_string(R"(
(
(const v0 2147483646)
(const v0 2147483647)
(const v1 2147483647)
(goto :end)
(const v0 2147483647)
(add-int/lit8 v0 v0 1)
:end
(return-void)
)
)");
EXPECT_EQ(assembler::to_s_expr(code.get()),
assembler::to_s_expr(expected_code.get()));
}
TEST(ConstantPropagation, AnalyzeCmp) {
auto code = assembler::ircode_from_string(R"(
(
(load-param v0)
(if-eqz v0 :b1) ; make sure all blocks appear reachable to constprop
(if-gez v0 :b2)
:b0 ; case v0 < v1
(const-wide v0 0)
(const-wide v1 1)
(cmp-long v2 v0 v1)
(const v3 -1)
(if-eq v2 v3 :end)
:b1 ; case v0 == v1
(const-wide v0 1)
(const-wide v1 1)
(cmp-long v2 v0 v1)
(const v3 0)
(if-eq v2 v3 :end)
:b2 ; case v0 > v1
(const-wide v0 1)
(const-wide v1 0)
(cmp-long v2 v0 v1)
(const v3 1)
(if-eq v2 v3 :end)
:end
(return v2)
)
)");
ConstPropConfig config;
config.propagate_conditions = true;
do_const_prop(code.get(), config);
auto expected_code = assembler::ircode_from_string(R"(
(
(load-param v0)
(if-eqz v0 :b1)
(if-gez v0 :b2)
:b0
(const-wide v0 0)
(const-wide v1 1)
(cmp-long v2 v0 v1)
(const v3 -1)
(goto :end)
:b1
(const-wide v0 1)
(const-wide v1 1)
(cmp-long v2 v0 v1)
(const v3 0)
(goto :end)
:b2
(const-wide v0 1)
(const-wide v1 0)
(cmp-long v2 v0 v1)
(const v3 1)
(goto :end)
:end
(return v2)
)
)");
EXPECT_EQ(assembler::to_s_expr(code.get()),
assembler::to_s_expr(expected_code.get()));
}
TEST(ConstantPropagation, SignedConstantDomainOperations) {
using namespace sign_domain;
auto one = SignedConstantDomain(1, ConstantValue::ConstantType::NARROW);
auto minus_one =
SignedConstantDomain(-1, ConstantValue::ConstantType::NARROW);
auto zero = SignedConstantDomain(0, ConstantValue::ConstantType::NARROW);
auto max_val = SignedConstantDomain(std::numeric_limits<int64_t>::max(),
ConstantValue::ConstantType::WIDE);
auto min_val = SignedConstantDomain(std::numeric_limits<int64_t>::min(),
ConstantValue::ConstantType::WIDE);
EXPECT_EQ(one.interval(), Interval::GTZ);
EXPECT_EQ(minus_one.interval(), Interval::LTZ);
EXPECT_EQ(zero.interval(), Interval::EQZ);
EXPECT_EQ(max_val.interval(), Interval::GTZ);
EXPECT_EQ(min_val.interval(), Interval::LTZ);
EXPECT_EQ(one.join(minus_one).interval(), Interval::ALL);
EXPECT_EQ(one.join(zero).interval(), Interval::GEZ);
EXPECT_EQ(minus_one.join(zero).interval(), Interval::LEZ);
EXPECT_EQ(max_val.join(zero).interval(), Interval::GEZ);
EXPECT_EQ(min_val.join(zero).interval(), Interval::LEZ);
auto positive = SignedConstantDomain(Interval::GTZ);
auto negative = SignedConstantDomain(Interval::LTZ);
EXPECT_EQ(one.join(positive), positive);
EXPECT_TRUE(one.join(negative).is_top());
EXPECT_EQ(max_val.join(positive), positive);
EXPECT_TRUE(max_val.join(negative).is_top());
EXPECT_EQ(minus_one.join(negative), negative);
EXPECT_TRUE(minus_one.join(positive).is_top());
EXPECT_EQ(min_val.join(negative), negative);
EXPECT_TRUE(min_val.join(positive).is_top());
EXPECT_EQ(zero.join(positive).interval(), Interval::GEZ);
EXPECT_EQ(zero.join(negative).interval(), Interval::LEZ);
EXPECT_EQ(one.meet(positive), one);
EXPECT_TRUE(one.meet(negative).is_bottom());
EXPECT_EQ(max_val.meet(positive), max_val);
EXPECT_TRUE(max_val.meet(negative).is_bottom());
EXPECT_EQ(minus_one.meet(negative), minus_one);
EXPECT_TRUE(minus_one.meet(positive).is_bottom());
EXPECT_EQ(min_val.meet(negative), min_val);
EXPECT_TRUE(min_val.meet(positive).is_bottom());
}
TEST(ConstantPropagation, WhiteBox1) {
auto code = assembler::ircode_from_string(R"(
(
(load-param v0)
(const v1 0)
(const v2 1)
(move v3 v1)
(if-eqz v0 :if-true-label)
(const v2 0)
(if-gez v0 :if-true-label)
:if-true-label
(return-void)
)
)");
ConstPropConfig config;
config.propagate_conditions = true;
code->build_cfg();
auto& cfg = code->cfg();
cfg.calculate_exit_block();
IntraProcConstantPropagation rcp(cfg, config);
rcp.run(ConstPropEnvironment());
auto exit_state = rcp.get_exit_state_at(cfg.exit_block());
EXPECT_EQ(exit_state.get(0), SignedConstantDomain::top());
EXPECT_EQ(exit_state.get(1),
SignedConstantDomain(0, ConstantValue::ConstantType::NARROW));
// v2 can contain either the value 0 or 1
EXPECT_EQ(exit_state.get(2),
SignedConstantDomain(sign_domain::Interval::GEZ));
EXPECT_EQ(exit_state.get(3),
SignedConstantDomain(0, ConstantValue::ConstantType::NARROW));
}
TEST(ConstantPropagation, WhiteBox2) {
auto code = assembler::ircode_from_string(R"(
(
(load-param v0)
:loop
(const v1 0)
(if-gez v0 :if-true-label)
(goto :loop)
; if we get here, that means v0 >= 0
:if-true-label
(return-void)
)
)");
ConstPropConfig config;
config.propagate_conditions = true;
code->build_cfg();
auto& cfg = code->cfg();
cfg.calculate_exit_block();
IntraProcConstantPropagation rcp(cfg, config);
rcp.run(ConstPropEnvironment());
auto exit_state = rcp.get_exit_state_at(cfg.exit_block());
EXPECT_EQ(exit_state.get(0),
SignedConstantDomain(sign_domain::Interval::GEZ));
EXPECT_EQ(exit_state.get(1),
SignedConstantDomain(0, ConstantValue::ConstantType::NARROW));
}
<|endoftext|> |
<commit_before>/*
* Copyright 2010 The Native Client 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 "native_client/tests/fake_browser_ppapi/fake_host.h"
#if !NACL_WINDOWS
# include <dlfcn.h>
#endif // !NACL_WINDOWS
#include <string.h>
#include "native_client/src/include/portability.h"
#include "native_client/src/shared/platform/nacl_check.h"
namespace {
#if NACL_WINDOWS
#define RTLD_NOW 0
#define RTLD_LOCAL 0
void* dlopen(const char* filename, int flag) {
return reinterpret_cast<void*>(LoadLibrary(filename));
}
void* dlsym(void *handle, const char* symbol_name) {
return GetProcAddress(reinterpret_cast<HMODULE>(handle), symbol_name);
}
int dlclose(void* handle) {
return !FreeLibrary(reinterpret_cast<HMODULE>(handle));
}
#endif
} // namespace
namespace fake_browser_ppapi {
Host::Host(const char* plugin_file)
: var_interface_(NULL), last_resource_id_(0) {
dl_handle_ = dlopen(plugin_file, RTLD_NOW | RTLD_LOCAL);
CHECK(dl_handle_ != NULL);
initialize_module_ =
reinterpret_cast<InitializeModuleFunc>(
reinterpret_cast<uintptr_t>(dlsym(dl_handle_, "PPP_InitializeModule")));
CHECK(initialize_module_ != NULL);
shutdown_module_ =
reinterpret_cast<ShutdownModuleFunc>(
reinterpret_cast<uintptr_t>(dlsym(dl_handle_, "PPP_ShutdownModule")));
CHECK(shutdown_module_ != NULL);
get_interface_ =
reinterpret_cast<GetInterfaceFunc>(
reinterpret_cast<uintptr_t>(dlsym(dl_handle_, "PPP_GetInterface")));
CHECK(get_interface_ != NULL);
}
Host::~Host() {
int rc = dlclose(dl_handle_);
CHECK(rc == 0);
ResourceMap::iterator ri;
while ((ri = resource_map_.begin()) != resource_map_.end()) {
delete(ri->second);
resource_map_.erase(ri);
}
InstanceMap::iterator ii;
while ((ii = instance_map_.begin()) != instance_map_.end()) {
delete(ii->second);
instance_map_.erase(ii);
}
}
int32_t Host::InitializeModule(PP_Module module,
PPB_GetInterface get_intf) {
return (*initialize_module_)(module, get_intf);
}
void Host::ShutdownModule() {
return (*shutdown_module_)();
}
const void* Host::GetInterface(const char* interface_name) {
return (*get_interface_)(interface_name);
}
PP_Resource Host::TrackResource(Resource* resource) {
PP_Resource resource_id = ++last_resource_id_;
resource_map_[resource_id] = resource;
resource->set_resource_id(resource_id);
return resource_id;
}
Resource* Host::GetResource(PP_Resource resource_id) {
ResourceMap::iterator iter = resource_map_.find(resource_id);
if (iter == resource_map_.end())
return Resource::Invalid();
return iter->second;
}
PP_Instance Host::TrackInstance(Instance* instance) {
PP_Instance instance_id = ++last_instance_id_;
instance_map_[instance_id] = instance;
instance->set_instance_id(instance_id);
return instance_id;
}
Instance* Host::GetInstance(PP_Instance instance_id) {
InstanceMap::iterator iter = instance_map_.find(instance_id);
if (iter == instance_map_.end())
return Instance::Invalid();
return iter->second;
}
} // namespace fake_browser_ppapi
<commit_msg>Fix the valgrind regression introduced at r4158 -- initialize the instance_ids passed out to clients. BUG=none TEST=valgrind bot tests<commit_after>/*
* Copyright 2010 The Native Client 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 "native_client/tests/fake_browser_ppapi/fake_host.h"
#if !NACL_WINDOWS
# include <dlfcn.h>
#endif // !NACL_WINDOWS
#include <string.h>
#include "native_client/src/include/portability.h"
#include "native_client/src/shared/platform/nacl_check.h"
namespace {
#if NACL_WINDOWS
#define RTLD_NOW 0
#define RTLD_LOCAL 0
void* dlopen(const char* filename, int flag) {
return reinterpret_cast<void*>(LoadLibrary(filename));
}
void* dlsym(void *handle, const char* symbol_name) {
return GetProcAddress(reinterpret_cast<HMODULE>(handle), symbol_name);
}
int dlclose(void* handle) {
return !FreeLibrary(reinterpret_cast<HMODULE>(handle));
}
#endif
} // namespace
namespace fake_browser_ppapi {
Host::Host(const char* plugin_file)
: var_interface_(NULL), last_resource_id_(0), last_instance_id_(0) {
dl_handle_ = dlopen(plugin_file, RTLD_NOW | RTLD_LOCAL);
CHECK(dl_handle_ != NULL);
initialize_module_ =
reinterpret_cast<InitializeModuleFunc>(
reinterpret_cast<uintptr_t>(dlsym(dl_handle_, "PPP_InitializeModule")));
CHECK(initialize_module_ != NULL);
shutdown_module_ =
reinterpret_cast<ShutdownModuleFunc>(
reinterpret_cast<uintptr_t>(dlsym(dl_handle_, "PPP_ShutdownModule")));
CHECK(shutdown_module_ != NULL);
get_interface_ =
reinterpret_cast<GetInterfaceFunc>(
reinterpret_cast<uintptr_t>(dlsym(dl_handle_, "PPP_GetInterface")));
CHECK(get_interface_ != NULL);
}
Host::~Host() {
int rc = dlclose(dl_handle_);
CHECK(rc == 0);
ResourceMap::iterator ri;
while ((ri = resource_map_.begin()) != resource_map_.end()) {
delete(ri->second);
resource_map_.erase(ri);
}
InstanceMap::iterator ii;
while ((ii = instance_map_.begin()) != instance_map_.end()) {
delete(ii->second);
instance_map_.erase(ii);
}
}
int32_t Host::InitializeModule(PP_Module module,
PPB_GetInterface get_intf) {
return (*initialize_module_)(module, get_intf);
}
void Host::ShutdownModule() {
return (*shutdown_module_)();
}
const void* Host::GetInterface(const char* interface_name) {
return (*get_interface_)(interface_name);
}
PP_Resource Host::TrackResource(Resource* resource) {
PP_Resource resource_id = ++last_resource_id_;
resource_map_[resource_id] = resource;
resource->set_resource_id(resource_id);
return resource_id;
}
Resource* Host::GetResource(PP_Resource resource_id) {
ResourceMap::iterator iter = resource_map_.find(resource_id);
if (iter == resource_map_.end())
return Resource::Invalid();
return iter->second;
}
PP_Instance Host::TrackInstance(Instance* instance) {
PP_Instance instance_id = ++last_instance_id_;
instance_map_[instance_id] = instance;
instance->set_instance_id(instance_id);
return instance_id;
}
Instance* Host::GetInstance(PP_Instance instance_id) {
InstanceMap::iterator iter = instance_map_.find(instance_id);
if (iter == instance_map_.end())
return Instance::Invalid();
return iter->second;
}
} // namespace fake_browser_ppapi
<|endoftext|> |
<commit_before>//=================================================================================================
// Copyright 2013-2014 Dirk Lemstra <https://magick.codeplex.com/>
//
// Licensed under the ImageMagick License (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.imagemagick.org/script/license.php
//
// 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 "Stdafx.h"
#include "ClipPathReader.h"
#include "..\..\Helpers\ByteConverter.h"
using namespace System::Globalization;
namespace ImageMagick
{
//==============================================================================================
void ClipPathReader::AddPath(array<Byte>^ data)
{
if (_KnotCount == 0)
{
_Index += 24;
return;
}
array<PointD>^ point = CreatePoint(data);
if (_InSubpath == false)
{
_Path->AppendFormat(CultureInfo::InvariantCulture, "M {0:0.###} {1:0.###}\n", point[1].X, point[1].Y);
for (int k=0; k < 3; k++)
{
_First[k]=point[k];
_Last[k]=point[k];
}
}
else
{
if ((_Last[1].X == _Last[2].X) && (_Last[1].Y == _Last[2].Y) && (point[0].X == point[1].X) && (point[0].Y == point[1].Y))
_Path->AppendFormat(CultureInfo::InvariantCulture, "L {0:0.###} {1:0.###}\n", point[1].X, point[1].Y);
else if ((_Last[1].X == _Last[2].X) && (_Last[1].Y == _Last[2].Y))
_Path->AppendFormat(CultureInfo::InvariantCulture, "Q {0:0.###} {1:0.###} {2:0.###} {3:0.###}\n", point[0].X, point[0].Y, point[1].X, point[1].Y);
else if ((point[0].X == point[1].X) && (point[0].Y == point[1].Y))
_Path->AppendFormat(CultureInfo::InvariantCulture, "S {0:0.###} {1:0.###} {2:0.###} {3:0.###}\n", _Last[2].X, _Last[2].Y, point[1].X, point[1].Y);
else
_Path->AppendFormat(CultureInfo::InvariantCulture, "C {0:0.###} {1:0.###} {2:0.###} {3:0.###} {4:0.###} {5:0.###}\n", _Last[2].X, _Last[2].Y, point[0].X, point[0].Y, point[1].X, point[1].Y);
for (int k=0; k < 3; k++)
_Last[k]=point[k];
}
_InSubpath = true;
_KnotCount--;
if (_KnotCount == 0)
{
ClosePath();
_InSubpath=false;
}
}
//==============================================================================================
void ClipPathReader::ClosePath()
{
if ((_Last[1].X == _Last[2].X) && (_Last[1].Y == _Last[2].Y) && (_First[0].X == _First[1].X) && (_First[0].Y == _First[1].Y))
_Path->AppendFormat(CultureInfo::InvariantCulture, "L {0:0.###} {1:0.###} Z\n", _First[1].X, _First[1].Y);
else if ((_Last[1].X == _Last[2].X) && (_Last[1].Y == _Last[2].Y))
_Path->AppendFormat(CultureInfo::InvariantCulture, "Q {0:0.###} {1:0.###} {2:0.###} {3:0.###} Z\n", _First[0].X, _First[0].Y, _First[1].X, _First[1].Y);
else if ((_First[0].X == _First[1].X) && (_First[0].Y == _First[1].Y))
_Path->AppendFormat(CultureInfo::InvariantCulture, "S {0:0.###} {1:0.###} {2:0.###} {3:0.###} Z\n", _Last[2].X, _Last[2].Y, _First[1].X, _First[1].Y);
else
_Path->AppendFormat(CultureInfo::InvariantCulture, "C {0:0.###} {1:0.###} {2:0.###} {3:0.###} {4:0.###} {5:0.###} Z\n", _Last[2].X, _Last[2].Y, _First[0].X, _First[0].Y, _First[1].X, _First[1].Y);
}
//==============================================================================================
array<PointD>^ ClipPathReader::CreatePoint(array<Byte>^ data)
{
array<PointD>^ result = gcnew array<PointD>(3);
for (int i=0; i < 3; i++)
{
int yy = ByteConverter::ToInt(data, _Index);
long y = (long) yy;
if (yy > 2147483647)
y = yy-4294967295U-1;
int xx = ByteConverter::ToInt(data, _Index);
long x = (long) xx;
if (xx > 2147483647)
x = (long)xx-4294967295U-1;
result[i].X = ((double)x*_Width/4096/4096);
result[i].Y = ((double)y*_Height/4096/4096);
}
return result;
}
//==============================================================================================
void ClipPathReader::Reset(int offset)
{
_Index = offset;
_KnotCount = 0;
_InSubpath = false;
_Path = gcnew StringBuilder();
_First = gcnew array<PointD>(3);
_Last = gcnew array<PointD>(3);
}
//==============================================================================================
void ClipPathReader::SetKnotCount(array<Byte>^ data)
{
if (_KnotCount != 0)
{
_Index += 24;
return;
}
_KnotCount = ByteConverter::ToShort(data, _Index);
_Index += 22;
}
//==============================================================================================
ClipPathReader::ClipPathReader(int width, int height)
{
_Width = width;
_Height = height;
}
//==============================================================================================
String^ ClipPathReader::Read(array<Byte>^ data, int offset, int length)
{
Reset(offset);
while (_Index < offset + length)
{
short selector = ByteConverter::ToShort(data, _Index);
switch (selector)
{
case 0:
case 3:
SetKnotCount(data);
break;
case 1:
case 2:
case 4:
case 5:
AddPath(data);
break;
case 6:
case 7:
case 8:
default:
_Index += 24;
break;
}
}
return _Path->ToString();
}
//==============================================================================================
}<commit_msg>Changed types in creation of clippath.<commit_after>//=================================================================================================
// Copyright 2013-2014 Dirk Lemstra <https://magick.codeplex.com/>
//
// Licensed under the ImageMagick License (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.imagemagick.org/script/license.php
//
// 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 "Stdafx.h"
#include "ClipPathReader.h"
#include "..\..\Helpers\ByteConverter.h"
using namespace System::Globalization;
namespace ImageMagick
{
//==============================================================================================
void ClipPathReader::AddPath(array<Byte>^ data)
{
if (_KnotCount == 0)
{
_Index += 24;
return;
}
array<PointD>^ point = CreatePoint(data);
if (_InSubpath == false)
{
_Path->AppendFormat(CultureInfo::InvariantCulture, "M {0:0.###} {1:0.###}\n", point[1].X, point[1].Y);
for (int k=0; k < 3; k++)
{
_First[k]=point[k];
_Last[k]=point[k];
}
}
else
{
if ((_Last[1].X == _Last[2].X) && (_Last[1].Y == _Last[2].Y) && (point[0].X == point[1].X) && (point[0].Y == point[1].Y))
_Path->AppendFormat(CultureInfo::InvariantCulture, "L {0:0.###} {1:0.###}\n", point[1].X, point[1].Y);
else if ((_Last[1].X == _Last[2].X) && (_Last[1].Y == _Last[2].Y))
_Path->AppendFormat(CultureInfo::InvariantCulture, "Q {0:0.###} {1:0.###} {2:0.###} {3:0.###}\n", point[0].X, point[0].Y, point[1].X, point[1].Y);
else if ((point[0].X == point[1].X) && (point[0].Y == point[1].Y))
_Path->AppendFormat(CultureInfo::InvariantCulture, "S {0:0.###} {1:0.###} {2:0.###} {3:0.###}\n", _Last[2].X, _Last[2].Y, point[1].X, point[1].Y);
else
_Path->AppendFormat(CultureInfo::InvariantCulture, "C {0:0.###} {1:0.###} {2:0.###} {3:0.###} {4:0.###} {5:0.###}\n", _Last[2].X, _Last[2].Y, point[0].X, point[0].Y, point[1].X, point[1].Y);
for (int k=0; k < 3; k++)
_Last[k]=point[k];
}
_InSubpath = true;
_KnotCount--;
if (_KnotCount == 0)
{
ClosePath();
_InSubpath=false;
}
}
//==============================================================================================
void ClipPathReader::ClosePath()
{
if ((_Last[1].X == _Last[2].X) && (_Last[1].Y == _Last[2].Y) && (_First[0].X == _First[1].X) && (_First[0].Y == _First[1].Y))
_Path->AppendFormat(CultureInfo::InvariantCulture, "L {0:0.###} {1:0.###} Z\n", _First[1].X, _First[1].Y);
else if ((_Last[1].X == _Last[2].X) && (_Last[1].Y == _Last[2].Y))
_Path->AppendFormat(CultureInfo::InvariantCulture, "Q {0:0.###} {1:0.###} {2:0.###} {3:0.###} Z\n", _First[0].X, _First[0].Y, _First[1].X, _First[1].Y);
else if ((_First[0].X == _First[1].X) && (_First[0].Y == _First[1].Y))
_Path->AppendFormat(CultureInfo::InvariantCulture, "S {0:0.###} {1:0.###} {2:0.###} {3:0.###} Z\n", _Last[2].X, _Last[2].Y, _First[1].X, _First[1].Y);
else
_Path->AppendFormat(CultureInfo::InvariantCulture, "C {0:0.###} {1:0.###} {2:0.###} {3:0.###} {4:0.###} {5:0.###} Z\n", _Last[2].X, _Last[2].Y, _First[0].X, _First[0].Y, _First[1].X, _First[1].Y);
}
//==============================================================================================
array<PointD>^ ClipPathReader::CreatePoint(array<Byte>^ data)
{
array<PointD>^ result = gcnew array<PointD>(3);
for (int i=0; i < 3; i++)
{
unsigned int yy = (unsigned int)ByteConverter::ToInt(data, _Index);
int y = (int) yy;
if (yy > 2147483647)
y = (int)yy-4294967295U-1;
unsigned int xx = (unsigned int)ByteConverter::ToInt(data, _Index);
int x = (int) xx;
if (xx > 2147483647)
x = (int)xx-4294967295U-1;
result[i].X = ((double)x*_Width/4096/4096);
result[i].Y = ((double)y*_Height/4096/4096);
}
return result;
}
//==============================================================================================
void ClipPathReader::Reset(int offset)
{
_Index = offset;
_KnotCount = 0;
_InSubpath = false;
_Path = gcnew StringBuilder();
_First = gcnew array<PointD>(3);
_Last = gcnew array<PointD>(3);
}
//==============================================================================================
void ClipPathReader::SetKnotCount(array<Byte>^ data)
{
if (_KnotCount != 0)
{
_Index += 24;
return;
}
_KnotCount = ByteConverter::ToShort(data, _Index);
_Index += 22;
}
//==============================================================================================
ClipPathReader::ClipPathReader(int width, int height)
{
_Width = width;
_Height = height;
}
//==============================================================================================
String^ ClipPathReader::Read(array<Byte>^ data, int offset, int length)
{
Reset(offset);
while (_Index < offset + length)
{
short selector = ByteConverter::ToShort(data, _Index);
switch (selector)
{
case 0:
case 3:
SetKnotCount(data);
break;
case 1:
case 2:
case 4:
case 5:
AddPath(data);
break;
case 6:
case 7:
case 8:
default:
_Index += 24;
break;
}
}
return _Path->ToString();
}
//==============================================================================================
}<|endoftext|> |
<commit_before>// Copyright (C) 2011 Ryan Curtin <ryan@igglybob.com>
//
// This file is part of the Armadillo C++ library.
// It is provided without any warranty of fitness
// for any purpose. You can redistribute this file
// and/or modify it under the terms of the GNU
// Lesser General Public License (LGPL) as published
// by the Free Software Foundation, either version 3
// of the License or (at your option) any later version.
// (see http://www.opensource.org/licenses for more info)
//! \addtogroup Proxy
//! @{
template<typename eT>
class Proxy< SpMat<eT> >
{
public:
typedef eT elem_type;
typedef typename get_pod_type<elem_type>::result pod_type;
typedef SpMat<eT> stored_type;
typedef const SpMat<eT>& ea_type;
static const bool prefer_at_accessor = false;
static const bool has_subview = false;
arma_aligned const SpMat<eT>& Q;
inline explicit Proxy(const SpMat<eT>& A)
: Q(A)
{
arma_extra_debug_sigprint();
}
arma_inline uword get_n_rows() const { return Q.n_rows; }
arma_inline uword get_n_cols() const { return Q.n_cols; }
arma_inline uword get_n_elem() const { return Q.n_elem; }
arma_inline elem_type operator[] (const uword i) const { return Q[i]; }
arma_inline elem_type at (const uword row, const uword col) const { return Q.at(row, col); }
arma_inline ea_type get_ea() const { return Q; }
arma_inline bool is_alias(const Mat<eT>& X) const { return false; }
};
template<typename eT>
class Proxy< SpCol<eT> >
{
public:
typedef eT elem_type;
typedef typename get_pod_type<elem_type>::result pod_type;
typedef SpCol<eT> stored_type;
typedef const SpCol<eT>& ea_type;
static const bool prefer_at_accessor = false;
static const bool has_subview = false;
arma_aligned const SpCol<eT>& Q;
inline explicit Proxy(const SpCol<eT>& A)
: Q(A)
{
arma_extra_debug_sigprint();
}
arma_inline uword get_n_rows() const { return Q.n_rows; }
arma_inline uword get_n_cols() const { return 1; }
arma_inline uword get_n_elem() const { return Q.n_elem; }
arma_inline elem_type operator[] (const uword i) const { return Q[i]; }
arma_inline elem_type at (const uword row, const uword col) const { return Q.at(row, col); }
arma_inline ea_type get_ea() const { return Q; }
arma_inline bool is_alias(const Mat<eT>& X) const { return false; }
};
template<typename eT>
class Proxy< SpRow<eT> >
{
public:
typedef eT elem_type;
typedef typename get_pod_type<elem_type>::result pod_type;
typedef SpRow<eT> stored_type;
typedef const SpRow<eT>& ea_type;
static const bool prefer_at_accessor = false;
static const bool has_subview = false;
arma_aligned const SpRow<eT>& Q;
inline explicit Proxy(const SpRow<eT>& A)
: Q(A)
{
arma_extra_debug_sigprint();
}
arma_inline uword get_n_rows() const { return 1; }
arma_inline uword get_n_cols() const { return Q.n_cols; }
arma_inline uword get_n_elem() const { return Q.n_elem; }
arma_inline elem_type operator[] (const uword i) const { return Q[i]; }
arma_inline elem_type at (const uword row, const uword col) const { return Q.at(row, col); }
arma_inline ea_type get_ea() const { return Q.memptr(); }
arma_inline bool is_alias(const Mat<eT>& X) const { return false; }
};
//! @}
<commit_msg>Support SpSubview proxies.<commit_after>// Copyright (C) 2011 Ryan Curtin <ryan@igglybob.com>
//
// This file is part of the Armadillo C++ library.
// It is provided without any warranty of fitness
// for any purpose. You can redistribute this file
// and/or modify it under the terms of the GNU
// Lesser General Public License (LGPL) as published
// by the Free Software Foundation, either version 3
// of the License or (at your option) any later version.
// (see http://www.opensource.org/licenses for more info)
//! \addtogroup Proxy
//! @{
template<typename eT>
class Proxy< SpMat<eT> >
{
public:
typedef eT elem_type;
typedef typename get_pod_type<elem_type>::result pod_type;
typedef SpMat<eT> stored_type;
typedef const SpMat<eT>& ea_type;
static const bool prefer_at_accessor = false;
static const bool has_subview = false;
arma_aligned const SpMat<eT>& Q;
inline explicit Proxy(const SpMat<eT>& A)
: Q(A)
{
arma_extra_debug_sigprint();
}
arma_inline uword get_n_rows() const { return Q.n_rows; }
arma_inline uword get_n_cols() const { return Q.n_cols; }
arma_inline uword get_n_elem() const { return Q.n_elem; }
arma_inline elem_type operator[] (const uword i) const { return Q[i]; }
arma_inline elem_type at (const uword row, const uword col) const { return Q.at(row, col); }
arma_inline ea_type get_ea() const { return Q; }
arma_inline bool is_alias(const Mat<eT>& X) const { return false; }
};
template<typename eT>
class Proxy< SpCol<eT> >
{
public:
typedef eT elem_type;
typedef typename get_pod_type<elem_type>::result pod_type;
typedef SpCol<eT> stored_type;
typedef const SpCol<eT>& ea_type;
static const bool prefer_at_accessor = false;
static const bool has_subview = false;
arma_aligned const SpCol<eT>& Q;
inline explicit Proxy(const SpCol<eT>& A)
: Q(A)
{
arma_extra_debug_sigprint();
}
arma_inline uword get_n_rows() const { return Q.n_rows; }
arma_inline uword get_n_cols() const { return 1; }
arma_inline uword get_n_elem() const { return Q.n_elem; }
arma_inline elem_type operator[] (const uword i) const { return Q[i]; }
arma_inline elem_type at (const uword row, const uword col) const { return Q.at(row, col); }
arma_inline ea_type get_ea() const { return Q; }
arma_inline bool is_alias(const Mat<eT>& X) const { return false; }
};
template<typename eT>
class Proxy< SpRow<eT> >
{
public:
typedef eT elem_type;
typedef typename get_pod_type<elem_type>::result pod_type;
typedef SpRow<eT> stored_type;
typedef const SpRow<eT>& ea_type;
static const bool prefer_at_accessor = false;
static const bool has_subview = false;
arma_aligned const SpRow<eT>& Q;
inline explicit Proxy(const SpRow<eT>& A)
: Q(A)
{
arma_extra_debug_sigprint();
}
arma_inline uword get_n_rows() const { return 1; }
arma_inline uword get_n_cols() const { return Q.n_cols; }
arma_inline uword get_n_elem() const { return Q.n_elem; }
arma_inline elem_type operator[] (const uword i) const { return Q[i]; }
arma_inline elem_type at (const uword row, const uword col) const { return Q.at(row, col); }
arma_inline ea_type get_ea() const { return Q.memptr(); }
arma_inline bool is_alias(const Mat<eT>& X) const { return false; }
};
template<typename eT>
class Proxy< SpSubview<eT> >
{
public:
typedef eT elem_type;
typedef typename get_pod_type<elem_type>::result pod_type;
typedef SpSubview<eT> stored_type;
typedef const SpSubview<eT>& ea_type;
static const bool prefer_at_accessor = true;
static const bool has_subview = true;
arma_aligned const SpSubview<eT>& Q;
inline explicit Proxy(const SpSubview<eT>& A)
: Q(A)
{
arma_extra_debug_sigprint();
}
arma_inline uword get_n_rows() const { return Q.n_rows; }
arma_inline uword get_n_cols() const { return Q.n_cols; }
arma_inline uword get_n_elem() const { return Q.n_elem; }
arma_inline elem_type operator[] (const uword i) const { return Q[i]; }
arma_inline elem_type at (const uword row, const uword col) const { return Q.at(row, col); }
arma_inline ea_type get_ea() const { return Q; }
arma_inline bool is_alias(const SpMat<eT>& X) const { return (&(Q.m) == &X); }
};
//! @}
<|endoftext|> |
<commit_before>/**
* @file network_util_impl.hpp
* @author Marcus Edel
*
* Implementation of the network auxiliary functions.
*/
#ifndef __MLPACK_METHODS_ANN_NETWORK_UTIL_IMPL_HPP
#define __MLPACK_METHODS_ANN_NETWORK_UTIL_IMPL_HPP
#include "network_util_impl.hpp"
#include <mlpack/methods/ann/layer/layer_traits.hpp>
namespace mlpack {
namespace ann {
template<size_t I, typename... Tp>
typename std::enable_if<I == sizeof...(Tp), size_t>::type
NetworkSize(std::tuple<Tp...>& /* unused */)
{
return 0;
}
template<size_t I, typename... Tp>
typename std::enable_if<I < sizeof...(Tp), size_t>::type
NetworkSize(std::tuple<Tp...>& network)
{
return LayerSize(std::get<I>(network), std::get<I>(
network).OutputParameter()) + NetworkSize<I + 1, Tp...>(network);
}
template<typename T, typename P>
typename std::enable_if<
HasWeightsCheck<T, P&(T::*)()>::value, size_t>::type
LayerSize(T& layer, P& /* unused */)
{
return layer.Weights().n_elem;
}
template<typename T, typename P>
typename std::enable_if<
!HasWeightsCheck<T, P&(T::*)()>::value, size_t>::type
LayerSize(T& /* unused */, P& /* unused */)
{
return 0;
}
template<size_t I, typename... Tp>
typename std::enable_if<I < sizeof...(Tp), void>::type
NetworkWeights(arma::mat& weights,
std::tuple<Tp...>& network,
size_t offset)
{
NetworkWeights<I + 1, Tp...>(weights, network,
offset + LayerWeights(std::get<I>(network), weights,
offset, std::get<I>(network).OutputParameter()));
}
template<size_t I, typename... Tp>
typename std::enable_if<I == sizeof...(Tp), void>::type
NetworkWeights(arma::mat& /* unused */,
std::tuple<Tp...>& /* unused */,
size_t /* unused */)
{
/* Nothing to do here */
}
template<typename T>
typename std::enable_if<
HasWeightsCheck<T, arma::mat&(T::*)()>::value, size_t>::type
LayerWeights(T& layer,
arma::mat& weights,
size_t offset,
arma::mat& /* unused */)
{
layer.Weights() = arma::mat(weights.memptr() + offset,
layer.Weights().n_rows, layer.Weights().n_cols, false);
return layer.Weights().n_elem;
}
template<typename T>
typename std::enable_if<
HasWeightsCheck<T, arma::cube&(T::*)()>::value, size_t>::type
LayerWeights(T& layer,
arma::mat& weights,
size_t offset,
arma::cube& /* unused */)
{
layer.Weights() = arma::cube(weights.memptr() + offset,
layer.Weights().n_rows, layer.Weights().n_cols,
layer.Weights().n_slices, false);
return layer.Weights().n_elem;
}
template<typename T, typename P>
typename std::enable_if<
!HasWeightsCheck<T, P&(T::*)()>::value, size_t>::type
LayerWeights(T& /* unused */,
arma::mat& /* unused */,
size_t /* unused */,
P& /* unused */)
{
return 0;
}
template<size_t I, typename... Tp>
typename std::enable_if<I < sizeof...(Tp), void>::type
NetworkGradients(arma::mat& gradients,
std::tuple<Tp...>& network,
size_t offset)
{
NetworkGradients<I + 1, Tp...>(gradients, network,
offset + LayerGradients(std::get<I>(network), gradients,
offset, std::get<I>(network).OutputParameter()));
}
template<size_t I, typename... Tp>
typename std::enable_if<I == sizeof...(Tp), void>::type
NetworkGradients(arma::mat& /* unused */,
std::tuple<Tp...>& /* unused */,
size_t /* unused */)
{
/* Nothing to do here */
}
template<typename T>
typename std::enable_if<
HasGradientCheck<T, arma::mat&(T::*)()>::value, size_t>::type
LayerGradients(T& layer,
arma::mat& gradients,
size_t offset,
arma::mat& /* unused */)
{
layer.Gradient() = arma::mat(gradients.memptr() + offset,
layer.Weights().n_rows, layer.Weights().n_cols, false);
return layer.Weights().n_elem;
}
template<typename T>
typename std::enable_if<
HasGradientCheck<T, arma::cube&(T::*)()>::value, size_t>::type
LayerGradients(T& layer,
arma::mat& gradients,
size_t offset,
arma::cube& /* unused */)
{
layer.Gradient() = arma::cube(gradients.memptr() + offset,
layer.Weights().n_rows, layer.Weights().n_cols,
layer.Weights().n_slices, false);
return layer.Weights().n_elem;
}
template<typename T, typename P>
typename std::enable_if<
!HasGradientCheck<T, P&(T::*)()>::value, size_t>::type
LayerGradients(T& /* unused */,
arma::mat& /* unused */,
size_t /* unused */,
P& /* unused */)
{
return 0;
}
} // namespace ann
} // namespace mlpack
#endif
<commit_msg>Set strict = false (use auxiliary memory until the size change) when creating the gradient storage; the default setting changed in armadillo 6.000 from true to false since.<commit_after>/**
* @file network_util_impl.hpp
* @author Marcus Edel
*
* Implementation of the network auxiliary functions.
*/
#ifndef __MLPACK_METHODS_ANN_NETWORK_UTIL_IMPL_HPP
#define __MLPACK_METHODS_ANN_NETWORK_UTIL_IMPL_HPP
#include "network_util_impl.hpp"
#include <mlpack/methods/ann/layer/layer_traits.hpp>
namespace mlpack {
namespace ann {
template<size_t I, typename... Tp>
typename std::enable_if<I == sizeof...(Tp), size_t>::type
NetworkSize(std::tuple<Tp...>& /* unused */)
{
return 0;
}
template<size_t I, typename... Tp>
typename std::enable_if<I < sizeof...(Tp), size_t>::type
NetworkSize(std::tuple<Tp...>& network)
{
return LayerSize(std::get<I>(network), std::get<I>(
network).OutputParameter()) + NetworkSize<I + 1, Tp...>(network);
}
template<typename T, typename P>
typename std::enable_if<
HasWeightsCheck<T, P&(T::*)()>::value, size_t>::type
LayerSize(T& layer, P& /* unused */)
{
return layer.Weights().n_elem;
}
template<typename T, typename P>
typename std::enable_if<
!HasWeightsCheck<T, P&(T::*)()>::value, size_t>::type
LayerSize(T& /* unused */, P& /* unused */)
{
return 0;
}
template<size_t I, typename... Tp>
typename std::enable_if<I < sizeof...(Tp), void>::type
NetworkWeights(arma::mat& weights,
std::tuple<Tp...>& network,
size_t offset)
{
NetworkWeights<I + 1, Tp...>(weights, network,
offset + LayerWeights(std::get<I>(network), weights,
offset, std::get<I>(network).OutputParameter()));
}
template<size_t I, typename... Tp>
typename std::enable_if<I == sizeof...(Tp), void>::type
NetworkWeights(arma::mat& /* unused */,
std::tuple<Tp...>& /* unused */,
size_t /* unused */)
{
/* Nothing to do here */
}
template<typename T>
typename std::enable_if<
HasWeightsCheck<T, arma::mat&(T::*)()>::value, size_t>::type
LayerWeights(T& layer,
arma::mat& weights,
size_t offset,
arma::mat& /* unused */)
{
layer.Weights() = arma::mat(weights.memptr() + offset,
layer.Weights().n_rows, layer.Weights().n_cols, false, false);
return layer.Weights().n_elem;
}
template<typename T>
typename std::enable_if<
HasWeightsCheck<T, arma::cube&(T::*)()>::value, size_t>::type
LayerWeights(T& layer,
arma::mat& weights,
size_t offset,
arma::cube& /* unused */)
{
layer.Weights() = arma::cube(weights.memptr() + offset,
layer.Weights().n_rows, layer.Weights().n_cols,
layer.Weights().n_slices, false, false);
return layer.Weights().n_elem;
}
template<typename T, typename P>
typename std::enable_if<
!HasWeightsCheck<T, P&(T::*)()>::value, size_t>::type
LayerWeights(T& /* unused */,
arma::mat& /* unused */,
size_t /* unused */,
P& /* unused */)
{
return 0;
}
template<size_t I, typename... Tp>
typename std::enable_if<I < sizeof...(Tp), void>::type
NetworkGradients(arma::mat& gradients,
std::tuple<Tp...>& network,
size_t offset)
{
NetworkGradients<I + 1, Tp...>(gradients, network,
offset + LayerGradients(std::get<I>(network), gradients,
offset, std::get<I>(network).OutputParameter()));
}
template<size_t I, typename... Tp>
typename std::enable_if<I == sizeof...(Tp), void>::type
NetworkGradients(arma::mat& /* unused */,
std::tuple<Tp...>& /* unused */,
size_t /* unused */)
{
/* Nothing to do here */
}
template<typename T>
typename std::enable_if<
HasGradientCheck<T, arma::mat&(T::*)()>::value, size_t>::type
LayerGradients(T& layer,
arma::mat& gradients,
size_t offset,
arma::mat& /* unused */)
{
layer.Gradient() = arma::mat(gradients.memptr() + offset,
layer.Weights().n_rows, layer.Weights().n_cols, false, false);
return layer.Weights().n_elem;
}
template<typename T>
typename std::enable_if<
HasGradientCheck<T, arma::cube&(T::*)()>::value, size_t>::type
LayerGradients(T& layer,
arma::mat& gradients,
size_t offset,
arma::cube& /* unused */)
{
layer.Gradient() = arma::cube(gradients.memptr() + offset,
layer.Weights().n_rows, layer.Weights().n_cols,
layer.Weights().n_slices, false, false);
return layer.Weights().n_elem;
}
template<typename T, typename P>
typename std::enable_if<
!HasGradientCheck<T, P&(T::*)()>::value, size_t>::type
LayerGradients(T& /* unused */,
arma::mat& /* unused */,
size_t /* unused */,
P& /* unused */)
{
return 0;
}
} // namespace ann
} // namespace mlpack
#endif
<|endoftext|> |
<commit_before>#include <nex/filesystem/directory.h>
#include <nex/filesystem/path.h>
/**
* Win32 directory implementation.
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <windows.h>
namespace nx
{
std::vector<std::string> split(const std::string& string)
{
std::vector<std::string> tokens;
char* ptr = strtok((char*)string.c_str(), "\\/");
tokens.push_back(std::string(ptr));
while(ptr != 0) {
ptr = strtok(0, "\\/");
if (ptr != 0)
tokens.push_back(std::string(ptr));
}
return tokens;
}
bool Directory::exists(const std::string& path)
{
}
void Directory::create(const std::string& path)
{
/*std::vector<std::string> tokens = split(path);
std::string fullPath;
for (auto& token : tokens)
{
fullPath += token + '/';
mkdir(fullPath.c_str(), 0777);
}*/
}
void Directory::remove(const std::string& dirname)
{
/* HANDLE hFind;
WIN32_FIND_DATA FindFileData;
std::string dirPath;
std::string fileName;
_tcscpy(dirPath, sPath);
_tcscat(dirPath, "\\*");
_tcscpy(fileName, sPath);
_tcscat(fileName, "\\");
hFind = FindFirstFile(dirPath, &FindFileData);
if(hFind == INVALID_HANDLE_VALUE)
return FALSE;
_tcscpy(dirPath,fileName);
bool bSearch = true;
while(bSearch) {
if (FindNextFile(hFind, &FindFileData)) {
if (IsDots(FindFileData.cFileName))
continue;
_tcscat(fileName, FindFileData.cFileName);
if ((FindFileData.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)) {
// we have found a directory, recurse
if (!remove(fileName)) {
FindClose(hFind);
}
// remove the empty directory
RemoveDirectoryA(fileName);
_tcscpy(fileName,dirPath);
}
else {
if (FindFileData.dwFileAttributes & FILE_ATTRIBUTE_READONLY)
_chmod(fileName, _S_IWRITE);
if (!DeleteFile(fileName)) {
FindClose(hFind);
return FALSE;
}
_tcscpy(fileName,dirPath);
}
}
else {
if(GetLastError() == ERROR_NO_MORE_FILES)
bSearch = false;
else {
// some error occured, close the handle and return FALSE
FindClose(hFind);
return FALSE;
}
}
}
FindClose(hFind);
return RemoveDirectory(sPath);*/
}
std::vector<DirectoryInfo> Directory::getDirectories(const std::string& dirname)
{
WIN32_FIND_DATA filePtr;
std::string tempPath = dirname;
tempPath += "\\*.*";
std::string currFile = "";
std::vector<DirectoryInfo> found;
HANDLE hFind = FindFirstFile(tempPath.c_str(), &filePtr );
if (hFind == INVALID_HANDLE_VALUE) {
return found;
}
else
{
do
{
//check if its a directory...
if ((filePtr.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY ))
{
std::string filePath = filePtr.cFileName;
//ignore '.' and '..'
if (strcmp(".", filePath.c_str()) && strcmp("..", filePath.c_str()))
{
tempPath = dirname + "\\" + filePath;
DirectoryInfo info;
info.path = tempPath;
info.name = filePath;
found.push_back(info);
}
}
else
{
tempPath = dirname + "\\";
currFile = tempPath + filePtr.cFileName;
}
}
while (FindNextFile(hFind, &filePtr) != 0);
FindClose(hFind);
}
return found;
}
std::vector<FileInfo> Directory::getFiles(const std::string& dirname)
{
WIN32_FIND_DATA filePtr;
std::string tempPath = dirname;
tempPath += "\\*.*";
std::string currFile = "";
std::vector<FileInfo> found;
HANDLE hFind = FindFirstFile(tempPath.c_str(), &filePtr );
if (hFind == INVALID_HANDLE_VALUE) {
return found;
}
else
{
do
{
//check if its a file.
if (!(filePtr.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY ))
{
tempPath = dirname + "\\";
currFile = tempPath + filePtr.cFileName;
FileInfo info;
info.path = currFile;
info.name = filePtr.cFileName;
info.extention = Path::getExtension(currFile);
found.push_back(info);
}
}
while (FindNextFile(hFind, &filePtr) != 0);
FindClose(hFind);
}
return found;
}
} // namespace nx
<commit_msg>Implemented the directory exists method. Implemented the directory create method. Implemented the directory remove method.<commit_after>#include <nex/filesystem/directory.h>
#include <nex/filesystem/path.h>
/**
* Win32 directory implementation.
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <windows.h>
#include <iostream>
namespace nx
{
std::vector<std::string> split(const std::string& string)
{
std::vector<std::string> tokens;
char* ptr = strtok((char*)string.c_str(), "\\/");
tokens.push_back(std::string(ptr));
while(ptr != 0) {
ptr = strtok(0, "\\/");
if (ptr != 0)
tokens.push_back(std::string(ptr));
}
return tokens;
}
bool Directory::exists(const std::string& path)
{
DWORD dwAttrib = GetFileAttributesA(path.c_str());
return (dwAttrib != INVALID_FILE_ATTRIBUTES &&
(dwAttrib & FILE_ATTRIBUTE_DIRECTORY));
}
void Directory::create(const std::string& path)
{
std::vector<std::string> tokens = split(path);
std::string fullPath;
for (auto& token : tokens)
{
fullPath += token + '/';
::CreateDirectoryA(fullPath.c_str(), 0);
}
}
void Directory::remove(const std::string& dirname)
{
WIN32_FIND_DATA FindFileData;
std::string searchPath = dirname;
searchPath += "\\*.*";
std::string currentFile = "";
HANDLE hFind = FindFirstFile(searchPath.c_str(), &FindFileData);
if (hFind == INVALID_HANDLE_VALUE) {
return;
}
else
{
do
{
// Check if its a directory...
if ((FindFileData.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY))
{
std::string filePath = FindFileData.cFileName;
// Ignore '.' and '..'
if (strcmp(".", filePath.c_str()) && strcmp("..", filePath.c_str())) {
searchPath = dirname + "\\" + filePath;
remove(searchPath);
}
}
else
{
searchPath = dirname + "\\";
currentFile = searchPath + FindFileData.cFileName;
::DeleteFileA(currentFile.c_str());
}
}
while (FindNextFile(hFind, &FindFileData) != 0);
FindClose(hFind);
}
::RemoveDirectoryA(dirname.c_str());
}
std::vector<DirectoryInfo> Directory::getDirectories(const std::string& dirname)
{
WIN32_FIND_DATA filePtr;
std::string tempPath = dirname;
tempPath += "\\*.*";
std::string currFile = "";
std::vector<DirectoryInfo> found;
HANDLE hFind = FindFirstFile(tempPath.c_str(), &filePtr );
if (hFind == INVALID_HANDLE_VALUE) {
return found;
}
else
{
do
{
//check if its a directory...
if ((filePtr.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY ))
{
std::string filePath = filePtr.cFileName;
//ignore '.' and '..'
if (strcmp(".", filePath.c_str()) && strcmp("..", filePath.c_str()))
{
tempPath = dirname + "\\" + filePath;
DirectoryInfo info;
info.path = tempPath;
info.name = filePath;
found.push_back(info);
}
}
else
{
tempPath = dirname + "\\";
currFile = tempPath + filePtr.cFileName;
}
}
while (FindNextFile(hFind, &filePtr) != 0);
FindClose(hFind);
}
return found;
}
std::vector<FileInfo> Directory::getFiles(const std::string& dirname)
{
WIN32_FIND_DATA filePtr;
std::string tempPath = dirname;
tempPath += "\\*.*";
std::string currFile = "";
std::vector<FileInfo> found;
HANDLE hFind = FindFirstFile(tempPath.c_str(), &filePtr );
if (hFind == INVALID_HANDLE_VALUE) {
return found;
}
else
{
do
{
//check if its a file.
if (!(filePtr.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY ))
{
tempPath = dirname + "\\";
currFile = tempPath + filePtr.cFileName;
FileInfo info;
info.path = currFile;
info.name = filePtr.cFileName;
info.extention = Path::getExtension(currFile);
found.push_back(info);
}
}
while (FindNextFile(hFind, &filePtr) != 0);
FindClose(hFind);
}
return found;
}
} // namespace nx
<|endoftext|> |
<commit_before>/**************************************************************************
**
** This file is part of Qt Creator
**
** Copyright (c) 2012 Nokia Corporation and/or its subsidiary(-ies).
**
** Contact: Nokia Corporation (qt-info@nokia.com)
**
**
** GNU Lesser General Public License Usage
**
** This file may be used under the terms of the GNU Lesser General Public
** License version 2.1 as published by the Free Software Foundation and
** appearing in the file LICENSE.LGPL included in the packaging of this file.
** Please review the following information to ensure the GNU Lesser General
** Public License version 2.1 requirements will be met:
** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Nokia gives you certain additional
** rights. These rights are described in the Nokia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** Other Usage
**
** Alternatively, this file may be used in accordance with the terms and
** conditions contained in a signed written agreement between you and Nokia.
**
** If you have questions regarding the use of this file, please contact
** Nokia at qt-info@nokia.com.
**
**************************************************************************/
#include "profilemodel.h"
#include "profile.h"
#include "profileconfigwidget.h"
#include "profilemanager.h"
#include <utils/qtcassert.h>
#include <QApplication>
#include <QLayout>
#include <QMessageBox>
namespace ProjectExplorer {
namespace Internal {
class ProfileNode
{
public:
explicit ProfileNode(ProfileNode *pn, Profile *p = 0, bool c = false) :
parent(pn), profile(p), changed(c)
{
if (pn)
pn->childNodes.append(this);
widget = ProfileManager::instance()->createConfigWidget(p);
if (widget) {
if (p && p->isAutoDetected())
widget->makeReadOnly();
widget->setVisible(false);
}
}
~ProfileNode()
{
if (parent)
parent->childNodes.removeOne(this);
// deleting a child removes it from childNodes
// so operate on a temporary list
QList<ProfileNode *> tmp = childNodes;
qDeleteAll(tmp);
Q_ASSERT(childNodes.isEmpty());
}
ProfileNode *parent;
QString newName;
QList<ProfileNode *> childNodes;
Profile *profile;
ProfileConfigWidget *widget;
bool changed;
};
// --------------------------------------------------------------------------
// ProfileModel
// --------------------------------------------------------------------------
ProfileModel::ProfileModel(QBoxLayout *parentLayout, QObject *parent) :
QAbstractItemModel(parent),
m_parentLayout(parentLayout),
m_defaultNode(0)
{
Q_ASSERT(m_parentLayout);
connect(ProfileManager::instance(), SIGNAL(profileAdded(ProjectExplorer::Profile*)),
this, SLOT(addProfile(ProjectExplorer::Profile*)));
connect(ProfileManager::instance(), SIGNAL(profileRemoved(ProjectExplorer::Profile*)),
this, SLOT(removeProfile(ProjectExplorer::Profile*)));
connect(ProfileManager::instance(), SIGNAL(profileUpdated(ProjectExplorer::Profile*)),
this, SLOT(updateProfile(ProjectExplorer::Profile*)));
connect(ProfileManager::instance(), SIGNAL(defaultProfileChanged()),
this, SLOT(changeDefaultProfile()));
m_root = new ProfileNode(0);
m_autoRoot = new ProfileNode(m_root);
m_manualRoot = new ProfileNode(m_root);
foreach (Profile *p, ProfileManager::instance()->profiles())
addProfile(p);
changeDefaultProfile();
}
ProfileModel::~ProfileModel()
{
delete m_root;
}
QModelIndex ProfileModel::index(int row, int column, const QModelIndex &parent) const
{
if (!parent.isValid()) {
if (row >= 0 && row < m_root->childNodes.count())
return createIndex(row, column, m_root->childNodes.at(row));
}
ProfileNode *node = static_cast<ProfileNode *>(parent.internalPointer());
if (row < node->childNodes.count() && column == 0)
return createIndex(row, column, node->childNodes.at(row));
else
return QModelIndex();
}
QModelIndex ProfileModel::parent(const QModelIndex &idx) const
{
if (!idx.isValid())
return QModelIndex();
ProfileNode *node = static_cast<ProfileNode *>(idx.internalPointer());
if (node->parent == m_root)
return QModelIndex();
return index(node->parent);
}
int ProfileModel::rowCount(const QModelIndex &parent) const
{
if (!parent.isValid())
return m_root->childNodes.count();
ProfileNode *node = static_cast<ProfileNode *>(parent.internalPointer());
return node->childNodes.count();
}
int ProfileModel::columnCount(const QModelIndex &parent) const
{
Q_UNUSED(parent);
return 1;
}
QVariant ProfileModel::data(const QModelIndex &index, int role) const
{
static QIcon warningIcon(":/projectexplorer/images/compile_warning.png");
if (!index.isValid() || index.column() != 0)
return QVariant();
ProfileNode *node = static_cast<ProfileNode *>(index.internalPointer());
QTC_ASSERT(node, return QVariant());
if (node == m_autoRoot && role == Qt::DisplayRole)
return tr("Auto-detected");
if (node == m_manualRoot && role == Qt::DisplayRole)
return tr("Manual");
if (node->profile) {
if (role == Qt::FontRole) {
QFont f = QApplication::font();
if (node->changed)
f.setBold(!f.bold());
if (node == m_defaultNode)
f.setItalic(f.style() != QFont::StyleItalic);
return f;
} else if (role == Qt::DisplayRole || role == Qt::EditRole) {
QString baseName = node->newName.isEmpty() ? node->profile->displayName() : node->newName;
if (node == m_defaultNode)
//: Mark up a profile as the default one.
baseName = tr("%1 (default)").arg(baseName);
return baseName;
} else if (role == Qt::DecorationRole) {
return node->profile->isValid() ? QIcon() : warningIcon;
} else if (role == Qt::ToolTipRole) {
return node->profile->toHtml();
}
}
return QVariant();
}
bool ProfileModel::setData(const QModelIndex &index, const QVariant &value, int role)
{
if (!index.isValid())
return false;
ProfileNode *node = static_cast<ProfileNode *>(index.internalPointer());
Q_ASSERT(node);
if (index.column() != 0 || !node->profile || role != Qt::EditRole)
return false;
node->newName = value.toString();
if (!node->newName.isEmpty() && node->newName != node->profile->displayName())
node->changed = true;
return true;
}
Qt::ItemFlags ProfileModel::flags(const QModelIndex &index) const
{
if (!index.isValid())
return 0;
ProfileNode *node = static_cast<ProfileNode *>(index.internalPointer());
Q_ASSERT(node);
if (!node->profile)
return Qt::ItemIsEnabled;
if (node->profile->isAutoDetected())
return Qt::ItemIsEnabled | Qt::ItemIsSelectable;
return Qt::ItemIsEnabled | Qt::ItemIsSelectable | Qt::ItemIsEditable;
}
QVariant ProfileModel::headerData(int section, Qt::Orientation orientation, int role) const
{
Q_UNUSED(section);
if (orientation == Qt::Horizontal && role == Qt::DisplayRole)
return tr("Name");
return QVariant();
}
Profile *ProfileModel::profile(const QModelIndex &index)
{
if (!index.isValid())
return 0;
ProfileNode *node = static_cast<ProfileNode *>(index.internalPointer());
Q_ASSERT(node);
return node->profile;
}
QModelIndex ProfileModel::indexOf(Profile *p) const
{
ProfileNode *n = find(p);
return n ? index(n) : QModelIndex();
}
void ProfileModel::setDefaultProfile(const QModelIndex &index)
{
if (!index.isValid())
return;
ProfileNode *node = static_cast<ProfileNode *>(index.internalPointer());
Q_ASSERT(node);
if (node->profile)
setDefaultNode(node);
}
bool ProfileModel::isDefaultProfile(const QModelIndex &index)
{
return m_defaultNode == static_cast<ProfileNode *>(index.internalPointer());
}
ProfileConfigWidget *ProfileModel::widget(const QModelIndex &index)
{
if (!index.isValid())
return 0;
ProfileNode *node = static_cast<ProfileNode *>(index.internalPointer());
Q_ASSERT(node);
return node->widget;
}
bool ProfileModel::isDirty() const
{
foreach (ProfileNode *n, m_manualRoot->childNodes) {
if (n->changed)
return true;
}
return false;
}
bool ProfileModel::isDirty(Profile *p) const
{
ProfileNode *n = find(p);
return n ? !n->changed : false;
}
void ProfileModel::setDirty()
{
ProfileConfigWidget *w = qobject_cast<ProfileConfigWidget *>(sender());
foreach (ProfileNode *n, m_manualRoot->childNodes) {
if (n->widget == w) {
n->changed = true;
emit dataChanged(index(n, 0), index(n, columnCount(QModelIndex())));
}
}
}
void ProfileModel::apply()
{
// Remove unused profiles:
QList<ProfileNode *> nodes = m_toRemoveList;
foreach (ProfileNode *n, nodes) {
Q_ASSERT(!n->parent);
ProfileManager::instance()->deregisterProfile(n->profile);
}
Q_ASSERT(m_toRemoveList.isEmpty());
// Update profiles:
foreach (ProfileNode *n, m_manualRoot->childNodes) {
Q_ASSERT(n);
Q_ASSERT(n->profile);
if (n->changed) {
ProfileManager::instance()->blockSignals(true);
if (!n->newName.isEmpty()) {
n->profile->setDisplayName(n->newName);
n->newName.clear();
}
if (n->widget)
n->widget->apply();
n->changed = false;
ProfileManager::instance()->blockSignals(false);
ProfileManager::instance()->notifyAboutUpdate(n->profile);
emit dataChanged(index(n, 0), index(n, columnCount(QModelIndex())));
}
}
// Add new (and already updated) profiles
QStringList removedSts;
nodes = m_toAddList;
foreach (ProfileNode *n, nodes) {
if (!ProfileManager::instance()->registerProfile(n->profile))
removedSts << n->profile->displayName();
}
foreach (ProfileNode *n, m_toAddList)
markForRemoval(n->profile);
if (removedSts.count() == 1) {
QMessageBox::warning(0,
tr("Duplicate profiles detected"),
tr("The following profile was already configured:<br>"
" %1<br>"
"It was not configured again.")
.arg(removedSts.at(0)));
} else if (!removedSts.isEmpty()) {
QMessageBox::warning(0,
tr("Duplicate profile detected"),
tr("The following profiles were already configured:<br>"
" %1<br>"
"They were not configured again.")
.arg(removedSts.join(QLatin1String(",<br> "))));
}
// Set default profile:
if (m_defaultNode)
ProfileManager::instance()->setDefaultProfile(m_defaultNode->profile);
}
void ProfileModel::markForRemoval(Profile *p)
{
ProfileNode *node = find(p);
if (!node)
return;
beginRemoveRows(index(m_manualRoot), m_manualRoot->childNodes.indexOf(node), m_manualRoot->childNodes.indexOf(node));
m_manualRoot->childNodes.removeOne(node);
node->parent = 0;
if (m_toAddList.contains(node)) {
delete node->profile;
node->profile = 0;
m_toAddList.removeOne(node);
delete node;
} else {
m_toRemoveList.append(node);
}
endRemoveRows();
if (node == m_defaultNode) {
ProfileNode *newDefault = 0;
if (!m_autoRoot->childNodes.isEmpty())
newDefault = m_autoRoot->childNodes.at(0);
else if (!m_manualRoot->childNodes.isEmpty())
newDefault = m_manualRoot->childNodes.at(0);
setDefaultNode(newDefault);
}
}
void ProfileModel::markForAddition(Profile *p)
{
int pos = m_manualRoot->childNodes.size();
beginInsertRows(index(m_manualRoot), pos, pos);
ProfileNode *node = createNode(m_manualRoot, p, true);
m_toAddList.append(node);
if (!m_defaultNode)
setDefaultNode(node);
endInsertRows();
}
QModelIndex ProfileModel::index(ProfileNode *node, int column) const
{
if (node->parent == 0) // is root (or was marked for deletion)
return QModelIndex();
else if (node->parent == m_root)
return index(m_root->childNodes.indexOf(node), column, QModelIndex());
else
return index(node->parent->childNodes.indexOf(node), column, index(node->parent));
}
ProfileNode *ProfileModel::find(Profile *p) const
{
foreach (ProfileNode *n, m_autoRoot->childNodes) {
if (n->profile == p)
return n;
}
foreach (ProfileNode *n, m_manualRoot->childNodes) {
if (n->profile == p)
return n;
}
return 0;
}
ProfileNode *ProfileModel::createNode(ProfileNode *parent, Profile *p, bool changed)
{
ProfileNode *node = new ProfileNode(parent, p, changed);
if (node->widget) {
m_parentLayout->addWidget(node->widget);
connect(node->widget, SIGNAL(dirty()),
this, SLOT(setDirty()));
}
return node;
}
void ProfileModel::setDefaultNode(ProfileNode *node)
{
if (m_defaultNode) {
QModelIndex idx = index(m_defaultNode);
if (idx.isValid())
emit dataChanged(idx, idx);
}
m_defaultNode = node;
if (m_defaultNode) {
QModelIndex idx = index(m_defaultNode);
if (idx.isValid())
emit dataChanged(idx, idx);
}
}
void ProfileModel::addProfile(Profile *p)
{
QList<ProfileNode *> nodes = m_toAddList;
foreach (ProfileNode *n, nodes) {
if (n->profile == p) {
m_toAddList.removeOne(n);
// do not delete n: Still used elsewhere!
return;
}
}
ProfileNode *parent = m_manualRoot;
if (p->isAutoDetected())
parent = m_autoRoot;
int row = parent->childNodes.count();
beginInsertRows(index(parent), row, row);
createNode(parent, p, false);
endInsertRows();
emit profileStateChanged();
}
void ProfileModel::removeProfile(Profile *p)
{
QList<ProfileNode *> nodes = m_toRemoveList;
foreach (ProfileNode *n, nodes) {
if (n->profile == p) {
m_toRemoveList.removeOne(n);
delete n;
return;
}
}
ProfileNode *parent = m_manualRoot;
if (p->isAutoDetected())
parent = m_autoRoot;
int row = 0;
ProfileNode *node = 0;
foreach (ProfileNode *current, parent->childNodes) {
if (current->profile == p) {
node = current;
break;
}
++row;
}
beginRemoveRows(index(parent), row, row);
parent->childNodes.removeAt(row);
delete node;
endRemoveRows();
emit profileStateChanged();
}
void ProfileModel::updateProfile(Profile *p)
{
ProfileNode *n = find(p);
if (n->widget)
n->widget->discard();
QModelIndex idx = index(n);
emit dataChanged(idx, idx);
}
void ProfileModel::changeDefaultProfile()
{
setDefaultNode(find(ProfileManager::instance()->defaultProfile()));
}
} // namespace Internal
} // namespace ProjectExplorer
<commit_msg>ProfileModel: Do not add "(default)" to name of profile<commit_after>/**************************************************************************
**
** This file is part of Qt Creator
**
** Copyright (c) 2012 Nokia Corporation and/or its subsidiary(-ies).
**
** Contact: Nokia Corporation (qt-info@nokia.com)
**
**
** GNU Lesser General Public License Usage
**
** This file may be used under the terms of the GNU Lesser General Public
** License version 2.1 as published by the Free Software Foundation and
** appearing in the file LICENSE.LGPL included in the packaging of this file.
** Please review the following information to ensure the GNU Lesser General
** Public License version 2.1 requirements will be met:
** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Nokia gives you certain additional
** rights. These rights are described in the Nokia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** Other Usage
**
** Alternatively, this file may be used in accordance with the terms and
** conditions contained in a signed written agreement between you and Nokia.
**
** If you have questions regarding the use of this file, please contact
** Nokia at qt-info@nokia.com.
**
**************************************************************************/
#include "profilemodel.h"
#include "profile.h"
#include "profileconfigwidget.h"
#include "profilemanager.h"
#include <utils/qtcassert.h>
#include <QApplication>
#include <QLayout>
#include <QMessageBox>
namespace ProjectExplorer {
namespace Internal {
class ProfileNode
{
public:
explicit ProfileNode(ProfileNode *pn, Profile *p = 0, bool c = false) :
parent(pn), profile(p), changed(c)
{
if (pn)
pn->childNodes.append(this);
widget = ProfileManager::instance()->createConfigWidget(p);
if (widget) {
if (p && p->isAutoDetected())
widget->makeReadOnly();
widget->setVisible(false);
}
}
~ProfileNode()
{
if (parent)
parent->childNodes.removeOne(this);
// deleting a child removes it from childNodes
// so operate on a temporary list
QList<ProfileNode *> tmp = childNodes;
qDeleteAll(tmp);
Q_ASSERT(childNodes.isEmpty());
}
ProfileNode *parent;
QString newName;
QList<ProfileNode *> childNodes;
Profile *profile;
ProfileConfigWidget *widget;
bool changed;
};
// --------------------------------------------------------------------------
// ProfileModel
// --------------------------------------------------------------------------
ProfileModel::ProfileModel(QBoxLayout *parentLayout, QObject *parent) :
QAbstractItemModel(parent),
m_parentLayout(parentLayout),
m_defaultNode(0)
{
Q_ASSERT(m_parentLayout);
connect(ProfileManager::instance(), SIGNAL(profileAdded(ProjectExplorer::Profile*)),
this, SLOT(addProfile(ProjectExplorer::Profile*)));
connect(ProfileManager::instance(), SIGNAL(profileRemoved(ProjectExplorer::Profile*)),
this, SLOT(removeProfile(ProjectExplorer::Profile*)));
connect(ProfileManager::instance(), SIGNAL(profileUpdated(ProjectExplorer::Profile*)),
this, SLOT(updateProfile(ProjectExplorer::Profile*)));
connect(ProfileManager::instance(), SIGNAL(defaultProfileChanged()),
this, SLOT(changeDefaultProfile()));
m_root = new ProfileNode(0);
m_autoRoot = new ProfileNode(m_root);
m_manualRoot = new ProfileNode(m_root);
foreach (Profile *p, ProfileManager::instance()->profiles())
addProfile(p);
changeDefaultProfile();
}
ProfileModel::~ProfileModel()
{
delete m_root;
}
QModelIndex ProfileModel::index(int row, int column, const QModelIndex &parent) const
{
if (!parent.isValid()) {
if (row >= 0 && row < m_root->childNodes.count())
return createIndex(row, column, m_root->childNodes.at(row));
}
ProfileNode *node = static_cast<ProfileNode *>(parent.internalPointer());
if (row < node->childNodes.count() && column == 0)
return createIndex(row, column, node->childNodes.at(row));
else
return QModelIndex();
}
QModelIndex ProfileModel::parent(const QModelIndex &idx) const
{
if (!idx.isValid())
return QModelIndex();
ProfileNode *node = static_cast<ProfileNode *>(idx.internalPointer());
if (node->parent == m_root)
return QModelIndex();
return index(node->parent);
}
int ProfileModel::rowCount(const QModelIndex &parent) const
{
if (!parent.isValid())
return m_root->childNodes.count();
ProfileNode *node = static_cast<ProfileNode *>(parent.internalPointer());
return node->childNodes.count();
}
int ProfileModel::columnCount(const QModelIndex &parent) const
{
Q_UNUSED(parent);
return 1;
}
QVariant ProfileModel::data(const QModelIndex &index, int role) const
{
static QIcon warningIcon(":/projectexplorer/images/compile_warning.png");
if (!index.isValid() || index.column() != 0)
return QVariant();
ProfileNode *node = static_cast<ProfileNode *>(index.internalPointer());
QTC_ASSERT(node, return QVariant());
if (node == m_autoRoot && role == Qt::DisplayRole)
return tr("Auto-detected");
if (node == m_manualRoot && role == Qt::DisplayRole)
return tr("Manual");
if (node->profile) {
if (role == Qt::FontRole) {
QFont f = QApplication::font();
if (node->changed)
f.setBold(!f.bold());
if (node == m_defaultNode)
f.setItalic(f.style() != QFont::StyleItalic);
return f;
} else if (role == Qt::DisplayRole) {
QString baseName = node->newName.isEmpty() ? node->profile->displayName() : node->newName;
if (node == m_defaultNode)
//: Mark up a profile as the default one.
baseName = tr("%1 (default)").arg(baseName);
return baseName;
} else if (role == Qt::EditRole) {
return node->newName.isEmpty() ? node->profile->displayName() : node->newName;
} else if (role == Qt::DecorationRole) {
return node->profile->isValid() ? QIcon() : warningIcon;
} else if (role == Qt::ToolTipRole) {
return node->profile->toHtml();
}
}
return QVariant();
}
bool ProfileModel::setData(const QModelIndex &index, const QVariant &value, int role)
{
if (!index.isValid())
return false;
ProfileNode *node = static_cast<ProfileNode *>(index.internalPointer());
Q_ASSERT(node);
if (index.column() != 0 || !node->profile || role != Qt::EditRole)
return false;
node->newName = value.toString();
if (!node->newName.isEmpty() && node->newName != node->profile->displayName())
node->changed = true;
return true;
}
Qt::ItemFlags ProfileModel::flags(const QModelIndex &index) const
{
if (!index.isValid())
return 0;
ProfileNode *node = static_cast<ProfileNode *>(index.internalPointer());
Q_ASSERT(node);
if (!node->profile)
return Qt::ItemIsEnabled;
if (node->profile->isAutoDetected())
return Qt::ItemIsEnabled | Qt::ItemIsSelectable;
return Qt::ItemIsEnabled | Qt::ItemIsSelectable | Qt::ItemIsEditable;
}
QVariant ProfileModel::headerData(int section, Qt::Orientation orientation, int role) const
{
Q_UNUSED(section);
if (orientation == Qt::Horizontal && role == Qt::DisplayRole)
return tr("Name");
return QVariant();
}
Profile *ProfileModel::profile(const QModelIndex &index)
{
if (!index.isValid())
return 0;
ProfileNode *node = static_cast<ProfileNode *>(index.internalPointer());
Q_ASSERT(node);
return node->profile;
}
QModelIndex ProfileModel::indexOf(Profile *p) const
{
ProfileNode *n = find(p);
return n ? index(n) : QModelIndex();
}
void ProfileModel::setDefaultProfile(const QModelIndex &index)
{
if (!index.isValid())
return;
ProfileNode *node = static_cast<ProfileNode *>(index.internalPointer());
Q_ASSERT(node);
if (node->profile)
setDefaultNode(node);
}
bool ProfileModel::isDefaultProfile(const QModelIndex &index)
{
return m_defaultNode == static_cast<ProfileNode *>(index.internalPointer());
}
ProfileConfigWidget *ProfileModel::widget(const QModelIndex &index)
{
if (!index.isValid())
return 0;
ProfileNode *node = static_cast<ProfileNode *>(index.internalPointer());
Q_ASSERT(node);
return node->widget;
}
bool ProfileModel::isDirty() const
{
foreach (ProfileNode *n, m_manualRoot->childNodes) {
if (n->changed)
return true;
}
return false;
}
bool ProfileModel::isDirty(Profile *p) const
{
ProfileNode *n = find(p);
return n ? !n->changed : false;
}
void ProfileModel::setDirty()
{
ProfileConfigWidget *w = qobject_cast<ProfileConfigWidget *>(sender());
foreach (ProfileNode *n, m_manualRoot->childNodes) {
if (n->widget == w) {
n->changed = true;
emit dataChanged(index(n, 0), index(n, columnCount(QModelIndex())));
}
}
}
void ProfileModel::apply()
{
// Remove unused profiles:
QList<ProfileNode *> nodes = m_toRemoveList;
foreach (ProfileNode *n, nodes) {
Q_ASSERT(!n->parent);
ProfileManager::instance()->deregisterProfile(n->profile);
}
Q_ASSERT(m_toRemoveList.isEmpty());
// Update profiles:
foreach (ProfileNode *n, m_manualRoot->childNodes) {
Q_ASSERT(n);
Q_ASSERT(n->profile);
if (n->changed) {
ProfileManager::instance()->blockSignals(true);
if (!n->newName.isEmpty()) {
n->profile->setDisplayName(n->newName);
n->newName.clear();
}
if (n->widget)
n->widget->apply();
n->changed = false;
ProfileManager::instance()->blockSignals(false);
ProfileManager::instance()->notifyAboutUpdate(n->profile);
emit dataChanged(index(n, 0), index(n, columnCount(QModelIndex())));
}
}
// Add new (and already updated) profiles
QStringList removedSts;
nodes = m_toAddList;
foreach (ProfileNode *n, nodes) {
if (!ProfileManager::instance()->registerProfile(n->profile))
removedSts << n->profile->displayName();
}
foreach (ProfileNode *n, m_toAddList)
markForRemoval(n->profile);
if (removedSts.count() == 1) {
QMessageBox::warning(0,
tr("Duplicate profiles detected"),
tr("The following profile was already configured:<br>"
" %1<br>"
"It was not configured again.")
.arg(removedSts.at(0)));
} else if (!removedSts.isEmpty()) {
QMessageBox::warning(0,
tr("Duplicate profile detected"),
tr("The following profiles were already configured:<br>"
" %1<br>"
"They were not configured again.")
.arg(removedSts.join(QLatin1String(",<br> "))));
}
// Set default profile:
if (m_defaultNode)
ProfileManager::instance()->setDefaultProfile(m_defaultNode->profile);
}
void ProfileModel::markForRemoval(Profile *p)
{
ProfileNode *node = find(p);
if (!node)
return;
beginRemoveRows(index(m_manualRoot), m_manualRoot->childNodes.indexOf(node), m_manualRoot->childNodes.indexOf(node));
m_manualRoot->childNodes.removeOne(node);
node->parent = 0;
if (m_toAddList.contains(node)) {
delete node->profile;
node->profile = 0;
m_toAddList.removeOne(node);
delete node;
} else {
m_toRemoveList.append(node);
}
endRemoveRows();
if (node == m_defaultNode) {
ProfileNode *newDefault = 0;
if (!m_autoRoot->childNodes.isEmpty())
newDefault = m_autoRoot->childNodes.at(0);
else if (!m_manualRoot->childNodes.isEmpty())
newDefault = m_manualRoot->childNodes.at(0);
setDefaultNode(newDefault);
}
}
void ProfileModel::markForAddition(Profile *p)
{
int pos = m_manualRoot->childNodes.size();
beginInsertRows(index(m_manualRoot), pos, pos);
ProfileNode *node = createNode(m_manualRoot, p, true);
m_toAddList.append(node);
if (!m_defaultNode)
setDefaultNode(node);
endInsertRows();
}
QModelIndex ProfileModel::index(ProfileNode *node, int column) const
{
if (node->parent == 0) // is root (or was marked for deletion)
return QModelIndex();
else if (node->parent == m_root)
return index(m_root->childNodes.indexOf(node), column, QModelIndex());
else
return index(node->parent->childNodes.indexOf(node), column, index(node->parent));
}
ProfileNode *ProfileModel::find(Profile *p) const
{
foreach (ProfileNode *n, m_autoRoot->childNodes) {
if (n->profile == p)
return n;
}
foreach (ProfileNode *n, m_manualRoot->childNodes) {
if (n->profile == p)
return n;
}
return 0;
}
ProfileNode *ProfileModel::createNode(ProfileNode *parent, Profile *p, bool changed)
{
ProfileNode *node = new ProfileNode(parent, p, changed);
if (node->widget) {
m_parentLayout->addWidget(node->widget);
connect(node->widget, SIGNAL(dirty()),
this, SLOT(setDirty()));
}
return node;
}
void ProfileModel::setDefaultNode(ProfileNode *node)
{
if (m_defaultNode) {
QModelIndex idx = index(m_defaultNode);
if (idx.isValid())
emit dataChanged(idx, idx);
}
m_defaultNode = node;
if (m_defaultNode) {
QModelIndex idx = index(m_defaultNode);
if (idx.isValid())
emit dataChanged(idx, idx);
}
}
void ProfileModel::addProfile(Profile *p)
{
QList<ProfileNode *> nodes = m_toAddList;
foreach (ProfileNode *n, nodes) {
if (n->profile == p) {
m_toAddList.removeOne(n);
// do not delete n: Still used elsewhere!
return;
}
}
ProfileNode *parent = m_manualRoot;
if (p->isAutoDetected())
parent = m_autoRoot;
int row = parent->childNodes.count();
beginInsertRows(index(parent), row, row);
createNode(parent, p, false);
endInsertRows();
emit profileStateChanged();
}
void ProfileModel::removeProfile(Profile *p)
{
QList<ProfileNode *> nodes = m_toRemoveList;
foreach (ProfileNode *n, nodes) {
if (n->profile == p) {
m_toRemoveList.removeOne(n);
delete n;
return;
}
}
ProfileNode *parent = m_manualRoot;
if (p->isAutoDetected())
parent = m_autoRoot;
int row = 0;
ProfileNode *node = 0;
foreach (ProfileNode *current, parent->childNodes) {
if (current->profile == p) {
node = current;
break;
}
++row;
}
beginRemoveRows(index(parent), row, row);
parent->childNodes.removeAt(row);
delete node;
endRemoveRows();
emit profileStateChanged();
}
void ProfileModel::updateProfile(Profile *p)
{
ProfileNode *n = find(p);
if (n->widget)
n->widget->discard();
QModelIndex idx = index(n);
emit dataChanged(idx, idx);
}
void ProfileModel::changeDefaultProfile()
{
setDefaultNode(find(ProfileManager::instance()->defaultProfile()));
}
} // namespace Internal
} // namespace ProjectExplorer
<|endoftext|> |
<commit_before>/**************************************************************************
**
** This file is part of Qt Creator
**
** Copyright (c) 2011 Nokia Corporation and/or its subsidiary(-ies).
**
** Contact: Nokia Corporation (qt-info@nokia.com)
**
** No Commercial Usage
**
** This file contains pre-release code and may not be distributed.
** You may use this file in accordance with the terms and conditions
** contained in the Technology Preview License Agreement accompanying
** this package.
**
** GNU Lesser General Public License Usage
**
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file. Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Nokia gives you certain additional
** rights. These rights are described in the Nokia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** If you have questions regarding the use of this file, please contact
** Nokia at qt-info@nokia.com.
**
**************************************************************************/
#include "qmljsplugindumper.h"
#include "qmljsmodelmanager.h"
#include <qmljs/qmljsdocument.h>
#include <qmljs/qmljsinterpreter.h>
#include <projectexplorer/filewatcher.h>
#include <projectexplorer/projectexplorer.h>
#include <coreplugin/messagemanager.h>
#include <QtCore/QDir>
using namespace LanguageUtils;
using namespace QmlJS;
using namespace QmlJSTools;
using namespace QmlJSTools::Internal;
PluginDumper::PluginDumper(ModelManager *modelManager)
: QObject(modelManager)
, m_modelManager(modelManager)
, m_pluginWatcher(new ProjectExplorer::FileWatcher(this))
{
connect(m_pluginWatcher, SIGNAL(fileChanged(QString)), SLOT(pluginChanged(QString)));
}
void PluginDumper::loadPluginTypes(const QString &libraryPath, const QString &importPath, const QString &importUri, const QString &importVersion)
{
// move to the owning thread
metaObject()->invokeMethod(this, "onLoadPluginTypes",
Q_ARG(QString, libraryPath),
Q_ARG(QString, importPath),
Q_ARG(QString, importUri),
Q_ARG(QString, importVersion));
}
void PluginDumper::onLoadPluginTypes(const QString &libraryPath, const QString &importPath, const QString &importUri, const QString &importVersion)
{
const QString canonicalLibraryPath = QDir::cleanPath(libraryPath);
if (m_runningQmldumps.values().contains(canonicalLibraryPath))
return;
const Snapshot snapshot = m_modelManager->snapshot();
const LibraryInfo libraryInfo = snapshot.libraryInfo(canonicalLibraryPath);
if (libraryInfo.dumpStatus() != LibraryInfo::DumpNotStartedOrRunning)
return;
// avoid inserting the same plugin twice
int index;
for (index = 0; index < m_plugins.size(); ++index) {
if (m_plugins.at(index).qmldirPath == libraryPath)
break;
}
if (index == m_plugins.size())
m_plugins.append(Plugin());
Plugin &plugin = m_plugins[index];
plugin.qmldirPath = canonicalLibraryPath;
plugin.importPath = importPath;
plugin.importUri = importUri;
plugin.importVersion = importVersion;
// watch plugin libraries
foreach (const QmlDirParser::Plugin &plugin, snapshot.libraryInfo(canonicalLibraryPath).plugins()) {
const QString pluginLibrary = resolvePlugin(canonicalLibraryPath, plugin.path, plugin.name);
m_pluginWatcher->addFile(pluginLibrary);
m_libraryToPluginIndex.insert(pluginLibrary, index);
}
// watch library xml file
if (plugin.hasPredumpedQmlTypesFile()) {
const QString &path = plugin.predumpedQmlTypesFilePath();
m_pluginWatcher->addFile(path);
m_libraryToPluginIndex.insert(path, index);
}
dump(plugin);
}
void PluginDumper::scheduleCompleteRedump()
{
metaObject()->invokeMethod(this, "dumpAllPlugins", Qt::QueuedConnection);
}
void PluginDumper::dumpAllPlugins()
{
foreach (const Plugin &plugin, m_plugins)
dump(plugin);
}
static QString qmldumpErrorMessage(const QString &libraryPath, const QString &error)
{
return PluginDumper::tr("Type dump of QML plugin in %1 failed.\nErrors:\n%2\n").
arg(libraryPath, error);
}
static QString qmldumpFailedMessage(const QString &error)
{
QString firstLines =
QStringList(error.split(QLatin1Char('\n')).mid(0, 10)).join(QLatin1String("\n"));
return PluginDumper::tr("Type dump of C++ plugin failed.\n"
"First 10 lines or errors:\n"
"\n"
"%1"
"\n"
"Check 'General Messages' output pane for details."
).arg(firstLines);
}
static QList<FakeMetaObject::ConstPtr> parseHelper(const QByteArray &qmlTypeDescriptions, QString *error)
{
QList<FakeMetaObject::ConstPtr> ret;
QHash<QString, FakeMetaObject::ConstPtr> newObjects;
*error = Interpreter::CppQmlTypesLoader::parseQmlTypeDescriptions(qmlTypeDescriptions, &newObjects);
if (error->isEmpty()) {
ret = newObjects.values();
}
return ret;
}
void PluginDumper::qmlPluginTypeDumpDone(int exitCode)
{
QProcess *process = qobject_cast<QProcess *>(sender());
if (!process)
return;
process->deleteLater();
const QString libraryPath = m_runningQmldumps.take(process);
const Snapshot snapshot = m_modelManager->snapshot();
LibraryInfo libraryInfo = snapshot.libraryInfo(libraryPath);
if (exitCode != 0) {
Core::MessageManager *messageManager = Core::MessageManager::instance();
const QString errorMessages = process->readAllStandardError();
messageManager->printToOutputPane(qmldumpErrorMessage(libraryPath, errorMessages));
libraryInfo.setDumpStatus(LibraryInfo::DumpError, qmldumpFailedMessage(errorMessages));
}
const QByteArray output = process->readAllStandardOutput();
QString error;
QList<FakeMetaObject::ConstPtr> objectsList = parseHelper(output, &error);
if (exitCode == 0 && !error.isEmpty()) {
libraryInfo.setDumpStatus(LibraryInfo::DumpError, tr("Type dump of C++ plugin failed. Parse error:\n'%1'").arg(error));
}
if (exitCode == 0 && error.isEmpty()) {
libraryInfo.setMetaObjects(objectsList);
// ### disabled code path for running qmldump to get Qt's builtins
// if (libraryPath.isEmpty())
// Interpreter::CppQmlTypesLoader::builtinObjects.append(objectsList);
libraryInfo.setDumpStatus(LibraryInfo::DumpDone);
}
if (!libraryPath.isEmpty())
m_modelManager->updateLibraryInfo(libraryPath, libraryInfo);
}
void PluginDumper::qmlPluginTypeDumpError(QProcess::ProcessError)
{
QProcess *process = qobject_cast<QProcess *>(sender());
if (!process)
return;
process->deleteLater();
const QString libraryPath = m_runningQmldumps.take(process);
Core::MessageManager *messageManager = Core::MessageManager::instance();
const QString errorMessages = process->readAllStandardError();
messageManager->printToOutputPane(qmldumpErrorMessage(libraryPath, errorMessages));
if (!libraryPath.isEmpty()) {
const Snapshot snapshot = m_modelManager->snapshot();
LibraryInfo libraryInfo = snapshot.libraryInfo(libraryPath);
libraryInfo.setDumpStatus(LibraryInfo::DumpError, qmldumpFailedMessage(errorMessages));
m_modelManager->updateLibraryInfo(libraryPath, libraryInfo);
}
}
void PluginDumper::pluginChanged(const QString &pluginLibrary)
{
const int pluginIndex = m_libraryToPluginIndex.value(pluginLibrary, -1);
if (pluginIndex == -1)
return;
const Plugin &plugin = m_plugins.at(pluginIndex);
dump(plugin);
}
void PluginDumper::dump(const Plugin &plugin)
{
if (plugin.hasPredumpedQmlTypesFile()) {
const Snapshot snapshot = m_modelManager->snapshot();
LibraryInfo libraryInfo = snapshot.libraryInfo(plugin.qmldirPath);
if (!libraryInfo.isValid())
return;
const QString &path = plugin.predumpedQmlTypesFilePath();
QFile libraryQmlTypesFile(path);
if (!libraryQmlTypesFile.open(QFile::ReadOnly | QFile::Text)) {
libraryInfo.setDumpStatus(LibraryInfo::DumpError,
tr("Could not open file '%1' for reading.").arg(path));
m_modelManager->updateLibraryInfo(plugin.qmldirPath, libraryInfo);
return;
}
const QByteArray qmlTypeDescriptions = libraryQmlTypesFile.readAll();
libraryQmlTypesFile.close();
QString error;
const QList<FakeMetaObject::ConstPtr> objectsList = parseHelper(qmlTypeDescriptions, &error);
if (error.isEmpty()) {
libraryInfo.setMetaObjects(objectsList);
libraryInfo.setDumpStatus(LibraryInfo::DumpDone);
} else {
libraryInfo.setDumpStatus(LibraryInfo::DumpError,
tr("Failed to parse '%1'.\nError: %2").arg(path, error));
}
m_modelManager->updateLibraryInfo(plugin.qmldirPath, libraryInfo);
return;
}
ProjectExplorer::Project *activeProject = ProjectExplorer::ProjectExplorerPlugin::instance()->startupProject();
if (!activeProject)
return;
ModelManagerInterface::ProjectInfo info = m_modelManager->projectInfo(activeProject);
if (info.qmlDumpPath.isEmpty()) {
const Snapshot snapshot = m_modelManager->snapshot();
LibraryInfo libraryInfo = snapshot.libraryInfo(plugin.qmldirPath);
if (!libraryInfo.isValid())
return;
libraryInfo.setDumpStatus(LibraryInfo::DumpError,
tr("Could not locate the helper application for dumping type information from C++ plugins.\n"
"Please build the debugging helpers on the Qt version options page."));
m_modelManager->updateLibraryInfo(plugin.qmldirPath, libraryInfo);
return;
}
QProcess *process = new QProcess(this);
process->setEnvironment(info.qmlDumpEnvironment.toStringList());
connect(process, SIGNAL(finished(int)), SLOT(qmlPluginTypeDumpDone(int)));
connect(process, SIGNAL(error(QProcess::ProcessError)), SLOT(qmlPluginTypeDumpError(QProcess::ProcessError)));
QStringList args;
if (plugin.importUri.isEmpty()) {
args << QLatin1String("--path");
args << plugin.importPath;
if (ComponentVersion(plugin.importVersion).isValid())
args << plugin.importVersion;
} else {
args << plugin.importUri;
args << plugin.importVersion;
args << plugin.importPath;
}
process->start(info.qmlDumpPath, args);
m_runningQmldumps.insert(process, plugin.qmldirPath);
}
/*!
Returns the result of the merge of \a baseName with \a path, \a suffixes, and \a prefix.
The \a prefix must contain the dot.
\a qmldirPath is the location of the qmldir file.
Adapted from QDeclarativeImportDatabase::resolvePlugin.
*/
QString PluginDumper::resolvePlugin(const QDir &qmldirPath, const QString &qmldirPluginPath,
const QString &baseName, const QStringList &suffixes,
const QString &prefix)
{
QStringList searchPaths;
searchPaths.append(QLatin1String("."));
bool qmldirPluginPathIsRelative = QDir::isRelativePath(qmldirPluginPath);
if (!qmldirPluginPathIsRelative)
searchPaths.prepend(qmldirPluginPath);
foreach (const QString &pluginPath, searchPaths) {
QString resolvedPath;
if (pluginPath == QLatin1String(".")) {
if (qmldirPluginPathIsRelative)
resolvedPath = qmldirPath.absoluteFilePath(qmldirPluginPath);
else
resolvedPath = qmldirPath.absolutePath();
} else {
resolvedPath = pluginPath;
}
QDir dir(resolvedPath);
foreach (const QString &suffix, suffixes) {
QString pluginFileName = prefix;
pluginFileName += baseName;
pluginFileName += suffix;
QFileInfo fileInfo(dir, pluginFileName);
if (fileInfo.exists())
return fileInfo.absoluteFilePath();
}
}
return QString();
}
/*!
Returns the result of the merge of \a baseName with \a dir and the platform suffix.
Adapted from QDeclarativeImportDatabase::resolvePlugin.
\table
\header \i Platform \i Valid suffixes
\row \i Windows \i \c .dll
\row \i Unix/Linux \i \c .so
\row \i AIX \i \c .a
\row \i HP-UX \i \c .sl, \c .so (HP-UXi)
\row \i Mac OS X \i \c .dylib, \c .bundle, \c .so
\row \i Symbian \i \c .dll
\endtable
Version number on unix are ignored.
*/
QString PluginDumper::resolvePlugin(const QDir &qmldirPath, const QString &qmldirPluginPath,
const QString &baseName)
{
#if defined(Q_OS_WIN32) || defined(Q_OS_WINCE)
return resolvePlugin(qmldirPath, qmldirPluginPath, baseName,
QStringList()
<< QLatin1String("d.dll") // try a qmake-style debug build first
<< QLatin1String(".dll"));
#elif defined(Q_OS_DARWIN)
return resolvePlugin(qmldirPath, qmldirPluginPath, baseName,
QStringList()
<< QLatin1String("_debug.dylib") // try a qmake-style debug build first
<< QLatin1String(".dylib")
<< QLatin1String(".so")
<< QLatin1String(".bundle"),
QLatin1String("lib"));
#else // Generic Unix
QStringList validSuffixList;
# if defined(Q_OS_HPUX)
/*
See "HP-UX Linker and Libraries User's Guide", section "Link-time Differences between PA-RISC and IPF":
"In PA-RISC (PA-32 and PA-64) shared libraries are suffixed with .sl. In IPF (32-bit and 64-bit),
the shared libraries are suffixed with .so. For compatibility, the IPF linker also supports the .sl suffix."
*/
validSuffixList << QLatin1String(".sl");
# if defined __ia64
validSuffixList << QLatin1String(".so");
# endif
# elif defined(Q_OS_AIX)
validSuffixList << QLatin1String(".a") << QLatin1String(".so");
# elif defined(Q_OS_UNIX)
validSuffixList << QLatin1String(".so");
# endif
// Examples of valid library names:
// libfoo.so
return resolvePlugin(qmldirPath, qmldirPluginPath, baseName, validSuffixList, QLatin1String("lib"));
#endif
}
bool PluginDumper::Plugin::hasPredumpedQmlTypesFile() const
{
return QFileInfo(predumpedQmlTypesFilePath()).isFile();
}
QString PluginDumper::Plugin::predumpedQmlTypesFilePath() const
{
return QString("%1%2plugins.qmltypes").arg(qmldirPath, QDir::separator());
}
<commit_msg>QmlJSDumper: fix for plugins/components<commit_after>/**************************************************************************
**
** This file is part of Qt Creator
**
** Copyright (c) 2011 Nokia Corporation and/or its subsidiary(-ies).
**
** Contact: Nokia Corporation (qt-info@nokia.com)
**
** No Commercial Usage
**
** This file contains pre-release code and may not be distributed.
** You may use this file in accordance with the terms and conditions
** contained in the Technology Preview License Agreement accompanying
** this package.
**
** GNU Lesser General Public License Usage
**
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file. Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Nokia gives you certain additional
** rights. These rights are described in the Nokia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** If you have questions regarding the use of this file, please contact
** Nokia at qt-info@nokia.com.
**
**************************************************************************/
#include "qmljsplugindumper.h"
#include "qmljsmodelmanager.h"
#include <qmljs/qmljsdocument.h>
#include <qmljs/qmljsinterpreter.h>
#include <projectexplorer/filewatcher.h>
#include <projectexplorer/projectexplorer.h>
#include <coreplugin/messagemanager.h>
#include <QtCore/QDir>
using namespace LanguageUtils;
using namespace QmlJS;
using namespace QmlJSTools;
using namespace QmlJSTools::Internal;
PluginDumper::PluginDumper(ModelManager *modelManager)
: QObject(modelManager)
, m_modelManager(modelManager)
, m_pluginWatcher(new ProjectExplorer::FileWatcher(this))
{
connect(m_pluginWatcher, SIGNAL(fileChanged(QString)), SLOT(pluginChanged(QString)));
}
void PluginDumper::loadPluginTypes(const QString &libraryPath, const QString &importPath, const QString &importUri, const QString &importVersion)
{
// move to the owning thread
metaObject()->invokeMethod(this, "onLoadPluginTypes",
Q_ARG(QString, libraryPath),
Q_ARG(QString, importPath),
Q_ARG(QString, importUri),
Q_ARG(QString, importVersion));
}
void PluginDumper::onLoadPluginTypes(const QString &libraryPath, const QString &importPath, const QString &importUri, const QString &importVersion)
{
const QString canonicalLibraryPath = QDir::cleanPath(libraryPath);
if (m_runningQmldumps.values().contains(canonicalLibraryPath))
return;
const Snapshot snapshot = m_modelManager->snapshot();
const LibraryInfo libraryInfo = snapshot.libraryInfo(canonicalLibraryPath);
if (libraryInfo.dumpStatus() != LibraryInfo::DumpNotStartedOrRunning)
return;
// avoid inserting the same plugin twice
int index;
for (index = 0; index < m_plugins.size(); ++index) {
if (m_plugins.at(index).qmldirPath == libraryPath)
break;
}
if (index == m_plugins.size())
m_plugins.append(Plugin());
Plugin &plugin = m_plugins[index];
plugin.qmldirPath = canonicalLibraryPath;
plugin.importPath = importPath;
plugin.importUri = importUri;
plugin.importVersion = importVersion;
// watch plugin libraries
foreach (const QmlDirParser::Plugin &plugin, snapshot.libraryInfo(canonicalLibraryPath).plugins()) {
const QString pluginLibrary = resolvePlugin(canonicalLibraryPath, plugin.path, plugin.name);
m_pluginWatcher->addFile(pluginLibrary);
m_libraryToPluginIndex.insert(pluginLibrary, index);
}
// watch library xml file
if (plugin.hasPredumpedQmlTypesFile()) {
const QString &path = plugin.predumpedQmlTypesFilePath();
m_pluginWatcher->addFile(path);
m_libraryToPluginIndex.insert(path, index);
}
dump(plugin);
}
void PluginDumper::scheduleCompleteRedump()
{
metaObject()->invokeMethod(this, "dumpAllPlugins", Qt::QueuedConnection);
}
void PluginDumper::dumpAllPlugins()
{
foreach (const Plugin &plugin, m_plugins)
dump(plugin);
}
static QString qmldumpErrorMessage(const QString &libraryPath, const QString &error)
{
return PluginDumper::tr("Type dump of QML plugin in %1 failed.\nErrors:\n%2\n").
arg(libraryPath, error);
}
static QString qmldumpFailedMessage(const QString &error)
{
QString firstLines =
QStringList(error.split(QLatin1Char('\n')).mid(0, 10)).join(QLatin1String("\n"));
return PluginDumper::tr("Type dump of C++ plugin failed.\n"
"First 10 lines or errors:\n"
"\n"
"%1"
"\n"
"Check 'General Messages' output pane for details."
).arg(firstLines);
}
static QList<FakeMetaObject::ConstPtr> parseHelper(const QByteArray &qmlTypeDescriptions, QString *error)
{
QList<FakeMetaObject::ConstPtr> ret;
QHash<QString, FakeMetaObject::ConstPtr> newObjects;
*error = Interpreter::CppQmlTypesLoader::parseQmlTypeDescriptions(qmlTypeDescriptions, &newObjects);
if (error->isEmpty()) {
ret = newObjects.values();
}
return ret;
}
void PluginDumper::qmlPluginTypeDumpDone(int exitCode)
{
QProcess *process = qobject_cast<QProcess *>(sender());
if (!process)
return;
process->deleteLater();
const QString libraryPath = m_runningQmldumps.take(process);
const Snapshot snapshot = m_modelManager->snapshot();
LibraryInfo libraryInfo = snapshot.libraryInfo(libraryPath);
if (exitCode != 0) {
Core::MessageManager *messageManager = Core::MessageManager::instance();
const QString errorMessages = process->readAllStandardError();
messageManager->printToOutputPane(qmldumpErrorMessage(libraryPath, errorMessages));
libraryInfo.setDumpStatus(LibraryInfo::DumpError, qmldumpFailedMessage(errorMessages));
}
const QByteArray output = process->readAllStandardOutput();
QString error;
QList<FakeMetaObject::ConstPtr> objectsList = parseHelper(output, &error);
if (exitCode == 0 && !error.isEmpty()) {
libraryInfo.setDumpStatus(LibraryInfo::DumpError, tr("Type dump of C++ plugin failed. Parse error:\n'%1'").arg(error));
}
if (exitCode == 0 && error.isEmpty()) {
libraryInfo.setMetaObjects(objectsList);
// ### disabled code path for running qmldump to get Qt's builtins
// if (libraryPath.isEmpty())
// Interpreter::CppQmlTypesLoader::builtinObjects.append(objectsList);
libraryInfo.setDumpStatus(LibraryInfo::DumpDone);
}
if (!libraryPath.isEmpty())
m_modelManager->updateLibraryInfo(libraryPath, libraryInfo);
}
void PluginDumper::qmlPluginTypeDumpError(QProcess::ProcessError)
{
QProcess *process = qobject_cast<QProcess *>(sender());
if (!process)
return;
process->deleteLater();
const QString libraryPath = m_runningQmldumps.take(process);
Core::MessageManager *messageManager = Core::MessageManager::instance();
const QString errorMessages = process->readAllStandardError();
messageManager->printToOutputPane(qmldumpErrorMessage(libraryPath, errorMessages));
if (!libraryPath.isEmpty()) {
const Snapshot snapshot = m_modelManager->snapshot();
LibraryInfo libraryInfo = snapshot.libraryInfo(libraryPath);
libraryInfo.setDumpStatus(LibraryInfo::DumpError, qmldumpFailedMessage(errorMessages));
m_modelManager->updateLibraryInfo(libraryPath, libraryInfo);
}
}
void PluginDumper::pluginChanged(const QString &pluginLibrary)
{
const int pluginIndex = m_libraryToPluginIndex.value(pluginLibrary, -1);
if (pluginIndex == -1)
return;
const Plugin &plugin = m_plugins.at(pluginIndex);
dump(plugin);
}
void PluginDumper::dump(const Plugin &plugin)
{
if (plugin.hasPredumpedQmlTypesFile()) {
const Snapshot snapshot = m_modelManager->snapshot();
LibraryInfo libraryInfo = snapshot.libraryInfo(plugin.qmldirPath);
if (!libraryInfo.isValid())
return;
const QString &path = plugin.predumpedQmlTypesFilePath();
QFile libraryQmlTypesFile(path);
if (!libraryQmlTypesFile.open(QFile::ReadOnly | QFile::Text)) {
libraryInfo.setDumpStatus(LibraryInfo::DumpError,
tr("Could not open file '%1' for reading.").arg(path));
m_modelManager->updateLibraryInfo(plugin.qmldirPath, libraryInfo);
return;
}
const QByteArray qmlTypeDescriptions = libraryQmlTypesFile.readAll();
libraryQmlTypesFile.close();
QString error;
const QList<FakeMetaObject::ConstPtr> objectsList = parseHelper(qmlTypeDescriptions, &error);
if (error.isEmpty()) {
libraryInfo.setMetaObjects(objectsList);
libraryInfo.setDumpStatus(LibraryInfo::DumpDone);
} else {
libraryInfo.setDumpStatus(LibraryInfo::DumpError,
tr("Failed to parse '%1'.\nError: %2").arg(path, error));
}
m_modelManager->updateLibraryInfo(plugin.qmldirPath, libraryInfo);
return;
}
ProjectExplorer::Project *activeProject = ProjectExplorer::ProjectExplorerPlugin::instance()->startupProject();
if (!activeProject)
return;
ModelManagerInterface::ProjectInfo info = m_modelManager->projectInfo(activeProject);
if (info.qmlDumpPath.isEmpty()) {
const Snapshot snapshot = m_modelManager->snapshot();
LibraryInfo libraryInfo = snapshot.libraryInfo(plugin.qmldirPath);
if (!libraryInfo.isValid())
return;
libraryInfo.setDumpStatus(LibraryInfo::DumpError,
tr("Could not locate the helper application for dumping type information from C++ plugins.\n"
"Please build the debugging helpers on the Qt version options page."));
m_modelManager->updateLibraryInfo(plugin.qmldirPath, libraryInfo);
return;
}
QProcess *process = new QProcess(this);
process->setEnvironment(info.qmlDumpEnvironment.toStringList());
connect(process, SIGNAL(finished(int)), SLOT(qmlPluginTypeDumpDone(int)));
connect(process, SIGNAL(error(QProcess::ProcessError)), SLOT(qmlPluginTypeDumpError(QProcess::ProcessError)));
QStringList args;
if (plugin.importUri.isEmpty()) {
args << "--notrelocatable ";
args << QLatin1String("--path");
args << plugin.importPath;
if (ComponentVersion(plugin.importVersion).isValid())
args << plugin.importVersion;
} else {
args << plugin.importUri;
args << plugin.importVersion;
args << plugin.importPath;
}
process->start(info.qmlDumpPath, args);
m_runningQmldumps.insert(process, plugin.qmldirPath);
}
/*!
Returns the result of the merge of \a baseName with \a path, \a suffixes, and \a prefix.
The \a prefix must contain the dot.
\a qmldirPath is the location of the qmldir file.
Adapted from QDeclarativeImportDatabase::resolvePlugin.
*/
QString PluginDumper::resolvePlugin(const QDir &qmldirPath, const QString &qmldirPluginPath,
const QString &baseName, const QStringList &suffixes,
const QString &prefix)
{
QStringList searchPaths;
searchPaths.append(QLatin1String("."));
bool qmldirPluginPathIsRelative = QDir::isRelativePath(qmldirPluginPath);
if (!qmldirPluginPathIsRelative)
searchPaths.prepend(qmldirPluginPath);
foreach (const QString &pluginPath, searchPaths) {
QString resolvedPath;
if (pluginPath == QLatin1String(".")) {
if (qmldirPluginPathIsRelative)
resolvedPath = qmldirPath.absoluteFilePath(qmldirPluginPath);
else
resolvedPath = qmldirPath.absolutePath();
} else {
resolvedPath = pluginPath;
}
QDir dir(resolvedPath);
foreach (const QString &suffix, suffixes) {
QString pluginFileName = prefix;
pluginFileName += baseName;
pluginFileName += suffix;
QFileInfo fileInfo(dir, pluginFileName);
if (fileInfo.exists())
return fileInfo.absoluteFilePath();
}
}
return QString();
}
/*!
Returns the result of the merge of \a baseName with \a dir and the platform suffix.
Adapted from QDeclarativeImportDatabase::resolvePlugin.
\table
\header \i Platform \i Valid suffixes
\row \i Windows \i \c .dll
\row \i Unix/Linux \i \c .so
\row \i AIX \i \c .a
\row \i HP-UX \i \c .sl, \c .so (HP-UXi)
\row \i Mac OS X \i \c .dylib, \c .bundle, \c .so
\row \i Symbian \i \c .dll
\endtable
Version number on unix are ignored.
*/
QString PluginDumper::resolvePlugin(const QDir &qmldirPath, const QString &qmldirPluginPath,
const QString &baseName)
{
#if defined(Q_OS_WIN32) || defined(Q_OS_WINCE)
return resolvePlugin(qmldirPath, qmldirPluginPath, baseName,
QStringList()
<< QLatin1String("d.dll") // try a qmake-style debug build first
<< QLatin1String(".dll"));
#elif defined(Q_OS_DARWIN)
return resolvePlugin(qmldirPath, qmldirPluginPath, baseName,
QStringList()
<< QLatin1String("_debug.dylib") // try a qmake-style debug build first
<< QLatin1String(".dylib")
<< QLatin1String(".so")
<< QLatin1String(".bundle"),
QLatin1String("lib"));
#else // Generic Unix
QStringList validSuffixList;
# if defined(Q_OS_HPUX)
/*
See "HP-UX Linker and Libraries User's Guide", section "Link-time Differences between PA-RISC and IPF":
"In PA-RISC (PA-32 and PA-64) shared libraries are suffixed with .sl. In IPF (32-bit and 64-bit),
the shared libraries are suffixed with .so. For compatibility, the IPF linker also supports the .sl suffix."
*/
validSuffixList << QLatin1String(".sl");
# if defined __ia64
validSuffixList << QLatin1String(".so");
# endif
# elif defined(Q_OS_AIX)
validSuffixList << QLatin1String(".a") << QLatin1String(".so");
# elif defined(Q_OS_UNIX)
validSuffixList << QLatin1String(".so");
# endif
// Examples of valid library names:
// libfoo.so
return resolvePlugin(qmldirPath, qmldirPluginPath, baseName, validSuffixList, QLatin1String("lib"));
#endif
}
bool PluginDumper::Plugin::hasPredumpedQmlTypesFile() const
{
return QFileInfo(predumpedQmlTypesFilePath()).isFile();
}
QString PluginDumper::Plugin::predumpedQmlTypesFilePath() const
{
return QString("%1%2plugins.qmltypes").arg(qmldirPath, QDir::separator());
}
<|endoftext|> |
<commit_before>//
// This file is part of the Marble Virtual Globe.
//
// This program is free software licensed under the GNU LGPL. You can
// find a copy of this license in LICENSE.txt in the top directory of
// the source code.
//
// Copyright 2009 Bastian Holst <bastianholst@gmx.de>
// Copyright 2012 Mohammed Nafees <nafees.technocool@gmail.com>
//
// Self
#include "PhotoPluginItem.h"
// Plugin
#include "CoordinatesParser.h"
#include "PhotoPluginModel.h"
// Marble
#include "AbstractDataPluginItem.h"
#include "GeoDataCoordinates.h"
#include "GeoPainter.h"
#include "LabelGraphicsItem.h"
#include "MarbleGraphicsGridLayout.h"
#include "TinyWebBrowser.h"
#include "ViewportParams.h"
#include "MarbleDebug.h"
#include "MarbleWidget.h"
#include "MarbleModel.h"
#include "RenderPlugin.h"
#include "AbstractInfoDialog.h"
#include "PluginManager.h"
// Qt
#include <QtGui/QAction>
#include <QtGui/QIcon>
#include <QtCore/QFile>
#include <QtCore/QHash>
#include <QtCore/QUrl>
#include <QtGui/QMouseEvent>
#include <QtGui/QPixmap>
using namespace Marble;
PhotoPluginItem::PhotoPluginItem( MarbleWidget *widget, QObject *parent )
: AbstractDataPluginItem( parent ),
m_marbleWidget( widget ),
m_image( this ),
m_browser( 0 )
{
m_action = new QAction( this );
connect( m_action, SIGNAL( triggered() ), this, SLOT( openBrowser() ) );
setCacheMode( MarbleGraphicsItem::ItemCoordinateCache );
m_image.setFrame( FrameGraphicsItem::RectFrame );
MarbleGraphicsGridLayout *layout = new MarbleGraphicsGridLayout( 1, 1 );
layout->addItem( &m_image, 0, 0 );
setLayout( layout );
}
PhotoPluginItem::~PhotoPluginItem()
{
delete m_browser;
}
QString PhotoPluginItem::name() const
{
return title();
}
QString PhotoPluginItem::itemType() const
{
return QString( "photoItem" );
}
bool PhotoPluginItem::initialized()
{
return !m_smallImage.isNull() && coordinate().isValid();
}
void PhotoPluginItem::addDownloadedFile( const QString& url, const QString& type )
{
if( type == "thumbnail" ) {
m_smallImage.load( url );
m_image.setImage( m_smallImage );
}
else if ( type == "info" ) {
QFile file( url );
if( !file.open( QIODevice::ReadOnly | QIODevice::Text ) ) {
return;
}
GeoDataCoordinates coordinates;
CoordinatesParser parser( &coordinates );
if( parser.read( &file ) ) {
setCoordinate( coordinates );
}
}
if ( initialized() ) {
emit updated();
}
}
bool PhotoPluginItem::operator<( const AbstractDataPluginItem *other ) const
{
return this->id() < other->id();
}
QUrl PhotoPluginItem::photoUrl() const
{
QString url = "http://farm%1.static.flickr.com/%2/%3_%4_t.jpg";
return QUrl( url.arg( farm() ).arg( server() ).arg( id() ).arg( secret() ) );
}
QUrl PhotoPluginItem::infoUrl() const
{
QHash<QString,QString> options;
options.insert( "photo_id", id() );
return PhotoPluginModel::generateUrl( "flickr", "flickr.photos.geo.getLocation", options );
}
QString PhotoPluginItem::server() const
{
return m_server;
}
void PhotoPluginItem::setServer( const QString& server )
{
m_server = server;
}
QString PhotoPluginItem::farm() const
{
return m_farm;
}
void PhotoPluginItem::setFarm( const QString& farm )
{
m_farm = farm;
}
QString PhotoPluginItem::secret() const
{
return m_secret;
}
void PhotoPluginItem::setSecret( const QString& secret )
{
m_secret = secret;
}
QString PhotoPluginItem::owner() const
{
return m_owner;
}
void PhotoPluginItem::setOwner( const QString& owner )
{
m_owner = owner;
}
QString PhotoPluginItem::title() const
{
return m_title;
}
void PhotoPluginItem::setTitle( const QString& title )
{
m_title = title;
m_action->setText( title );
}
QAction *PhotoPluginItem::action()
{
if( m_action->icon().isNull() ) {
m_action->setIcon( QIcon( QPixmap::fromImage( m_smallImage ) ) );
}
return m_action;
}
void PhotoPluginItem::openBrowser()
{
if ( m_marbleWidget ) {
QList<RenderPlugin*> plugins = m_marbleWidget->renderPlugins();
foreach( RenderPlugin* renderPlugin, plugins) {
AbstractInfoDialog* infoDialog = dynamic_cast<AbstractInfoDialog*>( renderPlugin );
if ( infoDialog ) {
renderPlugin->setEnabled( true );
renderPlugin->setVisible( true );
Q_ASSERT( renderPlugin->isInitialized() );
if( !renderPlugin->isInitialized() ) {
renderPlugin->initialize();
}
infoDialog->setCoordinates( coordinate(), Qt::AlignRight | Qt::AlignVCenter );
infoDialog->setSize( QSizeF( 400, 450 ) );
infoDialog->setUrl( QUrl( QString( "http://m.flickr.com/photos/%1/%2/" )
.arg( owner() ).arg( id() ) ) );
return;
}
}
mDebug() << "Unable to find a suitable render plugin for creating an info dialog";
}
if( !m_browser ) {
m_browser = new TinyWebBrowser();
}
QString url = "http://www.flickr.com/photos/%1/%2/";
m_browser->load( QUrl( url.arg( owner() ).arg( id() ) ) );
m_browser->show();
}
#include "PhotoPluginItem.moc"
<commit_msg>Remove assert, wrong here<commit_after>//
// This file is part of the Marble Virtual Globe.
//
// This program is free software licensed under the GNU LGPL. You can
// find a copy of this license in LICENSE.txt in the top directory of
// the source code.
//
// Copyright 2009 Bastian Holst <bastianholst@gmx.de>
// Copyright 2012 Mohammed Nafees <nafees.technocool@gmail.com>
//
// Self
#include "PhotoPluginItem.h"
// Plugin
#include "CoordinatesParser.h"
#include "PhotoPluginModel.h"
// Marble
#include "AbstractDataPluginItem.h"
#include "GeoDataCoordinates.h"
#include "GeoPainter.h"
#include "LabelGraphicsItem.h"
#include "MarbleGraphicsGridLayout.h"
#include "TinyWebBrowser.h"
#include "ViewportParams.h"
#include "MarbleDebug.h"
#include "MarbleWidget.h"
#include "MarbleModel.h"
#include "RenderPlugin.h"
#include "AbstractInfoDialog.h"
#include "PluginManager.h"
// Qt
#include <QtGui/QAction>
#include <QtGui/QIcon>
#include <QtCore/QFile>
#include <QtCore/QHash>
#include <QtCore/QUrl>
#include <QtGui/QMouseEvent>
#include <QtGui/QPixmap>
using namespace Marble;
PhotoPluginItem::PhotoPluginItem( MarbleWidget *widget, QObject *parent )
: AbstractDataPluginItem( parent ),
m_marbleWidget( widget ),
m_image( this ),
m_browser( 0 )
{
m_action = new QAction( this );
connect( m_action, SIGNAL( triggered() ), this, SLOT( openBrowser() ) );
setCacheMode( MarbleGraphicsItem::ItemCoordinateCache );
m_image.setFrame( FrameGraphicsItem::RectFrame );
MarbleGraphicsGridLayout *layout = new MarbleGraphicsGridLayout( 1, 1 );
layout->addItem( &m_image, 0, 0 );
setLayout( layout );
}
PhotoPluginItem::~PhotoPluginItem()
{
delete m_browser;
}
QString PhotoPluginItem::name() const
{
return title();
}
QString PhotoPluginItem::itemType() const
{
return QString( "photoItem" );
}
bool PhotoPluginItem::initialized()
{
return !m_smallImage.isNull() && coordinate().isValid();
}
void PhotoPluginItem::addDownloadedFile( const QString& url, const QString& type )
{
if( type == "thumbnail" ) {
m_smallImage.load( url );
m_image.setImage( m_smallImage );
}
else if ( type == "info" ) {
QFile file( url );
if( !file.open( QIODevice::ReadOnly | QIODevice::Text ) ) {
return;
}
GeoDataCoordinates coordinates;
CoordinatesParser parser( &coordinates );
if( parser.read( &file ) ) {
setCoordinate( coordinates );
}
}
if ( initialized() ) {
emit updated();
}
}
bool PhotoPluginItem::operator<( const AbstractDataPluginItem *other ) const
{
return this->id() < other->id();
}
QUrl PhotoPluginItem::photoUrl() const
{
QString url = "http://farm%1.static.flickr.com/%2/%3_%4_t.jpg";
return QUrl( url.arg( farm() ).arg( server() ).arg( id() ).arg( secret() ) );
}
QUrl PhotoPluginItem::infoUrl() const
{
QHash<QString,QString> options;
options.insert( "photo_id", id() );
return PhotoPluginModel::generateUrl( "flickr", "flickr.photos.geo.getLocation", options );
}
QString PhotoPluginItem::server() const
{
return m_server;
}
void PhotoPluginItem::setServer( const QString& server )
{
m_server = server;
}
QString PhotoPluginItem::farm() const
{
return m_farm;
}
void PhotoPluginItem::setFarm( const QString& farm )
{
m_farm = farm;
}
QString PhotoPluginItem::secret() const
{
return m_secret;
}
void PhotoPluginItem::setSecret( const QString& secret )
{
m_secret = secret;
}
QString PhotoPluginItem::owner() const
{
return m_owner;
}
void PhotoPluginItem::setOwner( const QString& owner )
{
m_owner = owner;
}
QString PhotoPluginItem::title() const
{
return m_title;
}
void PhotoPluginItem::setTitle( const QString& title )
{
m_title = title;
m_action->setText( title );
}
QAction *PhotoPluginItem::action()
{
if( m_action->icon().isNull() ) {
m_action->setIcon( QIcon( QPixmap::fromImage( m_smallImage ) ) );
}
return m_action;
}
void PhotoPluginItem::openBrowser()
{
if ( m_marbleWidget ) {
QList<RenderPlugin*> plugins = m_marbleWidget->renderPlugins();
foreach( RenderPlugin* renderPlugin, plugins) {
AbstractInfoDialog* infoDialog = dynamic_cast<AbstractInfoDialog*>( renderPlugin );
if ( infoDialog ) {
renderPlugin->setEnabled( true );
renderPlugin->setVisible( true );
if( !renderPlugin->isInitialized() ) {
renderPlugin->initialize();
}
infoDialog->setCoordinates( coordinate(), Qt::AlignRight | Qt::AlignVCenter );
infoDialog->setSize( QSizeF( 400, 450 ) );
infoDialog->setUrl( QUrl( QString( "http://m.flickr.com/photos/%1/%2/" )
.arg( owner() ).arg( id() ) ) );
return;
}
}
mDebug() << "Unable to find a suitable render plugin for creating an info dialog";
}
if( !m_browser ) {
m_browser = new TinyWebBrowser();
}
QString url = "http://www.flickr.com/photos/%1/%2/";
m_browser->load( QUrl( url.arg( owner() ).arg( id() ) ) );
m_browser->show();
}
#include "PhotoPluginItem.moc"
<|endoftext|> |
<commit_before>//===----------------------------------------------------------------------===//
//
// PelotonDB
//
// nested_loop_join_executor.cpp
//
// Identification: src/backend/executor/nested_loop_join_executor.cpp
//
// Copyright (c) 2015, Carnegie Mellon University Database Group
//
//===----------------------------------------------------------------------===//
#include <vector>
#include "backend/common/types.h"
#include "backend/common/logger.h"
#include "backend/executor/logical_tile_factory.h"
#include "backend/executor/nested_loop_join_executor.h"
#include "backend/expression/abstract_expression.h"
#include "backend/expression/container_tuple.h"
namespace peloton {
namespace executor {
/**
* @brief Constructor for nested loop join executor.
* @param node Nested loop join node corresponding to this executor.
*/
NestedLoopJoinExecutor::NestedLoopJoinExecutor(
planner::AbstractPlan *node, ExecutorContext *executor_context)
: AbstractJoinExecutor(node, executor_context) {}
/**
* @brief Do some basic checks and create the schema for the output logical
* tiles.
* @return true on success, false otherwise.
*/
bool NestedLoopJoinExecutor::DInit() {
auto status = AbstractJoinExecutor::DInit();
if (status == false) {
return status;
}
assert(right_result_tiles_.empty());
right_child_done_ = false;
right_result_itr_ = 0;
assert(left_result_tiles_.empty());
return true;
}
/**
* @brief Creates logical tiles from the two input logical tiles after applying
* join predicate.
* @return true on success, false otherwise.
*/
bool NestedLoopJoinExecutor::DExecute() {
LOG_TRACE("********** Nested Loop Join executor :: 2 children \n");
for(;;){ // Loop until we have non-empty result tile or exit
LogicalTile* left_tile = nullptr;
LogicalTile* right_tile = nullptr;
bool advance_left_child = false;
if(right_child_done_){ // If we have already retrieved all right child's results in buffer
LOG_TRACE("Advance the right buffer iterator.");
assert(!left_result_tiles_.empty());
assert(!right_result_tiles_.empty());
right_result_itr_++;
if(right_result_itr_ >= right_result_tiles_.size()){
advance_left_child = true;
right_result_itr_ = 0;
}
}
else { // Otherwise, we must attempt to execute the right child
if(false == children_[1]->Execute()){
// right child is finished, no more tiles
LOG_TRACE("My right child is exhausted.");
if(right_result_tiles_.empty()){
assert(left_result_tiles_.empty());
LOG_TRACE("Right child returns nothing totally. Exit.");
return false;
}
right_child_done_ = true;
right_result_itr_ = 0;
advance_left_child = true;
}
else { // Buffer the right child's result
LOG_TRACE("Retrieve a new tile from right child");
right_result_tiles_.push_back(children_[1]->GetOutput());
right_result_itr_ = right_result_tiles_.size() - 1;
}
}
if(advance_left_child || left_result_tiles_.empty()){
assert(0 == right_result_itr_);
// Need to advance the left child
if(false == children_[0]->Execute()){
LOG_TRACE("Left child is exhausted. Returning false.");
// Left child exhausted.
// The whole executor is done.
// Release cur left tile. Clear right child's result buffer and return.
assert(right_result_tiles_.size() > 0);
return false;
}
else{
LOG_TRACE("Advance the left child.");
// Insert left child's result to buffer
left_result_tiles_.push_back(children_[0]->GetOutput());
}
}
left_tile = left_result_tiles_.back();
right_tile = right_result_tiles_[right_result_itr_];
// Check the input logical tiles.
assert(left_tile != nullptr);
assert(right_tile != nullptr);
// Construct output logical tile.
std::unique_ptr<LogicalTile> output_tile(LogicalTileFactory::GetTile());
auto left_tile_schema = left_tile->GetSchema();
auto right_tile_schema = right_tile->GetSchema();
for (auto &col : right_tile_schema) {
col.position_list_idx += left_tile->GetPositionLists().size();
}
/* build the schema given the projection */
auto output_tile_schema = BuildSchema(left_tile_schema, right_tile_schema);
// Set the output logical tile schema
output_tile->SetSchema(std::move(output_tile_schema));
// Now, let's compute the position lists for the output tile
// Cartesian product
// Add everything from two logical tiles
auto left_tile_position_lists = left_tile->GetPositionLists();
auto right_tile_position_lists = right_tile->GetPositionLists();
// Compute output tile column count
size_t left_tile_column_count = left_tile_position_lists.size();
size_t right_tile_column_count = right_tile_position_lists.size();
size_t output_tile_column_count =
left_tile_column_count + right_tile_column_count;
assert(left_tile_column_count > 0);
assert(right_tile_column_count > 0);
// Construct position lists for output tile
// TODO: We don't have to copy position lists for each column,
// as there are likely duplications of them.
// But must pay attention to the output schema (see how it is constructed!)
std::vector<std::vector<oid_t>> position_lists;
for (size_t column_itr = 0; column_itr < output_tile_column_count;
column_itr++)
position_lists.push_back(std::vector<oid_t>());
LOG_TRACE("left col count: %lu, right col count: %lu", left_tile_column_count,
right_tile_column_count);
LOG_TRACE("left col count: %lu, right col count: %lu",
left_tile->GetColumnCount(),
right_tile->GetColumnCount());
LOG_TRACE("left row count: %lu, right row count: %lu", left_tile_row_count,
right_tile_row_count);
unsigned int removed = 0;
// Go over every pair of tuples in left and right logical tiles
for(auto left_tile_row_itr : *left_tile){
for(auto right_tile_row_itr : *right_tile){
// TODO: OPTIMIZATION : Can split the control flow into two paths -
// one for cartesian product and one for join
// Then, we can skip this branch atleast for the cartesian product path.
// Join predicate exists
if (predicate_ != nullptr) {
expression::ContainerTuple<executor::LogicalTile> left_tuple(
left_tile, left_tile_row_itr);
expression::ContainerTuple<executor::LogicalTile> right_tuple(
right_tile, right_tile_row_itr);
// Join predicate is false. Skip pair and continue.
if (predicate_->Evaluate(&left_tuple, &right_tuple, executor_context_)
.IsFalse()) {
removed++;
continue;
}
}
// Insert a tuple into the output logical tile
// First, copy the elements in left logical tile's tuple
for (size_t output_tile_column_itr = 0;
output_tile_column_itr < left_tile_column_count;
output_tile_column_itr++) {
position_lists[output_tile_column_itr].push_back(
left_tile_position_lists[output_tile_column_itr]
[left_tile_row_itr]);
}
// Then, copy the elements in right logical tile's tuple
for (size_t output_tile_column_itr = 0;
output_tile_column_itr < right_tile_column_count;
output_tile_column_itr++) {
position_lists[left_tile_column_count + output_tile_column_itr]
.push_back(right_tile_position_lists[output_tile_column_itr]
[right_tile_row_itr]);
}
} // inner loop of NLJ
} // outer loop of NLJ
LOG_INFO("Predicate removed %d rows", removed);
LOG_INFO("Predicate: %s", predicate_->Debug(" ").c_str());
// Check if we have any matching tuples.
if (position_lists[0].size() > 0) {
output_tile->SetPositionListsAndVisibility(std::move(position_lists));
SetOutput(output_tile.release());
return true;
}
LOG_TRACE("This pair produces empty join result. Loop.");
} // End large for-loop
}
NestedLoopJoinExecutor::~NestedLoopJoinExecutor(){
for(auto tile : left_result_tiles_){
delete tile;
left_result_tiles_.clear();
}
for(auto tile : right_result_tiles_){
delete tile;
right_result_tiles_.clear();
}
}
} // namespace executor
} // namespace peloton
<commit_msg>reduce logging, tpcc is working<commit_after>//===----------------------------------------------------------------------===//
//
// PelotonDB
//
// nested_loop_join_executor.cpp
//
// Identification: src/backend/executor/nested_loop_join_executor.cpp
//
// Copyright (c) 2015, Carnegie Mellon University Database Group
//
//===----------------------------------------------------------------------===//
#include <vector>
#include "backend/common/types.h"
#include "backend/common/logger.h"
#include "backend/executor/logical_tile_factory.h"
#include "backend/executor/nested_loop_join_executor.h"
#include "backend/expression/abstract_expression.h"
#include "backend/expression/container_tuple.h"
namespace peloton {
namespace executor {
/**
* @brief Constructor for nested loop join executor.
* @param node Nested loop join node corresponding to this executor.
*/
NestedLoopJoinExecutor::NestedLoopJoinExecutor(
planner::AbstractPlan *node, ExecutorContext *executor_context)
: AbstractJoinExecutor(node, executor_context) {}
/**
* @brief Do some basic checks and create the schema for the output logical
* tiles.
* @return true on success, false otherwise.
*/
bool NestedLoopJoinExecutor::DInit() {
auto status = AbstractJoinExecutor::DInit();
if (status == false) {
return status;
}
assert(right_result_tiles_.empty());
right_child_done_ = false;
right_result_itr_ = 0;
assert(left_result_tiles_.empty());
return true;
}
/**
* @brief Creates logical tiles from the two input logical tiles after applying
* join predicate.
* @return true on success, false otherwise.
*/
bool NestedLoopJoinExecutor::DExecute() {
LOG_TRACE("********** Nested Loop Join executor :: 2 children \n");
for(;;){ // Loop until we have non-empty result tile or exit
LogicalTile* left_tile = nullptr;
LogicalTile* right_tile = nullptr;
bool advance_left_child = false;
if(right_child_done_){ // If we have already retrieved all right child's results in buffer
LOG_TRACE("Advance the right buffer iterator.");
assert(!left_result_tiles_.empty());
assert(!right_result_tiles_.empty());
right_result_itr_++;
if(right_result_itr_ >= right_result_tiles_.size()){
advance_left_child = true;
right_result_itr_ = 0;
}
}
else { // Otherwise, we must attempt to execute the right child
if(false == children_[1]->Execute()){
// right child is finished, no more tiles
LOG_TRACE("My right child is exhausted.");
if(right_result_tiles_.empty()){
assert(left_result_tiles_.empty());
LOG_TRACE("Right child returns nothing totally. Exit.");
return false;
}
right_child_done_ = true;
right_result_itr_ = 0;
advance_left_child = true;
}
else { // Buffer the right child's result
LOG_TRACE("Retrieve a new tile from right child");
right_result_tiles_.push_back(children_[1]->GetOutput());
right_result_itr_ = right_result_tiles_.size() - 1;
}
}
if(advance_left_child || left_result_tiles_.empty()){
assert(0 == right_result_itr_);
// Need to advance the left child
if(false == children_[0]->Execute()){
LOG_TRACE("Left child is exhausted. Returning false.");
// Left child exhausted.
// The whole executor is done.
// Release cur left tile. Clear right child's result buffer and return.
assert(right_result_tiles_.size() > 0);
return false;
}
else{
LOG_TRACE("Advance the left child.");
// Insert left child's result to buffer
left_result_tiles_.push_back(children_[0]->GetOutput());
}
}
left_tile = left_result_tiles_.back();
right_tile = right_result_tiles_[right_result_itr_];
// Check the input logical tiles.
assert(left_tile != nullptr);
assert(right_tile != nullptr);
// Construct output logical tile.
std::unique_ptr<LogicalTile> output_tile(LogicalTileFactory::GetTile());
auto left_tile_schema = left_tile->GetSchema();
auto right_tile_schema = right_tile->GetSchema();
for (auto &col : right_tile_schema) {
col.position_list_idx += left_tile->GetPositionLists().size();
}
/* build the schema given the projection */
auto output_tile_schema = BuildSchema(left_tile_schema, right_tile_schema);
// Set the output logical tile schema
output_tile->SetSchema(std::move(output_tile_schema));
// Now, let's compute the position lists for the output tile
// Cartesian product
// Add everything from two logical tiles
auto left_tile_position_lists = left_tile->GetPositionLists();
auto right_tile_position_lists = right_tile->GetPositionLists();
// Compute output tile column count
size_t left_tile_column_count = left_tile_position_lists.size();
size_t right_tile_column_count = right_tile_position_lists.size();
size_t output_tile_column_count =
left_tile_column_count + right_tile_column_count;
assert(left_tile_column_count > 0);
assert(right_tile_column_count > 0);
// Construct position lists for output tile
// TODO: We don't have to copy position lists for each column,
// as there are likely duplications of them.
// But must pay attention to the output schema (see how it is constructed!)
std::vector<std::vector<oid_t>> position_lists;
for (size_t column_itr = 0; column_itr < output_tile_column_count;
column_itr++)
position_lists.push_back(std::vector<oid_t>());
LOG_TRACE("left col count: %lu, right col count: %lu", left_tile_column_count,
right_tile_column_count);
LOG_TRACE("left col count: %lu, right col count: %lu",
left_tile->GetColumnCount(),
right_tile->GetColumnCount());
LOG_TRACE("left row count: %lu, right row count: %lu", left_tile_row_count,
right_tile_row_count);
unsigned int removed = 0;
// Go over every pair of tuples in left and right logical tiles
for(auto left_tile_row_itr : *left_tile){
for(auto right_tile_row_itr : *right_tile){
// TODO: OPTIMIZATION : Can split the control flow into two paths -
// one for cartesian product and one for join
// Then, we can skip this branch atleast for the cartesian product path.
// Join predicate exists
if (predicate_ != nullptr) {
expression::ContainerTuple<executor::LogicalTile> left_tuple(
left_tile, left_tile_row_itr);
expression::ContainerTuple<executor::LogicalTile> right_tuple(
right_tile, right_tile_row_itr);
// Join predicate is false. Skip pair and continue.
if (predicate_->Evaluate(&left_tuple, &right_tuple, executor_context_)
.IsFalse()) {
removed++;
continue;
}
}
// Insert a tuple into the output logical tile
// First, copy the elements in left logical tile's tuple
for (size_t output_tile_column_itr = 0;
output_tile_column_itr < left_tile_column_count;
output_tile_column_itr++) {
position_lists[output_tile_column_itr].push_back(
left_tile_position_lists[output_tile_column_itr]
[left_tile_row_itr]);
}
// Then, copy the elements in right logical tile's tuple
for (size_t output_tile_column_itr = 0;
output_tile_column_itr < right_tile_column_count;
output_tile_column_itr++) {
position_lists[left_tile_column_count + output_tile_column_itr]
.push_back(right_tile_position_lists[output_tile_column_itr]
[right_tile_row_itr]);
}
} // inner loop of NLJ
} // outer loop of NLJ
LOG_INFO("Predicate removed %d rows", removed);
// Check if we have any matching tuples.
if (position_lists[0].size() > 0) {
output_tile->SetPositionListsAndVisibility(std::move(position_lists));
SetOutput(output_tile.release());
return true;
}
LOG_TRACE("This pair produces empty join result. Loop.");
} // End large for-loop
}
NestedLoopJoinExecutor::~NestedLoopJoinExecutor(){
for(auto tile : left_result_tiles_){
delete tile;
left_result_tiles_.clear();
}
for(auto tile : right_result_tiles_){
delete tile;
right_result_tiles_.clear();
}
}
} // namespace executor
} // namespace peloton
<|endoftext|> |
<commit_before>/*************************************************************************
*
* $RCSfile: ximpbody.cxx,v $
*
* $Revision: 1.19 $
*
* last change: $Author: rt $ $Date: 2004-03-30 16:15:41 $
*
* The Contents of this file are made available subject to the terms of
* either of the following licenses
*
* - GNU Lesser General Public License Version 2.1
* - Sun Industry Standards Source License Version 1.1
*
* Sun Microsystems Inc., October, 2000
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2000 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
*
* Sun Industry Standards Source License Version 1.1
* =================================================
* The contents of this file are subject to the Sun Industry Standards
* Source License Version 1.1 (the "License"); You may not use this file
* except in compliance with the License. You may obtain a copy of the
* License at http://www.openoffice.org/license.html.
*
* Software provided under this License is provided on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
* WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
* MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
* See the License for the specific provisions governing your rights and
* obligations concerning the Software.
*
* The Initial Developer of the Original Code is: Sun Microsystems, Inc.
*
* Copyright: 2000 by Sun Microsystems, Inc.
*
* All Rights Reserved.
*
* Contributor(s): _______________________________________
*
*
************************************************************************/
#pragma hdrstop
#ifndef _XIMPBODY_HXX
#include "ximpbody.hxx"
#endif
#ifndef _XMLOFF_PRSTYLEI_HXX_
#include "prstylei.hxx"
#endif
#ifndef _XIMPNOTES_HXX
#include "ximpnote.hxx"
#endif
#ifndef _COM_SUN_STAR_DRAWING_XDRAWPAGE_HPP_
#include <com/sun/star/drawing/XDrawPage.hpp>
#endif
#ifndef _COM_SUN_STAR_DRAWING_XDRAWPAGES_HPP_
#include <com/sun/star/drawing/XDrawPages.hpp>
#endif
#ifndef _COM_SUN_STAR_CONTAINER_XNAMED_HPP_
#include <com/sun/star/container/XNamed.hpp>
#endif
#ifndef _COM_SUN_STAR_PRESENTATION_XPRESENTATIONPAGE_HPP_
#include <com/sun/star/presentation/XPresentationPage.hpp>
#endif
#ifndef _XIMPSTYLE_HXX
#include "ximpstyl.hxx"
#endif
#ifndef _COM_SUN_STAR_DRAWING_XMASTERPAGETARGET_HPP_
#include <com/sun/star/drawing/XMasterPageTarget.hpp>
#endif
#ifndef _COM_SUN_STAR_BEANS_XPROPERTYSET_HPP_
#include <com/sun/star/beans/XPropertySet.hpp>
#endif
#ifndef _XMLOFF_XMLUCONV_HXX
#include "xmluconv.hxx"
#endif
#ifndef _XMLOFF_PROPERTYSETMAPPER_HXX
#include "xmlprmap.hxx"
#endif
#ifndef _XMLOFF_FAMILIES_HXX_
#include "families.hxx"
#endif
#ifndef _XMLOFF_XIMPSHOW_HXX
#include "ximpshow.hxx"
#endif
#ifndef _XMLOFF_PROPERTYSETMERGER_HXX_
#include "PropertySetMerger.hxx"
#endif
using namespace ::rtl;
using namespace ::com::sun::star;
//////////////////////////////////////////////////////////////////////////////
SdXMLDrawPageContext::SdXMLDrawPageContext( SdXMLImport& rImport,
USHORT nPrfx, const OUString& rLocalName,
const com::sun::star::uno::Reference< com::sun::star::xml::sax::XAttributeList>& xAttrList,
uno::Reference< drawing::XShapes >& rShapes)
: SdXMLGenericPageContext( rImport, nPrfx, rLocalName, xAttrList, rShapes )
{
sal_Int32 nPageId = -1;
sal_Int16 nAttrCount = xAttrList.is() ? xAttrList->getLength() : 0;
for(sal_Int16 i=0; i < nAttrCount; i++)
{
OUString sAttrName = xAttrList->getNameByIndex( i );
OUString aLocalName;
USHORT nPrefix = GetSdImport().GetNamespaceMap().GetKeyByAttrName( sAttrName, &aLocalName );
OUString sValue = xAttrList->getValueByIndex( i );
const SvXMLTokenMap& rAttrTokenMap = GetSdImport().GetDrawPageAttrTokenMap();
switch(rAttrTokenMap.Get(nPrefix, aLocalName))
{
case XML_TOK_DRAWPAGE_NAME:
{
maName = sValue;
break;
}
case XML_TOK_DRAWPAGE_STYLE_NAME:
{
maStyleName = sValue;
break;
}
case XML_TOK_DRAWPAGE_MASTER_PAGE_NAME:
{
maMasterPageName = sValue;
break;
}
case XML_TOK_DRAWPAGE_PAGE_LAYOUT_NAME:
{
maPageLayoutName = sValue;
break;
}
case XML_TOK_DRAWPAGE_ID:
{
sal_Int32 nId;
if( SvXMLUnitConverter::convertNumber( nId, sValue ) )
nPageId = nId;
break;
}
case XML_TOK_DRAWPAGE_HREF:
{
maHREF = sValue;
break;
}
}
}
GetImport().GetShapeImport()->startPage( rShapes );
uno::Reference< drawing::XDrawPage > xDrawPage(rShapes, uno::UNO_QUERY);
// set an id?
if( nPageId != -1 && xDrawPage.is() )
rImport.setDrawPageId( nPageId, xDrawPage );
// set PageName?
if(maName.getLength())
{
if(xDrawPage.is())
{
uno::Reference < container::XNamed > xNamed(xDrawPage, uno::UNO_QUERY);
if(xNamed.is())
xNamed->setName(maName);
}
}
SetStyle( maStyleName );
// set MasterPage?
if(maMasterPageName.getLength())
{
// #85906# Code for setting masterpage needs complete rework
// since GetSdImport().GetMasterStylesContext() gives always ZERO
// because of content/style file split. Now the nechanism is to
// compare the wanted masterpage-name with the existing masterpages
// which were loaded and created in the styles section loading.
uno::Reference< drawing::XDrawPages > xMasterPages(GetSdImport().GetLocalMasterPages(), uno::UNO_QUERY);
uno::Reference < drawing::XMasterPageTarget > xDrawPage(rShapes, uno::UNO_QUERY);
uno::Reference< drawing::XDrawPage > xMasterPage;
if(xDrawPage.is() && xMasterPages.is())
{
sal_Bool bDone(FALSE);
for(sal_Int32 a = 0; !bDone && a < xMasterPages->getCount(); a++)
{
uno::Any aAny(xMasterPages->getByIndex(a));
aAny >>= xMasterPage;
if(xMasterPage.is())
{
uno::Reference < container::XNamed > xMasterNamed(xMasterPage, uno::UNO_QUERY);
if(xMasterNamed.is())
{
OUString sMasterPageName = xMasterNamed->getName();
if(sMasterPageName.getLength() && sMasterPageName.equals(maMasterPageName))
{
xDrawPage->setMasterPage(xMasterPage);
bDone = TRUE;
}
}
}
}
}
}
if( maHREF.getLength() )
{
uno::Reference< beans::XPropertySet > xProps( xDrawPage, uno::UNO_QUERY );
if( xProps.is() )
{
sal_Int32 nIndex = maHREF.lastIndexOf( (sal_Unicode)'#' );
if( nIndex != -1 )
{
OUString aFileName( maHREF.copy( 0, nIndex ) );
OUString aBookmarkName( maHREF.copy( nIndex+1 ) );
maHREF = GetImport().GetAbsoluteReference( aFileName );
maHREF += OUString( (sal_Unicode)'#' );
maHREF += aBookmarkName;
}
xProps->setPropertyValue( OUString( RTL_CONSTASCII_USTRINGPARAM( "BookmarkURL" ) ), uno::makeAny( maHREF ) );
}
}
SetLayout();
DeleteAllShapes();
}
//////////////////////////////////////////////////////////////////////////////
SdXMLDrawPageContext::~SdXMLDrawPageContext()
{
}
//////////////////////////////////////////////////////////////////////////////
SvXMLImportContext *SdXMLDrawPageContext::CreateChildContext( USHORT nPrefix,
const OUString& rLocalName,
const com::sun::star::uno::Reference< com::sun::star::xml::sax::XAttributeList>& xAttrList )
{
SvXMLImportContext *pContext = 0L;
const SvXMLTokenMap& rTokenMap = GetSdImport().GetDrawPageElemTokenMap();
// some special objects inside draw:page context
switch(rTokenMap.Get(nPrefix, rLocalName))
{
case XML_TOK_DRAWPAGE_NOTES:
{
if( GetSdImport().IsImpress() )
{
// get notes page
uno::Reference< presentation::XPresentationPage > xPresPage(GetLocalShapesContext(), uno::UNO_QUERY);
if(xPresPage.is())
{
uno::Reference< drawing::XDrawPage > xNotesDrawPage(xPresPage->getNotesPage(), uno::UNO_QUERY);
if(xNotesDrawPage.is())
{
uno::Reference< drawing::XShapes > xNewShapes(xNotesDrawPage, uno::UNO_QUERY);
if(xNewShapes.is())
{
// presentation:notes inside draw:page context
pContext = new SdXMLNotesContext( GetSdImport(), nPrefix, rLocalName, xAttrList, xNewShapes);
}
}
}
}
}
}
// call parent when no own context was created
if(!pContext)
pContext = SdXMLGenericPageContext::CreateChildContext(nPrefix, rLocalName, xAttrList);
return pContext;
}
void SdXMLDrawPageContext::EndElement()
{
SdXMLGenericPageContext::EndElement();
GetImport().GetShapeImport()->endPage(GetLocalShapesContext());
}
//////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////
SdXMLBodyContext::SdXMLBodyContext( SdXMLImport& rImport,
USHORT nPrfx, const OUString& rLocalName )
: SvXMLImportContext( rImport, nPrfx, rLocalName )
{
}
//////////////////////////////////////////////////////////////////////////////
SdXMLBodyContext::~SdXMLBodyContext()
{
}
//////////////////////////////////////////////////////////////////////////////
SvXMLImportContext *SdXMLBodyContext::CreateChildContext(
USHORT nPrefix,
const OUString& rLocalName,
const uno::Reference< xml::sax::XAttributeList>& xAttrList )
{
SvXMLImportContext *pContext = 0L;
const SvXMLTokenMap& rTokenMap = GetSdImport().GetBodyElemTokenMap();
switch(rTokenMap.Get(nPrefix, rLocalName))
{
case XML_TOK_BODY_PAGE:
{
// only read the first page in preview mode
if( (GetSdImport().GetNewPageCount() == 0) || !GetSdImport().IsPreview() )
{
// import this page
uno::Reference< drawing::XDrawPage > xNewDrawPage;
uno::Reference< drawing::XDrawPages > xDrawPages(GetSdImport().GetLocalDrawPages(), uno::UNO_QUERY);
if(GetSdImport().GetNewPageCount() + 1 > xDrawPages->getCount())
{
// new page, create and insert
xNewDrawPage = xDrawPages->insertNewByIndex(xDrawPages->getCount());
}
else
{
// existing page, use it
uno::Any aAny(xDrawPages->getByIndex(GetSdImport().GetNewPageCount()));
aAny >>= xNewDrawPage;
}
// increment global import page counter
GetSdImport().IncrementNewPageCount();
if(xNewDrawPage.is())
{
uno::Reference< drawing::XShapes > xNewShapes(xNewDrawPage, uno::UNO_QUERY);
if(xNewShapes.is())
{
// draw:page inside office:body context
pContext = new SdXMLDrawPageContext(GetSdImport(), nPrefix, rLocalName, xAttrList,
xNewShapes);
}
}
}
break;
}
case XML_TOK_BODY_SETTINGS:
{
pContext = new SdXMLShowsContext( GetSdImport(), nPrefix, rLocalName, xAttrList );
}
}
// call parent when no own context was created
if(!pContext)
pContext = SvXMLImportContext::CreateChildContext(nPrefix, rLocalName, xAttrList);
return pContext;
}
<commit_msg>INTEGRATION: CWS oasis (1.18.266); FILE MERGED 2004/06/12 19:40:13 mib 1.18.266.2: RESYNC: (1.18-1.19); FILE MERGED 2004/05/07 11:59:54 mib 1.18.266.1: - #i20153#: encode/decode style names (ooo2oasis missing)<commit_after>/*************************************************************************
*
* $RCSfile: ximpbody.cxx,v $
*
* $Revision: 1.20 $
*
* last change: $Author: rt $ $Date: 2004-07-13 08:10:27 $
*
* The Contents of this file are made available subject to the terms of
* either of the following licenses
*
* - GNU Lesser General Public License Version 2.1
* - Sun Industry Standards Source License Version 1.1
*
* Sun Microsystems Inc., October, 2000
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2000 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
*
* Sun Industry Standards Source License Version 1.1
* =================================================
* The contents of this file are subject to the Sun Industry Standards
* Source License Version 1.1 (the "License"); You may not use this file
* except in compliance with the License. You may obtain a copy of the
* License at http://www.openoffice.org/license.html.
*
* Software provided under this License is provided on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
* WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
* MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
* See the License for the specific provisions governing your rights and
* obligations concerning the Software.
*
* The Initial Developer of the Original Code is: Sun Microsystems, Inc.
*
* Copyright: 2000 by Sun Microsystems, Inc.
*
* All Rights Reserved.
*
* Contributor(s): _______________________________________
*
*
************************************************************************/
#pragma hdrstop
#ifndef _XIMPBODY_HXX
#include "ximpbody.hxx"
#endif
#ifndef _XMLOFF_PRSTYLEI_HXX_
#include "prstylei.hxx"
#endif
#ifndef _XIMPNOTES_HXX
#include "ximpnote.hxx"
#endif
#ifndef _COM_SUN_STAR_DRAWING_XDRAWPAGE_HPP_
#include <com/sun/star/drawing/XDrawPage.hpp>
#endif
#ifndef _COM_SUN_STAR_DRAWING_XDRAWPAGES_HPP_
#include <com/sun/star/drawing/XDrawPages.hpp>
#endif
#ifndef _COM_SUN_STAR_CONTAINER_XNAMED_HPP_
#include <com/sun/star/container/XNamed.hpp>
#endif
#ifndef _COM_SUN_STAR_PRESENTATION_XPRESENTATIONPAGE_HPP_
#include <com/sun/star/presentation/XPresentationPage.hpp>
#endif
#ifndef _XIMPSTYLE_HXX
#include "ximpstyl.hxx"
#endif
#ifndef _COM_SUN_STAR_DRAWING_XMASTERPAGETARGET_HPP_
#include <com/sun/star/drawing/XMasterPageTarget.hpp>
#endif
#ifndef _COM_SUN_STAR_BEANS_XPROPERTYSET_HPP_
#include <com/sun/star/beans/XPropertySet.hpp>
#endif
#ifndef _XMLOFF_XMLUCONV_HXX
#include "xmluconv.hxx"
#endif
#ifndef _XMLOFF_PROPERTYSETMAPPER_HXX
#include "xmlprmap.hxx"
#endif
#ifndef _XMLOFF_FAMILIES_HXX_
#include "families.hxx"
#endif
#ifndef _XMLOFF_XIMPSHOW_HXX
#include "ximpshow.hxx"
#endif
#ifndef _XMLOFF_PROPERTYSETMERGER_HXX_
#include "PropertySetMerger.hxx"
#endif
using namespace ::rtl;
using namespace ::com::sun::star;
//////////////////////////////////////////////////////////////////////////////
SdXMLDrawPageContext::SdXMLDrawPageContext( SdXMLImport& rImport,
USHORT nPrfx, const OUString& rLocalName,
const com::sun::star::uno::Reference< com::sun::star::xml::sax::XAttributeList>& xAttrList,
uno::Reference< drawing::XShapes >& rShapes)
: SdXMLGenericPageContext( rImport, nPrfx, rLocalName, xAttrList, rShapes )
{
sal_Int32 nPageId = -1;
sal_Int16 nAttrCount = xAttrList.is() ? xAttrList->getLength() : 0;
for(sal_Int16 i=0; i < nAttrCount; i++)
{
OUString sAttrName = xAttrList->getNameByIndex( i );
OUString aLocalName;
USHORT nPrefix = GetSdImport().GetNamespaceMap().GetKeyByAttrName( sAttrName, &aLocalName );
OUString sValue = xAttrList->getValueByIndex( i );
const SvXMLTokenMap& rAttrTokenMap = GetSdImport().GetDrawPageAttrTokenMap();
switch(rAttrTokenMap.Get(nPrefix, aLocalName))
{
case XML_TOK_DRAWPAGE_NAME:
{
maName = sValue;
break;
}
case XML_TOK_DRAWPAGE_STYLE_NAME:
{
maStyleName = sValue;
break;
}
case XML_TOK_DRAWPAGE_MASTER_PAGE_NAME:
{
maMasterPageName = sValue;
break;
}
case XML_TOK_DRAWPAGE_PAGE_LAYOUT_NAME:
{
maPageLayoutName = sValue;
break;
}
case XML_TOK_DRAWPAGE_ID:
{
sal_Int32 nId;
if( SvXMLUnitConverter::convertNumber( nId, sValue ) )
nPageId = nId;
break;
}
case XML_TOK_DRAWPAGE_HREF:
{
maHREF = sValue;
break;
}
}
}
GetImport().GetShapeImport()->startPage( rShapes );
uno::Reference< drawing::XDrawPage > xDrawPage(rShapes, uno::UNO_QUERY);
// set an id?
if( nPageId != -1 && xDrawPage.is() )
rImport.setDrawPageId( nPageId, xDrawPage );
// set PageName?
if(maName.getLength())
{
if(xDrawPage.is())
{
uno::Reference < container::XNamed > xNamed(xDrawPage, uno::UNO_QUERY);
if(xNamed.is())
xNamed->setName(maName);
}
}
SetStyle( maStyleName );
// set MasterPage?
if(maMasterPageName.getLength())
{
// #85906# Code for setting masterpage needs complete rework
// since GetSdImport().GetMasterStylesContext() gives always ZERO
// because of content/style file split. Now the nechanism is to
// compare the wanted masterpage-name with the existing masterpages
// which were loaded and created in the styles section loading.
uno::Reference< drawing::XDrawPages > xMasterPages(GetSdImport().GetLocalMasterPages(), uno::UNO_QUERY);
uno::Reference < drawing::XMasterPageTarget > xDrawPage(rShapes, uno::UNO_QUERY);
uno::Reference< drawing::XDrawPage > xMasterPage;
if(xDrawPage.is() && xMasterPages.is())
{
sal_Bool bDone(FALSE);
OUString sDisplayName( rImport.GetStyleDisplayName(
XML_STYLE_FAMILY_MASTER_PAGE, maMasterPageName ) );
for(sal_Int32 a = 0; !bDone && a < xMasterPages->getCount(); a++)
{
uno::Any aAny(xMasterPages->getByIndex(a));
aAny >>= xMasterPage;
if(xMasterPage.is())
{
uno::Reference < container::XNamed > xMasterNamed(xMasterPage, uno::UNO_QUERY);
if(xMasterNamed.is())
{
OUString sMasterPageName = xMasterNamed->getName();
if(sMasterPageName.getLength() &&
sMasterPageName.equals(sDisplayName))
{
xDrawPage->setMasterPage(xMasterPage);
bDone = TRUE;
}
}
}
}
}
}
if( maHREF.getLength() )
{
uno::Reference< beans::XPropertySet > xProps( xDrawPage, uno::UNO_QUERY );
if( xProps.is() )
{
sal_Int32 nIndex = maHREF.lastIndexOf( (sal_Unicode)'#' );
if( nIndex != -1 )
{
OUString aFileName( maHREF.copy( 0, nIndex ) );
OUString aBookmarkName( maHREF.copy( nIndex+1 ) );
maHREF = GetImport().GetAbsoluteReference( aFileName );
maHREF += OUString( (sal_Unicode)'#' );
maHREF += aBookmarkName;
}
xProps->setPropertyValue( OUString( RTL_CONSTASCII_USTRINGPARAM( "BookmarkURL" ) ), uno::makeAny( maHREF ) );
}
}
SetLayout();
DeleteAllShapes();
}
//////////////////////////////////////////////////////////////////////////////
SdXMLDrawPageContext::~SdXMLDrawPageContext()
{
}
//////////////////////////////////////////////////////////////////////////////
SvXMLImportContext *SdXMLDrawPageContext::CreateChildContext( USHORT nPrefix,
const OUString& rLocalName,
const com::sun::star::uno::Reference< com::sun::star::xml::sax::XAttributeList>& xAttrList )
{
SvXMLImportContext *pContext = 0L;
const SvXMLTokenMap& rTokenMap = GetSdImport().GetDrawPageElemTokenMap();
// some special objects inside draw:page context
switch(rTokenMap.Get(nPrefix, rLocalName))
{
case XML_TOK_DRAWPAGE_NOTES:
{
if( GetSdImport().IsImpress() )
{
// get notes page
uno::Reference< presentation::XPresentationPage > xPresPage(GetLocalShapesContext(), uno::UNO_QUERY);
if(xPresPage.is())
{
uno::Reference< drawing::XDrawPage > xNotesDrawPage(xPresPage->getNotesPage(), uno::UNO_QUERY);
if(xNotesDrawPage.is())
{
uno::Reference< drawing::XShapes > xNewShapes(xNotesDrawPage, uno::UNO_QUERY);
if(xNewShapes.is())
{
// presentation:notes inside draw:page context
pContext = new SdXMLNotesContext( GetSdImport(), nPrefix, rLocalName, xAttrList, xNewShapes);
}
}
}
}
}
}
// call parent when no own context was created
if(!pContext)
pContext = SdXMLGenericPageContext::CreateChildContext(nPrefix, rLocalName, xAttrList);
return pContext;
}
void SdXMLDrawPageContext::EndElement()
{
SdXMLGenericPageContext::EndElement();
GetImport().GetShapeImport()->endPage(GetLocalShapesContext());
}
//////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////
SdXMLBodyContext::SdXMLBodyContext( SdXMLImport& rImport,
USHORT nPrfx, const OUString& rLocalName )
: SvXMLImportContext( rImport, nPrfx, rLocalName )
{
}
//////////////////////////////////////////////////////////////////////////////
SdXMLBodyContext::~SdXMLBodyContext()
{
}
//////////////////////////////////////////////////////////////////////////////
SvXMLImportContext *SdXMLBodyContext::CreateChildContext(
USHORT nPrefix,
const OUString& rLocalName,
const uno::Reference< xml::sax::XAttributeList>& xAttrList )
{
SvXMLImportContext *pContext = 0L;
const SvXMLTokenMap& rTokenMap = GetSdImport().GetBodyElemTokenMap();
switch(rTokenMap.Get(nPrefix, rLocalName))
{
case XML_TOK_BODY_PAGE:
{
// only read the first page in preview mode
if( (GetSdImport().GetNewPageCount() == 0) || !GetSdImport().IsPreview() )
{
// import this page
uno::Reference< drawing::XDrawPage > xNewDrawPage;
uno::Reference< drawing::XDrawPages > xDrawPages(GetSdImport().GetLocalDrawPages(), uno::UNO_QUERY);
if(GetSdImport().GetNewPageCount() + 1 > xDrawPages->getCount())
{
// new page, create and insert
xNewDrawPage = xDrawPages->insertNewByIndex(xDrawPages->getCount());
}
else
{
// existing page, use it
uno::Any aAny(xDrawPages->getByIndex(GetSdImport().GetNewPageCount()));
aAny >>= xNewDrawPage;
}
// increment global import page counter
GetSdImport().IncrementNewPageCount();
if(xNewDrawPage.is())
{
uno::Reference< drawing::XShapes > xNewShapes(xNewDrawPage, uno::UNO_QUERY);
if(xNewShapes.is())
{
// draw:page inside office:body context
pContext = new SdXMLDrawPageContext(GetSdImport(), nPrefix, rLocalName, xAttrList,
xNewShapes);
}
}
}
break;
}
case XML_TOK_BODY_SETTINGS:
{
pContext = new SdXMLShowsContext( GetSdImport(), nPrefix, rLocalName, xAttrList );
}
}
// call parent when no own context was created
if(!pContext)
pContext = SvXMLImportContext::CreateChildContext(nPrefix, rLocalName, xAttrList);
return pContext;
}
<|endoftext|> |
<commit_before>/*
* Copyright (C) 2016 Google, 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.
*/
#include <string>
#include <vector>
#include "Smoke.h"
namespace {
Game *create_game(const std::vector<std::string> &args)
{
return new Smoke(args);
}
Game *create_game(int argc, char **argv)
{
std::vector<std::string> args(argv, argv + argc);
return new Smoke(args);
}
} // namespace
#if defined(VK_USE_PLATFORM_XCB_KHR)
#include "ShellXcb.h"
int main(int argc, char **argv)
{
Game *game = create_game(argc, argv);
{
ShellXcb shell(*game);
shell.run();
}
delete game;
return 0;
}
#elif defined(VK_USE_PLATFORM_WAYLAND_KHR)
#include "ShellWayland.h"
int main(int argc, char **argv) {
Game *game = create_game(argc, argv);
{
ShellWayland shell(*game);
shell.run();
}
delete game;
return 0;
}
#elif defined(VK_USE_PLATFORM_ANDROID_KHR)
#include <android/log.h>
#include "ShellAndroid.h"
void android_main(android_app *app)
{
Game *game = create_game(ShellAndroid::get_args(*app));
try {
ShellAndroid shell(*app, *game);
shell.run();
} catch (const std::runtime_error &e) {
__android_log_print(ANDROID_LOG_ERROR, game->settings().name.c_str(),
"%s", e.what());
}
delete game;
}
#elif defined(VK_USE_PLATFORM_WIN32_KHR)
#include "ShellWin32.h"
int main(int argc, char **argv)
{
Game *game = create_game(argc, argv);
{
ShellWin32 shell(*game);
shell.run();
}
delete game;
return 0;
}
#endif // VK_USE_PLATFORM_XCB_KHR
<commit_msg>demos: Fix compile warning in smoke<commit_after>/*
* Copyright (C) 2016 Google, 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.
*/
#include <string>
#include <vector>
#include "Smoke.h"
namespace {
#if defined(VK_USE_PLATFORM_ANDROID_KHR)
Game *create_game(const std::vector<std::string> &args)
{
return new Smoke(args);
}
#endif
Game *create_game(int argc, char **argv)
{
std::vector<std::string> args(argv, argv + argc);
return new Smoke(args);
}
} // namespace
#if defined(VK_USE_PLATFORM_XCB_KHR)
#include "ShellXcb.h"
int main(int argc, char **argv)
{
Game *game = create_game(argc, argv);
{
ShellXcb shell(*game);
shell.run();
}
delete game;
return 0;
}
#elif defined(VK_USE_PLATFORM_WAYLAND_KHR)
#include "ShellWayland.h"
int main(int argc, char **argv) {
Game *game = create_game(argc, argv);
{
ShellWayland shell(*game);
shell.run();
}
delete game;
return 0;
}
#elif defined(VK_USE_PLATFORM_ANDROID_KHR)
#include <android/log.h>
#include "ShellAndroid.h"
void android_main(android_app *app)
{
Game *game = create_game(ShellAndroid::get_args(*app));
try {
ShellAndroid shell(*app, *game);
shell.run();
} catch (const std::runtime_error &e) {
__android_log_print(ANDROID_LOG_ERROR, game->settings().name.c_str(),
"%s", e.what());
}
delete game;
}
#elif defined(VK_USE_PLATFORM_WIN32_KHR)
#include "ShellWin32.h"
int main(int argc, char **argv)
{
Game *game = create_game(argc, argv);
{
ShellWin32 shell(*game);
shell.run();
}
delete game;
return 0;
}
#endif // VK_USE_PLATFORM_XCB_KHR
<|endoftext|> |
<commit_before> { 0, { uint256S("0xc866fdd44f0451466f20789210e1d53585ae94959f30d82ed2d6f02abab7711f"), 1593524096 } },
{ 5000, { uint256S("0x6c31b8f5dda18e625ade3f90c1769007668c342b8688d36836de2f96b837dc24"), 1597886084 } },
{ 10000, { uint256S("0xc1473eb25b2e45f7893b744c188da78c66f6feafd33cbfd5ed0e08355dae53d0"), 1599199015 } },
{ 15000, { uint256S("0xa931da9fe13914233e14c5d224019c831ae46751be719dc2fb869e7bc1c5a183"), 1600518207 } },
{ 20000, { uint256S("0x0fcbe7188c6fce24d586e562ba4800c2a989076ce1754d0728894fdd6f580c9b"), 1601833980 } },
{ 25000, { uint256S("0xd06ac7a8fbfc60a7db9fae000be733e80b0d3ae478897e2e8f7084aacf69e16b"), 1603149147 } },
{ 30000, { uint256S("0xf0361c189b1a76d72b62b6ed39203df2d5b702aa07944925153dac41a038a188"), 1604465211 } },
{ 30747, { uint256S("0x510169c13b7b1bcafc85a1e0882aea590163076b7588913c022860fa67182812"), 1604661587 } },
{ 31899, { uint256S("0x938211b632222b4127fcd60ef774805a30fcaea0548f07cd3ef55003fbb037eb"), 1604964758 } },
<commit_msg>MAINT: Update checkpoints<commit_after> { 0, { uint256S("0xc866fdd44f0451466f20789210e1d53585ae94959f30d82ed2d6f02abab7711f"), 1593524096 } },
{ 5000, { uint256S("0x6c31b8f5dda18e625ade3f90c1769007668c342b8688d36836de2f96b837dc24"), 1597886084 } },
{ 10000, { uint256S("0xc1473eb25b2e45f7893b744c188da78c66f6feafd33cbfd5ed0e08355dae53d0"), 1599199015 } },
{ 15000, { uint256S("0xa931da9fe13914233e14c5d224019c831ae46751be719dc2fb869e7bc1c5a183"), 1600518207 } },
{ 20000, { uint256S("0x0fcbe7188c6fce24d586e562ba4800c2a989076ce1754d0728894fdd6f580c9b"), 1601833980 } },
{ 25000, { uint256S("0xd06ac7a8fbfc60a7db9fae000be733e80b0d3ae478897e2e8f7084aacf69e16b"), 1603149147 } },
{ 30000, { uint256S("0xf0361c189b1a76d72b62b6ed39203df2d5b702aa07944925153dac41a038a188"), 1604465211 } },
{ 35000, { uint256S("0x38c013228c20b33b9732f8a182127a5d9352513449af898eeca43653b2e329c9"), 1605790096 } },
{ 40000, { uint256S("0xfd8606d5502feca3aeb92882f3835b41f93dc96d28e0166d61b7804cea1a563a"), 1607112798 } },
{ 45000, { uint256S("0xcad518f22cf8db822f72e217021881abbeeb15d1494f916c482943a632bd2604"), 1608450748 } },
{ 47336, { uint256S("0x552d1f7a3888d845b66ddb3493883461c2e27e4ad9dce3cd4d6dfc3d5dd9b6ca"), 1609065174 } },
{ 48488, { uint256S("0xceaf5e88faf0a892a8051876f6fd19a0501b0f2e8e16f37c2ce72aecef23152a"), 1609369594 } },
<|endoftext|> |
<commit_before>/*
* Copyright © 2012, United States Government, as represented by the
* Administrator of the National Aeronautics and Space Administration.
* All rights reserved.
*
* The NASA Tensegrity Robotics Toolkit (NTRT) v1 platform is licensed
* under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0.
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
* either express or implied. See the License for the specific language
* governing permissions and limitations under the License.
*/
/**
* @file AppGoalTensionNNW.cpp
* @brief Contains the definition of functions for multi-terrain app
* @author Brian Mirletz, Alexander Xydes
* @copyright Copyright (C) 2014 NASA Ames Research Center
* $Id$
*/
#include "AppGoalTensionNNW.h"
#include "helpers/FileHelpers.h"
#include "tgcreator/tgUtil.h"
#include "dev/btietz/JSONTests/tgCPGJSONLogger.h"
#include <json/json.h>
AppGoalTensionNNW::AppGoalTensionNNW(int argc, char** argv)
{
bSetup = false;
use_graphics = false;
add_controller = true;
add_blocks = false;
add_hills = false;
all_terrain = false;
timestep_physics = 1.0f/1000.0f;
timestep_graphics = 1.0f/60.0f;
nEpisodes = 1;
nSteps = 60000;
nSegments = 6;
nTypes = 3;
startX = 0;
startY = 20;
startZ = 0;
startAngle = 0;
goalAngle = 0;
suffix = "default";
handleOptions(argc, argv);
tgUtil::seedRandom();
}
bool AppGoalTensionNNW::setup()
{
// First create the world
world = createWorld();
// Second create the view
if (use_graphics)
view = createGraphicsView(world); // For visual experimenting on one tensegrity
else
view = createView(world); // For running multiple episodes
// Third create the simulation
simulation = new tgSimulation(*view);
// Fourth create the models with their controllers and add the models to the
// simulation
#if (0)
startAngle = ((rand() / (double)RAND_MAX) - 0.5) * 3.1415;
#endif
FlemonsSpineModelGoal* myModel =
new FlemonsSpineModelGoal(nSegments, goalAngle, startAngle);
// Fifth create the controllers, attach to model
if (add_controller)
{
Json::Value root; // will contains the root value after parsing.
Json::Reader reader;
std::string resourcePath = "bmirletz/TC_nn_Tension_new/";
std::string controlFilePath = FileHelpers::getResourcePath(resourcePath);
std::string controlFilename = controlFilePath + suffix;
bool parsingSuccessful = reader.parse( FileHelpers::getFileString(controlFilename.c_str()), root );
if ( !parsingSuccessful )
{
// report to the user the failure and their locations in the document.
std::cout << "Failed to parse configuration\n"
<< reader.getFormattedErrorMessages();
throw std::invalid_argument("Bad filename for JSON, check that resource path exists");
}
// Get the value of the member of root named 'encoding', return 'UTF-8' if there is no
// such member.
Json::Value impedenceVals = root.get("impedenceVals", "UTF-8");
impedenceVals = impedenceVals.get("params", "UTF-8");
// Keep drilling if necessary
if (impedenceVals[0].isArray())
{
impedenceVals = impedenceVals[0];
}
const double impedanceMax = 2000.0;
const int segmentSpan = 3;
const int numMuscles = 8;
const int numParams = 2;
const int segNumber = 5; // For learning results
const double controlTime = .01;
const double lowPhase = -1 * M_PI;
const double highPhase = M_PI;
const double lowAmplitude = 0.0;
const double highAmplitude = 300.0;
// JSONCPP's .get really wants this to be typed...
int j = 0;
const double kt = impedanceMax * (impedenceVals.get(j, 0.0)).asDouble();
const double kp = impedanceMax * (impedenceVals.get(1, 0.0)).asDouble();
const double kv = impedanceMax * (impedenceVals.get(2, 0.0)).asDouble();
const bool def = true;
// Overridden by def being true
const double cl = 10.0;
const double lf = 0.0;
const double hf = 30.0;
// Feedback parameters
const double ffMin = -0.5;
const double ffMax = 10.0;
const double afMin = 0.0;
const double afMax = 200.0;
const double pfMin = -0.5;
const double pfMax = 6.28;
const double tensionFeedback = impedanceMax *(impedenceVals.get(3, 0.0)).asDouble();
JSONGoalControl::Config control_config(segmentSpan,
numMuscles,
numMuscles,
numParams,
segNumber,
controlTime,
lowAmplitude,
highAmplitude,
lowPhase,
highPhase,
kt,
kp,
kv,
def,
cl,
lf,
hf,
ffMin,
ffMax,
afMin,
afMax,
pfMin,
pfMax,
tensionFeedback
);
/// @todo fix memory leak that occurs here
JSONGoalTensionNNW* const myControl =
new JSONGoalTensionNNW(control_config, suffix, resourcePath);
#if (1)
tgCPGJSONLogger* const myLogger =
new tgCPGJSONLogger("logs/CPGValues.txt");
myControl->attach(myLogger);
#endif
myModel->attach(myControl);
}
// Sixth add model & controller to simulation
simulation->addModel(myModel);
if (add_blocks)
{
tgModel* blockField = getBlocks();
simulation->addObstacle(blockField);
}
bSetup = true;
return bSetup;
}
void AppGoalTensionNNW::handleOptions(int argc, char **argv)
{
// Declare the supported options.
po::options_description desc("Allowed options");
desc.add_options()
("help,h", "produce help message")
("graphics,G", po::value<bool>(&use_graphics), "Test using graphical view")
("controller,c", po::value<bool>(&add_controller), "Attach the controller to the model.")
("blocks,b", po::value<bool>(&add_blocks)->implicit_value(false), "Add a block field as obstacles.")
("hills,H", po::value<bool>(&add_hills)->implicit_value(false), "Use hilly terrain.")
("all_terrain,A", po::value<bool>(&all_terrain)->implicit_value(false), "Alternate through terrain types. Only works with graphics off")
("phys_time,p", po::value<double>(), "Physics timestep value (Hz). Default=1000")
("graph_time,g", po::value<double>(), "Graphics timestep value a.k.a. render rate (Hz). Default = 60")
("episodes,e", po::value<int>(&nEpisodes), "Number of episodes to run. Default=1")
("steps,s", po::value<int>(&nSteps), "Number of steps per episode to run. Default=60K (60 seconds)")
("segments,S", po::value<int>(&nSegments), "Number of segments in the tensegrity spine. Default=6")
("start_x,x", po::value<double>(&startX), "X Coordinate of starting position for robot. Default = 0")
("start_y,y", po::value<double>(&startY), "Y Coordinate of starting position for robot. Default = 20")
("start_z,z", po::value<double>(&startZ), "Z Coordinate of starting position for robot. Default = 0")
("angle,a", po::value<double>(&startAngle), "Angle of starting rotation for robot. Degrees. Default = 0")
("goal_angle,B", po::value<double>(&goalAngle), "Angle of starting rotation for goal box. Degrees. Default = 0")
("learning_controller,l", po::value<std::string>(&suffix), "Which learned controller to write to or use. Default = default")
;
po::variables_map vm;
po::store(po::parse_command_line(argc, argv, desc), vm);
if (vm.count("help"))
{
std::cout << desc << "\n";
exit(0);
}
po::notify(vm);
if (vm.count("phys_time"))
{
timestep_physics = 1/vm["phys_time"].as<double>();
std::cout << "Physics timestep set to: " << timestep_physics << " seconds.\n";
}
if (vm.count("graph_time"))
{
timestep_graphics = 1/vm["graph_time"].as<double>();
std::cout << "Graphics timestep set to: " << timestep_graphics << " seconds.\n";
}
}
const tgHillyGround::Config AppGoalTensionNNW::getHillyConfig()
{
btVector3 eulerAngles = btVector3(0.0, 0.0, 0.0);
btScalar friction = 0.5;
btScalar restitution = 0.0;
// Size doesn't affect hilly terrain
btVector3 size = btVector3(0.0, 0.1, 0.0);
btVector3 origin = btVector3(0.0, 0.0, 0.0);
size_t nx = 240;
size_t ny = 240;
double margin = 0.5;
double triangleSize = 4.0;
double waveHeight = 2.0;
double offset = 0.0;
const tgHillyGround::Config hillGroundConfig(eulerAngles, friction, restitution,
size, origin, nx, ny, margin, triangleSize,
waveHeight, offset);
return hillGroundConfig;
}
const tgBoxGround::Config AppGoalTensionNNW::getBoxConfig()
{
const double yaw = 0.0;
const double pitch = 0.0;
const double roll = 0.0;
const double friction = 0.5;
const double restitution = 0.0;
const btVector3 size(1000.0, 1.5, 1000.0);
const tgBoxGround::Config groundConfig(btVector3(yaw, pitch, roll),
friction,
restitution,
size );
return groundConfig;
}
tgModel* AppGoalTensionNNW::getBlocks()
{
// Room to add a config
tgBlockField* myObstacle = new tgBlockField();
return myObstacle;
}
tgWorld* AppGoalTensionNNW::createWorld()
{
const tgWorld::Config config(
981 // gravity, cm/sec^2
);
tgBulletGround* ground;
if (add_hills)
{
const tgHillyGround::Config hillGroundConfig = getHillyConfig();
ground = new tgHillyGround(hillGroundConfig);
}
else
{
const tgBoxGround::Config groundConfig = getBoxConfig();
ground = new tgBoxGround(groundConfig);
}
return new tgWorld(config, ground);
}
tgSimViewGraphics *AppGoalTensionNNW::createGraphicsView(tgWorld *world)
{
return new tgSimViewGraphics(*world, timestep_physics, timestep_graphics);
}
tgSimView *AppGoalTensionNNW::createView(tgWorld *world)
{
return new tgSimView(*world, timestep_physics, timestep_graphics);
}
bool AppGoalTensionNNW::run()
{
if (!bSetup)
{
setup();
}
if (use_graphics)
{
// Run until the user stops
simulation->run();
}
else
{
// or run for a specific number of steps
simulate(simulation);
}
///@todo consider app.cleanup()
delete simulation;
delete view;
delete world;
return true;
}
void AppGoalTensionNNW::simulate(tgSimulation *simulation)
{
for (int i=0; i<nEpisodes; i++) {
fprintf(stderr,"Episode %d\n", i);
try
{
simulation->run(nSteps);
}
catch (std::runtime_error e)
{
// Nothing to do here, score will be set to -1
}
// Don't change the terrain before the last episode to avoid leaks
if (i != nEpisodes - 1)
{
if (all_terrain)
{
// Next run has Hills
if (i % nTypes == 0)
{
const tgHillyGround::Config hillGroundConfig = getHillyConfig();
tgBulletGround* ground = new tgHillyGround(hillGroundConfig);
simulation->reset(ground);
}
// Flat
else if (i % nTypes == 1)
{
const tgBoxGround::Config groundConfig = getBoxConfig();
tgBulletGround* ground = new tgBoxGround(groundConfig);
simulation->reset(ground);
}
// Flat with blocks
else if (i % nTypes == 2)
{
simulation->reset();
tgModel* obstacle = getBlocks();
simulation->addObstacle(obstacle);
}
}
else if(add_blocks)
{
simulation->reset();
tgModel* obstacle = getBlocks();
simulation->addObstacle(obstacle);
}
// Avoid resetting twice on the last run
else
{
simulation->reset();
}
}
}
}
/**
* The entry point.
* @param[in] argc the number of command-line arguments
* @param[in] argv argv[0] is the executable name
* @return 0
*/
int main(int argc, char** argv)
{
std::cout << "AppGoalTensionNNW" << std::endl;
AppGoalTensionNNW app (argc, argv);
if (app.setup())
app.run();
//Teardown is handled by delete, so that should be automatic
return 0;
}
<commit_msg>Revert file path<commit_after>/*
* Copyright © 2012, United States Government, as represented by the
* Administrator of the National Aeronautics and Space Administration.
* All rights reserved.
*
* The NASA Tensegrity Robotics Toolkit (NTRT) v1 platform is licensed
* under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0.
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
* either express or implied. See the License for the specific language
* governing permissions and limitations under the License.
*/
/**
* @file AppGoalTensionNNW.cpp
* @brief Contains the definition of functions for multi-terrain app
* @author Brian Mirletz, Alexander Xydes
* @copyright Copyright (C) 2014 NASA Ames Research Center
* $Id$
*/
#include "AppGoalTensionNNW.h"
#include "helpers/FileHelpers.h"
#include "tgcreator/tgUtil.h"
#include "dev/btietz/JSONTests/tgCPGJSONLogger.h"
#include <json/json.h>
AppGoalTensionNNW::AppGoalTensionNNW(int argc, char** argv)
{
bSetup = false;
use_graphics = false;
add_controller = true;
add_blocks = false;
add_hills = false;
all_terrain = false;
timestep_physics = 1.0f/1000.0f;
timestep_graphics = 1.0f/60.0f;
nEpisodes = 1;
nSteps = 60000;
nSegments = 6;
nTypes = 3;
startX = 0;
startY = 20;
startZ = 0;
startAngle = 0;
goalAngle = 0;
suffix = "default";
handleOptions(argc, argv);
tgUtil::seedRandom();
}
bool AppGoalTensionNNW::setup()
{
// First create the world
world = createWorld();
// Second create the view
if (use_graphics)
view = createGraphicsView(world); // For visual experimenting on one tensegrity
else
view = createView(world); // For running multiple episodes
// Third create the simulation
simulation = new tgSimulation(*view);
// Fourth create the models with their controllers and add the models to the
// simulation
#if (0)
startAngle = ((rand() / (double)RAND_MAX) - 0.5) * 3.1415;
#endif
FlemonsSpineModelGoal* myModel =
new FlemonsSpineModelGoal(nSegments, goalAngle, startAngle);
// Fifth create the controllers, attach to model
if (add_controller)
{
Json::Value root; // will contains the root value after parsing.
Json::Reader reader;
std::string resourcePath = "bmirletz/TC_nn_Tension/";
std::string controlFilePath = FileHelpers::getResourcePath(resourcePath);
std::string controlFilename = controlFilePath + suffix;
bool parsingSuccessful = reader.parse( FileHelpers::getFileString(controlFilename.c_str()), root );
if ( !parsingSuccessful )
{
// report to the user the failure and their locations in the document.
std::cout << "Failed to parse configuration\n"
<< reader.getFormattedErrorMessages();
throw std::invalid_argument("Bad filename for JSON, check that resource path exists");
}
// Get the value of the member of root named 'encoding', return 'UTF-8' if there is no
// such member.
Json::Value impedenceVals = root.get("impedenceVals", "UTF-8");
impedenceVals = impedenceVals.get("params", "UTF-8");
// Keep drilling if necessary
if (impedenceVals[0].isArray())
{
impedenceVals = impedenceVals[0];
}
const double impedanceMax = 2000.0;
const int segmentSpan = 3;
const int numMuscles = 8;
const int numParams = 2;
const int segNumber = 5; // For learning results
const double controlTime = .01;
const double lowPhase = -1 * M_PI;
const double highPhase = M_PI;
const double lowAmplitude = 0.0;
const double highAmplitude = 300.0;
// JSONCPP's .get really wants this to be typed...
int j = 0;
const double kt = impedanceMax * (impedenceVals.get(j, 0.0)).asDouble();
const double kp = impedanceMax * (impedenceVals.get(1, 0.0)).asDouble();
const double kv = impedanceMax * (impedenceVals.get(2, 0.0)).asDouble();
const bool def = true;
// Overridden by def being true
const double cl = 10.0;
const double lf = 0.0;
const double hf = 30.0;
// Feedback parameters
const double ffMin = -0.5;
const double ffMax = 10.0;
const double afMin = 0.0;
const double afMax = 200.0;
const double pfMin = -0.5;
const double pfMax = 6.28;
const double tensionFeedback = impedanceMax *(impedenceVals.get(3, 0.0)).asDouble();
JSONGoalControl::Config control_config(segmentSpan,
numMuscles,
numMuscles,
numParams,
segNumber,
controlTime,
lowAmplitude,
highAmplitude,
lowPhase,
highPhase,
kt,
kp,
kv,
def,
cl,
lf,
hf,
ffMin,
ffMax,
afMin,
afMax,
pfMin,
pfMax,
tensionFeedback
);
/// @todo fix memory leak that occurs here
JSONGoalTensionNNW* const myControl =
new JSONGoalTensionNNW(control_config, suffix, resourcePath);
#if (1)
tgCPGJSONLogger* const myLogger =
new tgCPGJSONLogger("logs/CPGValues.txt");
myControl->attach(myLogger);
#endif
myModel->attach(myControl);
}
// Sixth add model & controller to simulation
simulation->addModel(myModel);
if (add_blocks)
{
tgModel* blockField = getBlocks();
simulation->addObstacle(blockField);
}
bSetup = true;
return bSetup;
}
void AppGoalTensionNNW::handleOptions(int argc, char **argv)
{
// Declare the supported options.
po::options_description desc("Allowed options");
desc.add_options()
("help,h", "produce help message")
("graphics,G", po::value<bool>(&use_graphics), "Test using graphical view")
("controller,c", po::value<bool>(&add_controller), "Attach the controller to the model.")
("blocks,b", po::value<bool>(&add_blocks)->implicit_value(false), "Add a block field as obstacles.")
("hills,H", po::value<bool>(&add_hills)->implicit_value(false), "Use hilly terrain.")
("all_terrain,A", po::value<bool>(&all_terrain)->implicit_value(false), "Alternate through terrain types. Only works with graphics off")
("phys_time,p", po::value<double>(), "Physics timestep value (Hz). Default=1000")
("graph_time,g", po::value<double>(), "Graphics timestep value a.k.a. render rate (Hz). Default = 60")
("episodes,e", po::value<int>(&nEpisodes), "Number of episodes to run. Default=1")
("steps,s", po::value<int>(&nSteps), "Number of steps per episode to run. Default=60K (60 seconds)")
("segments,S", po::value<int>(&nSegments), "Number of segments in the tensegrity spine. Default=6")
("start_x,x", po::value<double>(&startX), "X Coordinate of starting position for robot. Default = 0")
("start_y,y", po::value<double>(&startY), "Y Coordinate of starting position for robot. Default = 20")
("start_z,z", po::value<double>(&startZ), "Z Coordinate of starting position for robot. Default = 0")
("angle,a", po::value<double>(&startAngle), "Angle of starting rotation for robot. Degrees. Default = 0")
("goal_angle,B", po::value<double>(&goalAngle), "Angle of starting rotation for goal box. Degrees. Default = 0")
("learning_controller,l", po::value<std::string>(&suffix), "Which learned controller to write to or use. Default = default")
;
po::variables_map vm;
po::store(po::parse_command_line(argc, argv, desc), vm);
if (vm.count("help"))
{
std::cout << desc << "\n";
exit(0);
}
po::notify(vm);
if (vm.count("phys_time"))
{
timestep_physics = 1/vm["phys_time"].as<double>();
std::cout << "Physics timestep set to: " << timestep_physics << " seconds.\n";
}
if (vm.count("graph_time"))
{
timestep_graphics = 1/vm["graph_time"].as<double>();
std::cout << "Graphics timestep set to: " << timestep_graphics << " seconds.\n";
}
}
const tgHillyGround::Config AppGoalTensionNNW::getHillyConfig()
{
btVector3 eulerAngles = btVector3(0.0, 0.0, 0.0);
btScalar friction = 0.5;
btScalar restitution = 0.0;
// Size doesn't affect hilly terrain
btVector3 size = btVector3(0.0, 0.1, 0.0);
btVector3 origin = btVector3(0.0, 0.0, 0.0);
size_t nx = 240;
size_t ny = 240;
double margin = 0.5;
double triangleSize = 4.0;
double waveHeight = 2.0;
double offset = 0.0;
const tgHillyGround::Config hillGroundConfig(eulerAngles, friction, restitution,
size, origin, nx, ny, margin, triangleSize,
waveHeight, offset);
return hillGroundConfig;
}
const tgBoxGround::Config AppGoalTensionNNW::getBoxConfig()
{
const double yaw = 0.0;
const double pitch = 0.0;
const double roll = 0.0;
const double friction = 0.5;
const double restitution = 0.0;
const btVector3 size(1000.0, 1.5, 1000.0);
const tgBoxGround::Config groundConfig(btVector3(yaw, pitch, roll),
friction,
restitution,
size );
return groundConfig;
}
tgModel* AppGoalTensionNNW::getBlocks()
{
// Room to add a config
tgBlockField* myObstacle = new tgBlockField();
return myObstacle;
}
tgWorld* AppGoalTensionNNW::createWorld()
{
const tgWorld::Config config(
981 // gravity, cm/sec^2
);
tgBulletGround* ground;
if (add_hills)
{
const tgHillyGround::Config hillGroundConfig = getHillyConfig();
ground = new tgHillyGround(hillGroundConfig);
}
else
{
const tgBoxGround::Config groundConfig = getBoxConfig();
ground = new tgBoxGround(groundConfig);
}
return new tgWorld(config, ground);
}
tgSimViewGraphics *AppGoalTensionNNW::createGraphicsView(tgWorld *world)
{
return new tgSimViewGraphics(*world, timestep_physics, timestep_graphics);
}
tgSimView *AppGoalTensionNNW::createView(tgWorld *world)
{
return new tgSimView(*world, timestep_physics, timestep_graphics);
}
bool AppGoalTensionNNW::run()
{
if (!bSetup)
{
setup();
}
if (use_graphics)
{
// Run until the user stops
simulation->run();
}
else
{
// or run for a specific number of steps
simulate(simulation);
}
///@todo consider app.cleanup()
delete simulation;
delete view;
delete world;
return true;
}
void AppGoalTensionNNW::simulate(tgSimulation *simulation)
{
for (int i=0; i<nEpisodes; i++) {
fprintf(stderr,"Episode %d\n", i);
try
{
simulation->run(nSteps);
}
catch (std::runtime_error e)
{
// Nothing to do here, score will be set to -1
}
// Don't change the terrain before the last episode to avoid leaks
if (i != nEpisodes - 1)
{
if (all_terrain)
{
// Next run has Hills
if (i % nTypes == 0)
{
const tgHillyGround::Config hillGroundConfig = getHillyConfig();
tgBulletGround* ground = new tgHillyGround(hillGroundConfig);
simulation->reset(ground);
}
// Flat
else if (i % nTypes == 1)
{
const tgBoxGround::Config groundConfig = getBoxConfig();
tgBulletGround* ground = new tgBoxGround(groundConfig);
simulation->reset(ground);
}
// Flat with blocks
else if (i % nTypes == 2)
{
simulation->reset();
tgModel* obstacle = getBlocks();
simulation->addObstacle(obstacle);
}
}
else if(add_blocks)
{
simulation->reset();
tgModel* obstacle = getBlocks();
simulation->addObstacle(obstacle);
}
// Avoid resetting twice on the last run
else
{
simulation->reset();
}
}
}
}
/**
* The entry point.
* @param[in] argc the number of command-line arguments
* @param[in] argv argv[0] is the executable name
* @return 0
*/
int main(int argc, char** argv)
{
std::cout << "AppGoalTensionNNW" << std::endl;
AppGoalTensionNNW app (argc, argv);
if (app.setup())
app.run();
//Teardown is handled by delete, so that should be automatic
return 0;
}
<|endoftext|> |
<commit_before>/*=========================================================================
*
* Copyright David Doria 2011 daviddoria@gmail.com
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0.txt
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*=========================================================================*/
#include "PixmapDelegate.h"
#include <QPainter>
#include <iostream>
PixmapDelegate::PixmapDelegate() : Padding(4)
{
}
void PixmapDelegate::SetPadding(const unsigned int padding)
{
this->Padding = padding;
}
void PixmapDelegate::paint(QPainter *painter, const QStyleOptionViewItem &option, const QModelIndex &index) const
{
QStyledItemDelegate::paint(painter, option, index);
QPixmap pixmap = index.data(Qt::DisplayRole).value<QPixmap>();
QRect rect = option.rect;
unsigned int originalWidth = rect.width();
unsigned int originalHeight = rect.height();
//std::cout << "width: " << originalWidth << " height: " << originalHeight << std::endl;
int minSize = std::min(rect.width(), rect.height()) - Padding*2; // We have to double the padding because we want it taken off from both sides.
//std::cout << "minSize: " << minSize << std::endl;
// These setLeft and setTop calls must come before setHeight and setWidth
rect.setLeft(originalWidth/2 - minSize/2);
rect.setTop(rect.top() + originalHeight/2 - minSize/2);
rect.setHeight(minSize);
rect.setWidth(minSize);
painter->drawPixmap(rect, pixmap, pixmap.rect());
}
QSize PixmapDelegate::sizeHint(const QStyleOptionViewItem & option, const QModelIndex & index ) const
{
QPixmap pixmap = index.data(Qt::DisplayRole).value<QPixmap>();
return pixmap.size();
}<commit_msg>Fix bug where patches would only display properly in the first column.<commit_after>/*=========================================================================
*
* Copyright David Doria 2011 daviddoria@gmail.com
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0.txt
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*=========================================================================*/
#include "PixmapDelegate.h"
#include <QPainter>
#include <iostream>
PixmapDelegate::PixmapDelegate() : Padding(4)
{
}
void PixmapDelegate::SetPadding(const unsigned int padding)
{
this->Padding = padding;
}
void PixmapDelegate::paint(QPainter *painter, const QStyleOptionViewItem &option, const QModelIndex &index) const
{
QStyledItemDelegate::paint(painter, option, index);
QPixmap pixmap = index.data(Qt::DisplayRole).value<QPixmap>();
QRect rect = option.rect;
unsigned int originalWidth = rect.width();
unsigned int originalHeight = rect.height();
//std::cout << "width: " << originalWidth << " height: " << originalHeight << std::endl;
int minSize = std::min(rect.width(), rect.height()) - Padding*2; // We have to double the padding because we want it taken off from both sides.
//std::cout << "minSize: " << minSize << std::endl;
// These setLeft and setTop calls must come before setHeight and setWidth
rect.setLeft(rect.left() + originalWidth/2 - minSize/2);
rect.setTop(rect.top() + originalHeight/2 - minSize/2);
rect.setHeight(minSize);
rect.setWidth(minSize);
painter->drawPixmap(rect, pixmap, pixmap.rect());
}
QSize PixmapDelegate::sizeHint(const QStyleOptionViewItem & option, const QModelIndex & index ) const
{
QPixmap pixmap = index.data(Qt::DisplayRole).value<QPixmap>();
return pixmap.size();
}<|endoftext|> |
<commit_before>/*
* Copyright 2010, 2011 Esrille 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.
*/
#include "U16InputStream.h"
#include <assert.h>
#include <string.h>
#include <unicode/ucnv.h>
#include <algorithm>
const char* U16InputStream::DefaultEncoding = "windows-1252";
namespace {
struct Override
{
const char* input;
const char* replacement;
};
// cf. HTML Living Standard 13.2.2.2 Character encodings
Override overrides[] = {
{ "euc-kr", "windows-949" },
{ "euc-jp", "cp51932" },
{ "gb2312", "gbk" },
{ "gb_2312-80", "gbk" },
{ "iso-2022-jp", "cp50220" },
{ "iso-8859-1", "windows-1252" },
{ "iso-8859-9", "windows-1254" },
{ "iso-8859-11", "windows-874" },
{ "ks_c_5601-1987", "windows-949" },
{ "shift_jis", "windows-31j" },
{ "tis-620", "windows-874" },
{ "us-ascii", "windows-1252" }
};
} // namespace
U16InputStream::U16InputStream(std::istream& stream, const std::string optionalEncoding) :
confidence(Certain),
stream(stream)
{
initializeConverter();
encoding = checkEncoding(optionalEncoding);
}
U16InputStream::~U16InputStream()
{
if (converter)
ucnv_close(converter);
}
const char* U16InputStream::skipSpace(const char* p)
{
while (*p) {
if (strchr(" \t\r\n\f", *p) == 0)
return p;
++p;
}
return p;
};
const char* U16InputStream::skipOver(const char* p, const char* target, size_t length)
{
while (*p) {
if (strncmp(p, target, length) == 0)
return p + length;
++p;
}
return p;
};
void U16InputStream::detect(const char* p)
{
if (strncmp(p, "\xfe\xff", 2) == 0) {
encoding = "utf-16be";
return;
}
if (strncmp(p, "\xff\xfe", 2) == 0) {
encoding = "utf-16le";
return;
}
if (strncmp(p, "\xef\xbb\xbf", 3) == 0) {
encoding = "utf-8";
return;
}
encoding = "";
}
std::string U16InputStream::checkEncoding(std::string value)
{
// Remove any leading or trailing space characters
std::string::iterator i = value.begin();
while (i < value.end() && strchr("\t\n\f\r ", *i))
++i;
value.erase(value.begin(), i);
int j;
for (j = value.length(); 0 < j && strchr("\t\n\f\r ", value[j - 1]); --j)
;
value.erase(j, value.length());
if (value.empty())
return "";
// Override character encoding
for (Override* override = overrides;
override < &overrides[sizeof overrides / sizeof overrides[0]];
++override) {
if (!strcasecmp(value.c_str(), override->input)) {
value = override->replacement;
break;
}
}
return value;
}
void U16InputStream::setEncoding(std::string value)
{
value = checkEncoding(value);
if (value.empty())
value = DefaultEncoding;
// Re-check encoding with ICU for conversion
UErrorCode error = U_ZERO_ERROR;
converter = ucnv_open(value.c_str(), &error);
if (!converter) {
value = DefaultEncoding;
converter = ucnv_open(value.c_str(), &error);
if (!converter)
eof = true;
}
encoding = value;
}
void U16InputStream::initializeConverter()
{
flush = false;
eof = !stream;
converter = 0;
source = sourceLimit = sourceBuffer;
target = targetBuffer;
nextChar = target;
lastChar = 0;
}
void U16InputStream::updateSource()
{
assert(!flush);
size_t count = sourceLimit - source;
if (0 < count && sourceBuffer != source)
memmove(sourceBuffer, source, count);
source = sourceBuffer;
sourceLimit = sourceBuffer + count;
count = ChunkSize - count;
if (0 < count) {
stream.read(sourceLimit, count);
count = stream.gcount();
if (!converter) {
if (encoding.empty()) {
sourceLimit[count] = '\0';
detect(sourceLimit);
}
setEncoding(encoding);
}
sourceLimit += count;
if (count == 0)
flush = true;
}
}
void U16InputStream::readChunk()
{
nextChar = target = targetBuffer;
updateSource();
UErrorCode err = U_ZERO_ERROR;
ucnv_toUnicode(converter,
reinterpret_cast<UChar**>(&target),
reinterpret_cast<UChar*>(targetBuffer) + ChunkSize,
const_cast<const char**>(&source),
sourceLimit, 0, flush, &err);
}
U16InputStream::operator std::u16string()
{
std::u16string text;
char16_t c;
while (getChar(c))
text += c;
return text;
}<commit_msg>(overrides) : Fix replacement encoding names for ucnv_open().<commit_after>/*
* Copyright 2010, 2011 Esrille 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.
*/
#include "U16InputStream.h"
#include <assert.h>
#include <string.h>
#include <unicode/ucnv.h>
#include <algorithm>
const char* U16InputStream::DefaultEncoding = "windows-1252";
namespace {
struct Override
{
const char* input;
const char* replacement;
};
// cf. HTML Living Standard 13.2.2.2 Character encodings
// cf. http://bugs.icu-project.org/trac/browser/icu/trunk/source/data/mappings/convrtrs.txt
Override overrides[] = {
{ "euc-kr", "windows-949" },
{ "euc-jp", "windows-51932" }, // ucnv_open() may not understand 'CP51932'.
{ "gb2312", "GBK" },
{ "gb_2312-80", "GBK" },
// { "iso-2022-jp", "CP50220" }, // ucnv_open() may not understand 'CP50220'; iso-2022-jp appears to be the same as CP50220 in ICU.
{ "iso-8859-1", "windows-1252" },
{ "iso-8859-9", "windows-1254" },
{ "iso-8859-11", "windows-874" },
{ "ks_c_5601-1987", "windows-949" },
{ "shift_jis", "Windows-31j" },
{ "tis-620", "windows-874" },
{ "us-ascii", "windows-1252" }
};
} // namespace
U16InputStream::U16InputStream(std::istream& stream, const std::string optionalEncoding) :
confidence(Certain),
stream(stream)
{
initializeConverter();
encoding = checkEncoding(optionalEncoding);
}
U16InputStream::~U16InputStream()
{
if (converter)
ucnv_close(converter);
}
const char* U16InputStream::skipSpace(const char* p)
{
while (*p) {
if (strchr(" \t\r\n\f", *p) == 0)
return p;
++p;
}
return p;
};
const char* U16InputStream::skipOver(const char* p, const char* target, size_t length)
{
while (*p) {
if (strncmp(p, target, length) == 0)
return p + length;
++p;
}
return p;
};
void U16InputStream::detect(const char* p)
{
if (strncmp(p, "\xfe\xff", 2) == 0) {
encoding = "utf-16be";
return;
}
if (strncmp(p, "\xff\xfe", 2) == 0) {
encoding = "utf-16le";
return;
}
if (strncmp(p, "\xef\xbb\xbf", 3) == 0) {
encoding = "utf-8";
return;
}
encoding = "";
}
std::string U16InputStream::checkEncoding(std::string value)
{
// Remove any leading or trailing space characters
std::string::iterator i = value.begin();
while (i < value.end() && strchr("\t\n\f\r ", *i))
++i;
value.erase(value.begin(), i);
int j;
for (j = value.length(); 0 < j && strchr("\t\n\f\r ", value[j - 1]); --j)
;
value.erase(j, value.length());
if (value.empty())
return "";
// Override character encoding
for (Override* override = overrides;
override < &overrides[sizeof overrides / sizeof overrides[0]];
++override) {
if (!strcasecmp(value.c_str(), override->input)) {
value = override->replacement;
break;
}
}
return value;
}
void U16InputStream::setEncoding(std::string value)
{
value = checkEncoding(value);
if (value.empty())
value = DefaultEncoding;
// Re-check encoding with ICU for conversion
UErrorCode error = U_ZERO_ERROR;
converter = ucnv_open(value.c_str(), &error);
if (!converter) {
value = DefaultEncoding;
converter = ucnv_open(value.c_str(), &error);
if (!converter)
eof = true;
}
encoding = value;
}
void U16InputStream::initializeConverter()
{
flush = false;
eof = !stream;
converter = 0;
source = sourceLimit = sourceBuffer;
target = targetBuffer;
nextChar = target;
lastChar = 0;
}
void U16InputStream::updateSource()
{
assert(!flush);
size_t count = sourceLimit - source;
if (0 < count && sourceBuffer != source)
memmove(sourceBuffer, source, count);
source = sourceBuffer;
sourceLimit = sourceBuffer + count;
count = ChunkSize - count;
if (0 < count) {
stream.read(sourceLimit, count);
count = stream.gcount();
if (!converter) {
if (encoding.empty()) {
sourceLimit[count] = '\0';
detect(sourceLimit);
}
setEncoding(encoding);
}
sourceLimit += count;
if (count == 0)
flush = true;
}
}
void U16InputStream::readChunk()
{
nextChar = target = targetBuffer;
updateSource();
UErrorCode err = U_ZERO_ERROR;
ucnv_toUnicode(converter,
reinterpret_cast<UChar**>(&target),
reinterpret_cast<UChar*>(targetBuffer) + ChunkSize,
const_cast<const char**>(&source),
sourceLimit, 0, flush, &err);
}
U16InputStream::operator std::u16string()
{
std::u16string text;
char16_t c;
while (getChar(c))
text += c;
return text;
}<|endoftext|> |
<commit_before>#include <cppunit/extensions/HelperMacros.h>
#include "spotty_network_failure_test.h"
#include <errno.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <sys/wait.h>
#include <sys/socket.h>
#include <netdb.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <assert.h>
#include <string.h>
#include <dlfcn.h>
#include <libcmm.h>
#include <libcmm_irob.h>
#include "net_interface.h"
#include "test_common.h"
#include "cmm_socket_control.h"
#include "libcmm_ipc.h"
#include <string>
#include <vector>
using std::string; using std::vector;
CPPUNIT_TEST_SUITE_REGISTRATION(SpottyNetworkFailureTest);
int
make_listening_socket(short port)
{
int sock = socket(PF_INET, SOCK_STREAM, 0);
handle_error(sock < 0, "socket");
int on = 1;
int rc = setsockopt(sock, SOL_SOCKET, SO_REUSEADDR,
(char *) &on, sizeof(on));
if (rc < 0) {
DEBUG_LOG("Cannot reuse socket address\n");
}
struct sockaddr_in addr;
memset(&addr, 0, sizeof(addr));
addr.sin_family = AF_INET;
addr.sin_addr.s_addr = INADDR_ANY;
addr.sin_port = htons(port);
socklen_t addrlen = sizeof(addr);
rc = bind(sock, (struct sockaddr*)&addr, addrlen);
handle_error(rc < 0, "bind");
rc = listen(sock, 5);
handle_error(rc < 0, "cmm_listen");
DEBUG_LOG("Receiver is listening...\n");
return sock;
}
void
SpottyNetworkFailureTest::setupReceiver()
{
listen_sock = make_listening_socket(TEST_PORT);
}
void
SpottyNetworkFailureTest::startReceiver()
{
struct sockaddr_in addr;
socklen_t addrlen = sizeof(addr);
int bootstrap_sock = accept(listen_sock,
(struct sockaddr *)&addr,
&addrlen);
handle_error(bootstrap_sock < 0, "accept");
DEBUG_LOG("Receiver accepted connection %d\n", bootstrap_sock);
doFakeIntNWSetup(bootstrap_sock);
close(bootstrap_sock);
}
void
SpottyNetworkFailureTest::doFakeIntNWSetup(int bootstrap_sock)
{
struct CMMSocketControlHdr hello;
int rc = read(bootstrap_sock, &hello, sizeof(hello));
handle_error(rc != sizeof(hello), "receiving intnw hello");
short intnw_listen_port = 42429;
intnw_listen_sock = make_listening_socket(intnw_listen_port);
handle_error(intnw_listen_sock < 0, "creating intnw listener socket");
hello.op.hello.listen_port = htons(intnw_listen_port);
hello.op.hello.num_ifaces = htonl(1);
rc = write(bootstrap_sock, &hello, sizeof(hello));
handle_error(rc != sizeof(hello), "sending intnw hello");
acceptCsocks();
exchangeNetworkInterfaces(bootstrap_sock);
}
struct net_interface init_csocket(int csock)
{
struct CMMSocketControlHdr hdr;
struct net_interface iface;
int rc = read(csock, &hdr, sizeof(hdr));
handle_error(rc != sizeof(hdr), "reading csock net_interface data");
assert(ntohs(hdr.type) == CMM_CONTROL_MSG_NEW_INTERFACE);
iface = hdr.op.new_interface;
iface.bandwidth_down = ntohl(iface.bandwidth_down);
iface.bandwidth_up = ntohl(iface.bandwidth_up);
iface.RTT = ntohl(iface.RTT);
memset(&hdr, 0, sizeof(hdr));
hdr.type = htons(CMM_CONTROL_MSG_HELLO);
rc = write(csock, &hdr, sizeof(hdr));
handle_error(rc != sizeof(hdr), "sending csock confirmation");
return iface;
}
void
SpottyNetworkFailureTest::acceptCsocks()
{
struct net_interface steady_iface, intermittent_iface;
steady_csock = accept(intnw_listen_sock, NULL, NULL);
handle_error(steady_csock < 0, "accepting csocket");
steady_iface = init_csocket(steady_csock);
intermittent_csock = accept(intnw_listen_sock, NULL, NULL);
handle_error(steady_csock < 0, "accepting csocket");
intermittent_iface = init_csocket(intermittent_csock);
// the better network is the intermittent one.
if (steady_iface.RTT < intermittent_iface.RTT) {
int tmpsock = steady_csock;
steady_csock = intermittent_csock;
intermittent_csock = tmpsock;
}
}
void
SpottyNetworkFailureTest::exchangeNetworkInterfaces(int bootstrap_sock)
{
struct net_interface sentinel;
memset(&sentinel, 0, sizeof(sentinel));
int rc;
struct CMMSocketControlHdr hdr;
do {
rc = read(bootstrap_sock, &hdr, sizeof(hdr));
handle_error(rc != sizeof(hdr), "reading net iface");
} while (memcmp(&hdr.op.new_interface, &sentinel, sizeof(struct net_interface)) != 0);
struct CMMSocketControlHdr hdrs[2];
memset(hdrs, 0, sizeof(hdrs));
hdrs[0].type = htons(CMM_CONTROL_MSG_NEW_INTERFACE);
inet_aton("141.212.110.132", &hdrs[0].op.new_interface.ip_addr);
hdrs[0].op.new_interface.bandwidth_down = 1250000;
hdrs[0].op.new_interface.bandwidth_up = 1250000;
hdrs[0].op.new_interface.RTT = 1;
hdrs[1].type = htons(CMM_CONTROL_MSG_NEW_INTERFACE);
hdrs[0].op.new_interface = sentinel;
rc = write(bootstrap_sock, hdrs, sizeof(hdrs));
handle_error(rc != sizeof(hdrs), "sending net iface");
}
void
SpottyNetworkFailureTest::startSender()
{
// start up intnw
void *dl_handle = dlopen("libcmm.so", RTLD_LAZY);
handle_error(dl_handle == NULL, "loading libcmm: dlopen");
// create connecting multisocket
EndToEndTestsBase::startSender();
}
void
SpottyNetworkFailureTest::tearDown()
{
if (isReceiver()) {
close(steady_csock);
close(intermittent_csock);
close(intnw_listen_sock);
close(listen_sock);
} else {
EndToEndTestsBase::tearDown();
}
}
int
connect_to_scout_control()
{
int sock = socket(PF_INET, SOCK_STREAM, 0);
handle_error(sock < 0, "creating scout control socket");
struct sockaddr_in addr;
memset(&addr, 0, sizeof(addr));
addr.sin_family = AF_INET;
addr.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
addr.sin_port = htons(CONTROL_SOCKET_PORT);
socklen_t addrlen = sizeof(addr);
int rc = connect(sock, (struct sockaddr *)&addr, addrlen);
handle_error(rc < 0, "connecting scout control socket");
return sock;
}
void
SpottyNetworkFailureTest::testOneNetworkFails()
{
const char expected_str[] = "ABCDEFGHIJ";
const size_t len = sizeof(expected_str);
sleep(1);
char buf[len + 1];
memset(buf, 0, sizeof(buf));
if (isReceiver()) {
shutdown(intermittent_csock, SHUT_RDWR);
// expected messages:
// in order:
// 1) begin_irob
// 2) irob_chunk
// 3) end_irob
//
// at any time:
// - down_interface
vector<struct CMMSocketControlHdr> hdrs;
while (hdrs.size() < 4) {
struct CMMSocketControlHdr hdr;
memset(&hdr, 0, sizeof(hdr));
int rc = recv(steady_csock, &hdr, sizeof(hdr), MSG_WAITALL);
CPPUNIT_ASSERT_EQUAL((int)sizeof(hdr), rc);
if (ntohs(hdr.type) == CMM_CONTROL_MSG_IROB_CHUNK) {
CPPUNIT_ASSERT_EQUAL(len, ntohl(hdr.op.irob_chunk.datalen));
rc = recv(steady_csock, buf, len, MSG_WAITALL);
CPPUNIT_ASSERT_EQUAL(rc, (int)len);
CPPUNIT_ASSERT_EQUAL(string(expected_str), string(buf));
}
hdrs.push_back(hdr);
}
CPPUNIT_ASSERT_EQUAL(4U, hdrs.size());
irob_id_t irob_id = -1;
bool begin_irob_recvd = false;
bool irob_chunk_recvd = false;
bool end_irob_recvd = false;
bool down_interface_recvd = false;
for (size_t i = 0; i < hdrs.size(); ++i) {
switch (ntohs(hdrs[i].type)) {
case CMM_CONTROL_MSG_BEGIN_IROB:
irob_id = ntohl(hdrs[i].op.begin_irob.id);
begin_irob_recvd = true; break;
case CMM_CONTROL_MSG_IROB_CHUNK:
irob_chunk_recvd = true; break;
case CMM_CONTROL_MSG_END_IROB:
end_irob_recvd = true; break;
case CMM_CONTROL_MSG_DOWN_INTERFACE:
down_interface_recvd = true; break;
default:
CPPUNIT_ASSERT(false);
}
}
CPPUNIT_ASSERT(begin_irob_recvd);
CPPUNIT_ASSERT(irob_chunk_recvd);
CPPUNIT_ASSERT(end_irob_recvd);
CPPUNIT_ASSERT(down_interface_recvd);
struct CMMSocketControlHdr ack;
memset(&ack, 0, sizeof(ack));
ack.type = htons(CMM_CONTROL_MSG_ACK);
ack.op.ack.id = htonl(irob_id);
int rc = write(steady_csock, &ack, sizeof(ack));
CPPUNIT_ASSERT_EQUAL((int)sizeof(ack), rc);
char response[sizeof(struct CMMSocketControlHdr) * 3 + len];
memset(response, 0, sizeof(response));
struct CMMSocketControlHdr *begin_irob_hdr = (struct CMMSocketControlHdr *) response;
struct CMMSocketControlHdr *irob_chunk_hdr =
(struct CMMSocketControlHdr *) (((char *) begin_irob_hdr) + sizeof(*begin_irob_hdr));
char *resp_data = ((char *) irob_chunk_hdr) + sizeof(*irob_chunk_hdr);
struct CMMSocketControlHdr *end_irob_hdr =
(struct CMMSocketControlHdr *) (resp_data + len);
irob_id_t resp_irob_id = irob_id + 1;
begin_irob_hdr->type = htons(CMM_CONTROL_MSG_BEGIN_IROB);
begin_irob_hdr->op.begin_irob.id = htonl(resp_irob_id);
irob_chunk_hdr->op.irob_chunk.id = htonl(resp_irob_id);
irob_chunk_hdr->op.irob_chunk.seqno = 0;
irob_chunk_hdr->op.irob_chunk.datalen = htonl(len);
memcpy(resp_data, buf, len);
end_irob_hdr->op.end_irob.id = htonl(resp_irob_id);
end_irob_hdr->op.end_irob.expected_bytes = htonl(len);
end_irob_hdr->op.end_irob.expected_chunks = htonl(1);
rc = write(steady_csock, response, sizeof(response));
CPPUNIT_ASSERT_EQUAL((int) sizeof(response), rc);
memset(&ack, 0, sizeof(ack));
rc = recv(steady_csock, &ack, sizeof(ack), MSG_WAITALL);
CPPUNIT_ASSERT_EQUAL((int) sizeof(ack), rc);
CPPUNIT_ASSERT_EQUAL((uint16_t) CMM_CONTROL_MSG_ACK, ntohs(ack.type));
CPPUNIT_ASSERT_EQUAL(resp_irob_id, (irob_id_t) ntohl(ack.op.ack.id));
} else {
int scout_control_sock = connect_to_scout_control();
sleep(1);
int rc = cmm_write(data_sock, buf, len, 0, NULL, NULL);
CPPUNIT_ASSERT_EQUAL((int)len, rc); // succeeds immediately without waiting for bytes to be sent
sleep(1);
char cmd[] = "bg_down\n";
rc = write(scout_control_sock, cmd, sizeof(cmd));
CPPUNIT_ASSERT_EQUAL((int) sizeof(cmd), rc);
sleep(1);
memset(buf, 0, sizeof(buf));
rc = cmm_recv(data_sock, buf, len, MSG_WAITALL, NULL);
CPPUNIT_ASSERT_EQUAL((int) len, rc);
CPPUNIT_ASSERT_EQUAL(string(expected_str), string(buf));
close(scout_control_sock);
}
}
<commit_msg>Small assertion fix; expected, then actual.<commit_after>#include <cppunit/extensions/HelperMacros.h>
#include "spotty_network_failure_test.h"
#include <errno.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <sys/wait.h>
#include <sys/socket.h>
#include <netdb.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <assert.h>
#include <string.h>
#include <dlfcn.h>
#include <libcmm.h>
#include <libcmm_irob.h>
#include "net_interface.h"
#include "test_common.h"
#include "cmm_socket_control.h"
#include "libcmm_ipc.h"
#include <string>
#include <vector>
using std::string; using std::vector;
CPPUNIT_TEST_SUITE_REGISTRATION(SpottyNetworkFailureTest);
int
make_listening_socket(short port)
{
int sock = socket(PF_INET, SOCK_STREAM, 0);
handle_error(sock < 0, "socket");
int on = 1;
int rc = setsockopt(sock, SOL_SOCKET, SO_REUSEADDR,
(char *) &on, sizeof(on));
if (rc < 0) {
DEBUG_LOG("Cannot reuse socket address\n");
}
struct sockaddr_in addr;
memset(&addr, 0, sizeof(addr));
addr.sin_family = AF_INET;
addr.sin_addr.s_addr = INADDR_ANY;
addr.sin_port = htons(port);
socklen_t addrlen = sizeof(addr);
rc = bind(sock, (struct sockaddr*)&addr, addrlen);
handle_error(rc < 0, "bind");
rc = listen(sock, 5);
handle_error(rc < 0, "cmm_listen");
DEBUG_LOG("Receiver is listening...\n");
return sock;
}
void
SpottyNetworkFailureTest::setupReceiver()
{
listen_sock = make_listening_socket(TEST_PORT);
}
void
SpottyNetworkFailureTest::startReceiver()
{
struct sockaddr_in addr;
socklen_t addrlen = sizeof(addr);
int bootstrap_sock = accept(listen_sock,
(struct sockaddr *)&addr,
&addrlen);
handle_error(bootstrap_sock < 0, "accept");
DEBUG_LOG("Receiver accepted connection %d\n", bootstrap_sock);
doFakeIntNWSetup(bootstrap_sock);
close(bootstrap_sock);
}
void
SpottyNetworkFailureTest::doFakeIntNWSetup(int bootstrap_sock)
{
struct CMMSocketControlHdr hello;
int rc = read(bootstrap_sock, &hello, sizeof(hello));
handle_error(rc != sizeof(hello), "receiving intnw hello");
short intnw_listen_port = 42429;
intnw_listen_sock = make_listening_socket(intnw_listen_port);
handle_error(intnw_listen_sock < 0, "creating intnw listener socket");
hello.op.hello.listen_port = htons(intnw_listen_port);
hello.op.hello.num_ifaces = htonl(1);
rc = write(bootstrap_sock, &hello, sizeof(hello));
handle_error(rc != sizeof(hello), "sending intnw hello");
acceptCsocks();
exchangeNetworkInterfaces(bootstrap_sock);
}
struct net_interface init_csocket(int csock)
{
struct CMMSocketControlHdr hdr;
struct net_interface iface;
int rc = read(csock, &hdr, sizeof(hdr));
handle_error(rc != sizeof(hdr), "reading csock net_interface data");
assert(ntohs(hdr.type) == CMM_CONTROL_MSG_NEW_INTERFACE);
iface = hdr.op.new_interface;
iface.bandwidth_down = ntohl(iface.bandwidth_down);
iface.bandwidth_up = ntohl(iface.bandwidth_up);
iface.RTT = ntohl(iface.RTT);
memset(&hdr, 0, sizeof(hdr));
hdr.type = htons(CMM_CONTROL_MSG_HELLO);
rc = write(csock, &hdr, sizeof(hdr));
handle_error(rc != sizeof(hdr), "sending csock confirmation");
return iface;
}
void
SpottyNetworkFailureTest::acceptCsocks()
{
struct net_interface steady_iface, intermittent_iface;
steady_csock = accept(intnw_listen_sock, NULL, NULL);
handle_error(steady_csock < 0, "accepting csocket");
steady_iface = init_csocket(steady_csock);
intermittent_csock = accept(intnw_listen_sock, NULL, NULL);
handle_error(steady_csock < 0, "accepting csocket");
intermittent_iface = init_csocket(intermittent_csock);
// the better network is the intermittent one.
if (steady_iface.RTT < intermittent_iface.RTT) {
int tmpsock = steady_csock;
steady_csock = intermittent_csock;
intermittent_csock = tmpsock;
}
}
void
SpottyNetworkFailureTest::exchangeNetworkInterfaces(int bootstrap_sock)
{
struct net_interface sentinel;
memset(&sentinel, 0, sizeof(sentinel));
int rc;
struct CMMSocketControlHdr hdr;
do {
rc = read(bootstrap_sock, &hdr, sizeof(hdr));
handle_error(rc != sizeof(hdr), "reading net iface");
} while (memcmp(&hdr.op.new_interface, &sentinel, sizeof(struct net_interface)) != 0);
struct CMMSocketControlHdr hdrs[2];
memset(hdrs, 0, sizeof(hdrs));
hdrs[0].type = htons(CMM_CONTROL_MSG_NEW_INTERFACE);
inet_aton("141.212.110.132", &hdrs[0].op.new_interface.ip_addr);
hdrs[0].op.new_interface.bandwidth_down = 1250000;
hdrs[0].op.new_interface.bandwidth_up = 1250000;
hdrs[0].op.new_interface.RTT = 1;
hdrs[1].type = htons(CMM_CONTROL_MSG_NEW_INTERFACE);
hdrs[0].op.new_interface = sentinel;
rc = write(bootstrap_sock, hdrs, sizeof(hdrs));
handle_error(rc != sizeof(hdrs), "sending net iface");
}
void
SpottyNetworkFailureTest::startSender()
{
// start up intnw
void *dl_handle = dlopen("libcmm.so", RTLD_LAZY);
handle_error(dl_handle == NULL, "loading libcmm: dlopen");
// create connecting multisocket
EndToEndTestsBase::startSender();
}
void
SpottyNetworkFailureTest::tearDown()
{
if (isReceiver()) {
close(steady_csock);
close(intermittent_csock);
close(intnw_listen_sock);
close(listen_sock);
} else {
EndToEndTestsBase::tearDown();
}
}
int
connect_to_scout_control()
{
int sock = socket(PF_INET, SOCK_STREAM, 0);
handle_error(sock < 0, "creating scout control socket");
struct sockaddr_in addr;
memset(&addr, 0, sizeof(addr));
addr.sin_family = AF_INET;
addr.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
addr.sin_port = htons(CONTROL_SOCKET_PORT);
socklen_t addrlen = sizeof(addr);
int rc = connect(sock, (struct sockaddr *)&addr, addrlen);
handle_error(rc < 0, "connecting scout control socket");
return sock;
}
void
SpottyNetworkFailureTest::testOneNetworkFails()
{
const char expected_str[] = "ABCDEFGHIJ";
const size_t len = sizeof(expected_str);
sleep(1);
char buf[len + 1];
memset(buf, 0, sizeof(buf));
if (isReceiver()) {
shutdown(intermittent_csock, SHUT_RDWR);
// expected messages:
// in order:
// 1) begin_irob
// 2) irob_chunk
// 3) end_irob
//
// at any time:
// - down_interface
vector<struct CMMSocketControlHdr> hdrs;
while (hdrs.size() < 4) {
struct CMMSocketControlHdr hdr;
memset(&hdr, 0, sizeof(hdr));
int rc = recv(steady_csock, &hdr, sizeof(hdr), MSG_WAITALL);
CPPUNIT_ASSERT_EQUAL((int)sizeof(hdr), rc);
if (ntohs(hdr.type) == CMM_CONTROL_MSG_IROB_CHUNK) {
CPPUNIT_ASSERT_EQUAL(len, ntohl(hdr.op.irob_chunk.datalen));
rc = recv(steady_csock, buf, len, MSG_WAITALL);
CPPUNIT_ASSERT_EQUAL((int)len, rc);
CPPUNIT_ASSERT_EQUAL(string(expected_str), string(buf));
}
hdrs.push_back(hdr);
}
CPPUNIT_ASSERT_EQUAL(4U, hdrs.size());
irob_id_t irob_id = -1;
bool begin_irob_recvd = false;
bool irob_chunk_recvd = false;
bool end_irob_recvd = false;
bool down_interface_recvd = false;
for (size_t i = 0; i < hdrs.size(); ++i) {
switch (ntohs(hdrs[i].type)) {
case CMM_CONTROL_MSG_BEGIN_IROB:
irob_id = ntohl(hdrs[i].op.begin_irob.id);
begin_irob_recvd = true; break;
case CMM_CONTROL_MSG_IROB_CHUNK:
irob_chunk_recvd = true; break;
case CMM_CONTROL_MSG_END_IROB:
end_irob_recvd = true; break;
case CMM_CONTROL_MSG_DOWN_INTERFACE:
down_interface_recvd = true; break;
default:
CPPUNIT_ASSERT(false);
}
}
CPPUNIT_ASSERT(begin_irob_recvd);
CPPUNIT_ASSERT(irob_chunk_recvd);
CPPUNIT_ASSERT(end_irob_recvd);
CPPUNIT_ASSERT(down_interface_recvd);
struct CMMSocketControlHdr ack;
memset(&ack, 0, sizeof(ack));
ack.type = htons(CMM_CONTROL_MSG_ACK);
ack.op.ack.id = htonl(irob_id);
int rc = write(steady_csock, &ack, sizeof(ack));
CPPUNIT_ASSERT_EQUAL((int)sizeof(ack), rc);
char response[sizeof(struct CMMSocketControlHdr) * 3 + len];
memset(response, 0, sizeof(response));
struct CMMSocketControlHdr *begin_irob_hdr = (struct CMMSocketControlHdr *) response;
struct CMMSocketControlHdr *irob_chunk_hdr =
(struct CMMSocketControlHdr *) (((char *) begin_irob_hdr) + sizeof(*begin_irob_hdr));
char *resp_data = ((char *) irob_chunk_hdr) + sizeof(*irob_chunk_hdr);
struct CMMSocketControlHdr *end_irob_hdr =
(struct CMMSocketControlHdr *) (resp_data + len);
irob_id_t resp_irob_id = irob_id + 1;
begin_irob_hdr->type = htons(CMM_CONTROL_MSG_BEGIN_IROB);
begin_irob_hdr->op.begin_irob.id = htonl(resp_irob_id);
irob_chunk_hdr->op.irob_chunk.id = htonl(resp_irob_id);
irob_chunk_hdr->op.irob_chunk.seqno = 0;
irob_chunk_hdr->op.irob_chunk.datalen = htonl(len);
memcpy(resp_data, buf, len);
end_irob_hdr->op.end_irob.id = htonl(resp_irob_id);
end_irob_hdr->op.end_irob.expected_bytes = htonl(len);
end_irob_hdr->op.end_irob.expected_chunks = htonl(1);
rc = write(steady_csock, response, sizeof(response));
CPPUNIT_ASSERT_EQUAL((int) sizeof(response), rc);
memset(&ack, 0, sizeof(ack));
rc = recv(steady_csock, &ack, sizeof(ack), MSG_WAITALL);
CPPUNIT_ASSERT_EQUAL((int) sizeof(ack), rc);
CPPUNIT_ASSERT_EQUAL((uint16_t) CMM_CONTROL_MSG_ACK, ntohs(ack.type));
CPPUNIT_ASSERT_EQUAL(resp_irob_id, (irob_id_t) ntohl(ack.op.ack.id));
} else {
int scout_control_sock = connect_to_scout_control();
sleep(1);
int rc = cmm_write(data_sock, buf, len, 0, NULL, NULL);
CPPUNIT_ASSERT_EQUAL((int)len, rc); // succeeds immediately without waiting for bytes to be sent
sleep(1);
char cmd[] = "bg_down\n";
rc = write(scout_control_sock, cmd, sizeof(cmd));
CPPUNIT_ASSERT_EQUAL((int) sizeof(cmd), rc);
sleep(1);
memset(buf, 0, sizeof(buf));
rc = cmm_recv(data_sock, buf, len, MSG_WAITALL, NULL);
CPPUNIT_ASSERT_EQUAL((int) len, rc);
CPPUNIT_ASSERT_EQUAL(string(expected_str), string(buf));
close(scout_control_sock);
}
}
<|endoftext|> |
<commit_before>/* vim: tabstop=2 shiftwidth=2 expandtab textwidth=80 linebreak wrap
*
* Copyright 2012 Matthew McCormick
* Copyright 2013 Justin Crawford <Justasic@gmail.com>
* Copyright 2015 Pawel 'l0ner' Soltys
* Copyright 2016 Compilenix
*
* 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.
*/
// Based on: github.com/freebsd/freebsd/blob/master/usr.bin/top/machine.c
// Based on: Apple.cpp for load_string/mem_string and apple's documentation
#include <sstream>
#include <string>
#include <stdlib.h> // getloadavg()
#include <cmath> // floorf()
#include <sys/types.h>
#include "cpu.h"
#include "load.h"
#include "luts.h"
#include "powerline.h"
// Load Averages
std::string load_string( bool use_colors,
bool use_powerline_left, bool use_powerline_right,
short num_averages )
{
std::ostringstream ss;
double averages[num_averages];
// based on: opensource.apple.com/source/Libc/Libc-262/gen/getloadavg.c
if( num_averages <= 0 || num_averages > 3)
{
ss << (char) 0;
return ss.str();
}
if( getloadavg( averages, num_averages ) < 0 )
{
ss << " 0.00 0.00 0.00"; // couldn't get averages.
}
else
{
unsigned load_percent = static_cast<unsigned int>( averages[0] /
get_cpu_count() * 0.5f * 100.0f );
if( load_percent > 100 )
{
load_percent = 100;
}
if( use_colors )
{
if( use_powerline_right )
{
powerline( ss, load_lut[load_percent], POWERLINE_RIGHT );
}
else if( use_powerline_left )
{
powerline( ss, load_lut[load_percent], POWERLINE_LEFT );
}
else
{
powerline( ss, load_lut[load_percent], NONE );
}
}
ss << ' ';
for( int i = 0; i < num_averages; ++i )
{
// Round to nearest, make sure this is only a 0.00 value not a 0.0000
float avg = floorf( static_cast<float>( averages[i] ) * 100 + 0.5 ) / 100;
// Don't print trailing whitespace for last element
if ( i == num_averages-1 )
{
ss << avg;
}
else
{
ss << avg << " ";
}
}
if( use_colors )
{
if( use_powerline_left )
{
powerline( ss, load_lut[load_percent], POWERLINE_LEFT, true );
powerline( ss, "#[fg=default,bg=default]", POWERLINE_LEFT );
}
else if( !use_powerline_right )
{
ss << "#[fg=default,bg=default]";
}
}
}
return ss.str();
}
<commit_msg>Use consistent precision for load output<commit_after>/* vim: tabstop=2 shiftwidth=2 expandtab textwidth=80 linebreak wrap
*
* Copyright 2012 Matthew McCormick
* Copyright 2013 Justin Crawford <Justasic@gmail.com>
* Copyright 2015 Pawel 'l0ner' Soltys
* Copyright 2016 Compilenix
*
* 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.
*/
// Based on: github.com/freebsd/freebsd/blob/master/usr.bin/top/machine.c
// Based on: Apple.cpp for load_string/mem_string and apple's documentation
#include <sstream>
#include <string>
#include <stdlib.h> // getloadavg()
#include <cmath> // floorf()
#include <sys/types.h>
#include "cpu.h"
#include "load.h"
#include "luts.h"
#include "powerline.h"
// Load Averages
std::string load_string( bool use_colors,
bool use_powerline_left, bool use_powerline_right,
short num_averages )
{
std::ostringstream ss;
ss.setf( std::ios::fixed, std::ios::floatfield );
ss.precision( 2 );
double averages[num_averages];
// based on: opensource.apple.com/source/Libc/Libc-262/gen/getloadavg.c
if( num_averages <= 0 || num_averages > 3)
{
ss << (char) 0;
return ss.str();
}
if( getloadavg( averages, num_averages ) < 0 )
{
ss << " 0.00 0.00 0.00"; // couldn't get averages.
}
else
{
unsigned load_percent = static_cast<unsigned int>( averages[0] /
get_cpu_count() * 0.5f * 100.0f );
if( load_percent > 100 )
{
load_percent = 100;
}
if( use_colors )
{
if( use_powerline_right )
{
powerline( ss, load_lut[load_percent], POWERLINE_RIGHT );
}
else if( use_powerline_left )
{
powerline( ss, load_lut[load_percent], POWERLINE_LEFT );
}
else
{
powerline( ss, load_lut[load_percent], NONE );
}
}
ss << ' ';
for( int i = 0; i < num_averages; ++i )
{
// Round to nearest, make sure this is only a 0.00 value not a 0.0000
float avg = floorf( static_cast<float>( averages[i] ) * 100 + 0.5 ) / 100;
// Don't print trailing whitespace for last element
if ( i == num_averages-1 )
{
ss << avg;
}
else
{
ss << avg << " ";
}
}
if( use_colors )
{
if( use_powerline_left )
{
powerline( ss, load_lut[load_percent], POWERLINE_LEFT, true );
powerline( ss, "#[fg=default,bg=default]", POWERLINE_LEFT );
}
else if( !use_powerline_right )
{
ss << "#[fg=default,bg=default]";
}
}
}
return ss.str();
}
<|endoftext|> |
<commit_before>#include "../PlyReader.h"
#include "../TriangleMeshPlyReaderDelegate.h"
// This file is a part of the OpenSurgSim project.
// Copyright 2013, SimQuest Solutions 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.
#include <gtest/gtest.h>
#include "SurgSim/DataStructures/AabbTree.h"
#include "SurgSim/DataStructures/AabbTreeNode.h"
#include "SurgSim/DataStructures/TriangleMeshBase.h"
#include "SurgSim/DataStructures/TriangleMeshPlyReaderDelegate.h"
#include "SurgSim/DataStructures/AabbTreeIntersectionVisitor.h"
#include "SurgSim/Math/Aabb.h"
#include "SurgSim/Math/MeshShape.h"
#include "SurgSim/Math/Vector.h"
#include "SurgSim/Math/RigidTransform.h"
#include "SurgSim/Framework/ApplicationData.h"
#include "SurgSim/Framework/Timer.h"
#include "SurgSim/Testing/MathUtilities.h"
using SurgSim::Math::Aabbd;
using SurgSim::Math::RigidTransform3d;
using SurgSim::Math::Vector3d;
namespace
{
std::shared_ptr<SurgSim::DataStructures::TriangleMeshBase<
SurgSim::DataStructures::EmptyData, SurgSim::DataStructures::EmptyData, SurgSim::DataStructures::EmptyData>>
loadTriangleMesh(const std::string& fileName)
{
auto triangleMeshDelegate = std::make_shared<SurgSim::DataStructures::TriangleMeshPlyReaderDelegate>();
SurgSim::DataStructures::PlyReader reader(fileName);
SURGSIM_ASSERT(reader.setDelegate(triangleMeshDelegate)) << "The input file " << fileName << " is malformed.";
reader.parseFile();
return triangleMeshDelegate->getMesh();
}
}
namespace SurgSim
{
namespace DataStructures
{
TEST(AabbTreeTests, InitTest)
{
ASSERT_NO_THROW({AabbTree tree(3);});
auto tree = std::make_shared<AabbTree>(3);
EXPECT_EQ(3u, tree->getMaxObjectsPerNode());
EXPECT_NE(nullptr, tree->getRoot());
}
TEST(AabbTreeTests, AddTest)
{
auto tree = std::make_shared<AabbTree>(3);
Aabbd one(Vector3d(-1.0, -1.0, -1.0), Vector3d(0.0, 0.0, 0.0));
Aabbd two(Vector3d(0.0, 0.0, 0.0), Vector3d(1.0, 1.0, 1.0));
EXPECT_NO_THROW(tree->add(one, 0));
EXPECT_NO_THROW(tree->add(one, 1));
EXPECT_NO_THROW(tree->add(two, 2));
EXPECT_NO_THROW(tree->add(two, 3));
EXPECT_EQ(2u, tree->getRoot()->getNumChildren());
}
TEST(AabbTreeTests, BuildTest)
{
SurgSim::Framework::ApplicationData data("config.txt");
auto tree = std::make_shared<AabbTree>(3);
std::string filename = data.findFile("Geometry/arm_collision.ply");
ASSERT_FALSE(filename.empty());
auto mesh = loadTriangleMesh(filename);
std::cout << mesh->getNumTriangles() << std::endl;
SurgSim::Framework::Timer timer;
for (size_t i = 0; i < mesh->getNumTriangles(); ++i)
{
auto triangle = mesh->getTriangle(i);
Aabbd aabb(SurgSim::Math::makeAabb(
mesh->getVertex(triangle.verticesId[0]).position,
mesh->getVertex(triangle.verticesId[1]).position,
mesh->getVertex(triangle.verticesId[2]).position));
tree->add(aabb, i);
}
timer.endFrame();
std::cout << timer.getCumulativeTime() << std::endl;
}
TEST(AabbTreeTests, EasyIntersectionTest)
{
auto tree = std::make_shared<AabbTree>(3);
Aabbd bigBox;
for (int i = 0; i <= 6; ++i)
{
Aabbd aabb(Vector3d(static_cast<double>(i) - 0.01, -0.01, -0.01),
Vector3d(static_cast<double>(i) + 0.01, 0.01, 0.01));
bigBox.extend(aabb);
tree->add(aabb, i);
}
EXPECT_TRUE(bigBox.isApprox(tree->getAabb())) << bigBox << ", " << tree->getAabb();
AabbTreeIntersectionVisitor visitor(bigBox);
tree->getRoot()->accept(&visitor);
EXPECT_EQ(7u, visitor.getIntersections().size());
Aabbd leftBox(Vector3d(0.0, -0.02, -0.02), Vector3d(3.4, 0.02, 0.02));
visitor.setAabb(leftBox);
tree->getRoot()->accept(&visitor);
EXPECT_EQ(4u, visitor.getIntersections().size()) << "Left Box Incorrect";
Aabbd middleBox(Vector3d(1.8, -0.02, -0.02), Vector3d(4.4, 0.02, 0.02));
visitor.setAabb(middleBox);
tree->getRoot()->accept(&visitor);
EXPECT_EQ(3u, visitor.getIntersections().size()) << "Middle Box Incorrect";
Aabbd rightBox(Vector3d(2.8, -0.02, -0.02), Vector3d(6.4, 0.02, 0.02));
visitor.setAabb(rightBox);
tree->getRoot()->accept(&visitor);
EXPECT_EQ(4u, visitor.getIntersections().size()) << "Right Box Incorrect";
}
TEST(AabbTreeTests, MeshIntersectionTest)
{
SurgSim::Framework::ApplicationData data("config.txt");
auto tree = std::make_shared<AabbTree>(3);
std::string filename = data.findFile("Geometry/arm_collision.ply");
ASSERT_FALSE(filename.empty());
auto mesh = loadTriangleMesh(filename);
std::cout << mesh->getNumTriangles() << std::endl;
Aabbd expectedBigBox;
for (size_t i = 0; i < mesh->getNumTriangles(); ++i)
{
auto triangle = mesh->getTriangle(i);
std::array<Vector3d, 3> vertices =
{
mesh->getVertex(triangle.verticesId[0]).position,
mesh->getVertex(triangle.verticesId[1]).position,
mesh->getVertex(triangle.verticesId[2]).position
};
Aabbd aabb(SurgSim::Math::makeAabb(vertices[0], vertices[1], vertices[2]));
expectedBigBox.extend(aabb);
tree->add(std::move(aabb), i);
}
Aabbd bigBox = tree->getAabb();
EXPECT_TRUE(expectedBigBox.isApprox(bigBox));
AabbTreeIntersectionVisitor intersector(bigBox);
SurgSim::Framework::Timer timer;
timer.start();
tree->getRoot()->accept(&intersector);
timer.endFrame();
std::cout << timer.getCumulativeTime() << std::endl;
std::cout << intersector.getIntersections().size() << std::endl;
EXPECT_EQ(mesh->getNumTriangles(), intersector.getIntersections().size());
}
template <typename NodeType>
class TreeLeavesVisitor : public TreeVisitor
{
public:
virtual bool handle(TreeNode* node) override
{
SURGSIM_FAILURE() << "Function " __FUNCTION__ " not implemented";
return false;
}
virtual bool handle(NodeType* node) override
{
if (node->getNumChildren() == 0)
{
leaves.push_back(node);
}
return true;
}
std::vector<NodeType*> leaves;
};
template <typename PairTypeLhs, typename PairTypeRhs>
static typename std::vector<PairTypeLhs>::const_iterator getEquivalentPair(const std::vector<PairTypeLhs>& list,
const PairTypeRhs& item)
{
return std::find_if(list.cbegin(), list.cend(),
[&item] (const PairTypeLhs& pair)
{
return (pair.first->getAabb().isApprox(item.first->getAabb())
&& pair.second->getAabb().isApprox(item.second->getAabb()))
|| (pair.first->getAabb().isApprox(item.second->getAabb())
&& pair.second->getAabb().isApprox(item.first->getAabb()));
}
);
}
TEST(AabbTreeTests, SpatialJoinTest)
{
const std::string fileName = "MeshShapeData/staple_collision.ply";
auto meshA = std::make_shared<SurgSim::Math::MeshShape>();
meshA->setFileName(fileName);
auto meshB = std::make_shared<SurgSim::Math::MeshShape>();
meshB->setFileName(fileName);
RigidTransform3d rhsPose = SurgSim::Math::makeRigidTranslation(Vector3d(0.005, 0.0, 0.0));
meshB->getMesh()->setTransformedFrom(rhsPose, *meshA->getMesh());
auto aabbA = meshA->createAabbTree();
auto aabbB = meshB->createAabbTree();
auto actualIntersection = spatialJoin(aabbA, aabbB);
TreeLeavesVisitor<SurgSim::DataStructures::AabbTreeNode> leavesVisitorA;
std::static_pointer_cast<SurgSim::DataStructures::AabbTreeNode>(aabbA->getRoot())->accept(&leavesVisitorA);
auto& leavesA = leavesVisitorA.leaves;
TreeLeavesVisitor<SurgSim::DataStructures::AabbTreeNode> leavesVisitorB;
std::static_pointer_cast<SurgSim::DataStructures::AabbTreeNode>(aabbB->getRoot())->accept(&leavesVisitorB);
auto& leavesB = leavesVisitorB.leaves;
std::vector<std::pair<SurgSim::DataStructures::AabbTreeNode*, SurgSim::DataStructures::AabbTreeNode*>>
expectedIntersection;
for (auto leafA = leavesA.begin(); leafA != leavesA.end(); ++leafA)
{
for (auto leafB = leavesB.begin(); leafB != leavesB.end(); ++leafB)
{
if (SurgSim::Math::doAabbIntersect((*leafA)->getAabb(), (*leafB)->getAabb()))
{
expectedIntersection.emplace_back(*leafA, *leafB);
}
}
}
{
SCOPED_TRACE("Equivalent sets");
ASSERT_GT(expectedIntersection.size(), 0u);
ASSERT_EQ(expectedIntersection.size(), actualIntersection.size());
// Sets A and B are equal if and only if A is a subset of B and B is a subset of A.
for (auto it = actualIntersection.begin(); it != actualIntersection.end(); ++it)
{
EXPECT_TRUE(getEquivalentPair(expectedIntersection, *it) != expectedIntersection.cend());
}
for (auto it = expectedIntersection.begin(); it != expectedIntersection.end(); ++it)
{
EXPECT_TRUE(getEquivalentPair(actualIntersection, *it) != actualIntersection.cend());
}
}
{
SCOPED_TRACE("Inequivalent sets.");
auto newNode = std::make_shared<SurgSim::DataStructures::AabbTreeNode>();
newNode->addData(
SurgSim::Math::makeAabb(Vector3d(-0.1, 0.3, 5.3), Vector3d(5.4, -5.8, 1.1), Vector3d(0, 0.5, 11)), 4543);
expectedIntersection.emplace_back(newNode.get(), expectedIntersection.front().second);
actualIntersection.emplace_back(newNode, actualIntersection.back().first);
ASSERT_GT(expectedIntersection.size(), 0u);
ASSERT_EQ(expectedIntersection.size(), actualIntersection.size());
EXPECT_FALSE(getEquivalentPair(expectedIntersection, actualIntersection.back()) != expectedIntersection.cend());
EXPECT_FALSE(getEquivalentPair(actualIntersection, expectedIntersection.back()) != actualIntersection.cend());
}
}
}
}
<commit_msg>AabbTreeTests, fix GCC compile bug<commit_after>#include "../PlyReader.h"
#include "../TriangleMeshPlyReaderDelegate.h"
// This file is a part of the OpenSurgSim project.
// Copyright 2013, SimQuest Solutions 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.
#include <gtest/gtest.h>
#include "SurgSim/DataStructures/AabbTree.h"
#include "SurgSim/DataStructures/AabbTreeNode.h"
#include "SurgSim/DataStructures/TriangleMeshBase.h"
#include "SurgSim/DataStructures/TriangleMeshPlyReaderDelegate.h"
#include "SurgSim/DataStructures/AabbTreeIntersectionVisitor.h"
#include "SurgSim/Math/Aabb.h"
#include "SurgSim/Math/MeshShape.h"
#include "SurgSim/Math/Vector.h"
#include "SurgSim/Math/RigidTransform.h"
#include "SurgSim/Framework/ApplicationData.h"
#include "SurgSim/Framework/Timer.h"
#include "SurgSim/Testing/MathUtilities.h"
using SurgSim::Math::Aabbd;
using SurgSim::Math::RigidTransform3d;
using SurgSim::Math::Vector3d;
namespace
{
std::shared_ptr<SurgSim::DataStructures::TriangleMeshBase<
SurgSim::DataStructures::EmptyData, SurgSim::DataStructures::EmptyData, SurgSim::DataStructures::EmptyData>>
loadTriangleMesh(const std::string& fileName)
{
auto triangleMeshDelegate = std::make_shared<SurgSim::DataStructures::TriangleMeshPlyReaderDelegate>();
SurgSim::DataStructures::PlyReader reader(fileName);
SURGSIM_ASSERT(reader.setDelegate(triangleMeshDelegate)) << "The input file " << fileName << " is malformed.";
reader.parseFile();
return triangleMeshDelegate->getMesh();
}
}
namespace SurgSim
{
namespace DataStructures
{
TEST(AabbTreeTests, InitTest)
{
ASSERT_NO_THROW({AabbTree tree(3);});
auto tree = std::make_shared<AabbTree>(3);
EXPECT_EQ(3u, tree->getMaxObjectsPerNode());
EXPECT_NE(nullptr, tree->getRoot());
}
TEST(AabbTreeTests, AddTest)
{
auto tree = std::make_shared<AabbTree>(3);
Aabbd one(Vector3d(-1.0, -1.0, -1.0), Vector3d(0.0, 0.0, 0.0));
Aabbd two(Vector3d(0.0, 0.0, 0.0), Vector3d(1.0, 1.0, 1.0));
EXPECT_NO_THROW(tree->add(one, 0));
EXPECT_NO_THROW(tree->add(one, 1));
EXPECT_NO_THROW(tree->add(two, 2));
EXPECT_NO_THROW(tree->add(two, 3));
EXPECT_EQ(2u, tree->getRoot()->getNumChildren());
}
TEST(AabbTreeTests, BuildTest)
{
SurgSim::Framework::ApplicationData data("config.txt");
auto tree = std::make_shared<AabbTree>(3);
std::string filename = data.findFile("Geometry/arm_collision.ply");
ASSERT_FALSE(filename.empty());
auto mesh = loadTriangleMesh(filename);
std::cout << mesh->getNumTriangles() << std::endl;
SurgSim::Framework::Timer timer;
for (size_t i = 0; i < mesh->getNumTriangles(); ++i)
{
auto triangle = mesh->getTriangle(i);
Aabbd aabb(SurgSim::Math::makeAabb(
mesh->getVertex(triangle.verticesId[0]).position,
mesh->getVertex(triangle.verticesId[1]).position,
mesh->getVertex(triangle.verticesId[2]).position));
tree->add(aabb, i);
}
timer.endFrame();
std::cout << timer.getCumulativeTime() << std::endl;
}
TEST(AabbTreeTests, EasyIntersectionTest)
{
auto tree = std::make_shared<AabbTree>(3);
Aabbd bigBox;
for (int i = 0; i <= 6; ++i)
{
Aabbd aabb(Vector3d(static_cast<double>(i) - 0.01, -0.01, -0.01),
Vector3d(static_cast<double>(i) + 0.01, 0.01, 0.01));
bigBox.extend(aabb);
tree->add(aabb, i);
}
EXPECT_TRUE(bigBox.isApprox(tree->getAabb())) << bigBox << ", " << tree->getAabb();
AabbTreeIntersectionVisitor visitor(bigBox);
tree->getRoot()->accept(&visitor);
EXPECT_EQ(7u, visitor.getIntersections().size());
Aabbd leftBox(Vector3d(0.0, -0.02, -0.02), Vector3d(3.4, 0.02, 0.02));
visitor.setAabb(leftBox);
tree->getRoot()->accept(&visitor);
EXPECT_EQ(4u, visitor.getIntersections().size()) << "Left Box Incorrect";
Aabbd middleBox(Vector3d(1.8, -0.02, -0.02), Vector3d(4.4, 0.02, 0.02));
visitor.setAabb(middleBox);
tree->getRoot()->accept(&visitor);
EXPECT_EQ(3u, visitor.getIntersections().size()) << "Middle Box Incorrect";
Aabbd rightBox(Vector3d(2.8, -0.02, -0.02), Vector3d(6.4, 0.02, 0.02));
visitor.setAabb(rightBox);
tree->getRoot()->accept(&visitor);
EXPECT_EQ(4u, visitor.getIntersections().size()) << "Right Box Incorrect";
}
TEST(AabbTreeTests, MeshIntersectionTest)
{
SurgSim::Framework::ApplicationData data("config.txt");
auto tree = std::make_shared<AabbTree>(3);
std::string filename = data.findFile("Geometry/arm_collision.ply");
ASSERT_FALSE(filename.empty());
auto mesh = loadTriangleMesh(filename);
std::cout << mesh->getNumTriangles() << std::endl;
Aabbd expectedBigBox;
for (size_t i = 0; i < mesh->getNumTriangles(); ++i)
{
auto triangle = mesh->getTriangle(i);
std::array<Vector3d, 3> vertices =
{
mesh->getVertex(triangle.verticesId[0]).position,
mesh->getVertex(triangle.verticesId[1]).position,
mesh->getVertex(triangle.verticesId[2]).position
};
Aabbd aabb(SurgSim::Math::makeAabb(vertices[0], vertices[1], vertices[2]));
expectedBigBox.extend(aabb);
tree->add(std::move(aabb), i);
}
Aabbd bigBox = tree->getAabb();
EXPECT_TRUE(expectedBigBox.isApprox(bigBox));
AabbTreeIntersectionVisitor intersector(bigBox);
SurgSim::Framework::Timer timer;
timer.start();
tree->getRoot()->accept(&intersector);
timer.endFrame();
std::cout << timer.getCumulativeTime() << std::endl;
std::cout << intersector.getIntersections().size() << std::endl;
EXPECT_EQ(mesh->getNumTriangles(), intersector.getIntersections().size());
}
template <typename NodeType>
class TreeLeavesVisitor : public TreeVisitor
{
public:
virtual bool handle(TreeNode* node) override
{
SURGSIM_FAILURE() << "Function " << __FUNCTION__ << " not implemented";
return false;
}
virtual bool handle(NodeType* node) override
{
if (node->getNumChildren() == 0)
{
leaves.push_back(node);
}
return true;
}
std::vector<NodeType*> leaves;
};
template <typename PairTypeLhs, typename PairTypeRhs>
static typename std::vector<PairTypeLhs>::const_iterator getEquivalentPair(const std::vector<PairTypeLhs>& list,
const PairTypeRhs& item)
{
return std::find_if(list.cbegin(), list.cend(),
[&item] (const PairTypeLhs& pair)
{
return (pair.first->getAabb().isApprox(item.first->getAabb())
&& pair.second->getAabb().isApprox(item.second->getAabb()))
|| (pair.first->getAabb().isApprox(item.second->getAabb())
&& pair.second->getAabb().isApprox(item.first->getAabb()));
}
);
}
TEST(AabbTreeTests, SpatialJoinTest)
{
const std::string fileName = "MeshShapeData/staple_collision.ply";
auto meshA = std::make_shared<SurgSim::Math::MeshShape>();
meshA->setFileName(fileName);
auto meshB = std::make_shared<SurgSim::Math::MeshShape>();
meshB->setFileName(fileName);
RigidTransform3d rhsPose = SurgSim::Math::makeRigidTranslation(Vector3d(0.005, 0.0, 0.0));
meshB->getMesh()->setTransformedFrom(rhsPose, *meshA->getMesh());
auto aabbA = meshA->createAabbTree();
auto aabbB = meshB->createAabbTree();
auto actualIntersection = spatialJoin(aabbA, aabbB);
TreeLeavesVisitor<SurgSim::DataStructures::AabbTreeNode> leavesVisitorA;
std::static_pointer_cast<SurgSim::DataStructures::AabbTreeNode>(aabbA->getRoot())->accept(&leavesVisitorA);
auto& leavesA = leavesVisitorA.leaves;
TreeLeavesVisitor<SurgSim::DataStructures::AabbTreeNode> leavesVisitorB;
std::static_pointer_cast<SurgSim::DataStructures::AabbTreeNode>(aabbB->getRoot())->accept(&leavesVisitorB);
auto& leavesB = leavesVisitorB.leaves;
std::vector<std::pair<SurgSim::DataStructures::AabbTreeNode*, SurgSim::DataStructures::AabbTreeNode*>>
expectedIntersection;
for (auto leafA = leavesA.begin(); leafA != leavesA.end(); ++leafA)
{
for (auto leafB = leavesB.begin(); leafB != leavesB.end(); ++leafB)
{
if (SurgSim::Math::doAabbIntersect((*leafA)->getAabb(), (*leafB)->getAabb()))
{
expectedIntersection.emplace_back(*leafA, *leafB);
}
}
}
{
SCOPED_TRACE("Equivalent sets");
ASSERT_GT(expectedIntersection.size(), 0u);
ASSERT_EQ(expectedIntersection.size(), actualIntersection.size());
// Sets A and B are equal if and only if A is a subset of B and B is a subset of A.
for (auto it = actualIntersection.begin(); it != actualIntersection.end(); ++it)
{
EXPECT_TRUE(getEquivalentPair(expectedIntersection, *it) != expectedIntersection.cend());
}
for (auto it = expectedIntersection.begin(); it != expectedIntersection.end(); ++it)
{
EXPECT_TRUE(getEquivalentPair(actualIntersection, *it) != actualIntersection.cend());
}
}
{
SCOPED_TRACE("Inequivalent sets.");
auto newNode = std::make_shared<SurgSim::DataStructures::AabbTreeNode>();
newNode->addData(
SurgSim::Math::makeAabb(Vector3d(-0.1, 0.3, 5.3), Vector3d(5.4, -5.8, 1.1), Vector3d(0, 0.5, 11)), 4543);
expectedIntersection.emplace_back(newNode.get(), expectedIntersection.front().second);
actualIntersection.emplace_back(newNode, actualIntersection.back().first);
ASSERT_GT(expectedIntersection.size(), 0u);
ASSERT_EQ(expectedIntersection.size(), actualIntersection.size());
EXPECT_FALSE(getEquivalentPair(expectedIntersection, actualIntersection.back()) != expectedIntersection.cend());
EXPECT_FALSE(getEquivalentPair(actualIntersection, expectedIntersection.back()) != actualIntersection.cend());
}
}
}
}
<|endoftext|> |
<commit_before>#include <cmath>
#include <iostream>
#include <string>
#include <TCanvas.h>
#include <TEfficiency.h>
#include <TFile.h>
#include <TList.h>
#include <TH1D.h>
#include <TH3D.h>
#include <AliPID.h>
#include "AliAnalysisTaskLFefficiencies.h"
void DivideBinomial(TH1* num, const TH1* den) {
for (int iBin = 1; iBin <= num->GetNbinsX(); ++iBin) {
const double n = num->GetBinContent(iBin);
const double d = den->GetBinContent(iBin);
const double eff = (d > 1.e-24) ? n / d : 0.;
const double err_eff = (d > 1.e-24 && eff < 1) ? std::sqrt(eff * (1. - eff) / d) : 0.;
num->SetBinContent(iBin, eff);
num->SetBinError(iBin, err_eff);
}
}
bool endsWith(const std::string &mainStr, const std::string &&toMatch)
{
if(mainStr.size() >= toMatch.size() &&
mainStr.compare(mainStr.size() - toMatch.size(), toMatch.size(), toMatch) == 0)
return true;
else
return false;
}
void ComputeLFefficiencies(std::string filename = "AnalysisResults") {
if (endsWith(filename,".root")) {
for (int i = 0; i < 5; ++i) filename.pop_back();
}
TFile input_file((filename + ".root").data());
TList* input_list = static_cast<TList*>(input_file.Get("PWGLF_QA/efficiencies"));
if (!input_list) {
::Fatal("ComputeLFefficiencies","Missing input list, check the input file.");
}
TCanvas cv("canvas");
TCanvas cv_eta("canvas_eta");
TCanvas cv_rec("reconstructed");
TCanvas cv_gen("generated");
cv.Print((filename + "_y.pdf[").data(),"pdf");
cv_eta.Print((filename + "_eta.pdf[").data(),"pdf");
TFile output_file((filename + "_out.root").data(),"recreate");
for (int iSpecies = 2; iSpecies < AliPID::kSPECIESC; ++iSpecies) {
for (int iCharge = 0; iCharge < 2; ++iCharge) {
cv.cd();
cv.DrawFrame(0.,0.,6.,1.1,Form("%s %s;#it{p}_{T} (GeV/#it{c}); Efficiency",AliPID::ParticleLatexName(iSpecies),AliAnalysisTaskLFefficiencies::fPosNeg[iCharge].data()));
TH3D* gen3D = static_cast<TH3D*>(input_list->FindObject(Form("Gen_%s_%s",AliPID::ParticleShortName(iSpecies),AliAnalysisTaskLFefficiencies::fPosNeg[iCharge].data())));
TH1D* gen = gen3D->ProjectionZ(Form("Gen_%s_%s_pz",AliPID::ParticleShortName(iSpecies),AliAnalysisTaskLFefficiencies::fPosNeg[iCharge].data()),3,7);
cv_eta.cd();
cv_eta.DrawFrame(0.,0.,6.,1.1,Form("%s %s |#eta|<0.8;#it{p}_{T} (GeV/#it{c}); Efficiency",AliPID::ParticleLatexName(iSpecies),AliAnalysisTaskLFefficiencies::fPosNeg[iCharge].data()));
TH3D* gen3Deta = static_cast<TH3D*>(input_list->FindObject(Form("GenEta_%s_%s",AliPID::ParticleShortName(iSpecies),AliAnalysisTaskLFefficiencies::fPosNeg[iCharge].data())));
TH1D* genEta = gen3Deta->ProjectionZ(Form("GenEta_%s_%s_pz",AliPID::ParticleShortName(iSpecies),AliAnalysisTaskLFefficiencies::fPosNeg[iCharge].data()),2,9);
for (int iCut = 0; iCut < AliAnalysisTaskLFefficiencies::fNcuts; ++iCut) {
cv.cd();
TH3D* rec3D = static_cast<TH3D*>(input_list->FindObject(Form("Rec_%s_%s_%i",AliPID::ParticleShortName(iSpecies),AliAnalysisTaskLFefficiencies::fPosNeg[iCharge].data(),iCut)));
TH1D* eff = rec3D->ProjectionZ(Form("Eff_%s_%s_%i",AliPID::ParticleShortName(iSpecies),AliAnalysisTaskLFefficiencies::fPosNeg[iCharge].data(),iCut),3,7);
DivideBinomial(eff,gen);
eff->Draw("same PLC PMC");
cv_eta.cd();
TH3D* rec3Deta = static_cast<TH3D*>(input_list->FindObject(Form("RecEta_%s_%s_%i",AliPID::ParticleShortName(iSpecies),AliAnalysisTaskLFefficiencies::fPosNeg[iCharge].data(),iCut)));
TH1D* effEta = rec3Deta->ProjectionZ(Form("EffEta_%s_%s_%i",AliPID::ParticleShortName(iSpecies),AliAnalysisTaskLFefficiencies::fPosNeg[iCharge].data(),iCut),2,9);
DivideBinomial(effEta,genEta);
effEta->Draw("same PLC PMC");
output_file.cd();
eff->Write();
effEta->Write();
}
cv.cd();
cv.BuildLegend();
cv.Print((filename + "_y.pdf").data(),"pdf");
cv_eta.cd();
cv_eta.BuildLegend();
cv_eta.Print((filename + "_eta.pdf").data(),"pdf");
}
}
cv.Print((filename + "_y.pdf]").data(),"pdf");
cv_rec.Print((filename + "_eta.pdf]").data(),"pdf");
output_file.Close();
}
<commit_msg>Add comparison between datasets in the QA macro<commit_after>#include <array>
#include <cmath>
#include <iostream>
#include <string>
#include <utility>
#include <TCanvas.h>
#include <TEfficiency.h>
#include <TFile.h>
#include <TList.h>
#include <TH1D.h>
#include <TH3D.h>
#include <AliPID.h>
#include "AliAnalysisTaskLFefficiencies.h"
void DivideBinomial(TH1* num, const TH1* den) {
for (int iBin = 1; iBin <= num->GetNbinsX(); ++iBin) {
const double n = num->GetBinContent(iBin);
const double d = den->GetBinContent(iBin);
const double eff = (d > 1.e-24) ? n / d : 0.;
const double err_eff = (d > 1.e-24 && eff < 1) ? std::sqrt(eff * (1. - eff) / d) : 0.;
num->SetBinContent(iBin, eff);
num->SetBinError(iBin, err_eff);
}
}
bool endsWith(const std::string &mainStr, const std::string &&toMatch)
{
if(mainStr.size() >= toMatch.size() &&
mainStr.compare(mainStr.size() - toMatch.size(), toMatch.size(), toMatch) == 0)
return true;
else
return false;
}
std::pair<std::array<std::vector<TH1D*>,AliPID::kSPECIESC * 2 - 4>,std::array<std::vector<TH1D*>,AliPID::kSPECIESC * 2 - 4>>
ComputeLFefficiencies(std::string filename = "AnalysisResults") {
if (endsWith(filename,".root")) {
for (int i = 0; i < 5; ++i) filename.pop_back();
}
TFile input_file((filename + ".root").data());
TList* input_list = static_cast<TList*>(input_file.Get("PWGLF_QA/efficiencies"));
if (!input_list) {
::Fatal("ComputeLFefficiencies","Missing input list, check the input file.");
}
std::pair<std::array<std::vector<TH1D*>,AliPID::kSPECIESC * 2 - 4>,std::array<std::vector<TH1D*>,AliPID::kSPECIESC * 2 - 4>> vec;
TCanvas cv("canvas");
TCanvas cv_eta("canvas_eta");
TCanvas cv_rec("reconstructed");
TCanvas cv_gen("generated");
cv.Print((filename + "_y.pdf[").data(),"pdf");
cv_eta.Print((filename + "_eta.pdf[").data(),"pdf");
TFile output_file((filename + "_out.root").data(),"recreate");
for (int iSpecies = 2; iSpecies < AliPID::kSPECIESC; ++iSpecies) {
for (int iCharge = 0; iCharge < 2; ++iCharge) {
cv.cd();
cv.DrawFrame(0.,0.,6.,1.1,Form("%s %s;#it{p}_{T} (GeV/#it{c}); Efficiency",AliPID::ParticleLatexName(iSpecies),AliAnalysisTaskLFefficiencies::fPosNeg[iCharge].data()));
TH3D* gen3D = static_cast<TH3D*>(input_list->FindObject(Form("Gen_%s_%s",AliPID::ParticleShortName(iSpecies),AliAnalysisTaskLFefficiencies::fPosNeg[iCharge].data())));
TH1D* gen = gen3D->ProjectionZ(Form("Gen_%s_%s_pz",AliPID::ParticleShortName(iSpecies),AliAnalysisTaskLFefficiencies::fPosNeg[iCharge].data()),3,7);
cv_eta.cd();
cv_eta.DrawFrame(0.,0.,6.,1.1,Form("%s %s |#eta|<0.8;#it{p}_{T} (GeV/#it{c}); Efficiency",AliPID::ParticleLatexName(iSpecies),AliAnalysisTaskLFefficiencies::fPosNeg[iCharge].data()));
TH3D* gen3Deta = static_cast<TH3D*>(input_list->FindObject(Form("GenEta_%s_%s",AliPID::ParticleShortName(iSpecies),AliAnalysisTaskLFefficiencies::fPosNeg[iCharge].data())));
TH1D* genEta = gen3Deta->ProjectionZ(Form("GenEta_%s_%s_pz",AliPID::ParticleShortName(iSpecies),AliAnalysisTaskLFefficiencies::fPosNeg[iCharge].data()),2,9);
for (int iCut = 0; iCut < AliAnalysisTaskLFefficiencies::fNcuts; ++iCut) {
cv.cd();
TH3D* rec3D = static_cast<TH3D*>(input_list->FindObject(Form("Rec_%s_%s_%i",AliPID::ParticleShortName(iSpecies),AliAnalysisTaskLFefficiencies::fPosNeg[iCharge].data(),iCut)));
TH1D* eff = rec3D->ProjectionZ(Form("Eff_%s_%s_%i",AliPID::ParticleShortName(iSpecies),AliAnalysisTaskLFefficiencies::fPosNeg[iCharge].data(),iCut),3,7);
DivideBinomial(eff,gen);
eff->Draw("same PLC PMC");
vec.first[(iSpecies - 2) * 2 + iCharge].push_back(static_cast<TH1D*>(eff->Clone()));
vec.first[(iSpecies - 2) * 2 + iCharge].back()->SetDirectory(0);
cv_eta.cd();
TH3D* rec3Deta = static_cast<TH3D*>(input_list->FindObject(Form("RecEta_%s_%s_%i",AliPID::ParticleShortName(iSpecies),AliAnalysisTaskLFefficiencies::fPosNeg[iCharge].data(),iCut)));
TH1D* effEta = rec3Deta->ProjectionZ(Form("EffEta_%s_%s_%i",AliPID::ParticleShortName(iSpecies),AliAnalysisTaskLFefficiencies::fPosNeg[iCharge].data(),iCut),2,9);
DivideBinomial(effEta,genEta);
effEta->Draw("same PLC PMC");
output_file.cd();
eff->Write();
effEta->Write();
vec.second[(iSpecies - 2) * 2 + iCharge].push_back(static_cast<TH1D*>(eff->Clone()));
vec.second[(iSpecies - 2) * 2 + iCharge].back()->SetDirectory(0);
}
cv.cd();
cv.BuildLegend();
cv.Print((filename + "_y.pdf").data(),"pdf");
cv_eta.cd();
cv_eta.BuildLegend();
cv_eta.Print((filename + "_eta.pdf").data(),"pdf");
}
}
cv.Print((filename + "_y.pdf]").data(),"pdf");
cv_rec.Print((filename + "_eta.pdf]").data(),"pdf");
output_file.Close();
return vec;
}
void ComputeLFefficiencies(std::string filename0, std::string filename1) {
std::array<std::string, 2> filenames { filename0, filename1 };
std::pair<std::array<std::vector<TH1D*>,AliPID::kSPECIESC * 2 - 4>,std::array<std::vector<TH1D*>,AliPID::kSPECIESC * 2 - 4>> efficiencies[2];
for (size_t iFile = 0; iFile < filenames.size(); ++iFile) {
std::string& fname = filenames[iFile];
efficiencies[iFile] = ComputeLFefficiencies(fname);
}
TCanvas cv_y("canvas_y");
TCanvas cv_eta("canvas_eta");
cv_y.Print("Comparison_y.pdf[","pdf");
cv_eta.Print("Comparison_eta.pdf[","pdf");
for (int iSpecies = 2; iSpecies < AliPID::kSPECIESC; ++iSpecies) {
for (int iCharge = 0; iCharge < 2; ++iCharge) {
cv_y.cd();
cv_y.DrawFrame(0.,0.,6.,2.1,Form("%s %s;#it{p}_{T} (GeV/#it{c}); Ratio",AliPID::ParticleLatexName(iSpecies),AliAnalysisTaskLFefficiencies::fPosNeg[iCharge].data()));
cv_eta.cd();
cv_eta.DrawFrame(0.,0.,6.,2.1,Form("%s %s |#eta|<0.8;#it{p}_{T} (GeV/#it{c}); Ratio",AliPID::ParticleLatexName(iSpecies),AliAnalysisTaskLFefficiencies::fPosNeg[iCharge].data()));
for (size_t iHist = 0; iHist < efficiencies[0].first[(iSpecies-2)*2+iCharge].size(); ++iHist) {
cv_y.cd();
efficiencies[0].first[(iSpecies-2)*2+iCharge][iHist]->Divide(efficiencies[1].first[(iSpecies-2)*2+iCharge][iHist]);
efficiencies[0].first[(iSpecies-2)*2+iCharge][iHist]->Draw("PMC PLC same");
cv_eta.cd();
efficiencies[0].second[(iSpecies-2)*2+iCharge][iHist]->Divide(efficiencies[1].second[(iSpecies-2)*2+iCharge][iHist]);
efficiencies[0].second[(iSpecies-2)*2+iCharge][iHist]->Draw("PMC PLC same");
}
cv_y.BuildLegend();
cv_eta.BuildLegend();
cv_y.Print("Comparison_y.pdf","pdf");
cv_eta.Print("Comparison_eta.pdf","pdf");
}
}
cv_y.Print("Comparison_y.pdf]","pdf");
cv_eta.Print("Comparison_eta.pdf]","pdf");
}<|endoftext|> |
<commit_before>#line 2 "togo/resource_manager.cpp"
/**
@copyright MIT license; see @ref index or the accompanying LICENSE file.
*/
#include <togo/config.hpp>
#include <togo/assert.hpp>
#include <togo/memory.hpp>
#include <togo/hash_map.hpp>
#include <togo/log.hpp>
#include <togo/resource_types.hpp>
#include <togo/resource_package.hpp>
#include <togo/resource_manager.hpp>
namespace togo {
namespace resource_manager {
static bool find_resource(
ResourceManager& rm,
ResourceType const type,
ResourceNameHash const name_hash,
ResourcePackage*& package,
ResourcePackage::EntryNode*& node
) {
// TODO: Tag filter
ResourcePackage::EntryNode* it_node;
for (
auto* it = array::end(rm._packages) - 1;
it >= array::begin(rm._packages);
--it
) {
it_node = resource_package::find_resource(**it, type, name_hash);
if (it_node) {
package = *it;
node = it_node;
return true;
}
}
return false;
}
} // namespace resource_manager
ResourceManager::~ResourceManager() {
resource_manager::clear_packages(*this);
}
ResourceManager::ResourceManager(Allocator& allocator)
: _handlers(allocator)
, _resources(allocator)
, _packages(allocator)
{
hash_map::reserve(_handlers, 16);
}
void resource_manager::register_handler(
ResourceManager& rm,
ResourceHandler const& handler,
void* type_data
) {
TOGO_ASSERT(
handler.func_load && handler.func_unload,
"load_func and unload_func must be assigned in handler"
);
TOGO_ASSERT(
!hash_map::has(rm._handlers, handler.type),
"type has already been registered"
);
hash_map::push(rm._handlers, handler.type, {handler, type_data});
}
bool resource_manager::has_handler(
ResourceManager const& rm,
ResourceType type
) {
return hash_map::has(rm._handlers, type);
}
hash64 resource_manager::add_package(
ResourceManager& rm,
StringRef const& root
) {
// NB: ResourcePackage ctor does modify root
Allocator& allocator = *rm._packages._allocator;
ResourcePackage* const pkg = TOGO_CONSTRUCT(allocator,
ResourcePackage, root, allocator
);
for (auto const* it_pkg : rm._packages) {
TOGO_ASSERTF(
it_pkg->_root_hash != pkg->_root_hash,
"package at '%.*s' has already been added",
root.size, root.data
);
}
array::push_back(rm._packages, pkg);
resource_package::load_manifest(*pkg, rm);
return resource_package::root_hash(*pkg);
}
void resource_manager::remove_package(
ResourceManager& rm,
hash64 const root_hash
) {
Allocator& allocator = *rm._packages._allocator;
for (unsigned i = 0; i < array::size(rm._packages); ++i) {
auto* const pkg = rm._packages[i];
if (root_hash == pkg->_root_hash) {
// TODO: Unload active resources from the package
TOGO_DESTROY(allocator, pkg);
array::remove(rm._packages, i);
return;
}
}
TOGO_ASSERT(false, "package not found");
}
void resource_manager::clear_packages(ResourceManager& rm) {
Allocator& allocator = *rm._packages._allocator;
// TODO: Unload all active resources
for (auto* pkg : rm._packages) {
TOGO_DESTROY(allocator, pkg);
}
array::clear(rm._packages);
}
void* resource_manager::load_resource(
ResourceManager& rm,
ResourceType const type,
ResourceNameHash const name_hash
) {
TOGO_DEBUG_ASSERTE(hash_map::has(rm._handlers, type));
auto* tr = hash_map::get(rm._resources, name_hash);
if (!tr) {
auto const* const handler = hash_map::get(rm._handlers, type);
ResourcePackage* pkg = nullptr;
ResourcePackage::EntryNode* node = nullptr;
if (!find_resource(rm, type, name_hash, pkg, node)) {
TOGO_LOG_ERRORF(
"resource not found: %08x %016lx\n",
type, name_hash
);
return nullptr;
}
StringRef const pkg_root_ref{resource_package::root(*pkg)};
StringRef const rpath_ref{node->value.path, node->value.path_size};
IReader* stream = resource_package::open_resource_stream(
*pkg, node
);
if (!stream) {
TOGO_LOG_ERRORF(
"failed to open resource stream from package '%.*s': '%.*s'\n",
pkg_root_ref.size, pkg_root_ref.data,
rpath_ref.size, rpath_ref.data
);
return nullptr;
}
void* const load_value = handler->handler.func_load(
handler->type_data, rm, name_hash, *stream
);
resource_package::close_resource_stream(*pkg);
if (!load_value) {
TOGO_LOG_ERRORF(
"failed to load resource from package '%.*s': '%.*s'\n",
pkg_root_ref.size, pkg_root_ref.data,
rpath_ref.size, rpath_ref.data
);
return nullptr;
}
tr = &hash_map::push(
rm._resources, name_hash, {load_value, type}
);
}
return (tr && tr->type == type) ? tr->value : nullptr;
}
void resource_manager::unload_resource(
ResourceManager& rm,
ResourceType const type,
ResourceNameHash const name_hash
) {
TOGO_DEBUG_ASSERTE(hash_map::has(rm._handlers, type));
auto* const node = hash_map::get_node(rm._resources, name_hash);
if (!node || node->value.type != type) {
return;
}
auto const* const handler = hash_map::get(rm._handlers, type);
handler->handler.func_unload(
handler->type_data, rm, name_hash, node->value.value
);
hash_map::remove(rm._resources, node);
}
void* resource_manager::get_resource(
ResourceManager& rm,
ResourceType const type,
ResourceNameHash const name_hash
) {
TOGO_DEBUG_ASSERTE(hash_map::has(rm._handlers, type));
auto* const tr = hash_map::get(rm._resources, name_hash);
return (tr && tr->type == type) ? tr->value : nullptr;
}
} // namespace togo
<commit_msg>resource_manager: corrected register_handler() error message; tidy.<commit_after>#line 2 "togo/resource_manager.cpp"
/**
@copyright MIT license; see @ref index or the accompanying LICENSE file.
*/
#include <togo/config.hpp>
#include <togo/assert.hpp>
#include <togo/memory.hpp>
#include <togo/array.hpp>
#include <togo/hash_map.hpp>
#include <togo/log.hpp>
#include <togo/resource_types.hpp>
#include <togo/resource_package.hpp>
#include <togo/resource_manager.hpp>
namespace togo {
namespace resource_manager {
static bool find_resource(
ResourceManager& rm,
ResourceType const type,
ResourceNameHash const name_hash,
ResourcePackage*& package,
ResourcePackage::EntryNode*& node
) {
// TODO: Tag filter
ResourcePackage::EntryNode* it_node;
for (
auto* it = array::end(rm._packages) - 1;
it >= array::begin(rm._packages);
--it
) {
it_node = resource_package::find_resource(**it, type, name_hash);
if (it_node) {
package = *it;
node = it_node;
return true;
}
}
return false;
}
} // namespace resource_manager
ResourceManager::~ResourceManager() {
resource_manager::clear_packages(*this);
}
ResourceManager::ResourceManager(Allocator& allocator)
: _handlers(allocator)
, _resources(allocator)
, _packages(allocator)
{
hash_map::reserve(_handlers, 16);
}
void resource_manager::register_handler(
ResourceManager& rm,
ResourceHandler const& handler,
void* type_data
) {
TOGO_ASSERT(
handler.func_load && handler.func_unload,
"func_load and func_unload must be assigned in handler"
);
TOGO_ASSERT(
!hash_map::has(rm._handlers, handler.type),
"type has already been registered"
);
hash_map::push(rm._handlers, handler.type, {handler, type_data});
}
bool resource_manager::has_handler(
ResourceManager const& rm,
ResourceType type
) {
return hash_map::has(rm._handlers, type);
}
hash64 resource_manager::add_package(
ResourceManager& rm,
StringRef const& root
) {
// NB: ResourcePackage ctor does modify root
Allocator& allocator = *rm._packages._allocator;
ResourcePackage* const pkg = TOGO_CONSTRUCT(allocator,
ResourcePackage, root, allocator
);
for (auto const* it_pkg : rm._packages) {
TOGO_ASSERTF(
it_pkg->_root_hash != pkg->_root_hash,
"package at '%.*s' has already been added",
root.size, root.data
);
}
array::push_back(rm._packages, pkg);
resource_package::load_manifest(*pkg, rm);
return resource_package::root_hash(*pkg);
}
void resource_manager::remove_package(
ResourceManager& rm,
hash64 const root_hash
) {
Allocator& allocator = *rm._packages._allocator;
for (unsigned i = 0; i < array::size(rm._packages); ++i) {
auto* const pkg = rm._packages[i];
if (root_hash == pkg->_root_hash) {
// TODO: Unload active resources from the package
TOGO_DESTROY(allocator, pkg);
array::remove(rm._packages, i);
return;
}
}
TOGO_ASSERT(false, "package not found");
}
void resource_manager::clear_packages(ResourceManager& rm) {
Allocator& allocator = *rm._packages._allocator;
// TODO: Unload all active resources
for (auto* pkg : rm._packages) {
TOGO_DESTROY(allocator, pkg);
}
array::clear(rm._packages);
}
void* resource_manager::load_resource(
ResourceManager& rm,
ResourceType const type,
ResourceNameHash const name_hash
) {
TOGO_DEBUG_ASSERTE(hash_map::has(rm._handlers, type));
auto* tr = hash_map::get(rm._resources, name_hash);
if (!tr) {
auto const* const handler = hash_map::get(rm._handlers, type);
ResourcePackage* pkg = nullptr;
ResourcePackage::EntryNode* node = nullptr;
if (!find_resource(rm, type, name_hash, pkg, node)) {
TOGO_LOG_ERRORF(
"resource not found: %08x %016lx\n",
type, name_hash
);
return nullptr;
}
StringRef const pkg_root_ref{resource_package::root(*pkg)};
StringRef const rpath_ref{node->value.path, node->value.path_size};
IReader* stream = resource_package::open_resource_stream(
*pkg, node
);
if (!stream) {
TOGO_LOG_ERRORF(
"failed to open resource stream from package '%.*s': '%.*s'\n",
pkg_root_ref.size, pkg_root_ref.data,
rpath_ref.size, rpath_ref.data
);
return nullptr;
}
void* const load_value = handler->handler.func_load(
handler->type_data, rm, name_hash, *stream
);
resource_package::close_resource_stream(*pkg);
if (!load_value) {
TOGO_LOG_ERRORF(
"failed to load resource from package '%.*s': '%.*s'\n",
pkg_root_ref.size, pkg_root_ref.data,
rpath_ref.size, rpath_ref.data
);
return nullptr;
}
tr = &hash_map::push(
rm._resources, name_hash, {load_value, type}
);
}
return (tr && tr->type == type) ? tr->value : nullptr;
}
void resource_manager::unload_resource(
ResourceManager& rm,
ResourceType const type,
ResourceNameHash const name_hash
) {
TOGO_DEBUG_ASSERTE(hash_map::has(rm._handlers, type));
auto* const node = hash_map::get_node(rm._resources, name_hash);
if (!node || node->value.type != type) {
return;
}
auto const* const handler = hash_map::get(rm._handlers, type);
handler->handler.func_unload(
handler->type_data, rm, name_hash, node->value.value
);
hash_map::remove(rm._resources, node);
}
void* resource_manager::get_resource(
ResourceManager& rm,
ResourceType const type,
ResourceNameHash const name_hash
) {
TOGO_DEBUG_ASSERTE(hash_map::has(rm._handlers, type));
auto* const tr = hash_map::get(rm._resources, name_hash);
return (tr && tr->type == type) ? tr->value : nullptr;
}
} // namespace togo
<|endoftext|> |
<commit_before>/*
*
* Copyright (c) 2021 Project CHIP 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.
*/
/**
* @file
* This file provides implementation of ExchangeMessageDispatch class.
*/
#ifndef __STDC_FORMAT_MACROS
#define __STDC_FORMAT_MACROS
#endif
#ifndef __STDC_LIMIT_MACROS
#define __STDC_LIMIT_MACROS
#endif
#include <inttypes.h>
#include <memory>
#include <lib/support/CodeUtils.h>
#include <messaging/ExchangeMessageDispatch.h>
#include <messaging/ReliableMessageContext.h>
#include <messaging/ReliableMessageMgr.h>
#include <protocols/secure_channel/Constants.h>
namespace chip {
namespace Messaging {
CHIP_ERROR ExchangeMessageDispatch::SendMessage(SessionHandle session, uint16_t exchangeId, bool isInitiator,
ReliableMessageContext * reliableMessageContext, bool isReliableTransmission,
Protocols::Id protocol, uint8_t type, System::PacketBufferHandle && message)
{
ReturnErrorCodeIf(!MessagePermitted(protocol.GetProtocolId(), type), CHIP_ERROR_INVALID_ARGUMENT);
PayloadHeader payloadHeader;
payloadHeader.SetExchangeID(exchangeId).SetMessageType(protocol, type).SetInitiator(isInitiator);
// If there is a pending acknowledgment piggyback it on this message.
if (reliableMessageContext->IsAckPending())
{
payloadHeader.SetAckMessageCounter(reliableMessageContext->TakePendingPeerAckMessageCounter());
#if !defined(NDEBUG)
if (!payloadHeader.HasMessageType(Protocols::SecureChannel::MsgType::StandaloneAck))
{
ChipLogDetail(ExchangeManager, "Piggybacking Ack for MessageCounter:%08" PRIX32 " with msg",
payloadHeader.GetAckMessageCounter().Value());
}
#endif
}
if (IsReliableTransmissionAllowed() && reliableMessageContext->AutoRequestAck() &&
reliableMessageContext->GetReliableMessageMgr() != nullptr && isReliableTransmission)
{
auto * reliableMessageMgr = reliableMessageContext->GetReliableMessageMgr();
payloadHeader.SetNeedsAck(true);
ReliableMessageMgr::RetransTableEntry * entry = nullptr;
// Add to Table for subsequent sending
ReturnErrorOnFailure(reliableMessageMgr->AddToRetransTable(reliableMessageContext, &entry));
auto deleter = [reliableMessageMgr](ReliableMessageMgr::RetransTableEntry * e) {
reliableMessageMgr->ClearRetransTable(*e);
};
std::unique_ptr<ReliableMessageMgr::RetransTableEntry, decltype(deleter)> entryOwner(entry, deleter);
ReturnErrorOnFailure(PrepareMessage(session, payloadHeader, std::move(message), entryOwner->retainedBuf));
CHIP_ERROR err = SendPreparedMessage(session, entryOwner->retainedBuf);
if (err == System::MapErrorPOSIX(ENOBUFS))
{
// sendmsg on BSD-based systems never blocks, no matter how the
// socket is configured, and will return ENOBUFS in situation in
// which Linux, for example, blocks.
//
// This is typically a transient situation, so we pretend like this
// packet drop happened somewhere on the network instead of inside
// sendmsg and will just resend it in the normal MRP way later.
ChipLogError(ExchangeManager, "Ignoring ENOBUFS: %" CHIP_ERROR_FORMAT, err.Format());
err = CHIP_NO_ERROR;
}
ReturnErrorOnFailure(err);
reliableMessageMgr->StartRetransmision(entryOwner.release());
}
else
{
// If the channel itself is providing reliability, let's not request MRP acks
payloadHeader.SetNeedsAck(false);
EncryptedPacketBufferHandle preparedMessage;
ReturnErrorOnFailure(PrepareMessage(session, payloadHeader, std::move(message), preparedMessage));
ReturnErrorOnFailure(SendPreparedMessage(session, preparedMessage));
}
return CHIP_NO_ERROR;
}
CHIP_ERROR ExchangeMessageDispatch::OnMessageReceived(uint32_t messageCounter, const PayloadHeader & payloadHeader,
const Transport::PeerAddress & peerAddress, MessageFlags msgFlags,
ReliableMessageContext * reliableMessageContext)
{
ReturnErrorCodeIf(!MessagePermitted(payloadHeader.GetProtocolID().GetProtocolId(), payloadHeader.GetMessageType()),
CHIP_ERROR_INVALID_ARGUMENT);
if (IsReliableTransmissionAllowed())
{
if (!msgFlags.Has(MessageFlagValues::kDuplicateMessage) && payloadHeader.IsAckMsg() &&
payloadHeader.GetAckMessageCounter().HasValue())
{
ReturnErrorOnFailure(reliableMessageContext->HandleRcvdAck(payloadHeader.GetAckMessageCounter().Value()));
}
if (payloadHeader.NeedsAck())
{
// An acknowledgment needs to be sent back to the peer for this message on this exchange,
ReturnErrorOnFailure(reliableMessageContext->HandleNeedsAck(messageCounter, msgFlags));
}
}
return CHIP_NO_ERROR;
}
} // namespace Messaging
} // namespace chip
<commit_msg>Fix merge conflict to fix build (#9834)<commit_after>/*
*
* Copyright (c) 2021 Project CHIP 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.
*/
/**
* @file
* This file provides implementation of ExchangeMessageDispatch class.
*/
#ifndef __STDC_FORMAT_MACROS
#define __STDC_FORMAT_MACROS
#endif
#ifndef __STDC_LIMIT_MACROS
#define __STDC_LIMIT_MACROS
#endif
#include <inttypes.h>
#include <memory>
#include <lib/support/CodeUtils.h>
#include <messaging/ExchangeMessageDispatch.h>
#include <messaging/ReliableMessageContext.h>
#include <messaging/ReliableMessageMgr.h>
#include <protocols/secure_channel/Constants.h>
namespace chip {
namespace Messaging {
CHIP_ERROR ExchangeMessageDispatch::SendMessage(SessionHandle session, uint16_t exchangeId, bool isInitiator,
ReliableMessageContext * reliableMessageContext, bool isReliableTransmission,
Protocols::Id protocol, uint8_t type, System::PacketBufferHandle && message)
{
ReturnErrorCodeIf(!MessagePermitted(protocol.GetProtocolId(), type), CHIP_ERROR_INVALID_ARGUMENT);
PayloadHeader payloadHeader;
payloadHeader.SetExchangeID(exchangeId).SetMessageType(protocol, type).SetInitiator(isInitiator);
// If there is a pending acknowledgment piggyback it on this message.
if (reliableMessageContext->IsAckPending())
{
payloadHeader.SetAckMessageCounter(reliableMessageContext->TakePendingPeerAckMessageCounter());
#if !defined(NDEBUG)
if (!payloadHeader.HasMessageType(Protocols::SecureChannel::MsgType::StandaloneAck))
{
ChipLogDetail(ExchangeManager, "Piggybacking Ack for MessageCounter:%08" PRIX32 " with msg",
payloadHeader.GetAckMessageCounter().Value());
}
#endif
}
if (IsReliableTransmissionAllowed() && reliableMessageContext->AutoRequestAck() &&
reliableMessageContext->GetReliableMessageMgr() != nullptr && isReliableTransmission)
{
auto * reliableMessageMgr = reliableMessageContext->GetReliableMessageMgr();
payloadHeader.SetNeedsAck(true);
ReliableMessageMgr::RetransTableEntry * entry = nullptr;
// Add to Table for subsequent sending
ReturnErrorOnFailure(reliableMessageMgr->AddToRetransTable(reliableMessageContext, &entry));
auto deleter = [reliableMessageMgr](ReliableMessageMgr::RetransTableEntry * e) {
reliableMessageMgr->ClearRetransTable(*e);
};
std::unique_ptr<ReliableMessageMgr::RetransTableEntry, decltype(deleter)> entryOwner(entry, deleter);
ReturnErrorOnFailure(PrepareMessage(session, payloadHeader, std::move(message), entryOwner->retainedBuf));
CHIP_ERROR err = SendPreparedMessage(session, entryOwner->retainedBuf);
if (err == CHIP_ERROR_POSIX(ENOBUFS))
{
// sendmsg on BSD-based systems never blocks, no matter how the
// socket is configured, and will return ENOBUFS in situation in
// which Linux, for example, blocks.
//
// This is typically a transient situation, so we pretend like this
// packet drop happened somewhere on the network instead of inside
// sendmsg and will just resend it in the normal MRP way later.
ChipLogError(ExchangeManager, "Ignoring ENOBUFS: %" CHIP_ERROR_FORMAT, err.Format());
err = CHIP_NO_ERROR;
}
ReturnErrorOnFailure(err);
reliableMessageMgr->StartRetransmision(entryOwner.release());
}
else
{
// If the channel itself is providing reliability, let's not request MRP acks
payloadHeader.SetNeedsAck(false);
EncryptedPacketBufferHandle preparedMessage;
ReturnErrorOnFailure(PrepareMessage(session, payloadHeader, std::move(message), preparedMessage));
ReturnErrorOnFailure(SendPreparedMessage(session, preparedMessage));
}
return CHIP_NO_ERROR;
}
CHIP_ERROR ExchangeMessageDispatch::OnMessageReceived(uint32_t messageCounter, const PayloadHeader & payloadHeader,
const Transport::PeerAddress & peerAddress, MessageFlags msgFlags,
ReliableMessageContext * reliableMessageContext)
{
ReturnErrorCodeIf(!MessagePermitted(payloadHeader.GetProtocolID().GetProtocolId(), payloadHeader.GetMessageType()),
CHIP_ERROR_INVALID_ARGUMENT);
if (IsReliableTransmissionAllowed())
{
if (!msgFlags.Has(MessageFlagValues::kDuplicateMessage) && payloadHeader.IsAckMsg() &&
payloadHeader.GetAckMessageCounter().HasValue())
{
ReturnErrorOnFailure(reliableMessageContext->HandleRcvdAck(payloadHeader.GetAckMessageCounter().Value()));
}
if (payloadHeader.NeedsAck())
{
// An acknowledgment needs to be sent back to the peer for this message on this exchange,
ReturnErrorOnFailure(reliableMessageContext->HandleNeedsAck(messageCounter, msgFlags));
}
}
return CHIP_NO_ERROR;
}
} // namespace Messaging
} // namespace chip
<|endoftext|> |
<commit_before>/*
* Copyright (c) 2021, The OpenThread Authors.
* 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. Neither the name of the copyright holder 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.
*/
/**
* @file
* This file includes implementation of TREL DNS-SD over mDNS.
*/
#if OTBR_ENABLE_TREL
#define OTBR_LOG_TAG "TrelDns"
#include "trel_dnssd/trel_dnssd.hpp"
#include <net/if.h>
#include <openthread/instance.h>
#include <openthread/link.h>
#include <openthread/platform/trel.h>
#include "common/code_utils.hpp"
#include "utils/hex.hpp"
#include "utils/string_utils.hpp"
static const char kTrelServiceName[] = "_trel._udp";
static otbr::TrelDnssd::TrelDnssd *sTrelDnssd = nullptr;
void trelDnssdInitialize(const char *aTrelNetif)
{
sTrelDnssd->Initialize(aTrelNetif);
}
void trelDnssdStartBrowse(void)
{
sTrelDnssd->StartBrowse();
}
void trelDnssdStopBrowse(void)
{
sTrelDnssd->StopBrowse();
}
void trelDnssdRegisterService(uint16_t aPort, const uint8_t *aTxtData, uint8_t aTxtLength)
{
sTrelDnssd->RegisterService(aPort, aTxtData, aTxtLength);
}
void trelDnssdRemoveService(void)
{
sTrelDnssd->UnregisterService();
}
namespace otbr {
namespace TrelDnssd {
TrelDnssd::TrelDnssd(Ncp::ControllerOpenThread &aNcp, Mdns::Publisher &aPublisher)
: mPublisher(aPublisher)
, mNcp(aNcp)
{
sTrelDnssd = this;
}
void TrelDnssd::Initialize(std::string aTrelNetif)
{
mTrelNetif = std::move(aTrelNetif);
if (IsInitialized())
{
otbrLogDebug("Initialized on netif \"%s\"", mTrelNetif.c_str());
CheckTrelNetifReady();
}
else
{
otbrLogDebug("Not initialized");
}
}
void TrelDnssd::StartBrowse(void)
{
VerifyOrExit(IsInitialized());
otbrLogDebug("Start browsing %s services ...", kTrelServiceName);
assert(mSubscriberId == 0);
mSubscriberId = mPublisher.AddSubscriptionCallbacks(
[this](const std::string &aType, const Mdns::Publisher::DiscoveredInstanceInfo &aInstanceInfo) {
OnTrelServiceInstanceResolved(aType, aInstanceInfo);
},
/* aHostCallback */ nullptr);
if (IsReady())
{
mPublisher.SubscribeService(kTrelServiceName, /* aInstanceName */ "");
}
exit:
return;
}
void TrelDnssd::StopBrowse(void)
{
VerifyOrExit(IsInitialized());
otbrLogDebug("Stop browsing %s service.", kTrelServiceName);
assert(mSubscriberId > 0);
mPublisher.RemoveSubscriptionCallbacks(mSubscriberId);
mSubscriberId = 0;
if (IsReady())
{
mPublisher.UnsubscribeService(kTrelServiceName, "");
}
exit:
return;
}
void TrelDnssd::RegisterService(uint16_t aPort, const uint8_t *aTxtData, uint8_t aTxtLength)
{
assert(aPort > 0);
assert(aTxtData != nullptr);
VerifyOrExit(IsInitialized());
otbrLogDebug("Register %s service: port=%u, TXT=%d bytes", kTrelServiceName, aPort, aTxtLength);
otbrDump(OTBR_LOG_DEBUG, OTBR_LOG_TAG, "TXT", aTxtData, aTxtLength);
if (mRegisterInfo.IsValid() && IsReady())
{
UnpublishTrelService();
}
mRegisterInfo.Assign(aPort, aTxtData, aTxtLength);
if (IsReady())
{
PublishTrelService();
}
exit:
return;
}
void TrelDnssd::UnregisterService(void)
{
VerifyOrExit(IsInitialized());
otbrLogDebug("Remove %s service", kTrelServiceName);
assert(mRegisterInfo.IsValid());
if (IsReady())
{
UnpublishTrelService();
}
mRegisterInfo.Clear();
exit:
return;
}
void TrelDnssd::OnMdnsPublisherReady(void)
{
VerifyOrExit(IsInitialized());
otbrLogDebug("mDNS Publisher is Ready");
mMdnsPublisherReady = true;
RemoveAllPeers();
if (mRegisterInfo.IsPublished())
{
mRegisterInfo.mInstanceName = "";
}
OnBecomeReady();
exit:
return;
}
void TrelDnssd::OnTrelServiceInstanceResolved(const std::string & aType,
const Mdns::Publisher::DiscoveredInstanceInfo &aInstanceInfo)
{
VerifyOrExit(StringUtils::EqualCaseInsensitive(aType, kTrelServiceName));
VerifyOrExit(aInstanceInfo.mNetifIndex == mTrelNetifIndex);
if (aInstanceInfo.mRemoved)
{
OnTrelServiceInstanceRemoved(aInstanceInfo.mName);
}
else
{
OnTrelServiceInstanceAdded(aInstanceInfo);
}
exit:
return;
}
std::string TrelDnssd::GetTrelInstanceName(void)
{
const otExtAddress *extaddr = otLinkGetExtendedAddress(mNcp.GetInstance());
std::string name;
char nameBuf[sizeof(extaddr) * 2 + 1];
Utils::Bytes2Hex(extaddr->m8, sizeof(extaddr), nameBuf);
name = StringUtils::ToLowercase(nameBuf);
assert(name.length() == sizeof(extaddr) * 2);
otbrLogDebug("Using instance name %s", name.c_str());
return name;
}
void TrelDnssd::PublishTrelService(void)
{
assert(mRegisterInfo.IsValid());
assert(!mRegisterInfo.IsPublished());
assert(mTrelNetifIndex > 0);
mRegisterInfo.mInstanceName = GetTrelInstanceName();
mPublisher.PublishService(/* aHostName */ "", mRegisterInfo.mPort, mRegisterInfo.mInstanceName, kTrelServiceName,
Mdns::Publisher::SubTypeList{}, mRegisterInfo.mTxtEntries);
}
void TrelDnssd::UnpublishTrelService(void)
{
assert(mRegisterInfo.IsValid());
assert(mRegisterInfo.IsPublished());
mPublisher.UnpublishService(mRegisterInfo.mInstanceName, kTrelServiceName);
mRegisterInfo.mInstanceName = "";
}
void TrelDnssd::OnTrelServiceInstanceAdded(const Mdns::Publisher::DiscoveredInstanceInfo &aInstanceInfo)
{
std::string instanceName = StringUtils::ToLowercase(aInstanceInfo.mName);
otPlatTrelPeerInfo peerInfo;
// Remove any existing TREL service instance before adding
OnTrelServiceInstanceRemoved(instanceName);
otbrLogDebug("Peer discovered: %s hostname %s addresses %zu port %d priority %d "
"weight %d",
aInstanceInfo.mName.c_str(), aInstanceInfo.mHostName.c_str(), aInstanceInfo.mAddresses.size(),
aInstanceInfo.mPort, aInstanceInfo.mPriority, aInstanceInfo.mWeight);
for (const auto &addr : aInstanceInfo.mAddresses)
{
otbrLogDebug("Peer address: %s", addr.ToString().c_str());
}
if (aInstanceInfo.mAddresses.empty())
{
otbrLogWarning("Peer %s does not have any IPv6 address, ignored", aInstanceInfo.mName.c_str());
ExitNow();
}
peerInfo.mRemoved = false;
memcpy(&peerInfo.mSockAddr.mAddress, &aInstanceInfo.mAddresses[0], sizeof(peerInfo.mSockAddr.mAddress));
peerInfo.mSockAddr.mPort = aInstanceInfo.mPort;
peerInfo.mTxtData = aInstanceInfo.mTxtData.data();
peerInfo.mTxtLength = aInstanceInfo.mTxtData.size();
{
Peer peer(aInstanceInfo.mTxtData, peerInfo.mSockAddr);
VerifyOrExit(peer.mValid, otbrLogWarning("Peer %s is invalid", aInstanceInfo.mName.c_str()));
otPlatTrelHandleDiscoveredPeerInfo(mNcp.GetInstance(), &peerInfo);
mPeers.emplace(instanceName, peer);
CheckPeersNumLimit();
}
exit:
return;
}
void TrelDnssd::OnTrelServiceInstanceRemoved(const std::string &aInstanceName)
{
std::string instanceName = StringUtils::ToLowercase(aInstanceName);
auto it = mPeers.find(instanceName);
VerifyOrExit(it != mPeers.end());
otbrLogDebug("Peer removed: %s", instanceName.c_str());
// Remove the peer only when all instances are removed because one peer can have multiple instances if expired
// instances were not properly removed by mDNS.
if (CountDuplicatePeers(it->second) == 0)
{
NotifyRemovePeer(it->second);
}
mPeers.erase(it);
exit:
return;
}
void TrelDnssd::CheckPeersNumLimit(void)
{
const PeerMap::value_type *oldestPeer = nullptr;
VerifyOrExit(mPeers.size() >= kPeerCacheSize);
for (const auto &entry : mPeers)
{
if (oldestPeer == nullptr || entry.second.mDiscoverTime < oldestPeer->second.mDiscoverTime)
{
oldestPeer = &entry;
}
}
OnTrelServiceInstanceRemoved(oldestPeer->first);
exit:
return;
}
void TrelDnssd::NotifyRemovePeer(const Peer &aPeer)
{
otPlatTrelPeerInfo peerInfo;
peerInfo.mRemoved = true;
peerInfo.mTxtData = aPeer.mTxtData.data();
peerInfo.mTxtLength = aPeer.mTxtData.size();
peerInfo.mSockAddr = aPeer.mSockAddr;
otPlatTrelHandleDiscoveredPeerInfo(mNcp.GetInstance(), &peerInfo);
}
void TrelDnssd::RemoveAllPeers(void)
{
for (const auto &entry : mPeers)
{
NotifyRemovePeer(entry.second);
}
mPeers.clear();
}
void TrelDnssd::CheckTrelNetifReady(void)
{
assert(IsInitialized());
if (mTrelNetifIndex == 0)
{
mTrelNetifIndex = if_nametoindex(mTrelNetif.c_str());
if (mTrelNetifIndex != 0)
{
otbrLogDebug("Netif %s is ready: index = %d", mTrelNetif.c_str(), mTrelNetifIndex);
OnBecomeReady();
}
else
{
uint16_t delay = kCheckNetifReadyIntervalMs;
otbrLogWarning("Netif %s is not ready (%s), will retry after %d seconds", mTrelNetif.c_str(),
strerror(errno), delay / 1000);
mTaskRunner.Post(Milliseconds(delay), [this]() { CheckTrelNetifReady(); });
}
}
}
bool TrelDnssd::IsReady(void) const
{
assert(IsInitialized());
return mTrelNetifIndex > 0 && mMdnsPublisherReady;
}
void TrelDnssd::OnBecomeReady(void)
{
if (IsReady())
{
otbrLogInfo("TREL DNS-SD Is Now Ready: Netif=%s(%u), SubscriberId=%u, Register=%s!", mTrelNetif.c_str(),
mTrelNetifIndex, mSubscriberId, mRegisterInfo.mInstanceName.c_str());
if (mSubscriberId > 0)
{
mPublisher.SubscribeService(kTrelServiceName, /* aInstanceName */ "");
}
if (mRegisterInfo.IsValid())
{
PublishTrelService();
}
}
}
uint16_t TrelDnssd::CountDuplicatePeers(const TrelDnssd::Peer &aPeer)
{
uint16_t count = 0;
for (const auto &entry : mPeers)
{
if (&entry.second == &aPeer)
{
continue;
}
if (!memcmp(&entry.second.mSockAddr, &aPeer.mSockAddr, sizeof(otSockAddr)) &&
!memcmp(&entry.second.mExtAddr, &aPeer.mExtAddr, sizeof(otExtAddress)))
{
count++;
}
}
return count;
}
void TrelDnssd::RegisterInfo::Assign(uint16_t aPort, const uint8_t *aTxtData, uint8_t aTxtLength)
{
otbrError error;
OTBR_UNUSED_VARIABLE(error);
assert(!IsPublished());
assert(aPort > 0);
mPort = aPort;
mTxtEntries.clear();
error = Mdns::Publisher::DecodeTxtData(mTxtEntries, aTxtData, aTxtLength);
assert(error == OTBR_ERROR_NONE);
}
void TrelDnssd::RegisterInfo::Clear(void)
{
assert(!IsPublished());
mPort = 0;
mTxtEntries.clear();
}
const char TrelDnssd::Peer::kTxtRecordExtAddressKey[] = "xa";
void TrelDnssd::Peer::ReadExtAddrFromTxtData(void)
{
std::vector<Mdns::Publisher::TxtEntry> txtEntries;
memset(&mExtAddr, 0, sizeof(mExtAddr));
SuccessOrExit(Mdns::Publisher::DecodeTxtData(txtEntries, mTxtData.data(), mTxtData.size()));
for (const auto &txtEntry : txtEntries)
{
if (StringUtils::EqualCaseInsensitive(txtEntry.mName, kTxtRecordExtAddressKey))
{
VerifyOrExit(txtEntry.mValue.size() == sizeof(mExtAddr));
memcpy(mExtAddr.m8, txtEntry.mValue.data(), sizeof(mExtAddr));
mValid = true;
break;
}
}
exit:
if (!mValid)
{
otbrLogInfo("Failed to dissect ExtAddr from peer TXT data");
}
return;
}
} // namespace TrelDnssd
} // namespace otbr
#endif // OTBR_ENABLE_TREL
<commit_msg>[trel-dnssd] fix wrong instance name size (#1241)<commit_after>/*
* Copyright (c) 2021, The OpenThread Authors.
* 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. Neither the name of the copyright holder 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.
*/
/**
* @file
* This file includes implementation of TREL DNS-SD over mDNS.
*/
#if OTBR_ENABLE_TREL
#define OTBR_LOG_TAG "TrelDns"
#include "trel_dnssd/trel_dnssd.hpp"
#include <net/if.h>
#include <openthread/instance.h>
#include <openthread/link.h>
#include <openthread/platform/trel.h>
#include "common/code_utils.hpp"
#include "utils/hex.hpp"
#include "utils/string_utils.hpp"
static const char kTrelServiceName[] = "_trel._udp";
static otbr::TrelDnssd::TrelDnssd *sTrelDnssd = nullptr;
void trelDnssdInitialize(const char *aTrelNetif)
{
sTrelDnssd->Initialize(aTrelNetif);
}
void trelDnssdStartBrowse(void)
{
sTrelDnssd->StartBrowse();
}
void trelDnssdStopBrowse(void)
{
sTrelDnssd->StopBrowse();
}
void trelDnssdRegisterService(uint16_t aPort, const uint8_t *aTxtData, uint8_t aTxtLength)
{
sTrelDnssd->RegisterService(aPort, aTxtData, aTxtLength);
}
void trelDnssdRemoveService(void)
{
sTrelDnssd->UnregisterService();
}
namespace otbr {
namespace TrelDnssd {
TrelDnssd::TrelDnssd(Ncp::ControllerOpenThread &aNcp, Mdns::Publisher &aPublisher)
: mPublisher(aPublisher)
, mNcp(aNcp)
{
sTrelDnssd = this;
}
void TrelDnssd::Initialize(std::string aTrelNetif)
{
mTrelNetif = std::move(aTrelNetif);
if (IsInitialized())
{
otbrLogDebug("Initialized on netif \"%s\"", mTrelNetif.c_str());
CheckTrelNetifReady();
}
else
{
otbrLogDebug("Not initialized");
}
}
void TrelDnssd::StartBrowse(void)
{
VerifyOrExit(IsInitialized());
otbrLogDebug("Start browsing %s services ...", kTrelServiceName);
assert(mSubscriberId == 0);
mSubscriberId = mPublisher.AddSubscriptionCallbacks(
[this](const std::string &aType, const Mdns::Publisher::DiscoveredInstanceInfo &aInstanceInfo) {
OnTrelServiceInstanceResolved(aType, aInstanceInfo);
},
/* aHostCallback */ nullptr);
if (IsReady())
{
mPublisher.SubscribeService(kTrelServiceName, /* aInstanceName */ "");
}
exit:
return;
}
void TrelDnssd::StopBrowse(void)
{
VerifyOrExit(IsInitialized());
otbrLogDebug("Stop browsing %s service.", kTrelServiceName);
assert(mSubscriberId > 0);
mPublisher.RemoveSubscriptionCallbacks(mSubscriberId);
mSubscriberId = 0;
if (IsReady())
{
mPublisher.UnsubscribeService(kTrelServiceName, "");
}
exit:
return;
}
void TrelDnssd::RegisterService(uint16_t aPort, const uint8_t *aTxtData, uint8_t aTxtLength)
{
assert(aPort > 0);
assert(aTxtData != nullptr);
VerifyOrExit(IsInitialized());
otbrLogDebug("Register %s service: port=%u, TXT=%d bytes", kTrelServiceName, aPort, aTxtLength);
otbrDump(OTBR_LOG_DEBUG, OTBR_LOG_TAG, "TXT", aTxtData, aTxtLength);
if (mRegisterInfo.IsValid() && IsReady())
{
UnpublishTrelService();
}
mRegisterInfo.Assign(aPort, aTxtData, aTxtLength);
if (IsReady())
{
PublishTrelService();
}
exit:
return;
}
void TrelDnssd::UnregisterService(void)
{
VerifyOrExit(IsInitialized());
otbrLogDebug("Remove %s service", kTrelServiceName);
assert(mRegisterInfo.IsValid());
if (IsReady())
{
UnpublishTrelService();
}
mRegisterInfo.Clear();
exit:
return;
}
void TrelDnssd::OnMdnsPublisherReady(void)
{
VerifyOrExit(IsInitialized());
otbrLogDebug("mDNS Publisher is Ready");
mMdnsPublisherReady = true;
RemoveAllPeers();
if (mRegisterInfo.IsPublished())
{
mRegisterInfo.mInstanceName = "";
}
OnBecomeReady();
exit:
return;
}
void TrelDnssd::OnTrelServiceInstanceResolved(const std::string & aType,
const Mdns::Publisher::DiscoveredInstanceInfo &aInstanceInfo)
{
VerifyOrExit(StringUtils::EqualCaseInsensitive(aType, kTrelServiceName));
VerifyOrExit(aInstanceInfo.mNetifIndex == mTrelNetifIndex);
if (aInstanceInfo.mRemoved)
{
OnTrelServiceInstanceRemoved(aInstanceInfo.mName);
}
else
{
OnTrelServiceInstanceAdded(aInstanceInfo);
}
exit:
return;
}
std::string TrelDnssd::GetTrelInstanceName(void)
{
const otExtAddress *extaddr = otLinkGetExtendedAddress(mNcp.GetInstance());
std::string name;
char nameBuf[sizeof(otExtAddress) * 2 + 1];
Utils::Bytes2Hex(extaddr->m8, sizeof(otExtAddress), nameBuf);
name = StringUtils::ToLowercase(nameBuf);
assert(name.length() == sizeof(otExtAddress) * 2);
otbrLogDebug("Using instance name %s", name.c_str());
return name;
}
void TrelDnssd::PublishTrelService(void)
{
assert(mRegisterInfo.IsValid());
assert(!mRegisterInfo.IsPublished());
assert(mTrelNetifIndex > 0);
mRegisterInfo.mInstanceName = GetTrelInstanceName();
mPublisher.PublishService(/* aHostName */ "", mRegisterInfo.mPort, mRegisterInfo.mInstanceName, kTrelServiceName,
Mdns::Publisher::SubTypeList{}, mRegisterInfo.mTxtEntries);
}
void TrelDnssd::UnpublishTrelService(void)
{
assert(mRegisterInfo.IsValid());
assert(mRegisterInfo.IsPublished());
mPublisher.UnpublishService(mRegisterInfo.mInstanceName, kTrelServiceName);
mRegisterInfo.mInstanceName = "";
}
void TrelDnssd::OnTrelServiceInstanceAdded(const Mdns::Publisher::DiscoveredInstanceInfo &aInstanceInfo)
{
std::string instanceName = StringUtils::ToLowercase(aInstanceInfo.mName);
otPlatTrelPeerInfo peerInfo;
// Remove any existing TREL service instance before adding
OnTrelServiceInstanceRemoved(instanceName);
otbrLogDebug("Peer discovered: %s hostname %s addresses %zu port %d priority %d "
"weight %d",
aInstanceInfo.mName.c_str(), aInstanceInfo.mHostName.c_str(), aInstanceInfo.mAddresses.size(),
aInstanceInfo.mPort, aInstanceInfo.mPriority, aInstanceInfo.mWeight);
for (const auto &addr : aInstanceInfo.mAddresses)
{
otbrLogDebug("Peer address: %s", addr.ToString().c_str());
}
if (aInstanceInfo.mAddresses.empty())
{
otbrLogWarning("Peer %s does not have any IPv6 address, ignored", aInstanceInfo.mName.c_str());
ExitNow();
}
peerInfo.mRemoved = false;
memcpy(&peerInfo.mSockAddr.mAddress, &aInstanceInfo.mAddresses[0], sizeof(peerInfo.mSockAddr.mAddress));
peerInfo.mSockAddr.mPort = aInstanceInfo.mPort;
peerInfo.mTxtData = aInstanceInfo.mTxtData.data();
peerInfo.mTxtLength = aInstanceInfo.mTxtData.size();
{
Peer peer(aInstanceInfo.mTxtData, peerInfo.mSockAddr);
VerifyOrExit(peer.mValid, otbrLogWarning("Peer %s is invalid", aInstanceInfo.mName.c_str()));
otPlatTrelHandleDiscoveredPeerInfo(mNcp.GetInstance(), &peerInfo);
mPeers.emplace(instanceName, peer);
CheckPeersNumLimit();
}
exit:
return;
}
void TrelDnssd::OnTrelServiceInstanceRemoved(const std::string &aInstanceName)
{
std::string instanceName = StringUtils::ToLowercase(aInstanceName);
auto it = mPeers.find(instanceName);
VerifyOrExit(it != mPeers.end());
otbrLogDebug("Peer removed: %s", instanceName.c_str());
// Remove the peer only when all instances are removed because one peer can have multiple instances if expired
// instances were not properly removed by mDNS.
if (CountDuplicatePeers(it->second) == 0)
{
NotifyRemovePeer(it->second);
}
mPeers.erase(it);
exit:
return;
}
void TrelDnssd::CheckPeersNumLimit(void)
{
const PeerMap::value_type *oldestPeer = nullptr;
VerifyOrExit(mPeers.size() >= kPeerCacheSize);
for (const auto &entry : mPeers)
{
if (oldestPeer == nullptr || entry.second.mDiscoverTime < oldestPeer->second.mDiscoverTime)
{
oldestPeer = &entry;
}
}
OnTrelServiceInstanceRemoved(oldestPeer->first);
exit:
return;
}
void TrelDnssd::NotifyRemovePeer(const Peer &aPeer)
{
otPlatTrelPeerInfo peerInfo;
peerInfo.mRemoved = true;
peerInfo.mTxtData = aPeer.mTxtData.data();
peerInfo.mTxtLength = aPeer.mTxtData.size();
peerInfo.mSockAddr = aPeer.mSockAddr;
otPlatTrelHandleDiscoveredPeerInfo(mNcp.GetInstance(), &peerInfo);
}
void TrelDnssd::RemoveAllPeers(void)
{
for (const auto &entry : mPeers)
{
NotifyRemovePeer(entry.second);
}
mPeers.clear();
}
void TrelDnssd::CheckTrelNetifReady(void)
{
assert(IsInitialized());
if (mTrelNetifIndex == 0)
{
mTrelNetifIndex = if_nametoindex(mTrelNetif.c_str());
if (mTrelNetifIndex != 0)
{
otbrLogDebug("Netif %s is ready: index = %d", mTrelNetif.c_str(), mTrelNetifIndex);
OnBecomeReady();
}
else
{
uint16_t delay = kCheckNetifReadyIntervalMs;
otbrLogWarning("Netif %s is not ready (%s), will retry after %d seconds", mTrelNetif.c_str(),
strerror(errno), delay / 1000);
mTaskRunner.Post(Milliseconds(delay), [this]() { CheckTrelNetifReady(); });
}
}
}
bool TrelDnssd::IsReady(void) const
{
assert(IsInitialized());
return mTrelNetifIndex > 0 && mMdnsPublisherReady;
}
void TrelDnssd::OnBecomeReady(void)
{
if (IsReady())
{
otbrLogInfo("TREL DNS-SD Is Now Ready: Netif=%s(%u), SubscriberId=%u, Register=%s!", mTrelNetif.c_str(),
mTrelNetifIndex, mSubscriberId, mRegisterInfo.mInstanceName.c_str());
if (mSubscriberId > 0)
{
mPublisher.SubscribeService(kTrelServiceName, /* aInstanceName */ "");
}
if (mRegisterInfo.IsValid())
{
PublishTrelService();
}
}
}
uint16_t TrelDnssd::CountDuplicatePeers(const TrelDnssd::Peer &aPeer)
{
uint16_t count = 0;
for (const auto &entry : mPeers)
{
if (&entry.second == &aPeer)
{
continue;
}
if (!memcmp(&entry.second.mSockAddr, &aPeer.mSockAddr, sizeof(otSockAddr)) &&
!memcmp(&entry.second.mExtAddr, &aPeer.mExtAddr, sizeof(otExtAddress)))
{
count++;
}
}
return count;
}
void TrelDnssd::RegisterInfo::Assign(uint16_t aPort, const uint8_t *aTxtData, uint8_t aTxtLength)
{
otbrError error;
OTBR_UNUSED_VARIABLE(error);
assert(!IsPublished());
assert(aPort > 0);
mPort = aPort;
mTxtEntries.clear();
error = Mdns::Publisher::DecodeTxtData(mTxtEntries, aTxtData, aTxtLength);
assert(error == OTBR_ERROR_NONE);
}
void TrelDnssd::RegisterInfo::Clear(void)
{
assert(!IsPublished());
mPort = 0;
mTxtEntries.clear();
}
const char TrelDnssd::Peer::kTxtRecordExtAddressKey[] = "xa";
void TrelDnssd::Peer::ReadExtAddrFromTxtData(void)
{
std::vector<Mdns::Publisher::TxtEntry> txtEntries;
memset(&mExtAddr, 0, sizeof(mExtAddr));
SuccessOrExit(Mdns::Publisher::DecodeTxtData(txtEntries, mTxtData.data(), mTxtData.size()));
for (const auto &txtEntry : txtEntries)
{
if (StringUtils::EqualCaseInsensitive(txtEntry.mName, kTxtRecordExtAddressKey))
{
VerifyOrExit(txtEntry.mValue.size() == sizeof(mExtAddr));
memcpy(mExtAddr.m8, txtEntry.mValue.data(), sizeof(mExtAddr));
mValid = true;
break;
}
}
exit:
if (!mValid)
{
otbrLogInfo("Failed to dissect ExtAddr from peer TXT data");
}
return;
}
} // namespace TrelDnssd
} // namespace otbr
#endif // OTBR_ENABLE_TREL
<|endoftext|> |
<commit_before>/*
* The Apache Software License, Version 1.1
*
*
* Copyright (c) 1999-2002 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 apache@apache.org.
*
* 5. Products derived from this software may not be called "Apache",
* nor may "Apache" appear in their name, without prior written
* permission of the Apache Software Foundation.
*
* THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR
* ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
* USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
* OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation and was
* originally based on software copyright (c) 1999, International
* Business Machines, Inc., http://www.ibm.com. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*/
#if !defined(XPATHFUNCTIONTABLE_HEADER_GUARD_1357924680)
#define XPATHFUNCTIONTABLE_HEADER_GUARD_1357924680
// Base include file. Must be first.
#include <XPath/XPathDefinitions.hpp>
#include <algorithm>
#include <map>
#include <XalanDOM/XalanDOMString.hpp>
#include <Include/STLHelper.hpp>
#include <XPath/Function.hpp>
#include <XPath/XalanXPathException.hpp>
class Locator;
/**
* Exception class thrown when an unknown function is encountered
*/
class XALAN_XPATH_EXPORT XPathExceptionFunctionNotAvailable : public XalanXPathException
{
public:
XPathExceptionFunctionNotAvailable(int theFunctionNumber);
XPathExceptionFunctionNotAvailable(const XalanDOMString& theFunctionName);
XPathExceptionFunctionNotAvailable(
int theFunctionNumber,
const Locator& theLocator);
XPathExceptionFunctionNotAvailable(
const XalanDOMString& theFunctionName,
const Locator& theLocator);
~XPathExceptionFunctionNotAvailable();
};
/**
* Class defines a table of functions that can be called in XPath expresions.
*/
class XALAN_XPATH_EXPORT XPathFunctionTable
{
public:
#if defined(XALAN_NO_NAMESPACES)
typedef vector<const Function*> CollectionType;
typedef map<XalanDOMString,
int,
less<XalanDOMString> > FunctionNameIndexMapType;
#else
typedef std::vector<const Function*> CollectionType;
typedef std::map<XalanDOMString, int> FunctionNameIndexMapType;
#endif
enum { eDefaultTableSize = 36 };
typedef DeleteFunctor<Function> DeleteFunctorType;
/**
* Constructor.
*
* @param fCreateTable If true, the internal table will be created. Otherwise, CreateTable() must be called.
*/
XPathFunctionTable(bool fCreateTable = true);
~XPathFunctionTable();
/**
* Set up the internal table.
*/
void
CreateTable();
/**
* Destroy the internal table.
*/
void
DestroyTable();
/**
* Retrieve the function object for a specified function name.
*
* @param theFunctionName name of function
* @return function named
*/
const Function&
operator[](const XalanDOMString& theFunctionName) const
{
FunctionNameIndexMapType::const_iterator i =
m_FunctionNameIndex.find(theFunctionName);
if (i != m_FunctionNameIndex.end())
{
return *m_FunctionCollection[(*i).second];
}
else
{
throw XPathExceptionFunctionNotAvailable(theFunctionName);
}
}
/**
* Retrieve the function object for a specified function ID number.
*
* @param theFunctionID ID number of the function
* @return function named
*/
const Function&
operator[](int theFunctionID) const
{
if (theFunctionID >= 0 &&
CollectionType::size_type(theFunctionID) < m_FunctionCollection.size())
{
return *m_FunctionCollection[theFunctionID];
}
else
{
throw XPathExceptionFunctionNotAvailable(theFunctionID);
}
}
enum { InvalidFunctionNumberID = -1 };
/**
* Map a function ID to the corresponding name.
*
* @param theFunctionID The ID number of the function
* @return The name of the function, or an empty string if the function doesn't exist.
*/
const XalanDOMString
idToName(int theFunctionID) const
{
XalanDOMString theName;
if (theFunctionID >= 0 &&
CollectionType::size_type(theFunctionID) < m_FunctionCollection.size())
{
FunctionNameIndexMapType::const_iterator i =
m_FunctionNameIndex.begin();
while (i != m_FunctionNameIndex.end())
{
if ((*i).second == theFunctionID)
{
theName = (*i).first;
break;
}
}
}
return theName;
}
/**
* Map a function name to the corresponding ID number.
*
* @param theName name of function
* @return The ID number of function, or InvalidFunctionNumberID if the function doesn't exist.
*/
int
nameToID(const XalanDOMString& theName) const
{
const FunctionNameIndexMapType::const_iterator i =
m_FunctionNameIndex.find(theName);
if (i != m_FunctionNameIndex.end())
{
return (*i).second;
}
else
{
return InvalidFunctionNumberID;
}
}
/**
* Insert a named function into the function table.
*
* @param theFunctionName name of function
* @param theFunction function object corresponding to name
*/
void
InstallFunction(
const XalanDOMString& theFunctionName,
const Function& theFunction);
/**
* Remove a named function from the function table.
*
* @param theFunctionName name of function
* @return true if the function was found and removed.
*/
bool
UninstallFunction(const XalanDOMString& theFunctionName);
/**
* Whether a named function is in the function table.
*
* @param theFunctionName name of function
* @return true if function is in table
*/
bool
isInstalledFunction(const XalanDOMString& theFunctionName) const
{
if (m_FunctionNameIndex.find(theFunctionName) != m_FunctionNameIndex.end())
{
return true;
}
else
{
return false;
}
}
#if defined(XALAN_NO_MEMBER_TEMPLATES)
#if defined(XALAN_NO_NAMESPACES)
typedef vector<XalanDOMString> InstalledFunctionNameVectorType;
#else
typedef std::vector<XalanDOMString> InstalledFunctionNameVectorType;
#endif
/**
* Add a list of the names of installed functions to a vector of names.
*
* @param theVector vector of function name strings added to
*/
void
getInstalledFunctionNames(InstalledFunctionNameVectorType& theVector) const
{
FunctionNameIndexMapType::const_iterator i =
m_FunctionNameIndex.begin();
while(i != m_FunctionNameIndex.end())
{
theVector.push_back((*i).first);
++i;
}
}
#else
/**
* Add a list of the names of installed functions to a vector of names.
*
* @param theIterator function table iterator to append names to
*/
template<class OutputIteratorType>
void
getInstalledFunctionNames(OutputIteratorType theIterator) const
{
FunctionNameIndexMapType::const_iterator i =
m_FunctionNameIndex.begin();
while(i != m_FunctionNameIndex.end())
{
*theIterator = (*i).first;
++i;
++theIterator;
}
}
#endif
private:
CollectionType m_FunctionCollection;
FunctionNameIndexMapType m_FunctionNameIndex;
// The string "id"
static const XalanDOMChar s_id[];
// The string "not"
static const XalanDOMChar s_not[];
// The string "sum"
static const XalanDOMChar s_sum[];
// The string "lang"
static const XalanDOMChar s_lang[];
// The string "last"
static const XalanDOMChar s_last[];
// The string "name"
static const XalanDOMChar s_name[];
// The string "true"
static const XalanDOMChar s_true[];
// The string "count"
static const XalanDOMChar s_count[];
// The string "false"
static const XalanDOMChar s_false[];
// The string "floor"
static const XalanDOMChar s_floor[];
// The string "round"
static const XalanDOMChar s_round[];
// The string "concat"
static const XalanDOMChar s_concat[];
// The string "number"
static const XalanDOMChar s_number[];
// The string "string"
static const XalanDOMChar s_string[];
// The string "boolean"
static const XalanDOMChar s_boolean[];
// The string "ceiling"
static const XalanDOMChar s_ceiling[];
// The string "contains"
static const XalanDOMChar s_contains[];
// The string "position"
static const XalanDOMChar s_position[];
// The string "substring"
static const XalanDOMChar s_substring[];
// The string "translate"
static const XalanDOMChar s_translate[];
// The string "local-name"
static const XalanDOMChar s_localName[];
// The string "starts-with"
static const XalanDOMChar s_startsWith[];
// The string "namespace-uri"
static const XalanDOMChar s_namespaceUri[];
// The string "string-length"
static const XalanDOMChar s_stringLength[];
// The string "normalize-space"
static const XalanDOMChar s_normalizeSpace[];
// The string "substring-after"
static const XalanDOMChar s_substringAfter[];
// The string "substring-before"
static const XalanDOMChar s_substringBefore[];
};
#endif // XPATHFUNCTIONTABLE_HEADER_GUARD_1357924680
<commit_msg>Don't check range.<commit_after>/*
* The Apache Software License, Version 1.1
*
*
* Copyright (c) 1999-2002 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 apache@apache.org.
*
* 5. Products derived from this software may not be called "Apache",
* nor may "Apache" appear in their name, without prior written
* permission of the Apache Software Foundation.
*
* THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR
* ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
* USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
* OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation and was
* originally based on software copyright (c) 1999, International
* Business Machines, Inc., http://www.ibm.com. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*/
#if !defined(XPATHFUNCTIONTABLE_HEADER_GUARD_1357924680)
#define XPATHFUNCTIONTABLE_HEADER_GUARD_1357924680
// Base include file. Must be first.
#include <XPath/XPathDefinitions.hpp>
#include <algorithm>
#include <map>
#include <XalanDOM/XalanDOMString.hpp>
#include <Include/STLHelper.hpp>
#include <XPath/Function.hpp>
#include <XPath/XalanXPathException.hpp>
class Locator;
/**
* Exception class thrown when an unknown function is encountered
*/
class XALAN_XPATH_EXPORT XPathExceptionFunctionNotAvailable : public XalanXPathException
{
public:
XPathExceptionFunctionNotAvailable(int theFunctionNumber);
XPathExceptionFunctionNotAvailable(const XalanDOMString& theFunctionName);
XPathExceptionFunctionNotAvailable(
int theFunctionNumber,
const Locator& theLocator);
XPathExceptionFunctionNotAvailable(
const XalanDOMString& theFunctionName,
const Locator& theLocator);
~XPathExceptionFunctionNotAvailable();
};
/**
* Class defines a table of functions that can be called in XPath expresions.
*/
class XALAN_XPATH_EXPORT XPathFunctionTable
{
public:
#if defined(XALAN_NO_NAMESPACES)
typedef vector<const Function*> CollectionType;
typedef map<XalanDOMString,
int,
less<XalanDOMString> > FunctionNameIndexMapType;
#else
typedef std::vector<const Function*> CollectionType;
typedef std::map<XalanDOMString, int> FunctionNameIndexMapType;
#endif
enum { eDefaultTableSize = 36 };
typedef DeleteFunctor<Function> DeleteFunctorType;
/**
* Constructor.
*
* @param fCreateTable If true, the internal table will be created. Otherwise, CreateTable() must be called.
*/
XPathFunctionTable(bool fCreateTable = true);
~XPathFunctionTable();
/**
* Set up the internal table.
*/
void
CreateTable();
/**
* Destroy the internal table.
*/
void
DestroyTable();
/**
* Retrieve the function object for a specified function name.
*
* @param theFunctionName name of function
* @return function named
*/
const Function&
operator[](const XalanDOMString& theFunctionName) const
{
FunctionNameIndexMapType::const_iterator i =
m_FunctionNameIndex.find(theFunctionName);
if (i != m_FunctionNameIndex.end())
{
return *m_FunctionCollection[(*i).second];
}
else
{
throw XPathExceptionFunctionNotAvailable(theFunctionName);
}
}
/**
* Retrieve the function object for a specified function ID number.
*
* @param theFunctionID ID number of the function
* @return function named
*/
const Function&
operator[](int theFunctionID) const
{
assert(theFunctionID >= 0 &&
CollectionType::size_type(theFunctionID) < m_FunctionCollection.size());
return *m_FunctionCollection[theFunctionID];
}
enum { InvalidFunctionNumberID = -1 };
/**
* Map a function ID to the corresponding name.
*
* @param theFunctionID The ID number of the function
* @return The name of the function, or an empty string if the function doesn't exist.
*/
const XalanDOMString
idToName(int theFunctionID) const
{
XalanDOMString theName;
if (theFunctionID >= 0 &&
CollectionType::size_type(theFunctionID) < m_FunctionCollection.size())
{
FunctionNameIndexMapType::const_iterator i =
m_FunctionNameIndex.begin();
while (i != m_FunctionNameIndex.end())
{
if ((*i).second == theFunctionID)
{
theName = (*i).first;
break;
}
}
}
return theName;
}
/**
* Map a function name to the corresponding ID number.
*
* @param theName name of function
* @return The ID number of function, or InvalidFunctionNumberID if the function doesn't exist.
*/
int
nameToID(const XalanDOMString& theName) const
{
const FunctionNameIndexMapType::const_iterator i =
m_FunctionNameIndex.find(theName);
if (i != m_FunctionNameIndex.end())
{
return (*i).second;
}
else
{
return InvalidFunctionNumberID;
}
}
/**
* Insert a named function into the function table.
*
* @param theFunctionName name of function
* @param theFunction function object corresponding to name
*/
void
InstallFunction(
const XalanDOMString& theFunctionName,
const Function& theFunction);
/**
* Remove a named function from the function table.
*
* @param theFunctionName name of function
* @return true if the function was found and removed.
*/
bool
UninstallFunction(const XalanDOMString& theFunctionName);
/**
* Whether a named function is in the function table.
*
* @param theFunctionName name of function
* @return true if function is in table
*/
bool
isInstalledFunction(const XalanDOMString& theFunctionName) const
{
if (m_FunctionNameIndex.find(theFunctionName) != m_FunctionNameIndex.end())
{
return true;
}
else
{
return false;
}
}
#if defined(XALAN_NO_MEMBER_TEMPLATES)
#if defined(XALAN_NO_NAMESPACES)
typedef vector<XalanDOMString> InstalledFunctionNameVectorType;
#else
typedef std::vector<XalanDOMString> InstalledFunctionNameVectorType;
#endif
/**
* Add a list of the names of installed functions to a vector of names.
*
* @param theVector vector of function name strings added to
*/
void
getInstalledFunctionNames(InstalledFunctionNameVectorType& theVector) const
{
FunctionNameIndexMapType::const_iterator i =
m_FunctionNameIndex.begin();
while(i != m_FunctionNameIndex.end())
{
theVector.push_back((*i).first);
++i;
}
}
#else
/**
* Add a list of the names of installed functions to a vector of names.
*
* @param theIterator function table iterator to append names to
*/
template<class OutputIteratorType>
void
getInstalledFunctionNames(OutputIteratorType theIterator) const
{
FunctionNameIndexMapType::const_iterator i =
m_FunctionNameIndex.begin();
while(i != m_FunctionNameIndex.end())
{
*theIterator = (*i).first;
++i;
++theIterator;
}
}
#endif
private:
CollectionType m_FunctionCollection;
FunctionNameIndexMapType m_FunctionNameIndex;
// The string "id"
static const XalanDOMChar s_id[];
// The string "not"
static const XalanDOMChar s_not[];
// The string "sum"
static const XalanDOMChar s_sum[];
// The string "lang"
static const XalanDOMChar s_lang[];
// The string "last"
static const XalanDOMChar s_last[];
// The string "name"
static const XalanDOMChar s_name[];
// The string "true"
static const XalanDOMChar s_true[];
// The string "count"
static const XalanDOMChar s_count[];
// The string "false"
static const XalanDOMChar s_false[];
// The string "floor"
static const XalanDOMChar s_floor[];
// The string "round"
static const XalanDOMChar s_round[];
// The string "concat"
static const XalanDOMChar s_concat[];
// The string "number"
static const XalanDOMChar s_number[];
// The string "string"
static const XalanDOMChar s_string[];
// The string "boolean"
static const XalanDOMChar s_boolean[];
// The string "ceiling"
static const XalanDOMChar s_ceiling[];
// The string "contains"
static const XalanDOMChar s_contains[];
// The string "position"
static const XalanDOMChar s_position[];
// The string "substring"
static const XalanDOMChar s_substring[];
// The string "translate"
static const XalanDOMChar s_translate[];
// The string "local-name"
static const XalanDOMChar s_localName[];
// The string "starts-with"
static const XalanDOMChar s_startsWith[];
// The string "namespace-uri"
static const XalanDOMChar s_namespaceUri[];
// The string "string-length"
static const XalanDOMChar s_stringLength[];
// The string "normalize-space"
static const XalanDOMChar s_normalizeSpace[];
// The string "substring-after"
static const XalanDOMChar s_substringAfter[];
// The string "substring-before"
static const XalanDOMChar s_substringBefore[];
};
#endif // XPATHFUNCTIONTABLE_HEADER_GUARD_1357924680
<|endoftext|> |
<commit_before>#pragma once
#ifndef WTL_CONCURRENT_HPP_
#define WTL_CONCURRENT_HPP_
#include <thread>
#include <mutex>
#include <condition_variable>
#include <future>
#include <chrono>
#include <vector>
#include <queue>
#include <memory>
#include <type_traits>
/////////1/////////2/////////3/////////4/////////5/////////6/////////7/////////
namespace wtl {
/////////1/////////2/////////3/////////4/////////5/////////6/////////7/////////
// compatible with std::lock_guard<BasicLockable>
class Semaphore {
public:
explicit
Semaphore(unsigned int n=std::thread::hardware_concurrency()) noexcept:
count_(n) {}
void lock() {
std::unique_lock<std::mutex> lck(mutex_);
condition_.wait(lck, [this]{return count_ > 0;});
--count_;
}
void unlock() {
std::lock_guard<std::mutex> lck(mutex_);
++count_;
condition_.notify_one();
}
// Pythonic alias
void acquire() {lock();}
void release() {unlock();}
private:
std::mutex mutex_;
std::condition_variable condition_;
unsigned int count_;
};
/////////1/////////2/////////3/////////4/////////5/////////6/////////7/////////
template <typename T> inline
std::future_status status(const std::future<T>& future) {
return future.wait_for(std::chrono::seconds(0));
}
template <typename T> inline
bool is_ready(const std::future<T>& future) {
return status(future) == std::future_status::ready;
}
/////////1/////////2/////////3/////////4/////////5/////////6/////////7/////////
class BasicTask {
public:
BasicTask() noexcept = default;
BasicTask(BasicTask&&) noexcept = default;
BasicTask(const BasicTask&) = delete;
virtual ~BasicTask() = default;
virtual void operator()() = 0;
};
template <typename result_t>
class Task: public BasicTask {
public:
template <class Func>
Task(Func&& func) noexcept: std_task_(std::forward<Func>(func)) {}
std::future<result_t> get_future() {return std_task_.get_future();}
void operator()() override {std_task_();}
private:
std::packaged_task<result_t()> std_task_;
};
static_assert(!std::is_default_constructible<Task<void>>{}, "");
static_assert(!std::is_copy_constructible<Task<void>>{}, "");
static_assert(std::is_nothrow_move_constructible<Task<void>>{}, "");
class ThreadPool {
public:
ThreadPool(unsigned int n) {
for (unsigned int i=0; i<n; ++i) {
threads_.emplace_back(&ThreadPool::run, this);
}
}
~ThreadPool() {
is_being_destroyed_ = true;
condition_run_.notify_all();
for (auto& th: threads_) {
th.join();
}
}
template <class Func>
void submit(Func&& func) {
std::lock_guard<std::mutex> lck(mutex_);
tasks_.push(std::make_unique<Task<void>>(std::forward<Func>(func)));
condition_run_.notify_one();
}
template <class Func, class... Args>
auto submit(Func&& func, Args&&... args) {
#if __cplusplus >= 201703L
using result_t = std::invoke_result_t<Func, Args...>;
#else
using result_t = std::result_of_t<Func(Args...)>;
#endif
std::lock_guard<std::mutex> lck(mutex_);
auto task = std::make_unique<Task<result_t>>(std::bind(func, args...));
std::future<result_t> ftr = task->get_future();
tasks_.push(std::move(task));
condition_run_.notify_one();
return ftr;
}
// wait for worker threads to finish all tasks without executing join()
void wait() {
std::unique_lock<std::mutex> lck(mutex_);
condition_wait_.wait(lck, [this]{
return tasks_.empty() &&
(waiting_threads_ == static_cast<unsigned int>(threads_.size()));
});
}
private:
void run() {
std::unique_ptr<BasicTask> task = nullptr;
while (true) {
{
std::unique_lock<std::mutex> lck(mutex_);
++waiting_threads_;
condition_wait_.notify_one();
condition_run_.wait(lck, [this] {
return !tasks_.empty() || is_being_destroyed_;
});
--waiting_threads_;
if (tasks_.empty()) return;
task = std::move(tasks_.front());
tasks_.pop();
}
(*task)();
}
}
std::vector<std::thread> threads_;
std::queue<std::unique_ptr<BasicTask>> tasks_;
std::mutex mutex_;
std::condition_variable condition_run_;
std::condition_variable condition_wait_;
bool is_being_destroyed_ = false;
unsigned int waiting_threads_ = 0;
};
/////////1/////////2/////////3/////////4/////////5/////////6/////////7/////////
} // namespace wtl
/////////1/////////2/////////3/////////4/////////5/////////6/////////7/////////
#endif /* WTL_CONCURRENT_HPP_ */
<commit_msg>:art: Prefer lambda to std::bind<commit_after>#pragma once
#ifndef WTL_CONCURRENT_HPP_
#define WTL_CONCURRENT_HPP_
#include <thread>
#include <mutex>
#include <condition_variable>
#include <future>
#include <chrono>
#include <vector>
#include <queue>
#include <memory>
#include <type_traits>
/////////1/////////2/////////3/////////4/////////5/////////6/////////7/////////
namespace wtl {
/////////1/////////2/////////3/////////4/////////5/////////6/////////7/////////
// compatible with std::lock_guard<BasicLockable>
class Semaphore {
public:
explicit
Semaphore(unsigned int n=std::thread::hardware_concurrency()) noexcept:
count_(n) {}
void lock() {
std::unique_lock<std::mutex> lck(mutex_);
condition_.wait(lck, [this]{return count_ > 0;});
--count_;
}
void unlock() {
std::lock_guard<std::mutex> lck(mutex_);
++count_;
condition_.notify_one();
}
// Pythonic alias
void acquire() {lock();}
void release() {unlock();}
private:
std::mutex mutex_;
std::condition_variable condition_;
unsigned int count_;
};
/////////1/////////2/////////3/////////4/////////5/////////6/////////7/////////
template <typename T> inline
std::future_status status(const std::future<T>& future) {
return future.wait_for(std::chrono::seconds(0));
}
template <typename T> inline
bool is_ready(const std::future<T>& future) {
return status(future) == std::future_status::ready;
}
/////////1/////////2/////////3/////////4/////////5/////////6/////////7/////////
class BasicTask {
public:
BasicTask() noexcept = default;
BasicTask(BasicTask&&) noexcept = default;
BasicTask(const BasicTask&) = delete;
virtual ~BasicTask() = default;
virtual void operator()() = 0;
};
template <typename result_t>
class Task: public BasicTask {
public:
template <class Func>
Task(Func&& func) noexcept: std_task_(std::forward<Func>(func)) {}
std::future<result_t> get_future() {return std_task_.get_future();}
void operator()() override {std_task_();}
private:
std::packaged_task<result_t()> std_task_;
};
static_assert(!std::is_default_constructible<Task<void>>{}, "");
static_assert(!std::is_copy_constructible<Task<void>>{}, "");
static_assert(std::is_nothrow_move_constructible<Task<void>>{}, "");
class ThreadPool {
public:
ThreadPool(unsigned int n) {
for (unsigned int i=0; i<n; ++i) {
threads_.emplace_back(&ThreadPool::run, this);
}
}
~ThreadPool() {
is_being_destroyed_ = true;
condition_run_.notify_all();
for (auto& th: threads_) {
th.join();
}
}
template <class Func>
void submit(Func&& func) {
std::lock_guard<std::mutex> lck(mutex_);
tasks_.push(std::make_unique<Task<void>>(std::forward<Func>(func)));
condition_run_.notify_one();
}
template <class Func, class... Args>
auto submit(Func&& func, Args&&... args) {
#if __cplusplus >= 201703L
using result_t = std::invoke_result_t<Func, Args...>;
#else
using result_t = std::result_of_t<Func(Args...)>;
#endif
std::lock_guard<std::mutex> lck(mutex_);
auto task = std::make_unique<Task<result_t>>(
[&func, args...]{return func(args...);}
);
std::future<result_t> ftr = task->get_future();
tasks_.push(std::move(task));
condition_run_.notify_one();
return ftr;
}
// wait for worker threads to finish all tasks without executing join()
void wait() {
std::unique_lock<std::mutex> lck(mutex_);
condition_wait_.wait(lck, [this]{
return tasks_.empty() &&
(waiting_threads_ == static_cast<unsigned int>(threads_.size()));
});
}
private:
void run() {
std::unique_ptr<BasicTask> task = nullptr;
while (true) {
{
std::unique_lock<std::mutex> lck(mutex_);
++waiting_threads_;
condition_wait_.notify_one();
condition_run_.wait(lck, [this] {
return !tasks_.empty() || is_being_destroyed_;
});
--waiting_threads_;
if (tasks_.empty()) return;
task = std::move(tasks_.front());
tasks_.pop();
}
(*task)();
}
}
std::vector<std::thread> threads_;
std::queue<std::unique_ptr<BasicTask>> tasks_;
std::mutex mutex_;
std::condition_variable condition_run_;
std::condition_variable condition_wait_;
bool is_being_destroyed_ = false;
unsigned int waiting_threads_ = 0;
};
/////////1/////////2/////////3/////////4/////////5/////////6/////////7/////////
} // namespace wtl
/////////1/////////2/////////3/////////4/////////5/////////6/////////7/////////
#endif /* WTL_CONCURRENT_HPP_ */
<|endoftext|> |
<commit_before>#include <GL/gl.h>
#include <GL/glu.h>
#include <GL/glut.h>
#include <vector>
#include <math.h>
#include <iostream>
using namespace std;
#include <glm/glm.hpp>
#include <glm/gtc/matrix_transform.hpp>
#include <glm/gtx/rotate_vector.hpp>
#include <glm/gtx/norm.hpp>
typedef glm::mat3 mat3;
typedef glm::vec3 vec3;
const float pi = 3.14159265 ; // For portability across platforms
using namespace std;
void initCube(void);
static void redraw(void);
struct Cube {
vector<vec3> verts;
} sCube;
int partition = 20;
vec3 force_center(0,-10,0);
const float DISPLACE_PER_UNIT = 7;
// cube unfolding
// looking to -Z axis
// ___________
// | | |
// | 1 | 2 |
// |_____|_____|_____
// | | |
// | 3 | 4 |
// |_____|_____|_____
// | | |
// | 5 | 6 |
// |_____|_____|
//
// from - (front, left, bottom)
// to - (back, right, top)
void generatePolyCubeVerts(vec3 from, vec3 to, int face_partition, Cube &c) {
float sx = (to.x - from.x) / face_partition;
float sy = (to.y - from.y) / face_partition;
float sz = (to.z - from.z) / face_partition;
//1 (front)
for (int px = 0; px < face_partition; px++)
for (int py = 0; py < face_partition; py++) {
c.verts.push_back( vec3(from.x + px * sx, from.y + py * sy, from.z));
c.verts.push_back( vec3(from.x + px * sx, from.y + (py+1) * sy, from.z));
c.verts.push_back( vec3(from.x + (px+1) * sx, from.y + (py+1) * sy, from.z));
c.verts.push_back( vec3(from.x + (px+1) * sx, from.y + py * sy, from.z));
}
//4 (back)
for (int px = 0; px < face_partition; px++)
for (int py = 0; py < face_partition; py++) {
c.verts.push_back( vec3(from.x + px * sx, from.y + py * sy, to.z));
c.verts.push_back( vec3(from.x + (px+1) * sx, from.y + py * sy, to.z));
c.verts.push_back( vec3(from.x + (px+1) * sx, from.y + (py+1) * sy, to.z));
c.verts.push_back( vec3(from.x + px * sx, from.y + (py+1) * sy, to.z));
}
//2 (right)
for (int pz = 0; pz < face_partition; pz++)
for (int py = 0; py < face_partition; py++) {
c.verts.push_back( vec3(to.x, from.y + py * sy, from.z + pz * sz));
c.verts.push_back( vec3(to.x, from.y + (py+1) * sy, from.z + pz * sz));
c.verts.push_back( vec3(to.x, from.y + (py+1) * sy, from.z + (pz+1) * sz));
c.verts.push_back( vec3(to.x, from.y + py * sy, from.z + (pz+1) * sz));
}
// 6 (left)
for (int pz = 0; pz < face_partition; pz++)
for (int py = 0; py < face_partition; py++) {
c.verts.push_back( vec3(from.x, from.y + py * sy, from.z + pz * sz));
c.verts.push_back( vec3(from.x, from.y + py * sy, from.z + (pz+1) * sz));
c.verts.push_back( vec3(from.x, from.y + (py+1) * sy, from.z + (pz+1) * sz));
c.verts.push_back( vec3(from.x, from.y + (py+1) * sy, from.z + pz * sz));
}
// 5 (top)
for (int pz = 0; pz < face_partition; pz++)
for (int px = 0; px < face_partition; px++) {
c.verts.push_back( vec3(from.x + px*sx, to.y, from.z + pz * sz));
c.verts.push_back( vec3(from.x + px*sx, to.y, from.z + (pz+1) * sz));
c.verts.push_back( vec3(from.x + (px+1)*sx, to.y, from.z + (pz+1) * sz));
c.verts.push_back( vec3(from.x + (px+1)*sx, to.y, from.z + pz * sz));
}
return;
//3 (bottom)
for (int pz = 0; pz < face_partition; pz++)
for (int px = 0; px < face_partition; px++) {
c.verts.push_back( vec3(from.x + px*sx, from.y, from.z + pz * sz));
c.verts.push_back( vec3(from.x + px*sx, from.y, from.z + (pz+1) * sz));
c.verts.push_back( vec3(from.x + (px+1)*sx, from.y, from.z + (pz+1) * sz));
c.verts.push_back( vec3(from.x + (px+1)*sx, from.y, from.z + pz * sz));
}
}
void initCube(void)
{
generatePolyCubeVerts(vec3(-10,-10,-10), vec3(10,10,10), partition, sCube);
}
mat3 rotate(const float degrees, const vec3& axis)
{
double phi = degrees/180 * pi;
vec3 u = glm::normalize(axis);
return mat3 (
cos(phi) + u.x * u.x * (1 - cos(phi)),
u.x * u.y * (1 - cos(phi)) - u.z * sin(phi),
u.x * u.z * (1 - cos(phi)) + u.y * sin(phi),
u.y * u.x * (1 - cos(phi)) + u.z * sin(phi),
cos(phi) + u.y * u.y * (1 - cos(phi)),
u.y * u.z * (1 - cos(phi)) - u.x * sin(phi),
u.z * u.x * (1 - cos(phi)) - u.y * sin(phi),
u.z * u.y * (1 - cos(phi)) + u.x * sin(phi),
cos(phi) + u.z * u.z * (1 - cos(phi)));
}
float calcDisplace(const vec3 &v) {
float dist = glm::gtx::norm::l2Norm(v, force_center);
// cout << "disp = " << dist*DISPLACE_PER_UNIT << endl;
// return 0;
return DISPLACE_PER_UNIT*dist;
}
float rSpeed = 8;
float rAccel = 0.9;
float yRot = 0;
vec3 rotFunc1(const vec3 &v, vec3 axis, int t) {
vec3 rv;
// float rotateBy = t % 360;
float rotateBy = t;
float delay = calcDisplace(v);
rotateBy -= delay;
if (rotateBy < 0.01)
rotateBy = 0;
if (rotateBy > 360)
rotateBy = 360;
// cout << delay << endl;
rv = glm::rotate(v, rotateBy, axis);
return rv;
}
static void redraw(void)
{
static float t=0;
int a,b;
unsigned int currentVer;
// if (rotateBy > 360) {
// rotateBy -= 360;
// if (yRot >= 0.9)
// yRot = 0.0;
// else yRot = 0.91;
// }
t+=rSpeed;
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
glPolygonMode( GL_FRONT_AND_BACK, GL_LINE );
glPushMatrix();
glTranslatef(0,0,-50);
// glRotatef(rotateBy,0,1,0.6);
glBegin(GL_QUADS);
for (int i = 0; i < sCube.verts.size(); i++) {
vec3 cv = sCube.verts[i];
cv = rotFunc1(cv, vec3(0,1,0.2), t);
cv = rotFunc1(cv, vec3(0,0.2,1), t-270);
cv = rotFunc1(cv, vec3(1,1,1), t-490);
float v[3] = {cv.x, cv.y, cv.z};
float col[3] = {(i%255)/255.0,(i%255)/255.0,(i%255)/255.0};
glColor3fv(col);
glVertex3fv(v);
// sCube.verts[i] = cv;
}
rSpeed += rAccel;
if (rSpeed > 15)
rAccel =- rAccel;
if (rSpeed < 4)
rAccel =- rAccel;
glEnd();
glPopMatrix();
glutSwapBuffers();
glutPostRedisplay();
}
int main(int argc, char **argv)
{
glutInit(&argc,argv);
glutInitDisplayMode(GLUT_RGB | GLUT_DOUBLE | GLUT_DEPTH);
glutCreateWindow("Vector slime demo");
glutDisplayFunc(redraw);
glMatrixMode(GL_PROJECTION); //hello
gluPerspective(45, //view angle
1.0, //aspect ratio
10.0, //near clip
10000.0);//far clip
glMatrixMode(GL_MODELVIEW);
glEnable(GL_CULL_FACE);
initCube();
glutMainLoop();
return 0;
}
<commit_msg>some refactring<commit_after>#include <GL/gl.h>
#include <GL/glu.h>
#include <GL/glut.h>
#include <vector>
#include <math.h>
#include <iostream>
using namespace std;
#include <glm/glm.hpp>
#include <glm/gtc/matrix_transform.hpp>
#include <glm/gtx/rotate_vector.hpp>
#include <glm/gtx/norm.hpp>
typedef glm::mat3 mat3;
typedef glm::vec3 vec3;
const float pi = 3.14159265 ; // For portability across platforms
using namespace std;
void initCube(void);
static void redraw(void);
struct Cube {
vector<vec3> verts;
} sCube;
int partition = 20;
vec3 force_center(0,-10,0);
const float DISPLACE_PER_UNIT = 7;
// cube unfolding
// looking to -Z axis
// ___________
// | | |
// | 1 | 2 |
// |_____|_____|_____
// | | |
// | 3 | 4 |
// |_____|_____|_____
// | | |
// | 5 | 6 |
// |_____|_____|
//
// from - (front, left, bottom)
// to - (back, right, top)
void generatePolyCubeVerts(vec3 from, vec3 to, int face_partition, Cube &c) {
float sx = (to.x - from.x) / face_partition;
float sy = (to.y - from.y) / face_partition;
float sz = (to.z - from.z) / face_partition;
//1 (front)
for (int px = 0; px < face_partition; px++)
for (int py = 0; py < face_partition; py++) {
c.verts.push_back( vec3(from.x + px * sx, from.y + py * sy, from.z));
c.verts.push_back( vec3(from.x + px * sx, from.y + (py+1) * sy, from.z));
c.verts.push_back( vec3(from.x + (px+1) * sx, from.y + (py+1) * sy, from.z));
c.verts.push_back( vec3(from.x + (px+1) * sx, from.y + py * sy, from.z));
}
//4 (back)
for (int px = 0; px < face_partition; px++)
for (int py = 0; py < face_partition; py++) {
c.verts.push_back( vec3(from.x + px * sx, from.y + py * sy, to.z));
c.verts.push_back( vec3(from.x + (px+1) * sx, from.y + py * sy, to.z));
c.verts.push_back( vec3(from.x + (px+1) * sx, from.y + (py+1) * sy, to.z));
c.verts.push_back( vec3(from.x + px * sx, from.y + (py+1) * sy, to.z));
}
//2 (right)
for (int pz = 0; pz < face_partition; pz++)
for (int py = 0; py < face_partition; py++) {
c.verts.push_back( vec3(to.x, from.y + py * sy, from.z + pz * sz));
c.verts.push_back( vec3(to.x, from.y + (py+1) * sy, from.z + pz * sz));
c.verts.push_back( vec3(to.x, from.y + (py+1) * sy, from.z + (pz+1) * sz));
c.verts.push_back( vec3(to.x, from.y + py * sy, from.z + (pz+1) * sz));
}
// 6 (left)
for (int pz = 0; pz < face_partition; pz++)
for (int py = 0; py < face_partition; py++) {
c.verts.push_back( vec3(from.x, from.y + py * sy, from.z + pz * sz));
c.verts.push_back( vec3(from.x, from.y + py * sy, from.z + (pz+1) * sz));
c.verts.push_back( vec3(from.x, from.y + (py+1) * sy, from.z + (pz+1) * sz));
c.verts.push_back( vec3(from.x, from.y + (py+1) * sy, from.z + pz * sz));
}
// 5 (top)
for (int pz = 0; pz < face_partition; pz++)
for (int px = 0; px < face_partition; px++) {
c.verts.push_back( vec3(from.x + px*sx, to.y, from.z + pz * sz));
c.verts.push_back( vec3(from.x + px*sx, to.y, from.z + (pz+1) * sz));
c.verts.push_back( vec3(from.x + (px+1)*sx, to.y, from.z + (pz+1) * sz));
c.verts.push_back( vec3(from.x + (px+1)*sx, to.y, from.z + pz * sz));
}
return;
//3 (bottom)
for (int pz = 0; pz < face_partition; pz++)
for (int px = 0; px < face_partition; px++) {
c.verts.push_back( vec3(from.x + px*sx, from.y, from.z + pz * sz));
c.verts.push_back( vec3(from.x + px*sx, from.y, from.z + (pz+1) * sz));
c.verts.push_back( vec3(from.x + (px+1)*sx, from.y, from.z + (pz+1) * sz));
c.verts.push_back( vec3(from.x + (px+1)*sx, from.y, from.z + pz * sz));
}
}
void initCube(void)
{
generatePolyCubeVerts(vec3(-10,-10,-10), vec3(10,10,10), partition, sCube);
}
mat3 rotate(const float degrees, const vec3& axis)
{
double phi = degrees/180 * pi;
vec3 u = glm::normalize(axis);
return mat3 (
cos(phi) + u.x * u.x * (1 - cos(phi)),
u.x * u.y * (1 - cos(phi)) - u.z * sin(phi),
u.x * u.z * (1 - cos(phi)) + u.y * sin(phi),
u.y * u.x * (1 - cos(phi)) + u.z * sin(phi),
cos(phi) + u.y * u.y * (1 - cos(phi)),
u.y * u.z * (1 - cos(phi)) - u.x * sin(phi),
u.z * u.x * (1 - cos(phi)) - u.y * sin(phi),
u.z * u.y * (1 - cos(phi)) + u.x * sin(phi),
cos(phi) + u.z * u.z * (1 - cos(phi)));
}
float calcDisplace(const vec3 &v) {
float dist = glm::gtx::norm::l2Norm(v, force_center);
// cout << "disp = " << dist*DISPLACE_PER_UNIT << endl;
// return 0;
return DISPLACE_PER_UNIT*dist;
}
vec3 rotFunc1(const vec3 &v, vec3 axis, int t) {
vec3 rv;
// float rotateBy = t % 360;
float rotateBy = t;
float delay = calcDisplace(v);
rotateBy -= delay;
if (rotateBy < 0.01) {
return v;
}
if (rotateBy > 360) {
return v;
}
// cout << delay << endl;
rv = glm::rotate(v, rotateBy, axis);
return rv;
}
float rSpeed = 3;
float rAccel = 0.2;
float yRot = 0;
float rUpper = 10;
float rLower = 3;
static void redraw(void)
{
static float t=0;
int a,b;
unsigned int currentVer;
// if (rotateBy > 360) {
// rotateBy -= 360;
// if (yRot >= 0.9)
// yRot = 0.0;
// else yRot = 0.91;
// }
t+=rSpeed;
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
glPolygonMode( GL_FRONT_AND_BACK, GL_LINE );
glPushMatrix();
glTranslatef(0,0,-50);
// glRotatef(rotateBy,0,1,0.6);
glBegin(GL_QUADS);
for (int i = 0; i < sCube.verts.size(); i++) {
vec3 cv = sCube.verts[i];
cv = rotFunc1(cv, vec3(0,1,0.2), t);
cv = rotFunc1(cv, vec3(0,0.2,1), t-270);
cv = rotFunc1(cv, vec3(1,1,1), t-490);
float v[3] = {cv.x, cv.y, cv.z};
float col[3] = {(i%255)/255.0,(i%255)/255.0,(i%255)/255.0};
glColor3fv(col);
glVertex3fv(v);
// sCube.verts[i] = cv;
}
rSpeed += rAccel;
if (rSpeed > rUpper)
rAccel =- rAccel;
if (rSpeed < rLower)
rAccel =- rAccel;
glEnd();
glPopMatrix();
glutSwapBuffers();
glutPostRedisplay();
}
int main(int argc, char **argv)
{
glutInit(&argc,argv);
glutInitDisplayMode(GLUT_RGB | GLUT_DOUBLE | GLUT_DEPTH);
glutCreateWindow("Vector slime demo");
glutDisplayFunc(redraw);
glMatrixMode(GL_PROJECTION); //hello
gluPerspective(45, //view angle
1.0, //aspect ratio
10.0, //near clip
10000.0);//far clip
glMatrixMode(GL_MODELVIEW);
glEnable(GL_CULL_FACE);
initCube();
glutMainLoop();
return 0;
}
<|endoftext|> |
<commit_before>/*
* Copyright 2017 Facebook, 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.
*/
#include <folly/io/async/ssl/SSLErrors.h>
#include <folly/Range.h>
#include <openssl/err.h>
#include <openssl/ssl.h>
using namespace folly;
namespace {
std::string decodeOpenSSLError(
int sslError,
unsigned long errError,
int sslOperationReturnValue) {
if (sslError == SSL_ERROR_SYSCALL && errError == 0) {
if (sslOperationReturnValue == 0) {
return "Connection EOF";
} else {
// In this case errno is set, AsyncSocketException will add it.
return "Network error";
}
} else if (sslError == SSL_ERROR_ZERO_RETURN) {
// This signifies a TLS closure alert.
return "SSL connection closed normally";
} else {
std::array<char, 256> buf;
ERR_error_string_n(errError, buf.data(), buf.size());
// OpenSSL will null terminate the string.
return std::string(buf.data());
}
}
const StringPiece getSSLErrorString(SSLError error) {
StringPiece ret;
switch (error) {
case SSLError::CLIENT_RENEGOTIATION:
ret = "Client tried to renegotiate with server";
break;
case SSLError::INVALID_RENEGOTIATION:
ret = "Attempt to start renegotiation, but unsupported";
break;
case SSLError::EARLY_WRITE:
ret = "Attempt to write before SSL connection established";
break;
case SSLError::SSL_ERROR:
ret = "SSL error";
break;
case SSLError::NETWORK_ERROR:
ret = "Network error";
break;
case SSLError::EOF_ERROR:
ret = "SSL connection closed normally";
break;
}
return ret;
}
AsyncSocketException::AsyncSocketExceptionType exTypefromSSLErrInfo(
int sslErr,
unsigned long errError,
int sslOperationReturnValue) {
if (sslErr == SSL_ERROR_ZERO_RETURN) {
return AsyncSocketException::END_OF_FILE;
} else if (sslErr == SSL_ERROR_SYSCALL) {
if (errError == 0 && sslOperationReturnValue == 0) {
return AsyncSocketException::END_OF_FILE;
} else {
return AsyncSocketException::NETWORK_ERROR;
}
} else {
// Assume an actual SSL error
return AsyncSocketException::SSL_ERROR;
}
}
AsyncSocketException::AsyncSocketExceptionType exTypefromSSLErr(SSLError err) {
switch (err) {
case SSLError::EOF_ERROR:
return AsyncSocketException::END_OF_FILE;
case SSLError::NETWORK_ERROR:
return AsyncSocketException::NETWORK_ERROR;
default:
// everything else is a SSL_ERROR
return AsyncSocketException::SSL_ERROR;
}
}
}
namespace folly {
SSLException::SSLException(
int sslErr,
unsigned long errError,
int sslOperationReturnValue,
int errno_copy)
: AsyncSocketException(
exTypefromSSLErrInfo(sslErr, errError, sslOperationReturnValue),
decodeOpenSSLError(sslErr, errError, sslOperationReturnValue),
sslErr == SSL_ERROR_SYSCALL ? errno_copy : 0) {
if (sslErr == SSL_ERROR_ZERO_RETURN) {
sslError = SSLError::EOF_ERROR;
} else if (sslErr == SSL_ERROR_SYSCALL) {
sslError = SSLError::NETWORK_ERROR;
} else {
// Conservatively assume that this is an SSL error
sslError = SSLError::SSL_ERROR;
}
}
SSLException::SSLException(SSLError error)
: AsyncSocketException(
exTypefromSSLErr(error),
getSSLErrorString(error).str(),
0),
sslError(error) {}
}
<commit_msg>include folly/portability/OpenSSL.h instead of openssl/*.h<commit_after>/*
* Copyright 2017 Facebook, 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.
*/
#include <folly/io/async/ssl/SSLErrors.h>
#include <folly/Range.h>
#include <folly/portability/OpenSSL.h>
using namespace folly;
namespace {
std::string decodeOpenSSLError(
int sslError,
unsigned long errError,
int sslOperationReturnValue) {
if (sslError == SSL_ERROR_SYSCALL && errError == 0) {
if (sslOperationReturnValue == 0) {
return "Connection EOF";
} else {
// In this case errno is set, AsyncSocketException will add it.
return "Network error";
}
} else if (sslError == SSL_ERROR_ZERO_RETURN) {
// This signifies a TLS closure alert.
return "SSL connection closed normally";
} else {
std::array<char, 256> buf;
ERR_error_string_n(errError, buf.data(), buf.size());
// OpenSSL will null terminate the string.
return std::string(buf.data());
}
}
const StringPiece getSSLErrorString(SSLError error) {
StringPiece ret;
switch (error) {
case SSLError::CLIENT_RENEGOTIATION:
ret = "Client tried to renegotiate with server";
break;
case SSLError::INVALID_RENEGOTIATION:
ret = "Attempt to start renegotiation, but unsupported";
break;
case SSLError::EARLY_WRITE:
ret = "Attempt to write before SSL connection established";
break;
case SSLError::SSL_ERROR:
ret = "SSL error";
break;
case SSLError::NETWORK_ERROR:
ret = "Network error";
break;
case SSLError::EOF_ERROR:
ret = "SSL connection closed normally";
break;
}
return ret;
}
AsyncSocketException::AsyncSocketExceptionType exTypefromSSLErrInfo(
int sslErr,
unsigned long errError,
int sslOperationReturnValue) {
if (sslErr == SSL_ERROR_ZERO_RETURN) {
return AsyncSocketException::END_OF_FILE;
} else if (sslErr == SSL_ERROR_SYSCALL) {
if (errError == 0 && sslOperationReturnValue == 0) {
return AsyncSocketException::END_OF_FILE;
} else {
return AsyncSocketException::NETWORK_ERROR;
}
} else {
// Assume an actual SSL error
return AsyncSocketException::SSL_ERROR;
}
}
AsyncSocketException::AsyncSocketExceptionType exTypefromSSLErr(SSLError err) {
switch (err) {
case SSLError::EOF_ERROR:
return AsyncSocketException::END_OF_FILE;
case SSLError::NETWORK_ERROR:
return AsyncSocketException::NETWORK_ERROR;
default:
// everything else is a SSL_ERROR
return AsyncSocketException::SSL_ERROR;
}
}
}
namespace folly {
SSLException::SSLException(
int sslErr,
unsigned long errError,
int sslOperationReturnValue,
int errno_copy)
: AsyncSocketException(
exTypefromSSLErrInfo(sslErr, errError, sslOperationReturnValue),
decodeOpenSSLError(sslErr, errError, sslOperationReturnValue),
sslErr == SSL_ERROR_SYSCALL ? errno_copy : 0) {
if (sslErr == SSL_ERROR_ZERO_RETURN) {
sslError = SSLError::EOF_ERROR;
} else if (sslErr == SSL_ERROR_SYSCALL) {
sslError = SSLError::NETWORK_ERROR;
} else {
// Conservatively assume that this is an SSL error
sslError = SSLError::SSL_ERROR;
}
}
SSLException::SSLException(SSLError error)
: AsyncSocketException(
exTypefromSSLErr(error),
getSSLErrorString(error).str(),
0),
sslError(error) {}
}
<|endoftext|> |
<commit_before>#include <franka_hw/service_server.h>
#include <franka/robot.h>
#include <ros/ros.h>
#include <array>
#include <functional>
#include <franka_hw/ErrorRecovery.h>
#include <franka_hw/SetCartesianImpedance.h>
#include <franka_hw/SetEEFrame.h>
#include <franka_hw/SetForceTorqueCollisionBehavior.h>
#include <franka_hw/SetFullCollisionBehavior.h>
#include <franka_hw/SetJointImpedance.h>
#include <franka_hw/SetKFrame.h>
#include <franka_hw/SetLoad.h>
#include <franka_hw/SetTimeScalingFactor.h>
namespace franka_hw {
ServiceServer::ServiceServer(franka::Robot* robot, ros::NodeHandle& node_handle)
: robot_(robot),
joint_impedance_server_(
node_handle.advertiseService<SetJointImpedance::Request,
SetJointImpedance::Response>(
"set_joint_impedance",
createErrorFunction<SetJointImpedance::Request,
SetJointImpedance::Response>(
std::bind(&ServiceServer::setJointImpedance,
this,
std::placeholders::_1,
std::placeholders::_2)))),
cartesian_impedance_server_(node_handle.advertiseService(
"set_cartesian_impedance",
createErrorFunction<SetCartesianImpedance::Request,
SetCartesianImpedance::Response>(
std::bind(&ServiceServer::setCartesianImpedance,
this,
std::placeholders::_1,
std::placeholders::_2)))),
EE_frame_server_(node_handle.advertiseService(
"set_EE_frame",
createErrorFunction<SetEEFrame::Request, SetEEFrame::Response>(
std::bind(&ServiceServer::setEEFrame,
this,
std::placeholders::_1,
std::placeholders::_2)))),
K_frame_server_(node_handle.advertiseService(
"set_K_frame",
createErrorFunction<SetKFrame::Request, SetKFrame::Response>(
std::bind(&ServiceServer::setKFrame,
this,
std::placeholders::_1,
std::placeholders::_2)))),
force_torque_collision_server_(node_handle.advertiseService(
"set_force_torque_collision_behavior",
createErrorFunction<SetForceTorqueCollisionBehavior::Request,
SetForceTorqueCollisionBehavior::Response>(
std::bind(&ServiceServer::setForceTorqueCollisionBehavior,
this,
std::placeholders::_1,
std::placeholders::_2)))),
full_collision_server_(node_handle.advertiseService(
"set_full_collision_behavior",
createErrorFunction<SetFullCollisionBehavior::Request,
SetFullCollisionBehavior::Response>(
std::bind(&ServiceServer::setFullCollisionBehavior,
this,
std::placeholders::_1,
std::placeholders::_2)))),
load_server_(node_handle.advertiseService(
"set_load",
createErrorFunction<SetLoad::Request, SetLoad::Response>(
std::bind(&ServiceServer::setLoad,
this,
std::placeholders::_1,
std::placeholders::_2)))),
time_scaling_server_(node_handle.advertiseService(
"set_time_scaling_factor",
createErrorFunction<SetTimeScalingFactor::Request,
SetTimeScalingFactor::Response>(
std::bind(&ServiceServer::setTimeScalingFactor,
this,
std::placeholders::_1,
std::placeholders::_2)))),
error_recovery_server_(node_handle.advertiseService(
"error_recovery",
createErrorFunction<ErrorRecovery::Request, ErrorRecovery::Response>(
std::bind(&ServiceServer::errorRecovery,
this,
std::placeholders::_1,
std::placeholders::_2)))) {}
bool ServiceServer::setCartesianImpedance(
SetCartesianImpedance::Request& req,
SetCartesianImpedance::Response& res) {
std::array<double, 6> cartesian_stiffness;
std::copy(req.cartesian_stiffness.cbegin(), req.cartesian_stiffness.cend(),
cartesian_stiffness.begin());
robot_->setCartesianImpedance(cartesian_stiffness);
return true;
}
bool ServiceServer::setJointImpedance(SetJointImpedance::Request& req,
SetJointImpedance::Response& res) {
std::array<double, 7> joint_stiffness;
std::copy(req.joint_stiffness.cbegin(), req.joint_stiffness.cend(),
joint_stiffness.begin());
robot_->setJointImpedance(joint_stiffness);
return true;
}
bool ServiceServer::setEEFrame(SetEEFrame::Request& req,
SetEEFrame::Response& res) {
std::array<double, 16> F_T_EE;
std::copy(req.F_T_EE.cbegin(), req.F_T_EE.cend(), F_T_EE.begin());
robot_->setEE(F_T_EE);
return true;
}
bool ServiceServer::setKFrame(SetKFrame::Request& req,
SetKFrame::Response& res) {
std::array<double, 16> EE_T_K;
std::copy(req.EE_T_K.cbegin(), req.EE_T_K.cend(), EE_T_K.begin());
robot_->setK(EE_T_K);
return true;
}
bool ServiceServer::setForceTorqueCollisionBehavior(
SetForceTorqueCollisionBehavior::Request& req,
SetForceTorqueCollisionBehavior::Response& res) {
std::array<double, 7> lower_torque_thresholds_nominal;
std::copy(req.lower_torque_thresholds_nominal.cbegin(),
req.lower_torque_thresholds_nominal.cend(),
lower_torque_thresholds_nominal.begin());
std::array<double, 7> upper_torque_thresholds_nominal;
std::copy(req.upper_torque_thresholds_nominal.cbegin(),
req.upper_torque_thresholds_nominal.cend(),
upper_torque_thresholds_nominal.begin());
std::array<double, 6> lower_force_thresholds_nominal;
std::copy(req.lower_force_thresholds_nominal.cbegin(),
req.lower_force_thresholds_nominal.cend(),
lower_force_thresholds_nominal.begin());
std::array<double, 6> upper_force_thresholds_nominal;
std::copy(req.upper_force_thresholds_nominal.cbegin(),
req.upper_force_thresholds_nominal.cend(),
upper_force_thresholds_nominal.begin());
robot_->setCollisionBehavior(
lower_torque_thresholds_nominal, upper_torque_thresholds_nominal,
lower_force_thresholds_nominal, upper_force_thresholds_nominal);
return true;
}
bool ServiceServer::setFullCollisionBehavior(
SetFullCollisionBehavior::Request& req,
SetFullCollisionBehavior::Response& res) {
std::array<double, 7> lower_torque_thresholds_acceleration;
std::copy(req.lower_torque_thresholds_acceleration.cbegin(),
req.lower_torque_thresholds_acceleration.cend(),
lower_torque_thresholds_acceleration.begin());
std::array<double, 7> upper_torque_thresholds_acceleration;
std::copy(req.upper_torque_thresholds_acceleration.cbegin(),
req.upper_torque_thresholds_acceleration.cend(),
upper_torque_thresholds_acceleration.begin());
std::array<double, 7> lower_torque_thresholds_nominal;
std::copy(req.lower_torque_thresholds_nominal.cbegin(),
req.lower_torque_thresholds_nominal.cend(),
lower_torque_thresholds_nominal.begin());
std::array<double, 7> upper_torque_thresholds_nominal;
std::copy(req.upper_torque_thresholds_nominal.cbegin(),
req.upper_torque_thresholds_nominal.cend(),
upper_torque_thresholds_nominal.begin());
std::array<double, 6> lower_force_thresholds_acceleration;
std::copy(req.lower_force_thresholds_acceleration.cbegin(),
req.lower_force_thresholds_acceleration.cend(),
lower_force_thresholds_acceleration.begin());
std::array<double, 6> upper_force_thresholds_acceleration;
std::copy(req.upper_force_thresholds_acceleration.cbegin(),
req.upper_force_thresholds_acceleration.cend(),
upper_force_thresholds_acceleration.begin());
std::array<double, 6> lower_force_thresholds_nominal;
std::copy(req.lower_force_thresholds_nominal.cbegin(),
req.lower_force_thresholds_nominal.cend(),
lower_force_thresholds_nominal.begin());
std::array<double, 6> upper_force_thresholds_nominal;
std::copy(req.upper_force_thresholds_nominal.cbegin(),
req.upper_force_thresholds_nominal.cend(),
upper_force_thresholds_nominal.begin());
robot_->setCollisionBehavior(
lower_torque_thresholds_acceleration,
upper_torque_thresholds_acceleration, lower_torque_thresholds_nominal,
upper_torque_thresholds_nominal, lower_force_thresholds_acceleration,
upper_force_thresholds_acceleration, lower_force_thresholds_nominal,
upper_force_thresholds_nominal);
return true;
}
bool ServiceServer::setLoad(SetLoad::Request& req, SetLoad::Response& res) {
double mass(req.mass);
std::array<double, 3> F_x_center_load;
std::copy(req.F_x_center_load.cbegin(), req.F_x_center_load.cend(),
F_x_center_load.begin());
std::array<double, 9> load_inertia;
std::copy(req.load_inertia.cbegin(), req.load_inertia.cend(),
load_inertia.begin());
robot_->setLoad(mass, F_x_center_load, load_inertia);
return true;
}
bool ServiceServer::setTimeScalingFactor(SetTimeScalingFactor::Request& req,
SetTimeScalingFactor::Response& res) {
robot_->setTimeScalingFactor(req.time_scaling_factor);
return true;
}
bool ServiceServer::errorRecovery(ErrorRecovery::Request& req,
ErrorRecovery::Response& res) {
robot_->automaticErrorRecovery();
return true;
}
} // namespace franka_hw
<commit_msg>removed unnecessary type declaration<commit_after>#include <franka_hw/service_server.h>
#include <franka/robot.h>
#include <ros/ros.h>
#include <array>
#include <functional>
#include <franka_hw/ErrorRecovery.h>
#include <franka_hw/SetCartesianImpedance.h>
#include <franka_hw/SetEEFrame.h>
#include <franka_hw/SetForceTorqueCollisionBehavior.h>
#include <franka_hw/SetFullCollisionBehavior.h>
#include <franka_hw/SetJointImpedance.h>
#include <franka_hw/SetKFrame.h>
#include <franka_hw/SetLoad.h>
#include <franka_hw/SetTimeScalingFactor.h>
namespace franka_hw {
ServiceServer::ServiceServer(franka::Robot* robot, ros::NodeHandle& node_handle)
: robot_(robot),
joint_impedance_server_(node_handle.advertiseService(
"set_joint_impedance",
createErrorFunction<SetJointImpedance::Request,
SetJointImpedance::Response>(
std::bind(&ServiceServer::setJointImpedance,
this,
std::placeholders::_1,
std::placeholders::_2)))),
cartesian_impedance_server_(node_handle.advertiseService(
"set_cartesian_impedance",
createErrorFunction<SetCartesianImpedance::Request,
SetCartesianImpedance::Response>(
std::bind(&ServiceServer::setCartesianImpedance,
this,
std::placeholders::_1,
std::placeholders::_2)))),
EE_frame_server_(node_handle.advertiseService(
"set_EE_frame",
createErrorFunction<SetEEFrame::Request, SetEEFrame::Response>(
std::bind(&ServiceServer::setEEFrame,
this,
std::placeholders::_1,
std::placeholders::_2)))),
K_frame_server_(node_handle.advertiseService(
"set_K_frame",
createErrorFunction<SetKFrame::Request, SetKFrame::Response>(
std::bind(&ServiceServer::setKFrame,
this,
std::placeholders::_1,
std::placeholders::_2)))),
force_torque_collision_server_(node_handle.advertiseService(
"set_force_torque_collision_behavior",
createErrorFunction<SetForceTorqueCollisionBehavior::Request,
SetForceTorqueCollisionBehavior::Response>(
std::bind(&ServiceServer::setForceTorqueCollisionBehavior,
this,
std::placeholders::_1,
std::placeholders::_2)))),
full_collision_server_(node_handle.advertiseService(
"set_full_collision_behavior",
createErrorFunction<SetFullCollisionBehavior::Request,
SetFullCollisionBehavior::Response>(
std::bind(&ServiceServer::setFullCollisionBehavior,
this,
std::placeholders::_1,
std::placeholders::_2)))),
load_server_(node_handle.advertiseService(
"set_load",
createErrorFunction<SetLoad::Request, SetLoad::Response>(
std::bind(&ServiceServer::setLoad,
this,
std::placeholders::_1,
std::placeholders::_2)))),
time_scaling_server_(node_handle.advertiseService(
"set_time_scaling_factor",
createErrorFunction<SetTimeScalingFactor::Request,
SetTimeScalingFactor::Response>(
std::bind(&ServiceServer::setTimeScalingFactor,
this,
std::placeholders::_1,
std::placeholders::_2)))),
error_recovery_server_(node_handle.advertiseService(
"error_recovery",
createErrorFunction<ErrorRecovery::Request, ErrorRecovery::Response>(
std::bind(&ServiceServer::errorRecovery,
this,
std::placeholders::_1,
std::placeholders::_2)))) {}
bool ServiceServer::setCartesianImpedance(
SetCartesianImpedance::Request& req,
SetCartesianImpedance::Response& res) {
std::array<double, 6> cartesian_stiffness;
std::copy(req.cartesian_stiffness.cbegin(), req.cartesian_stiffness.cend(),
cartesian_stiffness.begin());
robot_->setCartesianImpedance(cartesian_stiffness);
return true;
}
bool ServiceServer::setJointImpedance(SetJointImpedance::Request& req,
SetJointImpedance::Response& res) {
std::array<double, 7> joint_stiffness;
std::copy(req.joint_stiffness.cbegin(), req.joint_stiffness.cend(),
joint_stiffness.begin());
robot_->setJointImpedance(joint_stiffness);
return true;
}
bool ServiceServer::setEEFrame(SetEEFrame::Request& req,
SetEEFrame::Response& res) {
std::array<double, 16> F_T_EE;
std::copy(req.F_T_EE.cbegin(), req.F_T_EE.cend(), F_T_EE.begin());
robot_->setEE(F_T_EE);
return true;
}
bool ServiceServer::setKFrame(SetKFrame::Request& req,
SetKFrame::Response& res) {
std::array<double, 16> EE_T_K;
std::copy(req.EE_T_K.cbegin(), req.EE_T_K.cend(), EE_T_K.begin());
robot_->setK(EE_T_K);
return true;
}
bool ServiceServer::setForceTorqueCollisionBehavior(
SetForceTorqueCollisionBehavior::Request& req,
SetForceTorqueCollisionBehavior::Response& res) {
std::array<double, 7> lower_torque_thresholds_nominal;
std::copy(req.lower_torque_thresholds_nominal.cbegin(),
req.lower_torque_thresholds_nominal.cend(),
lower_torque_thresholds_nominal.begin());
std::array<double, 7> upper_torque_thresholds_nominal;
std::copy(req.upper_torque_thresholds_nominal.cbegin(),
req.upper_torque_thresholds_nominal.cend(),
upper_torque_thresholds_nominal.begin());
std::array<double, 6> lower_force_thresholds_nominal;
std::copy(req.lower_force_thresholds_nominal.cbegin(),
req.lower_force_thresholds_nominal.cend(),
lower_force_thresholds_nominal.begin());
std::array<double, 6> upper_force_thresholds_nominal;
std::copy(req.upper_force_thresholds_nominal.cbegin(),
req.upper_force_thresholds_nominal.cend(),
upper_force_thresholds_nominal.begin());
robot_->setCollisionBehavior(
lower_torque_thresholds_nominal, upper_torque_thresholds_nominal,
lower_force_thresholds_nominal, upper_force_thresholds_nominal);
return true;
}
bool ServiceServer::setFullCollisionBehavior(
SetFullCollisionBehavior::Request& req,
SetFullCollisionBehavior::Response& res) {
std::array<double, 7> lower_torque_thresholds_acceleration;
std::copy(req.lower_torque_thresholds_acceleration.cbegin(),
req.lower_torque_thresholds_acceleration.cend(),
lower_torque_thresholds_acceleration.begin());
std::array<double, 7> upper_torque_thresholds_acceleration;
std::copy(req.upper_torque_thresholds_acceleration.cbegin(),
req.upper_torque_thresholds_acceleration.cend(),
upper_torque_thresholds_acceleration.begin());
std::array<double, 7> lower_torque_thresholds_nominal;
std::copy(req.lower_torque_thresholds_nominal.cbegin(),
req.lower_torque_thresholds_nominal.cend(),
lower_torque_thresholds_nominal.begin());
std::array<double, 7> upper_torque_thresholds_nominal;
std::copy(req.upper_torque_thresholds_nominal.cbegin(),
req.upper_torque_thresholds_nominal.cend(),
upper_torque_thresholds_nominal.begin());
std::array<double, 6> lower_force_thresholds_acceleration;
std::copy(req.lower_force_thresholds_acceleration.cbegin(),
req.lower_force_thresholds_acceleration.cend(),
lower_force_thresholds_acceleration.begin());
std::array<double, 6> upper_force_thresholds_acceleration;
std::copy(req.upper_force_thresholds_acceleration.cbegin(),
req.upper_force_thresholds_acceleration.cend(),
upper_force_thresholds_acceleration.begin());
std::array<double, 6> lower_force_thresholds_nominal;
std::copy(req.lower_force_thresholds_nominal.cbegin(),
req.lower_force_thresholds_nominal.cend(),
lower_force_thresholds_nominal.begin());
std::array<double, 6> upper_force_thresholds_nominal;
std::copy(req.upper_force_thresholds_nominal.cbegin(),
req.upper_force_thresholds_nominal.cend(),
upper_force_thresholds_nominal.begin());
robot_->setCollisionBehavior(
lower_torque_thresholds_acceleration,
upper_torque_thresholds_acceleration, lower_torque_thresholds_nominal,
upper_torque_thresholds_nominal, lower_force_thresholds_acceleration,
upper_force_thresholds_acceleration, lower_force_thresholds_nominal,
upper_force_thresholds_nominal);
return true;
}
bool ServiceServer::setLoad(SetLoad::Request& req, SetLoad::Response& res) {
double mass(req.mass);
std::array<double, 3> F_x_center_load;
std::copy(req.F_x_center_load.cbegin(), req.F_x_center_load.cend(),
F_x_center_load.begin());
std::array<double, 9> load_inertia;
std::copy(req.load_inertia.cbegin(), req.load_inertia.cend(),
load_inertia.begin());
robot_->setLoad(mass, F_x_center_load, load_inertia);
return true;
}
bool ServiceServer::setTimeScalingFactor(SetTimeScalingFactor::Request& req,
SetTimeScalingFactor::Response& res) {
robot_->setTimeScalingFactor(req.time_scaling_factor);
return true;
}
bool ServiceServer::errorRecovery(ErrorRecovery::Request& req,
ErrorRecovery::Response& res) {
robot_->automaticErrorRecovery();
return true;
}
} // namespace franka_hw
<|endoftext|> |
<commit_before>#include <iostream>
#include <iostream>
#include <libgen.h>
#include "SDL/SDL.h"
#include "world.hpp"
#include "graphics/graphics.hpp"
#include "tmxparser.h"
namespace Polarity {
World *world = nullptr;
World::World(const std::string& tmxFile)
: physics(b2Vec2(0.0f, -10.0f)),
keyState(SDLK_LAST),
layers(nullptr) {
std::cerr << "World has started"<<std::endl;
for (int i=0; i< SDLK_LAST; ++i) {
keyState[i] = false;
}
load(tmxFile);
}
void World::init() {
world = new World("assets/levels/level1.tmx");
}
GameObject* World::addObject(Behavior *behavior, const b2BodyDef&bdef) {
GameObject * object = new GameObject(&physics, behavior, bdef);
objects.emplace_back(object);
return objects.back().get();
}
bool World::isKeyDown(int keyCode) {
return keyState[keyCode];
}
void World::keyEvent(int keyCode, bool pressed) {
if (keyCode < SDLK_LAST) {
keyState[keyCode] = pressed;
}else {
std::cerr << "Key code out of range "<<keyCode<<"\n";
}
}
void World::tick() {
physics.Step(0.0166666, 1, 1);
for (auto &obj : objects) {
obj->tick(this);
std::cerr << obj->printPosition()<<std::endl;
}
//for(auto &gameObject:objects){
//
//}
// Gets called every frame
}
void World::load(const std::string &tmxFile) {
char *filecpy = new char[tmxFile.length() + 1];
strncpy(filecpy, tmxFile.c_str(), tmxFile.length() + 1);
std::string dir (dirname(filecpy));
delete []filecpy;
std::cerr << "Loading: " << tmxFile << " from directory " << dir << std::endl;
tmxparser::TmxMap map;
tmxparser::TmxReturn error = tmxparser::parseFromFile(tmxFile, &map);
layers = std::unique_ptr<LayerCollection>(new LayerCollection(dir, map));
for (auto &it : map.tilesetCollection) {
std::cerr << "Found tileset: " << it.name << std::endl;
}
for (auto &it : map.layerCollection) {
std::cerr << "Found layer: " << it.name << std::endl;
}
for (auto &it : map.objectGroupCollection) {
std::cerr << "Found object group: " << it.name << std::endl;
}
}
}
<commit_msg>adding stuff for printing objects<commit_after>#include <iostream>
#include <iostream>
#include <libgen.h>
#include "SDL/SDL.h"
#include "world.hpp"
#include "graphics/graphics.hpp"
#include "tmxparser.h"
namespace Polarity {
World *world = nullptr;
World::World(const std::string& tmxFile)
: physics(b2Vec2(0.0f, -10.0f)),
keyState(SDLK_LAST),
layers(nullptr) {
std::cerr << "World has started"<<std::endl;
for (int i=0; i< SDLK_LAST; ++i) {
keyState[i] = false;
}
load(tmxFile);
}
void World::init() {
world = new World("assets/levels/level1.tmx");
}
GameObject* World::addObject(Behavior *behavior, const b2BodyDef&bdef) {
GameObject * object = new GameObject(&physics, behavior, bdef);
objects.emplace_back(object);
return objects.back().get();
}
bool World::isKeyDown(int keyCode) {
return keyState[keyCode];
}
void World::keyEvent(int keyCode, bool pressed) {
if (keyCode < SDLK_LAST) {
keyState[keyCode] = pressed;
}else {
std::cerr << "Key code out of range "<<keyCode<<"\n";
}
}
void World::tick() {
physics.Step(0.0166666, 1, 1);
for (auto &obj : objects) {
obj->tick(this);
// std::cerr << obj->printPosition()<<std::endl;
}
//for(auto &gameObject:objects){
//
//}
// Gets called every frame
}
void World::load(const std::string &tmxFile) {
char *filecpy = new char[tmxFile.length() + 1];
strncpy(filecpy, tmxFile.c_str(), tmxFile.length() + 1);
std::string dir (dirname(filecpy));
delete []filecpy;
std::cerr << "Loading: " << tmxFile << " from directory " << dir << std::endl;
tmxparser::TmxMap map;
tmxparser::TmxReturn error = tmxparser::parseFromFile(tmxFile, &map);
layers = std::unique_ptr<LayerCollection>(new LayerCollection(dir, map));
for (auto &it : map.tilesetCollection) {
std::cerr << "Found tileset: " << it.name << std::endl;
}
for (auto &it : map.layerCollection) {
std::cerr << "Found layer: " << it.name << std::endl;
}
for (auto &it : map.objectGroupCollection) {
// std::string name;
// std::string color;
// float opacity;
// bool visible;
// TmxPropertyMap_t propertyMap;
// TmxObjectCollection_t objects;
// typedef std::vector<TmxObject> TmxObjectCollection_t;
std::cerr << "Found object group (name): " << it.name << std::endl;
std::cerr << "Found object group (color): " << it.color << std::endl;
std::cerr << "Found object group (opacity): " << it.opacity << std::endl;
std::cerr << "Found object group (visible): " << it.visible << std::endl;
std::cerr << "Found object group (propertyMap): " << it.propertyMap.size() << std::endl;
for (auto &pit : it.propertyMap) {
std::cerr << "meow " << pit.first << std::endl;
}
std::cerr << "Found object group (objects): " << it.objects.size() << std::endl;
for (auto &oit : it.objects) {
SDL_Surface* surface = SDL_CreateRGBSurface(0, oit.width, oit.height, 32, 0, 0, 0, 0);
if(surface == NULL) {
fprintf(stderr, "CreateRGBSurface failed: %s\n", SDL_GetError());
exit(1);
}
int err = SDL_FillRect(surface, NULL, 100);
std::cerr << "error code = " << err << std::endl;
std::cerr << "object name = " << oit.name << std::endl;
std::cerr << "object type = " << oit.type << std::endl;
std::cerr << "object x = " << oit.x << std::endl;
std::cerr << "object y = " << oit.y << std::endl;
std::cerr << "object width = " << oit.width << std::endl;
std::cerr << "object height = " << oit.height << std::endl;
std::cerr << "object rotation = " << oit.rotation << std::endl;
std::cerr << "object referenceGid = " << oit.referenceGid << std::endl;
std::cerr << "object visible = " << oit.visible << std::endl;
std::cerr << "object propertyMap = " << oit.propertyMap.size() << std::endl;
std::cerr << "object shapeType = " << oit.shapeType << std::endl;
std::cerr << "object shapePoints = " << oit.shapePoints.size() << std::endl;
}
// typedef struct
// {
// std::string name;
// std::string type;
// int x;
// int y;
// unsigned int width;
// unsigned int height;
// float rotation;
// unsigned int referenceGid;
// bool visible;
// TmxPropertyMap_t propertyMap;
// TmxShapeType shapeType;
// TmxShapePointCollection_t shapePoints;
// } TmxObject;
}
}
}
<|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 "gl/GrGLExtensions.h"
#include "gl/GrGLInterface.h"
#include "../GrGLUtil.h"
#include <GL/glx.h>
#include <GL/gl.h>
#include <GL/glext.h>
#include <GL/glu.h>
#define GR_GL_GET_PROC(F) interface->f ## F = (GrGL ## F ## Proc) \
glXGetProcAddress(reinterpret_cast<const GLubyte*>("gl" #F));
#define GR_GL_GET_PROC_SUFFIX(F, S) interface->f ## F = (GrGL ## F ## Proc) \
glXGetProcAddress(reinterpret_cast<const GLubyte*>("gl" #F #S));
const GrGLInterface* GrGLCreateNativeInterface() {
if (NULL != glXGetCurrentContext()) {
const char* versionString = (const char*) glGetString(GL_VERSION);
GrGLVersion glVer = GrGLGetVersionFromString(versionString);
// This may or may not succeed depending on the gl version.
GrGLGetStringiProc glGetStringi =
(GrGLGetStringiProc) glXGetProcAddress(reinterpret_cast<const GLubyte*>("glGetStringi"));
GrGLExtensions extensions;
if (!extensions.init(kDesktop_GrGLBinding, glGetString, glGetStringi, glGetIntegerv)) {
return NULL;
}
if (glVer < GR_GL_VER(1,5)) {
// We must have array and element_array buffer objects.
return NULL;
}
GrGLInterface* interface = new GrGLInterface();
interface->fActiveTexture = glActiveTexture;
GR_GL_GET_PROC(AttachShader);
GR_GL_GET_PROC(BindAttribLocation);
GR_GL_GET_PROC(BindBuffer);
GR_GL_GET_PROC(BindFragDataLocation);
GR_GL_GET_PROC(BeginQuery);
interface->fBindTexture = glBindTexture;
interface->fBlendFunc = glBlendFunc;
if (glVer >= GR_GL_VER(1,4) ||
extensions.has("GL_ARB_imaging") ||
extensions.has("GL_EXT_blend_color")) {
GR_GL_GET_PROC(BlendColor);
}
GR_GL_GET_PROC(BufferData);
GR_GL_GET_PROC(BufferSubData);
interface->fClear = glClear;
interface->fClearColor = glClearColor;
interface->fClearStencil = glClearStencil;
interface->fColorMask = glColorMask;
GR_GL_GET_PROC(CompileShader);
interface->fCompressedTexImage2D = glCompressedTexImage2D;
interface->fCopyTexSubImage2D = glCopyTexSubImage2D;
GR_GL_GET_PROC(CreateProgram);
GR_GL_GET_PROC(CreateShader);
interface->fCullFace = glCullFace;
GR_GL_GET_PROC(DeleteBuffers);
GR_GL_GET_PROC(DeleteProgram);
GR_GL_GET_PROC(DeleteQueries);
GR_GL_GET_PROC(DeleteShader);
interface->fDeleteTextures = glDeleteTextures;
interface->fDepthMask = glDepthMask;
interface->fDisable = glDisable;
GR_GL_GET_PROC(DisableVertexAttribArray);
interface->fDrawArrays = glDrawArrays;
interface->fDrawBuffer = glDrawBuffer;
GR_GL_GET_PROC(DrawBuffers);
interface->fDrawElements = glDrawElements;
interface->fEnable = glEnable;
GR_GL_GET_PROC(EnableVertexAttribArray);
GR_GL_GET_PROC(EndQuery);
interface->fFinish = glFinish;
interface->fFlush = glFlush;
interface->fFrontFace = glFrontFace;
GR_GL_GET_PROC(GenBuffers);
GR_GL_GET_PROC(GenerateMipmap);
GR_GL_GET_PROC(GetBufferParameteriv);
interface->fGetError = glGetError;
interface->fGetIntegerv = glGetIntegerv;
GR_GL_GET_PROC(GetQueryObjectiv);
GR_GL_GET_PROC(GetQueryObjectuiv);
if (glVer >= GR_GL_VER(3,3) || extensions.has("GL_ARB_timer_query")) {
GR_GL_GET_PROC(GetQueryObjecti64v);
GR_GL_GET_PROC(GetQueryObjectui64v);
GR_GL_GET_PROC(QueryCounter);
} else if (extensions.has("GL_EXT_timer_query")) {
GR_GL_GET_PROC_SUFFIX(GetQueryObjecti64v, EXT);
GR_GL_GET_PROC_SUFFIX(GetQueryObjectui64v, EXT);
}
GR_GL_GET_PROC(GetQueryiv);
GR_GL_GET_PROC(GetProgramInfoLog);
GR_GL_GET_PROC(GetProgramiv);
GR_GL_GET_PROC(GetShaderInfoLog);
GR_GL_GET_PROC(GetShaderiv);
interface->fGetString = glGetString;
GR_GL_GET_PROC(GetStringi);
interface->fGetTexLevelParameteriv = glGetTexLevelParameteriv;
GR_GL_GET_PROC(GenQueries);
interface->fGenTextures = glGenTextures;
GR_GL_GET_PROC(GetUniformLocation);
interface->fLineWidth = glLineWidth;
GR_GL_GET_PROC(LinkProgram);
GR_GL_GET_PROC(MapBuffer);
interface->fPixelStorei = glPixelStorei;
interface->fReadBuffer = glReadBuffer;
interface->fReadPixels = glReadPixels;
if (extensions.has("GL_NV_framebuffer_multisample_coverage")) {
GR_GL_GET_PROC_SUFFIX(RenderbufferStorageMultisampleCoverage, NV);
}
interface->fScissor = glScissor;
GR_GL_GET_PROC(ShaderSource);
interface->fStencilFunc = glStencilFunc;
GR_GL_GET_PROC(StencilFuncSeparate);
interface->fStencilMask = glStencilMask;
GR_GL_GET_PROC(StencilMaskSeparate);
interface->fStencilOp = glStencilOp;
GR_GL_GET_PROC(StencilOpSeparate);
interface->fTexImage2D = glTexImage2D;
interface->fTexParameteri = glTexParameteri;
interface->fTexParameteriv = glTexParameteriv;
if (glVer >= GR_GL_VER(4,2) || extensions.has("GL_ARB_texture_storage")) {
GR_GL_GET_PROC(TexStorage2D);
} else if (extensions.has("GL_EXT_texture_storage")) {
GR_GL_GET_PROC_SUFFIX(TexStorage2D, EXT);
}
interface->fTexSubImage2D = glTexSubImage2D;
GR_GL_GET_PROC(Uniform1f);
GR_GL_GET_PROC(Uniform1i);
GR_GL_GET_PROC(Uniform1fv);
GR_GL_GET_PROC(Uniform1iv);
GR_GL_GET_PROC(Uniform2f);
GR_GL_GET_PROC(Uniform2i);
GR_GL_GET_PROC(Uniform2fv);
GR_GL_GET_PROC(Uniform2iv);
GR_GL_GET_PROC(Uniform3f);
GR_GL_GET_PROC(Uniform3i);
GR_GL_GET_PROC(Uniform3fv);
GR_GL_GET_PROC(Uniform3iv);
GR_GL_GET_PROC(Uniform4f);
GR_GL_GET_PROC(Uniform4i);
GR_GL_GET_PROC(Uniform4fv);
GR_GL_GET_PROC(Uniform4iv);
GR_GL_GET_PROC(UniformMatrix2fv);
GR_GL_GET_PROC(UniformMatrix3fv);
GR_GL_GET_PROC(UniformMatrix4fv);
GR_GL_GET_PROC(UnmapBuffer);
GR_GL_GET_PROC(UseProgram);
GR_GL_GET_PROC(VertexAttrib4fv);
GR_GL_GET_PROC(VertexAttribPointer);
interface->fViewport = glViewport;
GR_GL_GET_PROC(BindFragDataLocationIndexed);
if (glVer >= GR_GL_VER(3,0) || extensions.has("GL_ARB_vertex_array_object")) {
// no ARB suffix for GL_ARB_vertex_array_object
GR_GL_GET_PROC(BindVertexArray);
GR_GL_GET_PROC(GenVertexArrays);
GR_GL_GET_PROC(DeleteVertexArrays);
}
// First look for GL3.0 FBO or GL_ARB_framebuffer_object (same since
// GL_ARB_framebuffer_object doesn't use ARB suffix.)
if (glVer >= GR_GL_VER(3,0) || extensions.has("GL_ARB_framebuffer_object")) {
GR_GL_GET_PROC(GenFramebuffers);
GR_GL_GET_PROC(GetFramebufferAttachmentParameteriv);
GR_GL_GET_PROC(GetRenderbufferParameteriv);
GR_GL_GET_PROC(BindFramebuffer);
GR_GL_GET_PROC(FramebufferTexture2D);
GR_GL_GET_PROC(CheckFramebufferStatus);
GR_GL_GET_PROC(DeleteFramebuffers);
GR_GL_GET_PROC(RenderbufferStorage);
GR_GL_GET_PROC(GenRenderbuffers);
GR_GL_GET_PROC(DeleteRenderbuffers);
GR_GL_GET_PROC(FramebufferRenderbuffer);
GR_GL_GET_PROC(BindRenderbuffer);
GR_GL_GET_PROC(RenderbufferStorageMultisample);
GR_GL_GET_PROC(BlitFramebuffer);
} else if (extensions.has("GL_EXT_framebuffer_object")) {
GR_GL_GET_PROC_SUFFIX(GenFramebuffers, EXT);
GR_GL_GET_PROC_SUFFIX(GetFramebufferAttachmentParameteriv, EXT);
GR_GL_GET_PROC_SUFFIX(GetRenderbufferParameteriv, EXT);
GR_GL_GET_PROC_SUFFIX(BindFramebuffer, EXT);
GR_GL_GET_PROC_SUFFIX(FramebufferTexture2D, EXT);
GR_GL_GET_PROC_SUFFIX(CheckFramebufferStatus, EXT);
GR_GL_GET_PROC_SUFFIX(DeleteFramebuffers, EXT);
GR_GL_GET_PROC_SUFFIX(RenderbufferStorage, EXT);
GR_GL_GET_PROC_SUFFIX(GenRenderbuffers, EXT);
GR_GL_GET_PROC_SUFFIX(DeleteRenderbuffers, EXT);
GR_GL_GET_PROC_SUFFIX(FramebufferRenderbuffer, EXT);
GR_GL_GET_PROC_SUFFIX(BindRenderbuffer, EXT);
if (extensions.has("GL_EXT_framebuffer_multisample")) {
GR_GL_GET_PROC_SUFFIX(RenderbufferStorageMultisample, EXT);
}
if (extensions.has("GL_EXT_framebuffer_blit")) {
GR_GL_GET_PROC_SUFFIX(BlitFramebuffer, EXT);
}
} else {
// we must have FBOs
delete interface;
return NULL;
}
interface->fBindingsExported = kDesktop_GrGLBinding;
return interface;
} else {
return NULL;
}
}
<commit_msg>Add nv_path_rendering entry points to Unix GLInterface<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 "gl/GrGLExtensions.h"
#include "gl/GrGLInterface.h"
#include "../GrGLUtil.h"
#include <GL/glx.h>
#include <GL/gl.h>
#include <GL/glext.h>
#include <GL/glu.h>
#define GR_GL_GET_PROC(F) interface->f ## F = (GrGL ## F ## Proc) \
glXGetProcAddress(reinterpret_cast<const GLubyte*>("gl" #F));
#define GR_GL_GET_PROC_SUFFIX(F, S) interface->f ## F = (GrGL ## F ## Proc) \
glXGetProcAddress(reinterpret_cast<const GLubyte*>("gl" #F #S));
const GrGLInterface* GrGLCreateNativeInterface() {
if (NULL != glXGetCurrentContext()) {
const char* versionString = (const char*) glGetString(GL_VERSION);
GrGLVersion glVer = GrGLGetVersionFromString(versionString);
// This may or may not succeed depending on the gl version.
GrGLGetStringiProc glGetStringi =
(GrGLGetStringiProc) glXGetProcAddress(reinterpret_cast<const GLubyte*>("glGetStringi"));
GrGLExtensions extensions;
if (!extensions.init(kDesktop_GrGLBinding, glGetString, glGetStringi, glGetIntegerv)) {
return NULL;
}
if (glVer < GR_GL_VER(1,5)) {
// We must have array and element_array buffer objects.
return NULL;
}
GrGLInterface* interface = new GrGLInterface();
interface->fActiveTexture = glActiveTexture;
GR_GL_GET_PROC(AttachShader);
GR_GL_GET_PROC(BindAttribLocation);
GR_GL_GET_PROC(BindBuffer);
GR_GL_GET_PROC(BindFragDataLocation);
GR_GL_GET_PROC(BeginQuery);
interface->fBindTexture = glBindTexture;
interface->fBlendFunc = glBlendFunc;
if (glVer >= GR_GL_VER(1,4) ||
extensions.has("GL_ARB_imaging") ||
extensions.has("GL_EXT_blend_color")) {
GR_GL_GET_PROC(BlendColor);
}
GR_GL_GET_PROC(BufferData);
GR_GL_GET_PROC(BufferSubData);
interface->fClear = glClear;
interface->fClearColor = glClearColor;
interface->fClearStencil = glClearStencil;
interface->fColorMask = glColorMask;
GR_GL_GET_PROC(CompileShader);
interface->fCompressedTexImage2D = glCompressedTexImage2D;
interface->fCopyTexSubImage2D = glCopyTexSubImage2D;
GR_GL_GET_PROC(CreateProgram);
GR_GL_GET_PROC(CreateShader);
interface->fCullFace = glCullFace;
GR_GL_GET_PROC(DeleteBuffers);
GR_GL_GET_PROC(DeleteProgram);
GR_GL_GET_PROC(DeleteQueries);
GR_GL_GET_PROC(DeleteShader);
interface->fDeleteTextures = glDeleteTextures;
interface->fDepthMask = glDepthMask;
interface->fDisable = glDisable;
GR_GL_GET_PROC(DisableVertexAttribArray);
interface->fDrawArrays = glDrawArrays;
interface->fDrawBuffer = glDrawBuffer;
GR_GL_GET_PROC(DrawBuffers);
interface->fDrawElements = glDrawElements;
interface->fEnable = glEnable;
GR_GL_GET_PROC(EnableVertexAttribArray);
GR_GL_GET_PROC(EndQuery);
interface->fFinish = glFinish;
interface->fFlush = glFlush;
interface->fFrontFace = glFrontFace;
GR_GL_GET_PROC(GenBuffers);
GR_GL_GET_PROC(GenerateMipmap);
GR_GL_GET_PROC(GetBufferParameteriv);
interface->fGetError = glGetError;
interface->fGetIntegerv = glGetIntegerv;
GR_GL_GET_PROC(GetQueryObjectiv);
GR_GL_GET_PROC(GetQueryObjectuiv);
if (glVer >= GR_GL_VER(3,3) || extensions.has("GL_ARB_timer_query")) {
GR_GL_GET_PROC(GetQueryObjecti64v);
GR_GL_GET_PROC(GetQueryObjectui64v);
GR_GL_GET_PROC(QueryCounter);
} else if (extensions.has("GL_EXT_timer_query")) {
GR_GL_GET_PROC_SUFFIX(GetQueryObjecti64v, EXT);
GR_GL_GET_PROC_SUFFIX(GetQueryObjectui64v, EXT);
}
GR_GL_GET_PROC(GetQueryiv);
GR_GL_GET_PROC(GetProgramInfoLog);
GR_GL_GET_PROC(GetProgramiv);
GR_GL_GET_PROC(GetShaderInfoLog);
GR_GL_GET_PROC(GetShaderiv);
interface->fGetString = glGetString;
GR_GL_GET_PROC(GetStringi);
interface->fGetTexLevelParameteriv = glGetTexLevelParameteriv;
GR_GL_GET_PROC(GenQueries);
interface->fGenTextures = glGenTextures;
GR_GL_GET_PROC(GetUniformLocation);
interface->fLineWidth = glLineWidth;
GR_GL_GET_PROC(LinkProgram);
GR_GL_GET_PROC(MapBuffer);
interface->fPixelStorei = glPixelStorei;
interface->fReadBuffer = glReadBuffer;
interface->fReadPixels = glReadPixels;
if (extensions.has("GL_NV_framebuffer_multisample_coverage")) {
GR_GL_GET_PROC_SUFFIX(RenderbufferStorageMultisampleCoverage, NV);
}
interface->fScissor = glScissor;
GR_GL_GET_PROC(ShaderSource);
interface->fStencilFunc = glStencilFunc;
GR_GL_GET_PROC(StencilFuncSeparate);
interface->fStencilMask = glStencilMask;
GR_GL_GET_PROC(StencilMaskSeparate);
interface->fStencilOp = glStencilOp;
GR_GL_GET_PROC(StencilOpSeparate);
interface->fTexImage2D = glTexImage2D;
interface->fTexParameteri = glTexParameteri;
interface->fTexParameteriv = glTexParameteriv;
if (glVer >= GR_GL_VER(4,2) || extensions.has("GL_ARB_texture_storage")) {
GR_GL_GET_PROC(TexStorage2D);
} else if (extensions.has("GL_EXT_texture_storage")) {
GR_GL_GET_PROC_SUFFIX(TexStorage2D, EXT);
}
interface->fTexSubImage2D = glTexSubImage2D;
GR_GL_GET_PROC(Uniform1f);
GR_GL_GET_PROC(Uniform1i);
GR_GL_GET_PROC(Uniform1fv);
GR_GL_GET_PROC(Uniform1iv);
GR_GL_GET_PROC(Uniform2f);
GR_GL_GET_PROC(Uniform2i);
GR_GL_GET_PROC(Uniform2fv);
GR_GL_GET_PROC(Uniform2iv);
GR_GL_GET_PROC(Uniform3f);
GR_GL_GET_PROC(Uniform3i);
GR_GL_GET_PROC(Uniform3fv);
GR_GL_GET_PROC(Uniform3iv);
GR_GL_GET_PROC(Uniform4f);
GR_GL_GET_PROC(Uniform4i);
GR_GL_GET_PROC(Uniform4fv);
GR_GL_GET_PROC(Uniform4iv);
GR_GL_GET_PROC(UniformMatrix2fv);
GR_GL_GET_PROC(UniformMatrix3fv);
GR_GL_GET_PROC(UniformMatrix4fv);
GR_GL_GET_PROC(UnmapBuffer);
GR_GL_GET_PROC(UseProgram);
GR_GL_GET_PROC(VertexAttrib4fv);
GR_GL_GET_PROC(VertexAttribPointer);
interface->fViewport = glViewport;
GR_GL_GET_PROC(BindFragDataLocationIndexed);
if (glVer >= GR_GL_VER(3,0) || extensions.has("GL_ARB_vertex_array_object")) {
// no ARB suffix for GL_ARB_vertex_array_object
GR_GL_GET_PROC(BindVertexArray);
GR_GL_GET_PROC(GenVertexArrays);
GR_GL_GET_PROC(DeleteVertexArrays);
}
// First look for GL3.0 FBO or GL_ARB_framebuffer_object (same since
// GL_ARB_framebuffer_object doesn't use ARB suffix.)
if (glVer >= GR_GL_VER(3,0) || extensions.has("GL_ARB_framebuffer_object")) {
GR_GL_GET_PROC(GenFramebuffers);
GR_GL_GET_PROC(GetFramebufferAttachmentParameteriv);
GR_GL_GET_PROC(GetRenderbufferParameteriv);
GR_GL_GET_PROC(BindFramebuffer);
GR_GL_GET_PROC(FramebufferTexture2D);
GR_GL_GET_PROC(CheckFramebufferStatus);
GR_GL_GET_PROC(DeleteFramebuffers);
GR_GL_GET_PROC(RenderbufferStorage);
GR_GL_GET_PROC(GenRenderbuffers);
GR_GL_GET_PROC(DeleteRenderbuffers);
GR_GL_GET_PROC(FramebufferRenderbuffer);
GR_GL_GET_PROC(BindRenderbuffer);
GR_GL_GET_PROC(RenderbufferStorageMultisample);
GR_GL_GET_PROC(BlitFramebuffer);
} else if (extensions.has("GL_EXT_framebuffer_object")) {
GR_GL_GET_PROC_SUFFIX(GenFramebuffers, EXT);
GR_GL_GET_PROC_SUFFIX(GetFramebufferAttachmentParameteriv, EXT);
GR_GL_GET_PROC_SUFFIX(GetRenderbufferParameteriv, EXT);
GR_GL_GET_PROC_SUFFIX(BindFramebuffer, EXT);
GR_GL_GET_PROC_SUFFIX(FramebufferTexture2D, EXT);
GR_GL_GET_PROC_SUFFIX(CheckFramebufferStatus, EXT);
GR_GL_GET_PROC_SUFFIX(DeleteFramebuffers, EXT);
GR_GL_GET_PROC_SUFFIX(RenderbufferStorage, EXT);
GR_GL_GET_PROC_SUFFIX(GenRenderbuffers, EXT);
GR_GL_GET_PROC_SUFFIX(DeleteRenderbuffers, EXT);
GR_GL_GET_PROC_SUFFIX(FramebufferRenderbuffer, EXT);
GR_GL_GET_PROC_SUFFIX(BindRenderbuffer, EXT);
if (extensions.has("GL_EXT_framebuffer_multisample")) {
GR_GL_GET_PROC_SUFFIX(RenderbufferStorageMultisample, EXT);
}
if (extensions.has("GL_EXT_framebuffer_blit")) {
GR_GL_GET_PROC_SUFFIX(BlitFramebuffer, EXT);
}
} else {
// we must have FBOs
delete interface;
return NULL;
}
GR_GL_GET_PROC(LoadIdentity);
GR_GL_GET_PROC(LoadMatrixf);
GR_GL_GET_PROC(MatrixMode);
if (extensions.has("GL_NV_path_rendering")) {
GR_GL_GET_PROC_SUFFIX(PathCommands, NV);
GR_GL_GET_PROC_SUFFIX(PathCoords, NV);
GR_GL_GET_PROC_SUFFIX(PathSubCommands, NV);
GR_GL_GET_PROC_SUFFIX(PathSubCoords, NV);
GR_GL_GET_PROC_SUFFIX(PathString, NV);
GR_GL_GET_PROC_SUFFIX(PathGlyphs, NV);
GR_GL_GET_PROC_SUFFIX(PathGlyphRange, NV);
GR_GL_GET_PROC_SUFFIX(WeightPaths, NV);
GR_GL_GET_PROC_SUFFIX(CopyPath, NV);
GR_GL_GET_PROC_SUFFIX(InterpolatePaths, NV);
GR_GL_GET_PROC_SUFFIX(TransformPath, NV);
GR_GL_GET_PROC_SUFFIX(PathParameteriv, NV);
GR_GL_GET_PROC_SUFFIX(PathParameteri, NV);
GR_GL_GET_PROC_SUFFIX(PathParameterfv, NV);
GR_GL_GET_PROC_SUFFIX(PathParameterf, NV);
GR_GL_GET_PROC_SUFFIX(PathDashArray, NV);
GR_GL_GET_PROC_SUFFIX(GenPaths, NV);
GR_GL_GET_PROC_SUFFIX(DeletePaths, NV);
GR_GL_GET_PROC_SUFFIX(IsPath, NV);
GR_GL_GET_PROC_SUFFIX(PathStencilFunc, NV);
GR_GL_GET_PROC_SUFFIX(PathStencilDepthOffset, NV);
GR_GL_GET_PROC_SUFFIX(StencilFillPath, NV);
GR_GL_GET_PROC_SUFFIX(StencilStrokePath, NV);
GR_GL_GET_PROC_SUFFIX(StencilFillPathInstanced, NV);
GR_GL_GET_PROC_SUFFIX(StencilStrokePathInstanced, NV);
GR_GL_GET_PROC_SUFFIX(PathCoverDepthFunc, NV);
GR_GL_GET_PROC_SUFFIX(PathColorGen, NV);
GR_GL_GET_PROC_SUFFIX(PathTexGen, NV);
GR_GL_GET_PROC_SUFFIX(PathFogGen, NV);
GR_GL_GET_PROC_SUFFIX(CoverFillPath, NV);
GR_GL_GET_PROC_SUFFIX(CoverStrokePath, NV);
GR_GL_GET_PROC_SUFFIX(CoverFillPathInstanced, NV);
GR_GL_GET_PROC_SUFFIX(CoverStrokePathInstanced, NV);
GR_GL_GET_PROC_SUFFIX(GetPathParameteriv, NV);
GR_GL_GET_PROC_SUFFIX(GetPathParameterfv, NV);
GR_GL_GET_PROC_SUFFIX(GetPathCommands, NV);
GR_GL_GET_PROC_SUFFIX(GetPathCoords, NV);
GR_GL_GET_PROC_SUFFIX(GetPathDashArray, NV);
GR_GL_GET_PROC_SUFFIX(GetPathMetrics, NV);
GR_GL_GET_PROC_SUFFIX(GetPathMetricRange, NV);
GR_GL_GET_PROC_SUFFIX(GetPathSpacing, NV);
GR_GL_GET_PROC_SUFFIX(GetPathColorGeniv, NV);
GR_GL_GET_PROC_SUFFIX(GetPathColorGenfv, NV);
GR_GL_GET_PROC_SUFFIX(GetPathTexGeniv, NV);
GR_GL_GET_PROC_SUFFIX(GetPathTexGenfv, NV);
GR_GL_GET_PROC_SUFFIX(IsPointInFillPath, NV);
GR_GL_GET_PROC_SUFFIX(IsPointInStrokePath, NV);
GR_GL_GET_PROC_SUFFIX(GetPathLength, NV);
GR_GL_GET_PROC_SUFFIX(PointAlongPath, NV);
}
interface->fBindingsExported = kDesktop_GrGLBinding;
return interface;
} else {
return NULL;
}
}
<|endoftext|> |
<commit_before>/*
* gst_properties_module.cpp
*
* Created on: Jul 14, 2015
* Author: loganek
*/
#include "gst_properties_module.h"
#include "gvalue-converter/gvalue_enum.h"
#include "common/deserializer.h"
#include "controller/command_factory.h"
#include "controller/controller.h"
#include "controller/element_path_processor.h"
#include "ui_utils.h"
#include <gst/gst.h>
static void free_properties(Property *property) { delete property; }
GstPropertiesModule::GstPropertiesModule(const Glib::RefPtr<Gtk::Builder>& builder)
{
builder->get_widget("showPropertiesButton", show_propetries_button);
show_propetries_button->signal_clicked().connect(sigc::mem_fun(*this, &GstPropertiesModule::showPropertiesButton_clicked_cb));
builder->get_widget("propertiesBox", properties_box);
create_dispatcher("property", sigc::mem_fun(*this, &GstPropertiesModule::new_property_), (GDestroyNotify)free_properties);
create_dispatcher("selected-object-changed", sigc::mem_fun(*this, &GstPropertiesModule::selected_object_changed_), nullptr);
}
void GstPropertiesModule::set_controller(const std::shared_ptr<Controller> &controller)
{
IBaseView::set_controller(controller);
controller->on_property_received.connect(sigc::mem_fun(*this, &GstPropertiesModule::new_property));
controller->on_selected_object_changed.connect(sigc::mem_fun(*this, &GstPropertiesModule::selected_object_changed));
}
void GstPropertiesModule::new_property(const Property &property)
{
gui_push("property", new Property (property));
gui_emit("property");
}
void GstPropertiesModule::request_selected_element_property(const std::string &property_name)
{
auto obj = controller->get_selected_object();
if (!obj || !std::dynamic_pointer_cast<ElementModel>(obj))
{
return;
}
std::string element_path = ElementPathProcessor::get_object_path(obj);
controller->send_property_request_command(element_path, property_name);
if (element_path != previous_element_path)
{
clear_widgets();
previous_element_path = element_path;
}
}
void GstPropertiesModule::showPropertiesButton_clicked_cb()
{
request_selected_element_property("");
}
void GstPropertiesModule::new_property_()
{
auto property = gui_pop<Property*>("property");
auto element = std::dynamic_pointer_cast<ElementModel>(ElementPathProcessor(property->element_path()).get_last_obj());
if (!element)
{
return;
}
std::shared_ptr<GValueBase> value_base = element->get_property(property->property_name());
std::shared_ptr<GValueEnum> value_enum = std::dynamic_pointer_cast<GValueEnum>(value_base);
auto& container = const_cast<RemoteDataContainer<GstEnumType>&>(controller->get_enum_container());
if (value_enum && container.has_item(property->type_name()))
{
value_enum->set_type(container.get_item(property->type_name()));
}
if (!update_property(value_base, property))
{
append_property(value_base, property);
}
delete property;
}
bool GstPropertiesModule::update_property(const std::shared_ptr<GValueBase>& value_base, Property *property)
{
for (auto internal_box : properties_box->get_children())
{
Gtk::Box *hb = dynamic_cast<Gtk::Box*>(internal_box);
if (hb == nullptr)
{
continue;
}
Gtk::Label *label = nullptr;
Gtk::Widget *widget = nullptr;
for (auto cd : hb->get_children())
{
if (label == nullptr && (label = dynamic_cast<Gtk::Label*>(cd)) != nullptr)
{
if (label->get_text() != property->property_name())
{
label = nullptr;
break;
}
}
else if (dynamic_cast<Gtk::Button*>(cd) == nullptr || dynamic_cast<Gtk::CheckButton*>(cd) != nullptr)
{
widget = cd;
}
}
if (label == nullptr || widget == nullptr)
{
continue;
}
hb->remove(*widget);
widget = value_base->get_widget();
widget->show();
hb->pack_start(*widget, true, 10);
hb->reorder_child(*widget, 1);
return true;
}
return false;
}
void GstPropertiesModule::append_property(const std::shared_ptr<GValueBase>& value_base, Property *property)
{
Gtk::Box *hbox = new Gtk::Box (Gtk::ORIENTATION_HORIZONTAL, 0);
hbox->show();
auto prop_name = property->property_name();
Gtk::Label *lbl = Gtk::manage(new Gtk::Label(prop_name));
lbl->set_tooltip_text(property->description());
lbl->show();
Gtk::Button *btn = Gtk::manage(new Gtk::Button("Refresh"));
btn->signal_clicked().connect([this, prop_name] {request_selected_element_property(prop_name);});
btn->show();
hbox->pack_start(*lbl, false, false);
auto value_widget = value_base->get_widget();
value_widget->show();
hbox->pack_start(*value_widget, true, true);
hbox->pack_start(*btn, false, false);
properties_box->pack_start(*hbox);
}
void GstPropertiesModule::clear_widgets()
{
for (auto c : properties_box->get_children())
{
delete c;
}
}
void GstPropertiesModule::selected_object_changed()
{
gui_emit("selected-object-changed");
}
void GstPropertiesModule::selected_object_changed_()
{
clear_widgets();
auto element = std::dynamic_pointer_cast<ElementModel>(controller->get_selected_object());
if (element)
{
request_selected_element_property("");
return;
}
auto pad = std::dynamic_pointer_cast<PadModel>(controller->get_selected_object());
if (pad)
{
show_pad_properties();
}
}
class PadPropertyModelColumns : public Gtk::TreeModel::ColumnRecord
{
public:
Gtk::TreeModelColumn<Glib::ustring> m_col_name;
Gtk::TreeModelColumn<Glib::ustring> m_col_value;
PadPropertyModelColumns()
{
add(m_col_name);
add(m_col_value);
}
};
void GstPropertiesModule::show_pad_properties()
{
auto pad = std::dynamic_pointer_cast<PadModel>(controller->get_selected_object());
if (!pad)
{
return;
}
PadPropertyModelColumns cols;
auto model = Gtk::TreeStore::create(cols);
Gtk::TreeView *tree = Gtk::manage(new Gtk::TreeView());
tree->append_column("Property Name", cols.m_col_name);
tree->append_column("Property Value", cols.m_col_value);
tree->set_model(model);
#define APPEND_ROW(name, value) \
do { \
row = *(model->append()); \
row[cols.m_col_name] = name; \
row[cols.m_col_value] = value; \
} while (false);
std::string peer_pad = pad->get_peer() ? ElementPathProcessor::get_object_path(pad->get_peer()) : std::string("NO PEER PAD");
Gtk::TreeModel::Row row;
APPEND_ROW("Name", pad->get_name());
if (pad->get_template())
{
display_template_info(pad->get_template(), model, cols.m_col_name, cols.m_col_value);
}
APPEND_ROW("Presence", get_presence_str(pad->get_presence()));
APPEND_ROW("Direction", get_direction_str(pad->get_direction()));
APPEND_ROW("Peer pad", peer_pad);
if (pad->get_current_caps())
{
APPEND_ROW("Current caps", "");
display_caps(pad->get_current_caps(), model, cols.m_col_name, cols.m_col_value, row);
}
else
{
APPEND_ROW("Current caps", "unknown");
}
if (pad->get_allowed_caps())
{
APPEND_ROW("Allowed caps", "");
display_caps(pad->get_allowed_caps(), model, cols.m_col_name, cols.m_col_value, row);
}
else
{
APPEND_ROW("Allowed caps", "unknown");
}
#undef APPEND_ROW
tree->show();
properties_box->pack_start(*tree, true, true, 0);
}
<commit_msg>gst-debugger: lock widgets if property is not writable<commit_after>/*
* gst_properties_module.cpp
*
* Created on: Jul 14, 2015
* Author: loganek
*/
#include "gst_properties_module.h"
#include "gvalue-converter/gvalue_enum.h"
#include "common/deserializer.h"
#include "controller/command_factory.h"
#include "controller/controller.h"
#include "controller/element_path_processor.h"
#include "ui_utils.h"
#include <gst/gst.h>
static void free_properties(Property *property) { delete property; }
GstPropertiesModule::GstPropertiesModule(const Glib::RefPtr<Gtk::Builder>& builder)
{
builder->get_widget("showPropertiesButton", show_propetries_button);
show_propetries_button->signal_clicked().connect(sigc::mem_fun(*this, &GstPropertiesModule::showPropertiesButton_clicked_cb));
builder->get_widget("propertiesBox", properties_box);
create_dispatcher("property", sigc::mem_fun(*this, &GstPropertiesModule::new_property_), (GDestroyNotify)free_properties);
create_dispatcher("selected-object-changed", sigc::mem_fun(*this, &GstPropertiesModule::selected_object_changed_), nullptr);
}
void GstPropertiesModule::set_controller(const std::shared_ptr<Controller> &controller)
{
IBaseView::set_controller(controller);
controller->on_property_received.connect(sigc::mem_fun(*this, &GstPropertiesModule::new_property));
controller->on_selected_object_changed.connect(sigc::mem_fun(*this, &GstPropertiesModule::selected_object_changed));
}
void GstPropertiesModule::new_property(const Property &property)
{
gui_push("property", new Property (property));
gui_emit("property");
}
void GstPropertiesModule::request_selected_element_property(const std::string &property_name)
{
auto obj = controller->get_selected_object();
if (!obj || !std::dynamic_pointer_cast<ElementModel>(obj))
{
return;
}
std::string element_path = ElementPathProcessor::get_object_path(obj);
controller->send_property_request_command(element_path, property_name);
if (element_path != previous_element_path)
{
clear_widgets();
previous_element_path = element_path;
}
}
void GstPropertiesModule::showPropertiesButton_clicked_cb()
{
request_selected_element_property("");
}
void GstPropertiesModule::new_property_()
{
auto property = gui_pop<Property*>("property");
auto element = std::dynamic_pointer_cast<ElementModel>(ElementPathProcessor(property->element_path()).get_last_obj());
if (!element)
{
return;
}
std::shared_ptr<GValueBase> value_base = element->get_property(property->property_name());
std::shared_ptr<GValueEnum> value_enum = std::dynamic_pointer_cast<GValueEnum>(value_base);
auto& container = const_cast<RemoteDataContainer<GstEnumType>&>(controller->get_enum_container());
if (value_enum && container.has_item(property->type_name()))
{
value_enum->set_type(container.get_item(property->type_name()));
}
if (!update_property(value_base, property))
{
append_property(value_base, property);
}
delete property;
}
bool GstPropertiesModule::update_property(const std::shared_ptr<GValueBase>& value_base, Property *property)
{
for (auto internal_box : properties_box->get_children())
{
Gtk::Box *hb = dynamic_cast<Gtk::Box*>(internal_box);
if (hb == nullptr)
{
continue;
}
Gtk::Label *label = nullptr;
Gtk::Widget *widget = nullptr;
for (auto cd : hb->get_children())
{
if (label == nullptr && (label = dynamic_cast<Gtk::Label*>(cd)) != nullptr)
{
if (label->get_text() != property->property_name())
{
label = nullptr;
break;
}
}
else if (dynamic_cast<Gtk::Button*>(cd) == nullptr || dynamic_cast<Gtk::CheckButton*>(cd) != nullptr)
{
widget = cd;
}
}
if (label == nullptr || widget == nullptr)
{
continue;
}
hb->remove(*widget);
widget = value_base->get_widget();
widget->show();
hb->pack_start(*widget, true, 10);
hb->reorder_child(*widget, 1);
return true;
}
return false;
}
void GstPropertiesModule::append_property(const std::shared_ptr<GValueBase>& value_base, Property *property)
{
Gtk::Box *hbox = new Gtk::Box (Gtk::ORIENTATION_HORIZONTAL, 0);
hbox->show();
auto prop_name = property->property_name();
Gtk::Label *lbl = Gtk::manage(new Gtk::Label(prop_name));
lbl->set_tooltip_text(property->description());
lbl->show();
Gtk::Button *btn = Gtk::manage(new Gtk::Button("Refresh"));
btn->signal_clicked().connect([this, prop_name] {request_selected_element_property(prop_name);});
btn->show();
hbox->pack_start(*lbl, false, false);
auto value_widget = value_base->get_widget();
value_widget->show();
value_widget->set_sensitive(property->flags() & G_PARAM_WRITABLE);
hbox->pack_start(*value_widget, true, true);
hbox->pack_start(*btn, false, false);
properties_box->pack_start(*hbox);
}
void GstPropertiesModule::clear_widgets()
{
for (auto c : properties_box->get_children())
{
delete c;
}
}
void GstPropertiesModule::selected_object_changed()
{
gui_emit("selected-object-changed");
}
void GstPropertiesModule::selected_object_changed_()
{
clear_widgets();
auto element = std::dynamic_pointer_cast<ElementModel>(controller->get_selected_object());
if (element)
{
request_selected_element_property("");
return;
}
auto pad = std::dynamic_pointer_cast<PadModel>(controller->get_selected_object());
if (pad)
{
show_pad_properties();
}
}
class PadPropertyModelColumns : public Gtk::TreeModel::ColumnRecord
{
public:
Gtk::TreeModelColumn<Glib::ustring> m_col_name;
Gtk::TreeModelColumn<Glib::ustring> m_col_value;
PadPropertyModelColumns()
{
add(m_col_name);
add(m_col_value);
}
};
void GstPropertiesModule::show_pad_properties()
{
auto pad = std::dynamic_pointer_cast<PadModel>(controller->get_selected_object());
if (!pad)
{
return;
}
PadPropertyModelColumns cols;
auto model = Gtk::TreeStore::create(cols);
Gtk::TreeView *tree = Gtk::manage(new Gtk::TreeView());
tree->append_column("Property Name", cols.m_col_name);
tree->append_column("Property Value", cols.m_col_value);
tree->set_model(model);
#define APPEND_ROW(name, value) \
do { \
row = *(model->append()); \
row[cols.m_col_name] = name; \
row[cols.m_col_value] = value; \
} while (false);
std::string peer_pad = pad->get_peer() ? ElementPathProcessor::get_object_path(pad->get_peer()) : std::string("NO PEER PAD");
Gtk::TreeModel::Row row;
APPEND_ROW("Name", pad->get_name());
if (pad->get_template())
{
display_template_info(pad->get_template(), model, cols.m_col_name, cols.m_col_value);
}
APPEND_ROW("Presence", get_presence_str(pad->get_presence()));
APPEND_ROW("Direction", get_direction_str(pad->get_direction()));
APPEND_ROW("Peer pad", peer_pad);
if (pad->get_current_caps())
{
APPEND_ROW("Current caps", "");
display_caps(pad->get_current_caps(), model, cols.m_col_name, cols.m_col_value, row);
}
else
{
APPEND_ROW("Current caps", "unknown");
}
if (pad->get_allowed_caps())
{
APPEND_ROW("Allowed caps", "");
display_caps(pad->get_allowed_caps(), model, cols.m_col_name, cols.m_col_value, row);
}
else
{
APPEND_ROW("Allowed caps", "unknown");
}
#undef APPEND_ROW
tree->show();
properties_box->pack_start(*tree, true, true, 0);
}
<|endoftext|> |
<commit_before>/*************************************************************************
*
* $RCSfile: statusindicatorfactory.hxx,v $
*
* $Revision: 1.7 $
*
* last change: $Author: obo $ $Date: 2004-09-09 17:06:38 $
*
* The Contents of this file are made available subject to the terms of
* either of the following licenses
*
* - GNU Lesser General Public License Version 2.1
* - Sun Industry Standards Source License Version 1.1
*
* Sun Microsystems Inc., October, 2000
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2000 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
*
* Sun Industry Standards Source License Version 1.1
* =================================================
* The contents of this file are subject to the Sun Industry Standards
* Source License Version 1.1 (the "License"); You may not use this file
* except in compliance with the License. You may obtain a copy of the
* License at http://www.openoffice.org/license.html.
*
* Software provided under this License is provided on an "AS IS" basis,
* WITHOUT WARRUNTY OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING,
* WITHOUT LIMITATION, WARRUNTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
* MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
* See the License for the specific provisions governing your rights and
* obligations concerning the Software.
*
* The Initial Developer of the Original Code is: Sun Microsystems, Inc..
*
* Copyright: 2000 by Sun Microsystems, Inc.
*
* All Rights Reserved.
*
* Contributor(s): _______________________________________
*
*
************************************************************************/
#ifndef __FRAMEWORK_HELPER_STATUSINDICATORFACTORY_HXX_
#define __FRAMEWORK_HELPER_STATUSINDICATORFACTORY_HXX_
/** Attention: stl headers must(!) be included at first. Otherwhise it can make trouble
with solaris headers ...
*/
#include <vector>
//_________________________________________________________________________________________________________________
// my own includes
//_________________________________________________________________________________________________________________
#ifndef __FRAMEWORK_MACROS_GENERIC_HXX_
#include <macros/generic.hxx>
#endif
#ifndef __FRAMEWORK_MACROS_XINTERFACE_HXX_
#include <macros/xinterface.hxx>
#endif
#ifndef __FRAMEWORK_MACROS_DEBUG_HXX_
#include <macros/debug.hxx>
#endif
#ifndef __FRAMEWORK_THREADHELP_THREADHELPBASE_HXX_
#include <threadhelp/threadhelpbase.hxx>
#endif
#ifndef __FRAMEWORK_THREADHELP_TRANSACTIONBASE_HXX_
#include <threadhelp/transactionbase.hxx>
#endif
#ifndef __FRAMEWORK_GENERAL_H_
#include <general.h>
#endif
//_________________________________________________________________________________________________________________
// interface includes
//_________________________________________________________________________________________________________________
#ifndef _COM_SUN_STAR_LANG_XEVENTLISTENER_HPP_
#include <com/sun/star/lang/XEventListener.hpp>
#endif
#ifndef _COM_SUN_STAR_TASK_XSTATUSINDICATORFACTORY_HPP_
#include <com/sun/star/task/XStatusIndicatorFactory.hpp>
#endif
#ifndef _COM_SUN_STAR_TASK_XSTATUSINDICATOR_HPP_
#include <com/sun/star/task/XStatusIndicator.hpp>
#endif
#ifndef _COM_SUN_STAR_AWT_XWINDOW_HPP_
#include <com/sun/star/awt/XWindow.hpp>
#endif
#ifndef _COM_SUN_STAR_AWT_XWINDOWLISTENER_HPP_
#include <com/sun/star/awt/XWindowListener.hpp>
#endif
#ifndef _COM_SUN_STAR_LANG_EVENTOBJECT_HPP_
#include <com/sun/star/lang/EventObject.hpp>
#endif
#ifndef _COM_SUN_STAR_AWT_WINDOWEVENT_HPP_
#include <com/sun/star/awt/WindowEvent.hpp>
#endif
#ifndef _COM_SUN_STAR_LANG_XMULTISERVICEFACTORY_HPP_
#include <com/sun/star/lang/XMultiServiceFactory.hpp>
#endif
#ifndef _COM_SUN_STAR_FRAME_XFRAME_HPP_
#include <com/sun/star/frame/XFrame.hpp>
#endif
#ifndef _SV_STATUS_HXX
#include <vcl/status.hxx>
#endif
//_________________________________________________________________________________________________________________
// other includes
//_________________________________________________________________________________________________________________
#ifndef _CPPUHELPER_WEAK_HXX_
#include <cppuhelper/weak.hxx>
#endif
//_________________________________________________________________________________________________________________
// namespace
//_________________________________________________________________________________________________________________
namespace framework{
//_________________________________________________________________________________________________________________
// exported const
//_________________________________________________________________________________________________________________
//_________________________________________________________________________________________________________________
// exported definitions
//_________________________________________________________________________________________________________________
/*-************************************************************************************************************//**
@descr These struct hold some informations about all currently running progress proccesses.
We need a reference to right child indicator wrapper, his ranges and values.
*//*-*************************************************************************************************************/
struct IndicatorInfo
{
public:
//---------------------------------------------------------------------------------------------------------
// Initialize struct with new indicator and set default values for ranges and values
IndicatorInfo( const css::uno::Reference< css::task::XStatusIndicator >& xNewIndicator,
const ::rtl::OUString& sText ,
sal_Int32 nRange )
{
m_xIndicator = xNewIndicator;
m_sText = sText ;
m_nRange = nRange ;
m_nValue = 0 ;
}
//---------------------------------------------------------------------------------------------------------
// Don't forget to free used references!
~IndicatorInfo()
{
m_xIndicator = css::uno::Reference< css::task::XStatusIndicator >();
reset();
}
//---------------------------------------------------------------------------------------------------------
// Reset all values of these indicator.
void reset()
{
m_sText = ::rtl::OUString();
m_nRange = 0 ;
m_nValue = 0 ;
}
//---------------------------------------------------------------------------------------------------------
// Used by status indicator only, if other values of struct are unknown!
sal_Bool operator==( const css::uno::Reference< css::task::XStatusIndicator >& xIndicator )
{
return( m_xIndicator == xIndicator );
}
//---------------------------------------------------------------------------------------------------------
// norm nValue to fit range of 0..100%
sal_Int32 calcPercentage()
{
return ::std::min( (( m_nValue * 100 )/ ::std::max( m_nRange, (sal_Int32)1 ) ), (sal_Int32)100 );
}
public:
css::uno::Reference< css::task::XStatusIndicator > m_xIndicator ;
::rtl::OUString m_sText ;
sal_Int32 m_nRange ;
sal_Int32 m_nValue ;
};
typedef ::std::vector< IndicatorInfo > IndicatorStack;
/*-************************************************************************************************************//**
@short implement a factory to create new status indicator objects
@descr We use it as helper for our frame implementation.
The factory create different indicators and control his access to shared output device!
Only the last activated component can write his state to this device.
@implements XInterface
XStatusIndicatorFactory
XWindowListener
XEventListener
@base ThreadHelpBase
TransactionBase
OWeakObject
@devstatus ready to use
@threadsafe yes
*//*-*************************************************************************************************************/
class StatusIndicatorFactory : public css::task::XStatusIndicatorFactory ,
private ThreadHelpBase ,
private TransactionBase ,
public ::cppu::OWeakObject // => XInterface
{
//-------------------------------------------------------------------------------------------------------------
// public methods
//-------------------------------------------------------------------------------------------------------------
public:
//---------------------------------------------------------------------------------------------------------
// constructor / destructor
//---------------------------------------------------------------------------------------------------------
StatusIndicatorFactory( const css::uno::Reference< css::lang::XMultiServiceFactory >& xFactory ,
const css::uno::Reference< css::frame::XFrame >& xFrame ,
sal_Bool bShowStatusBar);
//---------------------------------------------------------------------------------------------------------
// XInterface
//---------------------------------------------------------------------------------------------------------
DECLARE_XINTERFACE
//---------------------------------------------------------------------------------------------------------
// XStatusIndicatorFactory
//---------------------------------------------------------------------------------------------------------
virtual css::uno::Reference< css::task::XStatusIndicator > SAL_CALL createStatusIndicator() throw( css::uno::RuntimeException );
//---------------------------------------------------------------------------------------------------------
// public shared method!
//---------------------------------------------------------------------------------------------------------
void start ( const css::uno::Reference< css::task::XStatusIndicator >& xChild ,
const ::rtl::OUString& sText ,
sal_Int32 nRange );
void end ( const css::uno::Reference< css::task::XStatusIndicator >& xChild );
void reset ( const css::uno::Reference< css::task::XStatusIndicator >& xChild );
void setText ( const css::uno::Reference< css::task::XStatusIndicator >& xChild ,
const ::rtl::OUString& sText );
void setValue ( const css::uno::Reference< css::task::XStatusIndicator >& xChild ,
sal_Int32 nValue );
//-------------------------------------------------------------------------------------------------------------
// protected methods
//-------------------------------------------------------------------------------------------------------------
protected:
virtual ~StatusIndicatorFactory();
//-------------------------------------------------------------------------------------------------------------
// private methods
//-------------------------------------------------------------------------------------------------------------
private:
void impl_reschedule();
sal_uInt32 impl_get10ThSec();
void impl_createStatusBar();
css::uno::Reference< css::awt::XWindow > implts_getParentWindow();
//-------------------------------------------------------------------------------------------------------------
// variables
// (should be private everyway!)
//-------------------------------------------------------------------------------------------------------------
private:
static sal_Int32 m_nInReschedule ; /// static counter for rescheduling
IndicatorStack m_aStack ; /// stack with all current indicator childs
css::uno::Reference< css::lang::XMultiServiceFactory > m_xFactory ; /// uno service manager to create new services
sal_Bool m_bProgressMode ;
css::uno::Reference< css::task::XStatusIndicator > m_xActiveIndicator ; /// most active indicator child, which could work with our shared indicator window only
css::uno::Reference< css::task::XStatusIndicator > m_xProgress ; /// status indicator from layout manager
css::uno::WeakReference< css::frame::XFrame > m_xFrame ;
long m_nStartTime ; /// time where there last start call was made
}; // class StatusIndicatorFactory
} // namespace framework
#endif // #ifndef __FRAMEWORK_HELPER_STATUSINDICATORFACTORY_HXX_
<commit_msg>INTEGRATION: CWS recovery04 (1.6.242); FILE MERGED 2004/10/21 05:10:51 as 1.6.242.6: fix some compile errors 2004/10/20 13:08:34 as 1.6.242.5: #i27726# redesign progress implementation after resync 2004/10/19 06:24:00 hro 1.6.242.4: #i28480# Resolved merge conflicts 2004/10/15 02:39:48 hro 1.6.242.3: RESYNC: (1.6-1.7); FILE MERGED 2004/08/05 11:24:48 as 1.6.242.2: #27726# make auto recovery aynchron 2004/07/23 13:46:18 hro 1.6.242.1: #i20882# Merging from recovery03<commit_after>/*************************************************************************
*
* $RCSfile: statusindicatorfactory.hxx,v $
*
* $Revision: 1.8 $
*
* last change: $Author: rt $ $Date: 2004-11-26 14:28:51 $
*
* The Contents of this file are made available subject to the terms of
* either of the following licenses
*
* - GNU Lesser General Public License Version 2.1
* - Sun Industry Standards Source License Version 1.1
*
* Sun Microsystems Inc., October, 2000
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2000 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
*
* Sun Industry Standards Source License Version 1.1
* =================================================
* The contents of this file are subject to the Sun Industry Standards
* Source License Version 1.1 (the "License"); You may not use this file
* except in compliance with the License. You may obtain a copy of the
* License at http://www.openoffice.org/license.html.
*
* Software provided under this License is provided on an "AS IS" basis,
* WITHOUT WARRUNTY OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING,
* WITHOUT LIMITATION, WARRUNTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
* MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
* See the License for the specific provisions governing your rights and
* obligations concerning the Software.
*
* The Initial Developer of the Original Code is: Sun Microsystems, Inc..
*
* Copyright: 2000 by Sun Microsystems, Inc.
*
* All Rights Reserved.
*
* Contributor(s): _______________________________________
*
*
************************************************************************/
#ifndef __FRAMEWORK_HELPER_STATUSINDICATORFACTORY_HXX_
#define __FRAMEWORK_HELPER_STATUSINDICATORFACTORY_HXX_
/** Attention: stl headers must(!) be included at first. Otherwhise it can make trouble
with solaris headers ...
*/
#include <vector>
//_________________________________________________________________________________________________________________
// my own includes
//_________________________________________________________________________________________________________________
#ifndef __FRAMEWORK_MACROS_GENERIC_HXX_
#include <macros/generic.hxx>
#endif
#ifndef __FRAMEWORK_MACROS_XINTERFACE_HXX_
#include <macros/xinterface.hxx>
#endif
#ifndef __FRAMEWORK_MACROS_XTYPEPROVIDER_HXX_
#include <macros/xtypeprovider.hxx>
#endif
#ifndef __FRAMEWORK_MACROS_XSERVICEINFO_HXX_
#include <macros/xserviceinfo.hxx>
#endif
#ifndef __FRAMEWORK_MACROS_DEBUG_HXX_
#include <macros/debug.hxx>
#endif
#ifndef __FRAMEWORK_THREADHELP_THREADHELPBASE_HXX_
#include <threadhelp/threadhelpbase.hxx>
#endif
#ifndef __FRAMEWORK_THREADHELP_TRANSACTIONBASE_HXX_
#include <threadhelp/transactionbase.hxx>
#endif
#ifndef __FRAMEWORK_GENERAL_H_
#include <general.h>
#endif
//_________________________________________________________________________________________________________________
// interface includes
//_________________________________________________________________________________________________________________
#ifndef _COM_SUN_STAR_LANG_XTYPEPROVIDER_HPP_
#include <com/sun/star/lang/XTypeProvider.hpp>
#endif
#ifndef _COM_SUN_STAR_LANG_XSERVICEINFO_HPP_
#include <com/sun/star/lang/XServiceInfo.hpp>
#endif
#ifndef _COM_SUN_STAR_LANG_XINITIALIZATION_HPP_
#include <com/sun/star/lang/XInitialization.hpp>
#endif
#ifndef _COM_SUN_STAR_LANG_XEVENTLISTENER_HPP_
#include <com/sun/star/lang/XEventListener.hpp>
#endif
#ifndef _COM_SUN_STAR_TASK_XSTATUSINDICATORFACTORY_HPP_
#include <com/sun/star/task/XStatusIndicatorFactory.hpp>
#endif
#ifndef _COM_SUN_STAR_TASK_XSTATUSINDICATOR_HPP_
#include <com/sun/star/task/XStatusIndicator.hpp>
#endif
#ifndef _COM_SUN_STAR_AWT_XWINDOW_HPP_
#include <com/sun/star/awt/XWindow.hpp>
#endif
#ifndef _COM_SUN_STAR_AWT_XWINDOWLISTENER_HPP_
#include <com/sun/star/awt/XWindowListener.hpp>
#endif
#ifndef _COM_SUN_STAR_LANG_EVENTOBJECT_HPP_
#include <com/sun/star/lang/EventObject.hpp>
#endif
#ifndef _COM_SUN_STAR_AWT_WINDOWEVENT_HPP_
#include <com/sun/star/awt/WindowEvent.hpp>
#endif
#ifndef _COM_SUN_STAR_LANG_XMULTISERVICEFACTORY_HPP_
#include <com/sun/star/lang/XMultiServiceFactory.hpp>
#endif
#ifndef _COM_SUN_STAR_FRAME_XFRAME_HPP_
#include <com/sun/star/frame/XFrame.hpp>
#endif
#ifndef _SV_STATUS_HXX
#include <vcl/status.hxx>
#endif
//_________________________________________________________________________________________________________________
// other includes
//_________________________________________________________________________________________________________________
#ifndef _CPPUHELPER_WEAK_HXX_
#include <cppuhelper/weak.hxx>
#endif
//_________________________________________________________________________________________________________________
// namespace
//_________________________________________________________________________________________________________________
namespace framework{
//_________________________________________________________________________________________________________________
// exported const
//_________________________________________________________________________________________________________________
//_________________________________________________________________________________________________________________
// exported definitions
//_________________________________________________________________________________________________________________
/*-************************************************************************************************************//**
@descr These struct hold some informations about all currently running progress proccesses.
We need a reference to right child indicator wrapper, his ranges and values.
*//*-*************************************************************************************************************/
struct IndicatorInfo
{
public:
//---------------------------------------------------------------------------------------------------------
// Initialize struct with new indicator and set default values for ranges and values
IndicatorInfo( const css::uno::Reference< css::task::XStatusIndicator >& xNewIndicator,
const ::rtl::OUString& sText ,
sal_Int32 nRange )
{
m_xIndicator = xNewIndicator;
m_sText = sText ;
m_nRange = nRange ;
m_nValue = 0 ;
}
//---------------------------------------------------------------------------------------------------------
// Don't forget to free used references!
~IndicatorInfo()
{
m_xIndicator = css::uno::Reference< css::task::XStatusIndicator >();
reset();
}
//---------------------------------------------------------------------------------------------------------
// Reset all values of these indicator.
void reset()
{
m_sText = ::rtl::OUString();
m_nRange = 0 ;
m_nValue = 0 ;
}
//---------------------------------------------------------------------------------------------------------
// Used by status indicator only, if other values of struct are unknown!
sal_Bool operator==( const css::uno::Reference< css::task::XStatusIndicator >& xIndicator )
{
return( m_xIndicator == xIndicator );
}
//---------------------------------------------------------------------------------------------------------
// norm nValue to fit range of 0..100%
sal_Int32 calcPercentage()
{
return ::std::min( (( m_nValue * 100 )/ ::std::max( m_nRange, (sal_Int32)1 ) ), (sal_Int32)100 );
}
public:
css::uno::Reference< css::task::XStatusIndicator > m_xIndicator ;
::rtl::OUString m_sText ;
sal_Int32 m_nRange ;
sal_Int32 m_nValue ;
};
typedef ::std::vector< IndicatorInfo > IndicatorStack;
/*-************************************************************************************************************//**
@short implement a factory service to create new status indicator objects
@descr Internaly it uses:
- a vcl based progress
- or an uno based and by the frame layouted
progress implementation.
This factory create different indicators and control his access to shared output device!
Only the last activated component can write his state to this device.
@devstatus ready to use
@threadsafe yes
*//*-*************************************************************************************************************/
class StatusIndicatorFactory : public css::lang::XTypeProvider
, public css::lang::XServiceInfo
, public css::lang::XInitialization
, public css::task::XStatusIndicatorFactory
, private ThreadHelpBase
, public ::cppu::OWeakObject // => XInterface
{
//-------------------------------------------
// member
private:
/** stack with all current indicator childs. */
IndicatorStack m_aStack;
/** uno service manager to create own needed uno resources. */
css::uno::Reference< css::lang::XMultiServiceFactory > m_xSMGR;
/** most active indicator child, which could work with our shared indicator window only. */
css::uno::Reference< css::task::XStatusIndicator > m_xActiveChild;
/** used to show the progress on the frame (layouted!) or
as a plugged vcl window. */
css::uno::Reference< css::task::XStatusIndicator > m_xProgress;
/** points to the frame, where we show the progress (in case
m_xProgress points to a frame progress. */
css::uno::WeakReference< css::frame::XFrame > m_xFrame;
/** points to an outside window, where we show the progress (in case
we are plugged into such window). */
css::uno::WeakReference< css::awt::XWindow > m_xPluggWindow;
/** static counter for rescheduling ... */
static sal_Int32 m_nInReschedule;
/** time where there last start call was made. */
sal_Int32 m_nStartTime;
//-------------------------------------------
// interface
public:
//---------------------------------------
// ctor
StatusIndicatorFactory(const css::uno::Reference< css::lang::XMultiServiceFactory >& xSMGR);
//---------------------------------------
// XInterface, XTypeProvider, XServiceInfo
DECLARE_XINTERFACE
DECLARE_XTYPEPROVIDER
DECLARE_XSERVICEINFO
//---------------------------------------
// XInitialization
virtual void SAL_CALL initialize(const css::uno::Sequence< css::uno::Any >& lArguments)
throw(css::uno::Exception ,
css::uno::RuntimeException);
//---------------------------------------
// XStatusIndicatorFactory
virtual css::uno::Reference< css::task::XStatusIndicator > SAL_CALL createStatusIndicator()
throw(css::uno::RuntimeException);
//---------------------------------------
// similar (XStatusIndicator)
virtual void start(const css::uno::Reference< css::task::XStatusIndicator >& xChild,
const ::rtl::OUString& sText ,
sal_Int32 nRange);
virtual void SAL_CALL reset(const css::uno::Reference< css::task::XStatusIndicator >& xChild);
virtual void SAL_CALL end(const css::uno::Reference< css::task::XStatusIndicator >& xChild);
virtual void SAL_CALL setText(const css::uno::Reference< css::task::XStatusIndicator >& xChild,
const ::rtl::OUString& sText );
virtual void SAL_CALL setValue(const css::uno::Reference< css::task::XStatusIndicator >& xChild,
sal_Int32 nValue);
//-------------------------------------------
// specials
protected:
virtual ~StatusIndicatorFactory();
//-------------------------------------------
// helper
private:
void impl_createProgress();
void impl_reschedule();
sal_uInt32 impl_get10ThSec();
}; // class StatusIndicatorFactory
} // namespace framework
#endif // #ifndef __FRAMEWORK_HELPER_STATUSINDICATORFACTORY_HXX_
<|endoftext|> |
<commit_before>/*************************************************************************
*
* $RCSfile: statusindicatorfactory.hxx,v $
*
* $Revision: 1.11 $
*
* last change: $Author: obo $ $Date: 2005-08-12 16:23:52 $
*
* The Contents of this file are made available subject to the terms of
* either of the following licenses
*
* - GNU Lesser General Public License Version 2.1
* - Sun Industry Standards Source License Version 1.1
*
* Sun Microsystems Inc., October, 2000
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2000 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
*
* Sun Industry Standards Source License Version 1.1
* =================================================
* The contents of this file are subject to the Sun Industry Standards
* Source License Version 1.1 (the "License"); You may not use this file
* except in compliance with the License. You may obtain a copy of the
* License at http://www.openoffice.org/license.html.
*
* Software provided under this License is provided on an "AS IS" basis,
* WITHOUT WARRUNTY OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING,
* WITHOUT LIMITATION, WARRUNTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
* MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
* See the License for the specific provisions governing your rights and
* obligations concerning the Software.
*
* The Initial Developer of the Original Code is: Sun Microsystems, Inc..
*
* Copyright: 2000 by Sun Microsystems, Inc.
*
* All Rights Reserved.
*
* Contributor(s): _______________________________________
*
*
************************************************************************/
#ifndef __FRAMEWORK_HELPER_STATUSINDICATORFACTORY_HXX_
#define __FRAMEWORK_HELPER_STATUSINDICATORFACTORY_HXX_
// Attention: stl headers must(!) be included at first. Otherwhise it can make trouble
// with solaris headers ...
#include <vector>
//_______________________________________________
// include files of own module
#ifndef __FRAMEWORK_HELPER_WAKEUPTHREAD_HXX_
#include <helper/wakeupthread.hxx>
#endif
#ifndef __FRAMEWORK_THREADHELP_THREADHELPBASE_HXX_
#include <threadhelp/threadhelpbase.hxx>
#endif
#ifndef __FRAMEWORK_MACROS_XINTERFACE_HXX_
#include <macros/xinterface.hxx>
#endif
#ifndef __FRAMEWORK_MACROS_XTYPEPROVIDER_HXX_
#include <macros/xtypeprovider.hxx>
#endif
#ifndef __FRAMEWORK_MACROS_XSERVICEINFO_HXX_
#include <macros/xserviceinfo.hxx>
#endif
#ifndef __FRAMEWORK_MACROS_DEBUG_HXX_
#include <macros/debug.hxx>
#endif
#ifndef __FRAMEWORK_MACROS_GENERIC_HXX_
#include <macros/generic.hxx>
#endif
#ifndef __FRAMEWORK_GENERAL_H_
#include <general.h>
#endif
//_______________________________________________
// include uno interfaces
#ifndef _COM_SUN_STAR_LANG_XTYPEPROVIDER_HPP_
#include <com/sun/star/lang/XTypeProvider.hpp>
#endif
#ifndef _COM_SUN_STAR_LANG_XSERVICEINFO_HPP_
#include <com/sun/star/lang/XServiceInfo.hpp>
#endif
#ifndef _COM_SUN_STAR_LANG_XINITIALIZATION_HPP_
#include <com/sun/star/lang/XInitialization.hpp>
#endif
#ifndef _COM_SUN_STAR_LANG_XEVENTLISTENER_HPP_
#include <com/sun/star/lang/XEventListener.hpp>
#endif
#ifndef _COM_SUN_STAR_TASK_XSTATUSINDICATORFACTORY_HPP_
#include <com/sun/star/task/XStatusIndicatorFactory.hpp>
#endif
#ifndef _COM_SUN_STAR_TASK_XSTATUSINDICATOR_HPP_
#include <com/sun/star/task/XStatusIndicator.hpp>
#endif
#ifndef _COM_SUN_STAR_AWT_XWINDOW_HPP_
#include <com/sun/star/awt/XWindow.hpp>
#endif
#ifndef _COM_SUN_STAR_AWT_XWINDOWLISTENER_HPP_
#include <com/sun/star/awt/XWindowListener.hpp>
#endif
#ifndef _COM_SUN_STAR_LANG_EVENTOBJECT_HPP_
#include <com/sun/star/lang/EventObject.hpp>
#endif
#ifndef _COM_SUN_STAR_AWT_WINDOWEVENT_HPP_
#include <com/sun/star/awt/WindowEvent.hpp>
#endif
#ifndef _COM_SUN_STAR_LANG_XMULTISERVICEFACTORY_HPP_
#include <com/sun/star/lang/XMultiServiceFactory.hpp>
#endif
#ifndef _COM_SUN_STAR_FRAME_XFRAME_HPP_
#include <com/sun/star/frame/XFrame.hpp>
#endif
#ifndef _COM_SUN_STAR_URTIL_XUPDATABLE_HPP_
#include <com/sun/star/util/XUpdatable.hpp>
#endif
//_______________________________________________
// include others
#ifndef _SV_STATUS_HXX
#include <vcl/status.hxx>
#endif
#ifndef _CPPUHELPER_WEAK_HXX_
#include <cppuhelper/weak.hxx>
#endif
#ifndef _THREAD_HXX_
#include <osl/thread.hxx>
#endif
//_______________________________________________
// namespace
namespace framework{
//_______________________________________________
// definitions
//===============================================
/**
@descr This struct hold some informations about all currently running progress proccesses.
Because the can be used on a stack, we must cache her states but must paint only
the top most one.
*/
struct IndicatorInfo
{
//-------------------------------------------
// member
public:
/** @short points to the indicator child, where we hold its states
alive here. */
css::uno::Reference< css::task::XStatusIndicator > m_xIndicator;
/** @short the last set text for this indicator */
::rtl::OUString m_sText;
/** @short the max range for this indicator. */
sal_Int32 m_nRange;
/** @short the last set value for this indicator */
sal_Int32 m_nValue;
//-------------------------------------------
// interface
public:
//---------------------------------------
/** @short initialize new instance of this class
@param xIndicator
the new child indiactor of our factory.
@param sText
its initial text.
@param nRange
the max range for this indicator.
*/
IndicatorInfo(const css::uno::Reference< css::task::XStatusIndicator >& xIndicator,
const ::rtl::OUString& sText ,
sal_Int32 nRange )
{
m_xIndicator = xIndicator;
m_sText = sText ;
m_nRange = nRange ;
m_nValue = 0 ;
}
//---------------------------------------
/** @short Don't forget to free used references!
*/
~IndicatorInfo()
{
m_xIndicator.clear();
}
//---------------------------------------------------------------------------------------------------------
/** @short Used to locate an info struct inside a stl structure ...
@descr The indicator object itself is used as key. Its values
are not interesting then. Because mor then one child
indicator can use the same values ...
*/
sal_Bool operator==(const css::uno::Reference< css::task::XStatusIndicator >& xIndicator)
{
return (m_xIndicator == xIndicator);
}
};
/*
//---------------------------------------------------------------------------------------------------------
// norm nValue to fit range of 0..100%
sal_Int32 calcPercentage()
{
return ::std::min( (( m_nValue * 100 )/ ::std::max( m_nRange, (sal_Int32)1 ) ), (sal_Int32)100 );
}
*/
//===============================================
/** @descr Define a lits of child indicator objects and her data. */
typedef ::std::vector< IndicatorInfo > IndicatorStack;
//===============================================
/** @short implement a factory service to create new status indicator objects
@descr Internaly it uses:
- a vcl based
- or an uno based and by the frame layouted
progress implementation.
This factory create different indicators and control his access
to a shared output device! Only the last activated component
can write his state to this device. All other requests will be
cached only.
@devstatus ready to use
@threadsafe yes
*/
class StatusIndicatorFactory : public css::lang::XTypeProvider
, public css::lang::XServiceInfo
, public css::lang::XInitialization
, public css::task::XStatusIndicatorFactory
, public css::util::XUpdatable
, private ThreadHelpBase
, public ::cppu::OWeakObject // => XInterface
{
//-------------------------------------------
// member
private:
/** stack with all current indicator childs. */
IndicatorStack m_aStack;
/** uno service manager to create own needed uno resources. */
css::uno::Reference< css::lang::XMultiServiceFactory > m_xSMGR;
/** most active indicator child, which could work with our shared indicator window only. */
css::uno::Reference< css::task::XStatusIndicator > m_xActiveChild;
/** used to show the progress on the frame (layouted!) or
as a plugged vcl window. */
css::uno::Reference< css::task::XStatusIndicator > m_xProgress;
/** points to the frame, where we show the progress (in case
m_xProgress points to a frame progress. */
css::uno::WeakReference< css::frame::XFrame > m_xFrame;
/** points to an outside window, where we show the progress (in case
we are plugged into such window). */
css::uno::WeakReference< css::awt::XWindow > m_xPluggWindow;
/** Notify us if a fix time is over. We use it to implement an
intelligent "Reschedule" ... */
WakeUpThread* m_pWakeUp;
/** Our WakeUpThread calls us in our interface method "XUpdatable::update().
There we set this member m_bAllowReschedule to TRUE. Next time if our impl_reschedule()
method is called, we know, that an Application::Reschedule() should be made.
Because the last made Reschedule can be was taken long time ago ... may be.*/
sal_Bool m_bAllowReschedule;
/** enable/disable automatic showing of our parent window. */
sal_Bool m_bAllowParentShow;
/** enable/disable rescheduling. Default=enabled*/
sal_Bool m_bDisableReschedule;
/** prevent recursive calling of Application::Reschedule(). */
static sal_Int32 m_nInReschedule;
/** time where there last start call was made. */
sal_Int32 m_nStartTime;
//-------------------------------------------
// interface
public:
//---------------------------------------
// ctor
StatusIndicatorFactory(const css::uno::Reference< css::lang::XMultiServiceFactory >& xSMGR);
//---------------------------------------
// XInterface, XTypeProvider, XServiceInfo
DECLARE_XINTERFACE
DECLARE_XTYPEPROVIDER
DECLARE_XSERVICEINFO
//---------------------------------------
// XInitialization
virtual void SAL_CALL initialize(const css::uno::Sequence< css::uno::Any >& lArguments)
throw(css::uno::Exception ,
css::uno::RuntimeException);
//---------------------------------------
// XStatusIndicatorFactory
virtual css::uno::Reference< css::task::XStatusIndicator > SAL_CALL createStatusIndicator()
throw(css::uno::RuntimeException);
//---------------------------------------
// XUpdatable
virtual void SAL_CALL update()
throw(css::uno::RuntimeException);
//---------------------------------------
// similar (XStatusIndicator)
virtual void start(const css::uno::Reference< css::task::XStatusIndicator >& xChild,
const ::rtl::OUString& sText ,
sal_Int32 nRange);
virtual void SAL_CALL reset(const css::uno::Reference< css::task::XStatusIndicator >& xChild);
virtual void SAL_CALL end(const css::uno::Reference< css::task::XStatusIndicator >& xChild);
virtual void SAL_CALL setText(const css::uno::Reference< css::task::XStatusIndicator >& xChild,
const ::rtl::OUString& sText );
virtual void SAL_CALL setValue(const css::uno::Reference< css::task::XStatusIndicator >& xChild,
sal_Int32 nValue);
//-------------------------------------------
// specials
protected:
virtual ~StatusIndicatorFactory();
//-------------------------------------------
// helper
private:
/** @short show the parent window of this progress ...
if it's allowed to do so.
@descr By default we show the parent window automaticly
if this progress is used.
If that isn't a valid operation, the user of this
progress can suppress this feature by initializaing
us with a special parameter.
@seealso initialize()
*/
void implts_makeParentVisibleIfAllowed();
/** @short creates a new internal used progress.
@descr This factory does not paint the progress itself.
It uses helper for that. They can be vcl based or
layouted by the frame and provided as an uno interface.
*/
void impl_createProgress();
/** @short try to "share the current thread in an intelligent manner" :-)
@param Overwrites our algorithm for Reschedule and force it to be shure
that our progress was painted right.
*/
void impl_reschedule(sal_Bool bForceUpdate);
void impl_startWakeUpThread();
void impl_stopWakeUpThread();
}; // class StatusIndicatorFactory
} // namespace framework
#endif // #ifndef __FRAMEWORK_HELPER_STATUSINDICATORFACTORY_HXX_
<commit_msg>INTEGRATION: CWS ooo19126 (1.11.18); FILE MERGED 2005/09/05 13:04:52 rt 1.11.18.1: #i54170# Change license header: remove SISSL<commit_after>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: statusindicatorfactory.hxx,v $
*
* $Revision: 1.12 $
*
* last change: $Author: rt $ $Date: 2005-09-09 00:19:40 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
#ifndef __FRAMEWORK_HELPER_STATUSINDICATORFACTORY_HXX_
#define __FRAMEWORK_HELPER_STATUSINDICATORFACTORY_HXX_
// Attention: stl headers must(!) be included at first. Otherwhise it can make trouble
// with solaris headers ...
#include <vector>
//_______________________________________________
// include files of own module
#ifndef __FRAMEWORK_HELPER_WAKEUPTHREAD_HXX_
#include <helper/wakeupthread.hxx>
#endif
#ifndef __FRAMEWORK_THREADHELP_THREADHELPBASE_HXX_
#include <threadhelp/threadhelpbase.hxx>
#endif
#ifndef __FRAMEWORK_MACROS_XINTERFACE_HXX_
#include <macros/xinterface.hxx>
#endif
#ifndef __FRAMEWORK_MACROS_XTYPEPROVIDER_HXX_
#include <macros/xtypeprovider.hxx>
#endif
#ifndef __FRAMEWORK_MACROS_XSERVICEINFO_HXX_
#include <macros/xserviceinfo.hxx>
#endif
#ifndef __FRAMEWORK_MACROS_DEBUG_HXX_
#include <macros/debug.hxx>
#endif
#ifndef __FRAMEWORK_MACROS_GENERIC_HXX_
#include <macros/generic.hxx>
#endif
#ifndef __FRAMEWORK_GENERAL_H_
#include <general.h>
#endif
//_______________________________________________
// include uno interfaces
#ifndef _COM_SUN_STAR_LANG_XTYPEPROVIDER_HPP_
#include <com/sun/star/lang/XTypeProvider.hpp>
#endif
#ifndef _COM_SUN_STAR_LANG_XSERVICEINFO_HPP_
#include <com/sun/star/lang/XServiceInfo.hpp>
#endif
#ifndef _COM_SUN_STAR_LANG_XINITIALIZATION_HPP_
#include <com/sun/star/lang/XInitialization.hpp>
#endif
#ifndef _COM_SUN_STAR_LANG_XEVENTLISTENER_HPP_
#include <com/sun/star/lang/XEventListener.hpp>
#endif
#ifndef _COM_SUN_STAR_TASK_XSTATUSINDICATORFACTORY_HPP_
#include <com/sun/star/task/XStatusIndicatorFactory.hpp>
#endif
#ifndef _COM_SUN_STAR_TASK_XSTATUSINDICATOR_HPP_
#include <com/sun/star/task/XStatusIndicator.hpp>
#endif
#ifndef _COM_SUN_STAR_AWT_XWINDOW_HPP_
#include <com/sun/star/awt/XWindow.hpp>
#endif
#ifndef _COM_SUN_STAR_AWT_XWINDOWLISTENER_HPP_
#include <com/sun/star/awt/XWindowListener.hpp>
#endif
#ifndef _COM_SUN_STAR_LANG_EVENTOBJECT_HPP_
#include <com/sun/star/lang/EventObject.hpp>
#endif
#ifndef _COM_SUN_STAR_AWT_WINDOWEVENT_HPP_
#include <com/sun/star/awt/WindowEvent.hpp>
#endif
#ifndef _COM_SUN_STAR_LANG_XMULTISERVICEFACTORY_HPP_
#include <com/sun/star/lang/XMultiServiceFactory.hpp>
#endif
#ifndef _COM_SUN_STAR_FRAME_XFRAME_HPP_
#include <com/sun/star/frame/XFrame.hpp>
#endif
#ifndef _COM_SUN_STAR_URTIL_XUPDATABLE_HPP_
#include <com/sun/star/util/XUpdatable.hpp>
#endif
//_______________________________________________
// include others
#ifndef _SV_STATUS_HXX
#include <vcl/status.hxx>
#endif
#ifndef _CPPUHELPER_WEAK_HXX_
#include <cppuhelper/weak.hxx>
#endif
#ifndef _THREAD_HXX_
#include <osl/thread.hxx>
#endif
//_______________________________________________
// namespace
namespace framework{
//_______________________________________________
// definitions
//===============================================
/**
@descr This struct hold some informations about all currently running progress proccesses.
Because the can be used on a stack, we must cache her states but must paint only
the top most one.
*/
struct IndicatorInfo
{
//-------------------------------------------
// member
public:
/** @short points to the indicator child, where we hold its states
alive here. */
css::uno::Reference< css::task::XStatusIndicator > m_xIndicator;
/** @short the last set text for this indicator */
::rtl::OUString m_sText;
/** @short the max range for this indicator. */
sal_Int32 m_nRange;
/** @short the last set value for this indicator */
sal_Int32 m_nValue;
//-------------------------------------------
// interface
public:
//---------------------------------------
/** @short initialize new instance of this class
@param xIndicator
the new child indiactor of our factory.
@param sText
its initial text.
@param nRange
the max range for this indicator.
*/
IndicatorInfo(const css::uno::Reference< css::task::XStatusIndicator >& xIndicator,
const ::rtl::OUString& sText ,
sal_Int32 nRange )
{
m_xIndicator = xIndicator;
m_sText = sText ;
m_nRange = nRange ;
m_nValue = 0 ;
}
//---------------------------------------
/** @short Don't forget to free used references!
*/
~IndicatorInfo()
{
m_xIndicator.clear();
}
//---------------------------------------------------------------------------------------------------------
/** @short Used to locate an info struct inside a stl structure ...
@descr The indicator object itself is used as key. Its values
are not interesting then. Because mor then one child
indicator can use the same values ...
*/
sal_Bool operator==(const css::uno::Reference< css::task::XStatusIndicator >& xIndicator)
{
return (m_xIndicator == xIndicator);
}
};
/*
//---------------------------------------------------------------------------------------------------------
// norm nValue to fit range of 0..100%
sal_Int32 calcPercentage()
{
return ::std::min( (( m_nValue * 100 )/ ::std::max( m_nRange, (sal_Int32)1 ) ), (sal_Int32)100 );
}
*/
//===============================================
/** @descr Define a lits of child indicator objects and her data. */
typedef ::std::vector< IndicatorInfo > IndicatorStack;
//===============================================
/** @short implement a factory service to create new status indicator objects
@descr Internaly it uses:
- a vcl based
- or an uno based and by the frame layouted
progress implementation.
This factory create different indicators and control his access
to a shared output device! Only the last activated component
can write his state to this device. All other requests will be
cached only.
@devstatus ready to use
@threadsafe yes
*/
class StatusIndicatorFactory : public css::lang::XTypeProvider
, public css::lang::XServiceInfo
, public css::lang::XInitialization
, public css::task::XStatusIndicatorFactory
, public css::util::XUpdatable
, private ThreadHelpBase
, public ::cppu::OWeakObject // => XInterface
{
//-------------------------------------------
// member
private:
/** stack with all current indicator childs. */
IndicatorStack m_aStack;
/** uno service manager to create own needed uno resources. */
css::uno::Reference< css::lang::XMultiServiceFactory > m_xSMGR;
/** most active indicator child, which could work with our shared indicator window only. */
css::uno::Reference< css::task::XStatusIndicator > m_xActiveChild;
/** used to show the progress on the frame (layouted!) or
as a plugged vcl window. */
css::uno::Reference< css::task::XStatusIndicator > m_xProgress;
/** points to the frame, where we show the progress (in case
m_xProgress points to a frame progress. */
css::uno::WeakReference< css::frame::XFrame > m_xFrame;
/** points to an outside window, where we show the progress (in case
we are plugged into such window). */
css::uno::WeakReference< css::awt::XWindow > m_xPluggWindow;
/** Notify us if a fix time is over. We use it to implement an
intelligent "Reschedule" ... */
WakeUpThread* m_pWakeUp;
/** Our WakeUpThread calls us in our interface method "XUpdatable::update().
There we set this member m_bAllowReschedule to TRUE. Next time if our impl_reschedule()
method is called, we know, that an Application::Reschedule() should be made.
Because the last made Reschedule can be was taken long time ago ... may be.*/
sal_Bool m_bAllowReschedule;
/** enable/disable automatic showing of our parent window. */
sal_Bool m_bAllowParentShow;
/** enable/disable rescheduling. Default=enabled*/
sal_Bool m_bDisableReschedule;
/** prevent recursive calling of Application::Reschedule(). */
static sal_Int32 m_nInReschedule;
/** time where there last start call was made. */
sal_Int32 m_nStartTime;
//-------------------------------------------
// interface
public:
//---------------------------------------
// ctor
StatusIndicatorFactory(const css::uno::Reference< css::lang::XMultiServiceFactory >& xSMGR);
//---------------------------------------
// XInterface, XTypeProvider, XServiceInfo
DECLARE_XINTERFACE
DECLARE_XTYPEPROVIDER
DECLARE_XSERVICEINFO
//---------------------------------------
// XInitialization
virtual void SAL_CALL initialize(const css::uno::Sequence< css::uno::Any >& lArguments)
throw(css::uno::Exception ,
css::uno::RuntimeException);
//---------------------------------------
// XStatusIndicatorFactory
virtual css::uno::Reference< css::task::XStatusIndicator > SAL_CALL createStatusIndicator()
throw(css::uno::RuntimeException);
//---------------------------------------
// XUpdatable
virtual void SAL_CALL update()
throw(css::uno::RuntimeException);
//---------------------------------------
// similar (XStatusIndicator)
virtual void start(const css::uno::Reference< css::task::XStatusIndicator >& xChild,
const ::rtl::OUString& sText ,
sal_Int32 nRange);
virtual void SAL_CALL reset(const css::uno::Reference< css::task::XStatusIndicator >& xChild);
virtual void SAL_CALL end(const css::uno::Reference< css::task::XStatusIndicator >& xChild);
virtual void SAL_CALL setText(const css::uno::Reference< css::task::XStatusIndicator >& xChild,
const ::rtl::OUString& sText );
virtual void SAL_CALL setValue(const css::uno::Reference< css::task::XStatusIndicator >& xChild,
sal_Int32 nValue);
//-------------------------------------------
// specials
protected:
virtual ~StatusIndicatorFactory();
//-------------------------------------------
// helper
private:
/** @short show the parent window of this progress ...
if it's allowed to do so.
@descr By default we show the parent window automaticly
if this progress is used.
If that isn't a valid operation, the user of this
progress can suppress this feature by initializaing
us with a special parameter.
@seealso initialize()
*/
void implts_makeParentVisibleIfAllowed();
/** @short creates a new internal used progress.
@descr This factory does not paint the progress itself.
It uses helper for that. They can be vcl based or
layouted by the frame and provided as an uno interface.
*/
void impl_createProgress();
/** @short try to "share the current thread in an intelligent manner" :-)
@param Overwrites our algorithm for Reschedule and force it to be shure
that our progress was painted right.
*/
void impl_reschedule(sal_Bool bForceUpdate);
void impl_startWakeUpThread();
void impl_stopWakeUpThread();
}; // class StatusIndicatorFactory
} // namespace framework
#endif // #ifndef __FRAMEWORK_HELPER_STATUSINDICATORFACTORY_HXX_
<|endoftext|> |
<commit_before>/*************************************************************************
*
* $RCSfile: transactionmanager.hxx,v $
*
* $Revision: 1.6 $
*
* last change: $Author: as $ $Date: 2002-05-02 11:41:09 $
*
* The Contents of this file are made available subject to the terms of
* either of the following licenses
*
* - GNU Lesser General Public License Version 2.1
* - Sun Industry Standards Source License Version 1.1
*
* Sun Microsystems Inc., October, 2000
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2000 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
*
* Sun Industry Standards Source License Version 1.1
* =================================================
* The contents of this file are subject to the Sun Industry Standards
* Source License Version 1.1 (the "License"); You may not use this file
* except in compliance with the License. You may obtain a copy of the
* License at http://www.openoffice.org/license.html.
*
* Software provided under this License is provided on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
* WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
* MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
* See the License for the specific provisions governing your rights and
* obligations concerning the Software.
*
* The Initial Developer of the Original Code is: Sun Microsystems, Inc.
*
* Copyright: 2000 by Sun Microsystems, Inc.
*
* All Rights Reserved.
*
* Contributor(s): _______________________________________
*
*
************************************************************************/
#ifndef __FRAMEWORK_THREADHELP_TRANSACTIONMANAGER_HXX_
#define __FRAMEWORK_THREADHELP_TRANSACTIONMANAGER_HXX_
//_________________________________________________________________________________________________________________
// my own includes
//_________________________________________________________________________________________________________________
#ifndef __FRAMEWORK_THREADHELP_INONCOPYABLE_H_
#include <threadhelp/inoncopyable.h>
#endif
#ifndef __FRAMEWORK_THREADHELP_ITRANSACTIONMANAGER_H_
#include <threadhelp/itransactionmanager.h>
#endif
#ifndef __FRAMEWORK_THREADHELP_GATE_HXX_
#include <threadhelp/gate.hxx>
#endif
#ifndef __FRAMEWORK_MACROS_DEBUG_HXX_
#include <macros/debug.hxx>
#endif
//_________________________________________________________________________________________________________________
// interface includes
//_________________________________________________________________________________________________________________
#ifndef _COM_SUN_STAR_UNO_REFERENCE_HXX_
#include <com/sun/star/uno/Reference.hxx>
#endif
#ifndef _COM_SUN_STAR_UNO_XINTERFACE_HPP_
#include <com/sun/star/uno/XInterface.hpp>
#endif
#ifndef _COM_SUN_STAR_UNO_RUNTIMEEXCEPTION_HPP_
#include <com/sun/star/uno/RuntimeException.hpp>
#endif
#ifndef _COM_SUN_STAR_LANG_DISPOSEDEXCEPTION_HPP_
#include <com/sun/star/lang/DisposedException.hpp>
#endif
//_________________________________________________________________________________________________________________
// other includes
//_________________________________________________________________________________________________________________
#ifndef _OSL_MUTEX_HXX_
#include <osl/mutex.hxx>
#endif
//_________________________________________________________________________________________________________________
// namespace
//_________________________________________________________________________________________________________________
namespace framework{
//_________________________________________________________________________________________________________________
// const
//_________________________________________________________________________________________________________________
//_________________________________________________________________________________________________________________
// declarations
//_________________________________________________________________________________________________________________
/*-************************************************************************************************************//**
@short implement a transaction manager to support non breakable interface methods
@descr Use it to support non breakable interface methods without using any thread
synchronization like e.g. mutex, rw-lock!
That protect your code against wrong calls at wrong time ... e.g. calls after disposing an object!
Use combination of EExceptionMode and ERejectReason to detect rejected requests
and react for it. You can enable automaticly throwing of exceptions too.
@implements ITransactionManager
@base INonCopyable
ITransactionManager
@devstatus draft
*//*-*************************************************************************************************************/
class TransactionManager : public ITransactionManager
, private INonCopyable
{
//-------------------------------------------------------------------------------------------------------------
// public methods
//-------------------------------------------------------------------------------------------------------------
public:
TransactionManager ( );
virtual void setWorkingMode ( EWorkingMode eMode );
virtual EWorkingMode getWorkingMode ( ) const;
virtual sal_Bool isCallRejected ( ERejectReason& eReason ) const;
virtual void registerTransaction ( EExceptionMode eMode, ERejectReason& eReason ) throw( css::uno::RuntimeException, css::lang::DisposedException );
virtual void unregisterTransaction ( ) throw( css::uno::RuntimeException, css::lang::DisposedException );
static TransactionManager& getGlobalTransactionManager ( );
//-------------------------------------------------------------------------------------------------------------
// private methods
//-------------------------------------------------------------------------------------------------------------
private:
void impl_throwExceptions( EExceptionMode eMode, ERejectReason eReason ) const throw( css::uno::RuntimeException, css::lang::DisposedException );
//-------------------------------------------------------------------------------------------------------------
// private member
//-------------------------------------------------------------------------------------------------------------
private:
mutable ::osl::Mutex m_aAccessLock ; /// regulate access on internal member of this instance
Gate m_aBarrier ; /// used to block transactions requests during change or work mode
EWorkingMode m_eWorkingMode ; /// current working mode of object which use this manager (used to reject calls at wrong time)
sal_Int32 m_nTransactionCount ; /// every transaction request is registered by this counter
}; // class TransactionManager
} // namespace framework
#endif // #ifndef __FRAMEWORK_THREADHELP_TRANSACTIONMANAGER_HXX_
<commit_msg>INTEGRATION: CWS ooo19126 (1.6.562); FILE MERGED 2005/09/05 13:05:26 rt 1.6.562.1: #i54170# Change license header: remove SISSL<commit_after>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: transactionmanager.hxx,v $
*
* $Revision: 1.7 $
*
* last change: $Author: rt $ $Date: 2005-09-09 00:38:41 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
#ifndef __FRAMEWORK_THREADHELP_TRANSACTIONMANAGER_HXX_
#define __FRAMEWORK_THREADHELP_TRANSACTIONMANAGER_HXX_
//_________________________________________________________________________________________________________________
// my own includes
//_________________________________________________________________________________________________________________
#ifndef __FRAMEWORK_THREADHELP_INONCOPYABLE_H_
#include <threadhelp/inoncopyable.h>
#endif
#ifndef __FRAMEWORK_THREADHELP_ITRANSACTIONMANAGER_H_
#include <threadhelp/itransactionmanager.h>
#endif
#ifndef __FRAMEWORK_THREADHELP_GATE_HXX_
#include <threadhelp/gate.hxx>
#endif
#ifndef __FRAMEWORK_MACROS_DEBUG_HXX_
#include <macros/debug.hxx>
#endif
//_________________________________________________________________________________________________________________
// interface includes
//_________________________________________________________________________________________________________________
#ifndef _COM_SUN_STAR_UNO_REFERENCE_HXX_
#include <com/sun/star/uno/Reference.hxx>
#endif
#ifndef _COM_SUN_STAR_UNO_XINTERFACE_HPP_
#include <com/sun/star/uno/XInterface.hpp>
#endif
#ifndef _COM_SUN_STAR_UNO_RUNTIMEEXCEPTION_HPP_
#include <com/sun/star/uno/RuntimeException.hpp>
#endif
#ifndef _COM_SUN_STAR_LANG_DISPOSEDEXCEPTION_HPP_
#include <com/sun/star/lang/DisposedException.hpp>
#endif
//_________________________________________________________________________________________________________________
// other includes
//_________________________________________________________________________________________________________________
#ifndef _OSL_MUTEX_HXX_
#include <osl/mutex.hxx>
#endif
//_________________________________________________________________________________________________________________
// namespace
//_________________________________________________________________________________________________________________
namespace framework{
//_________________________________________________________________________________________________________________
// const
//_________________________________________________________________________________________________________________
//_________________________________________________________________________________________________________________
// declarations
//_________________________________________________________________________________________________________________
/*-************************************************************************************************************//**
@short implement a transaction manager to support non breakable interface methods
@descr Use it to support non breakable interface methods without using any thread
synchronization like e.g. mutex, rw-lock!
That protect your code against wrong calls at wrong time ... e.g. calls after disposing an object!
Use combination of EExceptionMode and ERejectReason to detect rejected requests
and react for it. You can enable automaticly throwing of exceptions too.
@implements ITransactionManager
@base INonCopyable
ITransactionManager
@devstatus draft
*//*-*************************************************************************************************************/
class TransactionManager : public ITransactionManager
, private INonCopyable
{
//-------------------------------------------------------------------------------------------------------------
// public methods
//-------------------------------------------------------------------------------------------------------------
public:
TransactionManager ( );
virtual void setWorkingMode ( EWorkingMode eMode );
virtual EWorkingMode getWorkingMode ( ) const;
virtual sal_Bool isCallRejected ( ERejectReason& eReason ) const;
virtual void registerTransaction ( EExceptionMode eMode, ERejectReason& eReason ) throw( css::uno::RuntimeException, css::lang::DisposedException );
virtual void unregisterTransaction ( ) throw( css::uno::RuntimeException, css::lang::DisposedException );
static TransactionManager& getGlobalTransactionManager ( );
//-------------------------------------------------------------------------------------------------------------
// private methods
//-------------------------------------------------------------------------------------------------------------
private:
void impl_throwExceptions( EExceptionMode eMode, ERejectReason eReason ) const throw( css::uno::RuntimeException, css::lang::DisposedException );
//-------------------------------------------------------------------------------------------------------------
// private member
//-------------------------------------------------------------------------------------------------------------
private:
mutable ::osl::Mutex m_aAccessLock ; /// regulate access on internal member of this instance
Gate m_aBarrier ; /// used to block transactions requests during change or work mode
EWorkingMode m_eWorkingMode ; /// current working mode of object which use this manager (used to reject calls at wrong time)
sal_Int32 m_nTransactionCount ; /// every transaction request is registered by this counter
}; // class TransactionManager
} // namespace framework
#endif // #ifndef __FRAMEWORK_THREADHELP_TRANSACTIONMANAGER_HXX_
<|endoftext|> |
<commit_before>/*
Copyright (c) 2013 Microsoft Corporation. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Author: Leonardo de Moura
*/
#include <utility>
#include <string>
#include "util/script_exception.h"
#include "util/name_set.h"
#include "kernel/kernel_exception.h"
#include "kernel/for_each_fn.h"
#include "library/io_state_stream.h"
#include "library/unifier.h"
#include "library/parser_nested_exception.h"
#include "library/error_handling/error_handling.h"
namespace lean {
flycheck_scope::flycheck_scope(io_state_stream const & ios, char const * kind):
m_ios(ios),
m_flycheck(m_ios.get_options().get_bool("flycheck", false)) {
if (m_flycheck) m_ios << "FLYCHECK_BEGIN " << kind << endl;
}
flycheck_scope::~flycheck_scope() {
if (m_flycheck) m_ios << "FLYCHECK_END" << endl;
}
flyinfo_scope::flyinfo_scope(io_state_stream const & ios):
m_ios(ios),
m_flyinfo(m_ios.get_options().get_bool("flyinfo", false)) {
if (m_flyinfo) m_ios << "FLYCHECK_BEGIN INFO" << endl;
}
flyinfo_scope::~flyinfo_scope() {
if (m_flyinfo) m_ios << "FLYCHECK_END" << endl;
}
void display_pos(io_state_stream const & ios, char const * strm_name, unsigned line, unsigned pos) {
ios << strm_name << ":";
if (line != static_cast<unsigned>(-1))
ios << line << ":";
if (pos != static_cast<unsigned>(-1))
ios << pos << ":";
}
void display_error_pos(io_state_stream const & ios, char const * strm_name, unsigned line, unsigned pos) {
display_pos(ios, strm_name, line, pos);
ios << " error:";
}
void display_warning_pos(io_state_stream const & ios, char const * strm_name, unsigned line, unsigned pos) {
display_pos(ios, strm_name, line, pos);
ios << " warning:";
}
void display_error_pos(io_state_stream const & ios, pos_info_provider const * p, expr const & e) {
if (p) {
auto pos = p->get_pos_info_or_some(e);
display_error_pos(ios, p->get_file_name(), pos.first, pos.second);
} else {
ios << "error:";
}
}
void display_error_pos(io_state_stream const & ios, pos_info_provider const * p, optional<expr> const & e) {
if (e) {
display_error_pos(ios, p, *e);
} else if (p) {
auto pos = p->get_some_pos();
display_error_pos(ios, p->get_file_name(), pos.first, pos.second);
} else {
ios << "error:";
}
}
void display_error(io_state_stream const & ios, pos_info_provider const * p, exception const & ex);
static void display_error(io_state_stream const & ios, pos_info_provider const * p, kernel_exception const & ex) {
display_error_pos(ios, p, ex.get_main_expr());
ios << " " << ex << endl;
}
static void display_error(io_state_stream const & ios, pos_info_provider const * p, unifier_exception const & ex) {
formatter fmt = ios.get_formatter();
options opts = ios.get_options();
auto j = ex.get_justification();
display_error_pos(ios, p, j.get_main_expr());
ios << " " << mk_pair(j.pp(fmt, p, ex.get_substitution()), opts) << endl;
}
static void display_error(io_state_stream const & ios, pos_info_provider const * p, script_exception const & ex) {
if (p) {
char const * msg = ex.get_msg();
char const * space = msg && *msg == ' ' ? "" : " ";
switch (ex.get_source()) {
case script_exception::source::String:
display_error_pos(ios, p->get_file_name(), ex.get_line() + p->get_some_pos().first - 1, static_cast<unsigned>(-1));
ios << " executing script," << space << msg << endl;
break;
case script_exception::source::File:
display_error_pos(ios, p->get_file_name(), p->get_some_pos().first, p->get_some_pos().second);
ios << " executing external script (" << ex.get_file_name() << ":" << ex.get_line() << ")," << space << msg << endl;
break;
case script_exception::source::Unknown:
display_error_pos(ios, p->get_file_name(), p->get_some_pos().first, p->get_some_pos().second);
ios << " executing script, exact error position is not available, " << ex.what() << endl;
break;
}
} else {
ios << ex.what() << endl;
}
}
static void display_error(io_state_stream const & ios, pos_info_provider const * p, script_nested_exception const & ex) {
switch (ex.get_source()) {
case script_exception::source::String:
if (p) {
display_error_pos(ios, p->get_file_name(), ex.get_line() + p->get_some_pos().first - 1, static_cast<unsigned>(-1));
ios << " executing script" << endl;
}
display_error(ios, nullptr, ex.get_exception());
break;
case script_exception::source::File:
if (p) {
display_error_pos(ios, p->get_file_name(), p->get_some_pos().first, p->get_some_pos().second);
ios << " executing external script (" << ex.get_file_name() << ":" << ex.get_line() << ")" << endl;
} else {
display_error_pos(ios, ex.get_file_name(), ex.get_line(), -1);
ios << " executing script" << endl;
}
display_error(ios, nullptr, ex.get_exception());
break;
case script_exception::source::Unknown:
display_error(ios, nullptr, ex.get_exception());
break;
}
}
// static void display_error(io_state_stream const & ios, pos_info_provider const *, parser_nested_exception const & ex) {
// display_error(ios, &(ex.get_provider()), ex.get_exception());
// }
// static void display_error(io_state_stream const & ios, pos_info_provider const *, parser_exception const & ex) {
// ios << ex.what() << endl;
// }
void display_error(io_state_stream const & ios, pos_info_provider const * p, exception const & ex) {
flycheck_error err(ios);
if (auto k_ex = dynamic_cast<kernel_exception const *>(&ex)) {
display_error(ios, p, *k_ex);
} else if (auto e_ex = dynamic_cast<unifier_exception const *>(&ex)) {
display_error(ios, p, *e_ex);
} else if (auto ls_ex = dynamic_cast<script_nested_exception const *>(&ex)) {
display_error(ios, p, *ls_ex);
} else if (auto s_ex = dynamic_cast<script_exception const *>(&ex)) {
display_error(ios, p, *s_ex);
// } else if (auto n_ex = dynamic_cast<parser_nested_exception const *>(&ex)) {
// display_error(ios, p, *n_ex);
// } else if (auto n_ex = dynamic_cast<parser_exception const *>(&ex)) {
// display_error(ios, p, *n_ex);
} else if (p) {
display_error_pos(ios, p->get_file_name(), p->get_some_pos().first, p->get_some_pos().second);
ios << " " << ex.what() << endl;
} else {
ios << "error: " << ex.what() << endl;
}
}
}
<commit_msg>feat(library/error_handling): generate valid line and column information when in flycheck mode<commit_after>/*
Copyright (c) 2013 Microsoft Corporation. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Author: Leonardo de Moura
*/
#include <utility>
#include <string>
#include "util/script_exception.h"
#include "util/name_set.h"
#include "kernel/kernel_exception.h"
#include "kernel/for_each_fn.h"
#include "library/io_state_stream.h"
#include "library/unifier.h"
#include "library/parser_nested_exception.h"
#include "library/error_handling/error_handling.h"
namespace lean {
flycheck_scope::flycheck_scope(io_state_stream const & ios, char const * kind):
m_ios(ios),
m_flycheck(m_ios.get_options().get_bool("flycheck", false)) {
if (m_flycheck) m_ios << "FLYCHECK_BEGIN " << kind << endl;
}
flycheck_scope::~flycheck_scope() {
if (m_flycheck) m_ios << "FLYCHECK_END" << endl;
}
flyinfo_scope::flyinfo_scope(io_state_stream const & ios):
m_ios(ios),
m_flyinfo(m_ios.get_options().get_bool("flyinfo", false)) {
if (m_flyinfo) m_ios << "FLYCHECK_BEGIN INFO" << endl;
}
flyinfo_scope::~flyinfo_scope() {
if (m_flyinfo) m_ios << "FLYCHECK_END" << endl;
}
void display_pos(io_state_stream const & ios, char const * strm_name, unsigned line, unsigned pos) {
ios << strm_name << ":";
if (ios.get_options().get_bool("flycheck", false)) {
// generate valid line and column for flycheck mode
if (line == static_cast<unsigned>(-1))
line = 1;
if (pos == static_cast<unsigned>(-1))
pos = 0;
}
if (line != static_cast<unsigned>(-1))
ios << line << ":";
if (pos != static_cast<unsigned>(-1))
ios << pos << ":";
}
void display_error_pos(io_state_stream const & ios, char const * strm_name, unsigned line, unsigned pos) {
display_pos(ios, strm_name, line, pos);
ios << " error:";
}
void display_warning_pos(io_state_stream const & ios, char const * strm_name, unsigned line, unsigned pos) {
display_pos(ios, strm_name, line, pos);
ios << " warning:";
}
void display_error_pos(io_state_stream const & ios, pos_info_provider const * p, expr const & e) {
if (p) {
auto pos = p->get_pos_info_or_some(e);
display_error_pos(ios, p->get_file_name(), pos.first, pos.second);
} else {
ios << "error:";
}
}
void display_error_pos(io_state_stream const & ios, pos_info_provider const * p, optional<expr> const & e) {
if (e) {
display_error_pos(ios, p, *e);
} else if (p) {
auto pos = p->get_some_pos();
display_error_pos(ios, p->get_file_name(), pos.first, pos.second);
} else {
ios << "error:";
}
}
void display_error(io_state_stream const & ios, pos_info_provider const * p, exception const & ex);
static void display_error(io_state_stream const & ios, pos_info_provider const * p, kernel_exception const & ex) {
display_error_pos(ios, p, ex.get_main_expr());
ios << " " << ex << endl;
}
static void display_error(io_state_stream const & ios, pos_info_provider const * p, unifier_exception const & ex) {
formatter fmt = ios.get_formatter();
options opts = ios.get_options();
auto j = ex.get_justification();
display_error_pos(ios, p, j.get_main_expr());
ios << " " << mk_pair(j.pp(fmt, p, ex.get_substitution()), opts) << endl;
}
static void display_error(io_state_stream const & ios, pos_info_provider const * p, script_exception const & ex) {
if (p) {
char const * msg = ex.get_msg();
char const * space = msg && *msg == ' ' ? "" : " ";
switch (ex.get_source()) {
case script_exception::source::String:
display_error_pos(ios, p->get_file_name(), ex.get_line() + p->get_some_pos().first - 1, static_cast<unsigned>(-1));
ios << " executing script," << space << msg << endl;
break;
case script_exception::source::File:
display_error_pos(ios, p->get_file_name(), p->get_some_pos().first, p->get_some_pos().second);
ios << " executing external script (" << ex.get_file_name() << ":" << ex.get_line() << ")," << space << msg << endl;
break;
case script_exception::source::Unknown:
display_error_pos(ios, p->get_file_name(), p->get_some_pos().first, p->get_some_pos().second);
ios << " executing script, exact error position is not available, " << ex.what() << endl;
break;
}
} else {
ios << ex.what() << endl;
}
}
static void display_error(io_state_stream const & ios, pos_info_provider const * p, script_nested_exception const & ex) {
switch (ex.get_source()) {
case script_exception::source::String:
if (p) {
display_error_pos(ios, p->get_file_name(), ex.get_line() + p->get_some_pos().first - 1, static_cast<unsigned>(-1));
ios << " executing script" << endl;
}
display_error(ios, nullptr, ex.get_exception());
break;
case script_exception::source::File:
if (p) {
display_error_pos(ios, p->get_file_name(), p->get_some_pos().first, p->get_some_pos().second);
ios << " executing external script (" << ex.get_file_name() << ":" << ex.get_line() << ")" << endl;
} else {
display_error_pos(ios, ex.get_file_name(), ex.get_line(), -1);
ios << " executing script" << endl;
}
display_error(ios, nullptr, ex.get_exception());
break;
case script_exception::source::Unknown:
display_error(ios, nullptr, ex.get_exception());
break;
}
}
// static void display_error(io_state_stream const & ios, pos_info_provider const *, parser_nested_exception const & ex) {
// display_error(ios, &(ex.get_provider()), ex.get_exception());
// }
// static void display_error(io_state_stream const & ios, pos_info_provider const *, parser_exception const & ex) {
// ios << ex.what() << endl;
// }
void display_error(io_state_stream const & ios, pos_info_provider const * p, exception const & ex) {
flycheck_error err(ios);
if (auto k_ex = dynamic_cast<kernel_exception const *>(&ex)) {
display_error(ios, p, *k_ex);
} else if (auto e_ex = dynamic_cast<unifier_exception const *>(&ex)) {
display_error(ios, p, *e_ex);
} else if (auto ls_ex = dynamic_cast<script_nested_exception const *>(&ex)) {
display_error(ios, p, *ls_ex);
} else if (auto s_ex = dynamic_cast<script_exception const *>(&ex)) {
display_error(ios, p, *s_ex);
// } else if (auto n_ex = dynamic_cast<parser_nested_exception const *>(&ex)) {
// display_error(ios, p, *n_ex);
// } else if (auto n_ex = dynamic_cast<parser_exception const *>(&ex)) {
// display_error(ios, p, *n_ex);
} else if (p) {
display_error_pos(ios, p->get_file_name(), p->get_some_pos().first, p->get_some_pos().second);
ios << " " << ex.what() << endl;
} else {
ios << "error: " << ex.what() << endl;
}
}
}
<|endoftext|> |
<commit_before>// Copyright (c) 2011-2014, 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.
#define __STDC_LIMIT_MACROS
// STL
#include <stdexcept>
// Google Log
#include <glog/logging.h>
// po6
#include <po6/net/ipaddr.h>
#include <po6/net/hostname.h>
// e
#include <e/popt.h>
// BusyBee
#include <busybee_utils.h>
// HyperDex
#include "daemon/daemon.h"
int
main(int argc, const char* argv[])
{
bool daemonize = true;
const char* data = ".";
const char* log = NULL;
const char* pidfile = "";
bool has_pidfile = false;
bool listen = false;
const char* listen_host = "auto";
long listen_port = 2012;
bool coordinator = false;
const char* coordinator_host = "127.0.0.1";
long coordinator_port = 1982;
long threads = 0;
bool log_immediate = false;
e::argparser ap;
ap.autohelp();
ap.arg().name('d', "daemon")
.description("run in the background")
.set_true(&daemonize);
ap.arg().name('f', "foreground")
.description("run in the foreground")
.set_false(&daemonize);
ap.arg().name('D', "data")
.description("store persistent state in this directory (default: .)")
.metavar("dir").as_string(&data);
ap.arg().name('L', "log")
.description("store logs in this directory (default: --data)")
.metavar("dir").as_string(&log);
ap.arg().long_name("pidfile")
.description("write the PID to a file (default: don't)")
.metavar("file").as_string(&pidfile).set_true(&has_pidfile);
ap.arg().name('l', "listen")
.description("listen on a specific IP address (default: auto)")
.metavar("IP").as_string(&listen_host).set_true(&listen);
ap.arg().name('p', "listen-port")
.description("listen on an alternative port (default: 1982)")
.metavar("port").as_long(&listen_port).set_true(&listen);
ap.arg().name('c', "coordinator")
.description("join an existing HyperDex cluster through IP address or hostname")
.metavar("addr").as_string(&coordinator_host).set_true(&coordinator);
ap.arg().name('P', "coordinator-port")
.description("connect to an alternative port on the coordinator (default: 1982)")
.metavar("port").as_long(&coordinator_port).set_true(&coordinator);
ap.arg().name('t', "threads")
.description("the number of threads which will handle network traffic")
.metavar("N").as_long(&threads);
ap.arg().long_name("log-immediate")
.description("immediately flush all log output")
.set_true(&log_immediate).hidden();
if (!ap.parse(argc, argv))
{
return EXIT_FAILURE;
}
if (ap.args_sz() != 0)
{
std::cerr << "command takes no positional arguments\n" << std::endl;
ap.usage();
return EXIT_FAILURE;
}
if (listen_port >= (1 << 16))
{
std::cerr << "listen-port is out of range" << std::endl;
return EXIT_FAILURE;
}
if (coordinator_port >= (1 << 16))
{
std::cerr << "coordinator-port is out of range" << std::endl;
return EXIT_FAILURE;
}
po6::net::ipaddr listen_ip;
po6::net::location bind_to;
if (strcmp(listen_host, "auto") == 0)
{
if (!busybee_discover(&listen_ip))
{
std::cerr << "cannot automatically discover local address; specify one manually" << std::endl;
return EXIT_FAILURE;
}
bind_to = po6::net::location(listen_ip, listen_port);
}
else
{
try
{
listen_ip = po6::net::ipaddr(listen_host);
bind_to = po6::net::location(listen_ip, listen_port);
}
catch (std::invalid_argument& e)
{
// fallthrough
}
if (bind_to == po6::net::location())
{
bind_to = po6::net::hostname(listen_host, 0).lookup(AF_UNSPEC, IPPROTO_TCP);
bind_to.port = listen_port;
}
}
if (bind_to == po6::net::location())
{
std::cerr << "cannot interpret listen address as hostname or IP address" << std::endl;
return EXIT_FAILURE;
}
if (bind_to.address == po6::net::ipaddr("0.0.0.0"))
{
std::cerr << "cannot bind to " << bind_to << " because it is not routable" << std::endl;
return EXIT_FAILURE;
}
google::InitGoogleLogging(argv[0]);
google::InstallFailureSignalHandler();
if (log_immediate)
{
FLAGS_logbufsecs = 0;
}
try
{
hyperdex::daemon d;
if (threads <= 0)
{
threads += sysconf(_SC_NPROCESSORS_ONLN);
if (threads <= 0)
{
std::cerr << "cannot create a non-positive number of threads" << std::endl;
return EXIT_FAILURE;
}
}
else if (threads > 512)
{
std::cerr << "refusing to create more than 512 threads" << std::endl;
return EXIT_FAILURE;
}
return d.run(daemonize,
std::string(data),
std::string(log ? log : data),
std::string(pidfile), has_pidfile,
listen, bind_to,
coordinator, po6::net::hostname(coordinator_host, coordinator_port),
threads);
}
catch (std::exception& e)
{
std::cerr << "error: " << e.what() << std::endl;
return EXIT_FAILURE;
}
}
<commit_msg>UPdate deps<commit_after>// Copyright (c) 2011-2014, 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.
#define __STDC_LIMIT_MACROS
// STL
#include <stdexcept>
// Google Log
#include <glog/logging.h>
// po6
#include <po6/net/ipaddr.h>
#include <po6/net/hostname.h>
// e
#include <e/popt.h>
// BusyBee
#include <busybee_utils.h>
// HyperDex
#include "daemon/daemon.h"
int
main(int argc, const char* argv[])
{
bool daemonize = true;
const char* data = ".";
const char* log = NULL;
const char* pidfile = "";
bool has_pidfile = false;
bool listen = false;
const char* listen_host = "auto";
long listen_port = 2012;
bool coordinator = false;
const char* coordinator_host = "127.0.0.1";
long coordinator_port = 1982;
long threads = 0;
bool log_immediate = false;
e::argparser ap;
ap.autohelp();
ap.arg().name('d', "daemon")
.description("run in the background")
.set_true(&daemonize);
ap.arg().name('f', "foreground")
.description("run in the foreground")
.set_false(&daemonize);
ap.arg().name('D', "data")
.description("store persistent state in this directory (default: .)")
.metavar("dir").as_string(&data);
ap.arg().name('L', "log")
.description("store logs in this directory (default: --data)")
.metavar("dir").as_string(&log);
ap.arg().long_name("pidfile")
.description("write the PID to a file (default: don't)")
.metavar("file").as_string(&pidfile).set_true(&has_pidfile);
ap.arg().name('l', "listen")
.description("listen on a specific IP address (default: auto)")
.metavar("IP").as_string(&listen_host).set_true(&listen);
ap.arg().name('p', "listen-port")
.description("listen on an alternative port (default: 1982)")
.metavar("port").as_long(&listen_port).set_true(&listen);
ap.arg().name('c', "coordinator")
.description("join an existing HyperDex cluster through IP address or hostname")
.metavar("addr").as_string(&coordinator_host).set_true(&coordinator);
ap.arg().name('P', "coordinator-port")
.description("connect to an alternative port on the coordinator (default: 1982)")
.metavar("port").as_long(&coordinator_port).set_true(&coordinator);
ap.arg().name('t', "threads")
.description("the number of threads which will handle network traffic")
.metavar("N").as_long(&threads);
ap.arg().long_name("log-immediate")
.description("immediately flush all log output")
.set_true(&log_immediate).hidden();
if (!ap.parse(argc, argv))
{
return EXIT_FAILURE;
}
if (ap.args_sz() != 0)
{
std::cerr << "command takes no positional arguments\n" << std::endl;
ap.usage();
return EXIT_FAILURE;
}
if (listen_port >= (1 << 16))
{
std::cerr << "listen-port is out of range" << std::endl;
return EXIT_FAILURE;
}
if (coordinator_port >= (1 << 16))
{
std::cerr << "coordinator-port is out of range" << std::endl;
return EXIT_FAILURE;
}
po6::net::ipaddr listen_ip;
po6::net::location bind_to;
if (strcmp(listen_host, "auto") == 0)
{
if (!busybee_discover(&listen_ip))
{
std::cerr << "cannot automatically discover local address; specify one manually" << std::endl;
return EXIT_FAILURE;
}
bind_to = po6::net::location(listen_ip, listen_port);
}
else
{
if (listen_ip.set(listen_host))
{
bind_to = po6::net::location(listen_ip, listen_port);
}
if (bind_to == po6::net::location())
{
bind_to = po6::net::hostname(listen_host, 0).lookup(AF_UNSPEC, IPPROTO_TCP);
bind_to.port = listen_port;
}
}
if (bind_to == po6::net::location())
{
std::cerr << "cannot interpret listen address as hostname or IP address" << std::endl;
return EXIT_FAILURE;
}
if (bind_to.address == po6::net::ipaddr::ANY())
{
std::cerr << "cannot bind to " << bind_to << " because it is not routable" << std::endl;
return EXIT_FAILURE;
}
google::InitGoogleLogging(argv[0]);
google::InstallFailureSignalHandler();
if (log_immediate)
{
FLAGS_logbufsecs = 0;
}
try
{
hyperdex::daemon d;
if (threads <= 0)
{
threads += sysconf(_SC_NPROCESSORS_ONLN);
if (threads <= 0)
{
std::cerr << "cannot create a non-positive number of threads" << std::endl;
return EXIT_FAILURE;
}
}
else if (threads > 512)
{
std::cerr << "refusing to create more than 512 threads" << std::endl;
return EXIT_FAILURE;
}
return d.run(daemonize,
std::string(data),
std::string(log ? log : data),
std::string(pidfile), has_pidfile,
listen, bind_to,
coordinator, po6::net::hostname(coordinator_host, coordinator_port),
threads);
}
catch (std::exception& e)
{
std::cerr << "error: " << e.what() << std::endl;
return EXIT_FAILURE;
}
}
<|endoftext|> |
<commit_before>/*
* yosys -- Yosys Open SYnthesis Suite
*
* Copyright (C) 2012 Clifford Wolf <clifford@clifford.at>
*
* Permission to use, copy, modify, and/or distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
* ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
* ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
* OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*
*/
#include "kernel/yosys.h"
#include "kernel/sigtools.h"
#include <stdlib.h>
#include <stdio.h>
USING_YOSYS_NAMESPACE
PRIVATE_NAMESPACE_BEGIN
static SigBit get_bit_or_zero(const SigSpec &sig)
{
if (GetSize(sig) == 0)
return State::S0;
return sig[0];
}
static void run_ice40_unlut(Module *module)
{
SigMap sigmap(module);
for (auto cell : module->selected_cells())
{
if (cell->type == "\\SB_LUT4")
{
SigSpec inbits;
inbits.append(get_bit_or_zero(cell->getPort("\\I0")));
inbits.append(get_bit_or_zero(cell->getPort("\\I1")));
inbits.append(get_bit_or_zero(cell->getPort("\\I2")));
inbits.append(get_bit_or_zero(cell->getPort("\\I3")));
sigmap.apply(inbits);
log("Mapping SB_LUT4 cell %s.%s to $lut.\n", log_id(module), log_id(cell));
cell->type ="$lut";
cell->setParam("\\WIDTH", 4);
cell->setParam("\\LUT", cell->getParam("\\LUT_INIT"));
cell->unsetParam("\\LUT_INIT");
cell->setPort("\\A", SigSpec({
get_bit_or_zero(cell->getPort("\\I3")),
get_bit_or_zero(cell->getPort("\\I2")),
get_bit_or_zero(cell->getPort("\\I1")),
get_bit_or_zero(cell->getPort("\\I0"))
}));
cell->setPort("\\Y", cell->getPort("\\O")[0]);
cell->unsetPort("\\I0");
cell->unsetPort("\\I1");
cell->unsetPort("\\I2");
cell->unsetPort("\\I3");
cell->unsetPort("\\O");
cell->check();
}
}
}
struct Ice40UnlutPass : public Pass {
Ice40UnlutPass() : Pass("ice40_unlut", "iCE40: transform SBLUT4 cells to $lut cells") { }
void help() YS_OVERRIDE
{
// |---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|
log("\n");
log(" ice40_unlut [options] [selection]\n");
log("\n");
log("This command transforms all SB_LUT4 cells to generic $lut cells.\n");
log("\n");
}
void execute(std::vector<std::string> args, RTLIL::Design *design) YS_OVERRIDE
{
log_header(design, "Executing ICE40_UNLUT pass (convert SB_LUT4 to $lut).\n");
log_push();
size_t argidx;
for (argidx = 1; argidx < args.size(); argidx++) {
// if (args[argidx] == "-???") {
// continue;
// }
break;
}
extra_args(args, argidx, design);
for (auto module : design->selected_modules())
run_ice40_unlut(module);
}
} Ice40UnlutPass;
PRIVATE_NAMESPACE_END
<commit_msg>Fixed small typo in ice40_unlut help summary<commit_after>/*
* yosys -- Yosys Open SYnthesis Suite
*
* Copyright (C) 2012 Clifford Wolf <clifford@clifford.at>
*
* Permission to use, copy, modify, and/or distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
* ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
* ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
* OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*
*/
#include "kernel/yosys.h"
#include "kernel/sigtools.h"
#include <stdlib.h>
#include <stdio.h>
USING_YOSYS_NAMESPACE
PRIVATE_NAMESPACE_BEGIN
static SigBit get_bit_or_zero(const SigSpec &sig)
{
if (GetSize(sig) == 0)
return State::S0;
return sig[0];
}
static void run_ice40_unlut(Module *module)
{
SigMap sigmap(module);
for (auto cell : module->selected_cells())
{
if (cell->type == "\\SB_LUT4")
{
SigSpec inbits;
inbits.append(get_bit_or_zero(cell->getPort("\\I0")));
inbits.append(get_bit_or_zero(cell->getPort("\\I1")));
inbits.append(get_bit_or_zero(cell->getPort("\\I2")));
inbits.append(get_bit_or_zero(cell->getPort("\\I3")));
sigmap.apply(inbits);
log("Mapping SB_LUT4 cell %s.%s to $lut.\n", log_id(module), log_id(cell));
cell->type ="$lut";
cell->setParam("\\WIDTH", 4);
cell->setParam("\\LUT", cell->getParam("\\LUT_INIT"));
cell->unsetParam("\\LUT_INIT");
cell->setPort("\\A", SigSpec({
get_bit_or_zero(cell->getPort("\\I3")),
get_bit_or_zero(cell->getPort("\\I2")),
get_bit_or_zero(cell->getPort("\\I1")),
get_bit_or_zero(cell->getPort("\\I0"))
}));
cell->setPort("\\Y", cell->getPort("\\O")[0]);
cell->unsetPort("\\I0");
cell->unsetPort("\\I1");
cell->unsetPort("\\I2");
cell->unsetPort("\\I3");
cell->unsetPort("\\O");
cell->check();
}
}
}
struct Ice40UnlutPass : public Pass {
Ice40UnlutPass() : Pass("ice40_unlut", "iCE40: transform SB_LUT4 cells to $lut cells") { }
void help() YS_OVERRIDE
{
// |---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|
log("\n");
log(" ice40_unlut [options] [selection]\n");
log("\n");
log("This command transforms all SB_LUT4 cells to generic $lut cells.\n");
log("\n");
}
void execute(std::vector<std::string> args, RTLIL::Design *design) YS_OVERRIDE
{
log_header(design, "Executing ICE40_UNLUT pass (convert SB_LUT4 to $lut).\n");
log_push();
size_t argidx;
for (argidx = 1; argidx < args.size(); argidx++) {
// if (args[argidx] == "-???") {
// continue;
// }
break;
}
extra_args(args, argidx, design);
for (auto module : design->selected_modules())
run_ice40_unlut(module);
}
} Ice40UnlutPass;
PRIVATE_NAMESPACE_END
<|endoftext|> |
<commit_before>// Copyright (C) 2012-2017 Leap Motion, Inc. All rights reserved.
#include "stdafx.h"
#include "IPCTestUtils.h"
#include <leapipc/CircularBufferEndpoint.h>
#include <autowiring/autowiring.h>
#include <autowiring/CoreThread.h>
#include <cstdio>
#include <thread>
#include <gtest/gtest.h>
using namespace leap::ipc;
class CircularBufferEndpointTest :
public testing::Test
{};
TEST_F(CircularBufferEndpointTest, WriteReadSequence)
{
auto cbuf = std::make_shared<CircularBufferEndpoint>(32);
// read from buffer in separate thread
std::thread reader([cbuf] {
char t[16];
cbuf->ReadRaw(t, 4);
ASSERT_EQ(strncmp(t, "abcd", 4), 0);
cbuf->ReadRaw(t, 8);
ASSERT_EQ(strncmp(t, "efghijkl", 8), 0);
cbuf->ReadRaw(t, 16);
ASSERT_EQ(strncmp(t, "mnopqr0123456789", 16), 0);
cbuf->ReadRaw(t, 6);
ASSERT_EQ(strncmp(t, "987654", 6), 0);
cbuf->ReadRaw(t, 4);
ASSERT_EQ(strncmp(t, "3210", 4), 0);
cbuf->ReadRaw(t, 4);
ASSERT_EQ(strncmp(t, "abcd", 4), 0);
cbuf->ReadRaw(t, 8);
ASSERT_EQ(strncmp(t, "efghijkl", 8), 0);
cbuf->ReadRaw(t, 16);
ASSERT_EQ(strncmp(t, "mnopqr0123456789", 16), 0);
cbuf->ReadRaw(t, 6);
ASSERT_EQ(strncmp(t, "987654", 6), 0);
cbuf->ReadRaw(t, 4);
ASSERT_EQ(strncmp(t, "3210", 4), 0);
});
// write to buffer
cbuf->WriteRaw("abcdef", 6);
cbuf->WriteRaw("ghijkl", 6);
cbuf->WriteRaw("mnopqr", 6);
cbuf->WriteRaw("01234567899876543210", 20);
cbuf->WriteRaw("abcdef", 6);
cbuf->WriteRaw("ghijkl", 6);
cbuf->WriteRaw("mnopqr", 6);
cbuf->WriteRaw("01234567899876543210", 20);
reader.join();
}
TEST_F(CircularBufferEndpointTest, DoubleSize)
{
auto cbuf = std::make_shared<CircularBufferEndpoint>(16);
// read from buffer in separate thread
std::thread reader([cbuf] {
char t[16];
cbuf->ReadRaw(t, 4);
ASSERT_EQ(strncmp(t, "abcd", 4), 0);
cbuf->ReadRaw(t, 8);
ASSERT_EQ(strncmp(t, "efghijkl", 8), 0);
cbuf->ReadRaw(t, 16);
ASSERT_EQ(strncmp(t, "mnopqr0123456789", 16), 0);
cbuf->ReadRaw(t, 6);
ASSERT_EQ(strncmp(t, "987654", 6), 0);
cbuf->ReadRaw(t, 4);
ASSERT_EQ(strncmp(t, "3210", 4), 0);
cbuf->ReadRaw(t, 4);
ASSERT_EQ(strncmp(t, "abcd", 4), 0);
cbuf->ReadRaw(t, 8);
ASSERT_EQ(strncmp(t, "efghijkl", 8), 0);
cbuf->ReadRaw(t, 16);
ASSERT_EQ(strncmp(t, "mnopqr0123456789", 16), 0);
cbuf->ReadRaw(t, 6);
ASSERT_EQ(strncmp(t, "987654", 6), 0);
cbuf->ReadRaw(t, 4);
ASSERT_EQ(strncmp(t, "3210", 4), 0);
});
// write to buffer
cbuf->WriteRaw("abcdef", 6);
cbuf->WriteRaw("ghijkl", 6);
cbuf->WriteRaw("mnopqr", 6);
cbuf->WriteRaw("01234567899876543210", 20);
cbuf->WriteRaw("abcdef", 6);
cbuf->WriteRaw("ghijkl", 6);
cbuf->WriteRaw("mnopqr", 6);
cbuf->WriteRaw("01234567899876543210", 20);
reader.join();
}<commit_msg>Rename test<commit_after>// Copyright (C) 2012-2017 Leap Motion, Inc. All rights reserved.
#include "stdafx.h"
#include "IPCTestUtils.h"
#include <leapipc/CircularBufferEndpoint.h>
#include <autowiring/autowiring.h>
#include <autowiring/CoreThread.h>
#include <cstdio>
#include <thread>
#include <gtest/gtest.h>
using namespace leap::ipc;
class CircularBufferEndpointTest :
public testing::Test
{};
TEST_F(CircularBufferEndpointTest, WriteReadSequence)
{
auto cbuf = std::make_shared<CircularBufferEndpoint>(32);
// read from buffer in separate thread
std::thread reader([cbuf] {
char t[16];
cbuf->ReadRaw(t, 4);
ASSERT_EQ(strncmp(t, "abcd", 4), 0);
cbuf->ReadRaw(t, 8);
ASSERT_EQ(strncmp(t, "efghijkl", 8), 0);
cbuf->ReadRaw(t, 16);
ASSERT_EQ(strncmp(t, "mnopqr0123456789", 16), 0);
cbuf->ReadRaw(t, 6);
ASSERT_EQ(strncmp(t, "987654", 6), 0);
cbuf->ReadRaw(t, 4);
ASSERT_EQ(strncmp(t, "3210", 4), 0);
cbuf->ReadRaw(t, 4);
ASSERT_EQ(strncmp(t, "abcd", 4), 0);
cbuf->ReadRaw(t, 8);
ASSERT_EQ(strncmp(t, "efghijkl", 8), 0);
cbuf->ReadRaw(t, 16);
ASSERT_EQ(strncmp(t, "mnopqr0123456789", 16), 0);
cbuf->ReadRaw(t, 6);
ASSERT_EQ(strncmp(t, "987654", 6), 0);
cbuf->ReadRaw(t, 4);
ASSERT_EQ(strncmp(t, "3210", 4), 0);
});
// write to buffer
cbuf->WriteRaw("abcdef", 6);
cbuf->WriteRaw("ghijkl", 6);
cbuf->WriteRaw("mnopqr", 6);
cbuf->WriteRaw("01234567899876543210", 20);
cbuf->WriteRaw("abcdef", 6);
cbuf->WriteRaw("ghijkl", 6);
cbuf->WriteRaw("mnopqr", 6);
cbuf->WriteRaw("01234567899876543210", 20);
reader.join();
}
TEST_F(CircularBufferEndpointTest, IncreaseSize)
{
auto cbuf = std::make_shared<CircularBufferEndpoint>(16);
// read from buffer in separate thread
std::thread reader([cbuf] {
char t[16];
cbuf->ReadRaw(t, 4);
ASSERT_EQ(strncmp(t, "abcd", 4), 0);
cbuf->ReadRaw(t, 8);
ASSERT_EQ(strncmp(t, "efghijkl", 8), 0);
cbuf->ReadRaw(t, 16);
ASSERT_EQ(strncmp(t, "mnopqr0123456789", 16), 0);
cbuf->ReadRaw(t, 6);
ASSERT_EQ(strncmp(t, "987654", 6), 0);
cbuf->ReadRaw(t, 4);
ASSERT_EQ(strncmp(t, "3210", 4), 0);
cbuf->ReadRaw(t, 4);
ASSERT_EQ(strncmp(t, "abcd", 4), 0);
cbuf->ReadRaw(t, 8);
ASSERT_EQ(strncmp(t, "efghijkl", 8), 0);
cbuf->ReadRaw(t, 16);
ASSERT_EQ(strncmp(t, "mnopqr0123456789", 16), 0);
cbuf->ReadRaw(t, 6);
ASSERT_EQ(strncmp(t, "987654", 6), 0);
cbuf->ReadRaw(t, 4);
ASSERT_EQ(strncmp(t, "3210", 4), 0);
});
// write to buffer
cbuf->WriteRaw("abcdef", 6);
cbuf->WriteRaw("ghijkl", 6);
cbuf->WriteRaw("mnopqr", 6);
cbuf->WriteRaw("01234567899876543210", 20);
cbuf->WriteRaw("abcdef", 6);
cbuf->WriteRaw("ghijkl", 6);
cbuf->WriteRaw("mnopqr", 6);
cbuf->WriteRaw("01234567899876543210", 20);
reader.join();
}<|endoftext|> |
<commit_before>/*
Copyright (c) 2007 Till Adam <adam@kde.org>
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; see the file COPYING.LIB. If not, write to the
Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
02110-1301, USA.
*/
#include "akonadi_serializer_mail.h"
#include <QtCore/qplugin.h>
#include <kdebug.h>
#include <kmime/kmime_message.h>
#include <boost/shared_ptr.hpp>
#include <akonadi/item.h>
#include <akonadi/kmime/messageparts.h>
#include <akonadi/private/imapparser_p.h>
using namespace Akonadi;
using namespace KMime;
typedef boost::shared_ptr<KMime::Message> MessagePtr;
template <typename T> static void parseAddrList( const QList<QByteArray> &addrList, T *hdr )
{
for ( QList<QByteArray>::ConstIterator it = addrList.constBegin(); it != addrList.constEnd(); ++it ) {
QList<QByteArray> addr;
ImapParser::parseParenthesizedList( *it, addr );
if ( addr.count() != 4 ) {
kWarning( 5264 ) << "Error parsing envelope address field: " << addr;
continue;
}
KMime::Types::Mailbox addrField;
addrField.setNameFrom7Bit( addr[0] );
addrField.setAddress( addr[2] + '@' + addr[3] );
hdr->addAddress( addrField );
}
}
bool SerializerPluginMail::deserialize( Item& item, const QByteArray& label, QIODevice& data )
{
if ( label != MessagePart::Body && label != MessagePart::Envelope && label != MessagePart::Header )
return false;
MessagePtr msg;
if ( !item.hasPayload() ) {
Message *m = new Message();
msg = MessagePtr( m );
item.setPayload( msg );
} else {
msg = item.payload<MessagePtr>();
}
QByteArray buffer = data.readAll();
if ( buffer.isEmpty() )
return true;
if ( label == MessagePart::Body ) {
msg->setContent( buffer );
msg->parse();
} else if ( label == MessagePart::Header ) {
if ( !msg->body().isEmpty() && !msg->contents().isEmpty() ) {
msg->setHead( buffer );
msg->parse();
}
} else if ( label == MessagePart::Envelope ) {
QList<QByteArray> env;
ImapParser::parseParenthesizedList( buffer, env );
if ( env.count() < 10 ) {
kWarning( 5264 ) << "Akonadi KMime Deserializer: Got invalid envelope: " << env;
return false;
}
Q_ASSERT( env.count() >= 10 );
// date
msg->date()->from7BitString( env[0] );
// subject
msg->subject()->from7BitString( env[1] );
// from
QList<QByteArray> addrList;
ImapParser::parseParenthesizedList( env[2], addrList );
if ( !addrList.isEmpty() )
parseAddrList( addrList, msg->from() );
// sender
ImapParser::parseParenthesizedList( env[2], addrList );
if ( !addrList.isEmpty() )
parseAddrList( addrList, msg->sender() );
// reply-to
ImapParser::parseParenthesizedList( env[4], addrList );
if ( !addrList.isEmpty() )
parseAddrList( addrList, msg->replyTo() );
// to
ImapParser::parseParenthesizedList( env[5], addrList );
if ( !addrList.isEmpty() )
parseAddrList( addrList, msg->to() );
// cc
ImapParser::parseParenthesizedList( env[6], addrList );
if ( !addrList.isEmpty() )
parseAddrList( addrList, msg->cc() );
// bcc
ImapParser::parseParenthesizedList( env[7], addrList );
if ( !addrList.isEmpty() )
parseAddrList( addrList, msg->bcc() );
// in-reply-to
msg->inReplyTo()->from7BitString( env[8] );
// message id
msg->messageID()->from7BitString( env[9] );
}
return true;
}
static QByteArray quoteImapListEntry( const QByteArray &b )
{
if ( b.isEmpty() )
return "NIL";
return ImapParser::quote( b );
}
static QByteArray buildImapList( const QList<QByteArray> &list )
{
if ( list.isEmpty() )
return "NIL";
return QByteArray( "(" ) + ImapParser::join( list, " " ) + QByteArray( ")" );
}
template <typename T> static QByteArray buildAddrStruct( T const *hdr )
{
QList<QByteArray> addrList;
KMime::Types::Mailbox::List mb = hdr->mailboxes();
foreach ( const KMime::Types::Mailbox mbox, mb ) {
QList<QByteArray> addrStruct;
addrStruct << quoteImapListEntry( KMime::encodeRFC2047String( mbox.name(), "utf-8" ) );
addrStruct << quoteImapListEntry( QByteArray() );
addrStruct << quoteImapListEntry( mbox.addrSpec().localPart.toUtf8() );
addrStruct << quoteImapListEntry( mbox.addrSpec().domain.toUtf8() );
addrList << buildImapList( addrStruct );
}
return buildImapList( addrList );
}
void SerializerPluginMail::serialize( const Item& item, const QByteArray& label, QIODevice& data )
{
boost::shared_ptr<Message> m = item.payload< boost::shared_ptr<Message> >();
m->assemble();
if ( label == MessagePart::Body ) {
data.write( m->encodedContent() );
} else if ( label == MessagePart::Envelope ) {
QList<QByteArray> env;
env << quoteImapListEntry( m->date()->as7BitString( false ) );
env << quoteImapListEntry( m->subject()->as7BitString( false ) );
env << buildAddrStruct( m->from() );
env << buildAddrStruct( m->sender() );
env << buildAddrStruct( m->replyTo() );
env << buildAddrStruct( m->to() );
env << buildAddrStruct( m->cc() );
env << buildAddrStruct( m->bcc() );
env << quoteImapListEntry( m->inReplyTo()->as7BitString( false ) );
env << quoteImapListEntry( m->messageID()->as7BitString( false ) );
data.write( buildImapList( env ) );
} else if ( label == MessagePart::Header ) {
data.write( m->head() );
}
}
QSet<QByteArray> SerializerPluginMail::parts(const Item & item) const
{
if ( !item.hasPayload<MessagePtr>() )
return QSet<QByteArray>();
MessagePtr msg = item.payload<MessagePtr>();
QSet<QByteArray> set;
// FIXME: we actually want "has any header" here, but the kmime api doesn't offer that yet
if ( msg->hasContent() || msg->hasHeader( "Message-ID" ) ) {
set << MessagePart::Envelope << MessagePart::Header;
if ( !msg->body().isEmpty() || !msg->contents().isEmpty() )
set << MessagePart::Body;
}
return set;
}
Q_EXPORT_PLUGIN2( akonadi_serializer_mail, SerializerPluginMail );
#include "akonadi_serializer_mail.moc"
<commit_msg>pedantic--<commit_after>/*
Copyright (c) 2007 Till Adam <adam@kde.org>
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; see the file COPYING.LIB. If not, write to the
Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
02110-1301, USA.
*/
#include "akonadi_serializer_mail.h"
#include <QtCore/qplugin.h>
#include <kdebug.h>
#include <kmime/kmime_message.h>
#include <boost/shared_ptr.hpp>
#include <akonadi/item.h>
#include <akonadi/kmime/messageparts.h>
#include <akonadi/private/imapparser_p.h>
using namespace Akonadi;
using namespace KMime;
typedef boost::shared_ptr<KMime::Message> MessagePtr;
template <typename T> static void parseAddrList( const QList<QByteArray> &addrList, T *hdr )
{
for ( QList<QByteArray>::ConstIterator it = addrList.constBegin(); it != addrList.constEnd(); ++it ) {
QList<QByteArray> addr;
ImapParser::parseParenthesizedList( *it, addr );
if ( addr.count() != 4 ) {
kWarning( 5264 ) << "Error parsing envelope address field: " << addr;
continue;
}
KMime::Types::Mailbox addrField;
addrField.setNameFrom7Bit( addr[0] );
addrField.setAddress( addr[2] + '@' + addr[3] );
hdr->addAddress( addrField );
}
}
bool SerializerPluginMail::deserialize( Item& item, const QByteArray& label, QIODevice& data )
{
if ( label != MessagePart::Body && label != MessagePart::Envelope && label != MessagePart::Header )
return false;
MessagePtr msg;
if ( !item.hasPayload() ) {
Message *m = new Message();
msg = MessagePtr( m );
item.setPayload( msg );
} else {
msg = item.payload<MessagePtr>();
}
QByteArray buffer = data.readAll();
if ( buffer.isEmpty() )
return true;
if ( label == MessagePart::Body ) {
msg->setContent( buffer );
msg->parse();
} else if ( label == MessagePart::Header ) {
if ( !msg->body().isEmpty() && !msg->contents().isEmpty() ) {
msg->setHead( buffer );
msg->parse();
}
} else if ( label == MessagePart::Envelope ) {
QList<QByteArray> env;
ImapParser::parseParenthesizedList( buffer, env );
if ( env.count() < 10 ) {
kWarning( 5264 ) << "Akonadi KMime Deserializer: Got invalid envelope: " << env;
return false;
}
Q_ASSERT( env.count() >= 10 );
// date
msg->date()->from7BitString( env[0] );
// subject
msg->subject()->from7BitString( env[1] );
// from
QList<QByteArray> addrList;
ImapParser::parseParenthesizedList( env[2], addrList );
if ( !addrList.isEmpty() )
parseAddrList( addrList, msg->from() );
// sender
ImapParser::parseParenthesizedList( env[2], addrList );
if ( !addrList.isEmpty() )
parseAddrList( addrList, msg->sender() );
// reply-to
ImapParser::parseParenthesizedList( env[4], addrList );
if ( !addrList.isEmpty() )
parseAddrList( addrList, msg->replyTo() );
// to
ImapParser::parseParenthesizedList( env[5], addrList );
if ( !addrList.isEmpty() )
parseAddrList( addrList, msg->to() );
// cc
ImapParser::parseParenthesizedList( env[6], addrList );
if ( !addrList.isEmpty() )
parseAddrList( addrList, msg->cc() );
// bcc
ImapParser::parseParenthesizedList( env[7], addrList );
if ( !addrList.isEmpty() )
parseAddrList( addrList, msg->bcc() );
// in-reply-to
msg->inReplyTo()->from7BitString( env[8] );
// message id
msg->messageID()->from7BitString( env[9] );
}
return true;
}
static QByteArray quoteImapListEntry( const QByteArray &b )
{
if ( b.isEmpty() )
return "NIL";
return ImapParser::quote( b );
}
static QByteArray buildImapList( const QList<QByteArray> &list )
{
if ( list.isEmpty() )
return "NIL";
return QByteArray( "(" ) + ImapParser::join( list, " " ) + QByteArray( ")" );
}
template <typename T> static QByteArray buildAddrStruct( T const *hdr )
{
QList<QByteArray> addrList;
KMime::Types::Mailbox::List mb = hdr->mailboxes();
foreach ( const KMime::Types::Mailbox mbox, mb ) {
QList<QByteArray> addrStruct;
addrStruct << quoteImapListEntry( KMime::encodeRFC2047String( mbox.name(), "utf-8" ) );
addrStruct << quoteImapListEntry( QByteArray() );
addrStruct << quoteImapListEntry( mbox.addrSpec().localPart.toUtf8() );
addrStruct << quoteImapListEntry( mbox.addrSpec().domain.toUtf8() );
addrList << buildImapList( addrStruct );
}
return buildImapList( addrList );
}
void SerializerPluginMail::serialize( const Item& item, const QByteArray& label, QIODevice& data )
{
boost::shared_ptr<Message> m = item.payload< boost::shared_ptr<Message> >();
m->assemble();
if ( label == MessagePart::Body ) {
data.write( m->encodedContent() );
} else if ( label == MessagePart::Envelope ) {
QList<QByteArray> env;
env << quoteImapListEntry( m->date()->as7BitString( false ) );
env << quoteImapListEntry( m->subject()->as7BitString( false ) );
env << buildAddrStruct( m->from() );
env << buildAddrStruct( m->sender() );
env << buildAddrStruct( m->replyTo() );
env << buildAddrStruct( m->to() );
env << buildAddrStruct( m->cc() );
env << buildAddrStruct( m->bcc() );
env << quoteImapListEntry( m->inReplyTo()->as7BitString( false ) );
env << quoteImapListEntry( m->messageID()->as7BitString( false ) );
data.write( buildImapList( env ) );
} else if ( label == MessagePart::Header ) {
data.write( m->head() );
}
}
QSet<QByteArray> SerializerPluginMail::parts(const Item & item) const
{
if ( !item.hasPayload<MessagePtr>() )
return QSet<QByteArray>();
MessagePtr msg = item.payload<MessagePtr>();
QSet<QByteArray> set;
// FIXME: we actually want "has any header" here, but the kmime api doesn't offer that yet
if ( msg->hasContent() || msg->hasHeader( "Message-ID" ) ) {
set << MessagePart::Envelope << MessagePart::Header;
if ( !msg->body().isEmpty() || !msg->contents().isEmpty() )
set << MessagePart::Body;
}
return set;
}
Q_EXPORT_PLUGIN2( akonadi_serializer_mail, SerializerPluginMail )
#include "akonadi_serializer_mail.moc"
<|endoftext|> |
<commit_before>/*
* Copyright 2010-2012 Esrille 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.
*/
#include "NodeImp.h"
#include "DocumentImp.h"
#include "MutationEventImp.h"
#include "ElementImp.h"
#include "NodeListImp.h"
namespace org { namespace w3c { namespace dom { namespace bootstrap {
//
// Tree management
//
NodeImp* NodeImp::removeChild(NodeImp* item)
{
NodeImp* next = item->nextSibling;
NodeImp* prev = item->previousSibling;
if (!next)
lastChild = prev;
else
next->previousSibling = prev;
if (!prev)
firstChild = next;
else
prev->nextSibling = next;
item->parentNode = 0;
--childCount;
return item;
}
NodeImp* NodeImp::insertBefore(NodeImp* item, NodeImp* after)
{
item->previousSibling = after->previousSibling;
item->nextSibling = after;
after->previousSibling = item;
if (!item->previousSibling)
firstChild = item;
else
item->previousSibling->nextSibling = item;
item->parentNode = this;
++childCount;
return item;
}
NodeImp* NodeImp::appendChild(NodeImp* item)
{
NodeImp* prev = lastChild;
if (!prev)
firstChild = item;
else
prev->nextSibling = item;
item->previousSibling = prev;
item->nextSibling = 0;
lastChild = item;
item->parentNode = this;
++childCount;
return item;
}
void NodeImp::eval()
{
}
void NodeImp::setOwnerDocument(DocumentImp* document)
{
assert(!ownerDocument);
ownerDocument = document;
}
// Node
unsigned short NodeImp::getNodeType()
{
// TODO: SHOUD NOT REACH HERE
return 0;
}
std::u16string NodeImp::getNodeName()
{
return nodeName;
}
Nullable<std::u16string> NodeImp::getBaseURI()
{
// TODO: implement me!
return u"";
}
Document NodeImp::getOwnerDocument()
{
return ownerDocument;
}
Node NodeImp::getParentNode()
{
return parentNode;
}
Element NodeImp::getParentElement()
{
return dynamic_cast<ElementImp*>(parentNode);
}
bool NodeImp::hasChildNodes()
{
return firstChild;
}
NodeList NodeImp::getChildNodes()
{
return new(std::nothrow) NodeListImp(this);
}
Node NodeImp::getFirstChild()
{
return firstChild;
}
Node NodeImp::getLastChild()
{
return lastChild;
}
Node NodeImp::getPreviousSibling()
{
return previousSibling;
}
Node NodeImp::getNextSibling()
{
return nextSibling;
}
unsigned short NodeImp::compareDocumentPosition(Node other)
{
// TODO: implement me!
return 0;
}
Nullable<std::u16string> NodeImp::getNodeValue()
{
// TODO: implement me!
return u"";
}
void NodeImp::setNodeValue(Nullable<std::u16string> nodeValue)
{
// TODO: implement me!
}
Nullable<std::u16string> NodeImp::getTextContent()
{
return u""; // TODO: return null instead
}
void NodeImp::setTextContent(Nullable<std::u16string> textContent)
{
// TODO: implement me!
}
Node NodeImp::insertBefore(Node newChild, Node refChild)
{
if (!newChild)
return newChild;
if (!refChild)
return appendChild(newChild);
if (newChild != refChild) {
Document ownerOfChild = newChild.getOwnerDocument();
if (ownerOfChild != getOwnerDocument() && ownerOfChild != *this)
throw DOMException(DOMException::WRONG_DOCUMENT_ERR);
if (refChild.getParentNode() != *this)
throw DOMException(DOMException::NOT_FOUND_ERR);
if (NodeImp* child = dynamic_cast<NodeImp*>(newChild.self())) {
if (child == this || child->isAncestorOf(this))
throw DOMException(DOMException::HIERARCHY_REQUEST_ERR);
if (NodeImp* ref = dynamic_cast<NodeImp*>(refChild.self())) {
child->retain_();
if (child->parentNode) {
child->parentNode->removeChild(child);
child->release_();
}
insertBefore(child, ref);
events::MutationEvent event = new(std::nothrow) MutationEventImp;
event.initMutationEvent(u"DOMNodeInserted",
true, false, this, u"", u"", u"", 0);
child->dispatchEvent(event);
}
}
}
return newChild;
}
Node NodeImp::replaceChild(Node newChild, Node oldChild)
{
if (!newChild)
return oldChild;
if (!oldChild || oldChild.getParentNode() != *this)
throw DOMException(DOMException::NOT_FOUND_ERR);
if (newChild != oldChild) {
Document ownerOfChild = newChild.getOwnerDocument();
if (ownerOfChild != getOwnerDocument() && ownerOfChild != *this)
throw DOMException(DOMException::WRONG_DOCUMENT_ERR);
if (NodeImp* child = dynamic_cast<NodeImp*>(newChild.self())) {
if (child == this || child->isAncestorOf(this))
throw DOMException(DOMException::HIERARCHY_REQUEST_ERR);
if (NodeImp* ref = dynamic_cast<NodeImp*>(oldChild.self())) {
child->retain_();
if (child->parentNode) {
child->parentNode->removeChild(child);
child->release_();
}
insertBefore(child, ref);
removeChild(ref);
ref->release_();
}
}
}
return oldChild;
}
Node NodeImp::removeChild(Node oldChild)
{
if (!oldChild)
throw DOMException(DOMException::NOT_FOUND_ERR);
if (NodeImp* child = dynamic_cast<NodeImp*>(oldChild.self())) {
if (child->parentNode != this)
throw DOMException(DOMException::NOT_FOUND_ERR);
if (0 < count_()) { // Prevent dispatching an event from the destructor.
events::MutationEvent event = new(std::nothrow) MutationEventImp;
event.initMutationEvent(u"DOMNodeRemoved",
true, false, this, u"", u"", u"", 0);
child->dispatchEvent(event);
}
removeChild(child);
child->release_();
}
return oldChild;
}
Node NodeImp::appendChild(Node newChild)
{
if (!newChild)
return newChild;
Document ownerOfChild = newChild.getOwnerDocument();
if (ownerOfChild != getOwnerDocument() && ownerOfChild != *this)
throw DOMException(DOMException::WRONG_DOCUMENT_ERR);
if (NodeImp* child = dynamic_cast<NodeImp*>(newChild.self())) {
if (child == this || child->isAncestorOf(this))
throw DOMException(DOMException::HIERARCHY_REQUEST_ERR);
// TODO: case newChild is a DocumentFragment
child->retain_();
if (child->parentNode) {
child->parentNode->removeChild(child);
child->release_();
}
appendChild(child);
} // TODO: else ...
return newChild;
}
Node NodeImp::cloneNode(bool deep)
{
return new(std::nothrow) NodeImp(this, deep);
}
bool NodeImp::isSameNode(Node other)
{
return other == *this;
}
bool NodeImp::isEqualNode(Node arg)
{
// TODO: implement me!
return 0;
}
std::u16string NodeImp::lookupPrefix(std::u16string namespaceURI)
{
// TODO: implement me!
return u"";
}
std::u16string NodeImp::lookupNamespaceURI(Nullable<std::u16string> prefix)
{
// TODO: implement me!
return u"";
}
bool NodeImp::isDefaultNamespace(std::u16string namespaceURI)
{
// TODO: implement me!
return 0;
}
NodeImp::NodeImp(DocumentImp* ownerDocument) :
ownerDocument(ownerDocument),
parentNode(0),
firstChild(0),
lastChild(0),
previousSibling(0),
nextSibling(0),
childCount(0)
{
}
NodeImp::NodeImp(NodeImp* org, bool deep) :
ObjectMixin(org),
ownerDocument(0),
parentNode(0),
firstChild(0),
lastChild(0),
previousSibling(0),
nextSibling(0),
childCount(0),
nodeName(org->nodeName)
{
setOwnerDocument(org->ownerDocument);
if (!deep)
return;
for (NodeImp* node = org->firstChild; node; node = node->nextSibling) {
Node clone = node->cloneNode(true);
appendChild(clone);
}
}
NodeImp::~NodeImp()
{
assert(0 == count_());
while (0 < childCount)
removeChild(getFirstChild());
}
}}}} // org::w3c::dom::bootstrap
<commit_msg>(NodeImp::appendChild) : Generate a DOMNodeInserted event.<commit_after>/*
* Copyright 2010-2012 Esrille 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.
*/
#include "NodeImp.h"
#include "DocumentImp.h"
#include "MutationEventImp.h"
#include "ElementImp.h"
#include "NodeListImp.h"
namespace org { namespace w3c { namespace dom { namespace bootstrap {
//
// Tree management
//
NodeImp* NodeImp::removeChild(NodeImp* item)
{
NodeImp* next = item->nextSibling;
NodeImp* prev = item->previousSibling;
if (!next)
lastChild = prev;
else
next->previousSibling = prev;
if (!prev)
firstChild = next;
else
prev->nextSibling = next;
item->parentNode = 0;
--childCount;
return item;
}
NodeImp* NodeImp::insertBefore(NodeImp* item, NodeImp* after)
{
item->previousSibling = after->previousSibling;
item->nextSibling = after;
after->previousSibling = item;
if (!item->previousSibling)
firstChild = item;
else
item->previousSibling->nextSibling = item;
item->parentNode = this;
++childCount;
return item;
}
NodeImp* NodeImp::appendChild(NodeImp* item)
{
NodeImp* prev = lastChild;
if (!prev)
firstChild = item;
else
prev->nextSibling = item;
item->previousSibling = prev;
item->nextSibling = 0;
lastChild = item;
item->parentNode = this;
++childCount;
return item;
}
void NodeImp::eval()
{
}
void NodeImp::setOwnerDocument(DocumentImp* document)
{
assert(!ownerDocument);
ownerDocument = document;
}
// Node
unsigned short NodeImp::getNodeType()
{
// TODO: SHOUD NOT REACH HERE
return 0;
}
std::u16string NodeImp::getNodeName()
{
return nodeName;
}
Nullable<std::u16string> NodeImp::getBaseURI()
{
// TODO: implement me!
return u"";
}
Document NodeImp::getOwnerDocument()
{
return ownerDocument;
}
Node NodeImp::getParentNode()
{
return parentNode;
}
Element NodeImp::getParentElement()
{
return dynamic_cast<ElementImp*>(parentNode);
}
bool NodeImp::hasChildNodes()
{
return firstChild;
}
NodeList NodeImp::getChildNodes()
{
return new(std::nothrow) NodeListImp(this);
}
Node NodeImp::getFirstChild()
{
return firstChild;
}
Node NodeImp::getLastChild()
{
return lastChild;
}
Node NodeImp::getPreviousSibling()
{
return previousSibling;
}
Node NodeImp::getNextSibling()
{
return nextSibling;
}
unsigned short NodeImp::compareDocumentPosition(Node other)
{
// TODO: implement me!
return 0;
}
Nullable<std::u16string> NodeImp::getNodeValue()
{
// TODO: implement me!
return u"";
}
void NodeImp::setNodeValue(Nullable<std::u16string> nodeValue)
{
// TODO: implement me!
}
Nullable<std::u16string> NodeImp::getTextContent()
{
return u""; // TODO: return null instead
}
void NodeImp::setTextContent(Nullable<std::u16string> textContent)
{
// TODO: implement me!
}
Node NodeImp::insertBefore(Node newChild, Node refChild)
{
if (!newChild)
return newChild;
if (!refChild)
return appendChild(newChild);
if (newChild != refChild) {
Document ownerOfChild = newChild.getOwnerDocument();
if (ownerOfChild != getOwnerDocument() && ownerOfChild != *this)
throw DOMException(DOMException::WRONG_DOCUMENT_ERR);
if (refChild.getParentNode() != *this)
throw DOMException(DOMException::NOT_FOUND_ERR);
if (NodeImp* child = dynamic_cast<NodeImp*>(newChild.self())) {
if (child == this || child->isAncestorOf(this))
throw DOMException(DOMException::HIERARCHY_REQUEST_ERR);
if (NodeImp* ref = dynamic_cast<NodeImp*>(refChild.self())) {
child->retain_();
if (child->parentNode) {
child->parentNode->removeChild(child);
child->release_();
}
insertBefore(child, ref);
events::MutationEvent event = new(std::nothrow) MutationEventImp;
event.initMutationEvent(u"DOMNodeInserted",
true, false, this, u"", u"", u"", 0);
child->dispatchEvent(event);
}
}
}
return newChild;
}
Node NodeImp::replaceChild(Node newChild, Node oldChild)
{
if (!newChild)
return oldChild;
if (!oldChild || oldChild.getParentNode() != *this)
throw DOMException(DOMException::NOT_FOUND_ERR);
if (newChild != oldChild) {
Document ownerOfChild = newChild.getOwnerDocument();
if (ownerOfChild != getOwnerDocument() && ownerOfChild != *this)
throw DOMException(DOMException::WRONG_DOCUMENT_ERR);
if (NodeImp* child = dynamic_cast<NodeImp*>(newChild.self())) {
if (child == this || child->isAncestorOf(this))
throw DOMException(DOMException::HIERARCHY_REQUEST_ERR);
if (NodeImp* ref = dynamic_cast<NodeImp*>(oldChild.self())) {
child->retain_();
if (child->parentNode) {
child->parentNode->removeChild(child);
child->release_();
}
insertBefore(child, ref);
removeChild(ref);
ref->release_();
}
}
}
return oldChild;
}
Node NodeImp::removeChild(Node oldChild)
{
if (!oldChild)
throw DOMException(DOMException::NOT_FOUND_ERR);
if (NodeImp* child = dynamic_cast<NodeImp*>(oldChild.self())) {
if (child->parentNode != this)
throw DOMException(DOMException::NOT_FOUND_ERR);
if (0 < count_()) { // Prevent dispatching an event from the destructor.
events::MutationEvent event = new(std::nothrow) MutationEventImp;
event.initMutationEvent(u"DOMNodeRemoved",
true, false, this, u"", u"", u"", 0);
child->dispatchEvent(event);
}
removeChild(child);
child->release_();
}
return oldChild;
}
Node NodeImp::appendChild(Node newChild)
{
if (!newChild)
return newChild;
Document ownerOfChild = newChild.getOwnerDocument();
if (ownerOfChild != getOwnerDocument() && ownerOfChild != *this)
throw DOMException(DOMException::WRONG_DOCUMENT_ERR);
if (NodeImp* child = dynamic_cast<NodeImp*>(newChild.self())) {
if (child == this || child->isAncestorOf(this))
throw DOMException(DOMException::HIERARCHY_REQUEST_ERR);
// TODO: case newChild is a DocumentFragment
child->retain_();
if (child->parentNode) {
child->parentNode->removeChild(child);
child->release_();
}
appendChild(child);
events::MutationEvent event = new(std::nothrow) MutationEventImp;
event.initMutationEvent(u"DOMNodeInserted",
true, false, this, u"", u"", u"", 0);
child->dispatchEvent(event);
} // TODO: else ...
return newChild;
}
Node NodeImp::cloneNode(bool deep)
{
return new(std::nothrow) NodeImp(this, deep);
}
bool NodeImp::isSameNode(Node other)
{
return other == *this;
}
bool NodeImp::isEqualNode(Node arg)
{
// TODO: implement me!
return 0;
}
std::u16string NodeImp::lookupPrefix(std::u16string namespaceURI)
{
// TODO: implement me!
return u"";
}
std::u16string NodeImp::lookupNamespaceURI(Nullable<std::u16string> prefix)
{
// TODO: implement me!
return u"";
}
bool NodeImp::isDefaultNamespace(std::u16string namespaceURI)
{
// TODO: implement me!
return 0;
}
NodeImp::NodeImp(DocumentImp* ownerDocument) :
ownerDocument(ownerDocument),
parentNode(0),
firstChild(0),
lastChild(0),
previousSibling(0),
nextSibling(0),
childCount(0)
{
}
NodeImp::NodeImp(NodeImp* org, bool deep) :
ObjectMixin(org),
ownerDocument(0),
parentNode(0),
firstChild(0),
lastChild(0),
previousSibling(0),
nextSibling(0),
childCount(0),
nodeName(org->nodeName)
{
setOwnerDocument(org->ownerDocument);
if (!deep)
return;
for (NodeImp* node = org->firstChild; node; node = node->nextSibling) {
Node clone = node->cloneNode(true);
appendChild(clone);
}
}
NodeImp::~NodeImp()
{
assert(0 == count_());
while (0 < childCount)
removeChild(getFirstChild());
}
}}}} // org::w3c::dom::bootstrap
<|endoftext|> |
<commit_before>/*
* Copyright (C) 2012 Tommi Maekitalo
*
* 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.
*
* As a special exception, you may use this file as part of a free
* software library without restriction. Specifically, if other files
* instantiate templates or use macros or inline functions from this
* file, or you compile this file and link it with other files to
* produce an executable, this file does not by itself cause the
* resulting executable to be covered by the GNU General Public
* License. This exception does not however invalidate any other
* reasons why the executable file might be covered by the GNU Library
* General Public License.
*
* 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 <tnt/tntconfig.h>
namespace tnt
{
void operator>>= (const cxxtools::SerializationInfo& si, TntConfig::Mapping& mapping)
{
si.getMember("target") >>= mapping.target;
si.getMember("url") >>= mapping.url;
si.getMember("vhost", mapping.vhost);
si.getMember("method", mapping.method);
si.getMember("pathinfo", mapping.pathinfo);
bool ssl;
if (si.getMember("ssl", ssl))
mapping.ssl = ssl ? SSL_YES : SSL_NO;
else
mapping.ssl = SSL_ALL;
const cxxtools::SerializationInfo* args = si.findMember("args");
if (args)
{
for (cxxtools::SerializationInfo::ConstIterator it = args->begin(); it != args->end(); ++it)
{
std::string value;
it->getValue(value);
mapping.args[it->name()] = value;
}
}
}
void operator>>= (const cxxtools::SerializationInfo& si, TntConfig::Listener& listener)
{
si.getMember("ip") >>= listener.ip;
if (!si.getMember("port", listener.port))
listener.port = 80;
}
void operator>>= (const cxxtools::SerializationInfo& si, TntConfig::SslListener& ssllistener)
{
si.getMember("ip") >>= ssllistener.ip;
if (!si.getMember("port", ssllistener.port))
ssllistener.port = 443;
si.getMember("certificate") >>= ssllistener.certificate;
if (!si.getMember("key", ssllistener.key))
ssllistener.key = ssllistener.certificate;
}
void operator>>= (const cxxtools::SerializationInfo& si, TntConfig& config)
{
TntConfig::MappingsType mappings;
if (si.getMember("mappings", mappings))
config.mappings.insert(config.mappings.end(), mappings.begin(), mappings.end());
TntConfig::ListenersType listeners;
TntConfig::SslListenersType ssllisteners;
const cxxtools::SerializationInfo& lit = si.getMember("listeners");
for (cxxtools::SerializationInfo::ConstIterator it = lit.begin(); it != lit.end(); ++it)
{
if (it->findMember("certificate") != 0)
{
ssllisteners.resize(ssllisteners.size() + 1);
*it >>= ssllisteners.back();
}
else
{
listeners.resize(listeners.size() + 1);
*it >>= listeners.back();
}
}
config.listeners.insert(config.listeners.end(), listeners.begin(), listeners.end());
config.ssllisteners.insert(config.ssllisteners.end(), ssllisteners.begin(), ssllisteners.end());
if (config.listeners.empty() && config.ssllisteners.empty())
{
config.listeners.resize(1);
config.listeners.back().port = 80;
}
si.getMember("maxRequestSize", config.maxRequestSize);
si.getMember("maxRequestTime", config.maxRequestTime);
si.getMember("user", config.user);
si.getMember("group", config.group);
si.getMember("dir", config.dir);
si.getMember("chrootdir", config.chrootdir);
si.getMember("pidfile", config.pidfile);
si.getMember("daemon", config.daemon);
si.getMember("minThreads", config.minThreads);
si.getMember("maxThreads", config.maxThreads);
si.getMember("threadStartDelay", config.threadStartDelay);
si.getMember("queueSize", config.queueSize);
si.getMember("compPath", config.compPath);
si.getMember("socketBufferSize", config.socketBufferSize);
si.getMember("socketReadTimeout", config.socketReadTimeout);
si.getMember("socketWriteTimeout", config.socketWriteTimeout);
si.getMember("keepAliveTimeout", config.keepAliveTimeout);
si.getMember("keepAliveMax", config.keepAliveMax);
si.getMember("sessionTimeout", config.sessionTimeout);
si.getMember("listenBacklog", config.listenBacklog);
si.getMember("listenRetry", config.listenRetry);
si.getMember("enableCompression", config.enableCompression);
si.getMember("minCompressSize", config.minCompressSize);
si.getMember("mimeDb", config.mimeDb);
si.getMember("maxUrlMapCache", config.maxUrlMapCache);
si.getMember("defaultContentType", config.defaultContentType);
si.getMember("accessLog", config.accessLog);
si.getMember("errorLog", config.errorLog);
si.getMember("backgroundTasks", config.backgroundTasks);
si.getMember("timerSleep", config.timerSleep);
si.getMember("documentRoot", config.documentRoot);
si.getMember("includes", config.includes);
config.config = si;
const cxxtools::SerializationInfo* p = si.findMember("environment");
if (p)
{
for (cxxtools::SerializationInfo::ConstIterator it = p->begin(); it != p->end(); ++it)
{
std::string value;
it->getValue(value);
config.environment[it->name()] = value;
}
}
}
TntConfig::TntConfig()
: maxRequestSize(0),
maxRequestTime(600),
daemon(false),
minThreads(5),
maxThreads(100),
threadStartDelay(10),
queueSize(1000),
socketBufferSize(16384),
socketReadTimeout(10),
socketWriteTimeout(10000),
keepAliveTimeout(15000),
keepAliveMax(1000),
sessionTimeout(300),
listenBacklog(512),
listenRetry(5),
enableCompression(true),
minCompressSize(1024),
mimeDb("/etc/mime.types"),
maxUrlMapCache(8192),
defaultContentType("text/html; charset=UTF-8"),
backgroundTasks(5),
timerSleep(10)
{ }
TntConfig& TntConfig::it()
{
static TntConfig theConfig;
return theConfig;
}
}
<commit_msg>make ip address in listener section of tntnet.xml optional<commit_after>/*
* Copyright (C) 2012 Tommi Maekitalo
*
* 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.
*
* As a special exception, you may use this file as part of a free
* software library without restriction. Specifically, if other files
* instantiate templates or use macros or inline functions from this
* file, or you compile this file and link it with other files to
* produce an executable, this file does not by itself cause the
* resulting executable to be covered by the GNU General Public
* License. This exception does not however invalidate any other
* reasons why the executable file might be covered by the GNU Library
* General Public License.
*
* 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 <tnt/tntconfig.h>
namespace tnt
{
void operator>>= (const cxxtools::SerializationInfo& si, TntConfig::Mapping& mapping)
{
si.getMember("target") >>= mapping.target;
si.getMember("url") >>= mapping.url;
si.getMember("vhost", mapping.vhost);
si.getMember("method", mapping.method);
si.getMember("pathinfo", mapping.pathinfo);
bool ssl;
if (si.getMember("ssl", ssl))
mapping.ssl = ssl ? SSL_YES : SSL_NO;
else
mapping.ssl = SSL_ALL;
const cxxtools::SerializationInfo* args = si.findMember("args");
if (args)
{
for (cxxtools::SerializationInfo::ConstIterator it = args->begin(); it != args->end(); ++it)
{
std::string value;
it->getValue(value);
mapping.args[it->name()] = value;
}
}
}
void operator>>= (const cxxtools::SerializationInfo& si, TntConfig::Listener& listener)
{
si.getMember("ip", listener.ip);
if (!si.getMember("port", listener.port))
listener.port = 80;
}
void operator>>= (const cxxtools::SerializationInfo& si, TntConfig::SslListener& ssllistener)
{
si.getMember("ip", ssllistener.ip);
if (!si.getMember("port", ssllistener.port))
ssllistener.port = 443;
si.getMember("certificate") >>= ssllistener.certificate;
if (!si.getMember("key", ssllistener.key))
ssllistener.key = ssllistener.certificate;
}
void operator>>= (const cxxtools::SerializationInfo& si, TntConfig& config)
{
TntConfig::MappingsType mappings;
if (si.getMember("mappings", mappings))
config.mappings.insert(config.mappings.end(), mappings.begin(), mappings.end());
TntConfig::ListenersType listeners;
TntConfig::SslListenersType ssllisteners;
const cxxtools::SerializationInfo& lit = si.getMember("listeners");
for (cxxtools::SerializationInfo::ConstIterator it = lit.begin(); it != lit.end(); ++it)
{
if (it->findMember("certificate") != 0)
{
ssllisteners.resize(ssllisteners.size() + 1);
*it >>= ssllisteners.back();
}
else
{
listeners.resize(listeners.size() + 1);
*it >>= listeners.back();
}
}
config.listeners.insert(config.listeners.end(), listeners.begin(), listeners.end());
config.ssllisteners.insert(config.ssllisteners.end(), ssllisteners.begin(), ssllisteners.end());
if (config.listeners.empty() && config.ssllisteners.empty())
{
config.listeners.resize(1);
config.listeners.back().port = 80;
}
si.getMember("maxRequestSize", config.maxRequestSize);
si.getMember("maxRequestTime", config.maxRequestTime);
si.getMember("user", config.user);
si.getMember("group", config.group);
si.getMember("dir", config.dir);
si.getMember("chrootdir", config.chrootdir);
si.getMember("pidfile", config.pidfile);
si.getMember("daemon", config.daemon);
si.getMember("minThreads", config.minThreads);
si.getMember("maxThreads", config.maxThreads);
si.getMember("threadStartDelay", config.threadStartDelay);
si.getMember("queueSize", config.queueSize);
si.getMember("compPath", config.compPath);
si.getMember("socketBufferSize", config.socketBufferSize);
si.getMember("socketReadTimeout", config.socketReadTimeout);
si.getMember("socketWriteTimeout", config.socketWriteTimeout);
si.getMember("keepAliveTimeout", config.keepAliveTimeout);
si.getMember("keepAliveMax", config.keepAliveMax);
si.getMember("sessionTimeout", config.sessionTimeout);
si.getMember("listenBacklog", config.listenBacklog);
si.getMember("listenRetry", config.listenRetry);
si.getMember("enableCompression", config.enableCompression);
si.getMember("minCompressSize", config.minCompressSize);
si.getMember("mimeDb", config.mimeDb);
si.getMember("maxUrlMapCache", config.maxUrlMapCache);
si.getMember("defaultContentType", config.defaultContentType);
si.getMember("accessLog", config.accessLog);
si.getMember("errorLog", config.errorLog);
si.getMember("backgroundTasks", config.backgroundTasks);
si.getMember("timerSleep", config.timerSleep);
si.getMember("documentRoot", config.documentRoot);
si.getMember("includes", config.includes);
config.config = si;
const cxxtools::SerializationInfo* p = si.findMember("environment");
if (p)
{
for (cxxtools::SerializationInfo::ConstIterator it = p->begin(); it != p->end(); ++it)
{
std::string value;
it->getValue(value);
config.environment[it->name()] = value;
}
}
}
TntConfig::TntConfig()
: maxRequestSize(0),
maxRequestTime(600),
daemon(false),
minThreads(5),
maxThreads(100),
threadStartDelay(10),
queueSize(1000),
socketBufferSize(16384),
socketReadTimeout(10),
socketWriteTimeout(10000),
keepAliveTimeout(15000),
keepAliveMax(1000),
sessionTimeout(300),
listenBacklog(512),
listenRetry(5),
enableCompression(true),
minCompressSize(1024),
mimeDb("/etc/mime.types"),
maxUrlMapCache(8192),
defaultContentType("text/html; charset=UTF-8"),
backgroundTasks(5),
timerSleep(10)
{ }
TntConfig& TntConfig::it()
{
static TntConfig theConfig;
return theConfig;
}
}
<|endoftext|> |
<commit_before>#include "BonsaiCatalystData.h"
#include "vtkBonsaiPipeline.h"
//
#include "vtkCPDataDescription.h"
#include "vtkCPInputDataDescription.h"
#include "vtkCPProcessor.h"
#include "vtkCPPythonScriptPipeline.h"
#include "vtkPolyData.h"
#include "vtkFloatArray.h"
#include "vtkCellArray.h"
#include <vtkNew.h>
//----------------------------------------------------------------------------
BonsaiCatalystData::BonsaiCatalystData(const int rank, const int nrank, const MPI_Comm &comm) :
RendererData(rank, nrank, comm)
{
std::cout << "Creating Bonsai Catalyst Data adaptor" << std::endl;
this->cxxPipeline = vtkSmartPointer<vtkBonsaiPipeline>::New();
std::string temp = "/Users/biddisco/build/bcatalyst/bcat.vtk";
this->cxxPipeline->Initialize(1, temp);
isTimeDataSet = 0;
if(!coProcessor)
{
std::string cPythonFileName = "/Users/biddisco/build/bcatalyst/python-test-1.py";
std::string outFilename = "/Users/biddisco/build/bcatalyst/bdata-1.vtk";
// vtkCPPythonScriptPipeline* pipeline = vtkCPPythonScriptPipeline::New();
// pipeline->Initialize(cPythonFileName.c_str());
cxxPipeline = vtkSmartPointer<vtkBonsaiPipeline>::New();
cxxPipeline->Initialize(1,outFilename);
coProcessor = vtkSmartPointer<vtkCPProcessor>::New();
coProcessor->Initialize();
coProcessor->AddPipeline(cxxPipeline);
}
if(!coProcessorData)
{
coProcessorData = vtkSmartPointer<vtkCPDataDescription>::New();
coProcessorData->AddInput("input");
}
particles = vtkSmartPointer<vtkPolyData>::New();
}
//----------------------------------------------------------------------------
BonsaiCatalystData::~BonsaiCatalystData()
{
}
//----------------------------------------------------------------------------
void BonsaiCatalystData::coProcess(double time, unsigned int timeStep)
{
std::cout << "Calling coProcess" << std::endl;
if (!coProcessorData) {
coProcessorData = vtkSmartPointer<vtkCPDataDescription>::New();
coProcessorData->AddInput("input");
coProcessorData->SetTimeData(time, timeStep);
}
if(coProcessor->RequestDataDescription(coProcessorData.GetPointer()) != 0)
{
// BuildVTKDataStructures(grid, attributes);
// coProcessorData->GetInputDescriptionByName("input")->SetGrid(VTKGrid);
/*
struct particle_t
{
float posx, posy, posz;
IDType ID;
float attribute[NPROP];
};
*/
// create the points information,
// copy from particle_t struct into vtk array
// in next version, use vtk array adaptor for zero copy
// but first get working using a copy.
vtkNew<vtkFloatArray> pointArray;
pointArray->SetNumberOfComponents(3);
pointArray->SetNumberOfTuples(data.size());
float *pointarray = pointArray->GetPointer(0);
for (int i=0; i<data.size(); i++) {
// for (auto &i : data) {
pointarray[i*3+0] = data[i].posx;
pointarray[i*3+1] = data[i].posy;
pointarray[i*3+2] = data[i].posz;
}
//
// generate cells
//
if (1/*this->GenerateVertexCells*/)
{
vtkIdType Nt = data.size();
vtkSmartPointer<vtkCellArray> vertices = vtkSmartPointer<vtkCellArray>::New();
vtkIdType *cells = vertices->WritePointer(Nt, 2*Nt);
for (vtkIdType i=0; i<Nt; ++i)
{
cells[2*i] = 1;
cells[2*i+1] = i;
}
particles->SetVerts(vertices);
}
// pointArray->SetArray(pointsData, static_cast<vtkIdType>(numberOfPoints*3), 1);
vtkNew<vtkPoints> points;
points->SetData(pointArray.GetPointer());
particles->SetPoints(points.GetPointer());
// VTKGrid->SetPoints(points.GetPointer());
coProcessorData->GetInputDescriptionByName("input")->SetGrid(particles);
coProcessor->CoProcess(coProcessorData.GetPointer());
}
}
<commit_msg>Add export of field arrays to the particle dataset in catalyst<commit_after>#include "BonsaiCatalystData.h"
#include "vtkBonsaiPipeline.h"
//
#include "vtkCPDataDescription.h"
#include "vtkCPInputDataDescription.h"
#include "vtkCPProcessor.h"
#include "vtkCPPythonScriptPipeline.h"
#include "vtkPolyData.h"
#include "vtkPointData.h"
#include "vtkFloatArray.h"
#include "vtkCellArray.h"
#include <vtkNew.h>
//----------------------------------------------------------------------------
BonsaiCatalystData::BonsaiCatalystData(const int rank, const int nrank, const MPI_Comm &comm) :
RendererData(rank, nrank, comm)
{
std::cout << "Creating Bonsai Catalyst Data adaptor" << std::endl;
this->cxxPipeline = vtkSmartPointer<vtkBonsaiPipeline>::New();
std::string temp = "/Users/biddisco/build/bcatalyst/bcat.vtk";
this->cxxPipeline->Initialize(1, temp);
isTimeDataSet = 0;
if(!coProcessor)
{
std::string cPythonFileName = "/Users/biddisco/build/bcatalyst/python-test-1.py";
std::string outFilename = "/Users/biddisco/build/bcatalyst/bdata-1.vtk";
// vtkCPPythonScriptPipeline* pipeline = vtkCPPythonScriptPipeline::New();
// pipeline->Initialize(cPythonFileName.c_str());
cxxPipeline = vtkSmartPointer<vtkBonsaiPipeline>::New();
cxxPipeline->Initialize(1,outFilename);
coProcessor = vtkSmartPointer<vtkCPProcessor>::New();
coProcessor->Initialize();
coProcessor->AddPipeline(cxxPipeline);
}
if(!coProcessorData)
{
coProcessorData = vtkSmartPointer<vtkCPDataDescription>::New();
coProcessorData->AddInput("input");
}
particles = vtkSmartPointer<vtkPolyData>::New();
}
//----------------------------------------------------------------------------
BonsaiCatalystData::~BonsaiCatalystData()
{
}
//----------------------------------------------------------------------------
void BonsaiCatalystData::coProcess(double time, unsigned int timeStep)
{
std::cout << "Calling coProcess" << std::endl;
if (!coProcessorData) {
coProcessorData = vtkSmartPointer<vtkCPDataDescription>::New();
coProcessorData->AddInput("input");
coProcessorData->SetTimeData(time, timeStep);
}
if(coProcessor->RequestDataDescription(coProcessorData.GetPointer()) != 0)
{
// BuildVTKDataStructures(grid, attributes);
// coProcessorData->GetInputDescriptionByName("input")->SetGrid(VTKGrid);
/*
struct particle_t
{
float posx, posy, posz;
IDType ID;
float attribute[NPROP];
};
*/
// for each field array generate a vtk equivalent array
const char *names[] = {"MASS", "VEL", "RHO", "H"};
std::vector<vtkSmartPointer<vtkFloatArray> > fieldArrays;
for (int p = 0; p < NPROP; p++) {
fieldArrays.push_back(vtkSmartPointer<vtkFloatArray>::New());
fieldArrays[p]->SetNumberOfTuples(data.size());
fieldArrays[p]->SetName(names[p]);
}
// create the points information,
// copy from particle_t struct into vtk array
// in next version, use vtk array adaptor for zero copy
// but first get working using a copy.
vtkNew<vtkFloatArray> pointArray;
pointArray->SetNumberOfComponents(3);
pointArray->SetNumberOfTuples(data.size());
float *pointarray = pointArray->GetPointer(0);
for (int i=0; i<data.size(); i++) {
pointarray[i*3+0] = data[i].posx;
pointarray[i*3+1] = data[i].posy;
pointarray[i*3+2] = data[i].posz;
for (int p = 0; p < NPROP; p++) {
fieldArrays[p]->SetValue(i,data[i].attribute[p]);
}
}
for (int p = 0; p < NPROP; p++) {
particles->GetPointData()->AddArray(fieldArrays[p]);
}
//
// generate cells
//
if (1/*this->GenerateVertexCells*/)
{
vtkIdType Nt = data.size();
vtkSmartPointer<vtkCellArray> vertices = vtkSmartPointer<vtkCellArray>::New();
vtkIdType *cells = vertices->WritePointer(Nt, 2*Nt);
for (vtkIdType i=0; i<Nt; ++i)
{
cells[2*i] = 1;
cells[2*i+1] = i;
}
particles->SetVerts(vertices);
}
// pointArray->SetArray(pointsData, static_cast<vtkIdType>(numberOfPoints*3), 1);
vtkNew<vtkPoints> points;
points->SetData(pointArray.GetPointer());
particles->SetPoints(points.GetPointer());
// VTKGrid->SetPoints(points.GetPointer());
coProcessorData->GetInputDescriptionByName("input")->SetGrid(particles);
coProcessor->CoProcess(coProcessorData.GetPointer());
}
}
<|endoftext|> |
<commit_before>#include "classifier/svm/MKLClassification.h"
#include "classifier/svm/SVM_light.h"
#include "classifier/svm/LibSVM.h"
CMKLClassification::CMKLClassification(CSVM* s) : CMKL(s)
{
if (!s)
{
#ifdef USE_SVMLIGHT
s=new CSVMLight();
#endif //USE_SVMLIGHT
if (!s)
s=new CLibSVM();
set_svm(s);
}
}
CMKLClassification::~CMKLClassification()
{
}
float64_t CMKLClassification::compute_sum_alpha()
{
float64_t suma=0;
int32_t nsv=svm->get_num_support_vectors();
for (int32_t i=0; i<nsv; i++)
suma+=CMath::abs(svm->get_alpha(i));
return suma;
}
void CMKLClassification::init_training()
{
ASSERT(labels && labels->get_num_labels() && labels->is_two_class_labeling());
}
<commit_msg>fix compile error w/o svmlight<commit_after>#include "classifier/svm/MKLClassification.h"
#ifdef USE_SVMLIGHT
#include "classifier/svm/SVM_light.h"
#endif //USE_SVMLIGHT
#include "classifier/svm/LibSVM.h"
CMKLClassification::CMKLClassification(CSVM* s) : CMKL(s)
{
if (!s)
{
#ifdef USE_SVMLIGHT
s=new CSVMLight();
#endif //USE_SVMLIGHT
if (!s)
s=new CLibSVM();
set_svm(s);
}
}
CMKLClassification::~CMKLClassification()
{
}
float64_t CMKLClassification::compute_sum_alpha()
{
float64_t suma=0;
int32_t nsv=svm->get_num_support_vectors();
for (int32_t i=0; i<nsv; i++)
suma+=CMath::abs(svm->get_alpha(i));
return suma;
}
void CMKLClassification::init_training()
{
ASSERT(labels && labels->get_num_labels() && labels->is_two_class_labeling());
}
<|endoftext|> |
<commit_before>#include <string>
struct person
{
std::string surname;
std::string name;
std::string year;
};
struct PersonHash
{
std::size_t operator()(person const & s) const
{
std::size_t h1 = std::hash<std::string>{}(s.surname);
std::size_t h2 = std::hash<std::string>{}(s.name);
std::size_t h3 = std::hash<std::string>{}(s.year);
return h1 ^ ((h2 ^ (h3 << 1)) << 1); // or use boost::hash_combine
}
};
bool operator==(const person & left, const person & right) {
return left.name == right.name && left.surname == right.surname && left.year == right.year;
}
std::ostream & operator<<(std::ostream & output, person const & _person)
{
output << _person.surname << " ";
output << _person.name << " ";
output << _person.year;
return output;
}
std::istream & operator>>(std::istream & input, person & _person)
{
input >> _person.surname;
input >> _person.name;
input >> _person.year;
return input;
}
person readPersonFromFile(std::string file_name, size_t index) {
person result;
std::ifstream file(file_name);
for (size_t i = 0; i < index + 1; i++) {
file >> result;
}
file.close();
return result;
}
<commit_msg>Update person.hpp<commit_after>#include <string>
const size_t n_literals = 27;
size_t letterI(const char letter, const bool is_capital) {
int first_letter_code = static_cast<int>(is_capital ? 'A' : 'a');
size_t result = static_cast<int>(letter) - first_letter_code + 1;
return result;
}
struct person {
char * str;
unsigned char name_i;
unsigned char name_length;
person() : str(nullptr) {
;
}
size_t i(size_t sort_i) const {
if (sort_i < name_length) {
return letterI(str[name_i + sort_i], sort_i == 0);
}
else {
return 0;
}
}
char * getName() {
char * temp = new char[name_length + 1];
strncpy(temp, &(str[name_i]), name_length);
temp[name_length] = '\0';
return temp;
} //Boost
void putStr(std::string const & _str) {
str = new char[_str.length() + 1];
strncpy(str, _str, _str.length());
str[_str.length()] = '\0';
}
~person() {
delete[] str;
}
};
std::ostream & operator<<(std::ostream & output, person const & _person)
{
output << _person.str << " ";
return output;
}
std::istream & operator>>(std::istream & input, person & _person)
{
input >> _person.str;
/*input >> _person.name;
input >> _person.year;*/
return input;
}
<|endoftext|> |
<commit_before>#include "joblistwidget.h"
#include "debug.h"
#include "restoredialog.h"
#include <QMessageBox>
JobListWidget::JobListWidget(QWidget *parent) : QListWidget(parent)
{
connect(this, &QListWidget::itemActivated, [&](QListWidgetItem *item) {
emit displayJobDetails(static_cast<JobListItem *>(item)->job());
});
}
JobListWidget::~JobListWidget()
{
clear();
}
void JobListWidget::backupSelectedItems()
{
if(selectedItems().isEmpty())
return;
auto confirm =
QMessageBox::question(this, tr("Confirm action"),
tr("Initiate backup for the %1 selected job(s)?")
.arg(selectedItems().count()));
if(confirm == QMessageBox::Yes)
{
foreach(QListWidgetItem *item, selectedItems())
{
if(item->isSelected())
{
JobPtr job = static_cast<JobListItem *>(item)->job();
emit backupJob(job->createBackupTask());
}
}
}
}
void JobListWidget::selectJob(JobPtr job)
{
if(job)
selectJobByRef(job->objectKey());
}
void JobListWidget::selectJobByRef(QString jobRef)
{
if(jobRef.isEmpty())
return;
clearSelection();
JobListItem *jobItem = static_cast<JobListItem *>(currentItem());
if(jobItem && (jobItem->job()->objectKey() == jobRef))
{
emit displayJobDetails(jobItem->job());
}
else
{
for(int i = 0; i < count(); ++i)
{
jobItem = static_cast<JobListItem *>(item(i));
if(jobItem && (jobItem->job()->objectKey() == jobRef))
{
setCurrentItem(jobItem);
emit displayJobDetails(jobItem->job());
break;
}
}
}
scrollToItem(currentItem(), QAbstractItemView::EnsureVisible);
}
void JobListWidget::backupAllJobs()
{
for(int i = 0; i < count(); ++i)
{
JobPtr job = static_cast<JobListItem *>(item(i))->job();
emit backupJob(job->createBackupTask());
}
}
void JobListWidget::backupItem()
{
if(sender())
{
JobPtr job = qobject_cast<JobListItem *>(sender())->job();
if(job)
{
emit backupJob(job->createBackupTask());
}
}
}
void JobListWidget::inspectItem()
{
if(sender())
{
emit displayJobDetails(qobject_cast<JobListItem *>(sender())->job());
}
}
void JobListWidget::restoreItem()
{
if(sender())
{
JobPtr job = qobject_cast<JobListItem *>(sender())->job();
if(!job->archives().isEmpty())
{
ArchivePtr archive = job->archives().first();
RestoreDialog restoreDialog(archive, this);
if(QDialog::Accepted == restoreDialog.exec())
emit restoreArchive(archive, restoreDialog.getOptions());
}
}
}
void JobListWidget::deleteItem()
{
execDeleteJob(qobject_cast<JobListItem *>(sender()));
}
void JobListWidget::execDeleteJob(JobListItem *jobItem)
{
if(jobItem)
{
bool purgeArchives = false;
JobPtr job = jobItem->job();
auto confirm =
QMessageBox::question(this, tr("Confirm action"),
tr("Are you sure you want to delete job "
"\"%1\" (this cannot be undone)?")
.arg(job->name()));
if(confirm == QMessageBox::Yes)
{
if(!job->archives().isEmpty())
{
auto confirmArchives =
QMessageBox::question(this, tr("Confirm action"),
tr("Also delete %1 archives "
"pertaining to this job (this "
"cannot be undone)?")
.arg(job->archives().count()));
if(confirmArchives == QMessageBox::Yes)
purgeArchives = true;
}
emit deleteJob(job, purgeArchives);
delete jobItem;
}
}
}
void JobListWidget::addJobs(QMap<QString, JobPtr> jobs)
{
clear();
foreach(JobPtr job, jobs)
{
addJob(job);
}
}
void JobListWidget::addJob(JobPtr job)
{
if(job)
{
JobListItem *item = new JobListItem(job);
connect(item, &JobListItem::requestBackup, this,
&JobListWidget::backupItem);
connect(item, &JobListItem::requestInspect, this,
&JobListWidget::inspectItem);
connect(item, &JobListItem::requestRestore, this,
&JobListWidget::restoreItem);
connect(item, &JobListItem::requestDelete, this,
&JobListWidget::deleteItem);
insertItem(count(), item);
setItemWidget(item, item->widget());
}
}
void JobListWidget::inspectSelectedItem()
{
if(!selectedItems().isEmpty())
emit displayJobDetails(static_cast<JobListItem *>(selectedItems().first())->job());
}
void JobListWidget::restoreSelectedItem()
{
if(!selectedItems().isEmpty())
{
JobPtr job = static_cast<JobListItem *>(selectedItems().first())->job();
if(!job->archives().isEmpty())
{
ArchivePtr archive = job->archives().first();
RestoreDialog restoreDialog(archive, this);
if(QDialog::Accepted == restoreDialog.exec())
emit restoreArchive(archive, restoreDialog.getOptions());
}
}
}
void JobListWidget::deleteSelectedItem()
{
if(!selectedItems().isEmpty())
execDeleteJob(static_cast<JobListItem *>(selectedItems().first()));
}
void JobListWidget::keyReleaseEvent(QKeyEvent *event)
{
switch(event->key())
{
case Qt::Key_Escape:
if(!selectedItems().isEmpty())
clearSelection();
else
QListWidget::keyReleaseEvent(event);
break;
default:
QListWidget::keyReleaseEvent(event);
}
}
<commit_msg>Fix issue with Job selection when jumping from Archives.<commit_after>#include "joblistwidget.h"
#include "debug.h"
#include "restoredialog.h"
#include <QMessageBox>
JobListWidget::JobListWidget(QWidget *parent) : QListWidget(parent)
{
connect(this, &QListWidget::itemActivated, [&](QListWidgetItem *item) {
emit displayJobDetails(static_cast<JobListItem *>(item)->job());
});
}
JobListWidget::~JobListWidget()
{
clear();
}
void JobListWidget::backupSelectedItems()
{
if(selectedItems().isEmpty())
return;
auto confirm =
QMessageBox::question(this, tr("Confirm action"),
tr("Initiate backup for the %1 selected job(s)?")
.arg(selectedItems().count()));
if(confirm == QMessageBox::Yes)
{
foreach(QListWidgetItem *item, selectedItems())
{
if(item->isSelected())
{
JobPtr job = static_cast<JobListItem *>(item)->job();
emit backupJob(job->createBackupTask());
}
}
}
}
void JobListWidget::selectJob(JobPtr job)
{
if(job)
selectJobByRef(job->objectKey());
}
void JobListWidget::selectJobByRef(QString jobRef)
{
if(jobRef.isEmpty())
return;
JobListItem *jobItem = static_cast<JobListItem *>(currentItem());
if(!(jobItem && (jobItem->job()->objectKey() == jobRef)))
{
jobItem = nullptr;
for(int i = 0; i < count(); ++i)
{
jobItem = static_cast<JobListItem *>(item(i));
if(jobItem && (jobItem->job()->objectKey() == jobRef))
break;
jobItem = nullptr;
}
}
if(jobItem)
{
clearSelection();
setCurrentItem(jobItem);
emit displayJobDetails(jobItem->job());
scrollToItem(currentItem(), QAbstractItemView::EnsureVisible);
}
}
void JobListWidget::backupAllJobs()
{
for(int i = 0; i < count(); ++i)
{
JobPtr job = static_cast<JobListItem *>(item(i))->job();
emit backupJob(job->createBackupTask());
}
}
void JobListWidget::backupItem()
{
if(sender())
{
JobPtr job = qobject_cast<JobListItem *>(sender())->job();
if(job)
{
emit backupJob(job->createBackupTask());
}
}
}
void JobListWidget::inspectItem()
{
if(sender())
{
emit displayJobDetails(qobject_cast<JobListItem *>(sender())->job());
}
}
void JobListWidget::restoreItem()
{
if(sender())
{
JobPtr job = qobject_cast<JobListItem *>(sender())->job();
if(!job->archives().isEmpty())
{
ArchivePtr archive = job->archives().first();
RestoreDialog restoreDialog(archive, this);
if(QDialog::Accepted == restoreDialog.exec())
emit restoreArchive(archive, restoreDialog.getOptions());
}
}
}
void JobListWidget::deleteItem()
{
execDeleteJob(qobject_cast<JobListItem *>(sender()));
}
void JobListWidget::execDeleteJob(JobListItem *jobItem)
{
if(jobItem)
{
bool purgeArchives = false;
JobPtr job = jobItem->job();
auto confirm =
QMessageBox::question(this, tr("Confirm action"),
tr("Are you sure you want to delete job "
"\"%1\" (this cannot be undone)?")
.arg(job->name()));
if(confirm == QMessageBox::Yes)
{
if(!job->archives().isEmpty())
{
auto confirmArchives =
QMessageBox::question(this, tr("Confirm action"),
tr("Also delete %1 archives "
"pertaining to this job (this "
"cannot be undone)?")
.arg(job->archives().count()));
if(confirmArchives == QMessageBox::Yes)
purgeArchives = true;
}
emit deleteJob(job, purgeArchives);
delete jobItem;
}
}
}
void JobListWidget::addJobs(QMap<QString, JobPtr> jobs)
{
clear();
foreach(JobPtr job, jobs)
{
addJob(job);
}
}
void JobListWidget::addJob(JobPtr job)
{
if(job)
{
JobListItem *item = new JobListItem(job);
connect(item, &JobListItem::requestBackup, this,
&JobListWidget::backupItem);
connect(item, &JobListItem::requestInspect, this,
&JobListWidget::inspectItem);
connect(item, &JobListItem::requestRestore, this,
&JobListWidget::restoreItem);
connect(item, &JobListItem::requestDelete, this,
&JobListWidget::deleteItem);
insertItem(count(), item);
setItemWidget(item, item->widget());
}
}
void JobListWidget::inspectSelectedItem()
{
if(!selectedItems().isEmpty())
emit displayJobDetails(static_cast<JobListItem *>(selectedItems().first())->job());
}
void JobListWidget::restoreSelectedItem()
{
if(!selectedItems().isEmpty())
{
JobPtr job = static_cast<JobListItem *>(selectedItems().first())->job();
if(!job->archives().isEmpty())
{
ArchivePtr archive = job->archives().first();
RestoreDialog restoreDialog(archive, this);
if(QDialog::Accepted == restoreDialog.exec())
emit restoreArchive(archive, restoreDialog.getOptions());
}
}
}
void JobListWidget::deleteSelectedItem()
{
if(!selectedItems().isEmpty())
execDeleteJob(static_cast<JobListItem *>(selectedItems().first()));
}
void JobListWidget::keyReleaseEvent(QKeyEvent *event)
{
switch(event->key())
{
case Qt::Key_Escape:
if(!selectedItems().isEmpty())
clearSelection();
else
QListWidget::keyReleaseEvent(event);
break;
default:
QListWidget::keyReleaseEvent(event);
}
}
<|endoftext|> |
<commit_before>// (C) Copyright Gennadiy Rozental 2012.
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
// See http://www.boost.org/libs/test for the library home page.
//
// File : $RCSfile$
//
// Version : $Revision$
//
// Description : defines the is_forward_iterable collection type trait
// ***************************************************************************
#ifndef BOOST_TEST_IS_FORWARD_ITERABLE_HPP_110612GER
#define BOOST_TEST_IS_FORWARD_ITERABLE_HPP_110612GER
#ifdef BOOST_NO_CXX11_DECLTYPE
// Boost
#include <boost/mpl/bool.hpp>
// STL
#include <list>
#include <vector>
#else
// Boost
#include <boost/utility/declval.hpp>
#include <boost/type_traits/is_same.hpp>
#include <boost/type_traits/remove_reference.hpp>
#include <boost/type_traits/remove_cv.hpp>
// STL
#include <utility>
#include <type_traits>
#endif
//____________________________________________________________________________//
namespace boost {
namespace unit_test {
// ************************************************************************** //
// ************** is_forward_iterable ************** //
// ************************************************************************** //
#ifdef BOOST_NO_CXX11_DECLTYPE
template<typename T>
struct is_forward_iterable : public mpl::false_ {};
template<typename T>
struct is_forward_iterable<T const> : public is_forward_iterable<T> {};
template<typename T>
struct is_forward_iterable<T&> : public is_forward_iterable<T> {};
template<typename T>
struct is_forward_iterable<std::vector<T> > : public mpl::true_ {};
template<typename T>
struct is_forward_iterable<std::list<T> > : public mpl::true_ {};
#else
namespace ut_detail {
template<typename T>
struct is_present : public mpl::true_ {};
// some compiler do not implement properly decltype non expression involving members (eg. VS2013)
// a workaround is to use -> decltype syntax.
template <class T>
struct has_member_size {
private:
struct nil_t;
template<typename U> static auto test(U*) -> decltype( boost::declval<U>().size() );
template<typename> static nil_t test(...);
public:
static bool const value = !std::is_same< decltype(test<T>(nullptr)), nil_t>::value;
};
template <class T>
struct has_member_begin {
private:
struct nil_t;
template<typename U> static auto test(U*) -> decltype( boost::declval<U>().begin() );
template<typename> static nil_t test(...);
public:
static bool const value = !std::is_same< decltype(test<T>(nullptr)), nil_t>::value;
};
template <class T, class enabled = void>
struct is_forward_iterable_impl : std::false_type
{};
template <class T>
struct is_forward_iterable_impl<
T,
typename std::enable_if<
is_present<typename T::const_iterator>::value &&
is_present<typename T::value_type>::value &&
has_member_size<T>::value &&
has_member_begin<T>::value &&
!is_same<typename remove_cv<typename T::value_type>::type,char>::value &&
!is_same<typename remove_cv<typename T::value_type>::type,wchar_t>::value
>::type
> : std::true_type
{};
} // namespace ut_detail
template<typename T>
struct is_forward_iterable {
typedef typename std::remove_reference<T>::type T_ref;
typedef ut_detail::is_forward_iterable_impl<T_ref> is_fwd_it_t;
typedef mpl::bool_<is_fwd_it_t::value> type;
enum { value = is_fwd_it_t::value };
};
#endif
} // namespace unit_test
} // namespace boost
#endif // BOOST_TEST_IS_FORWARD_ITERABLE_HPP_110612GER
<commit_msg>Narrowing the possible deficiencies of the compiler<commit_after>// (C) Copyright Gennadiy Rozental 2012.
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
// See http://www.boost.org/libs/test for the library home page.
//
// File : $RCSfile$
//
// Version : $Revision$
//
// Description : defines the is_forward_iterable collection type trait
// ***************************************************************************
#ifndef BOOST_TEST_IS_FORWARD_ITERABLE_HPP_110612GER
#define BOOST_TEST_IS_FORWARD_ITERABLE_HPP_110612GER
#ifdef BOOST_NO_CXX11_DECLTYPE
// Boost
#include <boost/mpl/bool.hpp>
// STL
#include <list>
#include <vector>
#include <map>
#include <set>
#else
// Boost
#include <boost/utility/declval.hpp>
#include <boost/type_traits/is_same.hpp>
#include <boost/type_traits/remove_reference.hpp>
#include <boost/type_traits/remove_cv.hpp>
// STL
#include <utility>
#include <type_traits>
#endif
//____________________________________________________________________________//
namespace boost {
namespace unit_test {
// ************************************************************************** //
// ************** is_forward_iterable ************** //
// ************************************************************************** //
#if defined(BOOST_NO_CXX11_DECLTYPE) || defined(BOOST_NO_CXX11_NULLPTR) || defined(BOOST_NO_CXX11_TRAILING_RESULT_TYPES)
template<typename T>
struct is_forward_iterable : public mpl::false_ {};
template<typename T>
struct is_forward_iterable<T const> : public is_forward_iterable<T> {};
template<typename T>
struct is_forward_iterable<T&> : public is_forward_iterable<T> {};
template<typename T, typename A>
struct is_forward_iterable< std::vector<T, A> > : public mpl::true_ {};
template<typename T, typename A>
struct is_forward_iterable< std::list<T, A> > : public mpl::true_ {};
template<typename K, typename V, typename C, typename A>
struct is_forward_iterable< std::map<K, V, C, A> > : public mpl::true_ {};
template<typename K, typename C, typename A>
struct is_forward_iterable< std::set<K, C, A> > : public mpl::true_ {};
#else
namespace ut_detail {
template<typename T>
struct is_present : public mpl::true_ {};
// some compiler do not implement properly decltype non expression involving members (eg. VS2013)
// a workaround is to use -> decltype syntax.
template <class T>
struct has_member_size {
private:
struct nil_t;
template<typename U> static auto test(U*) -> decltype( boost::declval<U>().size() );
template<typename> static nil_t test(...);
public:
static bool const value = !std::is_same< decltype(test<T>(nullptr)), nil_t>::value;
};
template <class T>
struct has_member_begin {
private:
struct nil_t;
template<typename U> static auto test(U*) -> decltype( boost::declval<U>().begin() );
template<typename> static nil_t test(...);
public:
static bool const value = !std::is_same< decltype(test<T>(nullptr)), nil_t>::value;
};
template <class T, class enabled = void>
struct is_forward_iterable_impl : std::false_type
{};
template <class T>
struct is_forward_iterable_impl<
T,
typename std::enable_if<
is_present<typename T::const_iterator>::value &&
is_present<typename T::value_type>::value &&
has_member_size<T>::value &&
has_member_begin<T>::value &&
!is_same<typename remove_cv<typename T::value_type>::type,char>::value &&
!is_same<typename remove_cv<typename T::value_type>::type,wchar_t>::value
>::type
> : std::true_type
{};
} // namespace ut_detail
template<typename T>
struct is_forward_iterable {
typedef typename std::remove_reference<T>::type T_ref;
typedef ut_detail::is_forward_iterable_impl<T_ref> is_fwd_it_t;
typedef mpl::bool_<is_fwd_it_t::value> type;
enum { value = is_fwd_it_t::value };
};
#endif
} // namespace unit_test
} // namespace boost
#endif // BOOST_TEST_IS_FORWARD_ITERABLE_HPP_110612GER
<|endoftext|> |
<commit_before>#include "scales.hpp"
#include "mercator.hpp"
#include "../base/math.hpp"
#include "../std/algorithm.hpp"
namespace scales
{
double GetScaleLevelD(double ratio)
{
double const level = min(static_cast<double>(GetUpperScale()), log(ratio) / log(2.0));
return (level < 0.0 ? 0.0 : level);
}
double GetScaleLevelD(m2::RectD const & r)
{
// TODO: fix scale factors for mercator projection
double const dx = (MercatorBounds::maxX - MercatorBounds::minX) / r.SizeX();
double const dy = (MercatorBounds::maxY - MercatorBounds::minY) / r.SizeY();
// get the average ratio
return GetScaleLevelD((dx + dy) / 2.0);
}
int GetScaleLevel(double ratio)
{
return my::rounds(GetScaleLevelD(ratio));
}
int GetScaleLevel(m2::RectD const & r)
{
return my::rounds(GetScaleLevelD(r));
}
double GetRationForLevel(double level)
{
return max(0.0, pow(2.0, level));
}
m2::RectD GetRectForLevel(double level, m2::PointD const & center)
{
double const dy = GetRationForLevel(level);
double const dx = dy;
ASSERT_GREATER ( dy, 0.0, () );
ASSERT_GREATER ( dx, 0.0, () );
double const xL = (MercatorBounds::maxX - MercatorBounds::minX) / (2.0 * dx);
double const yL = (MercatorBounds::maxY - MercatorBounds::minY) / (2.0 * dy);
ASSERT_GREATER ( xL, 0.0, () );
ASSERT_GREATER ( yL, 0.0, () );
return m2::RectD(MercatorBounds::ClampX(center.x - xL),
MercatorBounds::ClampY(center.y - yL),
MercatorBounds::ClampX(center.x + xL),
MercatorBounds::ClampY(center.y + yL));
}
namespace
{
double GetEpsilonImpl(long level, double pixelTolerance)
{
return (MercatorBounds::maxX - MercatorBounds::minX) * pixelTolerance / double(256L << level);
}
}
double GetEpsilonForLevel(int level)
{
return GetEpsilonImpl(level, 7);
}
double GetEpsilonForSimplify(int level)
{
// Keep better geometries on highest zoom to allow scaling them deeper
if (level == GetUpperScale())
return GetEpsilonImpl(level, 0.4);
// Keep crude geometries for all other zooms
else
return GetEpsilonImpl(level, 1.3);
}
bool IsGoodForLevel(int level, m2::RectD const & r)
{
// assume that feature is always visible in upper scale
return (level == GetUpperScale() || max(r.SizeX(), r.SizeY()) > GetEpsilonForLevel(level));
}
}
<commit_msg>Return back INITIAL_LEVEL for scales - current styles are optimized for this increment.<commit_after>#include "scales.hpp"
#include "mercator.hpp"
#include "../base/math.hpp"
#include "../std/algorithm.hpp"
namespace scales
{
static const int INITIAL_LEVEL = 1;
double GetScaleLevelD(double ratio)
{
double const level = min(static_cast<double>(GetUpperScale()), log(ratio) / log(2.0) + INITIAL_LEVEL);
return (level < 0.0 ? 0.0 : level);
}
double GetScaleLevelD(m2::RectD const & r)
{
// TODO: fix scale factors for mercator projection
double const dx = (MercatorBounds::maxX - MercatorBounds::minX) / r.SizeX();
double const dy = (MercatorBounds::maxY - MercatorBounds::minY) / r.SizeY();
// get the average ratio
return GetScaleLevelD((dx + dy) / 2.0);
}
int GetScaleLevel(double ratio)
{
return my::rounds(GetScaleLevelD(ratio));
}
int GetScaleLevel(m2::RectD const & r)
{
return my::rounds(GetScaleLevelD(r));
}
double GetRationForLevel(double level)
{
if (level < INITIAL_LEVEL)
level = INITIAL_LEVEL;
return pow(2.0, level - INITIAL_LEVEL);
}
m2::RectD GetRectForLevel(double level, m2::PointD const & center)
{
double const dy = GetRationForLevel(level);
double const dx = dy;
ASSERT_GREATER ( dy, 0.0, () );
ASSERT_GREATER ( dx, 0.0, () );
double const xL = (MercatorBounds::maxX - MercatorBounds::minX) / (2.0 * dx);
double const yL = (MercatorBounds::maxY - MercatorBounds::minY) / (2.0 * dy);
ASSERT_GREATER ( xL, 0.0, () );
ASSERT_GREATER ( yL, 0.0, () );
return m2::RectD(MercatorBounds::ClampX(center.x - xL),
MercatorBounds::ClampY(center.y - yL),
MercatorBounds::ClampX(center.x + xL),
MercatorBounds::ClampY(center.y + yL));
}
namespace
{
double GetEpsilonImpl(long level, double pixelTolerance)
{
return (MercatorBounds::maxX - MercatorBounds::minX) * pixelTolerance / double(256L << level);
}
}
double GetEpsilonForLevel(int level)
{
return GetEpsilonImpl(level, 7);
}
double GetEpsilonForSimplify(int level)
{
// Keep better geometries on highest zoom to allow scaling them deeper
if (level == GetUpperScale())
return GetEpsilonImpl(level, 0.4);
// Keep crude geometries for all other zooms
else
return GetEpsilonImpl(level, 1.3);
}
bool IsGoodForLevel(int level, m2::RectD const & r)
{
// assume that feature is always visible in upper scale
return (level == GetUpperScale() || max(r.SizeX(), r.SizeY()) > GetEpsilonForLevel(level));
}
}
<|endoftext|> |
<commit_before>// Xerus - A General Purpose Tensor Library
// Copyright (C) 2014-2015 Benjamin Huber and Sebastian Wolf.
//
// Xerus 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.
//
// Xerus 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 Xerus. If not, see <http://www.gnu.org/licenses/>.
//
// For further information on Xerus visit https://libXerus.org
// or contact us at contact@libXerus.org.
/**
* @file
* @brief Implementation of the PerformanceData class.
*/
#include <string>
#include <fstream>
#include <xerus/performanceData.h>
#include <xerus/misc/missingFunctions.h>
namespace xerus {
PerformanceData::Histogram::Histogram(const std::vector< xerus::PerformanceData::DataPoint >& _data, const xerus::value_t _base) : base(_base), totalTime(0) {
for (size_t i = 1; i<_data.size(); ++i) {
if (_data[i].residual >= _data[i-1].residual) {
continue;
}
// assume x_2 = x_1 * 2^(-alpha * delta-t)
value_t relativeChange = _data[i].residual/_data[i-1].residual;
value_t exponent = log(relativeChange) / log(2);
size_t delta_t = _data[i].elapsedTime - _data[i-1].elapsedTime;
value_t rate = - exponent / value_t(delta_t);
int logRate = int(log(rate)/log(base));
buckets[logRate] += delta_t;
totalTime += delta_t;
}
}
PerformanceData::Histogram::Histogram(const xerus::value_t _base) : base(_base), totalTime(0) {}
PerformanceData::Histogram PerformanceData::Histogram::operator+=(const Histogram &_other) {
REQUIRE(misc::approx_equal(_other.base, base), "only histograms of identical base can be added");
for (const auto &h : _other.buckets) {
buckets[h.first] += h.second;
}
totalTime += _other.totalTime;
return *this;
}
PerformanceData::Histogram PerformanceData::Histogram::read_from_file(const std::string &_fileName) {
std::ifstream in(_fileName);
Histogram result(0.0);
std::string line;
std::getline(in, line);
REQUIRE(line == "# raw data:", "unknown histogram file format " << _fileName); //TODO this should throw an exception
char c;
in >> c;
REQUIRE(c == '#', "missing information in histogram file " << _fileName);
in >> result.base >> result.totalTime;
std::getline(in, line); // read in rest of this line
std::getline(in, line); // line now contains all buckets
std::stringstream bucketData(line);
bucketData >> c;
REQUIRE(c == '#', "missing information in histogram file " << _fileName);
int bucketIndex;
while (bucketData >> bucketIndex) {
size_t count;
if (!(bucketData >> count)) {
LOG(fatal, "missing bucket count in histogram file " << _fileName);
}
result.buckets[bucketIndex] = count;
}
size_t accountedTime=0;
for (auto &h : result.buckets) {
accountedTime += h.second;
}
REQUIRE(accountedTime == result.totalTime, "histogram data inconsistent in file " << _fileName);
return result;
}
void PerformanceData::Histogram::dump_to_file(const std::string &_fileName) const {
std::ofstream out(_fileName);
out << "# raw data:\n";
out << "# " << base << ' ' << totalTime << '\n';
out << '#';
for (auto &h : buckets) {
out << ' ' << h.first << ' ' << h.second;
}
out << "\n# plotable data:\n";
for (auto &h : buckets) {
out << pow(base, h.first) << " " << double(h.second)/double(totalTime) << '\n';
}
out.close();
}
void PerformanceData::add(const size_t _itrCount, const xerus::value_t _residual, const std::vector<size_t> _ranks, const size_t _flags) {
if (active) {
if (startTime == ~0ul) {
start();
}
data.emplace_back(_itrCount, get_runtime(), _residual, _ranks, _flags);
if(printProgress) {
LOG(PerformanceData, "Iteration " << std::setw(4) << std::setfill(' ') << _itrCount
<< " Time: " << std::setw(6) << std::setfill(' ') << std::fixed << double(data.back().elapsedTime)*1e-6
<< "s Residual: " << std::setw(11) << std::setfill(' ') << std::scientific << _residual << " Flags: " << _flags << " Ranks: " << _ranks);
}
}
}
void PerformanceData::add(const xerus::value_t _residual, const TensorNetwork::RankTuple _ranks, const size_t _flags) {
if (active) {
if (data.empty()) {
add(0, _residual, _ranks, _flags);
} else {
add(data.back().iterationCount+1, _residual, _ranks, _flags);
}
}
}
void PerformanceData::dump_to_file(const std::string &_fileName) const {
std::string header;
header += "# ";
header += additionalInformation;
misc::replace(header, "\n", "\n# ");
header += "\n# \n#itr \ttime[us] \tresidual \tflags \tranks...\n";
std::ofstream out(_fileName);
out << header;
for (const DataPoint &d : data) {
out << d.iterationCount << '\t' << d.elapsedTime << '\t' << d.residual << '\t' << d.flags;
for (size_t r : d.ranks) {
out << '\t' << r;
}
out << '\n';
}
out.close();
}
PerformanceData::Histogram PerformanceData::get_histogram(const xerus::value_t _base) const {
return Histogram(data, _base);
}
PerformanceData NoPerfData(false);
}
<commit_msg>Histogram::dump_to_file now prints empty buckets as well<commit_after>// Xerus - A General Purpose Tensor Library
// Copyright (C) 2014-2015 Benjamin Huber and Sebastian Wolf.
//
// Xerus 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.
//
// Xerus 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 Xerus. If not, see <http://www.gnu.org/licenses/>.
//
// For further information on Xerus visit https://libXerus.org
// or contact us at contact@libXerus.org.
/**
* @file
* @brief Implementation of the PerformanceData class.
*/
#include <string>
#include <fstream>
#include <xerus/performanceData.h>
#include <xerus/misc/missingFunctions.h>
namespace xerus {
PerformanceData::Histogram::Histogram(const std::vector< xerus::PerformanceData::DataPoint >& _data, const xerus::value_t _base) : base(_base), totalTime(0) {
for (size_t i = 1; i<_data.size(); ++i) {
if (_data[i].residual >= _data[i-1].residual) {
continue;
}
// assume x_2 = x_1 * 2^(-alpha * delta-t)
value_t relativeChange = _data[i].residual/_data[i-1].residual;
value_t exponent = log(relativeChange) / log(2);
size_t delta_t = _data[i].elapsedTime - _data[i-1].elapsedTime;
value_t rate = - exponent / value_t(delta_t);
int logRate = int(log(rate)/log(base));
buckets[logRate] += delta_t;
totalTime += delta_t;
}
}
PerformanceData::Histogram::Histogram(const xerus::value_t _base) : base(_base), totalTime(0) {}
PerformanceData::Histogram PerformanceData::Histogram::operator+=(const Histogram &_other) {
REQUIRE(misc::approx_equal(_other.base, base), "only histograms of identical base can be added");
for (const auto &h : _other.buckets) {
buckets[h.first] += h.second;
}
totalTime += _other.totalTime;
return *this;
}
PerformanceData::Histogram PerformanceData::Histogram::read_from_file(const std::string &_fileName) {
std::ifstream in(_fileName);
Histogram result(0.0);
std::string line;
std::getline(in, line);
REQUIRE(line == "# raw data:", "unknown histogram file format " << _fileName); //TODO this should throw an exception
char c;
in >> c;
REQUIRE(c == '#', "missing information in histogram file " << _fileName);
in >> result.base >> result.totalTime;
std::getline(in, line); // read in rest of this line
std::getline(in, line); // line now contains all buckets
std::stringstream bucketData(line);
bucketData >> c;
REQUIRE(c == '#', "missing information in histogram file " << _fileName);
int bucketIndex;
while (bucketData >> bucketIndex) {
size_t count;
if (!(bucketData >> count)) {
LOG(fatal, "missing bucket count in histogram file " << _fileName);
}
result.buckets[bucketIndex] = count;
}
size_t accountedTime=0;
for (auto &h : result.buckets) {
accountedTime += h.second;
}
REQUIRE(accountedTime == result.totalTime, "histogram data inconsistent in file " << _fileName);
return result;
}
void PerformanceData::Histogram::dump_to_file(const std::string &_fileName) const {
std::ofstream out(_fileName);
out << "# raw data:\n";
out << "# " << base << ' ' << totalTime << '\n';
out << '#';
for (auto &h : buckets) {
out << ' ' << h.first << ' ' << h.second;
}
out << "\n# plotable data:\n";
int firstOutput = buckets.begin()->first - 1;
int lastOutput = buckets.rbegin()->first + 1;
for (int i=firstOutput; i<=lastOutput; ++i) {
out << pow(base, i) << ' ';
if (buckets.count(i) > 0) {
out << double(buckets.find(i)->second)/double(totalTime) << '\n';
} else {
out << "0\n";
}
}
out.close();
}
void PerformanceData::add(const size_t _itrCount, const xerus::value_t _residual, const std::vector<size_t> _ranks, const size_t _flags) {
if (active) {
if (startTime == ~0ul) {
start();
}
data.emplace_back(_itrCount, get_runtime(), _residual, _ranks, _flags);
if(printProgress) {
LOG(PerformanceData, "Iteration " << std::setw(4) << std::setfill(' ') << _itrCount
<< " Time: " << std::setw(6) << std::setfill(' ') << std::fixed << double(data.back().elapsedTime)*1e-6
<< "s Residual: " << std::setw(11) << std::setfill(' ') << std::scientific << _residual << " Flags: " << _flags << " Ranks: " << _ranks);
}
}
}
void PerformanceData::add(const xerus::value_t _residual, const TensorNetwork::RankTuple _ranks, const size_t _flags) {
if (active) {
if (data.empty()) {
add(0, _residual, _ranks, _flags);
} else {
add(data.back().iterationCount+1, _residual, _ranks, _flags);
}
}
}
void PerformanceData::dump_to_file(const std::string &_fileName) const {
std::string header;
header += "# ";
header += additionalInformation;
misc::replace(header, "\n", "\n# ");
header += "\n# \n#itr \ttime[us] \tresidual \tflags \tranks...\n";
std::ofstream out(_fileName);
out << header;
for (const DataPoint &d : data) {
out << d.iterationCount << '\t' << d.elapsedTime << '\t' << d.residual << '\t' << d.flags;
for (size_t r : d.ranks) {
out << '\t' << r;
}
out << '\n';
}
out.close();
}
PerformanceData::Histogram PerformanceData::get_histogram(const xerus::value_t _base) const {
return Histogram(data, _base);
}
PerformanceData NoPerfData(false);
}
<|endoftext|> |
<commit_before>#include <Arduino.h>
#include <ESP8266WiFi.h>
#include <WiFiUdp.h>
#include <NeoPixelBus.h>
#define WIFI_SSID "****"
#define WIFI_PASS "****"
#define HORIZONTAL_LEDS 60
#define VERTICAL_LEDS 34
WiFiUDP *udp_socket;
NeoPixelBus<NeoGrbFeature, NeoEsp8266Dma800KbpsMethod> *strip;
void ICACHE_FLASH_ATTR setup() {
Serial.begin(115200);
strip = new NeoPixelBus<NeoGrbFeature, NeoEsp8266Dma800KbpsMethod>(2 * (HORIZONTAL_LEDS + VERTICAL_LEDS), 0);
strip->Begin();
WiFi.mode(WIFI_AP);
WiFi.begin(WIFI_SSID, WIFI_PASS);
while (WiFi.status() != WL_CONNECTED) {
delay(50);
Serial.print(".");
}
udp_socket = new WiFiUDP();
udp_socket->begin(65000);
delay(100);
}
void loop() {
if (udp_socket->parsePacket()) {
uint8_t buffer[6 * (HORIZONTAL_LEDS + VERTICAL_LEDS)];
udp_socket->readBytes(buffer, 6 * (HORIZONTAL_LEDS + VERTICAL_LEDS));
for (uint16_t p = 0; p < 2 * (HORIZONTAL_LEDS + VERTICAL_LEDS); p++) {
strip->SetPixelColor(p, RgbColor(buffer[0 + 3 * p], buffer[1 + 3 * p], buffer[2 + 3 * p]));
}
strip->Show();
}
yield(); // WATCHDOG/WIFI feed
}
<commit_msg>Ambi-Light auto-shutdown of leds<commit_after>#include <Arduino.h>
#include <ESP8266WiFi.h>
#include <WiFiUdp.h>
#include <NeoPixelBus.h>
#define WIFI_SSID "****"
#define WIFI_PASS "****"
#define HORIZONTAL_LEDS 60
#define VERTICAL_LEDS 34
static WiFiUDP *udp_socket;
static int missed_ticks = 0;
static NeoPixelBus<NeoGrbFeature, NeoEsp8266Dma800KbpsMethod> *strip;
void ICACHE_FLASH_ATTR setup() {
Serial.begin(115200);
strip = new NeoPixelBus<NeoGrbFeature, NeoEsp8266Dma800KbpsMethod>(2 * (HORIZONTAL_LEDS + VERTICAL_LEDS), 0);
strip->Begin();
WiFi.mode(WIFI_AP);
WiFi.begin(WIFI_SSID, WIFI_PASS);
while (WiFi.status() != WL_CONNECTED) {
delay(50);
Serial.print(".");
}
udp_socket = new WiFiUDP();
udp_socket->begin(65000);
delay(100);
}
void loop() {
if (udp_socket->parsePacket()) {
if (missed_ticks != 0) missed_ticks = 0;
uint8_t buffer[6 * (HORIZONTAL_LEDS + VERTICAL_LEDS)];
udp_socket->readBytes(buffer, 6 * (HORIZONTAL_LEDS + VERTICAL_LEDS));
for (uint16_t p = 0; p < 2 * (HORIZONTAL_LEDS + VERTICAL_LEDS); p++) {
strip->SetPixelColor(p, RgbColor(buffer[0 + 3 * p], buffer[1 + 3 * p], buffer[2 + 3 * p]));
}
strip->Show();
} else if (missed_ticks >= 500000) {
for (uint16_t p = 0; p < 2 * (HORIZONTAL_LEDS + VERTICAL_LEDS); p++) {
strip->SetPixelColor(p, RgbColor(0, 0, 0));
}
strip->Show();
missed_ticks = -1;
} else if (missed_ticks >= 0) {
missed_ticks++;
} else {
delay(500);
}
yield(); // WATCHDOG/WIFI feed
}
<|endoftext|> |
<commit_before>#include "rapid_pbd/action_names.h"
#include "rapid_pbd/fetch_actions.h"
#include "rapid_pbd_msgs/ArmControllerState.h"
#include "rapid_pbd_msgs/FreezeArm.h"
#include "rapid_pbd_msgs/RelaxArm.h"
#include "robot_controllers_msgs/QueryControllerStatesAction.h"
#include "ros/ros.h"
namespace pbd = rapid::pbd;
namespace msgs = rapid_pbd_msgs;
int main(int argc, char** argv) {
ros::init(argc, argv, "fetch_actuator_server");
ros::NodeHandle nh;
ros::Publisher arm_controller_state_pub =
nh.advertise<msgs::ArmControllerState>(pbd::kArmControllerStateTopic, 5,
true);
actionlib::SimpleActionClient<
robot_controllers_msgs::QueryControllerStatesAction>
client(pbd::fetch::kControllerActionName, true);
pbd::fetch::ArmControllerManager arm_controller_manager(
arm_controller_state_pub, &client);
ros::ServiceServer freeze_srv = nh.advertiseService(
pbd::kFreezeArmService, &pbd::fetch::ArmControllerManager::HandleFreeze,
&arm_controller_manager);
ros::ServiceServer relax_srv = nh.advertiseService(
pbd::kRelaxArmService, &pbd::fetch::ArmControllerManager::HandleRelax,
&arm_controller_manager);
arm_controller_manager.Start();
ros::spin();
return 0;
}
<commit_msg>Wait for arm controller server on startup.<commit_after>#include "rapid_pbd/action_names.h"
#include "rapid_pbd/fetch_actions.h"
#include "rapid_pbd_msgs/ArmControllerState.h"
#include "rapid_pbd_msgs/FreezeArm.h"
#include "rapid_pbd_msgs/RelaxArm.h"
#include "robot_controllers_msgs/QueryControllerStatesAction.h"
#include "ros/ros.h"
namespace pbd = rapid::pbd;
namespace msgs = rapid_pbd_msgs;
int main(int argc, char** argv) {
ros::init(argc, argv, "fetch_actuator_server");
ros::NodeHandle nh;
ros::Publisher arm_controller_state_pub =
nh.advertise<msgs::ArmControllerState>(pbd::kArmControllerStateTopic, 5,
true);
actionlib::SimpleActionClient<
robot_controllers_msgs::QueryControllerStatesAction>
client(pbd::fetch::kControllerActionName, true);
while (ros::ok() && !client.waitForServer(ros::Duration(5.0))) {
ROS_WARN("Waiting for arm controller manager.");
}
pbd::fetch::ArmControllerManager arm_controller_manager(
arm_controller_state_pub, &client);
ros::ServiceServer freeze_srv = nh.advertiseService(
pbd::kFreezeArmService, &pbd::fetch::ArmControllerManager::HandleFreeze,
&arm_controller_manager);
ros::ServiceServer relax_srv = nh.advertiseService(
pbd::kRelaxArmService, &pbd::fetch::ArmControllerManager::HandleRelax,
&arm_controller_manager);
arm_controller_manager.Start();
ros::spin();
return 0;
}
<|endoftext|> |
<commit_before>/*
* Software License Agreement (Apache License)
*
* Copyright (c) 2014, Dan Solomon
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <console_bridge/console.h>
#include "descartes_moveit/moveit_state_adapter.h"
#include "descartes_core/pretty_print.hpp"
#include "descartes_moveit/seed_search.h"
#include <eigen_conversions/eigen_msg.h>
#include <random_numbers/random_numbers.h>
#include <ros/assert.h>
#include <sstream>
const static int SAMPLE_ITERATIONS = 10;
namespace
{
bool getJointVelocityLimits(const moveit::core::RobotState& state, const std::string& group_name,
std::vector<double>& output)
{
std::vector<double> result;
auto models = state.getJointModelGroup(group_name)->getActiveJointModels();
for (const moveit::core::JointModel* model : models)
{
const auto& bounds = model->getVariableBounds();
// Check to see if there is a single bounds constraint (more might indicate
// not revolute joint)
if (model->getType() != moveit::core::JointModel::REVOLUTE &&
model->getType() != moveit::core::JointModel::PRISMATIC)
{
ROS_ERROR_STREAM(__FUNCTION__ << " Unexpected joint type. Currently works only"
" with single axis prismatic or revolute joints.");
return false;
}
else
{
result.push_back(bounds[0].max_velocity_);
}
}
output = result;
return true;
}
} // end anon namespace
namespace descartes_moveit
{
MoveitStateAdapter::MoveitStateAdapter() : world_to_root_(Eigen::Affine3d::Identity())
{
}
bool MoveitStateAdapter::initialize(const std::string& robot_description, const std::string& group_name,
const std::string& world_frame, const std::string& tcp_frame)
{
// Initialize MoveIt state objects
robot_model_loader_.reset(new robot_model_loader::RobotModelLoader(robot_description));
auto model = robot_model_loader_->getModel();
if (!model)
{
logError("Failed to load robot model from robot description parameter: %s", robot_description.c_str());
return false;
}
return initialize(model, group_name, world_frame, tcp_frame);
}
bool MoveitStateAdapter::initialize(robot_model::RobotModelConstPtr robot_model, const std::string &group_name,
const std::string &world_frame, const std::string &tcp_frame)
{
robot_model_ptr_ = robot_model;
robot_state_.reset(new moveit::core::RobotState(robot_model_ptr_));
robot_state_->setToDefaultValues();
planning_scene_.reset(new planning_scene::PlanningScene(robot_model));
joint_group_ = robot_model_ptr_->getJointModelGroup(group_name);
// Assign robot frames
group_name_ = group_name;
tool_frame_ = tcp_frame;
world_frame_ = world_frame;
// Validate our model inputs w/ URDF
if (!joint_group_)
{
logError("%s: Joint group '%s' does not exist in robot model", __FUNCTION__, group_name_.c_str());
std::stringstream msg;
msg << "Possible group names: " << robot_state_->getRobotModel()->getJointModelGroupNames();
logError(msg.str().c_str());
return false;
}
const auto& link_names = joint_group_->getLinkModelNames();
if (tool_frame_ != link_names.back())
{
logError("%s: Tool frame '%s' does not match group tool frame '%s', functionality"
"will be implemented in the future",
__FUNCTION__, tool_frame_.c_str(), link_names.back().c_str());
return false;
}
if (!::getJointVelocityLimits(*robot_state_, group_name, velocity_limits_))
{
logWarn("%s: Could not determine velocity limits of RobotModel from MoveIt", __FUNCTION__);
}
if (seed_states_.empty())
{
seed_states_ = seed::findRandomSeeds(*robot_state_, group_name_, SAMPLE_ITERATIONS);
logDebug("Generated %lu random seeds", static_cast<unsigned long>(seed_states_.size()));
}
auto model_frame = robot_state_->getRobotModel()->getModelFrame();
if (world_frame_ != model_frame)
{
logInform("%s: World frame '%s' does not match model root frame '%s', all poses will be"
" transformed to world frame '%s'",
__FUNCTION__, world_frame_.c_str(), model_frame.c_str(), world_frame_.c_str());
Eigen::Affine3d root_to_world = robot_state_->getFrameTransform(world_frame_);
world_to_root_ = descartes_core::Frame(root_to_world.inverse());
}
return true;
}
bool MoveitStateAdapter::getIK(const Eigen::Affine3d& pose, const std::vector<double>& seed_state,
std::vector<double>& joint_pose) const
{
robot_state_->setJointGroupPositions(group_name_, seed_state);
return getIK(pose, joint_pose);
}
bool MoveitStateAdapter::getIK(const Eigen::Affine3d& pose, std::vector<double>& joint_pose) const
{
bool rtn = false;
// transform to group base
Eigen::Affine3d tool_pose = world_to_root_.frame * pose;
if (robot_state_->setFromIK(joint_group_, tool_pose, tool_frame_))
{
robot_state_->copyJointGroupPositions(group_name_, joint_pose);
if (!isValid(joint_pose))
{
ROS_DEBUG_STREAM("Robot joint pose is invalid");
}
else
{
rtn = true;
}
}
else
{
rtn = false;
}
return rtn;
}
bool MoveitStateAdapter::getAllIK(const Eigen::Affine3d& pose, std::vector<std::vector<double> >& joint_poses) const
{
// The minimum difference between solutions should be greater than the search discretization
// used by the IK solver. This value is multiplied by 4 to remove any chance that a solution
// in the middle of a discretization step could be double counted. In reality, we'd like solutions
// to be further apart than this.
double epsilon = 4 * joint_group_->getSolverInstance()->getSearchDiscretization();
logDebug("Utilizing an min. difference of %f between IK solutions", epsilon);
joint_poses.clear();
for (size_t sample_iter = 0; sample_iter < seed_states_.size(); ++sample_iter)
{
robot_state_->setJointGroupPositions(group_name_, seed_states_[sample_iter]);
std::vector<double> joint_pose;
if (getIK(pose, joint_pose))
{
if (joint_poses.empty())
{
std::stringstream msg;
msg << "Found *first* solution on " << sample_iter << " iteration, joint: " << joint_pose;
logDebug(msg.str().c_str());
joint_poses.push_back(joint_pose);
}
else
{
std::stringstream msg;
msg << "Found *potential* solution on " << sample_iter << " iteration, joint: " << joint_pose;
logDebug(msg.str().c_str());
std::vector<std::vector<double> >::iterator joint_pose_it;
bool match_found = false;
for (joint_pose_it = joint_poses.begin(); joint_pose_it != joint_poses.end(); ++joint_pose_it)
{
if (descartes_core::utils::equal(joint_pose, (*joint_pose_it), epsilon))
{
logDebug("Found matching, potential solution is not new");
match_found = true;
break;
}
}
if (!match_found)
{
std::stringstream msg;
msg << "Found *new* solution on " << sample_iter << " iteration, joint: " << joint_pose;
logDebug(msg.str().c_str());
joint_poses.push_back(joint_pose);
}
}
}
}
logDebug("Found %lu joint solutions out of %lu iterations", static_cast<unsigned long>(joint_poses.size()),
static_cast<unsigned long>(seed_states_.size()));
if (joint_poses.empty())
{
logError("Found 0 joint solutions out of %lu iterations", static_cast<unsigned long>(seed_states_.size()));
return false;
}
else
{
logInform("Found %lu joint solutions out of %lu iterations", static_cast<unsigned long>(joint_poses.size()),
static_cast<unsigned long>(seed_states_.size()));
return true;
}
}
bool MoveitStateAdapter::isInCollision(const std::vector<double>& joint_pose) const
{
bool in_collision = false;
if (check_collisions_)
{
robot_state_->setJointGroupPositions(group_name_, joint_pose);
in_collision = planning_scene_->isStateColliding(*robot_state_, group_name_);
}
return in_collision;
}
bool MoveitStateAdapter::getFK(const std::vector<double>& joint_pose, Eigen::Affine3d& pose) const
{
bool rtn = false;
robot_state_->setJointGroupPositions(group_name_, joint_pose);
if (isValid(joint_pose))
{
if (robot_state_->knowsFrameTransform(tool_frame_))
{
pose = world_to_root_.frame * robot_state_->getFrameTransform(tool_frame_);
rtn = true;
}
else
{
logError("Robot state does not recognize tool frame: %s", tool_frame_.c_str());
rtn = false;
}
}
else
{
logError("Invalid joint pose passed to get forward kinematics");
rtn = false;
}
return rtn;
}
bool MoveitStateAdapter::isValid(const std::vector<double>& joint_pose) const
{
// Logical check on input sizes
if (joint_group_->getActiveJointModels().size() != joint_pose.size())
{
logError("Size of joint pose: %lu doesn't match robot state variable size: %lu",
static_cast<unsigned long>(joint_pose.size()),
static_cast<unsigned long>(joint_group_->getActiveJointModels().size()));
return false;
}
// Satisfies joint positional bounds?
if (!joint_group_->satisfiesPositionBounds(joint_pose.data()))
{
return false;
}
// Is in collision (if collision is active)
return !isInCollision(joint_pose);
}
bool MoveitStateAdapter::isValid(const Eigen::Affine3d& pose) const
{
// TODO: Could check robot extents first as a quick check
std::vector<double> dummy;
return getIK(pose, dummy);
}
int MoveitStateAdapter::getDOF() const
{
return joint_group_->getVariableCount();
}
bool MoveitStateAdapter::isValidMove(const double* from_joint_pose,
const double* to_joint_pose, double dt) const
{
for (std::size_t i = 0; i < getDOF(); ++i)
{
double dtheta = std::abs(from_joint_pose[i] - to_joint_pose[i]);
double max_dtheta = dt * velocity_limits_[i];
if (dtheta > max_dtheta)
return false;
}
return true;
}
std::vector<double> MoveitStateAdapter::getJointVelocityLimits() const
{
return velocity_limits_;
}
void MoveitStateAdapter::setState(const moveit::core::RobotState& state)
{
ROS_ASSERT_MSG(static_cast<bool>(robot_state_), "'robot_state_' member pointer is null. Have you called "
"initialize()?");
*robot_state_ = state;
planning_scene_->setCurrentState(state);
}
} // descartes_moveit
<commit_msg>Collision checks now create their own robot state object in line. Re-creation may be slower, but it also allows for easier parallelism.<commit_after>/*
* Software License Agreement (Apache License)
*
* Copyright (c) 2014, Dan Solomon
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <console_bridge/console.h>
#include "descartes_moveit/moveit_state_adapter.h"
#include "descartes_core/pretty_print.hpp"
#include "descartes_moveit/seed_search.h"
#include <eigen_conversions/eigen_msg.h>
#include <random_numbers/random_numbers.h>
#include <ros/assert.h>
#include <sstream>
const static int SAMPLE_ITERATIONS = 10;
namespace
{
bool getJointVelocityLimits(const moveit::core::RobotState& state, const std::string& group_name,
std::vector<double>& output)
{
std::vector<double> result;
auto models = state.getJointModelGroup(group_name)->getActiveJointModels();
for (const moveit::core::JointModel* model : models)
{
const auto& bounds = model->getVariableBounds();
// Check to see if there is a single bounds constraint (more might indicate
// not revolute joint)
if (model->getType() != moveit::core::JointModel::REVOLUTE &&
model->getType() != moveit::core::JointModel::PRISMATIC)
{
ROS_ERROR_STREAM(__FUNCTION__ << " Unexpected joint type. Currently works only"
" with single axis prismatic or revolute joints.");
return false;
}
else
{
result.push_back(bounds[0].max_velocity_);
}
}
output = result;
return true;
}
} // end anon namespace
namespace descartes_moveit
{
MoveitStateAdapter::MoveitStateAdapter() : world_to_root_(Eigen::Affine3d::Identity())
{
}
bool MoveitStateAdapter::initialize(const std::string& robot_description, const std::string& group_name,
const std::string& world_frame, const std::string& tcp_frame)
{
// Initialize MoveIt state objects
robot_model_loader_.reset(new robot_model_loader::RobotModelLoader(robot_description));
auto model = robot_model_loader_->getModel();
if (!model)
{
logError("Failed to load robot model from robot description parameter: %s", robot_description.c_str());
return false;
}
return initialize(model, group_name, world_frame, tcp_frame);
}
bool MoveitStateAdapter::initialize(robot_model::RobotModelConstPtr robot_model, const std::string &group_name,
const std::string &world_frame, const std::string &tcp_frame)
{
robot_model_ptr_ = robot_model;
robot_state_.reset(new moveit::core::RobotState(robot_model_ptr_));
robot_state_->setToDefaultValues();
planning_scene_.reset(new planning_scene::PlanningScene(robot_model));
joint_group_ = robot_model_ptr_->getJointModelGroup(group_name);
// Assign robot frames
group_name_ = group_name;
tool_frame_ = tcp_frame;
world_frame_ = world_frame;
// Validate our model inputs w/ URDF
if (!joint_group_)
{
logError("%s: Joint group '%s' does not exist in robot model", __FUNCTION__, group_name_.c_str());
std::stringstream msg;
msg << "Possible group names: " << robot_state_->getRobotModel()->getJointModelGroupNames();
logError(msg.str().c_str());
return false;
}
const auto& link_names = joint_group_->getLinkModelNames();
if (tool_frame_ != link_names.back())
{
logError("%s: Tool frame '%s' does not match group tool frame '%s', functionality"
"will be implemented in the future",
__FUNCTION__, tool_frame_.c_str(), link_names.back().c_str());
return false;
}
if (!::getJointVelocityLimits(*robot_state_, group_name, velocity_limits_))
{
logWarn("%s: Could not determine velocity limits of RobotModel from MoveIt", __FUNCTION__);
}
if (seed_states_.empty())
{
seed_states_ = seed::findRandomSeeds(*robot_state_, group_name_, SAMPLE_ITERATIONS);
logDebug("Generated %lu random seeds", static_cast<unsigned long>(seed_states_.size()));
}
auto model_frame = robot_state_->getRobotModel()->getModelFrame();
if (world_frame_ != model_frame)
{
logInform("%s: World frame '%s' does not match model root frame '%s', all poses will be"
" transformed to world frame '%s'",
__FUNCTION__, world_frame_.c_str(), model_frame.c_str(), world_frame_.c_str());
Eigen::Affine3d root_to_world = robot_state_->getFrameTransform(world_frame_);
world_to_root_ = descartes_core::Frame(root_to_world.inverse());
}
return true;
}
bool MoveitStateAdapter::getIK(const Eigen::Affine3d& pose, const std::vector<double>& seed_state,
std::vector<double>& joint_pose) const
{
robot_state_->setJointGroupPositions(group_name_, seed_state);
return getIK(pose, joint_pose);
}
bool MoveitStateAdapter::getIK(const Eigen::Affine3d& pose, std::vector<double>& joint_pose) const
{
bool rtn = false;
// transform to group base
Eigen::Affine3d tool_pose = world_to_root_.frame * pose;
if (robot_state_->setFromIK(joint_group_, tool_pose, tool_frame_))
{
robot_state_->copyJointGroupPositions(group_name_, joint_pose);
if (!isValid(joint_pose))
{
ROS_DEBUG_STREAM("Robot joint pose is invalid");
}
else
{
rtn = true;
}
}
else
{
rtn = false;
}
return rtn;
}
bool MoveitStateAdapter::getAllIK(const Eigen::Affine3d& pose, std::vector<std::vector<double> >& joint_poses) const
{
// The minimum difference between solutions should be greater than the search discretization
// used by the IK solver. This value is multiplied by 4 to remove any chance that a solution
// in the middle of a discretization step could be double counted. In reality, we'd like solutions
// to be further apart than this.
double epsilon = 4 * joint_group_->getSolverInstance()->getSearchDiscretization();
logDebug("Utilizing an min. difference of %f between IK solutions", epsilon);
joint_poses.clear();
for (size_t sample_iter = 0; sample_iter < seed_states_.size(); ++sample_iter)
{
robot_state_->setJointGroupPositions(group_name_, seed_states_[sample_iter]);
std::vector<double> joint_pose;
if (getIK(pose, joint_pose))
{
if (joint_poses.empty())
{
std::stringstream msg;
msg << "Found *first* solution on " << sample_iter << " iteration, joint: " << joint_pose;
logDebug(msg.str().c_str());
joint_poses.push_back(joint_pose);
}
else
{
std::stringstream msg;
msg << "Found *potential* solution on " << sample_iter << " iteration, joint: " << joint_pose;
logDebug(msg.str().c_str());
std::vector<std::vector<double> >::iterator joint_pose_it;
bool match_found = false;
for (joint_pose_it = joint_poses.begin(); joint_pose_it != joint_poses.end(); ++joint_pose_it)
{
if (descartes_core::utils::equal(joint_pose, (*joint_pose_it), epsilon))
{
logDebug("Found matching, potential solution is not new");
match_found = true;
break;
}
}
if (!match_found)
{
std::stringstream msg;
msg << "Found *new* solution on " << sample_iter << " iteration, joint: " << joint_pose;
logDebug(msg.str().c_str());
joint_poses.push_back(joint_pose);
}
}
}
}
logDebug("Found %lu joint solutions out of %lu iterations", static_cast<unsigned long>(joint_poses.size()),
static_cast<unsigned long>(seed_states_.size()));
if (joint_poses.empty())
{
logError("Found 0 joint solutions out of %lu iterations", static_cast<unsigned long>(seed_states_.size()));
return false;
}
else
{
logInform("Found %lu joint solutions out of %lu iterations", static_cast<unsigned long>(joint_poses.size()),
static_cast<unsigned long>(seed_states_.size()));
return true;
}
}
bool MoveitStateAdapter::isInCollision(const std::vector<double>& joint_pose) const
{
bool in_collision = false;
if (check_collisions_)
{
moveit::core::RobotState state (robot_model_ptr_);
state.setToDefaultValues();
robot_state_->setJointGroupPositions(joint_group_, joint_pose);
in_collision = planning_scene_->isStateColliding(state, group_name_);
}
return in_collision;
}
bool MoveitStateAdapter::getFK(const std::vector<double>& joint_pose, Eigen::Affine3d& pose) const
{
bool rtn = false;
robot_state_->setJointGroupPositions(group_name_, joint_pose);
if (isValid(joint_pose))
{
if (robot_state_->knowsFrameTransform(tool_frame_))
{
pose = world_to_root_.frame * robot_state_->getFrameTransform(tool_frame_);
rtn = true;
}
else
{
logError("Robot state does not recognize tool frame: %s", tool_frame_.c_str());
rtn = false;
}
}
else
{
logError("Invalid joint pose passed to get forward kinematics");
rtn = false;
}
return rtn;
}
bool MoveitStateAdapter::isValid(const std::vector<double>& joint_pose) const
{
// Logical check on input sizes
if (joint_group_->getActiveJointModels().size() != joint_pose.size())
{
logError("Size of joint pose: %lu doesn't match robot state variable size: %lu",
static_cast<unsigned long>(joint_pose.size()),
static_cast<unsigned long>(joint_group_->getActiveJointModels().size()));
return false;
}
// Satisfies joint positional bounds?
if (!joint_group_->satisfiesPositionBounds(joint_pose.data()))
{
return false;
}
// Is in collision (if collision is active)
return !isInCollision(joint_pose);
}
bool MoveitStateAdapter::isValid(const Eigen::Affine3d& pose) const
{
// TODO: Could check robot extents first as a quick check
std::vector<double> dummy;
return getIK(pose, dummy);
}
int MoveitStateAdapter::getDOF() const
{
return joint_group_->getVariableCount();
}
bool MoveitStateAdapter::isValidMove(const double* from_joint_pose,
const double* to_joint_pose, double dt) const
{
for (std::size_t i = 0; i < getDOF(); ++i)
{
double dtheta = std::abs(from_joint_pose[i] - to_joint_pose[i]);
double max_dtheta = dt * velocity_limits_[i];
if (dtheta > max_dtheta)
return false;
}
return true;
}
std::vector<double> MoveitStateAdapter::getJointVelocityLimits() const
{
return velocity_limits_;
}
void MoveitStateAdapter::setState(const moveit::core::RobotState& state)
{
ROS_ASSERT_MSG(static_cast<bool>(robot_state_), "'robot_state_' member pointer is null. Have you called "
"initialize()?");
*robot_state_ = state;
planning_scene_->setCurrentState(state);
}
} // descartes_moveit
<|endoftext|> |
<commit_before>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*
* This file is part of the LibreOffice project.
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
*
* This file incorporates work covered by the following license notice:
*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed
* with this work for additional information regarding copyright
* ownership. The ASF licenses this file to you under the Apache
* License, Version 2.0 (the "License"); you may not use this file
* except in compliance with the License. You may obtain a copy of
* the License at http://www.apache.org/licenses/LICENSE-2.0 .
*/
#include "launcher.hxx"
#ifndef _WINDOWS_
# define WIN32_LEAN_AND_MEAN
#if defined _MSC_VER
#pragma warning(push, 1)
#endif
# include <windows.h>
# include <shellapi.h>
#if defined _MSC_VER
#pragma warning(pop)
#endif
#endif
#include <stdlib.h>
#include <malloc.h>
#ifdef __MINGW32__
extern "C" int APIENTRY WinMain( HINSTANCE, HINSTANCE, LPSTR, int )
#else
extern "C" int APIENTRY _tWinMain( HINSTANCE, HINSTANCE, LPTSTR, int )
#endif
{
// Retrieve startup info
STARTUPINFO aStartupInfo;
ZeroMemory( &aStartupInfo, sizeof(aStartupInfo) );
aStartupInfo.cb = sizeof( aStartupInfo );
GetStartupInfo( &aStartupInfo );
// Retrieve command line
LPTSTR lpCommandLine = GetCommandLine();
{
lpCommandLine = (LPTSTR)_alloca( sizeof(_TCHAR) * (_tcslen(lpCommandLine) + _tcslen(APPLICATION_SWITCH) + 2) );
_tcscpy( lpCommandLine, GetCommandLine() );
_tcscat( lpCommandLine, _T(" ") );
_tcscat( lpCommandLine, APPLICATION_SWITCH );
}
// Calculate application name
TCHAR szApplicationName[MAX_PATH];
TCHAR szDrive[MAX_PATH];
TCHAR szDir[MAX_PATH];
TCHAR szFileName[MAX_PATH];
TCHAR szExt[MAX_PATH];
GetModuleFileName( NULL, szApplicationName, MAX_PATH );
_tsplitpath( szApplicationName, szDrive, szDir, szFileName, szExt );
_tmakepath( szApplicationName, szDrive, szDir, OFFICE_IMAGE_NAME, _T(".exe") );
PROCESS_INFORMATION aProcessInfo;
BOOL fSuccess = CreateProcess(
szApplicationName,
lpCommandLine,
NULL,
NULL,
TRUE,
0,
NULL,
NULL,
&aStartupInfo,
&aProcessInfo );
if ( fSuccess )
{
// Wait for soffice process to be terminated to allow other applications
// to wait for termination of started process
WaitForSingleObject( aProcessInfo.hProcess, INFINITE );
CloseHandle( aProcessInfo.hProcess );
CloseHandle( aProcessInfo.hThread );
return 0;
}
DWORD dwError = GetLastError();
LPVOID lpMsgBuf;
FormatMessage(
FORMAT_MESSAGE_ALLOCATE_BUFFER |
FORMAT_MESSAGE_FROM_SYSTEM,
NULL,
dwError,
MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), // Default language
(LPTSTR)&lpMsgBuf,
0,
NULL
);
// Display the string.
MessageBox( NULL, (LPCTSTR)lpMsgBuf, NULL, MB_OK | MB_ICONERROR );
// Free the buffer.
LocalFree( lpMsgBuf );
return GetLastError();
}
/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
<commit_msg>fdo#35785: don't rely on the old apps fallback mechanism to fix this bug<commit_after>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*
* This file is part of the LibreOffice project.
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
*
* This file incorporates work covered by the following license notice:
*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed
* with this work for additional information regarding copyright
* ownership. The ASF licenses this file to you under the Apache
* License, Version 2.0 (the "License"); you may not use this file
* except in compliance with the License. You may obtain a copy of
* the License at http://www.apache.org/licenses/LICENSE-2.0 .
*/
#include "launcher.hxx"
#ifndef _WINDOWS_
# define WIN32_LEAN_AND_MEAN
#if defined _MSC_VER
#pragma warning(push, 1)
#endif
# include <windows.h>
# include <shellapi.h>
#if defined _MSC_VER
#pragma warning(pop)
#endif
#endif
#include <stdlib.h>
#include <malloc.h>
#define PACKVERSION(major,minor) MAKELONG(minor,major)
#define APPUSERMODELID L"TheDocumentFoundation.LibreOffice"
#ifdef __MINGW32__
extern "C" int APIENTRY WinMain( HINSTANCE, HINSTANCE, LPSTR, int )
#else
extern "C" int APIENTRY _tWinMain( HINSTANCE, HINSTANCE, LPTSTR, int )
#endif
{
// Set an explicit Application User Model ID for the process
WCHAR szShell32[MAX_PATH];
GetSystemDirectoryW(szShell32, MAX_PATH);
wcscat(szShell32, L"\\Shell32.dll");
HINSTANCE hinstDll = LoadLibraryW(szShell32);
if(hinstDll)
{
DLLVERSIONINFO dvi;
ZeroMemory(&dvi, sizeof(dvi));
dvi.cbSize = sizeof(dvi);
DLLGETVERSIONPROC pDllGetVersion;
pDllGetVersion = (DLLGETVERSIONPROC)GetProcAddress(hinstDll, "DllGetVersion");
HRESULT hr = (*pDllGetVersion)(&dvi);
if(SUCCEEDED(hr))
{
DWORD dwVersion = PACKVERSION(dvi.dwMajorVersion, dvi.dwMinorVersion);
if(dwVersion >= PACKVERSION(6,1)) // Shell32 version in Windows 7
{
typedef HRESULT (WINAPI *SETCURRENTPROCESSEXPLICITAPPUSERMODELID)(PCWSTR);
SETCURRENTPROCESSEXPLICITAPPUSERMODELID pSetCurrentProcessExplicitAppUserModelID;
pSetCurrentProcessExplicitAppUserModelID =
(SETCURRENTPROCESSEXPLICITAPPUSERMODELID)GetProcAddress(hinstDll, "SetCurrentProcessExplicitAppUserModelID");
if(pSetCurrentProcessExplicitAppUserModelID)
(*pSetCurrentProcessExplicitAppUserModelID) (APPUSERMODELID);
}
}
}
FreeLibrary(hinstDll);
// Retreive startup info
STARTUPINFO aStartupInfo;
ZeroMemory( &aStartupInfo, sizeof(aStartupInfo) );
aStartupInfo.cb = sizeof( aStartupInfo );
GetStartupInfo( &aStartupInfo );
// Retrieve command line
LPTSTR lpCommandLine = GetCommandLine();
{
lpCommandLine = (LPTSTR)_alloca( sizeof(_TCHAR) * (_tcslen(lpCommandLine) + _tcslen(APPLICATION_SWITCH) + 2) );
_tcscpy( lpCommandLine, GetCommandLine() );
_tcscat( lpCommandLine, _T(" ") );
_tcscat( lpCommandLine, APPLICATION_SWITCH );
}
// Calculate application name
TCHAR szApplicationName[MAX_PATH];
TCHAR szDrive[MAX_PATH];
TCHAR szDir[MAX_PATH];
TCHAR szFileName[MAX_PATH];
TCHAR szExt[MAX_PATH];
GetModuleFileName( NULL, szApplicationName, MAX_PATH );
_tsplitpath( szApplicationName, szDrive, szDir, szFileName, szExt );
_tmakepath( szApplicationName, szDrive, szDir, OFFICE_IMAGE_NAME, _T(".exe") );
PROCESS_INFORMATION aProcessInfo;
BOOL fSuccess = CreateProcess(
szApplicationName,
lpCommandLine,
NULL,
NULL,
TRUE,
0,
NULL,
NULL,
&aStartupInfo,
&aProcessInfo );
if ( fSuccess )
{
// Wait for soffice process to be terminated to allow other applications
// to wait for termination of started process
WaitForSingleObject( aProcessInfo.hProcess, INFINITE );
CloseHandle( aProcessInfo.hProcess );
CloseHandle( aProcessInfo.hThread );
return 0;
}
DWORD dwError = GetLastError();
LPVOID lpMsgBuf;
FormatMessage(
FORMAT_MESSAGE_ALLOCATE_BUFFER |
FORMAT_MESSAGE_FROM_SYSTEM,
NULL,
dwError,
MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), // Default language
(LPTSTR)&lpMsgBuf,
0,
NULL
);
// Display the string.
MessageBox( NULL, (LPCTSTR)lpMsgBuf, NULL, MB_OK | MB_ICONERROR );
// Free the buffer.
LocalFree( lpMsgBuf );
return GetLastError();
}
/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
<|endoftext|> |
<commit_before>// Copyright (C) 2012-2015 Leap Motion, Inc. All rights reserved.
#include "stdafx.h"
#include "DispatchQueue.h"
#include "at_exit.h"
#include <assert.h>
using namespace autowiring;
DispatchQueue::DispatchQueue(void) {}
DispatchQueue::DispatchQueue(size_t dispatchCap):
m_dispatchCap(dispatchCap)
{}
DispatchQueue::DispatchQueue(DispatchQueue&& q):
onAborted(std::move(q.onAborted)),
m_dispatchCap(q.m_dispatchCap)
{
if (!onAborted)
*this += std::move(q);
}
DispatchQueue::~DispatchQueue(void) {
// Wipe out each entry in the queue, we can't call any of them because we're in teardown
for (auto cur = m_pHead; cur;) {
auto next = cur->m_pFlink;
delete cur;
cur = next;
}
}
bool DispatchQueue::PromoteReadyDispatchersUnsafe(void) {
// Move all ready elements out of the delayed queue and into the dispatch queue:
size_t nInitial = m_delayedQueue.size();
// String together a chain of things that will be made ready:
for (
auto now = std::chrono::steady_clock::now();
!m_delayedQueue.empty() && m_delayedQueue.top().GetReadyTime() < now;
m_delayedQueue.pop()
) {
// Update tail if head is already set, otherwise update head:
auto thunk = m_delayedQueue.top().GetThunk().release();
if (m_pHead)
m_pTail->m_pFlink = thunk;
else
m_pHead = thunk;
m_pTail = thunk;
m_count++;
}
// Something was promoted if the dispatch queue size is different
return nInitial != m_delayedQueue.size();
}
void DispatchQueue::DispatchEventUnsafe(std::unique_lock<std::mutex>& lk) {
// Pull the ready thunk off of the front of the queue and pop it while we hold the lock.
// Then, we will excecute the call while the lock has been released so we do not create
// deadlocks.
std::unique_ptr<DispatchThunkBase> thunk(m_pHead);
m_pHead = thunk->m_pFlink;
lk.unlock();
MakeAtExit([&] {
if (!--m_count) {
// Notify that we have hit zero:
std::lock_guard<std::mutex>{ *lk.mutex() };
m_queueUpdated.notify_all();
}
}),
(*thunk)();
}
void DispatchQueue::TryDispatchEventUnsafe(std::unique_lock<std::mutex>& lk) {
// Pull the ready thunk off of the front of the queue and pop it while we hold the lock.
// Then, we will excecute the call while the lock has been released so we do not create
// deadlocks.
DispatchThunkBase* pThunk = m_pHead;
m_pHead = pThunk->m_pFlink;
lk.unlock();
try { (*pThunk)(); }
catch (...) {
// Failed to execute thunk, put it back
lk.lock();
pThunk->m_pFlink = m_pHead;
m_pHead = pThunk;
throw;
}
if (!--m_count) {
// Notify that we have hit zero:
std::lock_guard<std::mutex>{ *lk.mutex() };
m_queueUpdated.notify_all();
}
delete pThunk;
}
void DispatchQueue::Abort(void) {
// Do not permit any more lambdas to be pended to our queue
DispatchThunkBase* pHead;
{
std::lock_guard<std::mutex> lk(m_dispatchLock);
onAborted();
m_dispatchCap = 0;
pHead = m_pHead;
m_pHead = nullptr;
m_pTail = nullptr;
}
// Destroy the whole dispatch queue. Do so in an unsynchronized context in order to prevent
// reentrancy.
size_t nTraversed = 0;
for (auto cur = pHead; cur;) {
auto next = cur->m_pFlink;
delete cur;
cur = next;
nTraversed++;
}
// Decrement the count by the number of entries we actually traversed. Abort may potentially
// be called from a lambda function, so assigning this value directly to zero would be an error.
m_count -= nTraversed;
// Wake up anyone who is still waiting:
m_queueUpdated.notify_all();
}
bool DispatchQueue::Cancel(void) {
// Holds the cancelled thunk, declared here so that we delete it out of the lock
std::unique_ptr<DispatchThunkBase> thunk;
std::lock_guard<std::mutex> lk(m_dispatchLock);
if(m_pHead) {
// Found a ready thunk, run from here:
thunk.reset(m_pHead);
m_pHead = thunk->m_pFlink;
}
else if (!m_delayedQueue.empty()) {
auto& f = m_delayedQueue.top();
thunk = std::move(f.GetThunk());
m_delayedQueue.pop();
}
else
// Nothing to cancel!
return false;
return true;
}
void DispatchQueue::WakeAllWaitingThreads(void) {
m_version++;
m_queueUpdated.notify_all();
}
void DispatchQueue::WaitForEvent(void) {
std::unique_lock<std::mutex> lk(m_dispatchLock);
if (onAborted)
throw dispatch_aborted_exception("Dispatch queue was aborted prior to waiting for an event");
// Unconditional delay:
uint64_t version = m_version;
m_queueUpdated.wait(
lk,
[this, version] {
if (onAborted)
throw dispatch_aborted_exception("Dispatch queue was aborted while waiting for an event");
return
// We will need to transition out if the delay queue receives any items:
!this->m_delayedQueue.empty() ||
// We also transition out if the dispatch queue has any events:
this->m_pHead ||
// Or, finally, if the versions don't match
version != m_version;
}
);
if (m_pHead) {
// We have an event, we can just hop over to this variant:
DispatchEventUnsafe(lk);
return;
}
if (!m_delayedQueue.empty())
// The delay queue has items but the dispatch queue does not, we need to switch
// to the suggested sleep timeout variant:
WaitForEventUnsafe(lk, m_delayedQueue.top().GetReadyTime());
}
bool DispatchQueue::WaitForEvent(std::chrono::milliseconds milliseconds) {
return WaitForEvent(std::chrono::steady_clock::now() + milliseconds);
}
bool DispatchQueue::WaitForEvent(std::chrono::steady_clock::time_point wakeTime) {
if (wakeTime == std::chrono::steady_clock::time_point::max())
// Maximal wait--we can optimize by using the zero-arguments version
return WaitForEvent(), true;
std::unique_lock<std::mutex> lk(m_dispatchLock);
return WaitForEventUnsafe(lk, wakeTime);
}
bool DispatchQueue::WaitForEventUnsafe(std::unique_lock<std::mutex>& lk, std::chrono::steady_clock::time_point wakeTime) {
if (onAborted)
throw dispatch_aborted_exception("Dispatch queue was aborted prior to waiting for an event");
while (!m_pHead) {
// Derive a wakeup time using the high precision timer:
wakeTime = SuggestSoonestWakeupTimeUnsafe(wakeTime);
// Now we wait, either for the timeout to elapse or for the dispatch queue itself to
// transition to the "aborted" state.
std::cv_status status = m_queueUpdated.wait_until(lk, wakeTime);
// Short-circuit if the queue was aborted
if (onAborted)
throw dispatch_aborted_exception("Dispatch queue was aborted while waiting for an event");
if (PromoteReadyDispatchersUnsafe())
// Dispatcher is ready to run! Exit our loop and dispatch an event
break;
if (status == std::cv_status::timeout)
// Can't proceed, queue is empty and nobody is ready to be run
return false;
}
DispatchEventUnsafe(lk);
return true;
}
bool DispatchQueue::DispatchEvent(void) {
std::unique_lock<std::mutex> lk(m_dispatchLock);
// If the queue is empty and we fail to promote anything, return here
// Note that, due to short-circuiting, promotion will not take place if the queue is not empty.
// This behavior is by design.
if (!m_pHead && !PromoteReadyDispatchersUnsafe())
return false;
DispatchEventUnsafe(lk);
return true;
}
bool DispatchQueue::TryDispatchEvent(void) {
std::unique_lock<std::mutex> lk(m_dispatchLock);
if (!m_pHead && !PromoteReadyDispatchersUnsafe())
return false;
TryDispatchEventUnsafe(lk);
return true;
}
int DispatchQueue::DispatchAllEvents(void) {
int retVal = 0;
while(DispatchEvent())
retVal++;
return retVal;
}
void DispatchQueue::PendExisting(std::unique_lock<std::mutex>&& lk, DispatchThunkBase* thunk) {
// Count must be separately maintained:
m_count++;
// Linked list setup:
if (m_pHead)
m_pTail->m_pFlink = thunk;
else {
m_pHead = thunk;
m_queueUpdated.notify_all();
}
m_pTail = thunk;
// Notification as needed:
OnPended(std::move(lk));
}
bool DispatchQueue::Barrier(std::chrono::nanoseconds timeout) {
// Optimistic check first:
if (!m_count)
return true;
// Short-circuit if zero is specified as the timeout value
if (timeout.count() == 0)
return false;
// Now lock and double-check:
std::unique_lock<std::mutex> lk(m_dispatchLock);
// Short-circuit if dispatching has been aborted
if (onAborted)
throw dispatch_aborted_exception("Dispatch queue was aborted before a timed wait was attempted");
// Short-circuit if the queue is already empty
if (!m_count)
return true;
// Set up the lambda. Note that the queue size CANNOT be 1, because we just checked to verify
// that it is non-empty. Thus, we do not need to signal the m_queueUpdated condition variable.
auto complete = std::make_shared<bool>(false);
auto lambda = [complete] { *complete = true; };
PendExisting(
std::move(lk),
new DispatchThunk<decltype(lambda)>(std::move(lambda))
);
if (!lk.owns_lock())
lk.lock();
// Wait until our variable is satisfied, which might be right away:
bool rv = m_queueUpdated.wait_for(lk, timeout, [&] { return onAborted || *complete; });
if (onAborted)
throw dispatch_aborted_exception("Dispatch queue was aborted during a timed wait");
return rv;
}
void DispatchQueue::Barrier(void) {
// Set up the lambda:
bool complete = false;
*this += [&] { complete = true; };
// Obtain the lock, wait until our variable is satisfied, which might be right away:
std::unique_lock<std::mutex> lk(m_dispatchLock);
m_queueUpdated.wait(lk, [&] { return onAborted || complete; });
if (onAborted)
// At this point, the dispatch queue MUST be completely run down. We have no outstanding references
// to our stack-allocated "complete" variable. Furthermore, after m_aborted is true, no further
// dispatchers are permitted to be run.
throw dispatch_aborted_exception("Dispatch queue was aborted while a barrier was invoked");
}
std::chrono::steady_clock::time_point
DispatchQueue::SuggestSoonestWakeupTimeUnsafe(std::chrono::steady_clock::time_point latestTime) const {
return
m_delayedQueue.empty() ?
// Nothing in the queue, no way to suggest a shorter time
latestTime :
// Return the shorter of the maximum wait time and the time of the queue ready--we don't want to tell the
// caller to wait longer than the limit of their interest.
std::min(
m_delayedQueue.top().GetReadyTime(),
latestTime
);
}
void DispatchQueue::operator+=(DispatchQueue&& rhs) {
std::unique_lock<std::mutex> lk(m_dispatchLock);
// Append thunks to our queue
if (m_pHead)
m_pTail->m_pFlink = rhs.m_pHead;
else
m_pHead = rhs.m_pHead;
m_pTail = rhs.m_pTail;
m_count += rhs.m_count;
// Clear queue from rhs
rhs.m_pHead = nullptr;
rhs.m_pTail = nullptr;
rhs.m_count = 0;
// Append delayed thunks
while (!rhs.m_delayedQueue.empty()) {
const auto& top = rhs.m_delayedQueue.top();
m_delayedQueue.emplace(top.GetReadyTime(), top.GetThunk().release());
rhs.m_delayedQueue.pop();
}
// Notification as needed:
m_queueUpdated.notify_all();
OnPended(std::move(lk));
}
DispatchQueue::DispatchThunkDelayedExpressionAbs DispatchQueue::operator+=(std::chrono::steady_clock::time_point rhs) {
return{this, rhs};
}
void DispatchQueue::operator+=(DispatchThunkDelayed&& rhs) {
bool shouldNotify;
{
std::lock_guard<std::mutex> lk(m_dispatchLock);
m_delayedQueue.push(std::forward<DispatchThunkDelayed>(rhs));
shouldNotify = m_delayedQueue.top().GetReadyTime() == rhs.GetReadyTime() && !m_count;
}
if(shouldNotify)
// We're becoming the new next-to-execute entity, dispatch queue currently empty, trigger wakeup
// so our newly pended delay thunk is eventually processed.
m_queueUpdated.notify_all();
}
<commit_msg>Adjustment of Barrier behavior to make it similar to other overload<commit_after>// Copyright (C) 2012-2015 Leap Motion, Inc. All rights reserved.
#include "stdafx.h"
#include "DispatchQueue.h"
#include "at_exit.h"
#include <assert.h>
using namespace autowiring;
DispatchQueue::DispatchQueue(void) {}
DispatchQueue::DispatchQueue(size_t dispatchCap):
m_dispatchCap(dispatchCap)
{}
DispatchQueue::DispatchQueue(DispatchQueue&& q):
onAborted(std::move(q.onAborted)),
m_dispatchCap(q.m_dispatchCap)
{
if (!onAborted)
*this += std::move(q);
}
DispatchQueue::~DispatchQueue(void) {
// Wipe out each entry in the queue, we can't call any of them because we're in teardown
for (auto cur = m_pHead; cur;) {
auto next = cur->m_pFlink;
delete cur;
cur = next;
}
}
bool DispatchQueue::PromoteReadyDispatchersUnsafe(void) {
// Move all ready elements out of the delayed queue and into the dispatch queue:
size_t nInitial = m_delayedQueue.size();
// String together a chain of things that will be made ready:
for (
auto now = std::chrono::steady_clock::now();
!m_delayedQueue.empty() && m_delayedQueue.top().GetReadyTime() < now;
m_delayedQueue.pop()
) {
// Update tail if head is already set, otherwise update head:
auto thunk = m_delayedQueue.top().GetThunk().release();
if (m_pHead)
m_pTail->m_pFlink = thunk;
else
m_pHead = thunk;
m_pTail = thunk;
m_count++;
}
// Something was promoted if the dispatch queue size is different
return nInitial != m_delayedQueue.size();
}
void DispatchQueue::DispatchEventUnsafe(std::unique_lock<std::mutex>& lk) {
// Pull the ready thunk off of the front of the queue and pop it while we hold the lock.
// Then, we will excecute the call while the lock has been released so we do not create
// deadlocks.
std::unique_ptr<DispatchThunkBase> thunk(m_pHead);
m_pHead = thunk->m_pFlink;
lk.unlock();
MakeAtExit([&] {
if (!--m_count) {
// Notify that we have hit zero:
std::lock_guard<std::mutex>{ *lk.mutex() };
m_queueUpdated.notify_all();
}
}),
(*thunk)();
}
void DispatchQueue::TryDispatchEventUnsafe(std::unique_lock<std::mutex>& lk) {
// Pull the ready thunk off of the front of the queue and pop it while we hold the lock.
// Then, we will excecute the call while the lock has been released so we do not create
// deadlocks.
DispatchThunkBase* pThunk = m_pHead;
m_pHead = pThunk->m_pFlink;
lk.unlock();
try { (*pThunk)(); }
catch (...) {
// Failed to execute thunk, put it back
lk.lock();
pThunk->m_pFlink = m_pHead;
m_pHead = pThunk;
throw;
}
if (!--m_count) {
// Notify that we have hit zero:
std::lock_guard<std::mutex>{ *lk.mutex() };
m_queueUpdated.notify_all();
}
delete pThunk;
}
void DispatchQueue::Abort(void) {
// Do not permit any more lambdas to be pended to our queue
DispatchThunkBase* pHead;
{
std::lock_guard<std::mutex> lk(m_dispatchLock);
onAborted();
m_dispatchCap = 0;
pHead = m_pHead;
m_pHead = nullptr;
m_pTail = nullptr;
}
// Destroy the whole dispatch queue. Do so in an unsynchronized context in order to prevent
// reentrancy.
size_t nTraversed = 0;
for (auto cur = pHead; cur;) {
auto next = cur->m_pFlink;
delete cur;
cur = next;
nTraversed++;
}
// Decrement the count by the number of entries we actually traversed. Abort may potentially
// be called from a lambda function, so assigning this value directly to zero would be an error.
m_count -= nTraversed;
// Wake up anyone who is still waiting:
m_queueUpdated.notify_all();
}
bool DispatchQueue::Cancel(void) {
// Holds the cancelled thunk, declared here so that we delete it out of the lock
std::unique_ptr<DispatchThunkBase> thunk;
std::lock_guard<std::mutex> lk(m_dispatchLock);
if(m_pHead) {
// Found a ready thunk, run from here:
thunk.reset(m_pHead);
m_pHead = thunk->m_pFlink;
}
else if (!m_delayedQueue.empty()) {
auto& f = m_delayedQueue.top();
thunk = std::move(f.GetThunk());
m_delayedQueue.pop();
}
else
// Nothing to cancel!
return false;
return true;
}
void DispatchQueue::WakeAllWaitingThreads(void) {
m_version++;
m_queueUpdated.notify_all();
}
void DispatchQueue::WaitForEvent(void) {
std::unique_lock<std::mutex> lk(m_dispatchLock);
if (onAborted)
throw dispatch_aborted_exception("Dispatch queue was aborted prior to waiting for an event");
// Unconditional delay:
uint64_t version = m_version;
m_queueUpdated.wait(
lk,
[this, version] {
if (onAborted)
throw dispatch_aborted_exception("Dispatch queue was aborted while waiting for an event");
return
// We will need to transition out if the delay queue receives any items:
!this->m_delayedQueue.empty() ||
// We also transition out if the dispatch queue has any events:
this->m_pHead ||
// Or, finally, if the versions don't match
version != m_version;
}
);
if (m_pHead) {
// We have an event, we can just hop over to this variant:
DispatchEventUnsafe(lk);
return;
}
if (!m_delayedQueue.empty())
// The delay queue has items but the dispatch queue does not, we need to switch
// to the suggested sleep timeout variant:
WaitForEventUnsafe(lk, m_delayedQueue.top().GetReadyTime());
}
bool DispatchQueue::WaitForEvent(std::chrono::milliseconds milliseconds) {
return WaitForEvent(std::chrono::steady_clock::now() + milliseconds);
}
bool DispatchQueue::WaitForEvent(std::chrono::steady_clock::time_point wakeTime) {
if (wakeTime == std::chrono::steady_clock::time_point::max())
// Maximal wait--we can optimize by using the zero-arguments version
return WaitForEvent(), true;
std::unique_lock<std::mutex> lk(m_dispatchLock);
return WaitForEventUnsafe(lk, wakeTime);
}
bool DispatchQueue::WaitForEventUnsafe(std::unique_lock<std::mutex>& lk, std::chrono::steady_clock::time_point wakeTime) {
if (onAborted)
throw dispatch_aborted_exception("Dispatch queue was aborted prior to waiting for an event");
while (!m_pHead) {
// Derive a wakeup time using the high precision timer:
wakeTime = SuggestSoonestWakeupTimeUnsafe(wakeTime);
// Now we wait, either for the timeout to elapse or for the dispatch queue itself to
// transition to the "aborted" state.
std::cv_status status = m_queueUpdated.wait_until(lk, wakeTime);
// Short-circuit if the queue was aborted
if (onAborted)
throw dispatch_aborted_exception("Dispatch queue was aborted while waiting for an event");
if (PromoteReadyDispatchersUnsafe())
// Dispatcher is ready to run! Exit our loop and dispatch an event
break;
if (status == std::cv_status::timeout)
// Can't proceed, queue is empty and nobody is ready to be run
return false;
}
DispatchEventUnsafe(lk);
return true;
}
bool DispatchQueue::DispatchEvent(void) {
std::unique_lock<std::mutex> lk(m_dispatchLock);
// If the queue is empty and we fail to promote anything, return here
// Note that, due to short-circuiting, promotion will not take place if the queue is not empty.
// This behavior is by design.
if (!m_pHead && !PromoteReadyDispatchersUnsafe())
return false;
DispatchEventUnsafe(lk);
return true;
}
bool DispatchQueue::TryDispatchEvent(void) {
std::unique_lock<std::mutex> lk(m_dispatchLock);
if (!m_pHead && !PromoteReadyDispatchersUnsafe())
return false;
TryDispatchEventUnsafe(lk);
return true;
}
int DispatchQueue::DispatchAllEvents(void) {
int retVal = 0;
while(DispatchEvent())
retVal++;
return retVal;
}
void DispatchQueue::PendExisting(std::unique_lock<std::mutex>&& lk, DispatchThunkBase* thunk) {
// Count must be separately maintained:
m_count++;
// Linked list setup:
if (m_pHead)
m_pTail->m_pFlink = thunk;
else {
m_pHead = thunk;
m_queueUpdated.notify_all();
}
m_pTail = thunk;
// Notification as needed:
OnPended(std::move(lk));
}
bool DispatchQueue::Barrier(std::chrono::nanoseconds timeout) {
// Short-circuit if zero is specified as the timeout value
if (!m_count && timeout.count() == 0)
return true;
// Now lock and double-check:
std::unique_lock<std::mutex> lk(m_dispatchLock);
// Short-circuit if dispatching has been aborted
if (onAborted)
throw dispatch_aborted_exception("Dispatch queue was aborted before a timed wait was attempted");
// Set up the lambda. Note that the queue size CANNOT be 1, because we just checked to verify
// that it is non-empty. Thus, we do not need to signal the m_queueUpdated condition variable.
auto complete = std::make_shared<bool>(false);
auto lambda = [complete] { *complete = true; };
PendExisting(
std::move(lk),
new DispatchThunk<decltype(lambda)>(std::move(lambda))
);
if (!lk.owns_lock())
lk.lock();
// Wait until our variable is satisfied, which might be right away:
bool rv = m_queueUpdated.wait_for(lk, timeout, [&] { return onAborted || *complete; });
if (onAborted)
throw dispatch_aborted_exception("Dispatch queue was aborted during a timed wait");
return rv;
}
void DispatchQueue::Barrier(void) {
// Set up the lambda:
bool complete = false;
*this += [&] { complete = true; };
// Obtain the lock, wait until our variable is satisfied, which might be right away:
std::unique_lock<std::mutex> lk(m_dispatchLock);
m_queueUpdated.wait(lk, [&] { return onAborted || complete; });
if (onAborted)
// At this point, the dispatch queue MUST be completely run down. We have no outstanding references
// to our stack-allocated "complete" variable. Furthermore, after m_aborted is true, no further
// dispatchers are permitted to be run.
throw dispatch_aborted_exception("Dispatch queue was aborted while a barrier was invoked");
}
std::chrono::steady_clock::time_point
DispatchQueue::SuggestSoonestWakeupTimeUnsafe(std::chrono::steady_clock::time_point latestTime) const {
return
m_delayedQueue.empty() ?
// Nothing in the queue, no way to suggest a shorter time
latestTime :
// Return the shorter of the maximum wait time and the time of the queue ready--we don't want to tell the
// caller to wait longer than the limit of their interest.
std::min(
m_delayedQueue.top().GetReadyTime(),
latestTime
);
}
void DispatchQueue::operator+=(DispatchQueue&& rhs) {
std::unique_lock<std::mutex> lk(m_dispatchLock);
// Append thunks to our queue
if (m_pHead)
m_pTail->m_pFlink = rhs.m_pHead;
else
m_pHead = rhs.m_pHead;
m_pTail = rhs.m_pTail;
m_count += rhs.m_count;
// Clear queue from rhs
rhs.m_pHead = nullptr;
rhs.m_pTail = nullptr;
rhs.m_count = 0;
// Append delayed thunks
while (!rhs.m_delayedQueue.empty()) {
const auto& top = rhs.m_delayedQueue.top();
m_delayedQueue.emplace(top.GetReadyTime(), top.GetThunk().release());
rhs.m_delayedQueue.pop();
}
// Notification as needed:
m_queueUpdated.notify_all();
OnPended(std::move(lk));
}
DispatchQueue::DispatchThunkDelayedExpressionAbs DispatchQueue::operator+=(std::chrono::steady_clock::time_point rhs) {
return{this, rhs};
}
void DispatchQueue::operator+=(DispatchThunkDelayed&& rhs) {
bool shouldNotify;
{
std::lock_guard<std::mutex> lk(m_dispatchLock);
m_delayedQueue.push(std::forward<DispatchThunkDelayed>(rhs));
shouldNotify = m_delayedQueue.top().GetReadyTime() == rhs.GetReadyTime() && !m_count;
}
if(shouldNotify)
// We're becoming the new next-to-execute entity, dispatch queue currently empty, trigger wakeup
// so our newly pended delay thunk is eventually processed.
m_queueUpdated.notify_all();
}
<|endoftext|> |
<commit_before>#include "worldscene.hpp"
#include "rendercontext.hpp"
#include <tiny_obj_loader.h>
#include <glm/gtc/matrix_transform.hpp>
WorldScene::WorldScene()
{
std::vector<tinyobj::shape_t> worldShapes;
tinyobj::LoadObj(worldShapes, "floor.obj");
if (worldShapes.empty())
{
throw std::runtime_error("floor model not available");
}
mpWorldMesh.reset(new GLmesh::StaticMesh());
mpWorldMesh->LoadShape(worldShapes[0]);
mpPlayerTexture.reset(new GLplus::Texture2D());
{
GLplus::ScopedTexture2DBinding scopedTextureBind(*mpPlayerTexture);
scopedTextureBind.GetBinding().LoadImage("player.png", GLplus::Texture2D::InvertY);
}
mBillboards.emplace_back(new Billboard());
std::unique_ptr<Billboard>& player = mBillboards.back();
player->SetTexture(mpPlayerTexture);
player->SetCenterPosition(glm::vec3(0.0f,1.0f,0.0f));
player->SetDimensions(glm::vec2(2.0f,2.0f));
mModelProgram.reset(new GLplus::Program(GLplus::Program::FromFiles("world.vs","world.fs")));
mCamera.EyePosition = glm::vec3(3.0f);
mCamera.TargetPosition = glm::vec3(0.0f);
mCamera.UpVector = glm::vec3(0.0f,1.0f,0.0f);
}
void WorldScene::Update(unsigned int deltaTimeMS)
{
}
void WorldScene::Render(RenderContext& renderContext, float partialUpdatePercentage)
{
float aspect = renderContext.GetAspectRatio();
glm::mat4 projection = glm::perspective(70.0f, aspect, 0.1f, 1000.0f);
glm::mat4 worldview = glm::lookAt(mCamera.EyePosition, mCamera.TargetPosition, mCamera.UpVector);
GLplus::ScopedProgramBinding scopedProgramBinding(*mModelProgram);
GLplus::ProgramBinding& programBinding = scopedProgramBinding.GetBinding();
programBinding.UploadMatrix4("projection", GL_FALSE, &projection[0][0]);
programBinding.UploadMatrix4("modelview", GL_FALSE, &worldview[0][0]);
glEnable(GL_DEPTH_TEST);
mpWorldMesh->Render(*mModelProgram);
for (const std::unique_ptr<Billboard>& pBillboard : mBillboards)
{
pBillboard->SetCameraPosition(mCamera.EyePosition);
pBillboard->SetCameraViewDirection(mCamera.TargetPosition - mCamera.EyePosition);
pBillboard->SetCameraUp(mCamera.UpVector);
pBillboard->Render(*mModelProgram);
}
}
<commit_msg>Got the player showing up<commit_after>#include "worldscene.hpp"
#include "rendercontext.hpp"
#include <tiny_obj_loader.h>
#include <glm/gtc/matrix_transform.hpp>
WorldScene::WorldScene()
{
std::vector<tinyobj::shape_t> worldShapes;
tinyobj::LoadObj(worldShapes, "floor.obj");
if (worldShapes.empty())
{
throw std::runtime_error("floor model not available");
}
mpWorldMesh.reset(new GLmesh::StaticMesh());
mpWorldMesh->LoadShape(worldShapes[0]);
mpPlayerTexture.reset(new GLplus::Texture2D());
{
GLplus::ScopedTexture2DBinding scopedTextureBind(*mpPlayerTexture);
scopedTextureBind.GetBinding().LoadImage("player.png", GLplus::Texture2D::InvertY);
}
mBillboards.emplace_back(new Billboard());
std::unique_ptr<Billboard>& player = mBillboards.back();
player->SetTexture(mpPlayerTexture);
player->SetCenterPosition(glm::vec3(0.0f,1.0f,0.0f));
player->SetDimensions(glm::vec2(2.0f,2.0f));
mModelProgram.reset(new GLplus::Program(GLplus::Program::FromFiles("world.vs","world.fs")));
mCamera.EyePosition = glm::vec3(3.0f);
mCamera.TargetPosition = glm::vec3(0.0f);
mCamera.UpVector = glm::vec3(0.0f,1.0f,0.0f);
}
void WorldScene::Update(unsigned int deltaTimeMS)
{
}
void WorldScene::Render(RenderContext& renderContext, float partialUpdatePercentage)
{
float aspect = renderContext.GetAspectRatio();
glm::mat4 projection = glm::perspective(70.0f, aspect, 0.1f, 1000.0f);
glm::mat4 worldview = glm::lookAt(mCamera.EyePosition, mCamera.TargetPosition, mCamera.UpVector);
GLplus::ScopedProgramBinding scopedProgramBinding(*mModelProgram);
GLplus::ProgramBinding& programBinding = scopedProgramBinding.GetBinding();
programBinding.UploadMatrix4("projection", GL_FALSE, &projection[0][0]);
programBinding.UploadMatrix4("modelview", GL_FALSE, &worldview[0][0]);
glEnable(GL_DEPTH_TEST);
GLplus::CheckGLErrors();
mpWorldMesh->Render(*mModelProgram);
glEnable(GL_BLEND);
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
GLplus::CheckGLErrors();
for (const std::unique_ptr<Billboard>& pBillboard : mBillboards)
{
pBillboard->SetCameraPosition(mCamera.EyePosition);
pBillboard->SetCameraViewDirection(mCamera.TargetPosition - mCamera.EyePosition);
pBillboard->SetCameraUp(mCamera.UpVector);
pBillboard->Render(*mModelProgram);
}
}
<|endoftext|> |
<commit_before>#include "fast_obj_loader.h"
#include <stdio.h>
#include <stdlib.h>
#include "fastdynamic.h"
#ifdef _OPENMP
#include <omp.h>
#endif
#include <time.h>
#include <string.h>
//bool getcstr(char *out,unsigned short bufflen,char *input,size_t &len) // bufflen = output buffer size // input has to be a copy of the original pointer
//{
// if(len<=0)
// return false;
// unsigned short i=0;
// while
//}
unsigned int getNextFaceNumber(char *line,size_t &offset,unsigned char &type,unsigned char &nexttype,bool &more,bool &valid)
{
#define buflen 256
unsigned int output=-1;
char tmp[buflen+1];
type=nexttype;
more = 1;
unsigned int j=0;
for(unsigned int i=0;i<buflen;i++)
{
switch(line[i+offset])
{
case 0:
more = 0;
i=buflen;
nexttype=0;
break;
case '/':
offset+=i+1;
i=buflen;
nexttype++;
break;
case ' ':
offset+=i+1;
i=buflen;
nexttype=0;
break;
default:
tmp[j]=line[i+offset];
j++;
break;
}
}
if(j!=0)
{
tmp[j]=0;
valid=1;
output=atoi(tmp);
//sscanf(tmp,"%99u",&output); 0.6seconds vs atoi 0.36seconds from 0.2seconds without face loading
}
else
{
valid=0;
}
return output;
}
obj *loadObj(const char *filename)
{
obj *output=new obj;
FILE *f=fopen(filename,"rb");
if(!f)
{
printf("file not found %s\n",filename);
return 0;
}
fseek(f,0,SEEK_END);
size_t filelength=ftell(f);
fseek(f,0,SEEK_SET);
//printf("filesize=%zu bytes\n",filelength);
char *memoryfile=new char[filelength];
fread(memoryfile,filelength,1,f);
timespec start,stop;
clock_gettime(CLOCK_REALTIME, &start );
double calltime;
size_t linecount=0;
int numthreads=0;
int numEnds=0;
size_t numverts=0;
size_t *lineends;
FastDynamic<size_t> *tmpends;
size_t *numtmpends;
#pragma omp parallel // first get line ends so they can be parsed in parallel
{
numthreads=omp_get_num_threads();
int threadid=omp_get_thread_num();
#pragma omp single
{
tmpends=new FastDynamic<unsigned int>[numthreads];
numtmpends=new size_t[numthreads];
for(int i=0;i<numthreads;i++)
{
tmpends[i].SetContainer_size(8192);
numtmpends[i]=0;
}
}
#pragma omp for reduction(+:linecount,numEnds)
for(size_t i=0;i<filelength;i++)
{
//printf("%i\n",i);
if(memoryfile[i]=='\n')
{
tmpends[threadid][numEnds]=i;
numtmpends[threadid]++;
numEnds++;
linecount++;
}
}
#pragma omp single
{
lineends=new size_t[numEnds+1];
lineends[numEnds+1]=filelength;
}
#pragma omp for
for(int i=0;i<numthreads;i++)
{
int offset=0;
for(int j=0;j<i;j++)
{
offset+=numtmpends[j];
}
tmpends[i].CopyToStatic(&lineends[offset],numtmpends[i]);
}
#pragma omp single
{
delete [] numtmpends;
delete [] tmpends;
}
}
FastDynamic<vec3> *tmpverts;
size_t *numtmpverts;
#pragma omp parallel
{
// read verts for now
numthreads=omp_get_num_threads();
int threadid=omp_get_thread_num();
#pragma omp single
{
tmpverts=new FastDynamic<vec3>[numthreads];
numtmpverts=new size_t[numthreads];
for(int i=0;i<numthreads;i++)
{
tmpverts[i].SetContainer_size(8192);
numtmpverts[i]=0;
}
}
#pragma omp single
{
// read first line here
}
#pragma omp for reduction(+:numverts)
for (int i = 1; i < numEnds; i++)
{
char line[1024]={0};
memcpy(&line,&memoryfile[lineends[i-1]+1],lineends[i]-lineends[i-1]-1);
if(line[0]=='v' && line[1]==' ')
{
vec3 vert;
sscanf(line,"v %99f %99f %99f",&vert.x,&vert.y,&vert.z);
tmpverts[threadid][numtmpverts[threadid]]=vert;
numtmpverts[threadid]++;
numverts++;
}
if(line[0]=='f' && line[1]==' ')
{
char *data=line+2;
size_t offset=0;
bool more=1;
unsigned char type=0;
unsigned char nexttype=0;
while(more)
{
bool valid;
unsigned int faceidnum=getNextFaceNumber(data,offset,type,nexttype,more,valid);
if(valid)
{
switch(type)
{
case 0:
// printf("p:%u ",faceidnum);
break;
case 1:
// printf("u:%u ",faceidnum);
break;
case 2:
// printf("n:%u ",faceidnum);
break;
}
}
}
// printf("\n");
}
}
#pragma omp single
{
output->verts=new vec3[numverts];
}
#pragma omp for
for(int i=0;i<numthreads;i++)
{
int offset=0;
for(int j=0;j<i;j++)
{
offset+=numtmpverts[j];
}
tmpverts[i].CopyToStatic(&(output->verts[offset]),numtmpverts[i]);
}
#pragma omp single
{
delete [] tmpverts;
delete [] numtmpverts;
}
}
delete [] lineends;
//printf("lines:%zu\n",linecount);
//printf("numthreads:%i\n",numthreads);
//printf("numverts:%zu\n",numverts);
clock_gettime(CLOCK_REALTIME, &stop );
calltime=(stop.tv_sec-start.tv_sec)+(stop.tv_nsec-start.tv_nsec)/1000000000.0;
// printf("done parsing file %lfseconds\n",calltime);
delete [] memoryfile;
fclose(f);
return output;
}
<commit_msg>using faster float reading using strtod<commit_after>#include "fast_obj_loader.h"
#include <stdio.h>
#include <stdlib.h>
#include "fastdynamic.h"
#ifdef _OPENMP
#include <omp.h>
#endif
#include <time.h>
#include <string.h>
//bool getcstr(char *out,unsigned short bufflen,char *input,size_t &len) // bufflen = output buffer size // input has to be a copy of the original pointer
//{
// if(len<=0)
// return false;
// unsigned short i=0;
// while
//}
unsigned int getNextFaceNumber(char *line,size_t &offset,unsigned char &type,unsigned char &nexttype,bool &more,bool &valid)
{
#define buflen 256
unsigned int output=-1;
char tmp[buflen+1];
type=nexttype;
more = 1;
unsigned int j=0;
for(unsigned int i=0;i<buflen;i++)
{
switch(line[i+offset])
{
case 0:
more = 0;
i=buflen;
nexttype=0;
break;
case '/':
offset+=i+1;
i=buflen;
nexttype++;
break;
case ' ':
offset+=i+1;
i=buflen;
nexttype=0;
break;
default:
tmp[j]=line[i+offset];
j++;
break;
}
}
if(j!=0)
{
tmp[j]=0;
valid=1;
output=atoi(tmp);
//sscanf(tmp,"%99u",&output); 0.6seconds vs atoi 0.36seconds from 0.2seconds without face loading
}
else
{
valid=0;
}
return output;
}
obj *loadObj(const char *filename)
{
obj *output=new obj;
FILE *f=fopen(filename,"rb");
if(!f)
{
printf("file not found %s\n",filename);
return 0;
}
fseek(f,0,SEEK_END);
size_t filelength=ftell(f);
fseek(f,0,SEEK_SET);
//printf("filesize=%zu bytes\n",filelength);
char *memoryfile=new char[filelength];
fread(memoryfile,filelength,1,f);
timespec start,stop;
clock_gettime(CLOCK_REALTIME, &start );
double calltime;
size_t linecount=0;
int numthreads=0;
int numEnds=0;
size_t numverts=0;
size_t *lineends;
FastDynamic<size_t> *tmpends;
size_t *numtmpends;
#pragma omp parallel // first get line ends so they can be parsed in parallel
{
numthreads=omp_get_num_threads();
int threadid=omp_get_thread_num();
#pragma omp single
{
tmpends=new FastDynamic<unsigned int>[numthreads];
numtmpends=new size_t[numthreads];
for(int i=0;i<numthreads;i++)
{
tmpends[i].SetContainer_size(8192);
numtmpends[i]=0;
}
}
#pragma omp for reduction(+:linecount,numEnds)
for(size_t i=0;i<filelength;i++)
{
//printf("%i\n",i);
if(memoryfile[i]=='\n')
{
tmpends[threadid][numEnds]=i;
numtmpends[threadid]++;
numEnds++;
linecount++;
}
}
#pragma omp single
{
lineends=new size_t[numEnds+1];
lineends[numEnds+1]=filelength;
}
#pragma omp for
for(int i=0;i<numthreads;i++)
{
int offset=0;
for(int j=0;j<i;j++)
{
offset+=numtmpends[j];
}
tmpends[i].CopyToStatic(&lineends[offset],numtmpends[i]);
}
#pragma omp single
{
delete [] numtmpends;
delete [] tmpends;
}
}
FastDynamic<vec3> *tmpverts;
size_t *numtmpverts;
#pragma omp parallel
{
// read verts for now
numthreads=omp_get_num_threads();
int threadid=omp_get_thread_num();
#pragma omp single
{
tmpverts=new FastDynamic<vec3>[numthreads];
numtmpverts=new size_t[numthreads];
for(int i=0;i<numthreads;i++)
{
tmpverts[i].SetContainer_size(8192);
numtmpverts[i]=0;
}
}
#pragma omp single
{
// read first line here
}
#pragma omp for reduction(+:numverts)
for (int i = 1; i < numEnds; i++)
{
char line[1024]={0};
memcpy(&line,&memoryfile[lineends[i-1]+1],lineends[i]-lineends[i-1]-1);
if(line[0]=='v' && line[1]==' ')
{
char *l=line+2;
char *tmpl;
vec3 vert;
vert.x=strtod(l,&tmpl);
l=tmpl;
vert.y=strtod(l,&tmpl);
l=tmpl;
vert.z=strtod(l,&tmpl);
l=tmpl;
tmpverts[threadid][numtmpverts[threadid]]=vert;
numtmpverts[threadid]++;
numverts++;
}
else if(line[0]=='f' && line[1]==' ')
{
char *data=line+2;
size_t offset=0;
bool more=1;
unsigned char type=0;
unsigned char nexttype=0;
while(more)
{
bool valid;
unsigned int faceidnum=getNextFaceNumber(data,offset,type,nexttype,more,valid);
if(valid)
{
switch(type)
{
case 0:
// printf("p:%u ",faceidnum);
break;
case 1:
// printf("u:%u ",faceidnum);
break;
case 2:
// printf("n:%u ",faceidnum);
break;
}
}
}
// printf("\n");
}
}
#pragma omp single
{
output->verts=new vec3[numverts];
}
#pragma omp for
for(int i=0;i<numthreads;i++)
{
int offset=0;
for(int j=0;j<i;j++)
{
offset+=numtmpverts[j];
}
tmpverts[i].CopyToStatic(&(output->verts[offset]),numtmpverts[i]);
}
#pragma omp single
{
delete [] tmpverts;
delete [] numtmpverts;
}
}
delete [] lineends;
//printf("lines:%zu\n",linecount);
//printf("numthreads:%i\n",numthreads);
//printf("numverts:%zu\n",numverts);
clock_gettime(CLOCK_REALTIME, &stop );
calltime=(stop.tv_sec-start.tv_sec)+(stop.tv_nsec-start.tv_nsec)/1000000000.0;
// printf("done parsing file %lfseconds\n",calltime);
delete [] memoryfile;
fclose(f);
return output;
}
<|endoftext|> |
<commit_before>// Copyright 2018 The NXT 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 "backend/vulkan/TextureVk.h"
#include "backend/vulkan/FencedDeleter.h"
#include "backend/vulkan/VulkanBackend.h"
namespace backend { namespace vulkan {
namespace {
// Converts an NXT texture dimension to a Vulkan image type.
// Note that in Vulkan dimensionality is only 1D, 2D, 3D. Arrays and cube maps are expressed
// via the array size and a "cubemap compatible" flag.
VkImageType VulkanImageType(nxt::TextureDimension dimension) {
switch (dimension) {
case nxt::TextureDimension::e2D:
return VK_IMAGE_TYPE_2D;
default:
UNREACHABLE();
}
}
// Converts an NXT texture dimension to a Vulkan image view type.
// Contrary to image types, image view types include arrayness and cubemapness
VkImageViewType VulkanImageViewType(nxt::TextureDimension dimension) {
switch (dimension) {
case nxt::TextureDimension::e2D:
return VK_IMAGE_VIEW_TYPE_2D;
default:
UNREACHABLE();
}
}
// Converts the NXT usage flags to Vulkan usage flags. Also needs the format to choose
// between color and depth attachment usages.
VkImageUsageFlags VulkanImageUsage(nxt::TextureUsageBit usage, nxt::TextureFormat format) {
VkImageUsageFlags flags = 0;
if (usage & nxt::TextureUsageBit::TransferSrc) {
flags |= VK_IMAGE_USAGE_TRANSFER_SRC_BIT;
}
if (usage & nxt::TextureUsageBit::TransferDst) {
flags |= VK_IMAGE_USAGE_TRANSFER_DST_BIT;
}
if (usage & nxt::TextureUsageBit::Sampled) {
flags |= VK_IMAGE_USAGE_SAMPLED_BIT;
}
if (usage & nxt::TextureUsageBit::Storage) {
flags |= VK_IMAGE_USAGE_STORAGE_BIT;
}
if (usage & nxt::TextureUsageBit::OutputAttachment) {
if (TextureFormatHasDepthOrStencil(format)) {
flags |= VK_IMAGE_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT;
} else {
flags |= VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT;
}
}
return flags;
}
// Computes which vulkan access type could be required for the given NXT usage.
VkAccessFlags VulkanAccessFlags(nxt::TextureUsageBit usage, nxt::TextureFormat format) {
VkAccessFlags flags = 0;
if (usage & nxt::TextureUsageBit::TransferSrc) {
flags |= VK_ACCESS_TRANSFER_READ_BIT;
}
if (usage & nxt::TextureUsageBit::TransferDst) {
flags |= VK_ACCESS_TRANSFER_WRITE_BIT;
}
if (usage & nxt::TextureUsageBit::Sampled) {
flags |= VK_ACCESS_SHADER_READ_BIT;
}
if (usage & nxt::TextureUsageBit::Storage) {
flags |= VK_ACCESS_SHADER_READ_BIT | VK_ACCESS_SHADER_WRITE_BIT;
}
if (usage & nxt::TextureUsageBit::OutputAttachment) {
if (TextureFormatHasDepthOrStencil(format)) {
flags |= VK_ACCESS_DEPTH_STENCIL_ATTACHMENT_READ_BIT |
VK_ACCESS_DEPTH_STENCIL_ATTACHMENT_WRITE_BIT;
} else {
flags |=
VK_ACCESS_COLOR_ATTACHMENT_READ_BIT | VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT;
}
}
// TODO(cwallez@chromium.org): What about present? Does it require VK_MEMORY_READ_BIT?
return flags;
}
// Chooses which Vulkan image layout should be used for the given NXT usage
VkImageLayout VulkanImageLayout(nxt::TextureUsageBit usage, nxt::TextureFormat format) {
if (usage == nxt::TextureUsageBit::None) {
return VK_IMAGE_LAYOUT_UNDEFINED;
}
if (!nxt::HasZeroOrOneBits(usage)) {
return VK_IMAGE_LAYOUT_GENERAL;
}
// Usage has a single bit so we can switch on its value directly.
switch (usage) {
case nxt::TextureUsageBit::TransferDst:
return VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL;
case nxt::TextureUsageBit::Sampled:
return VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL;
// Vulkan texture copy functions require the image to be in _one_ known layout.
// Depending on whether parts of the texture have been transitioned to only
// TransferSrc or a combination with something else, the texture could be in a
// combination of GENERAL and TRANSFER_SRC_OPTIMAL. This would be a problem, so we
// make TransferSrc use GENERAL.
case nxt::TextureUsageBit::TransferSrc:
// Writable storage textures must use general. If we could know the texture is read
// only we could use SHADER_READ_ONLY_OPTIMAL
case nxt::TextureUsageBit::Storage:
case nxt::TextureUsageBit::Present:
return VK_IMAGE_LAYOUT_GENERAL;
case nxt::TextureUsageBit::OutputAttachment:
if (TextureFormatHasDepthOrStencil(format)) {
return VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL;
} else {
return VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL;
}
default:
UNREACHABLE();
}
}
// Computes which Vulkan pipeline stage can access a texture in the given NXT usage
VkPipelineStageFlags VulkanPipelineStage(nxt::TextureUsageBit usage,
nxt::TextureFormat format) {
VkPipelineStageFlags flags = 0;
if (usage == nxt::TextureUsageBit::None) {
// This only happens when a texture is initially created (and for srcAccessMask) in
// which case there is no need to wait on anything to stop accessing this texture.
return VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT;
}
if (usage & (nxt::TextureUsageBit::TransferSrc | nxt::TextureUsageBit::TransferDst)) {
flags |= VK_PIPELINE_STAGE_TRANSFER_BIT;
}
if (usage & (nxt::TextureUsageBit::Sampled | nxt::TextureUsageBit::Storage)) {
flags |= VK_PIPELINE_STAGE_VERTEX_SHADER_BIT |
VK_PIPELINE_STAGE_FRAGMENT_SHADER_BIT |
VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT;
}
if (usage & nxt::TextureUsageBit::OutputAttachment) {
if (TextureFormatHasDepthOrStencil(format)) {
flags |= VK_PIPELINE_STAGE_EARLY_FRAGMENT_TESTS_BIT |
VK_PIPELINE_STAGE_LATE_FRAGMENT_TESTS_BIT;
// TODO(cwallez@chromium.org): This is missing the stage where the depth and
// stencil values are written, but it isn't clear which one it is.
} else {
flags |= VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT;
}
}
// TODO(cwallez@chromium.org) What about present?
return flags;
}
// Computes which Vulkan texture aspects are relevant for the given NXT format
VkImageAspectFlags VulkanAspectMask(nxt::TextureFormat format) {
bool isDepth = TextureFormatHasDepth(format);
bool isStencil = TextureFormatHasStencil(format);
VkImageAspectFlags flags = 0;
if (isDepth) {
flags |= VK_IMAGE_ASPECT_DEPTH_BIT;
}
if (isStencil) {
flags |= VK_IMAGE_ASPECT_STENCIL_BIT;
}
if (flags != 0) {
return flags;
}
return VK_IMAGE_ASPECT_COLOR_BIT;
}
} // namespace
// Converts NXT texture format to Vulkan formats.
VkFormat VulkanImageFormat(nxt::TextureFormat format) {
switch (format) {
case nxt::TextureFormat::R8G8B8A8Unorm:
return VK_FORMAT_R8G8B8A8_UNORM;
case nxt::TextureFormat::R8G8B8A8Uint:
return VK_FORMAT_R8G8B8A8_UINT;
case nxt::TextureFormat::B8G8R8A8Unorm:
return VK_FORMAT_B8G8R8A8_UNORM;
case nxt::TextureFormat::D32FloatS8Uint:
return VK_FORMAT_D32_SFLOAT_S8_UINT;
default:
UNREACHABLE();
}
}
Texture::Texture(TextureBuilder* builder) : TextureBase(builder) {
Device* device = ToBackend(GetDevice());
// Create the Vulkan image "container". We don't need to check that the format supports the
// combination of sample, usage etc. because validation should have been done in the NXT
// frontend already based on the minimum supported formats in the Vulkan spec
VkImageCreateInfo createInfo;
createInfo.sType = VK_STRUCTURE_TYPE_IMAGE_CREATE_INFO;
createInfo.pNext = nullptr;
createInfo.flags = 0;
createInfo.imageType = VulkanImageType(GetDimension());
createInfo.format = VulkanImageFormat(GetFormat());
createInfo.extent = VkExtent3D{GetWidth(), GetHeight(), GetDepth()};
createInfo.mipLevels = GetNumMipLevels();
createInfo.arrayLayers = 1;
createInfo.samples = VK_SAMPLE_COUNT_1_BIT;
createInfo.tiling = VK_IMAGE_TILING_OPTIMAL;
createInfo.usage = VulkanImageUsage(GetAllowedUsage(), GetFormat());
createInfo.sharingMode = VK_SHARING_MODE_EXCLUSIVE;
createInfo.queueFamilyIndexCount = 0;
createInfo.pQueueFamilyIndices = nullptr;
createInfo.initialLayout = VK_IMAGE_LAYOUT_UNDEFINED;
if (device->fn.CreateImage(device->GetVkDevice(), &createInfo, nullptr, &mHandle) !=
VK_SUCCESS) {
ASSERT(false);
}
// Create the image memory and associate it with the container
VkMemoryRequirements requirements;
device->fn.GetImageMemoryRequirements(device->GetVkDevice(), mHandle, &requirements);
if (!device->GetMemoryAllocator()->Allocate(requirements, false, &mMemoryAllocation)) {
ASSERT(false);
}
if (device->fn.BindImageMemory(device->GetVkDevice(), mHandle,
mMemoryAllocation.GetMemory(),
mMemoryAllocation.GetMemoryOffset()) != VK_SUCCESS) {
ASSERT(false);
}
}
Texture::~Texture() {
Device* device = ToBackend(GetDevice());
// We need to free both the memory allocation and the container. Memory should be freed
// after the VkImage is destroyed and this is taken care of by the FencedDeleter.
device->GetMemoryAllocator()->Free(&mMemoryAllocation);
if (mHandle != VK_NULL_HANDLE) {
device->GetFencedDeleter()->DeleteWhenUnused(mHandle);
mHandle = VK_NULL_HANDLE;
}
}
VkImage Texture::GetHandle() const {
return mHandle;
}
VkImageAspectFlags Texture::GetVkAspectMask() const {
return VulkanAspectMask(GetFormat());
}
// Helper function to add a texture barrier to a command buffer. This is inefficient because we
// should be coalescing barriers as much as possible.
void Texture::RecordBarrier(VkCommandBuffer commands,
nxt::TextureUsageBit currentUsage,
nxt::TextureUsageBit targetUsage) const {
nxt::TextureFormat format = GetFormat();
VkPipelineStageFlags srcStages = VulkanPipelineStage(currentUsage, format);
VkPipelineStageFlags dstStages = VulkanPipelineStage(targetUsage, format);
VkImageMemoryBarrier barrier;
barrier.sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER;
barrier.pNext = nullptr;
barrier.srcAccessMask = VulkanAccessFlags(currentUsage, format);
barrier.dstAccessMask = VulkanAccessFlags(targetUsage, format);
barrier.oldLayout = VulkanImageLayout(currentUsage, format);
barrier.newLayout = VulkanImageLayout(targetUsage, format);
barrier.srcQueueFamilyIndex = 0;
barrier.dstQueueFamilyIndex = 0;
barrier.image = mHandle;
// This transitions the whole resource but assumes it is a 2D texture
ASSERT(GetDimension() == nxt::TextureDimension::e2D);
barrier.subresourceRange.aspectMask = VulkanAspectMask(format);
barrier.subresourceRange.baseMipLevel = 0;
barrier.subresourceRange.levelCount = GetNumMipLevels();
barrier.subresourceRange.baseArrayLayer = 0;
barrier.subresourceRange.layerCount = 1;
ToBackend(GetDevice())
->fn.CmdPipelineBarrier(commands, srcStages, dstStages, 0, 0, nullptr, 0, nullptr, 1,
&barrier);
}
void Texture::TransitionUsageImpl(nxt::TextureUsageBit currentUsage,
nxt::TextureUsageBit targetUsage) {
VkCommandBuffer commands = ToBackend(GetDevice())->GetPendingCommandBuffer();
RecordBarrier(commands, currentUsage, targetUsage);
}
TextureView::TextureView(TextureViewBuilder* builder) : TextureViewBase(builder) {
Device* device = ToBackend(builder->GetDevice());
VkImageViewCreateInfo createInfo;
createInfo.sType = VK_STRUCTURE_TYPE_IMAGE_VIEW_CREATE_INFO;
createInfo.pNext = nullptr;
createInfo.flags = 0;
createInfo.image = ToBackend(GetTexture())->GetHandle();
createInfo.viewType = VulkanImageViewType(GetTexture()->GetDimension());
createInfo.format = VulkanImageFormat(GetTexture()->GetFormat());
createInfo.components = VkComponentMapping{VK_COMPONENT_SWIZZLE_R, VK_COMPONENT_SWIZZLE_G,
VK_COMPONENT_SWIZZLE_B, VK_COMPONENT_SWIZZLE_A};
createInfo.subresourceRange.aspectMask = VulkanAspectMask(GetTexture()->GetFormat());
createInfo.subresourceRange.baseMipLevel = 0;
createInfo.subresourceRange.levelCount = GetTexture()->GetNumMipLevels();
createInfo.subresourceRange.baseArrayLayer = 0;
createInfo.subresourceRange.layerCount = 1;
if (device->fn.CreateImageView(device->GetVkDevice(), &createInfo, nullptr, &mHandle) !=
VK_SUCCESS) {
ASSERT(false);
}
}
TextureView::~TextureView() {
Device* device = ToBackend(GetTexture()->GetDevice());
if (mHandle != VK_NULL_HANDLE) {
device->GetFencedDeleter()->DeleteWhenUnused(mHandle);
mHandle = VK_NULL_HANDLE;
}
}
VkImageView TextureView::GetHandle() const {
return mHandle;
}
}} // namespace backend::vulkan
<commit_msg>TextureVk: Transition to the first usage if needed<commit_after>// Copyright 2018 The NXT 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 "backend/vulkan/TextureVk.h"
#include "backend/vulkan/FencedDeleter.h"
#include "backend/vulkan/VulkanBackend.h"
namespace backend { namespace vulkan {
namespace {
// Converts an NXT texture dimension to a Vulkan image type.
// Note that in Vulkan dimensionality is only 1D, 2D, 3D. Arrays and cube maps are expressed
// via the array size and a "cubemap compatible" flag.
VkImageType VulkanImageType(nxt::TextureDimension dimension) {
switch (dimension) {
case nxt::TextureDimension::e2D:
return VK_IMAGE_TYPE_2D;
default:
UNREACHABLE();
}
}
// Converts an NXT texture dimension to a Vulkan image view type.
// Contrary to image types, image view types include arrayness and cubemapness
VkImageViewType VulkanImageViewType(nxt::TextureDimension dimension) {
switch (dimension) {
case nxt::TextureDimension::e2D:
return VK_IMAGE_VIEW_TYPE_2D;
default:
UNREACHABLE();
}
}
// Converts the NXT usage flags to Vulkan usage flags. Also needs the format to choose
// between color and depth attachment usages.
VkImageUsageFlags VulkanImageUsage(nxt::TextureUsageBit usage, nxt::TextureFormat format) {
VkImageUsageFlags flags = 0;
if (usage & nxt::TextureUsageBit::TransferSrc) {
flags |= VK_IMAGE_USAGE_TRANSFER_SRC_BIT;
}
if (usage & nxt::TextureUsageBit::TransferDst) {
flags |= VK_IMAGE_USAGE_TRANSFER_DST_BIT;
}
if (usage & nxt::TextureUsageBit::Sampled) {
flags |= VK_IMAGE_USAGE_SAMPLED_BIT;
}
if (usage & nxt::TextureUsageBit::Storage) {
flags |= VK_IMAGE_USAGE_STORAGE_BIT;
}
if (usage & nxt::TextureUsageBit::OutputAttachment) {
if (TextureFormatHasDepthOrStencil(format)) {
flags |= VK_IMAGE_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT;
} else {
flags |= VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT;
}
}
return flags;
}
// Computes which vulkan access type could be required for the given NXT usage.
VkAccessFlags VulkanAccessFlags(nxt::TextureUsageBit usage, nxt::TextureFormat format) {
VkAccessFlags flags = 0;
if (usage & nxt::TextureUsageBit::TransferSrc) {
flags |= VK_ACCESS_TRANSFER_READ_BIT;
}
if (usage & nxt::TextureUsageBit::TransferDst) {
flags |= VK_ACCESS_TRANSFER_WRITE_BIT;
}
if (usage & nxt::TextureUsageBit::Sampled) {
flags |= VK_ACCESS_SHADER_READ_BIT;
}
if (usage & nxt::TextureUsageBit::Storage) {
flags |= VK_ACCESS_SHADER_READ_BIT | VK_ACCESS_SHADER_WRITE_BIT;
}
if (usage & nxt::TextureUsageBit::OutputAttachment) {
if (TextureFormatHasDepthOrStencil(format)) {
flags |= VK_ACCESS_DEPTH_STENCIL_ATTACHMENT_READ_BIT |
VK_ACCESS_DEPTH_STENCIL_ATTACHMENT_WRITE_BIT;
} else {
flags |=
VK_ACCESS_COLOR_ATTACHMENT_READ_BIT | VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT;
}
}
// TODO(cwallez@chromium.org): What about present? Does it require VK_MEMORY_READ_BIT?
return flags;
}
// Chooses which Vulkan image layout should be used for the given NXT usage
VkImageLayout VulkanImageLayout(nxt::TextureUsageBit usage, nxt::TextureFormat format) {
if (usage == nxt::TextureUsageBit::None) {
return VK_IMAGE_LAYOUT_UNDEFINED;
}
if (!nxt::HasZeroOrOneBits(usage)) {
return VK_IMAGE_LAYOUT_GENERAL;
}
// Usage has a single bit so we can switch on its value directly.
switch (usage) {
case nxt::TextureUsageBit::TransferDst:
return VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL;
case nxt::TextureUsageBit::Sampled:
return VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL;
// Vulkan texture copy functions require the image to be in _one_ known layout.
// Depending on whether parts of the texture have been transitioned to only
// TransferSrc or a combination with something else, the texture could be in a
// combination of GENERAL and TRANSFER_SRC_OPTIMAL. This would be a problem, so we
// make TransferSrc use GENERAL.
case nxt::TextureUsageBit::TransferSrc:
// Writable storage textures must use general. If we could know the texture is read
// only we could use SHADER_READ_ONLY_OPTIMAL
case nxt::TextureUsageBit::Storage:
case nxt::TextureUsageBit::Present:
return VK_IMAGE_LAYOUT_GENERAL;
case nxt::TextureUsageBit::OutputAttachment:
if (TextureFormatHasDepthOrStencil(format)) {
return VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL;
} else {
return VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL;
}
default:
UNREACHABLE();
}
}
// Computes which Vulkan pipeline stage can access a texture in the given NXT usage
VkPipelineStageFlags VulkanPipelineStage(nxt::TextureUsageBit usage,
nxt::TextureFormat format) {
VkPipelineStageFlags flags = 0;
if (usage == nxt::TextureUsageBit::None) {
// This only happens when a texture is initially created (and for srcAccessMask) in
// which case there is no need to wait on anything to stop accessing this texture.
return VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT;
}
if (usage & (nxt::TextureUsageBit::TransferSrc | nxt::TextureUsageBit::TransferDst)) {
flags |= VK_PIPELINE_STAGE_TRANSFER_BIT;
}
if (usage & (nxt::TextureUsageBit::Sampled | nxt::TextureUsageBit::Storage)) {
flags |= VK_PIPELINE_STAGE_VERTEX_SHADER_BIT |
VK_PIPELINE_STAGE_FRAGMENT_SHADER_BIT |
VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT;
}
if (usage & nxt::TextureUsageBit::OutputAttachment) {
if (TextureFormatHasDepthOrStencil(format)) {
flags |= VK_PIPELINE_STAGE_EARLY_FRAGMENT_TESTS_BIT |
VK_PIPELINE_STAGE_LATE_FRAGMENT_TESTS_BIT;
// TODO(cwallez@chromium.org): This is missing the stage where the depth and
// stencil values are written, but it isn't clear which one it is.
} else {
flags |= VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT;
}
}
// TODO(cwallez@chromium.org) What about present?
return flags;
}
// Computes which Vulkan texture aspects are relevant for the given NXT format
VkImageAspectFlags VulkanAspectMask(nxt::TextureFormat format) {
bool isDepth = TextureFormatHasDepth(format);
bool isStencil = TextureFormatHasStencil(format);
VkImageAspectFlags flags = 0;
if (isDepth) {
flags |= VK_IMAGE_ASPECT_DEPTH_BIT;
}
if (isStencil) {
flags |= VK_IMAGE_ASPECT_STENCIL_BIT;
}
if (flags != 0) {
return flags;
}
return VK_IMAGE_ASPECT_COLOR_BIT;
}
} // namespace
// Converts NXT texture format to Vulkan formats.
VkFormat VulkanImageFormat(nxt::TextureFormat format) {
switch (format) {
case nxt::TextureFormat::R8G8B8A8Unorm:
return VK_FORMAT_R8G8B8A8_UNORM;
case nxt::TextureFormat::R8G8B8A8Uint:
return VK_FORMAT_R8G8B8A8_UINT;
case nxt::TextureFormat::B8G8R8A8Unorm:
return VK_FORMAT_B8G8R8A8_UNORM;
case nxt::TextureFormat::D32FloatS8Uint:
return VK_FORMAT_D32_SFLOAT_S8_UINT;
default:
UNREACHABLE();
}
}
Texture::Texture(TextureBuilder* builder) : TextureBase(builder) {
Device* device = ToBackend(GetDevice());
// Create the Vulkan image "container". We don't need to check that the format supports the
// combination of sample, usage etc. because validation should have been done in the NXT
// frontend already based on the minimum supported formats in the Vulkan spec
VkImageCreateInfo createInfo;
createInfo.sType = VK_STRUCTURE_TYPE_IMAGE_CREATE_INFO;
createInfo.pNext = nullptr;
createInfo.flags = 0;
createInfo.imageType = VulkanImageType(GetDimension());
createInfo.format = VulkanImageFormat(GetFormat());
createInfo.extent = VkExtent3D{GetWidth(), GetHeight(), GetDepth()};
createInfo.mipLevels = GetNumMipLevels();
createInfo.arrayLayers = 1;
createInfo.samples = VK_SAMPLE_COUNT_1_BIT;
createInfo.tiling = VK_IMAGE_TILING_OPTIMAL;
createInfo.usage = VulkanImageUsage(GetAllowedUsage(), GetFormat());
createInfo.sharingMode = VK_SHARING_MODE_EXCLUSIVE;
createInfo.queueFamilyIndexCount = 0;
createInfo.pQueueFamilyIndices = nullptr;
createInfo.initialLayout = VK_IMAGE_LAYOUT_UNDEFINED;
if (device->fn.CreateImage(device->GetVkDevice(), &createInfo, nullptr, &mHandle) !=
VK_SUCCESS) {
ASSERT(false);
}
// Create the image memory and associate it with the container
VkMemoryRequirements requirements;
device->fn.GetImageMemoryRequirements(device->GetVkDevice(), mHandle, &requirements);
if (!device->GetMemoryAllocator()->Allocate(requirements, false, &mMemoryAllocation)) {
ASSERT(false);
}
if (device->fn.BindImageMemory(device->GetVkDevice(), mHandle,
mMemoryAllocation.GetMemory(),
mMemoryAllocation.GetMemoryOffset()) != VK_SUCCESS) {
ASSERT(false);
}
// Vulkan requires images to be transitioned to their first usage. Do the transition if the
// texture has an initial usage.
if (GetUsage() != nxt::TextureUsageBit::None) {
TransitionUsageImpl(nxt::TextureUsageBit::None, GetUsage());
}
}
Texture::~Texture() {
Device* device = ToBackend(GetDevice());
// We need to free both the memory allocation and the container. Memory should be freed
// after the VkImage is destroyed and this is taken care of by the FencedDeleter.
device->GetMemoryAllocator()->Free(&mMemoryAllocation);
if (mHandle != VK_NULL_HANDLE) {
device->GetFencedDeleter()->DeleteWhenUnused(mHandle);
mHandle = VK_NULL_HANDLE;
}
}
VkImage Texture::GetHandle() const {
return mHandle;
}
VkImageAspectFlags Texture::GetVkAspectMask() const {
return VulkanAspectMask(GetFormat());
}
// Helper function to add a texture barrier to a command buffer. This is inefficient because we
// should be coalescing barriers as much as possible.
void Texture::RecordBarrier(VkCommandBuffer commands,
nxt::TextureUsageBit currentUsage,
nxt::TextureUsageBit targetUsage) const {
nxt::TextureFormat format = GetFormat();
VkPipelineStageFlags srcStages = VulkanPipelineStage(currentUsage, format);
VkPipelineStageFlags dstStages = VulkanPipelineStage(targetUsage, format);
VkImageMemoryBarrier barrier;
barrier.sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER;
barrier.pNext = nullptr;
barrier.srcAccessMask = VulkanAccessFlags(currentUsage, format);
barrier.dstAccessMask = VulkanAccessFlags(targetUsage, format);
barrier.oldLayout = VulkanImageLayout(currentUsage, format);
barrier.newLayout = VulkanImageLayout(targetUsage, format);
barrier.srcQueueFamilyIndex = 0;
barrier.dstQueueFamilyIndex = 0;
barrier.image = mHandle;
// This transitions the whole resource but assumes it is a 2D texture
ASSERT(GetDimension() == nxt::TextureDimension::e2D);
barrier.subresourceRange.aspectMask = VulkanAspectMask(format);
barrier.subresourceRange.baseMipLevel = 0;
barrier.subresourceRange.levelCount = GetNumMipLevels();
barrier.subresourceRange.baseArrayLayer = 0;
barrier.subresourceRange.layerCount = 1;
ToBackend(GetDevice())
->fn.CmdPipelineBarrier(commands, srcStages, dstStages, 0, 0, nullptr, 0, nullptr, 1,
&barrier);
}
void Texture::TransitionUsageImpl(nxt::TextureUsageBit currentUsage,
nxt::TextureUsageBit targetUsage) {
VkCommandBuffer commands = ToBackend(GetDevice())->GetPendingCommandBuffer();
RecordBarrier(commands, currentUsage, targetUsage);
}
TextureView::TextureView(TextureViewBuilder* builder) : TextureViewBase(builder) {
Device* device = ToBackend(builder->GetDevice());
VkImageViewCreateInfo createInfo;
createInfo.sType = VK_STRUCTURE_TYPE_IMAGE_VIEW_CREATE_INFO;
createInfo.pNext = nullptr;
createInfo.flags = 0;
createInfo.image = ToBackend(GetTexture())->GetHandle();
createInfo.viewType = VulkanImageViewType(GetTexture()->GetDimension());
createInfo.format = VulkanImageFormat(GetTexture()->GetFormat());
createInfo.components = VkComponentMapping{VK_COMPONENT_SWIZZLE_R, VK_COMPONENT_SWIZZLE_G,
VK_COMPONENT_SWIZZLE_B, VK_COMPONENT_SWIZZLE_A};
createInfo.subresourceRange.aspectMask = VulkanAspectMask(GetTexture()->GetFormat());
createInfo.subresourceRange.baseMipLevel = 0;
createInfo.subresourceRange.levelCount = GetTexture()->GetNumMipLevels();
createInfo.subresourceRange.baseArrayLayer = 0;
createInfo.subresourceRange.layerCount = 1;
if (device->fn.CreateImageView(device->GetVkDevice(), &createInfo, nullptr, &mHandle) !=
VK_SUCCESS) {
ASSERT(false);
}
}
TextureView::~TextureView() {
Device* device = ToBackend(GetTexture()->GetDevice());
if (mHandle != VK_NULL_HANDLE) {
device->GetFencedDeleter()->DeleteWhenUnused(mHandle);
mHandle = VK_NULL_HANDLE;
}
}
VkImageView TextureView::GetHandle() const {
return mHandle;
}
}} // namespace backend::vulkan
<|endoftext|> |
<commit_before>#include "geometry/spline.hpp"
#include "base/logging.hpp"
#include "std/numeric.hpp"
namespace m2
{
Spline::Spline(vector<PointD> const & path)
{
ASSERT(path.size() > 1, ("Wrong path size!"));
m_position.assign(path.begin(), path.end());
size_t cnt = m_position.size() - 1;
m_direction = vector<PointD>(cnt);
m_length = vector<double>(cnt);
for(int i = 0; i < cnt; ++i)
{
m_direction[i] = path[i+1] - path[i];
m_length[i] = m_direction[i].Length();
m_direction[i] = m_direction[i].Normalize();
}
}
Spline::Spline(size_t reservedSize)
{
ASSERT_LESS(0, reservedSize, ());
m_position.reserve(reservedSize);
m_direction.reserve(reservedSize - 1);
m_length.reserve(reservedSize - 1);
}
void Spline::AddPoint(PointD const & pt)
{
/// TODO remove this check when fix generator.
/// Now we have line objects with zero length segments
if (!IsEmpty() && (pt - m_position.back()).IsAlmostZero())
{
LOG(LDEBUG, ("Found a zero-length segment (the endpoints coincide)"));
return;
}
if(IsEmpty())
m_position.push_back(pt);
else
{
PointD dir = pt - m_position.back();
m_position.push_back(pt);
m_length.push_back(dir.Length());
m_direction.push_back(dir.Normalize());
}
}
void Spline::ReplacePoint(PointD const & pt)
{
ASSERT(m_position.size() > 1, ());
ASSERT(!m_length.empty(), ());
ASSERT(!m_direction.empty(), ());
m_position.pop_back();
m_length.pop_back();
m_direction.pop_back();
AddPoint(pt);
}
bool Spline::IsPrelonging(PointD const & pt)
{
if (m_position.size() < 2)
return false;
PointD dir = pt - m_position.back();
if (dir.IsAlmostZero())
return true;
dir = dir.Normalize();
PointD prevDir = m_direction.back().Normalize();
double const MAX_ANGLE_THRESHOLD = 0.995;
return fabs(DotProduct(prevDir, dir)) > MAX_ANGLE_THRESHOLD;
}
size_t Spline::GetSize() const
{
return m_position.size();
}
bool Spline::IsEmpty() const
{
return m_position.empty();
}
bool Spline::IsValid() const
{
return m_position.size() > 1;
}
Spline const & Spline::operator = (Spline const & spl)
{
if(&spl != this)
{
m_position = spl.m_position;
m_direction = spl.m_direction;
m_length = spl.m_length;
}
return *this;
}
double Spline::GetLength() const
{
return accumulate(m_length.begin(), m_length.end(), 0.0);
}
Spline::iterator::iterator()
: m_checker(false)
, m_spl(NULL)
, m_index(0)
, m_dist(0) {}
Spline::iterator::iterator(Spline::iterator const & other)
{
m_checker = other.m_checker;
m_spl = other.m_spl;
m_index = other.m_index;
m_dist = other.m_dist;
m_pos = other.m_pos;
m_dir = other.m_dir;
m_avrDir = other.m_avrDir;
}
Spline::iterator & Spline::iterator::operator=(Spline::iterator const & other)
{
if (this == &other)
return *this;
m_checker = other.m_checker;
m_spl = other.m_spl;
m_index = other.m_index;
m_dist = other.m_dist;
m_pos = other.m_pos;
m_dir = other.m_dir;
m_avrDir = other.m_avrDir;
return *this;
}
void Spline::iterator::Attach(Spline const & spl)
{
m_spl = &spl;
m_index = 0;
m_dist = 0;
m_checker = false;
m_dir = m_spl->m_direction[m_index];
m_avrDir = m_spl->m_direction[m_index];
m_pos = m_spl->m_position[m_index] + m_dir * m_dist;
}
void Spline::iterator::Advance(double step)
{
if (step < 0.0)
AdvanceBackward(step);
else
AdvanceForward(step);
}
double Spline::iterator::GetLength() const
{
return accumulate(m_spl->m_length.begin(), m_spl->m_length.begin() + m_index, m_dist);
}
double Spline::iterator::GetFullLength() const
{
return m_spl->GetLength();
}
bool Spline::iterator::BeginAgain() const
{
return m_checker;
}
double Spline::iterator::GetDistance() const
{
return m_dist;
}
int Spline::iterator::GetIndex() const
{
return m_index;
}
void Spline::iterator::AdvanceBackward(double step)
{
m_dist += step;
while(m_dist < 0.0f)
{
m_index--;
if (m_index < 0)
{
m_index = 0;
m_checker = true;
m_pos = m_spl->m_position[m_index];
m_dir = m_spl->m_direction[m_index];
m_avrDir = m2::PointD::Zero();
m_dist = 0.0;
return;
}
m_dist += m_spl->m_length[m_index];
}
m_dir = m_spl->m_direction[m_index];
m_avrDir = -m_pos;
m_pos = m_spl->m_position[m_index] + m_dir * m_dist;
m_avrDir += m_pos;
}
void Spline::iterator::AdvanceForward(double step)
{
m_dist += step;
if (m_checker)
{
m_pos = m_spl->m_position[m_index] + m_dir * m_dist;
return;
}
while (m_dist > m_spl->m_length[m_index])
{
m_dist -= m_spl->m_length[m_index];
m_index++;
if (m_index >= m_spl->m_direction.size())
{
m_index--;
m_dist += m_spl->m_length[m_index];
m_checker = true;
break;
}
}
m_dir = m_spl->m_direction[m_index];
m_avrDir = -m_pos;
m_pos = m_spl->m_position[m_index] + m_dir * m_dist;
m_avrDir += m_pos;
}
SharedSpline::SharedSpline(vector<PointD> const & path)
{
m_spline.reset(new Spline(path));
}
SharedSpline::SharedSpline(SharedSpline const & other)
{
if (this != &other)
m_spline = other.m_spline;
}
SharedSpline const & SharedSpline::operator= (SharedSpline const & spl)
{
if (this != &spl)
m_spline = spl.m_spline;
return *this;
}
bool SharedSpline::IsNull() const
{
return m_spline == NULL;
}
void SharedSpline::Reset(Spline * spline)
{
m_spline.reset(spline);
}
void SharedSpline::Reset(vector<PointD> const & path)
{
m_spline.reset(new Spline(path));
}
Spline::iterator SharedSpline::CreateIterator() const
{
Spline::iterator result;
result.Attach(*m_spline.get());
return result;
}
Spline * SharedSpline::operator->()
{
ASSERT(!IsNull(), ());
return m_spline.get();
}
Spline const * SharedSpline::operator->() const
{
ASSERT(!IsNull(), ());
return m_spline.get();
}
}
<commit_msg>[geometry] Removed a log about zero length segments.<commit_after>#include "geometry/spline.hpp"
#include "base/logging.hpp"
#include "std/numeric.hpp"
namespace m2
{
Spline::Spline(vector<PointD> const & path)
{
ASSERT(path.size() > 1, ("Wrong path size!"));
m_position.assign(path.begin(), path.end());
size_t cnt = m_position.size() - 1;
m_direction = vector<PointD>(cnt);
m_length = vector<double>(cnt);
for(int i = 0; i < cnt; ++i)
{
m_direction[i] = path[i+1] - path[i];
m_length[i] = m_direction[i].Length();
m_direction[i] = m_direction[i].Normalize();
}
}
Spline::Spline(size_t reservedSize)
{
ASSERT_LESS(0, reservedSize, ());
m_position.reserve(reservedSize);
m_direction.reserve(reservedSize - 1);
m_length.reserve(reservedSize - 1);
}
void Spline::AddPoint(PointD const & pt)
{
/// TODO remove this check when fix generator.
/// Now we have line objects with zero length segments
if (!IsEmpty() && (pt - m_position.back()).IsAlmostZero())
return;
if(IsEmpty())
m_position.push_back(pt);
else
{
PointD dir = pt - m_position.back();
m_position.push_back(pt);
m_length.push_back(dir.Length());
m_direction.push_back(dir.Normalize());
}
}
void Spline::ReplacePoint(PointD const & pt)
{
ASSERT(m_position.size() > 1, ());
ASSERT(!m_length.empty(), ());
ASSERT(!m_direction.empty(), ());
m_position.pop_back();
m_length.pop_back();
m_direction.pop_back();
AddPoint(pt);
}
bool Spline::IsPrelonging(PointD const & pt)
{
if (m_position.size() < 2)
return false;
PointD dir = pt - m_position.back();
if (dir.IsAlmostZero())
return true;
dir = dir.Normalize();
PointD prevDir = m_direction.back().Normalize();
double const MAX_ANGLE_THRESHOLD = 0.995;
return fabs(DotProduct(prevDir, dir)) > MAX_ANGLE_THRESHOLD;
}
size_t Spline::GetSize() const
{
return m_position.size();
}
bool Spline::IsEmpty() const
{
return m_position.empty();
}
bool Spline::IsValid() const
{
return m_position.size() > 1;
}
Spline const & Spline::operator = (Spline const & spl)
{
if(&spl != this)
{
m_position = spl.m_position;
m_direction = spl.m_direction;
m_length = spl.m_length;
}
return *this;
}
double Spline::GetLength() const
{
return accumulate(m_length.begin(), m_length.end(), 0.0);
}
Spline::iterator::iterator()
: m_checker(false)
, m_spl(NULL)
, m_index(0)
, m_dist(0) {}
Spline::iterator::iterator(Spline::iterator const & other)
{
m_checker = other.m_checker;
m_spl = other.m_spl;
m_index = other.m_index;
m_dist = other.m_dist;
m_pos = other.m_pos;
m_dir = other.m_dir;
m_avrDir = other.m_avrDir;
}
Spline::iterator & Spline::iterator::operator=(Spline::iterator const & other)
{
if (this == &other)
return *this;
m_checker = other.m_checker;
m_spl = other.m_spl;
m_index = other.m_index;
m_dist = other.m_dist;
m_pos = other.m_pos;
m_dir = other.m_dir;
m_avrDir = other.m_avrDir;
return *this;
}
void Spline::iterator::Attach(Spline const & spl)
{
m_spl = &spl;
m_index = 0;
m_dist = 0;
m_checker = false;
m_dir = m_spl->m_direction[m_index];
m_avrDir = m_spl->m_direction[m_index];
m_pos = m_spl->m_position[m_index] + m_dir * m_dist;
}
void Spline::iterator::Advance(double step)
{
if (step < 0.0)
AdvanceBackward(step);
else
AdvanceForward(step);
}
double Spline::iterator::GetLength() const
{
return accumulate(m_spl->m_length.begin(), m_spl->m_length.begin() + m_index, m_dist);
}
double Spline::iterator::GetFullLength() const
{
return m_spl->GetLength();
}
bool Spline::iterator::BeginAgain() const
{
return m_checker;
}
double Spline::iterator::GetDistance() const
{
return m_dist;
}
int Spline::iterator::GetIndex() const
{
return m_index;
}
void Spline::iterator::AdvanceBackward(double step)
{
m_dist += step;
while(m_dist < 0.0f)
{
m_index--;
if (m_index < 0)
{
m_index = 0;
m_checker = true;
m_pos = m_spl->m_position[m_index];
m_dir = m_spl->m_direction[m_index];
m_avrDir = m2::PointD::Zero();
m_dist = 0.0;
return;
}
m_dist += m_spl->m_length[m_index];
}
m_dir = m_spl->m_direction[m_index];
m_avrDir = -m_pos;
m_pos = m_spl->m_position[m_index] + m_dir * m_dist;
m_avrDir += m_pos;
}
void Spline::iterator::AdvanceForward(double step)
{
m_dist += step;
if (m_checker)
{
m_pos = m_spl->m_position[m_index] + m_dir * m_dist;
return;
}
while (m_dist > m_spl->m_length[m_index])
{
m_dist -= m_spl->m_length[m_index];
m_index++;
if (m_index >= m_spl->m_direction.size())
{
m_index--;
m_dist += m_spl->m_length[m_index];
m_checker = true;
break;
}
}
m_dir = m_spl->m_direction[m_index];
m_avrDir = -m_pos;
m_pos = m_spl->m_position[m_index] + m_dir * m_dist;
m_avrDir += m_pos;
}
SharedSpline::SharedSpline(vector<PointD> const & path)
{
m_spline.reset(new Spline(path));
}
SharedSpline::SharedSpline(SharedSpline const & other)
{
if (this != &other)
m_spline = other.m_spline;
}
SharedSpline const & SharedSpline::operator= (SharedSpline const & spl)
{
if (this != &spl)
m_spline = spl.m_spline;
return *this;
}
bool SharedSpline::IsNull() const
{
return m_spline == NULL;
}
void SharedSpline::Reset(Spline * spline)
{
m_spline.reset(spline);
}
void SharedSpline::Reset(vector<PointD> const & path)
{
m_spline.reset(new Spline(path));
}
Spline::iterator SharedSpline::CreateIterator() const
{
Spline::iterator result;
result.Attach(*m_spline.get());
return result;
}
Spline * SharedSpline::operator->()
{
ASSERT(!IsNull(), ());
return m_spline.get();
}
Spline const * SharedSpline::operator->() const
{
ASSERT(!IsNull(), ());
return m_spline.get();
}
}
<|endoftext|> |
<commit_before>#pragma once
#include <cmath>
#include <algorithm>
using std::max;
using std::abs;
using std::hypot;
using std::find;
namespace search
{
template<typename Node>
inline auto dy(Node const& node) -> Size
{
return abs(node.goal().y - node.coordinate().y);
}
template<typename Node>
inline auto dx(Node const& node) -> Size
{
return abs(node.goal().x - node.coordinate().x);
}
template<typename Node>
struct Heuristc{};
template<typename Node>
struct ManhattanDistance : public Heuristc<Node>
{
auto operator()(Node const& node) const -> Size
{
return max(dy(node), dx(node));
}
};
template<typename Node>
struct EuclideanDinstance : public Heuristc<Node>
{
auto operator()(Node const& node) const -> Size
{
return static_cast<Size>(round(hypot(dy(node), dx(node))));
}
};
template<typename Node>
struct Cost
{
auto operator()(Node const& node) const -> Size
{
return node.path().size();
}
};
template<typename Node, typename Hfunc, typename Cfunc = Cost<Node>>
struct Less
{
Hfunc h;
Cfunc c;
auto operator()(Node const& lhs, Node const& rhs) const -> Size
{
return h(lhs) + c(lhs) < h(rhs) + c(rhs);
}
};
}//end of namespace
<commit_msg>polished<commit_after>#pragma once
#include <cmath>
#include <algorithm>
using std::max;
using std::abs;
using std::hypot;
using std::find;
namespace search
{
template<typename Node>
inline auto dy(Node const& node) -> Size
{
return abs(node.goal().y - node.coordinate().y);
}
template<typename Node>
inline auto dx(Node const& node) -> Size
{
return abs(node.goal().x - node.coordinate().x);
}
template<typename Node>
struct Heuristc{};
template<typename Node>
struct ManhattanDistance : public Heuristc<Node>
{
auto operator()(Node const& node) const -> Size
{
return max(dy(node), dx(node));
}
};
template<typename Node>
struct EuclideanDinstance : public Heuristc<Node>
{
auto operator()(Node const& node) const -> Size
{
return static_cast<Size>(round(hypot(dy(node), dx(node))));
}
};
template<typename Node>
struct Cost
{
auto operator()(Node const& node) const -> Size
{
return node.path().size();
}
};
template<typename Node, typename Hfunc, typename Cfunc = Cost<Node>>
struct Less
{
Hfunc h;
Cfunc c;
auto operator()(Node const& lhs, Node const& rhs) const -> Size
{
return h(lhs) + c(lhs) < h(rhs) + c(rhs);
}
};
}//end of namespace
<|endoftext|> |
<commit_before>// Copyright (c) 2008, Jacob Burnim (jburnim@cs.berkeley.edu)
//
// This file is part of CREST, which is distributed under the revised
// BSD license. A copy of this license can be found in the file LICENSE.
//
// 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 LICENSE
// for details.
#include <algorithm>
#include <assert.h>
#include <stdio.h>
#include <utility>
#include <vector>
#include "base/symbolic_interpreter.h"
#include "base/yices_solver.h"
using std::make_pair;
using std::swap;
using std::vector;
#ifdef DEBUG
#define IFDEBUG(x) x
#else
#define IFDEBUG(x)
#endif
namespace crest {
typedef map<addr_t,SymbolicExpr*>::const_iterator ConstMemIt;
SymbolicInterpreter::SymbolicInterpreter()
: pred_(NULL), return_value_(false), ex_(true), num_inputs_(0) {
stack_.reserve(16);
}
SymbolicInterpreter::SymbolicInterpreter(const vector<value_t>& input)
: pred_(NULL), return_value_(false), ex_(true), num_inputs_(0) {
stack_.reserve(16);
ex_.mutable_inputs()->assign(input.begin(), input.end());
}
void SymbolicInterpreter::DumpMemory() {
for (ConstMemIt i = mem_.begin(); i != mem_.end(); ++i) {
string s;
i->second->AppendToString(&s);
fprintf(stderr, "%lu: %s [%d]\n", i->first, s.c_str(), *(int*)(i->first));
}
for (size_t i = 0; i < stack_.size(); i++) {
string s;
if (stack_[i].expr) {
stack_[i].expr->AppendToString(&s);
} else if ((i == stack_.size() - 1) && pred_) {
pred_->AppendToString(&s);
}
fprintf(stderr, "s%d: %lld [ %s ]\n", i, stack_[i].concrete, s.c_str());
}
}
void SymbolicInterpreter::ClearStack(id_t id) {
IFDEBUG(fprintf(stderr, "clear\n"));
for (vector<StackElem>::const_iterator it = stack_.begin(); it != stack_.end(); ++it) {
delete it->expr;
}
stack_.clear();
ClearPredicateRegister();
return_value_ = false;
IFDEBUG(DumpMemory());
}
void SymbolicInterpreter::Load(id_t id, addr_t addr, value_t value) {
IFDEBUG(fprintf(stderr, "load %lu %lld\n", addr, value));
ConstMemIt it = mem_.find(addr);
if (it == mem_.end()) {
PushConcrete(value);
} else {
PushSymbolic(new SymbolicExpr(*it->second), value);
}
ClearPredicateRegister();
IFDEBUG(DumpMemory());
}
void SymbolicInterpreter::Store(id_t id, addr_t addr) {
IFDEBUG(fprintf(stderr, "store %lu\n", addr));
assert(stack_.size() > 0);
const StackElem& se = stack_.back();
if (se.expr) {
if (!se.expr->IsConcrete()) {
mem_[addr] = se.expr;
} else {
mem_.erase(addr);
delete se.expr;
}
} else {
mem_.erase(addr);
}
stack_.pop_back();
ClearPredicateRegister();
IFDEBUG(DumpMemory());
}
void SymbolicInterpreter::ApplyUnaryOp(id_t id, unary_op_t op, value_t value) {
IFDEBUG(fprintf(stderr, "apply1 %d %lld\n", op, value));
assert(stack_.size() >= 1);
StackElem& se = stack_.back();
if (se.expr) {
switch (op) {
case ops::NEGATE:
se.expr->Negate();
ClearPredicateRegister();
break;
case ops::LOGICAL_NOT:
if (pred_) {
pred_->Negate();
break;
}
// Otherwise, fall through to the concrete case.
default:
// Concrete operator.
delete se.expr;
se.expr = NULL;
ClearPredicateRegister();
}
}
se.concrete = value;
IFDEBUG(DumpMemory());
}
void SymbolicInterpreter::ApplyBinaryOp(id_t id, binary_op_t op, value_t value) {
IFDEBUG(fprintf(stderr, "apply2 %d %lld\n", op, value));
assert(stack_.size() >= 2);
StackElem& a = *(stack_.rbegin()+1);
StackElem& b = stack_.back();
if (a.expr || b.expr) {
switch (op) {
case ops::ADD:
if (a.expr == NULL) {
swap(a, b);
*a.expr += b.concrete;
} else if (b.expr == NULL) {
*a.expr += b.concrete;
} else {
*a.expr += *b.expr;
delete b.expr;
}
break;
case ops::SUBTRACT:
if (a.expr == NULL) {
b.expr->Negate();
swap(a, b);
*a.expr += b.concrete;
} else if (b.expr == NULL) {
*a.expr -= b.concrete;
} else {
*a.expr -= *b.expr;
delete b.expr;
}
break;
case ops::SHIFT_L:
if (a.expr != NULL) {
// Convert to multiplication by a (concrete) constant.
*a.expr *= (1 << b.concrete);
}
delete b.expr;
break;
case ops::MULTIPLY:
if (a.expr == NULL) {
swap(a, b);
*a.expr *= b.concrete;
} else if (b.expr == NULL) {
*a.expr *= b.concrete;
} else {
swap(a, b);
*a.expr *= b.concrete;
delete b.expr;
}
break;
default:
// Concrete operator.
delete a.expr;
delete b.expr;
a.expr = NULL;
}
}
a.concrete = value;
stack_.pop_back();
ClearPredicateRegister();
IFDEBUG(DumpMemory());
}
void SymbolicInterpreter::ApplyCompareOp(id_t id, compare_op_t op, value_t value) {
IFDEBUG(fprintf(stderr, "compare2 %d %lld\n", op, value));
assert(stack_.size() >= 2);
StackElem& a = *(stack_.rbegin()+1);
StackElem& b = stack_.back();
if (a.expr || b.expr) {
// Symbolically compute "a -= b".
if (a.expr == NULL) {
b.expr->Negate();
swap(a, b);
*a.expr += b.concrete;
} else if (b.expr == NULL) {
*a.expr -= b.concrete;
} else {
*a.expr -= *b.expr;
delete b.expr;
}
// Construct a symbolic predicate (if "a - b" is symbolic), and
// store it in the predicate register.
if (!a.expr->IsConcrete()) {
pred_ = new SymbolicPred(op, a.expr);
} else {
ClearPredicateRegister();
delete a.expr;
}
// We leave a concrete value on the stack.
a.expr = NULL;
}
a.concrete = value;
stack_.pop_back();
IFDEBUG(DumpMemory());
}
void SymbolicInterpreter::Call(id_t id, function_id_t fid) {
ex_.mutable_path()->Push(kCallId);
}
void SymbolicInterpreter::Return(id_t id) {
ex_.mutable_path()->Push(kReturnId);
// There is either exactly one value on the stack -- the current function's
// return value -- or the stack is empty.
assert(stack_.size() <= 1);
return_value_ = (stack_.size() == 1);
}
void SymbolicInterpreter::HandleReturn(id_t id, value_t value) {
if (return_value_) {
// We just returned from an instrumented function, so the stack
// contains a single element -- the (possibly symbolic) return value.
assert(stack_.size() == 1);
return_value_ = false;
} else {
// We just returned from an uninstrumented function, so the stack
// still contains the arguments to that function. Thus, we clear
// the stack and push the concrete value that was returned.
ClearStack(-1);
PushConcrete(value);
}
}
void SymbolicInterpreter::Branch(id_t id, branch_id_t bid, bool pred_value) {
IFDEBUG(fprintf(stderr, "branch %d %d\n", bid, pred_value));
assert(stack_.size() == 1);
stack_.pop_back();
if (pred_ && !pred_value) {
pred_->Negate();
}
ex_.mutable_path()->Push(bid, pred_);
pred_ = NULL;
IFDEBUG(DumpMemory());
}
value_t SymbolicInterpreter::NewInput(type_t type, addr_t addr) {
mem_[addr] = new SymbolicExpr(1, num_inputs_);
ex_.mutable_vars()->insert(make_pair(num_inputs_ ,type));
value_t ret = 0;
if (num_inputs_ < ex_.inputs().size()) {
ret = ex_.inputs()[num_inputs_];
} else {
// Generate a new random input.
// TODO: User a better pseudorandom number generator.
ret = CastTo(rand(), type);
ex_.mutable_inputs()->push_back(ret);
}
num_inputs_ ++;
return ret;
}
void SymbolicInterpreter::PushConcrete(value_t value) {
PushSymbolic(NULL, value);
}
void SymbolicInterpreter::PushSymbolic(SymbolicExpr* expr, value_t value) {
stack_.push_back(StackElem());
StackElem& se = stack_.back();
se.expr = expr;
se.concrete = value;
}
void SymbolicInterpreter::ClearPredicateRegister() {
delete pred_;
pred_ = NULL;
}
} // namespace crest
<commit_msg>Adds additional debug output (about return values) to SymbolicInterpreter.<commit_after>// Copyright (c) 2008, Jacob Burnim (jburnim@cs.berkeley.edu)
//
// This file is part of CREST, which is distributed under the revised
// BSD license. A copy of this license can be found in the file LICENSE.
//
// 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 LICENSE
// for details.
#include <algorithm>
#include <assert.h>
#include <stdio.h>
#include <utility>
#include <vector>
#include "base/symbolic_interpreter.h"
#include "base/yices_solver.h"
using std::make_pair;
using std::swap;
using std::vector;
#ifdef DEBUG
#define IFDEBUG(x) x
#else
#define IFDEBUG(x)
#endif
namespace crest {
typedef map<addr_t,SymbolicExpr*>::const_iterator ConstMemIt;
SymbolicInterpreter::SymbolicInterpreter()
: pred_(NULL), return_value_(false), ex_(true), num_inputs_(0) {
stack_.reserve(16);
}
SymbolicInterpreter::SymbolicInterpreter(const vector<value_t>& input)
: pred_(NULL), return_value_(false), ex_(true), num_inputs_(0) {
stack_.reserve(16);
ex_.mutable_inputs()->assign(input.begin(), input.end());
}
void SymbolicInterpreter::DumpMemory() {
for (ConstMemIt i = mem_.begin(); i != mem_.end(); ++i) {
string s;
i->second->AppendToString(&s);
fprintf(stderr, "%lu: %s [%d]\n", i->first, s.c_str(), *(int*)(i->first));
}
for (size_t i = 0; i < stack_.size(); i++) {
string s;
if (stack_[i].expr) {
stack_[i].expr->AppendToString(&s);
} else if ((i == stack_.size() - 1) && pred_) {
pred_->AppendToString(&s);
}
if ((i == (stack_.size() - 1)) && return_value_) {
fprintf(stderr, "s%d: %lld [ %s ] (RETURN VALUE)\n",
i, stack_[i].concrete, s.c_str());
} else {
fprintf(stderr, "s%d: %lld [ %s ]\n", i, stack_[i].concrete, s.c_str());
}
}
if ((stack_.size() == 0) && return_value_) {
fprintf(stderr, "MISSING RETURN VALUE\n");
}
}
void SymbolicInterpreter::ClearStack(id_t id) {
IFDEBUG(fprintf(stderr, "clear\n"));
for (vector<StackElem>::const_iterator it = stack_.begin(); it != stack_.end(); ++it) {
delete it->expr;
}
stack_.clear();
ClearPredicateRegister();
return_value_ = false;
IFDEBUG(DumpMemory());
}
void SymbolicInterpreter::Load(id_t id, addr_t addr, value_t value) {
IFDEBUG(fprintf(stderr, "load %lu %lld\n", addr, value));
ConstMemIt it = mem_.find(addr);
if (it == mem_.end()) {
PushConcrete(value);
} else {
PushSymbolic(new SymbolicExpr(*it->second), value);
}
ClearPredicateRegister();
IFDEBUG(DumpMemory());
}
void SymbolicInterpreter::Store(id_t id, addr_t addr) {
IFDEBUG(fprintf(stderr, "store %lu\n", addr));
assert(stack_.size() > 0);
const StackElem& se = stack_.back();
if (se.expr) {
if (!se.expr->IsConcrete()) {
mem_[addr] = se.expr;
} else {
mem_.erase(addr);
delete se.expr;
}
} else {
mem_.erase(addr);
}
stack_.pop_back();
ClearPredicateRegister();
IFDEBUG(DumpMemory());
}
void SymbolicInterpreter::ApplyUnaryOp(id_t id, unary_op_t op, value_t value) {
IFDEBUG(fprintf(stderr, "apply1 %d %lld\n", op, value));
assert(stack_.size() >= 1);
StackElem& se = stack_.back();
if (se.expr) {
switch (op) {
case ops::NEGATE:
se.expr->Negate();
ClearPredicateRegister();
break;
case ops::LOGICAL_NOT:
if (pred_) {
pred_->Negate();
break;
}
// Otherwise, fall through to the concrete case.
default:
// Concrete operator.
delete se.expr;
se.expr = NULL;
ClearPredicateRegister();
}
}
se.concrete = value;
IFDEBUG(DumpMemory());
}
void SymbolicInterpreter::ApplyBinaryOp(id_t id, binary_op_t op, value_t value) {
IFDEBUG(fprintf(stderr, "apply2 %d %lld\n", op, value));
assert(stack_.size() >= 2);
StackElem& a = *(stack_.rbegin()+1);
StackElem& b = stack_.back();
if (a.expr || b.expr) {
switch (op) {
case ops::ADD:
if (a.expr == NULL) {
swap(a, b);
*a.expr += b.concrete;
} else if (b.expr == NULL) {
*a.expr += b.concrete;
} else {
*a.expr += *b.expr;
delete b.expr;
}
break;
case ops::SUBTRACT:
if (a.expr == NULL) {
b.expr->Negate();
swap(a, b);
*a.expr += b.concrete;
} else if (b.expr == NULL) {
*a.expr -= b.concrete;
} else {
*a.expr -= *b.expr;
delete b.expr;
}
break;
case ops::SHIFT_L:
if (a.expr != NULL) {
// Convert to multiplication by a (concrete) constant.
*a.expr *= (1 << b.concrete);
}
delete b.expr;
break;
case ops::MULTIPLY:
if (a.expr == NULL) {
swap(a, b);
*a.expr *= b.concrete;
} else if (b.expr == NULL) {
*a.expr *= b.concrete;
} else {
swap(a, b);
*a.expr *= b.concrete;
delete b.expr;
}
break;
default:
// Concrete operator.
delete a.expr;
delete b.expr;
a.expr = NULL;
}
}
a.concrete = value;
stack_.pop_back();
ClearPredicateRegister();
IFDEBUG(DumpMemory());
}
void SymbolicInterpreter::ApplyCompareOp(id_t id, compare_op_t op, value_t value) {
IFDEBUG(fprintf(stderr, "compare2 %d %lld\n", op, value));
assert(stack_.size() >= 2);
StackElem& a = *(stack_.rbegin()+1);
StackElem& b = stack_.back();
if (a.expr || b.expr) {
// Symbolically compute "a -= b".
if (a.expr == NULL) {
b.expr->Negate();
swap(a, b);
*a.expr += b.concrete;
} else if (b.expr == NULL) {
*a.expr -= b.concrete;
} else {
*a.expr -= *b.expr;
delete b.expr;
}
// Construct a symbolic predicate (if "a - b" is symbolic), and
// store it in the predicate register.
if (!a.expr->IsConcrete()) {
pred_ = new SymbolicPred(op, a.expr);
} else {
ClearPredicateRegister();
delete a.expr;
}
// We leave a concrete value on the stack.
a.expr = NULL;
}
a.concrete = value;
stack_.pop_back();
IFDEBUG(DumpMemory());
}
void SymbolicInterpreter::Call(id_t id, function_id_t fid) {
IFDEBUG(fprintf(stderr, "call %u\n", fid));
ex_.mutable_path()->Push(kCallId);
IFDEBUG(DumpMemory());
}
void SymbolicInterpreter::Return(id_t id) {
IFDEBUG(fprintf(stderr, "return\n"));
ex_.mutable_path()->Push(kReturnId);
// There is either exactly one value on the stack -- the current function's
// return value -- or the stack is empty.
assert(stack_.size() <= 1);
return_value_ = (stack_.size() == 1);
IFDEBUG(DumpMemory());
}
void SymbolicInterpreter::HandleReturn(id_t id, value_t value) {
IFDEBUG(fprintf(stderr, "handle_return %lld\n", value));
if (return_value_) {
// We just returned from an instrumented function, so the stack
// contains a single element -- the (possibly symbolic) return value.
assert(stack_.size() == 1);
return_value_ = false;
} else {
// We just returned from an uninstrumented function, so the stack
// still contains the arguments to that function. Thus, we clear
// the stack and push the concrete value that was returned.
ClearStack(-1);
PushConcrete(value);
}
IFDEBUG(DumpMemory());
}
void SymbolicInterpreter::Branch(id_t id, branch_id_t bid, bool pred_value) {
IFDEBUG(fprintf(stderr, "branch %d %d\n", bid, pred_value));
assert(stack_.size() == 1);
stack_.pop_back();
if (pred_ && !pred_value) {
pred_->Negate();
}
ex_.mutable_path()->Push(bid, pred_);
pred_ = NULL;
IFDEBUG(DumpMemory());
}
value_t SymbolicInterpreter::NewInput(type_t type, addr_t addr) {
IFDEBUG(fprintf(stderr, "symbolic_input %d %lu\n", type, addr));
mem_[addr] = new SymbolicExpr(1, num_inputs_);
ex_.mutable_vars()->insert(make_pair(num_inputs_ ,type));
value_t ret = 0;
if (num_inputs_ < ex_.inputs().size()) {
ret = ex_.inputs()[num_inputs_];
} else {
// Generate a new random input.
// TODO: User a better pseudorandom number generator.
ret = CastTo(rand(), type);
ex_.mutable_inputs()->push_back(ret);
}
num_inputs_ ++;
IFDEBUG(DumpMemory());
return ret;
}
void SymbolicInterpreter::PushConcrete(value_t value) {
PushSymbolic(NULL, value);
}
void SymbolicInterpreter::PushSymbolic(SymbolicExpr* expr, value_t value) {
stack_.push_back(StackElem());
StackElem& se = stack_.back();
se.expr = expr;
se.concrete = value;
}
void SymbolicInterpreter::ClearPredicateRegister() {
delete pred_;
pred_ = NULL;
}
} // namespace crest
<|endoftext|> |
<commit_before>// This file is part of Eigen, a lightweight C++ template library
// for linear algebra.
//
// Copyright (C) 2006-2010 Benoit Jacob <jacob.benoit.1@gmail.com>
//
// This Source Code Form is subject to the terms of the Mozilla
// Public License v. 2.0. If a copy of the MPL was not distributed
// with this file, You can obtain one at http://mozilla.org/MPL/2.0/.
#ifndef EIGEN_NO_STATIC_ASSERT
#define EIGEN_NO_STATIC_ASSERT // turn static asserts into runtime asserts in order to check them
#endif
#include "main.h"
template<typename VectorType> void map_class_vector(const VectorType& m)
{
typedef typename VectorType::Index Index;
typedef typename VectorType::Scalar Scalar;
Index size = m.size();
// test Map.h
Scalar* array1 = internal::aligned_new<Scalar>(size);
Scalar* array2 = internal::aligned_new<Scalar>(size);
Scalar* array3 = new Scalar[size+1];
Scalar* array3unaligned = size_t(array3)%16 == 0 ? array3+1 : array3;
Map<VectorType, Aligned>(array1, size) = VectorType::Random(size);
Map<VectorType, Aligned>(array2, size) = Map<VectorType,Aligned>(array1, size);
Map<VectorType>(array3unaligned, size) = Map<VectorType>(array1, size);
VectorType ma1 = Map<VectorType, Aligned>(array1, size);
VectorType ma2 = Map<VectorType, Aligned>(array2, size);
VectorType ma3 = Map<VectorType>(array3unaligned, size);
VERIFY_IS_EQUAL(ma1, ma2);
VERIFY_IS_EQUAL(ma1, ma3);
#ifdef EIGEN_VECTORIZE
if(internal::packet_traits<Scalar>::Vectorizable)
VERIFY_RAISES_ASSERT((Map<VectorType,Aligned>(array3unaligned, size)))
#endif
internal::aligned_delete(array1, size);
internal::aligned_delete(array2, size);
delete[] array3;
}
template<typename MatrixType> void map_class_matrix(const MatrixType& m)
{
typedef typename MatrixType::Index Index;
typedef typename MatrixType::Scalar Scalar;
Index rows = m.rows(), cols = m.cols(), size = rows*cols;
// test Map.h
Scalar* array1 = internal::aligned_new<Scalar>(size);
for(int i = 0; i < size; i++) array1[i] = Scalar(1);
Scalar* array2 = internal::aligned_new<Scalar>(size);
for(int i = 0; i < size; i++) array2[i] = Scalar(1);
Scalar* array3 = new Scalar[size+1];
for(int i = 0; i < size+1; i++) array3[i] = Scalar(1);
Scalar* array3unaligned = size_t(array3)%16 == 0 ? array3+1 : array3;
Map<MatrixType, Aligned>(array1, rows, cols) = MatrixType::Ones(rows,cols);
Map<MatrixType>(array2, rows, cols) = Map<MatrixType>(array1, rows, cols);
Map<MatrixType>(array3unaligned, rows, cols) = Map<MatrixType>(array1, rows, cols);
MatrixType ma1 = Map<MatrixType>(array1, rows, cols);
MatrixType ma2 = Map<MatrixType, Aligned>(array2, rows, cols);
VERIFY_IS_EQUAL(ma1, ma2);
MatrixType ma3 = Map<MatrixType>(array3unaligned, rows, cols);
VERIFY_IS_EQUAL(ma1, ma3);
internal::aligned_delete(array1, size);
internal::aligned_delete(array2, size);
delete[] array3;
}
template<typename VectorType> void map_static_methods(const VectorType& m)
{
typedef typename VectorType::Index Index;
typedef typename VectorType::Scalar Scalar;
Index size = m.size();
// test Map.h
Scalar* array1 = internal::aligned_new<Scalar>(size);
Scalar* array2 = internal::aligned_new<Scalar>(size);
Scalar* array3 = new Scalar[size+1];
Scalar* array3unaligned = size_t(array3)%16 == 0 ? array3+1 : array3;
VectorType::MapAligned(array1, size) = VectorType::Random(size);
VectorType::Map(array2, size) = VectorType::Map(array1, size);
VectorType::Map(array3unaligned, size) = VectorType::Map(array1, size);
VectorType ma1 = VectorType::Map(array1, size);
VectorType ma2 = VectorType::MapAligned(array2, size);
VectorType ma3 = VectorType::Map(array3unaligned, size);
VERIFY_IS_EQUAL(ma1, ma2);
VERIFY_IS_EQUAL(ma1, ma3);
internal::aligned_delete(array1, size);
internal::aligned_delete(array2, size);
delete[] array3;
}
template<typename PlainObjectType> void check_const_correctness(const PlainObjectType&)
{
// there's a lot that we can't test here while still having this test compile!
// the only possible approach would be to run a script trying to compile stuff and checking that it fails.
// CMake can help with that.
// verify that map-to-const don't have LvalueBit
typedef typename internal::add_const<PlainObjectType>::type ConstPlainObjectType;
VERIFY( !(internal::traits<Map<ConstPlainObjectType> >::Flags & LvalueBit) );
VERIFY( !(internal::traits<Map<ConstPlainObjectType, Aligned> >::Flags & LvalueBit) );
VERIFY( !(Map<ConstPlainObjectType>::Flags & LvalueBit) );
VERIFY( !(Map<ConstPlainObjectType, Aligned>::Flags & LvalueBit) );
}
void test_mapped_matrix()
{
for(int i = 0; i < g_repeat; i++) {
CALL_SUBTEST_1( map_class_vector(Matrix<float, 1, 1>()) );
CALL_SUBTEST_1( check_const_correctness(Matrix<float, 1, 1>()) );
CALL_SUBTEST_2( map_class_vector(Vector4d()) );
CALL_SUBTEST_2( check_const_correctness(Matrix4d()) );
CALL_SUBTEST_3( map_class_vector(RowVector4f()) );
CALL_SUBTEST_4( map_class_vector(VectorXcf(8)) );
CALL_SUBTEST_5( map_class_vector(VectorXi(12)) );
CALL_SUBTEST_5( check_const_correctness(VectorXi(12)) );
CALL_SUBTEST_1( map_class_matrix(Matrix<float, 1, 1>()) );
CALL_SUBTEST_2( map_class_matrix(Matrix4d()) );
CALL_SUBTEST_11( map_class_matrix(Matrix<float,3,5>()) );
CALL_SUBTEST_4( map_class_matrix(MatrixXcf(internal::random<int>(1,10),internal::random<int>(1,10))) );
CALL_SUBTEST_5( map_class_matrix(MatrixXi(internal::random<int>(1,10),internal::random<int>(1,10))) );
CALL_SUBTEST_6( map_static_methods(Matrix<double, 1, 1>()) );
CALL_SUBTEST_7( map_static_methods(Vector3f()) );
CALL_SUBTEST_8( map_static_methods(RowVector3d()) );
CALL_SUBTEST_9( map_static_methods(VectorXcd(8)) );
CALL_SUBTEST_10( map_static_methods(VectorXf(12)) );
}
}
<commit_msg>extend Map unit test to check buffers allocated on the stack<commit_after>// This file is part of Eigen, a lightweight C++ template library
// for linear algebra.
//
// Copyright (C) 2006-2010 Benoit Jacob <jacob.benoit.1@gmail.com>
//
// This Source Code Form is subject to the terms of the Mozilla
// Public License v. 2.0. If a copy of the MPL was not distributed
// with this file, You can obtain one at http://mozilla.org/MPL/2.0/.
#ifndef EIGEN_NO_STATIC_ASSERT
#define EIGEN_NO_STATIC_ASSERT // turn static asserts into runtime asserts in order to check them
#endif
#include "main.h"
#define EIGEN_TESTMAP_MAX_SIZE 256
template<typename VectorType> void map_class_vector(const VectorType& m)
{
typedef typename VectorType::Index Index;
typedef typename VectorType::Scalar Scalar;
Index size = m.size();
// test Map.h
Scalar* array1 = internal::aligned_new<Scalar>(size);
Scalar* array2 = internal::aligned_new<Scalar>(size);
Scalar* array3 = new Scalar[size+1];
Scalar* array3unaligned = size_t(array3)%16 == 0 ? array3+1 : array3;
Scalar array4[EIGEN_TESTMAP_MAX_SIZE];
Map<VectorType, Aligned>(array1, size) = VectorType::Random(size);
Map<VectorType, Aligned>(array2, size) = Map<VectorType,Aligned>(array1, size);
Map<VectorType>(array3unaligned, size) = Map<VectorType>(array1, size);
Map<VectorType>(array4, size) = Map<VectorType,Aligned>(array1, size);
VectorType ma1 = Map<VectorType, Aligned>(array1, size);
VectorType ma2 = Map<VectorType, Aligned>(array2, size);
VectorType ma3 = Map<VectorType>(array3unaligned, size);
VectorType ma4 = Map<VectorType>(array4, size);
VERIFY_IS_EQUAL(ma1, ma2);
VERIFY_IS_EQUAL(ma1, ma3);
VERIFY_IS_EQUAL(ma1, ma4);
#ifdef EIGEN_VECTORIZE
if(internal::packet_traits<Scalar>::Vectorizable)
VERIFY_RAISES_ASSERT((Map<VectorType,Aligned>(array3unaligned, size)))
#endif
internal::aligned_delete(array1, size);
internal::aligned_delete(array2, size);
delete[] array3;
}
template<typename MatrixType> void map_class_matrix(const MatrixType& m)
{
typedef typename MatrixType::Index Index;
typedef typename MatrixType::Scalar Scalar;
Index rows = m.rows(), cols = m.cols(), size = rows*cols;
// test Map.h
Scalar* array1 = internal::aligned_new<Scalar>(size);
for(int i = 0; i < size; i++) array1[i] = Scalar(1);
Scalar* array2 = internal::aligned_new<Scalar>(size);
for(int i = 0; i < size; i++) array2[i] = Scalar(1);
Scalar* array3 = new Scalar[size+1];
for(int i = 0; i < size+1; i++) array3[i] = Scalar(1);
Scalar* array3unaligned = size_t(array3)%16 == 0 ? array3+1 : array3;
Map<MatrixType, Aligned>(array1, rows, cols) = MatrixType::Ones(rows,cols);
Map<MatrixType>(array2, rows, cols) = Map<MatrixType>(array1, rows, cols);
Map<MatrixType>(array3unaligned, rows, cols) = Map<MatrixType>(array1, rows, cols);
MatrixType ma1 = Map<MatrixType>(array1, rows, cols);
MatrixType ma2 = Map<MatrixType, Aligned>(array2, rows, cols);
VERIFY_IS_EQUAL(ma1, ma2);
MatrixType ma3 = Map<MatrixType>(array3unaligned, rows, cols);
VERIFY_IS_EQUAL(ma1, ma3);
internal::aligned_delete(array1, size);
internal::aligned_delete(array2, size);
delete[] array3;
}
template<typename VectorType> void map_static_methods(const VectorType& m)
{
typedef typename VectorType::Index Index;
typedef typename VectorType::Scalar Scalar;
Index size = m.size();
// test Map.h
Scalar* array1 = internal::aligned_new<Scalar>(size);
Scalar* array2 = internal::aligned_new<Scalar>(size);
Scalar* array3 = new Scalar[size+1];
Scalar* array3unaligned = size_t(array3)%16 == 0 ? array3+1 : array3;
VectorType::MapAligned(array1, size) = VectorType::Random(size);
VectorType::Map(array2, size) = VectorType::Map(array1, size);
VectorType::Map(array3unaligned, size) = VectorType::Map(array1, size);
VectorType ma1 = VectorType::Map(array1, size);
VectorType ma2 = VectorType::MapAligned(array2, size);
VectorType ma3 = VectorType::Map(array3unaligned, size);
VERIFY_IS_EQUAL(ma1, ma2);
VERIFY_IS_EQUAL(ma1, ma3);
internal::aligned_delete(array1, size);
internal::aligned_delete(array2, size);
delete[] array3;
}
template<typename PlainObjectType> void check_const_correctness(const PlainObjectType&)
{
// there's a lot that we can't test here while still having this test compile!
// the only possible approach would be to run a script trying to compile stuff and checking that it fails.
// CMake can help with that.
// verify that map-to-const don't have LvalueBit
typedef typename internal::add_const<PlainObjectType>::type ConstPlainObjectType;
VERIFY( !(internal::traits<Map<ConstPlainObjectType> >::Flags & LvalueBit) );
VERIFY( !(internal::traits<Map<ConstPlainObjectType, Aligned> >::Flags & LvalueBit) );
VERIFY( !(Map<ConstPlainObjectType>::Flags & LvalueBit) );
VERIFY( !(Map<ConstPlainObjectType, Aligned>::Flags & LvalueBit) );
}
void test_mapped_matrix()
{
for(int i = 0; i < g_repeat; i++) {
CALL_SUBTEST_1( map_class_vector(Matrix<float, 1, 1>()) );
CALL_SUBTEST_1( check_const_correctness(Matrix<float, 1, 1>()) );
CALL_SUBTEST_2( map_class_vector(Vector4d()) );
CALL_SUBTEST_2( map_class_vector(VectorXd(13)) );
CALL_SUBTEST_2( check_const_correctness(Matrix4d()) );
CALL_SUBTEST_3( map_class_vector(RowVector4f()) );
CALL_SUBTEST_4( map_class_vector(VectorXcf(8)) );
CALL_SUBTEST_5( map_class_vector(VectorXi(12)) );
CALL_SUBTEST_5( check_const_correctness(VectorXi(12)) );
CALL_SUBTEST_1( map_class_matrix(Matrix<float, 1, 1>()) );
CALL_SUBTEST_2( map_class_matrix(Matrix4d()) );
CALL_SUBTEST_11( map_class_matrix(Matrix<float,3,5>()) );
CALL_SUBTEST_4( map_class_matrix(MatrixXcf(internal::random<int>(1,10),internal::random<int>(1,10))) );
CALL_SUBTEST_5( map_class_matrix(MatrixXi(internal::random<int>(1,10),internal::random<int>(1,10))) );
CALL_SUBTEST_6( map_static_methods(Matrix<double, 1, 1>()) );
CALL_SUBTEST_7( map_static_methods(Vector3f()) );
CALL_SUBTEST_8( map_static_methods(RowVector3d()) );
CALL_SUBTEST_9( map_static_methods(VectorXcd(8)) );
CALL_SUBTEST_10( map_static_methods(VectorXf(12)) );
}
}
<|endoftext|> |
<commit_before>#pragma once
#include <iostream>
#include <cstdint>
#include <initializer_list>
#include <iterator>
#include <stdexcept>
#include <string>
#include <type_traits>
#include <vector>
#include <boost/optional.hpp>
#include "blackhole/attribute/set.hpp"
#include "blackhole/config.hpp"
#include "blackhole/detail/iterator/join.hpp"
namespace blackhole {
namespace attribute {
class set_view_t {
public:
typedef aux::iterator::join_t<set_t, true> const_iterator;
typedef set_t::size_type size_type;
private:
set_t global; // Likely empty.
set_t local; // About 1-2 + message + tid + timestamp (4-5).
set_t other; // The most filled (scoped + user attributes)
public:
set_view_t() = default;
set_view_t(set_t global, set_t scoped, set_t&& local);
bool empty() const BLACKHOLE_NOEXCEPT;
size_type upper_size() const BLACKHOLE_NOEXCEPT;
size_type count(const std::string& name) const BLACKHOLE_NOEXCEPT;
void insert(pair_t pair);
template<typename InputIterator>
void insert(InputIterator first, InputIterator last);
const_iterator begin() const BLACKHOLE_NOEXCEPT;
const_iterator end() const BLACKHOLE_NOEXCEPT;
boost::optional<const attribute_t&>
find(const std::string& name) const BLACKHOLE_NOEXCEPT;
const attribute_t& at(const std::string& name) const;
};
BLACKHOLE_API
set_view_t::set_view_t(set_t global, set_t scoped, set_t&& local) :
global(std::move(global)),
local(std::move(local)),
other(std::move(scoped))
{}
BLACKHOLE_API
bool
set_view_t::empty() const BLACKHOLE_NOEXCEPT {
return local.empty() && other.empty() && global.empty();
}
BLACKHOLE_API
set_view_t::size_type
set_view_t::upper_size() const BLACKHOLE_NOEXCEPT {
return local.size() + other.size() + global.size();
}
BLACKHOLE_API
set_view_t::size_type
set_view_t::count(const std::string& name) const BLACKHOLE_NOEXCEPT {
return local.count(name) + other.count(name) + global.count(name);
}
BLACKHOLE_API
void
set_view_t::insert(pair_t pair) {
other.insert(std::move(pair));
}
template<typename InputIterator>
BLACKHOLE_API
void
set_view_t::insert(InputIterator first, InputIterator last) {
other.insert(first, last);
}
BLACKHOLE_API
set_view_t::const_iterator
set_view_t::begin() const BLACKHOLE_NOEXCEPT {
return const_iterator({ &local, &other, &global });
}
BLACKHOLE_API
set_view_t::const_iterator
set_view_t::end() const BLACKHOLE_NOEXCEPT {
return const_iterator({ &local, &other, &global }, aux::iterator::invalidate_tag);
}
BLACKHOLE_API
boost::optional<const attribute_t&>
set_view_t::find(const std::string& name) const BLACKHOLE_NOEXCEPT {
auto it = local.find(name);
if (it != local.end()) {
return it->second;
}
it = other.find(name);
if (it != other.end()) {
return it->second;
}
it = global.find(name);
if (it != global.end()) {
return it->second;
}
return boost::optional<const attribute_t&>();
}
BLACKHOLE_API
const attribute_t&
set_view_t::at(const std::string &name) const {
auto value = find(name);
if (!value) {
throw std::out_of_range(name);
}
return *value;
}
} // namespace attribute
} // namespace blackhole
<commit_msg>[Tasks] One more task.<commit_after>#pragma once
#include <iostream>
#include <cstdint>
#include <initializer_list>
#include <iterator>
#include <stdexcept>
#include <string>
#include <type_traits>
#include <vector>
#include <boost/optional.hpp>
#include "blackhole/attribute/set.hpp"
#include "blackhole/config.hpp"
#include "blackhole/detail/iterator/join.hpp"
namespace blackhole {
namespace attribute {
class set_view_t {
public:
typedef aux::iterator::join_t<set_t, true> const_iterator;
typedef set_t::size_type size_type;
private:
//!@todo: Rename to '?', 'internal' 'external'.
set_t global; // Likely empty.
set_t local; // About 1-2 + message + tid + timestamp (4-5).
set_t other; // The most filled (scoped + user attributes)
public:
set_view_t() = default;
set_view_t(set_t global, set_t scoped, set_t&& local);
bool empty() const BLACKHOLE_NOEXCEPT;
size_type upper_size() const BLACKHOLE_NOEXCEPT;
size_type count(const std::string& name) const BLACKHOLE_NOEXCEPT;
void insert(pair_t pair);
template<typename InputIterator>
void insert(InputIterator first, InputIterator last);
const_iterator begin() const BLACKHOLE_NOEXCEPT;
const_iterator end() const BLACKHOLE_NOEXCEPT;
boost::optional<const attribute_t&>
find(const std::string& name) const BLACKHOLE_NOEXCEPT;
const attribute_t& at(const std::string& name) const;
};
BLACKHOLE_API
set_view_t::set_view_t(set_t global, set_t scoped, set_t&& local) :
global(std::move(global)),
local(std::move(local)),
other(std::move(scoped))
{}
BLACKHOLE_API
bool
set_view_t::empty() const BLACKHOLE_NOEXCEPT {
return local.empty() && other.empty() && global.empty();
}
BLACKHOLE_API
set_view_t::size_type
set_view_t::upper_size() const BLACKHOLE_NOEXCEPT {
return local.size() + other.size() + global.size();
}
BLACKHOLE_API
set_view_t::size_type
set_view_t::count(const std::string& name) const BLACKHOLE_NOEXCEPT {
return local.count(name) + other.count(name) + global.count(name);
}
BLACKHOLE_API
void
set_view_t::insert(pair_t pair) {
other.insert(std::move(pair));
}
template<typename InputIterator>
BLACKHOLE_API
void
set_view_t::insert(InputIterator first, InputIterator last) {
other.insert(first, last);
}
BLACKHOLE_API
set_view_t::const_iterator
set_view_t::begin() const BLACKHOLE_NOEXCEPT {
return const_iterator({ &local, &other, &global });
}
BLACKHOLE_API
set_view_t::const_iterator
set_view_t::end() const BLACKHOLE_NOEXCEPT {
return const_iterator({ &local, &other, &global }, aux::iterator::invalidate_tag);
}
BLACKHOLE_API
boost::optional<const attribute_t&>
set_view_t::find(const std::string& name) const BLACKHOLE_NOEXCEPT {
auto it = local.find(name);
if (it != local.end()) {
return it->second;
}
it = other.find(name);
if (it != other.end()) {
return it->second;
}
it = global.find(name);
if (it != global.end()) {
return it->second;
}
return boost::optional<const attribute_t&>();
}
BLACKHOLE_API
const attribute_t&
set_view_t::at(const std::string &name) const {
auto value = find(name);
if (!value) {
throw std::out_of_range(name);
}
return *value;
}
} // namespace attribute
} // namespace blackhole
<|endoftext|> |
<commit_before>/*
# File : classad_c_helper.C
#
#
# Author : Francesco Prelz ($Author: fprelz $)
# e-mail : "francesco.prelz@mi.infn.it"
#
# Revision history :
# 5-Apr-2004 Original release
# 16-Apr-2004 Added string list parse and unparse.
# 7-May-2004 Added retrieval of string argument into dynamic string.
# 19-Aug-2004 Added boolean attribute.
# 30-Nov-2007 Added function to evaluate a boolean expression
# in the context of a classad.
# 15-Sep-2011 Added helper function to accumulate and return all the attribute
# names in a classad.
#
# Description:
# c-callable layer for handling Classad parse and unparse via the 'new'
# ClassAd library.
#
# Copyright (c) Members of the EGEE Collaboration. 2007-2010.
#
# See http://www.eu-egee.org/partners/ for details on the copyright
# holders.
#
# 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 <string.h>
#include "classad/classad_distribution.h"
#include "classad_binary_op_unwind.h"
#ifdef WANT_NAMESPACES
using namespace classad;
#endif
extern "C"
{
#include <string.h>
#include "classad_c_helper.h"
classad_context
classad_parse (char *s_in)
{
ClassAd *ad = NULL;
ClassAdParser parser;
ad = parser.ParseClassAd(s_in);
// ad == NULL on error.
return ((classad_context)ad);
}
char *
classad_unparse (classad_context cad)
{
if (cad == NULL) return NULL;
std::string res_s;
char *res_c = NULL;
ClassAd *ad = (ClassAd *)cad;
ClassAdUnParser unparser;
unparser.Unparse(res_s, ad);
if (res_s.size() > 0)
{
res_c = strdup(res_s.c_str());
}
// res_c == NULL on error.
return (res_c);
}
int
classad_get_string_attribute (classad_context cad, const char *attribute_name,
char *result, int l_result)
{
if (cad == NULL) return C_CLASSAD_INVALID_CONTEXT;
ClassAd *ad = (ClassAd *)cad;
Value v;
ad->EvaluateAttr(attribute_name, v);
if (v.IsStringValue( result, l_result ))
{
return C_CLASSAD_NO_ERROR;
}
return C_CLASSAD_VALUE_NOT_FOUND;
}
int
classad_get_dstring_attribute (classad_context cad, const char *attribute_name,
char **result)
{
if (cad == NULL) return C_CLASSAD_INVALID_CONTEXT;
ClassAd *ad = (ClassAd *)cad;
if (result != NULL) *result = NULL; /* For those who don't check */
/* the return code... */
Value v;
ad->EvaluateAttr(attribute_name, v);
std::string res_str;
if (v.IsStringValue( res_str ))
{
(*result) = strdup(res_str.c_str());
if ((*result) == NULL) return C_CLASSAD_OUT_OF_MEMORY;
return C_CLASSAD_NO_ERROR;
}
return C_CLASSAD_VALUE_NOT_FOUND;
}
void
classad_free_string_list(char **strl)
{
if (strl != NULL)
{
char **str_val;
for(str_val=strl; (*str_val) != NULL; str_val++)
{
if ((*str_val)!=NULL) free(*str_val);
}
free(strl);
}
}
int
classad_get_string_list_attribute (classad_context cad,
const char *attribute_name,
char ***result)
{
if (cad == NULL) return C_CLASSAD_INVALID_CONTEXT;
int n_results = 0;
(*result) = (char **)malloc(sizeof(char **));
if ((*result) == NULL) return C_CLASSAD_OUT_OF_MEMORY;
(*result)[0] = NULL;
ClassAd *ad = (ClassAd *)cad;
Value vl;
ad->EvaluateAttr(attribute_name, vl);
const ExprList *et_result;
if (vl.IsListValue(et_result))
{
std::vector<ExprTree*> ads;
et_result->GetComponents(ads);
// Get string values.
for(std::vector<ExprTree*>::const_iterator it = ads.begin();
it != ads.end(); ++it)
{
if ((*it)->GetKind() == ExprTree::LITERAL_NODE)
{
Value v;
EvalState state;
state.SetScopes( ad );
(*it)->Evaluate(state,v);
std::string res_str;
if (v.IsStringValue( res_str ))
{
// add string value to result, which is a NULL-terminated
// string array.
n_results++;
(*result) = (char **)realloc(*result, (n_results+1)*sizeof(char *));
if ((*result) == NULL) return C_CLASSAD_OUT_OF_MEMORY;
(*result)[n_results-1] = strdup(res_str.c_str());
(*result)[n_results] = NULL;
}
}
}
return C_CLASSAD_NO_ERROR;
}
// The result list needs to be freed on success only.
classad_free_string_list(*result);
(*result) = NULL;
return C_CLASSAD_VALUE_NOT_FOUND;
}
int
classad_get_int_attribute (classad_context cad, const char *attribute_name,
int *result)
{
if (cad == NULL) return C_CLASSAD_INVALID_CONTEXT;
ClassAd *ad = (ClassAd *)cad;
Value v;
ad->EvaluateAttr(attribute_name, v);
if (v.IsIntegerValue( *result ))
{
return C_CLASSAD_NO_ERROR;
}
return C_CLASSAD_VALUE_NOT_FOUND;
}
int
classad_get_bool_attribute (classad_context cad, const char *attribute_name,
int *result)
{
if (cad == NULL) return C_CLASSAD_INVALID_CONTEXT;
ClassAd *ad = (ClassAd *)cad;
Value v;
ad->EvaluateAttr(attribute_name, v);
bool tmp_res;
if (v.IsBooleanValue( tmp_res ))
{
if (tmp_res) *result = 1;
else *result = 0;
return C_CLASSAD_NO_ERROR;
}
return C_CLASSAD_VALUE_NOT_FOUND;
}
int
classad_put_string_attribute (classad_context *cad, const char *name,
const char *value)
{
ClassAd *ad;
if ((*cad) == NULL)
{
ad = new ClassAd;
(*cad) = (classad_context) ad;
}
else ad = (ClassAd *)(*cad);
std::string str_val(value);
if (ad->InsertAttr (name, str_val)) return C_CLASSAD_NO_ERROR;
else return C_CLASSAD_INSERT_FAILED;
}
int
classad_put_string_list_attribute (classad_context *cad,
const char *name,
char **value)
{
if (value == NULL) return C_CLASSAD_INVALID_VALUE;
ClassAd *ad;
if ((*cad) == NULL)
{
ad = new ClassAd;
(*cad) = (classad_context) ad;
}
else ad = (ClassAd *)(*cad);
char **str_val;
std::vector<ExprTree*> et_ads;
// Traverse NULL-terminated string array.
for(str_val=value; (*str_val) != NULL; str_val++)
{
Value v;
v.SetStringValue(*str_val);
et_ads.push_back(Literal::MakeLiteral(v));
}
ExprList *et_value;
et_value = ExprList::MakeExprList(et_ads);
if (ad->Insert (name, (ExprTree* &)et_value)) return C_CLASSAD_NO_ERROR;
else return C_CLASSAD_INSERT_FAILED;
}
int
classad_put_int_attribute (classad_context *cad, const char *name,
int value)
{
ClassAd *ad;
if ((*cad) == NULL)
{
ad = new ClassAd;
(*cad) = (classad_context) ad;
}
else ad = (ClassAd *)(*cad);
if (ad->InsertAttr (name, value)) return C_CLASSAD_NO_ERROR;
else return C_CLASSAD_INSERT_FAILED;
}
int
classad_put_bool_attribute (classad_context *cad, const char *name,
int value)
{
ClassAd *ad;
if ((*cad) == NULL)
{
ad = new ClassAd;
(*cad) = (classad_context) ad;
}
else ad = (ClassAd *)(*cad);
bool tmp_value;
if (value != 0) tmp_value = true;
else tmp_value = false;
if (ad->InsertAttr (name, tmp_value)) return C_CLASSAD_NO_ERROR;
else return C_CLASSAD_INSERT_FAILED;
}
void
classad_free (classad_context cad)
{
ClassAd *ad;
if (cad != NULL)
{
ad = (ClassAd *)cad;
delete ad;
}
}
void
classad_dump (classad_context cad)
{
ClassAd *ad;
if (cad != NULL)
{
ad = (ClassAd *)cad;
ad->Puke();
}
}
int
unwind_attributes(classad_context cad, char *attribute_name, char ***results)
{
if (cad == NULL) return C_CLASSAD_INVALID_CONTEXT;
if ((results == NULL) || (attribute_name == NULL))
return C_CLASSAD_INVALID_ARG;
ClassAd *ad = (ClassAd *)cad;
ExprTree *et;
bool need_to_delete_et = false;
et = ad->Lookup(attribute_name);
if (et == NULL)
{
return C_CLASSAD_VALUE_NOT_FOUND;
}
if (et->GetKind() == ExprTree::LITERAL_NODE)
{
// The attribute was probably stringified. Try to parse it.
Value v;
EvalState state;
state.SetScopes( ad );
et->Evaluate(state,v);
std::string strres;
if (v.IsStringValue( strres ))
{
ClassAdParser parser;
et=NULL;
parser.ParseExpression(strres,et);
need_to_delete_et = true;
}
}
BinaryOpUnwind res_unp;
std::string result;
res_unp.Unparse(result, et);
int n_results;
if (*results == NULL)
{
n_results = 0;
(*results) = (char **)malloc(sizeof(char **));
if ((*results) == NULL) return C_CLASSAD_OUT_OF_MEMORY;
(*results)[0] = NULL;
}
else
{
for (n_results = 0; (*results)[n_results] != NULL; n_results++) /*NOP*/ ;
}
std::vector<std::string>::const_iterator it;
for (it = res_unp.m_unwind_output.begin();
it != res_unp.m_unwind_output.end(); ++it)
{
n_results++;
char **new_results;
new_results = (char **)realloc(*results, (n_results+1)*sizeof(char *));
if (new_results == NULL)
{
if (need_to_delete_et) delete et;
return C_CLASSAD_OUT_OF_MEMORY;
}
(*results) = new_results;
(*results)[n_results] = NULL;
(*results)[n_results-1] = strdup(it->c_str());
if (((*results)[n_results-1]) == NULL)
{
if (need_to_delete_et) delete et;
return C_CLASSAD_OUT_OF_MEMORY;
}
}
if (need_to_delete_et) delete et;
return C_CLASSAD_NO_ERROR;
}
classad_expr_tree
classad_parse_expr(const char *s_ex)
{
ClassAdParser parser;
ExprTree *et = parser.ParseExpression(s_ex);
// et == NULL on error.
return ((classad_expr_tree)et);
}
void
classad_free_tree(classad_expr_tree t_ex)
{
ExprTree *et = (ExprTree *)t_ex;
if (et) delete et;
}
int
classad_evaluate_boolean_expr(const char *s_in, const classad_expr_tree t_ex,
int *result)
{
ClassAd *ad;
ClassAdParser parser;
if (s_in == NULL || t_ex == NULL || result == NULL)
return C_CLASSAD_INVALID_ARG;
ExprTree *et = (ExprTree *)t_ex;
ad = parser.ParseClassAd(s_in);
if (ad == NULL) return C_CLASSAD_PARSE_ERROR;
int retcod = C_CLASSAD_NO_ERROR;
Value v;
et->SetParentScope(ad);
ad->EvaluateExpr(et, v);
et->SetParentScope(NULL);
bool tmp_res;
if (v.IsBooleanValue( tmp_res ))
{
if (tmp_res) *result = 1;
else *result = 0;
retcod = C_CLASSAD_NO_ERROR;
}
else retcod = C_CLASSAD_INVALID_VALUE;
delete ad;
return retcod;
}
int
classad_get_attribute_names(classad_context cad, char ***results)
{
if (cad == NULL) return C_CLASSAD_INVALID_CONTEXT;
if (results == NULL)
return C_CLASSAD_INVALID_ARG;
ClassAd *ad = (ClassAd *)cad;
int n_results = 0;
ClassAd::const_iterator it;
for (it = ad->begin(); it != ad->end(); ++it)
{
n_results++;
char **new_results;
new_results = (char **)realloc(*results, (n_results+1)*sizeof(char *));
if (new_results == NULL)
{
return C_CLASSAD_OUT_OF_MEMORY;
}
(*results) = new_results;
(*results)[n_results] = NULL;
(*results)[n_results-1] = strdup(it->first.c_str());
if (((*results)[n_results-1]) == NULL)
{
return C_CLASSAD_OUT_OF_MEMORY;
}
}
return C_CLASSAD_NO_ERROR;
}
void
classad_free_results(char **results)
{
char **cur;
if (results != NULL)
{
for(cur=results; (*cur)!=NULL; cur++)
{
free(*cur);
}
free(results);
}
}
} // end of extern "C"
<commit_msg>avoid strict alias warning<commit_after>/*
# File : classad_c_helper.C
#
#
# Author : Francesco Prelz ($Author: fprelz $)
# e-mail : "francesco.prelz@mi.infn.it"
#
# Revision history :
# 5-Apr-2004 Original release
# 16-Apr-2004 Added string list parse and unparse.
# 7-May-2004 Added retrieval of string argument into dynamic string.
# 19-Aug-2004 Added boolean attribute.
# 30-Nov-2007 Added function to evaluate a boolean expression
# in the context of a classad.
# 15-Sep-2011 Added helper function to accumulate and return all the attribute
# names in a classad.
#
# Description:
# c-callable layer for handling Classad parse and unparse via the 'new'
# ClassAd library.
#
# Copyright (c) Members of the EGEE Collaboration. 2007-2010.
#
# See http://www.eu-egee.org/partners/ for details on the copyright
# holders.
#
# 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 <string.h>
#include "classad/classad_distribution.h"
#include "classad_binary_op_unwind.h"
#ifdef WANT_NAMESPACES
using namespace classad;
#endif
extern "C"
{
#include <string.h>
#include "classad_c_helper.h"
classad_context
classad_parse (char *s_in)
{
ClassAd *ad = NULL;
ClassAdParser parser;
ad = parser.ParseClassAd(s_in);
// ad == NULL on error.
return ((classad_context)ad);
}
char *
classad_unparse (classad_context cad)
{
if (cad == NULL) return NULL;
std::string res_s;
char *res_c = NULL;
ClassAd *ad = (ClassAd *)cad;
ClassAdUnParser unparser;
unparser.Unparse(res_s, ad);
if (res_s.size() > 0)
{
res_c = strdup(res_s.c_str());
}
// res_c == NULL on error.
return (res_c);
}
int
classad_get_string_attribute (classad_context cad, const char *attribute_name,
char *result, int l_result)
{
if (cad == NULL) return C_CLASSAD_INVALID_CONTEXT;
ClassAd *ad = (ClassAd *)cad;
Value v;
ad->EvaluateAttr(attribute_name, v);
if (v.IsStringValue( result, l_result ))
{
return C_CLASSAD_NO_ERROR;
}
return C_CLASSAD_VALUE_NOT_FOUND;
}
int
classad_get_dstring_attribute (classad_context cad, const char *attribute_name,
char **result)
{
if (cad == NULL) return C_CLASSAD_INVALID_CONTEXT;
ClassAd *ad = (ClassAd *)cad;
if (result != NULL) *result = NULL; /* For those who don't check */
/* the return code... */
Value v;
ad->EvaluateAttr(attribute_name, v);
std::string res_str;
if (v.IsStringValue( res_str ))
{
(*result) = strdup(res_str.c_str());
if ((*result) == NULL) return C_CLASSAD_OUT_OF_MEMORY;
return C_CLASSAD_NO_ERROR;
}
return C_CLASSAD_VALUE_NOT_FOUND;
}
void
classad_free_string_list(char **strl)
{
if (strl != NULL)
{
char **str_val;
for(str_val=strl; (*str_val) != NULL; str_val++)
{
if ((*str_val)!=NULL) free(*str_val);
}
free(strl);
}
}
int
classad_get_string_list_attribute (classad_context cad,
const char *attribute_name,
char ***result)
{
if (cad == NULL) return C_CLASSAD_INVALID_CONTEXT;
int n_results = 0;
(*result) = (char **)malloc(sizeof(char **));
if ((*result) == NULL) return C_CLASSAD_OUT_OF_MEMORY;
(*result)[0] = NULL;
ClassAd *ad = (ClassAd *)cad;
Value vl;
ad->EvaluateAttr(attribute_name, vl);
const ExprList *et_result;
if (vl.IsListValue(et_result))
{
std::vector<ExprTree*> ads;
et_result->GetComponents(ads);
// Get string values.
for(std::vector<ExprTree*>::const_iterator it = ads.begin();
it != ads.end(); ++it)
{
if ((*it)->GetKind() == ExprTree::LITERAL_NODE)
{
Value v;
EvalState state;
state.SetScopes( ad );
(*it)->Evaluate(state,v);
std::string res_str;
if (v.IsStringValue( res_str ))
{
// add string value to result, which is a NULL-terminated
// string array.
n_results++;
(*result) = (char **)realloc(*result, (n_results+1)*sizeof(char *));
if ((*result) == NULL) return C_CLASSAD_OUT_OF_MEMORY;
(*result)[n_results-1] = strdup(res_str.c_str());
(*result)[n_results] = NULL;
}
}
}
return C_CLASSAD_NO_ERROR;
}
// The result list needs to be freed on success only.
classad_free_string_list(*result);
(*result) = NULL;
return C_CLASSAD_VALUE_NOT_FOUND;
}
int
classad_get_int_attribute (classad_context cad, const char *attribute_name,
int *result)
{
if (cad == NULL) return C_CLASSAD_INVALID_CONTEXT;
ClassAd *ad = (ClassAd *)cad;
Value v;
ad->EvaluateAttr(attribute_name, v);
if (v.IsIntegerValue( *result ))
{
return C_CLASSAD_NO_ERROR;
}
return C_CLASSAD_VALUE_NOT_FOUND;
}
int
classad_get_bool_attribute (classad_context cad, const char *attribute_name,
int *result)
{
if (cad == NULL) return C_CLASSAD_INVALID_CONTEXT;
ClassAd *ad = (ClassAd *)cad;
Value v;
ad->EvaluateAttr(attribute_name, v);
bool tmp_res;
if (v.IsBooleanValue( tmp_res ))
{
if (tmp_res) *result = 1;
else *result = 0;
return C_CLASSAD_NO_ERROR;
}
return C_CLASSAD_VALUE_NOT_FOUND;
}
int
classad_put_string_attribute (classad_context *cad, const char *name,
const char *value)
{
ClassAd *ad;
if ((*cad) == NULL)
{
ad = new ClassAd;
(*cad) = (classad_context) ad;
}
else ad = (ClassAd *)(*cad);
std::string str_val(value);
if (ad->InsertAttr (name, str_val)) return C_CLASSAD_NO_ERROR;
else return C_CLASSAD_INSERT_FAILED;
}
int
classad_put_string_list_attribute (classad_context *cad,
const char *name,
char **value)
{
if (value == NULL) return C_CLASSAD_INVALID_VALUE;
ClassAd *ad;
if ((*cad) == NULL)
{
ad = new ClassAd;
(*cad) = (classad_context) ad;
}
else ad = (ClassAd *)(*cad);
char **str_val;
std::vector<ExprTree*> et_ads;
// Traverse NULL-terminated string array.
for(str_val=value; (*str_val) != NULL; str_val++)
{
Value v;
v.SetStringValue(*str_val);
et_ads.push_back(Literal::MakeLiteral(v));
}
ExprTree *et_value = ExprList::MakeExprList(et_ads);
if (ad->Insert (name, et_value)) return C_CLASSAD_NO_ERROR;
else return C_CLASSAD_INSERT_FAILED;
}
int
classad_put_int_attribute (classad_context *cad, const char *name,
int value)
{
ClassAd *ad;
if ((*cad) == NULL)
{
ad = new ClassAd;
(*cad) = (classad_context) ad;
}
else ad = (ClassAd *)(*cad);
if (ad->InsertAttr (name, value)) return C_CLASSAD_NO_ERROR;
else return C_CLASSAD_INSERT_FAILED;
}
int
classad_put_bool_attribute (classad_context *cad, const char *name,
int value)
{
ClassAd *ad;
if ((*cad) == NULL)
{
ad = new ClassAd;
(*cad) = (classad_context) ad;
}
else ad = (ClassAd *)(*cad);
bool tmp_value;
if (value != 0) tmp_value = true;
else tmp_value = false;
if (ad->InsertAttr (name, tmp_value)) return C_CLASSAD_NO_ERROR;
else return C_CLASSAD_INSERT_FAILED;
}
void
classad_free (classad_context cad)
{
ClassAd *ad;
if (cad != NULL)
{
ad = (ClassAd *)cad;
delete ad;
}
}
void
classad_dump (classad_context cad)
{
ClassAd *ad;
if (cad != NULL)
{
ad = (ClassAd *)cad;
ad->Puke();
}
}
int
unwind_attributes(classad_context cad, char *attribute_name, char ***results)
{
if (cad == NULL) return C_CLASSAD_INVALID_CONTEXT;
if ((results == NULL) || (attribute_name == NULL))
return C_CLASSAD_INVALID_ARG;
ClassAd *ad = (ClassAd *)cad;
ExprTree *et;
bool need_to_delete_et = false;
et = ad->Lookup(attribute_name);
if (et == NULL)
{
return C_CLASSAD_VALUE_NOT_FOUND;
}
if (et->GetKind() == ExprTree::LITERAL_NODE)
{
// The attribute was probably stringified. Try to parse it.
Value v;
EvalState state;
state.SetScopes( ad );
et->Evaluate(state,v);
std::string strres;
if (v.IsStringValue( strres ))
{
ClassAdParser parser;
et=NULL;
parser.ParseExpression(strres,et);
need_to_delete_et = true;
}
}
BinaryOpUnwind res_unp;
std::string result;
res_unp.Unparse(result, et);
int n_results;
if (*results == NULL)
{
n_results = 0;
(*results) = (char **)malloc(sizeof(char **));
if ((*results) == NULL) return C_CLASSAD_OUT_OF_MEMORY;
(*results)[0] = NULL;
}
else
{
for (n_results = 0; (*results)[n_results] != NULL; n_results++) /*NOP*/ ;
}
std::vector<std::string>::const_iterator it;
for (it = res_unp.m_unwind_output.begin();
it != res_unp.m_unwind_output.end(); ++it)
{
n_results++;
char **new_results;
new_results = (char **)realloc(*results, (n_results+1)*sizeof(char *));
if (new_results == NULL)
{
if (need_to_delete_et) delete et;
return C_CLASSAD_OUT_OF_MEMORY;
}
(*results) = new_results;
(*results)[n_results] = NULL;
(*results)[n_results-1] = strdup(it->c_str());
if (((*results)[n_results-1]) == NULL)
{
if (need_to_delete_et) delete et;
return C_CLASSAD_OUT_OF_MEMORY;
}
}
if (need_to_delete_et) delete et;
return C_CLASSAD_NO_ERROR;
}
classad_expr_tree
classad_parse_expr(const char *s_ex)
{
ClassAdParser parser;
ExprTree *et = parser.ParseExpression(s_ex);
// et == NULL on error.
return ((classad_expr_tree)et);
}
void
classad_free_tree(classad_expr_tree t_ex)
{
ExprTree *et = (ExprTree *)t_ex;
if (et) delete et;
}
int
classad_evaluate_boolean_expr(const char *s_in, const classad_expr_tree t_ex,
int *result)
{
ClassAd *ad;
ClassAdParser parser;
if (s_in == NULL || t_ex == NULL || result == NULL)
return C_CLASSAD_INVALID_ARG;
ExprTree *et = (ExprTree *)t_ex;
ad = parser.ParseClassAd(s_in);
if (ad == NULL) return C_CLASSAD_PARSE_ERROR;
int retcod = C_CLASSAD_NO_ERROR;
Value v;
et->SetParentScope(ad);
ad->EvaluateExpr(et, v);
et->SetParentScope(NULL);
bool tmp_res;
if (v.IsBooleanValue( tmp_res ))
{
if (tmp_res) *result = 1;
else *result = 0;
retcod = C_CLASSAD_NO_ERROR;
}
else retcod = C_CLASSAD_INVALID_VALUE;
delete ad;
return retcod;
}
int
classad_get_attribute_names(classad_context cad, char ***results)
{
if (cad == NULL) return C_CLASSAD_INVALID_CONTEXT;
if (results == NULL)
return C_CLASSAD_INVALID_ARG;
ClassAd *ad = (ClassAd *)cad;
int n_results = 0;
ClassAd::const_iterator it;
for (it = ad->begin(); it != ad->end(); ++it)
{
n_results++;
char **new_results;
new_results = (char **)realloc(*results, (n_results+1)*sizeof(char *));
if (new_results == NULL)
{
return C_CLASSAD_OUT_OF_MEMORY;
}
(*results) = new_results;
(*results)[n_results] = NULL;
(*results)[n_results-1] = strdup(it->first.c_str());
if (((*results)[n_results-1]) == NULL)
{
return C_CLASSAD_OUT_OF_MEMORY;
}
}
return C_CLASSAD_NO_ERROR;
}
void
classad_free_results(char **results)
{
char **cur;
if (results != NULL)
{
for(cur=results; (*cur)!=NULL; cur++)
{
free(*cur);
}
free(results);
}
}
} // end of extern "C"
<|endoftext|> |
<commit_before>// Copyright (c) 2010, Lawrence Livermore National Security, LLC. Produced at
// the Lawrence Livermore National Laboratory. LLNL-CODE-443211. All Rights
// reserved. See file COPYRIGHT for details.
//
// This file is part of the MFEM library. For more information and source code
// availability see http://mfem.org.
//
// MFEM 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) version 2.1 dated February 1999.
#include "../config/config.hpp"
#ifdef MFEM_USE_MPI
#include "fem.hpp"
using namespace std;
namespace mfem
{
void ParLinearForm::Update(ParFiniteElementSpace *pf)
{
if (pf) { pfes = pf; }
LinearForm::Update(pfes);
}
void ParLinearForm::Update(ParFiniteElementSpace *pf, Vector &v, int v_offset)
{
pfes = pf;
LinearForm::Update(pf,v,v_offset);
}
void ParLinearForm::ParallelAssemble(Vector &tv)
{
pfes->GetProlongationMatrix()->MultTranspose(*this, tv);
}
HypreParVector *ParLinearForm::ParallelAssemble()
{
HypreParVector *tv = pfes->NewTrueDofVector();
pfes->GetProlongationMatrix()->MultTranspose(*this, *tv);
return tv;
}
}
#endif
<commit_msg>Removing unneeded "using" declaration<commit_after>// Copyright (c) 2010, Lawrence Livermore National Security, LLC. Produced at
// the Lawrence Livermore National Laboratory. LLNL-CODE-443211. All Rights
// reserved. See file COPYRIGHT for details.
//
// This file is part of the MFEM library. For more information and source code
// availability see http://mfem.org.
//
// MFEM 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) version 2.1 dated February 1999.
#include "../config/config.hpp"
#ifdef MFEM_USE_MPI
#include "fem.hpp"
namespace mfem
{
void ParLinearForm::Update(ParFiniteElementSpace *pf)
{
if (pf) { pfes = pf; }
LinearForm::Update(pfes);
}
void ParLinearForm::Update(ParFiniteElementSpace *pf, Vector &v, int v_offset)
{
pfes = pf;
LinearForm::Update(pf,v,v_offset);
}
void ParLinearForm::ParallelAssemble(Vector &tv)
{
pfes->GetProlongationMatrix()->MultTranspose(*this, tv);
}
HypreParVector *ParLinearForm::ParallelAssemble()
{
HypreParVector *tv = pfes->NewTrueDofVector();
pfes->GetProlongationMatrix()->MultTranspose(*this, *tv);
return tv;
}
}
#endif
<|endoftext|> |
<commit_before>/*
* Funambol is a mobile platform developed by Funambol, Inc.
* Copyright (C) 2003 - 2007 Funambol, Inc.
*
* This program is free software; you can redistribute it and/or modify it under
* the terms of the GNU Affero General Public License version 3 as published by
* the Free Software Foundation with the addition of the following permission
* added to Section 15 as permitted in Section 7(a): FOR ANY PART OF THE COVERED
* WORK IN WHICH THE COPYRIGHT IS OWNED BY FUNAMBOL, FUNAMBOL DISCLAIMS THE
* WARRANTY OF NON INFRINGEMENT OF THIRD PARTY RIGHTS.
*
* 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 Affero General Public License
* along with this program; if not, see http://www.gnu.org/licenses or write to
* the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
* MA 02110-1301 USA.
*
* You can contact Funambol, Inc. headquarters at 643 Bair Island Road, Suite
* 305, Redwood City, CA 94063, USA, or at email address info@funambol.com.
*
* The interactive user interfaces in modified source and object code versions
* of this program must display Appropriate Legal Notices, as required under
* Section 5 of the GNU Affero General Public License version 3.
*
* In accordance with Section 7(b) of the GNU Affero General Public License
* version 3, these Appropriate Legal Notices must retain the display of the
* "Powered by Funambol" logo. If the display of the logo is not reasonably
* feasible for technical reasons, the Appropriate Legal Notices must display
* the words "Powered by Funambol".
*/
#include <CommDbConnPref.h> // connection prefs (iap)
#include "push/FSocket.h"
#include "base/SymbianLog.h"
#include "base/util/stringUtils.h"
#include "base/util/symbianUtils.h"
StringBuffer FSocket::lIP;
FSocket* FSocket::createSocket(const StringBuffer& peer, int32_t port)
{
return FSocket::NewL(peer, port);
}
FSocket* FSocket::NewL(const StringBuffer& peer, int32_t port)
{
FSocket* self = FSocket::NewLC(peer, port);
CleanupStack::Pop( self );
return self;
}
FSocket* FSocket::NewLC(const StringBuffer& peer, int32_t port)
{
FSocket* self = new ( ELeave ) FSocket();
CleanupStack::PushL( self );
self->ConstructL(peer, port);
return self;
}
void FSocket::ConstructL(const StringBuffer& peer, int32_t port)
{
LOG.debug("FSocket::ConstructL");
StringBuffer errorMsg;
RHostResolver resolver;
RBuf serverName;
TNameEntry hostAddress;
TInetAddr address;
serverName.Assign(stringBufferToNewBuf(peer));
// Create the socket session
iSocketSession.Connect();
// Open the Client Socket tcp/ip
TInt res = iSocket.Open(iSocketSession, KAfInet, KSockStream, KProtocolInetTcp);
if (res != KErrNone) {
iStatus = -1;
errorMsg = "Error opening socket";
goto error;
}
// --- Resolve the host address ---
LOG.debug("resolve IP address...");
res = resolver.Open(iSocketSession, KAfInet, KProtocolInetTcp);
if (res != KErrNone) {
iStatus = -2;
errorMsg = "Host resolver open failed";
goto error;
}
resolver.GetByName(serverName, hostAddress, iStatus);
User::WaitForRequest(iStatus);
resolver.Close();
if (iStatus != KErrNone) {
errorMsg = "DNS lookup failed";
goto error;
}
// Set the socket server address/port
address = hostAddress().iAddr;
address.SetPort(port);
// --- Connect to host ---
LOG.debug("connect...");
iSocket.Connect(address, iStatus);
User::WaitForRequest(iStatus);
if (iStatus != KErrNone) {
errorMsg = "Failed to connect to Server";
goto error;
}
return;
error:
LOG.error(errorMsg.c_str()); // msgBox?
iSocketSession.Close();
return;
}
FSocket::FSocket()
{
iStatus = 0;
}
FSocket::~FSocket()
{
close();
}
int32_t FSocket::writeBuffer(const int8_t* const buffer, int32_t len)
{
// This doesn't copy the buffer in memory.
TPtr8 data((TUint8*)buffer, len);
// Sends data to the remote host.
iSocket.Write(data, iStatus);
User::WaitForRequest(iStatus);
if (iStatus == KErrNone) {
return len;
}
else {
LOG.error("FSocket: error writing on socket (status = %d)", iStatus.Int());
return -1;
}
}
int32_t FSocket::readBuffer(int8_t* buffer, int32_t maxLen)
{
RBuf8 data;
data.CreateL(maxLen);
// Receives data from a remote host and completes when data is available.
do {
TSockXfrLength len;
iSocket.RecvOneOrMore(data, 0, iStatus, len);
User::WaitForRequest(iStatus);
LOG.debug("received %d bytes...", data.Length());
} while (iStatus == KErrNone);
//
// TODO: status error codes?
//
if (iStatus == KErrNone) {
const char* ret = buf8ToNewChar(data);
buffer = (int8_t*)ret;
return data.Length();
}
else {
LOG.error("FSocket: error reading on socket (status = %d)", iStatus.Int());
buffer = NULL;
return -1;
}
}
void FSocket::close()
{
LOG.debug("FSocket::close");
//iSocket.CancelAll();
iSocket.Close();
iSocketSession.Close();
}
const StringBuffer& FSocket::address() const {
return lAddress;
}
const StringBuffer& FSocket::peerAddress() const {
return pAddress;
}
const StringBuffer& FSocket::localIP() {
return lIP;
}
void FSocket::startConnection()
{
RConnection connection;
RSocketServ socketServ;
User::LeaveIfError(socketServ.Connect());
// Use the default IAP without prompting the user
TUint32 UidAP=0;
TCommDbConnPref prefs;
prefs.SetDialogPreference (ECommDbDialogPrefDoNotPrompt);
prefs.SetDirection (ECommDbConnectionDirectionUnknown);
prefs.SetIapId (UidAP);
User::LeaveIfError (connection.Open (socketServ, KAfInet));
User::LeaveIfError (connection.Start (prefs));
// use this to search for a particular IAP to use
// withouth prompting the user
#if defined(PREDEFINED_IAP)
CCommsDatabase* commDb = CCommsDatabase::NewL(EDatabaseTypeIAP);
CleanupStack::PushL(commDb);
CApSelect* select = CApSelect::NewLC(*commDb,KEApIspTypeAll,EApBearerTypeAll,KEApSortUidAscending);
TBuf<256> accessPoint;
TInt UidAP= 0;
TBool ok = select->MoveToFirst();
for (TInt32 i = 0; ok&&(i<select->Count()); i++)
{
if ( select->Name ()==_L(PREDEFINED_IAP))
{
UidAP = select->Uid ();
TCommDbConnPref prefs;
prefs.SetDialogPreference (ECommDbDialogPrefDoNotPrompt);
prefs.SetDirection (ECommDbConnectionDirectionUnknown);
prefs.SetIapId (UidAP);
User::LeaveIfError (iConnection.Open (iSocketSession, KAfInet));
User::LeaveIfError (iConnection.Start (prefs));
}
else
{
ok = select->MoveNext ();
}
}
#else
// use this if you want prompt user for IAP
TCommDbConnPref pref;
pref.SetDirection(ECommDbConnectionDirectionUnknown);
connection.Open(socketServ, KAfInet);
connection.Start(pref);
#endif
socketServ.Close();
}
<commit_msg>- createSocket() returns NULL if there was some error inside ContructL - numeric ipaddress are accepted (like "x.y.z.w")<commit_after>/*
* Funambol is a mobile platform developed by Funambol, Inc.
* Copyright (C) 2003 - 2007 Funambol, Inc.
*
* This program is free software; you can redistribute it and/or modify it under
* the terms of the GNU Affero General Public License version 3 as published by
* the Free Software Foundation with the addition of the following permission
* added to Section 15 as permitted in Section 7(a): FOR ANY PART OF THE COVERED
* WORK IN WHICH THE COPYRIGHT IS OWNED BY FUNAMBOL, FUNAMBOL DISCLAIMS THE
* WARRANTY OF NON INFRINGEMENT OF THIRD PARTY RIGHTS.
*
* 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 Affero General Public License
* along with this program; if not, see http://www.gnu.org/licenses or write to
* the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
* MA 02110-1301 USA.
*
* You can contact Funambol, Inc. headquarters at 643 Bair Island Road, Suite
* 305, Redwood City, CA 94063, USA, or at email address info@funambol.com.
*
* The interactive user interfaces in modified source and object code versions
* of this program must display Appropriate Legal Notices, as required under
* Section 5 of the GNU Affero General Public License version 3.
*
* In accordance with Section 7(b) of the GNU Affero General Public License
* version 3, these Appropriate Legal Notices must retain the display of the
* "Powered by Funambol" logo. If the display of the logo is not reasonably
* feasible for technical reasons, the Appropriate Legal Notices must display
* the words "Powered by Funambol".
*/
#include <CommDbConnPref.h> // connection prefs (iap)
#include "push/FSocket.h"
#include "base/SymbianLog.h"
#include "base/util/stringUtils.h"
#include "base/util/symbianUtils.h"
StringBuffer FSocket::lIP;
FSocket* FSocket::createSocket(const StringBuffer& peer, int32_t port)
{
return FSocket::NewL(peer, port);
}
FSocket* FSocket::NewL(const StringBuffer& peer, int32_t port)
{
FSocket* self = FSocket::NewLC(peer, port);
CleanupStack::Pop( self );
return self;
}
FSocket* FSocket::NewLC(const StringBuffer& peer, int32_t port)
{
FSocket* self = new ( ELeave ) FSocket();
CleanupStack::PushL( self );
self->ConstructL(peer, port);
if (self->getLastStatus() != KErrNone) {
// Something wrong.
delete self;
return NULL;
}
return self;
}
void FSocket::ConstructL(const StringBuffer& peer, int32_t port)
{
LOG.debug("FSocket::ConstructL");
StringBuffer errorMsg;
RHostResolver resolver;
RBuf serverName;
TNameEntry hostAddress;
TInetAddr address;
serverName.Assign(stringBufferToNewBuf(peer));
// Create the socket session
iSocketSession.Connect();
// Open the Client Socket tcp/ip
TInt res = iSocket.Open(iSocketSession, KAfInet, KSockStream, KProtocolInetTcp);
if (res != KErrNone) {
iStatus = -1;
errorMsg = "Error opening socket";
goto error;
}
// This works if serverName is the ip address, like "x.y.z.w"
res = address.Input(serverName);
if (res != KErrNone) {
// Try to resolve the host address
LOG.debug("resolve IP address...");
res = resolver.Open(iSocketSession, KAfInet, KProtocolInetTcp);
if (res != KErrNone) {
iStatus = -2;
errorMsg = "Host resolver open failed";
goto error;
}
resolver.GetByName(serverName, hostAddress, iStatus);
User::WaitForRequest(iStatus);
resolver.Close();
if (iStatus != KErrNone) {
errorMsg = "DNS lookup failed";
goto error;
}
// Set the socket server address/port
address = hostAddress().iAddr;
}
address.SetPort(port);
// --- Connect to host ---
LOG.debug("connect...");
iSocket.Connect(address, iStatus);
User::WaitForRequest(iStatus);
if (iStatus != KErrNone) {
errorMsg = "Failed to connect to Server";
goto error;
}
return;
error:
LOG.error(errorMsg.c_str()); // msgBox?
iSocketSession.Close();
return;
}
FSocket::FSocket()
{
iStatus = 0;
}
FSocket::~FSocket()
{
close();
}
int32_t FSocket::writeBuffer(const int8_t* const buffer, int32_t len)
{
// This doesn't copy the buffer in memory.
TPtr8 data((TUint8*)buffer, len);
// Sends data to the remote host.
iSocket.Write(data, iStatus);
User::WaitForRequest(iStatus);
if (iStatus == KErrNone) {
return len;
}
else {
LOG.error("FSocket: error writing on socket (status = %d)", iStatus.Int());
return -1;
}
}
int32_t FSocket::readBuffer(int8_t* buffer, int32_t maxLen)
{
RBuf8 data;
data.CreateL(maxLen);
// Receives data from a remote host and completes when data is available.
do {
TSockXfrLength len;
iSocket.RecvOneOrMore(data, 0, iStatus, len);
User::WaitForRequest(iStatus);
LOG.debug("received %d bytes...", data.Length());
} while (iStatus == KErrNone);
//
// TODO: status error codes?
//
if (iStatus == KErrNone) {
const char* ret = buf8ToNewChar(data);
buffer = (int8_t*)ret;
return data.Length();
}
else {
LOG.error("FSocket: error reading on socket (status = %d)", iStatus.Int());
buffer = NULL;
return -1;
}
}
void FSocket::close()
{
LOG.debug("FSocket::close");
//iSocket.CancelAll();
iSocket.Close();
iSocketSession.Close();
}
const StringBuffer& FSocket::address() const {
return lAddress;
}
const StringBuffer& FSocket::peerAddress() const {
return pAddress;
}
const StringBuffer& FSocket::localIP() {
return lIP;
}
void FSocket::startConnection()
{
RConnection connection;
RSocketServ socketServ;
User::LeaveIfError(socketServ.Connect());
// Use the default IAP without prompting the user
TUint32 UidAP=0;
TCommDbConnPref prefs;
prefs.SetDialogPreference (ECommDbDialogPrefDoNotPrompt);
prefs.SetDirection (ECommDbConnectionDirectionUnknown);
prefs.SetIapId (UidAP);
User::LeaveIfError (connection.Open (socketServ, KAfInet));
User::LeaveIfError (connection.Start (prefs));
// use this to search for a particular IAP to use
// withouth prompting the user
#if defined(PREDEFINED_IAP)
CCommsDatabase* commDb = CCommsDatabase::NewL(EDatabaseTypeIAP);
CleanupStack::PushL(commDb);
CApSelect* select = CApSelect::NewLC(*commDb,KEApIspTypeAll,EApBearerTypeAll,KEApSortUidAscending);
TBuf<256> accessPoint;
TInt UidAP= 0;
TBool ok = select->MoveToFirst();
for (TInt32 i = 0; ok&&(i<select->Count()); i++)
{
if ( select->Name ()==_L(PREDEFINED_IAP))
{
UidAP = select->Uid ();
TCommDbConnPref prefs;
prefs.SetDialogPreference (ECommDbDialogPrefDoNotPrompt);
prefs.SetDirection (ECommDbConnectionDirectionUnknown);
prefs.SetIapId (UidAP);
User::LeaveIfError (iConnection.Open (iSocketSession, KAfInet));
User::LeaveIfError (iConnection.Start (prefs));
}
else
{
ok = select->MoveNext ();
}
}
#else
// use this if you want prompt user for IAP
TCommDbConnPref pref;
pref.SetDirection(ECommDbConnectionDirectionUnknown);
connection.Open(socketServ, KAfInet);
connection.Start(pref);
#endif
socketServ.Close();
}
<|endoftext|> |
<commit_before>#include <wayfire/plugin.hpp>
#include <wayfire/view.hpp>
#include <wayfire/matcher.hpp>
#include <wayfire/output.hpp>
#include <wayfire/view-transform.hpp>
#include <wayfire/workspace-stream.hpp>
#include <wayfire/workspace-manager.hpp>
#include <wayfire/signal-definitions.hpp>
#include "blur.hpp"
using blur_algorithm_provider = std::function<nonstd::observer_ptr<wf_blur_base>()>;
class wf_blur_transformer : public wf::view_transformer_t
{
blur_algorithm_provider provider;
wf::output_t *output;
wayfire_view view;
public:
wf_blur_transformer(blur_algorithm_provider blur_algorithm_provider,
wf::output_t *output, wayfire_view view)
{
provider = blur_algorithm_provider;
this->output = output;
this->view = view;
}
wf::pointf_t transform_point(wf::geometry_t view,
wf::pointf_t point) override
{
return point;
}
wf::pointf_t untransform_point(wf::geometry_t view,
wf::pointf_t point) override
{
return point;
}
wlr_box get_bounding_box(wf::geometry_t view, wlr_box region) override
{
return region;
}
wf::region_t transform_opaque_region(
wf::geometry_t bbox, wf::region_t region) override
{
return region;
}
uint32_t get_z_order() override
{
return wf::TRANSFORMER_BLUR;
}
/* Render without blending */
void direct_render(wf::texture_t src_tex, wlr_box src_box,
const wf::region_t& damage, const wf::framebuffer_t& target_fb)
{
OpenGL::render_begin(target_fb);
for (auto& rect : damage)
{
target_fb.logic_scissor(wlr_box_from_pixman_box(rect));
OpenGL::render_texture(src_tex, target_fb, src_box);
}
OpenGL::render_end();
}
void render_with_damage(wf::texture_t src_tex, wlr_box src_box,
const wf::region_t& damage, const wf::framebuffer_t& target_fb) override
{
wf::region_t clip_damage = damage & src_box;
/* We want to check if the opaque region completely occludes
* the bounding box. If this is the case, we can skip blurring
* altogether and just render the surface. First we disable
* shrinking and get the opaque region without padding */
wf::surface_interface_t::set_opaque_shrink_constraint("blur", 0);
wf::region_t full_opaque = view->get_transformed_opaque_region();
/* Shrink the opaque region by the padding amount since the render
* chain expects this, as we have applied padding to damage in
* frame_pre_paint for this frame already */
int padding = std::ceil(provider()->calculate_blur_radius() /
output->render->get_target_framebuffer().scale);
wf::surface_interface_t::set_opaque_shrink_constraint("blur", padding);
wf::region_t bbox_region{src_box};
if ((bbox_region ^ full_opaque).empty())
{
/* In case the whole surface is opaque, we can simply skip blurring */
direct_render(src_tex, src_box, damage, target_fb);
return;
}
wf::region_t opaque_region = view->get_transformed_opaque_region();
wf::region_t blurred_region = clip_damage ^ opaque_region;
provider()->pre_render(src_tex, src_box, blurred_region, target_fb);
wf::view_transformer_t::render_with_damage(src_tex, src_box, blurred_region,
target_fb);
/* Opaque non-blurred regions can be rendered directly without blending */
direct_render(src_tex, src_box, opaque_region & clip_damage, target_fb);
}
void render_box(wf::texture_t src_tex, wlr_box src_box, wlr_box scissor_box,
const wf::framebuffer_t& target_fb) override
{
provider()->render(src_tex, src_box, scissor_box, target_fb);
}
};
class wayfire_blur : public wf::plugin_interface_t
{
wf::button_callback button_toggle;
wf::effect_hook_t frame_pre_paint;
wf::signal_callback_t workspace_stream_pre, workspace_stream_post,
view_attached, view_detached;
wf::view_matcher_t blur_by_default{"blur/blur_by_default"};
wf::option_wrapper_t<std::string> method_opt{"blur/method"};
wf::option_wrapper_t<wf::buttonbinding_t> toggle_button{"blur/toggle"};
wf::config::option_base_t::updated_callback_t blur_method_changed;
std::unique_ptr<wf_blur_base> blur_algorithm;
const std::string transformer_name = "blur";
/* the pixels from padded_region */
wf::framebuffer_base_t saved_pixels;
wf::region_t padded_region;
void add_transformer(wayfire_view view)
{
if (view->get_transformer(transformer_name))
{
return;
}
view->add_transformer(std::make_unique<wf_blur_transformer>(
[=] () {return nonstd::make_observer(blur_algorithm.get()); },
output, view),
transformer_name);
}
void pop_transformer(wayfire_view view)
{
if (view->get_transformer(transformer_name))
{
view->pop_transformer(transformer_name);
}
}
void remove_transformers()
{
for (auto& view : output->workspace->get_views_in_layer(wf::ALL_LAYERS))
{
pop_transformer(view);
}
}
/** Transform region into framebuffer coordinates */
wf::region_t get_fb_region(const wf::region_t& region,
const wf::framebuffer_t& fb) const
{
wf::region_t result;
for (const auto& rect : region)
{
result |= fb.framebuffer_box_from_geometry_box(
wlr_box_from_pixman_box(rect));
}
return result;
}
wf::region_t expand_region(const wf::region_t& region, double scale) const
{
// As long as the padding is big enough to cover the
// furthest sampled pixel by the shader, there should
// be no visual artifacts.
int padding = std::ceil(
blur_algorithm->calculate_blur_radius() / scale);
wf::region_t padded;
for (const auto& rect : region)
{
padded |= wlr_box{
(rect.x1 - padding),
(rect.y1 - padding),
(rect.x2 - rect.x1) + 2 * padding,
(rect.y2 - rect.y1) + 2 * padding
};
}
return padded;
}
// Blur region for current frame
wf::region_t blur_region;
void update_blur_region()
{
blur_region.clear();
auto views = output->workspace->get_views_in_layer(wf::ALL_LAYERS);
for (auto& view : views)
{
if (!view->get_transformer("blur"))
{
continue;
}
auto bbox = view->get_bounding_box();
if (!view->sticky)
{
blur_region |= bbox;
} else
{
auto wsize = output->workspace->get_workspace_grid_size();
for (int i = 0; i < wsize.width; i++)
{
for (int j = 0; j < wsize.height; j++)
{
blur_region |=
bbox + wf::origin(output->render->get_ws_box({i, j}));
}
}
}
}
}
/** Find the region of blurred views on the given workspace */
wf::region_t get_blur_region(wf::point_t ws) const
{
return blur_region & output->render->get_ws_box(ws);
}
public:
void init() override
{
grab_interface->name = "blur";
grab_interface->capabilities = 0;
blur_method_changed = [=] ()
{
blur_algorithm = create_blur_from_name(output, method_opt);
output->render->damage_whole();
};
/* Create initial blur algorithm */
blur_method_changed();
method_opt.set_callback(blur_method_changed);
/* Toggles the blur state of the view the user clicked on */
button_toggle = [=] (uint32_t, int, int)
{
if (!output->can_activate_plugin(grab_interface))
{
return false;
}
auto view = wf::get_core().get_cursor_focus_view();
if (!view)
{
return false;
}
if (view->get_transformer(transformer_name))
{
view->pop_transformer(transformer_name);
} else
{
add_transformer(view);
}
return true;
};
output->add_button(toggle_button, &button_toggle);
// Add blur transformers to views which have blur enabled
view_attached = [=] (wf::signal_data_t *data)
{
auto view = get_signaled_view(data);
/* View was just created -> we don't know its layer yet */
if (!view->is_mapped())
{
return;
}
if (blur_by_default.matches(view))
{
add_transformer(view);
}
};
/* If a view is detached, we remove its blur transformer.
* If it is just moved to another output, the blur plugin
* on the other output will add its own transformer there */
view_detached = [=] (wf::signal_data_t *data)
{
auto view = get_signaled_view(data);
pop_transformer(view);
};
output->connect_signal("view-attached", &view_attached);
output->connect_signal("view-mapped", &view_attached);
output->connect_signal("view-detached", &view_detached);
/* frame_pre_paint is called before each frame has started.
* It expands the damage by the blur radius.
* This is needed, because when blurring, the pixels that changed
* affect a larger area than the really damaged region, e.g the region
* that comes from client damage */
frame_pre_paint = [=] ()
{
update_blur_region();
auto damage = output->render->get_scheduled_damage();
const auto& fb = output->render->get_target_framebuffer();
int padding = std::ceil(
blur_algorithm->calculate_blur_radius() / fb.scale);
wf::surface_interface_t::set_opaque_shrink_constraint("blur",
padding);
output->render->damage(expand_region(
damage & this->blur_region, fb.scale));
};
output->render->add_effect(&frame_pre_paint, wf::OUTPUT_EFFECT_DAMAGE);
/* workspace_stream_pre is called before rendering each frame
* when rendering a workspace. It gives us a chance to pad
* damage and take a snapshot of the padded area. The padded
* damage will be used to render the scene as normal. Then
* workspace_stream_post is called so we can copy the padded
* pixels back. */
workspace_stream_pre = [=] (wf::signal_data_t *data)
{
auto& damage = static_cast<wf::stream_signal_t*>(data)->raw_damage;
const auto& ws = static_cast<wf::stream_signal_t*>(data)->ws;
const auto& target_fb = static_cast<wf::stream_signal_t*>(data)->fb;
wf::region_t expanded_damage =
expand_region(damage & get_blur_region(ws), target_fb.scale);
/* Keep rects on screen */
expanded_damage &= output->render->get_ws_box(ws);
/* Compute padded region and store result in padded_region.
* We need to be careful, because core needs to scale the damage
* back and forth for wlroots. */
padded_region = get_fb_region(expanded_damage, target_fb) ^
get_fb_region(damage, target_fb);
OpenGL::render_begin(target_fb);
/* Initialize a place to store padded region pixels. */
saved_pixels.allocate(target_fb.viewport_width,
target_fb.viewport_height);
/* Setup framebuffer I/O. target_fb contains the pixels
* from last frame at this point. We are writing them
* to saved_pixels, bound as GL_DRAW_FRAMEBUFFER */
saved_pixels.bind();
GL_CALL(glBindFramebuffer(GL_READ_FRAMEBUFFER, target_fb.fb));
/* Copy pixels in padded_region from target_fb to saved_pixels. */
for (const auto& box : padded_region)
{
GL_CALL(glBlitFramebuffer(
box.x1, target_fb.viewport_height - box.y2,
box.x2, target_fb.viewport_height - box.y1,
box.x1, box.y1, box.x2, box.y2,
GL_COLOR_BUFFER_BIT, GL_LINEAR));
}
/* This effectively makes damage the same as expanded_damage. */
damage |= expanded_damage;
GL_CALL(glBindTexture(GL_TEXTURE_2D, 0));
OpenGL::render_end();
};
output->render->connect_signal("workspace-stream-pre",
&workspace_stream_pre);
/* workspace_stream_post is called after rendering each frame
* when rendering a workspace. It gives us a chance to copy
* the pixels back to the framebuffer that we saved in
* workspace_stream_pre. */
workspace_stream_post = [=] (wf::signal_data_t *data)
{
const auto& target_fb = static_cast<wf::stream_signal_t*>(data)->fb;
OpenGL::render_begin(target_fb);
/* Setup framebuffer I/O. target_fb contains the frame
* rendered with expanded damage and artifacts on the edges.
* saved_pixels has the the padded region of pixels to overwrite the
* artifacts that blurring has left behind. */
GL_CALL(glBindFramebuffer(GL_READ_FRAMEBUFFER, saved_pixels.fb));
/* Copy pixels back from saved_pixels to target_fb. */
for (const auto& box : padded_region)
{
GL_CALL(glBlitFramebuffer(box.x1, box.y1, box.x2, box.y2,
box.x1, target_fb.viewport_height - box.y2,
box.x2, target_fb.viewport_height - box.y1,
GL_COLOR_BUFFER_BIT, GL_LINEAR));
}
/* Reset stuff */
padded_region.clear();
GL_CALL(glBindTexture(GL_TEXTURE_2D, 0));
OpenGL::render_end();
};
output->render->connect_signal("workspace-stream-post",
&workspace_stream_post);
}
void fini() override
{
remove_transformers();
output->rem_binding(&button_toggle);
output->disconnect_signal("view-attached", &view_attached);
output->disconnect_signal("view-mapped", &view_attached);
output->disconnect_signal("view-detached", &view_detached);
output->render->rem_effect(&frame_pre_paint);
output->render->disconnect_signal("workspace-stream-pre",
&workspace_stream_pre);
output->render->disconnect_signal("workspace-stream-post",
&workspace_stream_post);
/* Call blur algorithm destructor */
blur_algorithm = nullptr;
OpenGL::render_begin();
saved_pixels.release();
OpenGL::render_end();
}
};
DECLARE_WAYFIRE_PLUGIN(wayfire_blur);
<commit_msg>blur: Enable blur for matching surfaces when plugin is enabled<commit_after>#include <wayfire/plugin.hpp>
#include <wayfire/view.hpp>
#include <wayfire/matcher.hpp>
#include <wayfire/output.hpp>
#include <wayfire/view-transform.hpp>
#include <wayfire/workspace-stream.hpp>
#include <wayfire/workspace-manager.hpp>
#include <wayfire/signal-definitions.hpp>
#include "blur.hpp"
using blur_algorithm_provider = std::function<nonstd::observer_ptr<wf_blur_base>()>;
class wf_blur_transformer : public wf::view_transformer_t
{
blur_algorithm_provider provider;
wf::output_t *output;
wayfire_view view;
public:
wf_blur_transformer(blur_algorithm_provider blur_algorithm_provider,
wf::output_t *output, wayfire_view view)
{
provider = blur_algorithm_provider;
this->output = output;
this->view = view;
}
wf::pointf_t transform_point(wf::geometry_t view,
wf::pointf_t point) override
{
return point;
}
wf::pointf_t untransform_point(wf::geometry_t view,
wf::pointf_t point) override
{
return point;
}
wlr_box get_bounding_box(wf::geometry_t view, wlr_box region) override
{
return region;
}
wf::region_t transform_opaque_region(
wf::geometry_t bbox, wf::region_t region) override
{
return region;
}
uint32_t get_z_order() override
{
return wf::TRANSFORMER_BLUR;
}
/* Render without blending */
void direct_render(wf::texture_t src_tex, wlr_box src_box,
const wf::region_t& damage, const wf::framebuffer_t& target_fb)
{
OpenGL::render_begin(target_fb);
for (auto& rect : damage)
{
target_fb.logic_scissor(wlr_box_from_pixman_box(rect));
OpenGL::render_texture(src_tex, target_fb, src_box);
}
OpenGL::render_end();
}
void render_with_damage(wf::texture_t src_tex, wlr_box src_box,
const wf::region_t& damage, const wf::framebuffer_t& target_fb) override
{
wf::region_t clip_damage = damage & src_box;
/* We want to check if the opaque region completely occludes
* the bounding box. If this is the case, we can skip blurring
* altogether and just render the surface. First we disable
* shrinking and get the opaque region without padding */
wf::surface_interface_t::set_opaque_shrink_constraint("blur", 0);
wf::region_t full_opaque = view->get_transformed_opaque_region();
/* Shrink the opaque region by the padding amount since the render
* chain expects this, as we have applied padding to damage in
* frame_pre_paint for this frame already */
int padding = std::ceil(provider()->calculate_blur_radius() /
output->render->get_target_framebuffer().scale);
wf::surface_interface_t::set_opaque_shrink_constraint("blur", padding);
wf::region_t bbox_region{src_box};
if ((bbox_region ^ full_opaque).empty())
{
/* In case the whole surface is opaque, we can simply skip blurring */
direct_render(src_tex, src_box, damage, target_fb);
return;
}
wf::region_t opaque_region = view->get_transformed_opaque_region();
wf::region_t blurred_region = clip_damage ^ opaque_region;
provider()->pre_render(src_tex, src_box, blurred_region, target_fb);
wf::view_transformer_t::render_with_damage(src_tex, src_box, blurred_region,
target_fb);
/* Opaque non-blurred regions can be rendered directly without blending */
direct_render(src_tex, src_box, opaque_region & clip_damage, target_fb);
}
void render_box(wf::texture_t src_tex, wlr_box src_box, wlr_box scissor_box,
const wf::framebuffer_t& target_fb) override
{
provider()->render(src_tex, src_box, scissor_box, target_fb);
}
};
class wayfire_blur : public wf::plugin_interface_t
{
wf::button_callback button_toggle;
wf::effect_hook_t frame_pre_paint;
wf::signal_callback_t workspace_stream_pre, workspace_stream_post,
view_attached, view_detached;
wf::view_matcher_t blur_by_default{"blur/blur_by_default"};
wf::option_wrapper_t<std::string> method_opt{"blur/method"};
wf::option_wrapper_t<wf::buttonbinding_t> toggle_button{"blur/toggle"};
wf::config::option_base_t::updated_callback_t blur_method_changed;
std::unique_ptr<wf_blur_base> blur_algorithm;
const std::string transformer_name = "blur";
/* the pixels from padded_region */
wf::framebuffer_base_t saved_pixels;
wf::region_t padded_region;
void add_transformer(wayfire_view view)
{
if (view->get_transformer(transformer_name))
{
return;
}
view->add_transformer(std::make_unique<wf_blur_transformer>(
[=] () {return nonstd::make_observer(blur_algorithm.get()); },
output, view),
transformer_name);
}
void pop_transformer(wayfire_view view)
{
if (view->get_transformer(transformer_name))
{
view->pop_transformer(transformer_name);
}
}
void remove_transformers()
{
for (auto& view : output->workspace->get_views_in_layer(wf::ALL_LAYERS))
{
pop_transformer(view);
}
}
/** Transform region into framebuffer coordinates */
wf::region_t get_fb_region(const wf::region_t& region,
const wf::framebuffer_t& fb) const
{
wf::region_t result;
for (const auto& rect : region)
{
result |= fb.framebuffer_box_from_geometry_box(
wlr_box_from_pixman_box(rect));
}
return result;
}
wf::region_t expand_region(const wf::region_t& region, double scale) const
{
// As long as the padding is big enough to cover the
// furthest sampled pixel by the shader, there should
// be no visual artifacts.
int padding = std::ceil(
blur_algorithm->calculate_blur_radius() / scale);
wf::region_t padded;
for (const auto& rect : region)
{
padded |= wlr_box{
(rect.x1 - padding),
(rect.y1 - padding),
(rect.x2 - rect.x1) + 2 * padding,
(rect.y2 - rect.y1) + 2 * padding
};
}
return padded;
}
// Blur region for current frame
wf::region_t blur_region;
void update_blur_region()
{
blur_region.clear();
auto views = output->workspace->get_views_in_layer(wf::ALL_LAYERS);
for (auto& view : views)
{
if (!view->get_transformer("blur"))
{
continue;
}
auto bbox = view->get_bounding_box();
if (!view->sticky)
{
blur_region |= bbox;
} else
{
auto wsize = output->workspace->get_workspace_grid_size();
for (int i = 0; i < wsize.width; i++)
{
for (int j = 0; j < wsize.height; j++)
{
blur_region |=
bbox + wf::origin(output->render->get_ws_box({i, j}));
}
}
}
}
}
/** Find the region of blurred views on the given workspace */
wf::region_t get_blur_region(wf::point_t ws) const
{
return blur_region & output->render->get_ws_box(ws);
}
public:
void init() override
{
grab_interface->name = "blur";
grab_interface->capabilities = 0;
blur_method_changed = [=] ()
{
blur_algorithm = create_blur_from_name(output, method_opt);
output->render->damage_whole();
};
/* Create initial blur algorithm */
blur_method_changed();
method_opt.set_callback(blur_method_changed);
/* Toggles the blur state of the view the user clicked on */
button_toggle = [=] (uint32_t, int, int)
{
if (!output->can_activate_plugin(grab_interface))
{
return false;
}
auto view = wf::get_core().get_cursor_focus_view();
if (!view)
{
return false;
}
if (view->get_transformer(transformer_name))
{
view->pop_transformer(transformer_name);
} else
{
add_transformer(view);
}
return true;
};
output->add_button(toggle_button, &button_toggle);
// Add blur transformers to views which have blur enabled
view_attached = [=] (wf::signal_data_t *data)
{
auto view = get_signaled_view(data);
/* View was just created -> we don't know its layer yet */
if (!view->is_mapped())
{
return;
}
if (blur_by_default.matches(view))
{
add_transformer(view);
}
};
/* If a view is detached, we remove its blur transformer.
* If it is just moved to another output, the blur plugin
* on the other output will add its own transformer there */
view_detached = [=] (wf::signal_data_t *data)
{
auto view = get_signaled_view(data);
pop_transformer(view);
};
output->connect_signal("view-attached", &view_attached);
output->connect_signal("view-mapped", &view_attached);
output->connect_signal("view-detached", &view_detached);
/* frame_pre_paint is called before each frame has started.
* It expands the damage by the blur radius.
* This is needed, because when blurring, the pixels that changed
* affect a larger area than the really damaged region, e.g the region
* that comes from client damage */
frame_pre_paint = [=] ()
{
update_blur_region();
auto damage = output->render->get_scheduled_damage();
const auto& fb = output->render->get_target_framebuffer();
int padding = std::ceil(
blur_algorithm->calculate_blur_radius() / fb.scale);
wf::surface_interface_t::set_opaque_shrink_constraint("blur",
padding);
output->render->damage(expand_region(
damage & this->blur_region, fb.scale));
};
output->render->add_effect(&frame_pre_paint, wf::OUTPUT_EFFECT_DAMAGE);
/* workspace_stream_pre is called before rendering each frame
* when rendering a workspace. It gives us a chance to pad
* damage and take a snapshot of the padded area. The padded
* damage will be used to render the scene as normal. Then
* workspace_stream_post is called so we can copy the padded
* pixels back. */
workspace_stream_pre = [=] (wf::signal_data_t *data)
{
auto& damage = static_cast<wf::stream_signal_t*>(data)->raw_damage;
const auto& ws = static_cast<wf::stream_signal_t*>(data)->ws;
const auto& target_fb = static_cast<wf::stream_signal_t*>(data)->fb;
wf::region_t expanded_damage =
expand_region(damage & get_blur_region(ws), target_fb.scale);
/* Keep rects on screen */
expanded_damage &= output->render->get_ws_box(ws);
/* Compute padded region and store result in padded_region.
* We need to be careful, because core needs to scale the damage
* back and forth for wlroots. */
padded_region = get_fb_region(expanded_damage, target_fb) ^
get_fb_region(damage, target_fb);
OpenGL::render_begin(target_fb);
/* Initialize a place to store padded region pixels. */
saved_pixels.allocate(target_fb.viewport_width,
target_fb.viewport_height);
/* Setup framebuffer I/O. target_fb contains the pixels
* from last frame at this point. We are writing them
* to saved_pixels, bound as GL_DRAW_FRAMEBUFFER */
saved_pixels.bind();
GL_CALL(glBindFramebuffer(GL_READ_FRAMEBUFFER, target_fb.fb));
/* Copy pixels in padded_region from target_fb to saved_pixels. */
for (const auto& box : padded_region)
{
GL_CALL(glBlitFramebuffer(
box.x1, target_fb.viewport_height - box.y2,
box.x2, target_fb.viewport_height - box.y1,
box.x1, box.y1, box.x2, box.y2,
GL_COLOR_BUFFER_BIT, GL_LINEAR));
}
/* This effectively makes damage the same as expanded_damage. */
damage |= expanded_damage;
GL_CALL(glBindTexture(GL_TEXTURE_2D, 0));
OpenGL::render_end();
};
output->render->connect_signal("workspace-stream-pre",
&workspace_stream_pre);
/* workspace_stream_post is called after rendering each frame
* when rendering a workspace. It gives us a chance to copy
* the pixels back to the framebuffer that we saved in
* workspace_stream_pre. */
workspace_stream_post = [=] (wf::signal_data_t *data)
{
const auto& target_fb = static_cast<wf::stream_signal_t*>(data)->fb;
OpenGL::render_begin(target_fb);
/* Setup framebuffer I/O. target_fb contains the frame
* rendered with expanded damage and artifacts on the edges.
* saved_pixels has the the padded region of pixels to overwrite the
* artifacts that blurring has left behind. */
GL_CALL(glBindFramebuffer(GL_READ_FRAMEBUFFER, saved_pixels.fb));
/* Copy pixels back from saved_pixels to target_fb. */
for (const auto& box : padded_region)
{
GL_CALL(glBlitFramebuffer(box.x1, box.y1, box.x2, box.y2,
box.x1, target_fb.viewport_height - box.y2,
box.x2, target_fb.viewport_height - box.y1,
GL_COLOR_BUFFER_BIT, GL_LINEAR));
}
/* Reset stuff */
padded_region.clear();
GL_CALL(glBindTexture(GL_TEXTURE_2D, 0));
OpenGL::render_end();
};
output->render->connect_signal("workspace-stream-post",
&workspace_stream_post);
for (auto& view :
output->workspace->get_views_in_layer(wf::ALL_LAYERS))
{
if (blur_by_default.matches(view))
{
add_transformer(view);
}
}
}
void fini() override
{
remove_transformers();
output->rem_binding(&button_toggle);
output->disconnect_signal("view-attached", &view_attached);
output->disconnect_signal("view-mapped", &view_attached);
output->disconnect_signal("view-detached", &view_detached);
output->render->rem_effect(&frame_pre_paint);
output->render->disconnect_signal("workspace-stream-pre",
&workspace_stream_pre);
output->render->disconnect_signal("workspace-stream-post",
&workspace_stream_post);
/* Call blur algorithm destructor */
blur_algorithm = nullptr;
OpenGL::render_begin();
saved_pixels.release();
OpenGL::render_end();
}
};
DECLARE_WAYFIRE_PLUGIN(wayfire_blur);
<|endoftext|> |
<commit_before>// Copyright 2016 Zheng Xian Qiu
#include "Seeker.h"
namespace Seeker {
vector<ISubscriber*> Event::subscribers;
void Event::Refresh() {
SDL_Event ev;
while(SDL_PollEvent(&ev)) {
switch(ev.type) {
case SDL_KEYDOWN:
Dispatch(EventType::Key);
break;
case SDL_QUIT:
Dispatch(EventType::Quit);
break;
case SDL_MOUSEBUTTONDOWN:
Dispatch(EventType::Mouse);
break;
}
}
}
void Event::On(ISubscriber* event) {
if(Exists(event)) return;
subscribers.push_back(event);
}
void Event::Off(ISubscriber* event) {
if(Exists(event)) {
subscribers.erase(std::remove(subscribers.begin(), subscribers.end(), event), subscribers.end());
}
}
bool Event::Exists(ISubscriber* event) {
for(auto ¤t : subscribers) {
if(current == event) {
return true;
}
}
return false;
}
void Event::Dispatch(const EventType type) {
for(auto ¤t : subscribers) {
current->OnEvent(type);
}
}
}
<commit_msg>Fix compiler use wrong version std::remove<commit_after>// Copyright 2016 Zheng Xian Qiu
#include "Seeker.h"
#include<algorithm> // Prevent use C++17 std::remove
namespace Seeker {
vector<ISubscriber*> Event::subscribers;
void Event::Refresh() {
SDL_Event ev;
while(SDL_PollEvent(&ev)) {
switch(ev.type) {
case SDL_KEYDOWN:
Dispatch(EventType::Key);
break;
case SDL_QUIT:
Dispatch(EventType::Quit);
break;
case SDL_MOUSEBUTTONDOWN:
Dispatch(EventType::Mouse);
break;
}
}
}
void Event::On(ISubscriber* event) {
if(Exists(event)) return;
subscribers.push_back(event);
}
void Event::Off(ISubscriber* event) {
if(Exists(event)) {
subscribers.erase(std::remove(subscribers.begin(), subscribers.end(), event), subscribers.end());
}
}
bool Event::Exists(ISubscriber* event) {
for(auto ¤t : subscribers) {
if(current == event) {
return true;
}
}
return false;
}
void Event::Dispatch(const EventType type) {
for(auto ¤t : subscribers) {
current->OnEvent(type);
}
}
}
<|endoftext|> |
<commit_before>/*=========================================================================
Program: Visualization Library
Module: GlrRen.cc
Language: C++
Date: $Date$
Version: $Revision$
This file is part of the Visualization Library. No part of this file or its
contents may be copied, reproduced or altered in any way without the express
written consent of the authors.
Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen 1993, 1994
=========================================================================*/
#include <math.h>
#include <iostream.h>
#include "GlrRen.hh"
#include "GlrRenW.hh"
#include "GlrProp.hh"
#include "GlrCam.hh"
#include "GlrLgt.hh"
#include "GlrPoly.hh"
#include "GlrTri.hh"
#include "GlrLine.hh"
#include "GlrPnt.hh"
#define MAX_LIGHTS 8
static float amb_light_info[] = {
AMBIENT, 0.2, 0.2, 0.2,
LMNULL
};
vlGlrRenderer::vlGlrRenderer()
{
}
// Description:
// Ask actors to build and draw themselves.
int vlGlrRenderer::UpdateActors()
{
vlActor *anActor;
float visibility;
vlMatrix4x4 matrix;
int count = 0;
// set matrix mode for actors
mmode(MVIEWING);
// loop through actors
for ( this->Actors.InitTraversal(); anActor = this->Actors.GetNextItem(); )
{
// if it's invisible, we can skip the rest
visibility = anActor->GetVisibility();
if (visibility == 1.0)
{
count++;
// build transformation
anActor->GetMatrix(matrix);
matrix.Transpose();
// insert model transformation
pushmatrix();
multmatrix((float (*)[4])(matrix[0]));
anActor->Render((vlRenderer *)this);
popmatrix();
}
}
return count;
}
// Description:
// Ask active camera to load its view matrix.
int vlGlrRenderer::UpdateCameras ()
{
// update the viewing transformation
if (!this->ActiveCamera) return 0;
this->ActiveCamera->Render((vlRenderer *)this);
return 1;
}
// Description:
// Internal method temporarily removes lights before reloading them
// into graphics pipeline.
void vlGlrRenderer::ClearLights (void)
{
short cur_light;
// define a lighting model and set up the ambient light.
// use index 11 for the heck of it. Doesn't matter except for 0.
// update the ambient light
amb_light_info[1] = this->Ambient[0];
amb_light_info[2] = this->Ambient[1];
amb_light_info[3] = this->Ambient[2];
lmdef(DEFLMODEL, 11, 0, amb_light_info);
lmbind(LMODEL, 11);
// now delete all the old lights
for (cur_light = LIGHT0;
cur_light < LIGHT0 + MAX_LIGHTS; cur_light++)
{
lmbind(cur_light,0);
}
this->NumberOfLightsBound = 0;
}
// Description:
// Ask lights to load themselves into graphics pipeline.
int vlGlrRenderer::UpdateLights ()
{
vlLight *light;
short cur_light;
float status;
int count = 0;
cur_light= this->NumberOfLightsBound + LIGHT0;
// set the matrix mode for lighting. ident matrix on viewing stack
mmode(MVIEWING);
pushmatrix();
for ( this->Lights.InitTraversal(); light = this->Lights.GetNextItem(); )
{
status = light->GetSwitch();
// if the light is on then define it and bind it.
// also make sure we still have room.
if ((status > 0.0)&& (cur_light < (LIGHT0+MAX_LIGHTS)))
{
light->Render((vlRenderer *)this,cur_light);
lmbind(cur_light, cur_light);
// increment the current light by one
cur_light++;
count++;
// and do the same for the mirror source if backlit is on
// and we aren't out of lights
if ((this->BackLight > 0.0) &&
(cur_light < (LIGHT0+MAX_LIGHTS)))
{
lmbind(cur_light,cur_light);
// if backlighting is on then increment the current light again
cur_light++;
}
}
}
this->NumberOfLightsBound = cur_light - LIGHT0;
popmatrix();
return count;
}
// Description:
// Concrete gl render method.
void vlGlrRenderer::Render(void)
{
// standard render method
this->ClearLights();
this->DoCameras();
this->DoLights();
this->DoActors();
// clean up the model view matrix set up by the camera
mmode(MVIEWING);
popmatrix();
}
// Description:
// Create particular type of gl geometry primitive.
vlGeometryPrimitive *vlGlrRenderer::GetPrimitive(char *type)
{
vlGeometryPrimitive *prim;
if (!strcmp(type,"polygons"))
{
prim = new vlGlrPolygons;
return (vlGeometryPrimitive *)prim;
}
if (!strcmp(type,"triangle_strips"))
{
prim = new vlGlrTriangleMesh;
return (vlGeometryPrimitive *)prim;
}
if (!strcmp(type,"lines"))
{
prim = new vlGlrLines;
return (vlGeometryPrimitive *)prim;
}
if (!strcmp(type,"points"))
{
prim = new vlGlrPoints;
return (vlGeometryPrimitive *)prim;
}
return((vlGeometryPrimitive *)NULL);
}
void vlGlrRenderer::PrintSelf(ostream& os, vlIndent indent)
{
this->vlRenderer::PrintSelf(os,indent);
os << indent << "Number Of Lights Bound: " <<
this->NumberOfLightsBound << "\n";
}
// Description:
// Return center of renderer in display coordinates.
float *vlGlrRenderer::GetCenter()
{
int *size;
// get physical window dimensions
size = this->RenderWindow->GetSize();
if (this->RenderWindow->GetStereoRender())
{
// take into account stereo effects
switch (this->RenderWindow->GetStereoType())
{
case VL_STEREO_CRYSTAL_EYES:
{
this->Center[0] = ((this->Viewport[2]+this->Viewport[0])
/2.0*(float)size[0]);
this->Center[1] = ((this->Viewport[3]+this->Viewport[1])
/2.0*(float)size[1]);
this->Center[1] = this->Center[1]*(491.0/1024.0);
}
break;
default:
{
this->Center[0] = ((this->Viewport[2]+this->Viewport[0])
/2.0*(float)size[0]);
this->Center[1] = ((this->Viewport[3]+this->Viewport[1])
/2.0*(float)size[1]);
}
}
}
else
{
this->Center[0] = ((this->Viewport[2]+this->Viewport[0])
/2.0*(float)size[0]);
this->Center[1] = ((this->Viewport[3]+this->Viewport[1])
/2.0*(float)size[1]);
}
return this->Center;
}
// Description:
// Convert display coordinates to view coordinates.
void vlGlrRenderer::DisplayToView()
{
float vx,vy,vz;
int sizex,sizey;
int *size;
/* get physical window dimensions */
size = this->RenderWindow->GetSize();
sizex = size[0];
sizey = size[1];
if (this->RenderWindow->GetStereoRender())
{
// take into account stereo effects
switch (this->RenderWindow->GetStereoType())
{
case VL_STEREO_CRYSTAL_EYES:
{
vx = 2.0 * (this->DisplayPoint[0] - sizex*this->Viewport[0])/
(sizex*(this->Viewport[2]-this->Viewport[0])) - 1.0;
vy = 2.0 * (this->DisplayPoint[1]*(1024.0/491.0) -
sizey*this->Viewport[1])/
(sizey*(this->Viewport[3]-this->Viewport[1])) - 1.0;
}
break;
default:
{
vx = 2.0 * (this->DisplayPoint[0] - sizex*this->Viewport[0])/
(sizex*(this->Viewport[2]-this->Viewport[0])) - 1.0;
vy = 2.0 * (this->DisplayPoint[1] - sizey*this->Viewport[1])/
(sizey*(this->Viewport[3]-this->Viewport[1])) - 1.0;
}
}
}
else
{
vx = 2.0 * (this->DisplayPoint[0] - sizex*this->Viewport[0])/
(sizex*(this->Viewport[2]-this->Viewport[0])) - 1.0;
vy = 2.0 * (this->DisplayPoint[1] - sizey*this->Viewport[1])/
(sizey*(this->Viewport[3]-this->Viewport[1])) - 1.0;
}
vz = this->DisplayPoint[2];
this->SetViewPoint(vx*this->Aspect[0],vy*this->Aspect[1],vz);
}
// Description:
// Convert view coordinates to display coordinates.
void vlGlrRenderer::ViewToDisplay()
{
int dx,dy;
int sizex,sizey;
int *size;
/* get physical window dimensions */
size = this->RenderWindow->GetSize();
sizex = size[0];
sizey = size[1];
if (this->RenderWindow->GetStereoRender())
{
// take into account stereo effects
switch (this->RenderWindow->GetStereoType())
{
case VL_STEREO_CRYSTAL_EYES:
{
dx = (int)((this->ViewPoint[0]/this->Aspect[0] + 1.0) *
(sizex*(this->Viewport[2]-this->Viewport[0])) / 2.0 +
sizex*this->Viewport[0]);
dy = (int)((this->ViewPoint[1]/this->Aspect[1] + 1.0) *
(sizey*(this->Viewport[3]-this->Viewport[1])) / 2.0 +
sizey*this->Viewport[1]);
dy = (int)(dy*(491.0/1024.0));
}
break;
default:
{
dx = (int)((this->ViewPoint[0]/this->Aspect[0] + 1.0) *
(sizex*(this->Viewport[2]-this->Viewport[0])) / 2.0 +
sizex*this->Viewport[0]);
dy = (int)((this->ViewPoint[1]/this->Aspect[1] + 1.0) *
(sizey*(this->Viewport[3]-this->Viewport[1])) / 2.0 +
sizey*this->Viewport[1]);
}
}
}
else
{
dx = (int)((this->ViewPoint[0]/this->Aspect[0] + 1.0) *
(sizex*(this->Viewport[2]-this->Viewport[0])) / 2.0 +
sizex*this->Viewport[0]);
dy = (int)((this->ViewPoint[1]/this->Aspect[1] + 1.0) *
(sizey*(this->Viewport[3]-this->Viewport[1])) / 2.0 +
sizey*this->Viewport[1]);
}
this->SetDisplayPoint(dx,dy,this->ViewPoint[2]);
}
// Description:
// Is a given display point in this renderer's viewport.
int vlGlrRenderer::IsInViewport(int x,int y)
{
int *size;
// get physical window dimensions
size = this->RenderWindow->GetSize();
if (this->RenderWindow->GetStereoRender())
{
// take into account stereo effects
switch (this->RenderWindow->GetStereoType())
{
case VL_STEREO_CRYSTAL_EYES:
{
int ty = (int)(y*(1023.0/491.0));
if ((this->Viewport[0]*size[0] <= x)&&
(this->Viewport[2]*size[0] >= x)&&
(this->Viewport[1]*size[1] <= ty)&&
(this->Viewport[3]*size[1] >= ty))
{
return 1;
}
}
break;
default:
{
if ((this->Viewport[0]*size[0] <= x)&&
(this->Viewport[2]*size[0] >= x)&&
(this->Viewport[1]*size[1] <= y)&&
(this->Viewport[3]*size[1] >= y))
{
return 1;
}
}
}
}
else
{
if ((this->Viewport[0]*size[0] <= x)&&
(this->Viewport[2]*size[0] >= x)&&
(this->Viewport[1]*size[1] <= y)&&
(this->Viewport[3]*size[1] >= y))
{
return 1;
}
}
return 0;
}
<commit_msg>added mods for volume rendering<commit_after>/*=========================================================================
Program: Visualization Library
Module: GlrRen.cc
Language: C++
Date: $Date$
Version: $Revision$
This file is part of the Visualization Library. No part of this file or its
contents may be copied, reproduced or altered in any way without the express
written consent of the authors.
Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen 1993, 1994
=========================================================================*/
#include <math.h>
#include <iostream.h>
#include "GlrRen.hh"
#include "GlrRenW.hh"
#include "GlrProp.hh"
#include "GlrCam.hh"
#include "GlrLgt.hh"
#include "GlrPoly.hh"
#include "GlrTri.hh"
#include "GlrLine.hh"
#include "GlrPnt.hh"
#include "VolRen.hh"
#define MAX_LIGHTS 8
static float amb_light_info[] = {
AMBIENT, 0.2, 0.2, 0.2,
LMNULL
};
vlGlrRenderer::vlGlrRenderer()
{
}
// Description:
// Ask actors to build and draw themselves.
int vlGlrRenderer::UpdateActors()
{
vlActor *anActor;
float visibility;
vlMatrix4x4 matrix;
int count = 0;
// set matrix mode for actors
mmode(MVIEWING);
// loop through actors
for ( this->Actors.InitTraversal(); anActor = this->Actors.GetNextItem(); )
{
// if it's invisible, we can skip the rest
visibility = anActor->GetVisibility();
if (visibility == 1.0)
{
count++;
// build transformation
anActor->GetMatrix(matrix);
matrix.Transpose();
// insert model transformation
pushmatrix();
multmatrix((float (*)[4])(matrix[0]));
anActor->Render((vlRenderer *)this);
popmatrix();
}
}
return count;
}
// Description:
// Ask active camera to load its view matrix.
int vlGlrRenderer::UpdateCameras ()
{
// update the viewing transformation
if (!this->ActiveCamera) return 0;
this->ActiveCamera->Render((vlRenderer *)this);
return 1;
}
// Description:
// Internal method temporarily removes lights before reloading them
// into graphics pipeline.
void vlGlrRenderer::ClearLights (void)
{
short cur_light;
// define a lighting model and set up the ambient light.
// use index 11 for the heck of it. Doesn't matter except for 0.
// update the ambient light
amb_light_info[1] = this->Ambient[0];
amb_light_info[2] = this->Ambient[1];
amb_light_info[3] = this->Ambient[2];
lmdef(DEFLMODEL, 11, 0, amb_light_info);
lmbind(LMODEL, 11);
// now delete all the old lights
for (cur_light = LIGHT0;
cur_light < LIGHT0 + MAX_LIGHTS; cur_light++)
{
lmbind(cur_light,0);
}
this->NumberOfLightsBound = 0;
}
// Description:
// Ask lights to load themselves into graphics pipeline.
int vlGlrRenderer::UpdateLights ()
{
vlLight *light;
short cur_light;
float status;
int count = 0;
cur_light= this->NumberOfLightsBound + LIGHT0;
// set the matrix mode for lighting. ident matrix on viewing stack
mmode(MVIEWING);
pushmatrix();
for ( this->Lights.InitTraversal(); light = this->Lights.GetNextItem(); )
{
status = light->GetSwitch();
// if the light is on then define it and bind it.
// also make sure we still have room.
if ((status > 0.0)&& (cur_light < (LIGHT0+MAX_LIGHTS)))
{
light->Render((vlRenderer *)this,cur_light);
lmbind(cur_light, cur_light);
// increment the current light by one
cur_light++;
count++;
// and do the same for the mirror source if backlit is on
// and we aren't out of lights
if ((this->BackLight > 0.0) &&
(cur_light < (LIGHT0+MAX_LIGHTS)))
{
lmbind(cur_light,cur_light);
// if backlighting is on then increment the current light again
cur_light++;
}
}
}
this->NumberOfLightsBound = cur_light - LIGHT0;
popmatrix();
return count;
}
// Description:
// Concrete gl render method.
void vlGlrRenderer::Render(void)
{
// standard render method
this->ClearLights();
this->DoCameras();
this->DoLights();
this->DoActors();
// clean up the model view matrix set up by the camera
mmode(MVIEWING);
popmatrix();
if (this->VolumeRenderer)
{
this->VolumeRenderer->Render((vlRenderer *)this);
}
}
// Description:
// Create particular type of gl geometry primitive.
vlGeometryPrimitive *vlGlrRenderer::GetPrimitive(char *type)
{
vlGeometryPrimitive *prim;
if (!strcmp(type,"polygons"))
{
prim = new vlGlrPolygons;
return (vlGeometryPrimitive *)prim;
}
if (!strcmp(type,"triangle_strips"))
{
prim = new vlGlrTriangleMesh;
return (vlGeometryPrimitive *)prim;
}
if (!strcmp(type,"lines"))
{
prim = new vlGlrLines;
return (vlGeometryPrimitive *)prim;
}
if (!strcmp(type,"points"))
{
prim = new vlGlrPoints;
return (vlGeometryPrimitive *)prim;
}
return((vlGeometryPrimitive *)NULL);
}
void vlGlrRenderer::PrintSelf(ostream& os, vlIndent indent)
{
this->vlRenderer::PrintSelf(os,indent);
os << indent << "Number Of Lights Bound: " <<
this->NumberOfLightsBound << "\n";
}
// Description:
// Return center of renderer in display coordinates.
float *vlGlrRenderer::GetCenter()
{
int *size;
// get physical window dimensions
size = this->RenderWindow->GetSize();
if (this->RenderWindow->GetStereoRender())
{
// take into account stereo effects
switch (this->RenderWindow->GetStereoType())
{
case VL_STEREO_CRYSTAL_EYES:
{
this->Center[0] = ((this->Viewport[2]+this->Viewport[0])
/2.0*(float)size[0]);
this->Center[1] = ((this->Viewport[3]+this->Viewport[1])
/2.0*(float)size[1]);
this->Center[1] = this->Center[1]*(491.0/1024.0);
}
break;
default:
{
this->Center[0] = ((this->Viewport[2]+this->Viewport[0])
/2.0*(float)size[0]);
this->Center[1] = ((this->Viewport[3]+this->Viewport[1])
/2.0*(float)size[1]);
}
}
}
else
{
this->Center[0] = ((this->Viewport[2]+this->Viewport[0])
/2.0*(float)size[0]);
this->Center[1] = ((this->Viewport[3]+this->Viewport[1])
/2.0*(float)size[1]);
}
return this->Center;
}
// Description:
// Convert display coordinates to view coordinates.
void vlGlrRenderer::DisplayToView()
{
float vx,vy,vz;
int sizex,sizey;
int *size;
/* get physical window dimensions */
size = this->RenderWindow->GetSize();
sizex = size[0];
sizey = size[1];
if (this->RenderWindow->GetStereoRender())
{
// take into account stereo effects
switch (this->RenderWindow->GetStereoType())
{
case VL_STEREO_CRYSTAL_EYES:
{
vx = 2.0 * (this->DisplayPoint[0] - sizex*this->Viewport[0])/
(sizex*(this->Viewport[2]-this->Viewport[0])) - 1.0;
vy = 2.0 * (this->DisplayPoint[1]*(1024.0/491.0) -
sizey*this->Viewport[1])/
(sizey*(this->Viewport[3]-this->Viewport[1])) - 1.0;
}
break;
default:
{
vx = 2.0 * (this->DisplayPoint[0] - sizex*this->Viewport[0])/
(sizex*(this->Viewport[2]-this->Viewport[0])) - 1.0;
vy = 2.0 * (this->DisplayPoint[1] - sizey*this->Viewport[1])/
(sizey*(this->Viewport[3]-this->Viewport[1])) - 1.0;
}
}
}
else
{
vx = 2.0 * (this->DisplayPoint[0] - sizex*this->Viewport[0])/
(sizex*(this->Viewport[2]-this->Viewport[0])) - 1.0;
vy = 2.0 * (this->DisplayPoint[1] - sizey*this->Viewport[1])/
(sizey*(this->Viewport[3]-this->Viewport[1])) - 1.0;
}
vz = this->DisplayPoint[2];
this->SetViewPoint(vx*this->Aspect[0],vy*this->Aspect[1],vz);
}
// Description:
// Convert view coordinates to display coordinates.
void vlGlrRenderer::ViewToDisplay()
{
int dx,dy;
int sizex,sizey;
int *size;
/* get physical window dimensions */
size = this->RenderWindow->GetSize();
sizex = size[0];
sizey = size[1];
if (this->RenderWindow->GetStereoRender())
{
// take into account stereo effects
switch (this->RenderWindow->GetStereoType())
{
case VL_STEREO_CRYSTAL_EYES:
{
dx = (int)((this->ViewPoint[0]/this->Aspect[0] + 1.0) *
(sizex*(this->Viewport[2]-this->Viewport[0])) / 2.0 +
sizex*this->Viewport[0]);
dy = (int)((this->ViewPoint[1]/this->Aspect[1] + 1.0) *
(sizey*(this->Viewport[3]-this->Viewport[1])) / 2.0 +
sizey*this->Viewport[1]);
dy = (int)(dy*(491.0/1024.0));
}
break;
default:
{
dx = (int)((this->ViewPoint[0]/this->Aspect[0] + 1.0) *
(sizex*(this->Viewport[2]-this->Viewport[0])) / 2.0 +
sizex*this->Viewport[0]);
dy = (int)((this->ViewPoint[1]/this->Aspect[1] + 1.0) *
(sizey*(this->Viewport[3]-this->Viewport[1])) / 2.0 +
sizey*this->Viewport[1]);
}
}
}
else
{
dx = (int)((this->ViewPoint[0]/this->Aspect[0] + 1.0) *
(sizex*(this->Viewport[2]-this->Viewport[0])) / 2.0 +
sizex*this->Viewport[0]);
dy = (int)((this->ViewPoint[1]/this->Aspect[1] + 1.0) *
(sizey*(this->Viewport[3]-this->Viewport[1])) / 2.0 +
sizey*this->Viewport[1]);
}
this->SetDisplayPoint(dx,dy,this->ViewPoint[2]);
}
// Description:
// Is a given display point in this renderer's viewport.
int vlGlrRenderer::IsInViewport(int x,int y)
{
int *size;
// get physical window dimensions
size = this->RenderWindow->GetSize();
if (this->RenderWindow->GetStereoRender())
{
// take into account stereo effects
switch (this->RenderWindow->GetStereoType())
{
case VL_STEREO_CRYSTAL_EYES:
{
int ty = (int)(y*(1023.0/491.0));
if ((this->Viewport[0]*size[0] <= x)&&
(this->Viewport[2]*size[0] >= x)&&
(this->Viewport[1]*size[1] <= ty)&&
(this->Viewport[3]*size[1] >= ty))
{
return 1;
}
}
break;
default:
{
if ((this->Viewport[0]*size[0] <= x)&&
(this->Viewport[2]*size[0] >= x)&&
(this->Viewport[1]*size[1] <= y)&&
(this->Viewport[3]*size[1] >= y))
{
return 1;
}
}
}
}
else
{
if ((this->Viewport[0]*size[0] <= x)&&
(this->Viewport[2]*size[0] >= x)&&
(this->Viewport[1]*size[1] <= y)&&
(this->Viewport[3]*size[1] >= y))
{
return 1;
}
}
return 0;
}
<|endoftext|> |
<commit_before>#include <iostream>
#include "Input.h"
#include <queue>
#include <sys/wait.h>
#include <sys/types.h>
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <pwd.h>
#include <algorithm>
using namespace std;
// void Input::setUser() {
// }
void Input::getInput() {
strLine.clear();
cout << "$ ";
getline (cin, strLine);
// if the user ONLY entered exit
if (strLine == "exit") {
cout << "You have exited shell." << endl;
exit(0);
}
// if # spotted, cuts off # and everything after it
size_t found = strLine.find('#');
if (found != string::npos) {
strLine.erase(strLine.begin() + found, strLine.end());
if (strLine.size() == 0) {
// cout << "nothing left" << endl;
}
}
}
bool Input::isTest() {
size_t found = strLine.find('[');
if (found != string::npos) {
if ( validTest() ) {
return true;
}
return false;
}
// check if test is first word in string or after connector
if (strLine.find("test ") != string::npos) {
return true;
}
return false;
}
// handle error when user puts something like "] [" wtf
bool Input::validTest() {
size_t cntrOpen = std::count(strLine.begin(), strLine.end(), '[');
size_t cntrClose = std::count(strLine.begin(), strLine.end(), ']');
if (cntrOpen == cntrClose) {
return true;
}
return false;
}
void Input::brackTest() {
// handles [ ]
}
// if semicolon, erase
void Input::semicolon(queue<string>& q, string s) {
if (s.size() != 0 && s.at(s.size()-1) == ';') {
s.erase(s.size()-1);
q.push(s);
q.push(";");
}
else {
q.push(s);
}
}
// returns a queue of parsed string
queue<string> Input::Parse() {
// checks if there's anything
// cout << "test: " << strLine << endl;
// clears tasks queue
queue<string> empty;
swap(tasks, empty);
if (strLine.size() == 0) {
return tasks;
}
// checks if string has only spaces
if (strLine.find_first_not_of(' ') == string::npos) {
return tasks;
}
istringstream iss(strLine);
// iss >> ws;
string token;
string cmd;
// end used to determine if its end of user input
bool end = true;
bool start = true;
// if a connector was just detected
bool con = false;
// if there is a parentheses
bool paren = false;
bool tested = false;
// ignores ' '
while (getline(iss, token, ' ')) {
if ( (start && token == "test") || (con && token == "test" )) {
tasks.push(token);
if (getline(iss, token, ' ')) {
if (token == "-e" || token == "-f" || token == "-d") {
tasks.push(token);
if (getline(iss, token, ' ')) {
// tasks.push(token);
semicolon(tasks, token);
}
// strLine empty
else {return tasks;}
}
else if (token != "&&" && token != "||" && token != ";") {
tasks.push("-e");
// tasks.push(token);
semicolon(tasks, token);
}
else if (token == "&&" || token == "||" || token == ";") {
// tasks.push(token);
semicolon(tasks, token);
}
}
end = false;
tested = true;
}
// removed else if
else if (token == "&&" || token == "||" || token == ";" ||
token == "(" || token == ")") {
// pushes whatever cmd was
// if (!tested) {
if (!cmd.empty()) {
tasks.push(cmd);
}
// makes string empty
cmd.clear();
// pushes &&, ||, or ;
tasks.push(token);
if (token == "(") {paren = true;}
end = false;
con = true;
tested = false;
}
// if you see [, keep reading til you see ]
else if ( (start && token == "[") || (con && token == "[") ) {
tasks.push(token);
bool flag = false;
while (token != "]") {
if (getline(iss, token, ' ')) {
// tasks.push(token);
if (token != "-e" && token != "-f" && token != "-d" && !flag) {
tasks.push("-e");
};
semicolon(tasks, token);
}
// empty
else {return tasks;}
flag = true;
}
end = false;
con = false;
tested = false;
}
// would see if the first char of token is
// ( then would push ( delete it from
// the token then push the actual token in
// would set paren to true letting
// it know that there is a closing
// paren to look for
else if (token.at(0) == '(') {
while (token.at(0) == '(') {
paren = true;
tasks.push("(");
token.erase(0, 1);
// tasks.push(token);
if (cmd.empty() && !token.empty() && token.at(0) != '(') {
cmd = token;
}
else if (!cmd.empty()) {
cmd += " " + token;
}
}
// end = false;
end = true;
con = false;
}
// would check to see if paren is true
// and would see is the last char in
// token is ) then would erase ) from token
// push the token in push the
// ) in and make paren false again
// so that it know the braket is closed
else if (paren == true && token.at(token.size() - 1) == ')') {
int count = 0;
paren = false;
while (token.at(token.size() - 1) == ')') {
token.erase(token.size()-1);
++count;
if (cmd.empty() && !token.empty() && token.at(0) != ')') {
// cout << "1: " << token << endl;
// tasks.push(token);
cmd = token;
}
else if (!cmd.empty() && token.at(token.size()-1) != ')') {
// tasks.push(cmd + " " + token);
// cmd.clear();
cmd += " " + token;
}
// tasks.push(token);
// tasks.push(")");
}
// tasks.push(cmd);
semicolon(tasks, cmd);
cmd.clear();
// paren = false;
while (count != 0) {
tasks.push(")");
count -= 1;
}
end = false;
con = false;
}
// else if not a connector
// else if (strLine.find("&&") != std::string::npos) {
// cout << "found &&" << endl;
// find position and split up string accordingly
// }
else { //if (!tested) {
// check if end of token has semicolon
// remove the extra spaces
// cout << "token: " << token << token.size() << endl;
if (token.size() != 0 && token.at(token.size() - 1) == ';') {
token.erase(token.size()-1);
if (cmd.empty()) {
tasks.push(token);
}
else {
tasks.push(cmd + " " + token);
cmd.clear();
}
tasks.push(";");
end = false;
}
// check if connectors are hidden in words
// no semicolon detected at end of word
else {
if (cmd.empty()) {
cmd = token;
}
else {
cmd = cmd + " " + token;
}
end = true;
}
con = false;
tested = false;
}
start = false;
}
// if no more connectors were detected
if (end && paren) {
if (cmd.at(cmd.size() - 1) == ')') {
cmd.erase(cmd.size()-1);
semicolon(tasks, cmd);
tasks.push(")");
}
}
else if (end) {
tasks.push(cmd);
}
// check if last thing in task is a && or ||
// if (token == "&&" || token == "||") {
// get user input again
// getInput();
// Parse();
// }
return tasks;
}
// converts a token to char**
char** Input::toChar(string a) {
stringstream stream(a);
string oneWord;
int i = 0;
char** c = new char*[1024];
// one word at a time
while (stream >> oneWord) {
// allocating memory
char* ptr = new char[oneWord.size() + 1];
// copies string (converted to c-string) to ptr)
memcpy(ptr, oneWord.c_str(), oneWord.size() + 1);
c[i] = ptr;
++i;
}
// null terminates the char**
c[i] = '\0';
return c;
}
<commit_msg>fixed semi in paren, need to fix after paren<commit_after>#include <iostream>
#include "Input.h"
#include <queue>
#include <sys/wait.h>
#include <sys/types.h>
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <pwd.h>
#include <algorithm>
using namespace std;
// void Input::setUser() {
// }
void Input::getInput() {
strLine.clear();
cout << "$ ";
getline (cin, strLine);
// if the user ONLY entered exit
if (strLine == "exit") {
cout << "You have exited shell." << endl;
exit(0);
}
// if # spotted, cuts off # and everything after it
size_t found = strLine.find('#');
if (found != string::npos) {
strLine.erase(strLine.begin() + found, strLine.end());
if (strLine.size() == 0) {
// cout << "nothing left" << endl;
}
}
}
bool Input::isTest() {
size_t found = strLine.find('[');
if (found != string::npos) {
if ( validTest() ) {
return true;
}
return false;
}
// check if test is first word in string or after connector
if (strLine.find("test ") != string::npos) {
return true;
}
return false;
}
// handle error when user puts something like "] [" wtf
bool Input::validTest() {
size_t cntrOpen = std::count(strLine.begin(), strLine.end(), '[');
size_t cntrClose = std::count(strLine.begin(), strLine.end(), ']');
if (cntrOpen == cntrClose) {
return true;
}
return false;
}
void Input::brackTest() {
// handles [ ]
}
// if semicolon, erase
void Input::semicolon(queue<string>& q, string s) {
if (s.size() != 0 && s.at(s.size()-1) == ';') {
s.erase(s.size()-1);
q.push(s);
q.push(";");
}
else {
q.push(s);
}
}
// returns a queue of parsed string
queue<string> Input::Parse() {
// checks if there's anything
// cout << "test: " << strLine << endl;
// clears tasks queue
queue<string> empty;
swap(tasks, empty);
if (strLine.size() == 0) {
return tasks;
}
// checks if string has only spaces
if (strLine.find_first_not_of(' ') == string::npos) {
return tasks;
}
istringstream iss(strLine);
// iss >> ws;
string token;
string cmd;
// end used to determine if its end of user input
bool end = true;
bool start = true;
// if a connector was just detected
bool con = false;
// if there is a parentheses
bool paren = false;
bool tested = false;
// ignores ' '
while (getline(iss, token, ' ')) {
if ( (start && token == "test") || (con && token == "test" )) {
tasks.push(token);
if (getline(iss, token, ' ')) {
if (token == "-e" || token == "-f" || token == "-d") {
tasks.push(token);
if (getline(iss, token, ' ')) {
// tasks.push(token);
semicolon(tasks, token);
}
// strLine empty
else {return tasks;}
}
else if (token != "&&" && token != "||" && token != ";") {
tasks.push("-e");
// tasks.push(token);
semicolon(tasks, token);
}
else if (token == "&&" || token == "||" || token == ";") {
// tasks.push(token);
semicolon(tasks, token);
}
}
end = false;
tested = true;
}
// removed else if
else if (token == "&&" || token == "||" || token == ";" ||
token == "(" || token == ")") {
// pushes whatever cmd was
// if (!tested) {
if (!cmd.empty()) {
tasks.push(cmd);
}
// makes string empty
cmd.clear();
// pushes &&, ||, or ;
tasks.push(token);
if (token == "(") {paren = true;}
end = false;
con = true;
tested = false;
}
// if you see [, keep reading til you see ]
else if ( (start && token == "[") || (con && token == "[") ) {
tasks.push(token);
bool flag = false;
while (token != "]") {
if (getline(iss, token, ' ')) {
// tasks.push(token);
if (token != "-e" && token != "-f" && token != "-d" && !flag) {
tasks.push("-e");
};
semicolon(tasks, token);
}
// empty
else {return tasks;}
flag = true;
}
end = false;
con = false;
tested = false;
}
// would see if the first char of token is
// ( then would push ( delete it from
// the token then push the actual token in
// would set paren to true letting
// it know that there is a closing
// paren to look for
else if (token.at(0) == '(') {
while (token.at(0) == '(') {
paren = true;
tasks.push("(");
token.erase(0, 1);
// tasks.push(token);
if (cmd.empty() && !token.empty() && token.at(0) != '(') {
if (token.at(token.size()-1) == ';') {
token.erase(token.size()-1);
tasks.push(token);
tasks.push(";");
}
else {
cmd = token;
}
}
else if (!cmd.empty()) {
cmd += " " + token;
}
}
// end = false;
end = true;
con = false;
}
// would check to see if paren is true
// and would see is the last char in
// token is ) then would erase ) from token
// push the token in push the
// ) in and make paren false again
// so that it know the braket is closed
else if (paren == true && token.at(token.size() - 1) == ')') {
int count = 0;
paren = false;
while (token.at(token.size() - 1) == ')') {
token.erase(token.size()-1);
++count;
if (cmd.empty() && !token.empty() && token.at(0) != ')') {
// cout << "1: " << token << endl;
// tasks.push(token);
cmd = token;
}
else if (!cmd.empty() && token.at(token.size()-1) != ')') {
// tasks.push(cmd + " " + token);
// cmd.clear();
cmd += " " + token;
}
// tasks.push(token);
// tasks.push(")");
}
// tasks.push(cmd);
semicolon(tasks, cmd);
cmd.clear();
// paren = false;
while (count != 0) {
tasks.push(")");
count -= 1;
}
end = false;
con = false;
}
// else if not a connector
else { //if (!tested) {
// check if end of token has semicolon
// remove the extra spaces
// cout << "token: " << token << token.size() << endl;
if (token.size() != 0 && token.at(token.size() - 1) == ';') {
token.erase(token.size()-1);
if (cmd.empty()) {
tasks.push(token);
}
else {
tasks.push(cmd + " " + token);
cmd.clear();
}
tasks.push(";");
end = false;
}
// check if connectors are hidden in words
// no semicolon detected at end of word
else {
if (cmd.empty()) {
cmd = token;
}
else {
cmd = cmd + " " + token;
}
end = true;
}
con = false;
tested = false;
}
start = false;
}
// if no more connectors were detected
if (end && paren) {
if (cmd.at(cmd.size() - 1) == ')') {
cmd.erase(cmd.size()-1);
semicolon(tasks, cmd);
tasks.push(")");
}
}
else if (end) {
tasks.push(cmd);
}
// check if last thing in task is a && or ||
// if (token == "&&" || token == "||") {
// get user input again
// getInput();
// Parse();
// }
return tasks;
}
// converts a token to char**
char** Input::toChar(string a) {
stringstream stream(a);
string oneWord;
int i = 0;
char** c = new char*[1024];
// one word at a time
while (stream >> oneWord) {
// allocating memory
char* ptr = new char[oneWord.size() + 1];
// copies string (converted to c-string) to ptr)
memcpy(ptr, oneWord.c_str(), oneWord.size() + 1);
c[i] = ptr;
++i;
}
// null terminates the char**
c[i] = '\0';
return c;
}
<|endoftext|> |
<commit_before>/*
* Level.cpp
*
* Created on: 24.01.2015
* Author: sartz
*/
#include "Level.hpp"
#include "Tile.hpp"
#include "global.hpp"
#include "GUI.hpp"
#include <math.h>
#include "Player.hpp"
#include "Menu.hpp"
#include "Items/KeyItem.hpp"
#include "TextFileParser.hpp"
Level::Level(unsigned int number):
Scene(gb::screenWidth, gb::screenHeight)
{
gameBoard.resize(gb::sizeX * gb::sizeY * gb::largeTileSizeX * gb::largeTileSizeY);
textBox = new TextBox();
leaved = false;
highscore = 0;
fooexit = false;
gb::showOutline = true;
// load and set timebar
gui = new GUI();
gui->setTimeout(20);
// load image bitmapt file
sf::Image levelImg;
// try to load the file
std::string fileName = std::string(PATH) + "levels/level" + std::to_string(number);
if (!levelImg.loadFromFile(fileName+".png")) {
gb::inMenu = true;
return;
}
// create a tileset
std::map<sf::Uint32, bool> walkableTileState;
walkableTileState[0x000100ff] = false; // wall
walkableTileState[0x5f5f5fff] = true; // wet stone
walkableTileState[0x9b6d27ff] = true; // dirt
walkableTileState[0x969896ff] = true; // stone
walkableTileState[0x11941bff] = true; // grass
walkableTileState[0x003E04ff] = false; // trees
walkableTileState[0x0000abff] = false; // water
std::map<sf::Uint32, unsigned int> colorToInt;
colorToInt[0x000100ff] = 6; // wall
colorToInt[0x5f5f5fff] = 4; // wet stone
colorToInt[0x9b6d27ff] = 3; // dirt
colorToInt[0x969896ff] = 2; // stone
colorToInt[0x11941bff] = 1; // grass
colorToInt[0x003E04ff] = 5; // trees
colorToInt[0x0000abff] = 0; // water
const sf::Vector2u gridSize(gb::sizeX * gb::largeTileSizeX, gb::sizeY * gb::largeTileSizeY);
// TODO determine the following two variables in another way
const sf::Vector2u tileSize(32, 32);
const sf::Vector2f scale(0.5f, 0.5f);
std::vector<unsigned int> mapping;
for (int x = 0; x < gridSize.y; ++x)
{
for (int y = 0; y < gridSize.x; ++y)
{
sf::Uint32 colorKey = createColorKey(levelImg.getPixel(y, x));
mapping.push_back(colorToInt[colorKey]);
}
}
const sf::Texture& baseTileSet = gb::textureManager.getTexture(std::string(PATH) + "img/tileset.png", false);
sf::Vector2f offset(-6, -6);
const sf::Texture& tileSet = gb::textureManager.getTileSet(baseTileSet, mapping, tileSize, gridSize, offset);
// create sprites for each tile
for (int x = 0; x < gridSize.x; ++x)
{
for (int y = 0; y < gridSize.y; ++y)
{
// create tile sprite
sf::Sprite* sprite = new sf::Sprite();
sprite->setTexture(tileSet);
sprite->setTextureRect(sf::IntRect(x * tileSize.x, y * tileSize.y, tileSize.x, tileSize.y));
sprite->setScale(scale);
sprite->setPosition(x * tileSize.x * scale.x, y * tileSize.y * scale.y);
// create the tile and add it to the scene
Tile* tmpTile = new Tile();
sf::Uint32 colorKey = createColorKey(levelImg.getPixel(x, y));
tmpTile->walkable = walkableTileState[colorKey];
tmpTile->mySprite = sprite;
gameBoard[x + y * gridSize.x] = tmpTile;
}
}
player = new Player();
sf::Sprite *playerSprite = new sf::Sprite();
sf::Sprite *doggieSprite = new sf::Sprite();
playerSprite->setTexture(gb::textureManager.getTexture(std::string(PATH) + "img/player.png", false));
playerSprite->setPosition(90,90);
doggieSprite->setTexture(gb::textureManager.getTexture(std::string(PATH) + "img/player.png", false));
doggieSprite->setPosition(90,90);
player->mySprite = playerSprite;
player->doggieSprite = doggieSprite;
// read text file
TextFileParser::loadTextFile(this, fileName + ".txt");
textBox->triggerText("start");
}
GameObject* Level::getTile(int x, int y)
{
if (x + y*gb::sizeX < (int)gameBoard.size())
{
return gameBoard[x + y * gb::sizeX * gb::largeTileSizeX];
}
return 0;
}
const std::vector<GameObject*> &Level::getGameBoard() const
{
return gameBoard;
}
void Level::switchLargeTile(int x1, int y1, int x2, int y2)
{
int startX1 = x1*gb::largeTileSizeX;
int startY1 = y1*gb::largeTileSizeY;
int startX2 = x2*gb::largeTileSizeX;
int startY2 = y2*gb::largeTileSizeY;
sf::Vector2f orthogonal, dir;
float length;
float momMax = 80.f;
for (int x=0;x<gb::largeTileSizeX;x++)
{
for (int y=0;y<gb::largeTileSizeY;y++)
{
sf::Vector2f tmpPos = getTile(startX1+x, startY1+y)->getPosition();
sf::Vector2f tmpPos2 = getTile(startX2+x, startY2+y)->getPosition();
// getTile(startX2+x, startY2+y)->setPosition(tmpPos.x, tmpPos.y);
// getTile(startX1+x, startY1+y)->setPosition(tmpPos2.x, tmpPos2.y);
TileFlightData tmp;
tmp.startPos = tmpPos;
tmp.currentPos = tmpPos;
tmp.targetPos = tmpPos2;
tmp.tile = getTile(startX1+x, startY1+y);
dir = tmp.targetPos - tmp.currentPos;
dir *= 0.2f;
orthogonal.x = -dir.y;
orthogonal.y = dir.x;
length = sqrt(orthogonal.x*orthogonal.x+orthogonal.y*orthogonal.y);
orthogonal = orthogonal * 1.f/length;
tmp.momentum.x = momMax * (2.f * (1.f*rand() / RAND_MAX) - 1.f);
tmp.momentum.y = momMax * (2.f * (1.f*rand() / RAND_MAX) - 1.f);
tmp.scale = 1.f;
tileAnimationPos.push_back(tmp);
tmp.startPos = tmpPos2;
tmp.currentPos = tmpPos2;
tmp.targetPos = tmpPos;
tmp.tile = getTile(startX2+x, startY2+y);
dir = tmp.targetPos -tmp.currentPos;
length = sqrt(dir.x*dir.x+dir.y*dir.y);
dir = dir * 1.f/length;
orthogonal.x = -dir.y;
orthogonal.y = dir.x;
// length = sqrt(orthogonal.x*orthogonal.x+orthogonal.y*orthogonal.y);
// orthogonal = orthogonal * 1.f/length;
tmp.momentum.x = momMax * (2.f * (1.f*rand() / RAND_MAX) - 1.f);
tmp.momentum.y = momMax * (2.f * (1.f*rand() / RAND_MAX) - 1.f);
tmp.scale = 1.f;
// tmp.momentum = orthogonal * 40.f * (2.f * (1.f*rand() / RAND_MAX) - 1.f);
tileAnimationPos.push_back(tmp);
}
}
tileAnimationTime = 1.5f;
}
void Level::updateTileAnimation(sf::Time deltaT)
{
float dt = deltaT.asSeconds() * 1000;
tileAnimationTime -= dt / 1000;
float scaleMax = 1.4;
for(std::vector<TileFlightData>::iterator itIt = tileAnimationPos.begin() ; itIt != tileAnimationPos.end() ; ) {
TileFlightData &tmpObj = (*itIt);
tmpObj.momentum = tmpObj.momentum * 0.95f + (tmpObj.targetPos - tmpObj.currentPos)* 0.02f;
sf::Vector2f dir = tmpObj.momentum;
tmpObj.currentPos += dt*dir * 0.01f;
sf::Vector2f distVec1 = tmpObj.currentPos- tmpObj.startPos;
sf::Vector2f distVec2 = tmpObj.currentPos- tmpObj.targetPos;
sf::Vector2f distTotalVec = tmpObj.startPos- tmpObj.targetPos;
float dist1 = sqrt(distVec1.x*distVec1.x+distVec1.y*distVec1.y);
float dist2 = sqrt(distVec2.x*distVec2.x+distVec2.y*distVec2.y);
float distTotal = sqrt(distTotalVec.x*distTotalVec.x+distTotalVec.y*distTotalVec.y);
tmpObj.scale = (std::min(dist1,dist2)+distTotal) / distTotal;
tmpObj.tile->mySprite->setScale(scaleMax*tmpObj.scale, scaleMax*tmpObj.scale);
tmpObj.tile->setPosition(tmpObj.currentPos.x, tmpObj.currentPos.y);
// delete animation if target is reached
if (dir.x*dir.x+dir.y*dir.y < 10 || tileAnimationTime < 0)
{
tmpObj.tile->setPosition(tmpObj.targetPos.x, tmpObj.targetPos.y);
tmpObj.tile->mySprite->setScale(1, 1);
itIt = tileAnimationPos.erase(itIt);
}
else
{
itIt ++;
}
}
}
void Level::update(sf::Time deltaT, sf::RenderWindow& window)
{
// if (sf::Mouse::isButtonPressed(sf::Mouse::Left))
// {
// sf::Vector2i globalPosition = sf::Mouse::getPosition(gb::window);
//
// sf::Vector2f localPosition;
// localPosition.x = 1.f*globalPosition.x/(gb::pixelSizeX);
// localPosition.y = 1.f*globalPosition.y/(gb::pixelSizeY);
// std::cout<<localPosition.x<<", "<<localPosition.y<<std::endl;
// }
/*for (std::vector<GameObject*>::iterator it = gameBoard.begin();it != gameBoard.end(); it++)
{
(*it)->update(deltaT);
std::cout << (*it) << std::endl;
}*/
if (highscore != 0)
{
highscore->update(deltaT);
return;
}
if (leaved && !textBox->enabled())
{
finishLevel();
}
updateTileAnimation(deltaT);
for(auto& obj: gameBoard) {
obj->update(deltaT);
}
for(auto& obj: items) {
obj->update(deltaT);
}
player->update(deltaT);
if (gui != 0)
{
gui->update(deltaT);
}
sf::Font font;
font.loadFromFile(std::string(PATH) + "fonts/LiberationSerif-Regular.ttf");
sf::Text level;
level.setFont(font);
level.setPosition(gb::gridWidth + 2, gb::gridHeight - 32);
level.setString(std::to_string(gb::sceneManager.getCurrentLevelNumber()+1));
gb::window.draw(level);
textBox->update(deltaT);
if (!fooexit){
for(std::vector<Item*>::iterator itIt = items.begin() ; itIt != items.end() ; ) {
if (player->intersects(**itIt))
{
if ((*itIt)->applyEffect())
{
fooexit = true;
return;
}
if ((*itIt)->collectable)
{
itIt = items.erase(itIt);
}
else
{
itIt ++;
}
}
else
{
itIt ++;
}
}
}
}
void Level::draw(sf::RenderTarget &renderTarget)
{
for(auto& obj: gameBoard) {
obj->draw(renderTarget, &shader);
}
for(auto& obj: items) {
obj->draw(renderTarget, &shader);
}
player->draw(renderTarget, &shader);
}
void Level::finishLevel()
{
highscore = new Highscore(gb::sceneManager.getCurrentLevelNumber()+1);
highscore->save();
highscore->load();
}
bool Level::readyToLeave() const
{
int size = items.size();
int keysInLevel = 0;
for(int i = 0;i < size;i++)
{
if (dynamic_cast<KeyItem*>(items[i]))
{
keysInLevel++;
}
}
return (keysInLevel == 0);
}
void Level::leave()
{
if (!readyToLeave()) return;
leaved = true;
textBox->triggerText("end");
if (!textBox->enabled())
{
finishLevel();
}
}
Scene* Level::processEvent(sf::Event event, sf::RenderWindow& window)
{
// preprocessing key input (to enhance code readability)
sf::Keyboard::Key keyPressed = sf::Keyboard::Unknown;
if (event.type == sf::Event::KeyPressed)
{
keyPressed = event.key.code;
}
// process events
if (keyPressed == sf::Keyboard::Escape)
{
return new Menu(Menu::Command::LEVEL);
}
return this;
}
sf::Uint32 Level::createColorKey(sf::Color color) {
sf::Uint32 colorKey = 0;
colorKey |= color.r << 3*8;
colorKey |= color.g << 2*8;
colorKey |= color.b << 1*8;
colorKey |= color.a << 0*8;
return colorKey;
}
<commit_msg>quick and dirty fix (will be removed by new algorithm)<commit_after>/*
* Level.cpp
*
* Created on: 24.01.2015
* Author: sartz
*/
#include "Level.hpp"
#include "Tile.hpp"
#include "global.hpp"
#include "GUI.hpp"
#include <math.h>
#include "Player.hpp"
#include "Menu.hpp"
#include "Items/KeyItem.hpp"
#include "TextFileParser.hpp"
Level::Level(unsigned int number):
Scene(gb::screenWidth, gb::screenHeight)
{
gameBoard.resize(gb::sizeX * gb::sizeY * gb::largeTileSizeX * gb::largeTileSizeY);
textBox = new TextBox();
leaved = false;
highscore = 0;
fooexit = false;
gb::showOutline = true;
// load and set timebar
gui = new GUI();
gui->setTimeout(20);
// load image bitmapt file
sf::Image levelImg;
// try to load the file
std::string fileName = std::string(PATH) + "levels/level" + std::to_string(number);
if (!levelImg.loadFromFile(fileName+".png")) {
gb::inMenu = true;
return;
}
// create a tileset
std::map<sf::Uint32, bool> walkableTileState;
walkableTileState[0x000100ff] = false; // wall
walkableTileState[0x5f5f5fff] = true; // wet stone
walkableTileState[0x9b6d27ff] = true; // dirt
walkableTileState[0x969896ff] = true; // stone
walkableTileState[0x11941bff] = true; // grass
walkableTileState[0x003E04ff] = false; // trees
walkableTileState[0x0000abff] = false; // water
std::map<sf::Uint32, unsigned int> colorToInt;
colorToInt[0x000100ff] = 6; // wall
colorToInt[0x5f5f5fff] = 4; // wet stone
colorToInt[0x9b6d27ff] = 3; // dirt
colorToInt[0x969896ff] = 2; // stone
colorToInt[0x11941bff] = 1; // grass
colorToInt[0x003E04ff] = 5; // trees
colorToInt[0x0000abff] = 0; // water
const sf::Vector2u gridSize(gb::sizeX * gb::largeTileSizeX, gb::sizeY * gb::largeTileSizeY);
// TODO determine the following two variables in another way
const sf::Vector2u tileSize(32, 32);
const sf::Vector2f scale(0.5f, 0.5f);
std::vector<unsigned int> mapping;
for (int x = 0; x < gridSize.y; ++x)
{
for (int y = 0; y < gridSize.x; ++y)
{
sf::Uint32 colorKey = createColorKey(levelImg.getPixel(y, x));
mapping.push_back(colorToInt[colorKey]);
}
}
const sf::Texture& baseTileSet = gb::textureManager.getTexture(std::string(PATH) + "img/tileset.png", false);
sf::Vector2f offset(-6, -6);
const sf::Texture& tileSet = gb::textureManager.getTileSet(baseTileSet, mapping, tileSize, gridSize, offset);
// create sprites for each tile
for (int x = 0; x < gridSize.x; ++x)
{
for (int y = 0; y < gridSize.y; ++y)
{
// create tile sprite
sf::Sprite* sprite = new sf::Sprite();
sprite->setTexture(tileSet);
sprite->setTextureRect(sf::IntRect(x * tileSize.x, y * tileSize.y, tileSize.x, tileSize.y));
sprite->setScale(scale);
sprite->setPosition(x * tileSize.x * scale.x, y * tileSize.y * scale.y);
// create the tile and add it to the scene
Tile* tmpTile = new Tile();
sf::Uint32 colorKey = createColorKey(levelImg.getPixel(x, y));
tmpTile->walkable = walkableTileState[colorKey];
tmpTile->mySprite = sprite;
gameBoard[x + y * gridSize.x] = tmpTile;
}
}
player = new Player();
sf::Sprite *playerSprite = new sf::Sprite();
sf::Sprite *doggieSprite = new sf::Sprite();
playerSprite->setTexture(gb::textureManager.getTexture(std::string(PATH) + "img/player.png", false));
playerSprite->setPosition(90,90);
doggieSprite->setTexture(gb::textureManager.getTexture(std::string(PATH) + "img/player.png", false));
doggieSprite->setPosition(90,90);
player->mySprite = playerSprite;
player->doggieSprite = doggieSprite;
// read text file
TextFileParser::loadTextFile(this, fileName + ".txt");
textBox->triggerText("start");
}
GameObject* Level::getTile(int x, int y)
{
if (x + y*gb::sizeX < (int)gameBoard.size())
{
return gameBoard[x + y * gb::sizeX * gb::largeTileSizeX];
}
return 0;
}
const std::vector<GameObject*> &Level::getGameBoard() const
{
return gameBoard;
}
void Level::switchLargeTile(int x1, int y1, int x2, int y2)
{
int startX1 = x1*gb::largeTileSizeX;
int startY1 = y1*gb::largeTileSizeY;
int startX2 = x2*gb::largeTileSizeX;
int startY2 = y2*gb::largeTileSizeY;
sf::Vector2f orthogonal, dir;
float length;
float momMax = 80.f;
for (int x=0;x<gb::largeTileSizeX;x++)
{
for (int y=0;y<gb::largeTileSizeY;y++)
{
sf::Vector2f tmpPos = getTile(startX1+x, startY1+y)->getPosition();
sf::Vector2f tmpPos2 = getTile(startX2+x, startY2+y)->getPosition();
// getTile(startX2+x, startY2+y)->setPosition(tmpPos.x, tmpPos.y);
// getTile(startX1+x, startY1+y)->setPosition(tmpPos2.x, tmpPos2.y);
TileFlightData tmp;
tmp.startPos = tmpPos;
tmp.currentPos = tmpPos;
tmp.targetPos = tmpPos2;
tmp.tile = getTile(startX1+x, startY1+y);
dir = tmp.targetPos - tmp.currentPos;
dir *= 0.2f;
orthogonal.x = -dir.y;
orthogonal.y = dir.x;
length = sqrt(orthogonal.x*orthogonal.x+orthogonal.y*orthogonal.y);
orthogonal = orthogonal * 1.f/length;
tmp.momentum.x = momMax * (2.f * (1.f*rand() / RAND_MAX) - 1.f);
tmp.momentum.y = momMax * (2.f * (1.f*rand() / RAND_MAX) - 1.f);
tmp.scale = 0.5f;
tileAnimationPos.push_back(tmp);
tmp.startPos = tmpPos2;
tmp.currentPos = tmpPos2;
tmp.targetPos = tmpPos;
tmp.tile = getTile(startX2+x, startY2+y);
dir = tmp.targetPos -tmp.currentPos;
length = sqrt(dir.x*dir.x+dir.y*dir.y);
dir = dir * 1.f/length;
orthogonal.x = -dir.y;
orthogonal.y = dir.x;
// length = sqrt(orthogonal.x*orthogonal.x+orthogonal.y*orthogonal.y);
// orthogonal = orthogonal * 1.f/length;
tmp.momentum.x = momMax * (2.f * (1.f*rand() / RAND_MAX) - 1.f);
tmp.momentum.y = momMax * (2.f * (1.f*rand() / RAND_MAX) - 1.f);
tmp.scale = 0.5f;
// tmp.momentum = orthogonal * 40.f * (2.f * (1.f*rand() / RAND_MAX) - 1.f);
tileAnimationPos.push_back(tmp);
}
}
tileAnimationTime = 1.5f;
}
void Level::updateTileAnimation(sf::Time deltaT)
{
float dt = deltaT.asSeconds() * 1000;
tileAnimationTime -= dt / 1000;
float scaleMax = 0.7f;
for(std::vector<TileFlightData>::iterator itIt = tileAnimationPos.begin() ; itIt != tileAnimationPos.end() ; ) {
TileFlightData &tmpObj = (*itIt);
tmpObj.momentum = tmpObj.momentum * 0.95f + (tmpObj.targetPos - tmpObj.currentPos)* 0.02f;
sf::Vector2f dir = tmpObj.momentum;
tmpObj.currentPos += dt*dir * 0.01f;
sf::Vector2f distVec1 = tmpObj.currentPos- tmpObj.startPos;
sf::Vector2f distVec2 = tmpObj.currentPos- tmpObj.targetPos;
sf::Vector2f distTotalVec = tmpObj.startPos- tmpObj.targetPos;
float dist1 = sqrt(distVec1.x*distVec1.x+distVec1.y*distVec1.y);
float dist2 = sqrt(distVec2.x*distVec2.x+distVec2.y*distVec2.y);
float distTotal = sqrt(distTotalVec.x*distTotalVec.x+distTotalVec.y*distTotalVec.y);
tmpObj.scale = (std::min(dist1,dist2)+distTotal) / distTotal;
tmpObj.tile->mySprite->setScale(scaleMax*tmpObj.scale, scaleMax*tmpObj.scale);
tmpObj.tile->setPosition(tmpObj.currentPos.x, tmpObj.currentPos.y);
// delete animation if target is reached
if (dir.x*dir.x+dir.y*dir.y < 10 || tileAnimationTime < 0)
{
tmpObj.tile->setPosition(tmpObj.targetPos.x, tmpObj.targetPos.y);
tmpObj.tile->mySprite->setScale(0.5f, 0.5f);
itIt = tileAnimationPos.erase(itIt);
}
else
{
itIt ++;
}
}
}
void Level::update(sf::Time deltaT, sf::RenderWindow& window)
{
// if (sf::Mouse::isButtonPressed(sf::Mouse::Left))
// {
// sf::Vector2i globalPosition = sf::Mouse::getPosition(gb::window);
//
// sf::Vector2f localPosition;
// localPosition.x = 1.f*globalPosition.x/(gb::pixelSizeX);
// localPosition.y = 1.f*globalPosition.y/(gb::pixelSizeY);
// std::cout<<localPosition.x<<", "<<localPosition.y<<std::endl;
// }
/*for (std::vector<GameObject*>::iterator it = gameBoard.begin();it != gameBoard.end(); it++)
{
(*it)->update(deltaT);
std::cout << (*it) << std::endl;
}*/
if (highscore != 0)
{
highscore->update(deltaT);
return;
}
if (leaved && !textBox->enabled())
{
finishLevel();
}
updateTileAnimation(deltaT);
for(auto& obj: gameBoard) {
obj->update(deltaT);
}
for(auto& obj: items) {
obj->update(deltaT);
}
player->update(deltaT);
if (gui != 0)
{
gui->update(deltaT);
}
sf::Font font;
font.loadFromFile(std::string(PATH) + "fonts/LiberationSerif-Regular.ttf");
sf::Text level;
level.setFont(font);
level.setPosition(gb::gridWidth + 2, gb::gridHeight - 32);
level.setString(std::to_string(gb::sceneManager.getCurrentLevelNumber()+1));
gb::window.draw(level);
textBox->update(deltaT);
if (!fooexit){
for(std::vector<Item*>::iterator itIt = items.begin() ; itIt != items.end() ; ) {
if (player->intersects(**itIt))
{
if ((*itIt)->applyEffect())
{
fooexit = true;
return;
}
if ((*itIt)->collectable)
{
itIt = items.erase(itIt);
}
else
{
itIt ++;
}
}
else
{
itIt ++;
}
}
}
}
void Level::draw(sf::RenderTarget &renderTarget)
{
for(auto& obj: gameBoard) {
obj->draw(renderTarget, &shader);
}
for(auto& obj: items) {
obj->draw(renderTarget, &shader);
}
player->draw(renderTarget, &shader);
}
void Level::finishLevel()
{
highscore = new Highscore(gb::sceneManager.getCurrentLevelNumber()+1);
highscore->save();
highscore->load();
}
bool Level::readyToLeave() const
{
int size = items.size();
int keysInLevel = 0;
for(int i = 0;i < size;i++)
{
if (dynamic_cast<KeyItem*>(items[i]))
{
keysInLevel++;
}
}
return (keysInLevel == 0);
}
void Level::leave()
{
if (!readyToLeave()) return;
leaved = true;
textBox->triggerText("end");
if (!textBox->enabled())
{
finishLevel();
}
}
Scene* Level::processEvent(sf::Event event, sf::RenderWindow& window)
{
// preprocessing key input (to enhance code readability)
sf::Keyboard::Key keyPressed = sf::Keyboard::Unknown;
if (event.type == sf::Event::KeyPressed)
{
keyPressed = event.key.code;
}
// process events
if (keyPressed == sf::Keyboard::Escape)
{
return new Menu(Menu::Command::LEVEL);
}
return this;
}
sf::Uint32 Level::createColorKey(sf::Color color) {
sf::Uint32 colorKey = 0;
colorKey |= color.r << 3*8;
colorKey |= color.g << 2*8;
colorKey |= color.b << 1*8;
colorKey |= color.a << 0*8;
return colorKey;
}
<|endoftext|> |
<commit_before>#include "pch.h"
#include "MyPin.h"
#include "AudioRenderer.h"
namespace SaneAudioRenderer
{
MyPin::MyPin(AudioRenderer& renderer, CBaseFilter* pFilter, HRESULT& result)
: CBaseInputPin(L"SaneAudioRenderer::MyPin", pFilter, this, &result, L"Input0")
, m_bufferFilled(TRUE/*manual reset*/)
, m_renderer(renderer)
{
if (FAILED(result))
return;
if (static_cast<HANDLE>(m_bufferFilled) == NULL)
result = E_OUTOFMEMORY;
}
HRESULT MyPin::CheckMediaType(const CMediaType* pmt)
{
CheckPointer(pmt, E_POINTER);
if (pmt->majortype == MEDIATYPE_Audio &&
pmt->formattype == FORMAT_WaveFormatEx)
{
auto pFormat = reinterpret_cast<const WAVEFORMATEX*>(pmt->pbFormat);
if (!pFormat ||
pmt->cbFormat < sizeof(WAVEFORMATEX) ||
pmt->cbFormat != sizeof(WAVEFORMATEX) + pFormat->cbSize)
{
return E_INVALIDARG;
}
try
{
if (m_renderer.CheckFormat(CopyWaveFormat(*pFormat), m_live))
return S_OK;
}
catch (std::bad_alloc&)
{
return E_OUTOFMEMORY;
}
}
return S_FALSE;
}
HRESULT MyPin::SetMediaType(const CMediaType* pmt)
{
assert(CritCheckIn(this));
ReturnIfFailed(CBaseInputPin::SetMediaType(pmt));
auto pFormat = reinterpret_cast<const WAVEFORMATEX*>(pmt->pbFormat);
// No point in doing integrity checks, that was done in CheckMediaType().
assert(pFormat);
assert(pmt->cbFormat == sizeof(WAVEFORMATEX) + pFormat->cbSize);
m_live = CheckLive(m_Connected);
try
{
m_renderer.SetFormat(CopyWaveFormat(*pFormat), m_live);
}
catch (std::bad_alloc&)
{
return E_OUTOFMEMORY;
}
return S_OK;
}
HRESULT MyPin::CheckConnect(IPin* pPin)
{
assert(CritCheckIn(this));
ReturnIfFailed(CBaseInputPin::CheckConnect(pPin));
m_live = CheckLive(pPin);
return S_OK;
}
STDMETHODIMP MyPin::NewSegment(REFERENCE_TIME startTime, REFERENCE_TIME stopTime, double rate)
{
CAutoLock receiveLock(&m_receiveMutex);
CAutoLock objectLock(this);
CBaseInputPin::NewSegment(startTime, stopTime, rate);
m_renderer.NewSegment(rate);
return S_OK;
}
STDMETHODIMP MyPin::Receive(IMediaSample* pSample)
{
CAutoLock receiveLock(&m_receiveMutex);
{
CAutoLock objectLock(this);
if (m_state == State_Stopped)
return VFW_E_WRONG_STATE;
ReturnIfNotEquals(S_OK, CBaseInputPin::Receive(pSample));
if (m_SampleProps.dwSampleFlags & AM_SAMPLE_TYPECHANGED)
{
// TODO: don't recreate the device when possible
m_renderer.Finish(false, &m_bufferFilled);
ReturnIfFailed(SetMediaType(static_cast<CMediaType*>(m_SampleProps.pMediaType)));
}
if (m_eosUp)
return S_FALSE;
}
// Raise Receive() thread priority, once.
if (m_hReceiveThread != GetCurrentThread())
{
m_hReceiveThread = GetCurrentThread();
if (GetThreadPriority(m_hReceiveThread) < THREAD_PRIORITY_ABOVE_NORMAL)
SetThreadPriority(m_hReceiveThread, THREAD_PRIORITY_ABOVE_NORMAL);
}
// Push() returns 'false' in case of interruption.
return m_renderer.Push(pSample, m_SampleProps, &m_bufferFilled) ? S_OK : S_FALSE;
}
STDMETHODIMP MyPin::EndOfStream()
{
CAutoLock receiveLock(&m_receiveMutex);
{
CAutoLock objectLock(this);
if (m_state == State_Stopped)
return VFW_E_WRONG_STATE;
if (m_bFlushing)
return S_FALSE;
m_eosUp = true;
}
// We ask audio renderer to block until all samples are played.
// Finish() returns 'false' in case of interruption.
bool eosDown = m_renderer.Finish(true, &m_bufferFilled);
{
CAutoLock objectLock(this);
m_eosDown = eosDown;
if (m_eosDown)
m_pFilter->NotifyEvent(EC_COMPLETE, S_OK, (LONG_PTR)m_pFilter);
}
return S_OK;
}
STDMETHODIMP MyPin::BeginFlush()
{
// Parent method locks the object before modifying it, all is good.
CBaseInputPin::BeginFlush();
m_renderer.BeginFlush();
// Barrier for any present Receive() and EndOfStream() calls.
// Subsequent ones will be rejected because m_bFlushing == TRUE.
CAutoLock receiveLock(&m_receiveMutex);
m_bufferFilled.Reset();
{
CAutoLock objectLock(this);
m_eosUp = false;
m_eosDown = false;
}
m_hReceiveThread = NULL;
m_renderer.EndFlush();
return S_OK;
}
STDMETHODIMP MyPin::EndFlush()
{
// Parent method locks the object before modifying it, all is good.
CBaseInputPin::EndFlush();
return S_OK;
}
HRESULT MyPin::Active()
{
CAutoLock objectLock(this);
assert(m_state != State_Paused);
m_state = State_Paused;
if (IsConnected())
{
m_renderer.Pause();
}
else
{
m_eosUp = true;
m_eosDown = true;
}
return S_OK;
}
HRESULT MyPin::Run(REFERENCE_TIME startTime)
{
CAutoLock objectLock(this);
assert(m_state == State_Paused);
m_state = State_Running;
if (m_eosDown)
{
m_pFilter->NotifyEvent(EC_COMPLETE, S_OK, (LONG_PTR)m_pFilter);
}
else
{
assert(IsConnected());
m_renderer.Play(startTime);
}
return S_OK;
}
HRESULT MyPin::Inactive()
{
{
CAutoLock objectLock(this);
assert(m_state != State_Stopped);
m_state = State_Stopped;
CBaseInputPin::Inactive();
}
m_renderer.BeginFlush();
// Barrier for any present Receive() and EndOfStream() calls.
// Subsequent ones will be rejected because m_state == State_Stopped.
CAutoLock receiveLock(&m_receiveMutex);
m_bufferFilled.Reset();
{
CAutoLock objectLock(this);
m_eosUp = false;
m_eosDown = false;
}
m_hReceiveThread = NULL;
m_renderer.Stop();
m_renderer.EndFlush();
return S_OK;
}
bool MyPin::StateTransitionFinished(uint32_t timeoutMilliseconds)
{
{
CAutoLock objectLock(this);
if (!IsConnected() || m_state == State_Stopped)
return true;
}
// Don't lock the object, we don't want to block Receive() method.
// There won't be any state transitions during the wait,
// because MyFilter always locks itself before calling this method.
return !!m_bufferFilled.Wait(timeoutMilliseconds);
}
bool MyPin::CheckLive(IPin* pPin)
{
assert(pPin);
bool live = false;
IAMGraphStreamsPtr graphStreams;
IAMPushSourcePtr pushSource;
if (SUCCEEDED(m_pFilter->GetFilterGraph()->QueryInterface(IID_PPV_ARGS(&graphStreams))) &&
SUCCEEDED(graphStreams->FindUpstreamInterface(pPin, IID_PPV_ARGS(&pushSource), AM_INTF_SEARCH_OUTPUT_PIN)))
{
live = true;
ULONG flags;
if (SUCCEEDED(pushSource->GetPushSourceFlags(&flags)))
{
if (flags & AM_PUSHSOURCECAPS_INTERNAL_RM)
DebugOut("MyPin upstream live pin has AM_PUSHSOURCECAPS_INTERNAL_RM flag");
if (flags & AM_PUSHSOURCECAPS_NOT_LIVE)
{
DebugOut("MyPin upstream live pin has AM_PUSHSOURCECAPS_NOT_LIVE flag");
live = false;
}
if (flags & AM_PUSHSOURCECAPS_PRIVATE_CLOCK)
DebugOut("MyPin upstream live pin has AM_PUSHSOURCECAPS_PRIVATE_CLOCK flag");
if (flags & AM_PUSHSOURCEREQS_USE_STREAM_CLOCK)
DebugOut("MyPin upstream live pin has AM_PUSHSOURCEREQS_USE_STREAM_CLOCK flag");
if (!flags)
DebugOut("MyPin upstream live pin has no flags");
}
}
return live;
}
}
<commit_msg>Tweak GetState() behaviour<commit_after>#include "pch.h"
#include "MyPin.h"
#include "AudioRenderer.h"
namespace SaneAudioRenderer
{
MyPin::MyPin(AudioRenderer& renderer, CBaseFilter* pFilter, HRESULT& result)
: CBaseInputPin(L"SaneAudioRenderer::MyPin", pFilter, this, &result, L"Input0")
, m_bufferFilled(TRUE/*manual reset*/)
, m_renderer(renderer)
{
if (FAILED(result))
return;
if (static_cast<HANDLE>(m_bufferFilled) == NULL)
result = E_OUTOFMEMORY;
}
HRESULT MyPin::CheckMediaType(const CMediaType* pmt)
{
CheckPointer(pmt, E_POINTER);
if (pmt->majortype == MEDIATYPE_Audio &&
pmt->formattype == FORMAT_WaveFormatEx)
{
auto pFormat = reinterpret_cast<const WAVEFORMATEX*>(pmt->pbFormat);
if (!pFormat ||
pmt->cbFormat < sizeof(WAVEFORMATEX) ||
pmt->cbFormat != sizeof(WAVEFORMATEX) + pFormat->cbSize)
{
return E_INVALIDARG;
}
try
{
if (m_renderer.CheckFormat(CopyWaveFormat(*pFormat), m_live))
return S_OK;
}
catch (std::bad_alloc&)
{
return E_OUTOFMEMORY;
}
}
return S_FALSE;
}
HRESULT MyPin::SetMediaType(const CMediaType* pmt)
{
assert(CritCheckIn(this));
ReturnIfFailed(CBaseInputPin::SetMediaType(pmt));
auto pFormat = reinterpret_cast<const WAVEFORMATEX*>(pmt->pbFormat);
// No point in doing integrity checks, that was done in CheckMediaType().
assert(pFormat);
assert(pmt->cbFormat == sizeof(WAVEFORMATEX) + pFormat->cbSize);
m_live = CheckLive(m_Connected);
try
{
m_renderer.SetFormat(CopyWaveFormat(*pFormat), m_live);
}
catch (std::bad_alloc&)
{
return E_OUTOFMEMORY;
}
return S_OK;
}
HRESULT MyPin::CheckConnect(IPin* pPin)
{
assert(CritCheckIn(this));
ReturnIfFailed(CBaseInputPin::CheckConnect(pPin));
m_live = CheckLive(pPin);
return S_OK;
}
STDMETHODIMP MyPin::NewSegment(REFERENCE_TIME startTime, REFERENCE_TIME stopTime, double rate)
{
CAutoLock receiveLock(&m_receiveMutex);
CAutoLock objectLock(this);
CBaseInputPin::NewSegment(startTime, stopTime, rate);
m_renderer.NewSegment(rate);
return S_OK;
}
STDMETHODIMP MyPin::Receive(IMediaSample* pSample)
{
CAutoLock receiveLock(&m_receiveMutex);
{
CAutoLock objectLock(this);
if (m_state == State_Stopped)
return VFW_E_WRONG_STATE;
ReturnIfNotEquals(S_OK, CBaseInputPin::Receive(pSample));
if (m_SampleProps.dwSampleFlags & AM_SAMPLE_TYPECHANGED)
{
// TODO: don't recreate the device when possible
m_renderer.Finish(false, &m_bufferFilled);
ReturnIfFailed(SetMediaType(static_cast<CMediaType*>(m_SampleProps.pMediaType)));
}
if (m_eosUp)
return S_FALSE;
}
// Raise Receive() thread priority, once.
if (m_hReceiveThread != GetCurrentThread())
{
m_hReceiveThread = GetCurrentThread();
if (GetThreadPriority(m_hReceiveThread) < THREAD_PRIORITY_ABOVE_NORMAL)
SetThreadPriority(m_hReceiveThread, THREAD_PRIORITY_ABOVE_NORMAL);
}
// Push() returns 'false' in case of interruption.
return m_renderer.Push(pSample, m_SampleProps, &m_bufferFilled) ? S_OK : S_FALSE;
}
STDMETHODIMP MyPin::EndOfStream()
{
CAutoLock receiveLock(&m_receiveMutex);
{
CAutoLock objectLock(this);
if (m_state == State_Stopped)
return VFW_E_WRONG_STATE;
if (m_bFlushing)
return S_FALSE;
m_eosUp = true;
}
// We ask audio renderer to block until all samples are played.
// Finish() returns 'false' in case of interruption.
bool eosDown = m_renderer.Finish(true, &m_bufferFilled);
{
CAutoLock objectLock(this);
m_eosDown = eosDown;
if (m_eosDown)
m_pFilter->NotifyEvent(EC_COMPLETE, S_OK, (LONG_PTR)m_pFilter);
}
return S_OK;
}
STDMETHODIMP MyPin::BeginFlush()
{
// Parent method locks the object before modifying it, all is good.
CBaseInputPin::BeginFlush();
m_renderer.BeginFlush();
// Barrier for any present Receive() and EndOfStream() calls.
// Subsequent ones will be rejected because m_bFlushing == TRUE.
CAutoLock receiveLock(&m_receiveMutex);
m_bufferFilled.Reset();
{
CAutoLock objectLock(this);
m_eosUp = false;
m_eosDown = false;
}
m_hReceiveThread = NULL;
m_renderer.EndFlush();
return S_OK;
}
STDMETHODIMP MyPin::EndFlush()
{
// Parent method locks the object before modifying it, all is good.
CBaseInputPin::EndFlush();
return S_OK;
}
HRESULT MyPin::Active()
{
CAutoLock objectLock(this);
assert(m_state != State_Paused);
m_state = State_Paused;
if (IsConnected())
{
m_renderer.Pause();
}
else
{
m_eosUp = true;
m_eosDown = true;
}
return S_OK;
}
HRESULT MyPin::Run(REFERENCE_TIME startTime)
{
CAutoLock objectLock(this);
assert(m_state == State_Paused);
m_state = State_Running;
if (m_eosDown)
{
m_pFilter->NotifyEvent(EC_COMPLETE, S_OK, (LONG_PTR)m_pFilter);
}
else
{
assert(IsConnected());
m_renderer.Play(startTime);
}
return S_OK;
}
HRESULT MyPin::Inactive()
{
{
CAutoLock objectLock(this);
assert(m_state != State_Stopped);
m_state = State_Stopped;
CBaseInputPin::Inactive();
}
m_renderer.BeginFlush();
// Barrier for any present Receive() and EndOfStream() calls.
// Subsequent ones will be rejected because m_state == State_Stopped.
CAutoLock receiveLock(&m_receiveMutex);
m_bufferFilled.Reset();
{
CAutoLock objectLock(this);
m_eosUp = false;
m_eosDown = false;
}
m_hReceiveThread = NULL;
m_renderer.Stop();
m_renderer.EndFlush();
return S_OK;
}
bool MyPin::StateTransitionFinished(uint32_t timeoutMilliseconds)
{
{
CAutoLock objectLock(this);
if (!IsConnected() || m_state != State_Paused)
return true;
}
// Don't lock the object, we don't want to block Receive() method.
// There won't be any state transitions during the wait,
// because MyFilter always locks itself before calling this method.
return !!m_bufferFilled.Wait(timeoutMilliseconds);
}
bool MyPin::CheckLive(IPin* pPin)
{
assert(pPin);
bool live = false;
IAMGraphStreamsPtr graphStreams;
IAMPushSourcePtr pushSource;
if (SUCCEEDED(m_pFilter->GetFilterGraph()->QueryInterface(IID_PPV_ARGS(&graphStreams))) &&
SUCCEEDED(graphStreams->FindUpstreamInterface(pPin, IID_PPV_ARGS(&pushSource), AM_INTF_SEARCH_OUTPUT_PIN)))
{
live = true;
ULONG flags;
if (SUCCEEDED(pushSource->GetPushSourceFlags(&flags)))
{
if (flags & AM_PUSHSOURCECAPS_INTERNAL_RM)
DebugOut("MyPin upstream live pin has AM_PUSHSOURCECAPS_INTERNAL_RM flag");
if (flags & AM_PUSHSOURCECAPS_NOT_LIVE)
{
DebugOut("MyPin upstream live pin has AM_PUSHSOURCECAPS_NOT_LIVE flag");
live = false;
}
if (flags & AM_PUSHSOURCECAPS_PRIVATE_CLOCK)
DebugOut("MyPin upstream live pin has AM_PUSHSOURCECAPS_PRIVATE_CLOCK flag");
if (flags & AM_PUSHSOURCEREQS_USE_STREAM_CLOCK)
DebugOut("MyPin upstream live pin has AM_PUSHSOURCEREQS_USE_STREAM_CLOCK flag");
if (!flags)
DebugOut("MyPin upstream live pin has no flags");
}
}
return live;
}
}
<|endoftext|> |
<commit_before>#include "Reset.h"
#include "WebPage.h"
#include "NetworkAccessManager.h"
#include "NetworkCookieJar.h"
Reset::Reset(WebPage *page, QObject *parent) : Command(page, parent) {
}
void Reset::start(QStringList &arguments) {
Q_UNUSED(arguments);
page()->triggerAction(QWebPage::Stop);
page()->currentFrame()->setHtml("<html><body></body></html>");
page()->networkAccessManager()->setCookieJar(new NetworkCookieJar());
page()->setCustomNetworkAccessManager();
page()->setUserAgent(NULL);
page()->resetResponseHeaders();
page()->resetConsoleMessages();
resetHistory();
emit finished(new Response(true));
}
void Reset::resetHistory() {
// Clearing the history preserves the current history item, so set it to blank first.
page()->currentFrame()->setUrl(QUrl("about:blank"));
page()->history()->clear();
}
<commit_msg>We don't need to clear the page if we're visiting about:blank<commit_after>#include "Reset.h"
#include "WebPage.h"
#include "NetworkAccessManager.h"
#include "NetworkCookieJar.h"
Reset::Reset(WebPage *page, QObject *parent) : Command(page, parent) {
}
void Reset::start(QStringList &arguments) {
Q_UNUSED(arguments);
page()->triggerAction(QWebPage::Stop);
page()->networkAccessManager()->setCookieJar(new NetworkCookieJar());
page()->setCustomNetworkAccessManager();
page()->setUserAgent(NULL);
page()->resetResponseHeaders();
page()->resetConsoleMessages();
resetHistory();
emit finished(new Response(true));
}
void Reset::resetHistory() {
// Clearing the history preserves the current history item, so set it to blank first.
page()->currentFrame()->setUrl(QUrl("about:blank"));
page()->history()->clear();
}
<|endoftext|> |
<commit_before>#include <iostream>
#include <string>
#include "Stats.h"
std::unique_ptr<Stats> Stats::inst = std::unique_ptr<Stats>(new Stats());
Maybe<Statistic> Stats::getStat(std::string key) {
auto testIter = stats.find(key);
if (testIter != stats.end()) {
return Maybe<Statistic>(testIter->second);
} else {
return Maybe<Statistic>();
}
}
void Stats::setStat(std::string key, Statistic value) {
stats[key] = value;
}
Maybe<int> Stats::getInteger(std::string key) {
Maybe<Statistic> stat = getStat(key);
if (stat && stat().type == Statistic::Type::INT) {
return Maybe<int>(stat().value.i);
} else {
return Maybe<int>();
}
}
Maybe<double> Stats::getDouble(std::string key) {
Maybe<Statistic> stat = getStat(key);
if (stat && stat().type == Statistic::Type::DOUBLE) {
return Maybe<double>(stat().value.d);
} else {
return Maybe<double>();
}
}
Maybe<std::string> Stats::getString(std::string key) {
Maybe<Statistic> stat = getStat(key);
if (stat && stat().type == Statistic::Type::STRING) {
return Maybe<std::string>(stat().value.s);
} else {
return Maybe<std::string>();
}
}
Maybe<bool> Stats::getBool(std::string key) {
Maybe<Statistic> stat = getStat(key);
if (stat && stat().type == Statistic::Type::BOOL) {
return Maybe<bool>(stat().value.b);
} else {
return Maybe<bool>();
}
}
Maybe<time_t> Stats::getTime(std::string key) {
Maybe<Statistic> stat = getStat(key);
if (stat && stat().type == Statistic::Type::TIME) {
return Maybe<time_t>(stat().value.t);
} else {
return Maybe<time_t>();
}
}
void Stats::setInteger(std::string key, int value) {
setStat(key, Statistic(value));
}
void Stats::setDouble(std::string key, double value) {
setStat(key, Statistic(value));
}
void Stats::setString(std::string key, std::string value) {
setStat(key, Statistic(value));
}
void Stats::setBool(std::string key, bool value) {
setStat(key, Statistic(value));
}
void Stats::setTime(std::string key, time_t value) {
setStat(key, Statistic(value));
}
namespace {
void printTime(time_t t, std::ostream& os) {
auto timeinfo = *localtime(&t);
char buf[80];
strftime(buf,80,"%m-%d-%Y %I:%M:%S",&timeinfo);
os << buf;
}
}
std::ostream& operator<<(std::ostream& os, const Stats& obj) {
os << std::endl << "Stats:" << std::endl;
for (auto iter = obj.stats.begin(); iter != obj.stats.end(); iter++) {
os << " " << iter->first << " : ";
switch (iter->second.type) {
case Statistic::Type::INT:
os << iter->second.value.i;
break;
case Statistic::Type::DOUBLE:
os << iter->second.value.d;
break;
case Statistic::Type::STRING:
os << iter->second.value.s;
break;
case Statistic::Type::BOOL:
os << (iter->second.value.b ? "true" : "false");
break;
case Statistic::Type::TIME:
printTime(iter->second.value.t, os);
break;
case Statistic::Type::NONE:
os << "NONE_TYPE";
break;
default:
os << "UNKNOWN_TYPE";
}
os << std::endl;
}
return os;
}
Stats& Stats::getInst() {
return *inst;
}
<commit_msg>Better stats formatting Not that it matters since I'll never print these in release, but it looks nice<commit_after>#include <iostream>
#include <iomanip>
#include <string>
#include "Stats.h"
std::unique_ptr<Stats> Stats::inst = std::unique_ptr<Stats>(new Stats());
Maybe<Statistic> Stats::getStat(std::string key) {
auto testIter = stats.find(key);
if (testIter != stats.end()) {
return Maybe<Statistic>(testIter->second);
} else {
return Maybe<Statistic>();
}
}
void Stats::setStat(std::string key, Statistic value) {
stats[key] = value;
}
Maybe<int> Stats::getInteger(std::string key) {
Maybe<Statistic> stat = getStat(key);
if (stat && stat().type == Statistic::Type::INT) {
return Maybe<int>(stat().value.i);
} else {
return Maybe<int>();
}
}
Maybe<double> Stats::getDouble(std::string key) {
Maybe<Statistic> stat = getStat(key);
if (stat && stat().type == Statistic::Type::DOUBLE) {
return Maybe<double>(stat().value.d);
} else {
return Maybe<double>();
}
}
Maybe<std::string> Stats::getString(std::string key) {
Maybe<Statistic> stat = getStat(key);
if (stat && stat().type == Statistic::Type::STRING) {
return Maybe<std::string>(stat().value.s);
} else {
return Maybe<std::string>();
}
}
Maybe<bool> Stats::getBool(std::string key) {
Maybe<Statistic> stat = getStat(key);
if (stat && stat().type == Statistic::Type::BOOL) {
return Maybe<bool>(stat().value.b);
} else {
return Maybe<bool>();
}
}
Maybe<time_t> Stats::getTime(std::string key) {
Maybe<Statistic> stat = getStat(key);
if (stat && stat().type == Statistic::Type::TIME) {
return Maybe<time_t>(stat().value.t);
} else {
return Maybe<time_t>();
}
}
void Stats::setInteger(std::string key, int value) {
setStat(key, Statistic(value));
}
void Stats::setDouble(std::string key, double value) {
setStat(key, Statistic(value));
}
void Stats::setString(std::string key, std::string value) {
setStat(key, Statistic(value));
}
void Stats::setBool(std::string key, bool value) {
setStat(key, Statistic(value));
}
void Stats::setTime(std::string key, time_t value) {
setStat(key, Statistic(value));
}
namespace {
void printTime(time_t t, std::ostream& os) {
auto timeinfo = *localtime(&t);
char buf[80];
strftime(buf,80,"%m-%d-%Y %I:%M:%S",&timeinfo);
os << buf;
}
}
std::ostream& operator<<(std::ostream& os, const Stats& obj) {
int maxLength = 0;
for (auto iter = obj.stats.begin(); iter != obj.stats.end(); iter++) {
int length = iter->first.length();
if (length > maxLength) maxLength = length;
}
os << std::endl << "Stats:" << std::endl;
for (auto iter = obj.stats.begin(); iter != obj.stats.end(); iter++) {
os << " " << std::setw(maxLength) << iter->first << " : ";
switch (iter->second.type) {
case Statistic::Type::INT:
os << iter->second.value.i;
break;
case Statistic::Type::DOUBLE:
os << iter->second.value.d;
break;
case Statistic::Type::STRING:
os << iter->second.value.s;
break;
case Statistic::Type::BOOL:
os << (iter->second.value.b ? "true" : "false");
break;
case Statistic::Type::TIME:
printTime(iter->second.value.t, os);
break;
case Statistic::Type::NONE:
os << "NONE_TYPE";
break;
default:
os << "UNKNOWN_TYPE";
}
os << std::endl;
}
return os;
}
Stats& Stats::getInst() {
return *inst;
}
<|endoftext|> |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.