text stringlengths 54 60.6k |
|---|
<commit_before><commit_msg>Destroy HidServiceLinux::FileThreadHelper before DeviceManagerLinux.<commit_after><|endoftext|> |
<commit_before>//==============================================================================
// SingleCellSimulation plugin
//==============================================================================
#include "singlecellsimulationplugin.h"
#include "cellmlfilemanager.h"
//==============================================================================
#include <QFileInfo>
#include <QMainWindow>
#include <QPen>
#include <QTime>
#include <QVector>
//==============================================================================
#include "qwt_plot.h"
#include "qwt_plot_grid.h"
#include "qwt_plot_curve.h"
//==============================================================================
#include "llvm/Module.h"
#include "llvm/ExecutionEngine/ExecutionEngine.h"
//==============================================================================
namespace OpenCOR {
namespace SingleCellSimulation {
//==============================================================================
PLUGININFO_FUNC SingleCellSimulationPluginInfo()
{
Descriptions descriptions;
descriptions.insert("en", "A plugin to run single cell simulations");
descriptions.insert("fr", "Une extension pour excuter des simulations unicellulaires");
return PluginInfo(PluginInfo::V001,
PluginInfo::Gui,
PluginInfo::Simulation,
true,
QStringList() << "CoreSimulation" << "CellMLSupport" << "Qwt",
descriptions);
}
//==============================================================================
Q_EXPORT_PLUGIN2(SingleCellSimulation, SingleCellSimulationPlugin)
//==============================================================================
SingleCellSimulationPlugin::SingleCellSimulationPlugin()
{
// Set our settings
mGuiSettings->addView(GuiViewSettings::Simulation, 0);
}
//==============================================================================
void SingleCellSimulationPlugin::initialize()
{
// Create our simulation view widget
mSimulationView = new QwtPlot(mMainWindow);
// Hide our simulation view widget since it may not initially be shown in
// our central widget
mSimulationView->setVisible(false);
// Customise our simulation view widget
mSimulationView->setCanvasBackground(Qt::white);
// Remove the canvas' border as it otherwise looks odd, not to say ugly,
// with one
mSimulationView->setCanvasLineWidth(0);
// Add a grid to our simulation view widget
QwtPlotGrid *grid = new QwtPlotGrid;
grid->setMajPen(QPen(Qt::gray, 0, Qt::DotLine));
grid->attach(mSimulationView);
}
//==============================================================================
void SingleCellSimulationPlugin::finalize()
{
// Delete some internal objects
resetCurves();
}
//==============================================================================
void SingleCellSimulationPlugin::resetCurves()
{
// Remove any existing curve
foreach (QwtPlotCurve *curve, mCurves) {
curve->detach();
delete curve;
}
mCurves.clear();
// Refresh the view
mSimulationView->replot();
}
//==============================================================================
QWidget * SingleCellSimulationPlugin::viewWidget(const QString &pFileName,
const int &)
{
// Check that we are dealing with a CellML file and, if so, return our
// generic simulation view widget
CellMLSupport::CellmlFile *cellmlFile = CellMLSupport::CellmlFileManager::instance()->cellmlFile(pFileName);
if (!cellmlFile)
// We are not dealing with a CellML file, so...
return 0;
//--- TESTING --- BEGIN ---
qDebug("=======================================");
qDebug("%s:", qPrintable(pFileName));
// Check the file's validity
if (cellmlFile->isValid()) {
// The file is valid, but let's see whether warnings were generated
int warningsCount = cellmlFile->issues().count();
if (warningsCount)
qDebug(" - The file was properly loaded:");
else
qDebug(" - The file was properly loaded.");
} else {
qDebug(" - The file was NOT properly loaded:");
}
// Output any warnings/errors that were generated
foreach (const CellMLSupport::CellmlFileIssue &issue, cellmlFile->issues()) {
QString type = QString((issue.type() == CellMLSupport::CellmlFileIssue::Error)?"Error":"Warning");
QString message = issue.formattedMessage();
uint32_t line = issue.line();
uint32_t column = issue.column();
QString importedFile = issue.importedFile();
if (line && column) {
if (importedFile.isEmpty())
qDebug(" [%s at line %s column %s] %s", qPrintable(type),
qPrintable(QString::number(issue.line())),
qPrintable(QString::number(issue.column())),
qPrintable(message));
else
qDebug(" [%s at line %s column %s from imported file %s] %s", qPrintable(type),
qPrintable(QString::number(issue.line())),
qPrintable(QString::number(issue.column())),
qPrintable(importedFile),
qPrintable(message));
} else {
if (importedFile.isEmpty())
qDebug(" [%s] %s", qPrintable(type),
qPrintable(message));
else
qDebug(" [%s from imported file %s] %s", qPrintable(type),
qPrintable(importedFile),
qPrintable(message));
}
}
// Get a runtime for the file
CellMLSupport::CellmlFileRuntime *cellmlFileRuntime = cellmlFile->runtime();
if (cellmlFileRuntime->isValid()) {
qDebug(" - The file's runtime was properly generated.");
qDebug(" [Information] Model type = %s", (cellmlFileRuntime->modelType() == CellMLSupport::CellmlFileRuntime::Ode)?"ODE":"DAE");
} else {
qDebug(" - The file's runtime was NOT properly generated:");
foreach (const CellMLSupport::CellmlFileIssue &issue,
cellmlFileRuntime->issues())
qDebug(" [%s] %s",
(issue.type() == CellMLSupport::CellmlFileIssue::Error)?"Error":"Warning",
qPrintable(issue.formattedMessage()));
}
// Remove any existing curve
resetCurves();
// Compute the model, if supported
enum Model {
Unknown,
VanDerPol1928,
Hodgkin1952,
Noble1962,
Noble1984,
Noble1991,
Noble1998,
Zhang2000,
Mitchell2003
} model;
QString fileBaseName = QFileInfo(pFileName).baseName();
if (!fileBaseName.compare("van_der_pol_model_1928"))
model = VanDerPol1928;
else if ( !fileBaseName.compare("hodgkin_huxley_squid_axon_model_1952")
|| !fileBaseName.compare("hodgkin_huxley_squid_axon_model_1952_modified")
|| !fileBaseName.compare("hodgkin_huxley_squid_axon_model_1952_original"))
model = Hodgkin1952;
else if (!fileBaseName.compare("noble_model_1962"))
model = Noble1962;
else if (!fileBaseName.compare("noble_noble_SAN_model_1984"))
model = Noble1984;
else if (!fileBaseName.compare("noble_model_1991"))
model = Noble1991;
else if (!fileBaseName.compare("noble_model_1998"))
model = Noble1998;
else if ( !fileBaseName.compare("zhang_SAN_model_2000_0D_capable")
|| !fileBaseName.compare("zhang_SAN_model_2000_1D_capable")
|| !fileBaseName.compare("zhang_SAN_model_2000_all")
|| !fileBaseName.compare("zhang_SAN_model_2000_published"))
model = Zhang2000;
else if (!fileBaseName.compare("mitchell_schaeffer_2003"))
model = Mitchell2003;
else
model = Unknown;
if (cellmlFileRuntime->isValid() && (model != Unknown)) {
typedef QVector<double> Doubles;
int statesCount = cellmlFileRuntime->statesCount();
Doubles xData;
Doubles yData[statesCount];
double voi = 0; // ms
double voiStep; // ms
double voiMax; // ms
double constants[cellmlFileRuntime->constantsCount()];
double rates[cellmlFileRuntime->ratesCount()];
double states[statesCount];
double algebraic[cellmlFileRuntime->algebraicCount()];
int voiCount = 0;
int voiOutputCount; // ms
switch (model) {
case Hodgkin1952:
voiStep = 0.01; // ms
voiMax = 50; // ms
voiOutputCount = 10;
break;
case Noble1962:
case Mitchell2003:
voiStep = 0.01; // ms
voiMax = 1000; // ms
voiOutputCount = 100;
break;
case Noble1984:
case Noble1991:
case Noble1998:
case Zhang2000:
voiStep = 0.00001; // s
voiMax = 1; // s
voiOutputCount = 100;
break;
default: // van der Pol 1928
voiStep = 0.01; // s
voiMax = 10; // s
voiOutputCount = 1;
}
CellMLSupport::CellmlFileRuntimeOdeFunctions odeFunctions = cellmlFileRuntime->odeFunctions();
QTime time;
time.start();
// Initialise the constants and compute the rates and variables
odeFunctions.initializeConstants(constants, rates, states);
odeFunctions.computeRates(voi, constants, rates, states, algebraic);
odeFunctions.computeVariables(voi, constants, rates, states, algebraic);
do {
// Output the current data, if needed
if(voiCount % voiOutputCount == 0) {
xData.append(voi);
for (int i = 0; i < statesCount; ++i)
yData[i].append(states[i]);
}
// Compute the rates and variables
odeFunctions.computeRates(voi, constants, rates, states, algebraic);
odeFunctions.computeVariables(voi, constants, rates, states, algebraic);
// Go to the next voiStep and integrate the states
voi = ++voiCount*voiStep;
for (int i = 0; i < statesCount; ++i)
states[i] += voiStep*rates[i];
} while (voi < voiMax);
xData.append(voi);
for (int i = 0; i < statesCount; ++i)
yData[i].append(states[i]);
qDebug(" - Simulation time: %s s", qPrintable(QString::number(0.001*time.elapsed(), 'g', 3)));
// Add some curves to our plotting area
for (int i = 0, iMax = (model == VanDerPol1928)?statesCount:1; i < iMax; ++i) {
QwtPlotCurve *curve = new QwtPlotCurve();
curve->setRenderHint(QwtPlotItem::RenderAntialiased);
curve->setPen(QPen(i%2?Qt::darkBlue:Qt::darkRed));
curve->setSamples(xData, yData[i]);
curve->attach(mSimulationView);
// Keep track of the curve
mCurves.append(curve);
}
// Make sure that the view is up-to-date
mSimulationView->replot();
}
//--- TESTING --- END ---
// The expected file extension, so return our generic simulation view
// widget
return mSimulationView;
}
//==============================================================================
QString SingleCellSimulationPlugin::viewName(const int &pViewIndex)
{
// We have only one view, so return its name otherwise call the GuiInterface
// implementation of viewName
switch (pViewIndex) {
case 0:
return tr("Single Cell");
default:
return GuiInterface::viewName(pViewIndex);
}
}
//==============================================================================
} // namespace SingleCellSimulation
} // namespace OpenCOR
//==============================================================================
// End of file
//==============================================================================
<commit_msg>Minor editing.<commit_after>//==============================================================================
// SingleCellSimulation plugin
//==============================================================================
#include "singlecellsimulationplugin.h"
#include "cellmlfilemanager.h"
//==============================================================================
#include <QFileInfo>
#include <QMainWindow>
#include <QPen>
#include <QTime>
#include <QVector>
//==============================================================================
#include "qwt_plot.h"
#include "qwt_plot_grid.h"
#include "qwt_plot_curve.h"
//==============================================================================
#include "llvm/Module.h"
#include "llvm/ExecutionEngine/ExecutionEngine.h"
//==============================================================================
namespace OpenCOR {
namespace SingleCellSimulation {
//==============================================================================
PLUGININFO_FUNC SingleCellSimulationPluginInfo()
{
Descriptions descriptions;
descriptions.insert("en", "A plugin to run single cell simulations");
descriptions.insert("fr", "Une extension pour excuter des simulations unicellulaires");
return PluginInfo(PluginInfo::V001,
PluginInfo::Gui,
PluginInfo::Simulation,
true,
QStringList() << "CoreSimulation" << "CellMLSupport" << "Qwt",
descriptions);
}
//==============================================================================
Q_EXPORT_PLUGIN2(SingleCellSimulation, SingleCellSimulationPlugin)
//==============================================================================
SingleCellSimulationPlugin::SingleCellSimulationPlugin()
{
// Set our settings
mGuiSettings->addView(GuiViewSettings::Simulation, 0);
}
//==============================================================================
void SingleCellSimulationPlugin::initialize()
{
// Create our simulation view widget
mSimulationView = new QwtPlot(mMainWindow);
// Hide our simulation view widget since it may not initially be shown in
// our central widget
mSimulationView->setVisible(false);
// Customise our simulation view widget
mSimulationView->setCanvasBackground(Qt::white);
// Remove the canvas' border as it otherwise looks odd, not to say ugly,
// with one
mSimulationView->setCanvasLineWidth(0);
// Add a grid to our simulation view widget
QwtPlotGrid *grid = new QwtPlotGrid;
grid->setMajPen(QPen(Qt::gray, 0, Qt::DotLine));
grid->attach(mSimulationView);
}
//==============================================================================
void SingleCellSimulationPlugin::finalize()
{
// Delete some internal objects
resetCurves();
}
//==============================================================================
void SingleCellSimulationPlugin::resetCurves()
{
// Remove any existing curve
foreach (QwtPlotCurve *curve, mCurves) {
curve->detach();
delete curve;
}
mCurves.clear();
// Refresh the view
mSimulationView->replot();
}
//==============================================================================
QWidget * SingleCellSimulationPlugin::viewWidget(const QString &pFileName,
const int &)
{
// Check that we are dealing with a CellML file and, if so, return our
// generic simulation view widget
CellMLSupport::CellmlFile *cellmlFile = CellMLSupport::CellmlFileManager::instance()->cellmlFile(pFileName);
if (!cellmlFile)
// We are not dealing with a CellML file, so...
return 0;
//--- TESTING --- BEGIN ---
qDebug("=======================================");
qDebug("%s:", qPrintable(pFileName));
// Check the file's validity
if (cellmlFile->isValid()) {
// The file is valid, but let's see whether warnings were generated
int warningsCount = cellmlFile->issues().count();
if (warningsCount)
qDebug(" - The file was properly loaded:");
else
qDebug(" - The file was properly loaded.");
} else {
qDebug(" - The file was NOT properly loaded:");
}
// Output any warnings/errors that were generated
foreach (const CellMLSupport::CellmlFileIssue &issue, cellmlFile->issues()) {
QString type = QString((issue.type() == CellMLSupport::CellmlFileIssue::Error)?"Error":"Warning");
QString message = issue.formattedMessage();
uint32_t line = issue.line();
uint32_t column = issue.column();
QString importedFile = issue.importedFile();
if (line && column) {
if (importedFile.isEmpty())
qDebug(" [%s at line %s column %s] %s", qPrintable(type),
qPrintable(QString::number(issue.line())),
qPrintable(QString::number(issue.column())),
qPrintable(message));
else
qDebug(" [%s at line %s column %s from imported file %s] %s", qPrintable(type),
qPrintable(QString::number(issue.line())),
qPrintable(QString::number(issue.column())),
qPrintable(importedFile),
qPrintable(message));
} else {
if (importedFile.isEmpty())
qDebug(" [%s] %s", qPrintable(type),
qPrintable(message));
else
qDebug(" [%s from imported file %s] %s", qPrintable(type),
qPrintable(importedFile),
qPrintable(message));
}
}
// Get a runtime for the file
CellMLSupport::CellmlFileRuntime *cellmlFileRuntime = cellmlFile->runtime();
if (cellmlFileRuntime->isValid()) {
qDebug(" - The file's runtime was properly generated.");
qDebug(" [Information] Model type = %s", (cellmlFileRuntime->modelType() == CellMLSupport::CellmlFileRuntime::Ode)?"ODE":"DAE");
} else {
qDebug(" - The file's runtime was NOT properly generated:");
foreach (const CellMLSupport::CellmlFileIssue &issue,
cellmlFileRuntime->issues())
qDebug(" [%s] %s",
(issue.type() == CellMLSupport::CellmlFileIssue::Error)?"Error":"Warning",
qPrintable(issue.formattedMessage()));
}
// Remove any existing curve
resetCurves();
// Compute the model, if supported
enum Model {
Unknown,
VanDerPol1928,
Hodgkin1952,
Noble1962,
Noble1984,
Noble1991,
Noble1998,
Zhang2000,
Mitchell2003
} model;
QString fileBaseName = QFileInfo(pFileName).baseName();
if (!fileBaseName.compare("van_der_pol_model_1928"))
model = VanDerPol1928;
else if ( !fileBaseName.compare("hodgkin_huxley_squid_axon_model_1952")
|| !fileBaseName.compare("hodgkin_huxley_squid_axon_model_1952_modified")
|| !fileBaseName.compare("hodgkin_huxley_squid_axon_model_1952_original"))
model = Hodgkin1952;
else if (!fileBaseName.compare("noble_model_1962"))
model = Noble1962;
else if (!fileBaseName.compare("noble_noble_SAN_model_1984"))
model = Noble1984;
else if (!fileBaseName.compare("noble_model_1991"))
model = Noble1991;
else if (!fileBaseName.compare("noble_model_1998"))
model = Noble1998;
else if ( !fileBaseName.compare("zhang_SAN_model_2000_0D_capable")
|| !fileBaseName.compare("zhang_SAN_model_2000_1D_capable")
|| !fileBaseName.compare("zhang_SAN_model_2000_all")
|| !fileBaseName.compare("zhang_SAN_model_2000_published"))
model = Zhang2000;
else if (!fileBaseName.compare("mitchell_schaeffer_2003"))
model = Mitchell2003;
else
model = Unknown;
if (cellmlFileRuntime->isValid() && (model != Unknown)) {
typedef QVector<double> Doubles;
int statesCount = cellmlFileRuntime->statesCount();
Doubles xData;
Doubles yData[statesCount];
double voi = 0; // ms
double voiStep; // ms
double voiMax; // ms
double constants[cellmlFileRuntime->constantsCount()];
double rates[cellmlFileRuntime->ratesCount()];
double states[statesCount];
double algebraic[cellmlFileRuntime->algebraicCount()];
int voiCount = 0;
int voiOutputCount; // ms
switch (model) {
case Hodgkin1952:
voiStep = 0.01; // ms
voiMax = 50; // ms
voiOutputCount = 10;
break;
case Noble1962:
case Mitchell2003:
voiStep = 0.01; // ms
voiMax = 1000; // ms
voiOutputCount = 100;
break;
case Noble1984:
case Noble1991:
case Noble1998:
case Zhang2000:
voiStep = 0.00001; // s
voiMax = 1; // s
voiOutputCount = 100;
break;
default: // van der Pol 1928
voiStep = 0.01; // s
voiMax = 10; // s
voiOutputCount = 1;
}
CellMLSupport::CellmlFileRuntimeOdeFunctions odeFunctions = cellmlFileRuntime->odeFunctions();
// Initialise the constants and compute the rates and variables
QTime time;
time.start();
odeFunctions.initializeConstants(constants, rates, states);
odeFunctions.computeRates(voi, constants, rates, states, algebraic);
odeFunctions.computeVariables(voi, constants, rates, states, algebraic);
do {
// Output the current data, if needed
if(voiCount % voiOutputCount == 0) {
xData.append(voi);
for (int i = 0; i < statesCount; ++i)
yData[i].append(states[i]);
}
// Compute the rates and variables
odeFunctions.computeRates(voi, constants, rates, states, algebraic);
odeFunctions.computeVariables(voi, constants, rates, states, algebraic);
// Go to the next voiStep and integrate the states
voi = ++voiCount*voiStep;
for (int i = 0; i < statesCount; ++i)
states[i] += voiStep*rates[i];
} while (voi < voiMax);
xData.append(voi);
for (int i = 0; i < statesCount; ++i)
yData[i].append(states[i]);
qDebug(" - Simulation time: %s s", qPrintable(QString::number(0.001*time.elapsed(), 'g', 3)));
// Add some curves to our plotting area
for (int i = 0, iMax = (model == VanDerPol1928)?statesCount:1; i < iMax; ++i) {
QwtPlotCurve *curve = new QwtPlotCurve();
curve->setRenderHint(QwtPlotItem::RenderAntialiased);
curve->setPen(QPen(i%2?Qt::darkBlue:Qt::darkRed));
curve->setSamples(xData, yData[i]);
curve->attach(mSimulationView);
// Keep track of the curve
mCurves.append(curve);
}
// Make sure that the view is up-to-date
mSimulationView->replot();
}
//--- TESTING --- END ---
// The expected file extension, so return our generic simulation view
// widget
return mSimulationView;
}
//==============================================================================
QString SingleCellSimulationPlugin::viewName(const int &pViewIndex)
{
// We have only one view, so return its name otherwise call the GuiInterface
// implementation of viewName
switch (pViewIndex) {
case 0:
return tr("Single Cell");
default:
return GuiInterface::viewName(pViewIndex);
}
}
//==============================================================================
} // namespace SingleCellSimulation
} // namespace OpenCOR
//==============================================================================
// End of file
//==============================================================================
<|endoftext|> |
<commit_before>#include <GarrysMod/Lua/Interface.h>
#include <GarrysMod/Lua/LuaInterface.h>
#include <SymbolFinder.hpp>
#include <MologieDetours/detours.h>
#include <stdexcept>
#include <string>
#include <stdint.h>
#include <stdio.h>
#include <sha1.h>
#if defined _WIN32
#define snprintf _snprintf
#define FASTCALL __fastcall
#define THISCALL __thiscall
#define SERVER_BINARY "server.dll"
#define ADDORUPDATEFILE_SYM reinterpret_cast<const uint8_t *>( "\x55\x8B\xEC\x83\xEC\x18\x53\x56\x8B\x75\x08\x83\xC6\x04\x83\x7E" )
#define ADDORUPDATEFILE_SYMLEN 16
#elif defined __linux || defined __APPLE__
#define CDECL __attribute__((cdecl))
#if defined __linux
#define SERVER_BINARY "garrysmod/bin/server_srv.so"
#define SYMBOL_PREFIX "@"
#else
#define SERVER_BINARY "garrysmod/bin/server.dylib"
#define SYMBOL_PREFIX "@_"
#endif
#define ADDORUPDATEFILE_SYM reinterpret_cast<const uint8_t *>( SYMBOL_PREFIX "_ZN12GModDataPack15AddOrUpdateFileEP7LuaFileb" )
#define ADDORUPDATEFILE_SYMLEN 0
#endif
GarrysMod::Lua::ILuaInterface *lua = NULL;
class GModDataPack;
struct LuaFile
{
uint32_t skip;
const char *path;
};
#if defined _WIN32
typedef void ( THISCALL *AddOrUpdateFile_t ) ( GModDataPack *self, LuaFile *file, bool force );
#elif defined __linux || defined __APPLE__
typedef void ( CDECL *AddOrUpdateFile_t ) ( GModDataPack *self, LuaFile *file, bool force );
#endif
AddOrUpdateFile_t AddOrUpdateFile = NULL;
MologieDetours::Detour<AddOrUpdateFile_t> *AddOrUpdateFile_d = NULL;
#if defined _WIN32
void FASTCALL AddOrUpdateFile_h( GModDataPack *self, void *, LuaFile *file, bool b )
#elif defined __linux || defined __APPLE__
void CDECL AddOrUpdateFile_h( GModDataPack *self, LuaFile *file, bool b )
#endif
{
lua->PushSpecial( GarrysMod::Lua::SPECIAL_GLOB );
if( lua->IsType( -1, GarrysMod::Lua::Type::TABLE ) )
{
lua->GetField( -1, "hook" );
if( lua->IsType( -1, GarrysMod::Lua::Type::TABLE ) )
{
lua->GetField( -1, "Run" );
if( lua->IsType( -1, GarrysMod::Lua::Type::FUNCTION ) )
{
lua->PushString( "AddOrUpdateCSLuaFile" );
lua->PushString( file->path );
lua->PushBool( b );
if( lua->PCall( 3, 1, 0 ) != 0 )
{
lua->Msg( "[luapack_internal] %s\n", lua->GetString( ) );
lua->Pop( 3 );
return AddOrUpdateFile( self, file, b );
}
if( lua->IsType( -1, GarrysMod::Lua::Type::BOOL ) && lua->GetBool( ) )
{
lua->Pop( 3 );
return;
}
lua->Pop( 1 );
}
else
{
lua->Pop( 1 );
}
}
lua->Pop( 1 );
}
lua->Pop( 1 );
return AddOrUpdateFile( self, file, b );
}
#define HASHER_METATABLE "SHA1"
#define HASHER_TYPE 31
#define THROW_ERROR( error ) ( LUA->ThrowError( error ), 0 )
#define LUA_ERROR( ) THROW_ERROR( LUA->GetString( ) )
#define GET_USERDATA( index ) reinterpret_cast<GarrysMod::Lua::UserData *>( LUA->GetUserdata( index ) )
#define GET_HASHER( index ) reinterpret_cast<sha1_context *>( GET_USERDATA( index )->data )
#define VALIDATE_HASHER( hasher ) if( hasher == 0 ) return THROW_ERROR( HASHER_METATABLE " object is not valid" )
LUA_FUNCTION_STATIC( hasher__new )
{
try
{
sha1_context *context = new sha1_context;
sha1_starts( context );
void *luadata = LUA->NewUserdata( sizeof( GarrysMod::Lua::UserData ) );
GarrysMod::Lua::UserData *userdata = reinterpret_cast<GarrysMod::Lua::UserData *>( luadata );
userdata->data = context;
userdata->type = HASHER_TYPE;
LUA->CreateMetaTableType( HASHER_METATABLE, HASHER_TYPE );
LUA->SetMetaTable( -2 );
return 1;
}
catch( std::exception &e )
{
LUA->PushString( e.what( ) );
}
return LUA_ERROR( );
}
LUA_FUNCTION_STATIC( hasher__gc )
{
LUA->CheckType( 1, HASHER_TYPE );
GarrysMod::Lua::UserData *userdata = GET_USERDATA( 1 );
sha1_context *hasher = reinterpret_cast<sha1_context *>( userdata->data );
VALIDATE_HASHER( hasher );
userdata->data = 0;
delete hasher;
return 0;
}
LUA_FUNCTION_STATIC( hasher_update )
{
LUA->CheckType( 1, HASHER_TYPE );
LUA->CheckType( 2, GarrysMod::Lua::Type::STRING );
sha1_context *hasher = GET_HASHER( 1 );
VALIDATE_HASHER( hasher );
uint32_t len = 0;
const uint8_t *data = reinterpret_cast<const uint8_t *>( LUA->GetString( 2, &len ) );
sha1_update( hasher, data, len );
return 0;
}
LUA_FUNCTION_STATIC( hasher_final )
{
LUA->CheckType( 1, HASHER_TYPE );
sha1_context *hasher = GET_HASHER( 1 );
VALIDATE_HASHER( hasher );
uint8_t digest[20];
sha1_finish( hasher, digest );
LUA->PushString( reinterpret_cast<const char *>( digest ), sizeof( digest ) );
return 1;
}
static void SubstituteChar( std::string &path, char part, char sub )
{
size_t pos = path.find( part );
while( pos != path.npos )
{
path.erase( pos, 1 );
path.insert( pos, 1, sub );
pos = path.find( part, pos + 1 );
}
}
static void RemovePart( std::string &path, const char *part )
{
size_t len = strlen( part ), pos = path.find( part );
while( pos != path.npos )
{
path.erase( pos, len );
pos = path.find( part, pos );
}
}
static bool HasWhitelistedExtension( const std::string &path )
{
size_t extstart = path.find( '.' );
if( extstart != path.npos )
{
size_t lastslash = path.find( '/' );
if( lastslash != path.npos && lastslash > extstart )
return false;
std::string ext = path.substr( extstart + 1 );
return ext == "txt" || ext == "dat" || ext == "lua";
}
return false;
}
static bool Rename( const char *f, const char *t )
{
std::string from = "garrysmod/";
from += f;
if( !HasWhitelistedExtension( from ) )
return false;
std::string to = "garrysmod/";
to += t;
if( !HasWhitelistedExtension( to ) )
return false;
SubstituteChar( from, '\\', '/' );
RemovePart( from, "../" );
RemovePart( from, "./" );
SubstituteChar( to, '\\', '/' );
RemovePart( to, "../" );
RemovePart( to, "./" );
return rename( from.c_str( ), to.c_str( ) ) == 0;
}
LUA_FUNCTION_STATIC( luapack_rename )
{
LUA->CheckType( 1, GarrysMod::Lua::Type::STRING );
LUA->CheckType( 2, GarrysMod::Lua::Type::STRING );
LUA->PushBool( Rename( LUA->GetString( 1 ), LUA->GetString( 2 ) ) );
return 1;
}
GMOD_MODULE_OPEN( )
{
lua = reinterpret_cast<GarrysMod::Lua::ILuaInterface *>( LUA );
try
{
lua->PushSpecial( GarrysMod::Lua::SPECIAL_GLOB );
lua->GetField( -1, "luapack" );
if( !lua->IsType( -1, GarrysMod::Lua::Type::TABLE ) )
throw std::runtime_error( "luapack table not found" );
lua->PushCFunction( luapack_rename );
lua->SetField( -2, "Rename" );
lua->PushCFunction( hasher__new );
lua->SetField( -2, HASHER_METATABLE );
LUA->CreateMetaTableType( HASHER_METATABLE, HASHER_TYPE );
LUA->Push( -1 );
LUA->SetField( -2, "__index" );
LUA->PushCFunction( hasher__gc );
LUA->SetField( -2, "__gc" );
LUA->PushCFunction( hasher_update );
LUA->SetField( -2, "Update" );
LUA->PushCFunction( hasher_final );
LUA->SetField( -2, "Final" );
SymbolFinder symfinder;
AddOrUpdateFile = reinterpret_cast<AddOrUpdateFile_t>( symfinder.ResolveOnBinary( SERVER_BINARY, ADDORUPDATEFILE_SYM, ADDORUPDATEFILE_SYMLEN ) );
if( AddOrUpdateFile == NULL )
throw std::runtime_error( "GModDataPack::AddOrUpdateFile detour failed" );
AddOrUpdateFile_d = new MologieDetours::Detour<AddOrUpdateFile_t>( AddOrUpdateFile, reinterpret_cast<AddOrUpdateFile_t>( AddOrUpdateFile_h ) );
AddOrUpdateFile = AddOrUpdateFile_d->GetOriginalFunction( );
lua->Msg( "[luapack_internal] GModDataPack::AddOrUpdateFile detoured.\n" );
return 0;
}
catch( std::exception &e )
{
LUA->PushString( e.what( ) );
}
return LUA_ERROR( );
}
GMOD_MODULE_CLOSE( )
{
delete AddOrUpdateFile_d;
return 0;
}<commit_msg>Wrong std::string find function used. Replaced with correct one.<commit_after>#include <GarrysMod/Lua/Interface.h>
#include <GarrysMod/Lua/LuaInterface.h>
#include <SymbolFinder.hpp>
#include <MologieDetours/detours.h>
#include <stdexcept>
#include <string>
#include <stdint.h>
#include <stdio.h>
#include <sha1.h>
#if defined _WIN32
#define snprintf _snprintf
#define FASTCALL __fastcall
#define THISCALL __thiscall
#define SERVER_BINARY "server.dll"
#define ADDORUPDATEFILE_SYM reinterpret_cast<const uint8_t *>( "\x55\x8B\xEC\x83\xEC\x18\x53\x56\x8B\x75\x08\x83\xC6\x04\x83\x7E" )
#define ADDORUPDATEFILE_SYMLEN 16
#elif defined __linux || defined __APPLE__
#define CDECL __attribute__((cdecl))
#if defined __linux
#define SERVER_BINARY "garrysmod/bin/server_srv.so"
#define SYMBOL_PREFIX "@"
#else
#define SERVER_BINARY "garrysmod/bin/server.dylib"
#define SYMBOL_PREFIX "@_"
#endif
#define ADDORUPDATEFILE_SYM reinterpret_cast<const uint8_t *>( SYMBOL_PREFIX "_ZN12GModDataPack15AddOrUpdateFileEP7LuaFileb" )
#define ADDORUPDATEFILE_SYMLEN 0
#endif
GarrysMod::Lua::ILuaInterface *lua = NULL;
class GModDataPack;
struct LuaFile
{
uint32_t skip;
const char *path;
};
#if defined _WIN32
typedef void ( THISCALL *AddOrUpdateFile_t ) ( GModDataPack *self, LuaFile *file, bool force );
#elif defined __linux || defined __APPLE__
typedef void ( CDECL *AddOrUpdateFile_t ) ( GModDataPack *self, LuaFile *file, bool force );
#endif
AddOrUpdateFile_t AddOrUpdateFile = NULL;
MologieDetours::Detour<AddOrUpdateFile_t> *AddOrUpdateFile_d = NULL;
#if defined _WIN32
void FASTCALL AddOrUpdateFile_h( GModDataPack *self, void *, LuaFile *file, bool b )
#elif defined __linux || defined __APPLE__
void CDECL AddOrUpdateFile_h( GModDataPack *self, LuaFile *file, bool b )
#endif
{
lua->PushSpecial( GarrysMod::Lua::SPECIAL_GLOB );
if( lua->IsType( -1, GarrysMod::Lua::Type::TABLE ) )
{
lua->GetField( -1, "hook" );
if( lua->IsType( -1, GarrysMod::Lua::Type::TABLE ) )
{
lua->GetField( -1, "Run" );
if( lua->IsType( -1, GarrysMod::Lua::Type::FUNCTION ) )
{
lua->PushString( "AddOrUpdateCSLuaFile" );
lua->PushString( file->path );
lua->PushBool( b );
if( lua->PCall( 3, 1, 0 ) != 0 )
{
lua->Msg( "[luapack_internal] %s\n", lua->GetString( ) );
lua->Pop( 3 );
return AddOrUpdateFile( self, file, b );
}
if( lua->IsType( -1, GarrysMod::Lua::Type::BOOL ) && lua->GetBool( ) )
{
lua->Pop( 3 );
return;
}
lua->Pop( 1 );
}
else
{
lua->Pop( 1 );
}
}
lua->Pop( 1 );
}
lua->Pop( 1 );
return AddOrUpdateFile( self, file, b );
}
#define HASHER_METATABLE "SHA1"
#define HASHER_TYPE 31
#define THROW_ERROR( error ) ( LUA->ThrowError( error ), 0 )
#define LUA_ERROR( ) THROW_ERROR( LUA->GetString( ) )
#define GET_USERDATA( index ) reinterpret_cast<GarrysMod::Lua::UserData *>( LUA->GetUserdata( index ) )
#define GET_HASHER( index ) reinterpret_cast<sha1_context *>( GET_USERDATA( index )->data )
#define VALIDATE_HASHER( hasher ) if( hasher == 0 ) return THROW_ERROR( HASHER_METATABLE " object is not valid" )
LUA_FUNCTION_STATIC( hasher__new )
{
try
{
sha1_context *context = new sha1_context;
sha1_starts( context );
void *luadata = LUA->NewUserdata( sizeof( GarrysMod::Lua::UserData ) );
GarrysMod::Lua::UserData *userdata = reinterpret_cast<GarrysMod::Lua::UserData *>( luadata );
userdata->data = context;
userdata->type = HASHER_TYPE;
LUA->CreateMetaTableType( HASHER_METATABLE, HASHER_TYPE );
LUA->SetMetaTable( -2 );
return 1;
}
catch( std::exception &e )
{
LUA->PushString( e.what( ) );
}
return LUA_ERROR( );
}
LUA_FUNCTION_STATIC( hasher__gc )
{
LUA->CheckType( 1, HASHER_TYPE );
GarrysMod::Lua::UserData *userdata = GET_USERDATA( 1 );
sha1_context *hasher = reinterpret_cast<sha1_context *>( userdata->data );
VALIDATE_HASHER( hasher );
userdata->data = 0;
delete hasher;
return 0;
}
LUA_FUNCTION_STATIC( hasher_update )
{
LUA->CheckType( 1, HASHER_TYPE );
LUA->CheckType( 2, GarrysMod::Lua::Type::STRING );
sha1_context *hasher = GET_HASHER( 1 );
VALIDATE_HASHER( hasher );
uint32_t len = 0;
const uint8_t *data = reinterpret_cast<const uint8_t *>( LUA->GetString( 2, &len ) );
sha1_update( hasher, data, len );
return 0;
}
LUA_FUNCTION_STATIC( hasher_final )
{
LUA->CheckType( 1, HASHER_TYPE );
sha1_context *hasher = GET_HASHER( 1 );
VALIDATE_HASHER( hasher );
uint8_t digest[20];
sha1_finish( hasher, digest );
LUA->PushString( reinterpret_cast<const char *>( digest ), sizeof( digest ) );
return 1;
}
static void SubstituteChar( std::string &path, char part, char sub )
{
size_t pos = path.find( part );
while( pos != path.npos )
{
path.erase( pos, 1 );
path.insert( pos, 1, sub );
pos = path.find( part, pos + 1 );
}
}
static void RemovePart( std::string &path, const char *part )
{
size_t len = strlen( part ), pos = path.find( part );
while( pos != path.npos )
{
path.erase( pos, len );
pos = path.find( part, pos );
}
}
static bool HasWhitelistedExtension( const std::string &path )
{
size_t extstart = path.rfind( '.' );
if( extstart != path.npos )
{
size_t lastslash = path.rfind( '/' );
if( lastslash != path.npos && lastslash > extstart )
return false;
std::string ext = path.substr( extstart + 1 );
return ext == "txt" || ext == "dat" || ext == "lua";
}
return false;
}
static bool Rename( const char *f, const char *t )
{
std::string from = "garrysmod/";
from += f;
if( !HasWhitelistedExtension( from ) )
return false;
std::string to = "garrysmod/";
to += t;
if( !HasWhitelistedExtension( to ) )
return false;
SubstituteChar( from, '\\', '/' );
RemovePart( from, "../" );
RemovePart( from, "./" );
SubstituteChar( to, '\\', '/' );
RemovePart( to, "../" );
RemovePart( to, "./" );
return rename( from.c_str( ), to.c_str( ) ) == 0;
}
LUA_FUNCTION_STATIC( luapack_rename )
{
LUA->CheckType( 1, GarrysMod::Lua::Type::STRING );
LUA->CheckType( 2, GarrysMod::Lua::Type::STRING );
LUA->PushBool( Rename( LUA->GetString( 1 ), LUA->GetString( 2 ) ) );
return 1;
}
GMOD_MODULE_OPEN( )
{
lua = reinterpret_cast<GarrysMod::Lua::ILuaInterface *>( LUA );
try
{
lua->PushSpecial( GarrysMod::Lua::SPECIAL_GLOB );
lua->GetField( -1, "luapack" );
if( !lua->IsType( -1, GarrysMod::Lua::Type::TABLE ) )
throw std::runtime_error( "luapack table not found" );
lua->PushCFunction( luapack_rename );
lua->SetField( -2, "Rename" );
lua->PushCFunction( hasher__new );
lua->SetField( -2, HASHER_METATABLE );
LUA->CreateMetaTableType( HASHER_METATABLE, HASHER_TYPE );
LUA->Push( -1 );
LUA->SetField( -2, "__index" );
LUA->PushCFunction( hasher__gc );
LUA->SetField( -2, "__gc" );
LUA->PushCFunction( hasher_update );
LUA->SetField( -2, "Update" );
LUA->PushCFunction( hasher_final );
LUA->SetField( -2, "Final" );
SymbolFinder symfinder;
AddOrUpdateFile = reinterpret_cast<AddOrUpdateFile_t>( symfinder.ResolveOnBinary( SERVER_BINARY, ADDORUPDATEFILE_SYM, ADDORUPDATEFILE_SYMLEN ) );
if( AddOrUpdateFile == NULL )
throw std::runtime_error( "GModDataPack::AddOrUpdateFile detour failed" );
AddOrUpdateFile_d = new MologieDetours::Detour<AddOrUpdateFile_t>( AddOrUpdateFile, reinterpret_cast<AddOrUpdateFile_t>( AddOrUpdateFile_h ) );
AddOrUpdateFile = AddOrUpdateFile_d->GetOriginalFunction( );
lua->Msg( "[luapack_internal] GModDataPack::AddOrUpdateFile detoured.\n" );
return 0;
}
catch( std::exception &e )
{
LUA->PushString( e.what( ) );
}
return LUA_ERROR( );
}
GMOD_MODULE_CLOSE( )
{
delete AddOrUpdateFile_d;
return 0;
}<|endoftext|> |
<commit_before>#include "verify.hpp"
#include <iostream>
#include "sta_util.hpp"
#include "util.hpp"
#define RELATIVE_EPSILON 1.e-5
#define ABSOLUTE_EPSILON 1.e-13
using std::cout;
using std::endl;
using tatum::NodeId;
using tatum::DomainId;
using tatum::LevelId;
using tatum::TimingGraph;
using tatum::NodeType;
bool verify_arr_tag(float arr_time, float vpr_arr_time, NodeId node_id, DomainId domain, const std::set<NodeId>& clock_gen_fanout_nodes, std::streamsize num_width);
bool verify_req_tag(float req_time, float vpr_req_time, NodeId node_id, DomainId domain, const std::set<NodeId>& const_gen_fanout_nodes, std::streamsize num_width);
int verify_analyzer(const TimingGraph& tg, const tatum::SetupTimingAnalyzer& analyzer, const VprArrReqTimes& expected_arr_req_times, const std::set<NodeId>& const_gen_fanout_nodes, const std::set<NodeId>& clock_gen_fanout_nodes) {
//expected_arr_req_times.print();
//std::cout << "Verifying Calculated Timing Against VPR" << std::endl;
std::ios_base::fmtflags saved_flags = std::cout.flags();
std::streamsize prec = std::cout.precision();
std::streamsize width = std::cout.width();
std::streamsize num_width = 10;
std::cout.precision(3);
std::cout << std::scientific;
std::cout << std::setw(10);
int arr_reqs_verified = 0;
bool error = false;
/*
* Check from VPR to Tatum results
*/
for(const DomainId domain : expected_arr_req_times.clocks()) {
int arrival_nodes_checked = 0; //Count number of nodes checked
int required_nodes_checked = 0; //Count number of nodes checked
//Arrival check by level
for(const LevelId ilevel : tg.levels()){
//std::cout << "LEVEL " << ilevel << std::endl;
for(const NodeId node_id : tg.level_nodes(ilevel)) {
//std::cout << "Verifying node: " << node_id << " Launch: " << src_domain << " Capture: " << sink_domain << std::endl;
const auto& node_data_tags = analyzer.get_setup_data_tags(node_id);
float vpr_arr_time = expected_arr_req_times.get_arr_time(domain, node_id);
//Check arrival
auto data_tag_iter = node_data_tags.find_tag_by_clock_domain(domain);
if(data_tag_iter == node_data_tags.end()) {
//Did not find a matching data tag
//See if there is an associated clock tag.
//Note that VPR doesn't handle seperate clock tags, but we place
//clock arrivals on FF_SINK and FF_SOURCE nodes from the clock network,
//so even if such a clock tag exists we don't want to compare it to VPR
if(tg.node_type(node_id) != NodeType::FF_SINK && tg.node_type(node_id) != NodeType::FF_SOURCE) {
const auto& node_clock_tags = analyzer.get_setup_clock_tags(node_id);
auto clock_tag_iter = node_clock_tags.find_tag_by_clock_domain(domain);
if(clock_tag_iter != node_clock_tags.end()) {
error |= verify_arr_tag(clock_tag_iter->arr_time().value(), vpr_arr_time, node_id, domain, clock_gen_fanout_nodes, num_width);
} else if(!isnan(vpr_arr_time)) {
error = true;
std::cout << "Node: " << node_id << " Clk: " << domain << std::endl;
std::cout << "\tERROR Found no arrival-time tag, but VPR arrival time was ";
std::cout << std::setw(num_width) << vpr_arr_time << " (expected NAN)" << std::endl;
} else {
TATUM_ASSERT(isnan(vpr_arr_time));
}
}
} else {
error |= verify_arr_tag(data_tag_iter->arr_time().value(), vpr_arr_time, node_id, domain, clock_gen_fanout_nodes, num_width);
}
arr_reqs_verified ++;
arrival_nodes_checked++;
}
}
//Since we walk our version of the graph make sure we see the same number of nodes as VPR
TATUM_ASSERT(arrival_nodes_checked == (int) expected_arr_req_times.get_num_nodes());
//Required check by level (in reverse)
for(const LevelId level_id : tg.levels()) {
for(const NodeId node_id : tg.level_nodes(level_id)) {
const auto& node_data_tags = analyzer.get_setup_data_tags(node_id);
float vpr_req_time = expected_arr_req_times.get_req_time(domain, node_id);
//Check Required time
auto data_tag_iter = node_data_tags.find_tag_by_clock_domain(domain);
if(data_tag_iter == node_data_tags.end()) {
//See if there is an associated clock tag.
//Note that VPR doesn't handle seperate clock tags, but we place
//clock arrivals on FF_SINK and FF_SOURCE nodes from the clock network,
//so even if such a clock tag exists we don't want to compare it to VPR
if(tg.node_type(node_id) != NodeType::FF_SINK && tg.node_type(node_id) != NodeType::FF_SOURCE) {
const auto& node_clock_tags = analyzer.get_setup_clock_tags(node_id);
auto clock_tag_iter = node_clock_tags.find_tag_by_clock_domain(domain);
if(clock_tag_iter != node_clock_tags.end()) {
error |= verify_req_tag(clock_tag_iter->req_time().value(), vpr_req_time, node_id, domain, const_gen_fanout_nodes, num_width);
} else if(!isnan(vpr_req_time)) {
error = true;
std::cout << "Node: " << node_id << " Clk: " << domain << std::endl;
std::cout << "\tERROR Found no required-time tag, but VPR required time was " << std::setw(num_width);
std::cout << vpr_req_time << " (expected NAN)" << std::endl;
}
}
} else {
error |= verify_req_tag(data_tag_iter->req_time().value(), vpr_req_time, node_id, domain, const_gen_fanout_nodes, num_width);
}
arr_reqs_verified++;
required_nodes_checked++;
}
}
TATUM_ASSERT(required_nodes_checked == (int) expected_arr_req_times.get_num_nodes());
}
/*
* Check from Tatum to VPR
*/
//Check by level
//#ifdef CHECK_TATUM_TO_VPR_DIFFERENCES
#if 0
for(int ilevel = 0; ilevel <tg.num_levels(); ilevel++) {
//std::cout << "LEVEL " << ilevel << std::endl;
for(NodeId node_id : tg.level(ilevel)) {
for(const TimingTag& data_tag : analyzer.data_tags(node_id)) {
//Arrival
float arr_time = data_tag.arr_time().value();
float vpr_arr_time = expected_arr_req_times.get_arr_time(data_tag.clock_domain(), node_id);
verify_arr_tag(arr_time, vpr_arr_time, node_id, data_tag.clock_domain(), clock_gen_fanout_nodes, num_width);
//Required
float req_time = data_tag.req_time().value();
float vpr_req_time = expected_arr_req_times.get_req_time(data_tag.clock_domain(), node_id);
verify_req_tag(req_time, vpr_req_time, node_id, data_tag.clock_domain(), const_gen_fanout_nodes, num_width);
}
}
}
#endif
if(error) {
std::cout << "Timing verification FAILED!" << std::endl;
exit(1);
} else {
//std::cout << "Timing verification SUCCEEDED" << std::endl;
}
std::cout.flags(saved_flags);
std::cout.precision(prec);
std::cout.width(width);
return arr_reqs_verified;
}
bool verify_arr_tag(float arr_time, float vpr_arr_time, NodeId node_id, DomainId domain, const std::set<NodeId>& clock_gen_fanout_nodes, std::streamsize num_width) {
bool error = false;
float arr_abs_err = fabs(arr_time - vpr_arr_time);
float arr_rel_err = relative_error(arr_time, vpr_arr_time);
if(isnan(arr_time) && isnan(arr_time) != isnan(vpr_arr_time)) {
error = true;
cout << "Node: " << node_id << " Clk: " << domain;
cout << " Calc_Arr: " << std::setw(num_width) << arr_time;
cout << " VPR_Arr: " << std::setw(num_width) << vpr_arr_time << endl;
cout << "\tERROR Calculated arrival time was nan and didn't match VPR." << endl;
} else if (!isnan(arr_time) && isnan(vpr_arr_time)) {
if(clock_gen_fanout_nodes.count(node_id)) {
//Pass, clock gen fanout can be NAN in VPR but have a value here,
//since (unlike VPR) we explictly track clock arrivals as tags
} else {
error = true;
cout << "Node: " << node_id << " Clk: " << domain;
cout << " Calc_Arr: " << std::setw(num_width) << arr_time;
cout << " VPR_Arr: " << std::setw(num_width) << vpr_arr_time << endl;
cout << "\tERROR Calculated arrival time was not nan but VPR expected nan." << endl;
}
} else if (isnan(arr_time) && isnan(vpr_arr_time)) {
//They agree, pass
} else if(arr_rel_err > RELATIVE_EPSILON && arr_abs_err > ABSOLUTE_EPSILON) {
error = true;
cout << "Node: " << node_id << " Clk: " << domain;
cout << " Calc_Arr: " << std::setw(num_width) << arr_time;
cout << " VPR_Arr: " << std::setw(num_width) << vpr_arr_time << endl;
cout << "\tERROR arrival time abs, rel errs: " << std::setw(num_width) << arr_abs_err;
cout << ", " << std::setw(num_width) << arr_rel_err << endl;
} else {
TATUM_ASSERT(!isnan(arr_rel_err) && !isnan(arr_abs_err));
TATUM_ASSERT(arr_rel_err < RELATIVE_EPSILON || arr_abs_err < ABSOLUTE_EPSILON);
}
return error;
}
bool verify_req_tag(float req_time, float vpr_req_time, NodeId node_id, DomainId domain, const std::set<NodeId>& const_gen_fanout_nodes, std::streamsize num_width) {
bool error = false;
float req_abs_err = fabs(req_time - vpr_req_time);
float req_rel_err = relative_error(req_time, vpr_req_time);
if(isnan(req_time) && isnan(req_time) != isnan(vpr_req_time)) {
error = true;
cout << "Node: " << node_id << " Clk: " << domain;
cout << " Calc_Req: " << std::setw(num_width) << req_time;
cout << " VPR_Req: " << std::setw(num_width) << vpr_req_time << endl;
cout << "\tERROR Calculated required time was nan and didn't match VPR." << endl;
} else if (!isnan(req_time) && isnan(vpr_req_time)) {
if (const_gen_fanout_nodes.count(node_id)) {
//VPR doesn't propagate required times along paths sourced by constant generators
//but we do, so ignore such errors
#if 0
cout << "Node: " << node_id << " Clk: " << domain;
cout << " Calc_Req: " << std::setw(num_width) << req_time;
cout << " VPR_Req: " << std::setw(num_width) << vpr_req_time << endl;
cout << "\tOK since " << node_id << " in fanout of Constant Generator" << endl;
#endif
} else {
error = true;
cout << "Node: " << node_id << " Clk: " << domain;
cout << " Calc_Req: " << std::setw(num_width) << req_time;
cout << " VPR_Req: " << std::setw(num_width) << vpr_req_time << endl;
cout << "\tERROR Calculated required time was not nan but VPR expected nan." << endl;
}
} else if (isnan(req_time) && isnan(vpr_req_time)) {
//They agree, pass
} else if(req_rel_err > RELATIVE_EPSILON && req_abs_err > ABSOLUTE_EPSILON) {
error = true;
cout << "Node: " << node_id << " Clk: " << domain;
cout << " Calc_Req: " << std::setw(num_width) << req_time;
cout << " VPR_Req: " << std::setw(num_width) << vpr_req_time << endl;
cout << "\tERROR required time abs, rel errs: " << std::setw(num_width) << req_abs_err;
cout << ", " << std::setw(num_width) << req_rel_err << endl;
} else {
TATUM_ASSERT(!isnan(req_rel_err) && !isnan(req_abs_err));
TATUM_ASSERT(req_rel_err < RELATIVE_EPSILON || req_abs_err < ABSOLUTE_EPSILON);
}
return error;
}
<commit_msg>Relax verification to allow for Tatum to report a time when VPR reports NAN<commit_after>#include "verify.hpp"
#include <iostream>
#include "sta_util.hpp"
#include "util.hpp"
#define RELATIVE_EPSILON 1.e-5
#define ABSOLUTE_EPSILON 1.e-13
using std::cout;
using std::endl;
using tatum::NodeId;
using tatum::DomainId;
using tatum::LevelId;
using tatum::TimingGraph;
using tatum::NodeType;
bool verify_arr_tag(float arr_time, float vpr_arr_time, NodeId node_id, DomainId domain, const std::set<NodeId>& clock_gen_fanout_nodes, std::streamsize num_width);
bool verify_req_tag(float req_time, float vpr_req_time, NodeId node_id, DomainId domain, const std::set<NodeId>& const_gen_fanout_nodes, std::streamsize num_width);
int verify_analyzer(const TimingGraph& tg, const tatum::SetupTimingAnalyzer& analyzer, const VprArrReqTimes& expected_arr_req_times, const std::set<NodeId>& const_gen_fanout_nodes, const std::set<NodeId>& clock_gen_fanout_nodes) {
//expected_arr_req_times.print();
//std::cout << "Verifying Calculated Timing Against VPR" << std::endl;
std::ios_base::fmtflags saved_flags = std::cout.flags();
std::streamsize prec = std::cout.precision();
std::streamsize width = std::cout.width();
std::streamsize num_width = 10;
std::cout.precision(3);
std::cout << std::scientific;
std::cout << std::setw(10);
int arr_reqs_verified = 0;
bool error = false;
/*
* Check from VPR to Tatum results
*/
for(const DomainId domain : expected_arr_req_times.clocks()) {
int arrival_nodes_checked = 0; //Count number of nodes checked
int required_nodes_checked = 0; //Count number of nodes checked
//Arrival check by level
for(const LevelId ilevel : tg.levels()){
//std::cout << "LEVEL " << ilevel << std::endl;
for(const NodeId node_id : tg.level_nodes(ilevel)) {
//std::cout << "Verifying node: " << node_id << " Launch: " << src_domain << " Capture: " << sink_domain << std::endl;
const auto& node_data_tags = analyzer.get_setup_data_tags(node_id);
float vpr_arr_time = expected_arr_req_times.get_arr_time(domain, node_id);
//Check arrival
auto data_tag_iter = node_data_tags.find_tag_by_clock_domain(domain);
if(data_tag_iter == node_data_tags.end()) {
//Did not find a matching data tag
//See if there is an associated clock tag.
//Note that VPR doesn't handle seperate clock tags, but we place
//clock arrivals on FF_SINK and FF_SOURCE nodes from the clock network,
//so even if such a clock tag exists we don't want to compare it to VPR
if(tg.node_type(node_id) != NodeType::FF_SINK && tg.node_type(node_id) != NodeType::FF_SOURCE) {
const auto& node_clock_tags = analyzer.get_setup_clock_tags(node_id);
auto clock_tag_iter = node_clock_tags.find_tag_by_clock_domain(domain);
if(clock_tag_iter != node_clock_tags.end()) {
error |= verify_arr_tag(clock_tag_iter->arr_time().value(), vpr_arr_time, node_id, domain, clock_gen_fanout_nodes, num_width);
} else if(!isnan(vpr_arr_time)) {
error = true;
std::cout << "Node: " << node_id << " Clk: " << domain << std::endl;
std::cout << "\tERROR Found no arrival-time tag, but VPR arrival time was ";
std::cout << std::setw(num_width) << vpr_arr_time << " (expected NAN)" << std::endl;
} else {
TATUM_ASSERT(isnan(vpr_arr_time));
}
}
} else {
error |= verify_arr_tag(data_tag_iter->arr_time().value(), vpr_arr_time, node_id, domain, clock_gen_fanout_nodes, num_width);
}
arr_reqs_verified ++;
arrival_nodes_checked++;
}
}
//Since we walk our version of the graph make sure we see the same number of nodes as VPR
TATUM_ASSERT(arrival_nodes_checked == (int) expected_arr_req_times.get_num_nodes());
//Required check by level (in reverse)
for(const LevelId level_id : tg.levels()) {
for(const NodeId node_id : tg.level_nodes(level_id)) {
const auto& node_data_tags = analyzer.get_setup_data_tags(node_id);
float vpr_req_time = expected_arr_req_times.get_req_time(domain, node_id);
//Check Required time
auto data_tag_iter = node_data_tags.find_tag_by_clock_domain(domain);
if(data_tag_iter == node_data_tags.end()) {
//See if there is an associated clock tag.
//Note that VPR doesn't handle seperate clock tags, but we place
//clock arrivals on FF_SINK and FF_SOURCE nodes from the clock network,
//so even if such a clock tag exists we don't want to compare it to VPR
if(tg.node_type(node_id) != NodeType::FF_SINK && tg.node_type(node_id) != NodeType::FF_SOURCE) {
const auto& node_clock_tags = analyzer.get_setup_clock_tags(node_id);
auto clock_tag_iter = node_clock_tags.find_tag_by_clock_domain(domain);
if(clock_tag_iter != node_clock_tags.end()) {
error |= verify_req_tag(clock_tag_iter->req_time().value(), vpr_req_time, node_id, domain, const_gen_fanout_nodes, num_width);
} else if(!isnan(vpr_req_time)) {
error = true;
std::cout << "Node: " << node_id << " Clk: " << domain << std::endl;
std::cout << "\tERROR Found no required-time tag, but VPR required time was " << std::setw(num_width);
std::cout << vpr_req_time << " (expected NAN)" << std::endl;
}
}
} else {
error |= verify_req_tag(data_tag_iter->req_time().value(), vpr_req_time, node_id, domain, const_gen_fanout_nodes, num_width);
}
arr_reqs_verified++;
required_nodes_checked++;
}
}
TATUM_ASSERT(required_nodes_checked == (int) expected_arr_req_times.get_num_nodes());
}
/*
* Check from Tatum to VPR
*/
//Check by level
//#ifdef CHECK_TATUM_TO_VPR_DIFFERENCES
#if 0
for(int ilevel = 0; ilevel <tg.num_levels(); ilevel++) {
//std::cout << "LEVEL " << ilevel << std::endl;
for(NodeId node_id : tg.level(ilevel)) {
for(const TimingTag& data_tag : analyzer.data_tags(node_id)) {
//Arrival
float arr_time = data_tag.arr_time().value();
float vpr_arr_time = expected_arr_req_times.get_arr_time(data_tag.clock_domain(), node_id);
verify_arr_tag(arr_time, vpr_arr_time, node_id, data_tag.clock_domain(), clock_gen_fanout_nodes, num_width);
//Required
float req_time = data_tag.req_time().value();
float vpr_req_time = expected_arr_req_times.get_req_time(data_tag.clock_domain(), node_id);
verify_req_tag(req_time, vpr_req_time, node_id, data_tag.clock_domain(), const_gen_fanout_nodes, num_width);
}
}
}
#endif
if(error) {
std::cout << "Timing verification FAILED!" << std::endl;
exit(1);
} else {
//std::cout << "Timing verification SUCCEEDED" << std::endl;
}
std::cout.flags(saved_flags);
std::cout.precision(prec);
std::cout.width(width);
return arr_reqs_verified;
}
bool verify_arr_tag(float arr_time, float vpr_arr_time, NodeId node_id, DomainId domain, const std::set<NodeId>& clock_gen_fanout_nodes, std::streamsize num_width) {
bool error = false;
float arr_abs_err = fabs(arr_time - vpr_arr_time);
float arr_rel_err = relative_error(arr_time, vpr_arr_time);
if(isnan(arr_time) && isnan(arr_time) != isnan(vpr_arr_time)) {
error = true;
cout << "Node: " << node_id << " Clk: " << domain;
cout << " Calc_Arr: " << std::setw(num_width) << arr_time;
cout << " VPR_Arr: " << std::setw(num_width) << vpr_arr_time << endl;
cout << "\tERROR Calculated arrival time was nan and didn't match VPR." << endl;
} else if (!isnan(arr_time) && isnan(vpr_arr_time)) {
if(clock_gen_fanout_nodes.count(node_id)) {
//Pass, clock gen fanout can be NAN in VPR but have a value here,
//since (unlike VPR) we explictly track clock arrivals as tags
} else {
//We allow tatum results to be non-NAN when VPR is NAN
//
//This occurs in some cases (such as applying clock tags to primary outputs)
//which are cuased by the differeing analysis methods
#if 0
error = true;
cout << "Node: " << node_id << " Clk: " << domain;
cout << " Calc_Arr: " << std::setw(num_width) << arr_time;
cout << " VPR_Arr: " << std::setw(num_width) << vpr_arr_time << endl;
cout << "\tERROR Calculated arrival time was not nan but VPR expected nan." << endl;
#endif
}
} else if (isnan(arr_time) && isnan(vpr_arr_time)) {
//They agree, pass
} else if(arr_rel_err > RELATIVE_EPSILON && arr_abs_err > ABSOLUTE_EPSILON) {
error = true;
cout << "Node: " << node_id << " Clk: " << domain;
cout << " Calc_Arr: " << std::setw(num_width) << arr_time;
cout << " VPR_Arr: " << std::setw(num_width) << vpr_arr_time << endl;
cout << "\tERROR arrival time abs, rel errs: " << std::setw(num_width) << arr_abs_err;
cout << ", " << std::setw(num_width) << arr_rel_err << endl;
} else {
TATUM_ASSERT(!isnan(arr_rel_err) && !isnan(arr_abs_err));
TATUM_ASSERT(arr_rel_err < RELATIVE_EPSILON || arr_abs_err < ABSOLUTE_EPSILON);
}
return error;
}
bool verify_req_tag(float req_time, float vpr_req_time, NodeId node_id, DomainId domain, const std::set<NodeId>& const_gen_fanout_nodes, std::streamsize num_width) {
bool error = false;
float req_abs_err = fabs(req_time - vpr_req_time);
float req_rel_err = relative_error(req_time, vpr_req_time);
if(isnan(req_time) && isnan(req_time) != isnan(vpr_req_time)) {
error = true;
cout << "Node: " << node_id << " Clk: " << domain;
cout << " Calc_Req: " << std::setw(num_width) << req_time;
cout << " VPR_Req: " << std::setw(num_width) << vpr_req_time << endl;
cout << "\tERROR Calculated required time was nan and didn't match VPR." << endl;
} else if (!isnan(req_time) && isnan(vpr_req_time)) {
if (const_gen_fanout_nodes.count(node_id)) {
//VPR doesn't propagate required times along paths sourced by constant generators
//but we do, so ignore such errors
#if 0
cout << "Node: " << node_id << " Clk: " << domain;
cout << " Calc_Req: " << std::setw(num_width) << req_time;
cout << " VPR_Req: " << std::setw(num_width) << vpr_req_time << endl;
cout << "\tOK since " << node_id << " in fanout of Constant Generator" << endl;
#endif
} else {
error = true;
cout << "Node: " << node_id << " Clk: " << domain;
cout << " Calc_Req: " << std::setw(num_width) << req_time;
cout << " VPR_Req: " << std::setw(num_width) << vpr_req_time << endl;
cout << "\tERROR Calculated required time was not nan but VPR expected nan." << endl;
}
} else if (isnan(req_time) && isnan(vpr_req_time)) {
//They agree, pass
} else if(req_rel_err > RELATIVE_EPSILON && req_abs_err > ABSOLUTE_EPSILON) {
error = true;
cout << "Node: " << node_id << " Clk: " << domain;
cout << " Calc_Req: " << std::setw(num_width) << req_time;
cout << " VPR_Req: " << std::setw(num_width) << vpr_req_time << endl;
cout << "\tERROR required time abs, rel errs: " << std::setw(num_width) << req_abs_err;
cout << ", " << std::setw(num_width) << req_rel_err << endl;
} else {
TATUM_ASSERT(!isnan(req_rel_err) && !isnan(req_abs_err));
TATUM_ASSERT(req_rel_err < RELATIVE_EPSILON || req_abs_err < ABSOLUTE_EPSILON);
}
return error;
}
<|endoftext|> |
<commit_before>#include "commonOptions.h"
#include "Option.h"
namespace commonOptions {
bool& hasError() {
static bool error{false};
return error;
}
void print() {
auto allOptions = getRootSection()->getVariables();
for (auto b : allOptions) {
b->print();
}
}
void printShellCompl() {
auto allOptions = getRootSection()->getVariables();
for (auto b : allOptions) {
b->printShellCompl();
}
}
/**
* This is a very simple command line parser
* It can parse stuff like
* --option
* --option value
* --opiton=value
*
* it will ignore everything else on the command line. This is needed because boost::
* program_options is handling unknown options very badly
*/
bool parse(int argc, char const* const* argv) {
std::map<std::string, std::string> options;
for (int i(1); i<argc; ++i) {
std::string arg = argv[i];
if (0 == arg.compare(0, 2, "--")) {
arg = arg.substr(2); // cut of first two symbols
} else {
arg = "__command__" + arg;
}
std::string key = arg;
std::string value = "true";
size_t equalSignPos = arg.find("=");
if (equalSignPos != std::string::npos) {
key = arg.substr(0, equalSignPos);
value = arg.substr(equalSignPos+1);
} else if (has_key(key) and get_option(key)->isListType()) {
if (i+1 < argc) {
value = argv[++i];
while (i+1 < argc) {
value += std::string(", ") + argv[++i];
}
}
value = "[" + value + "]";
} else if (i+1 < argc && std::string(argv[i+1]).compare(0, 2, "--" ) != 0) {
value = argv[++i];
}
auto description = get_description(key);
description->changeDefaultValue(value, 1);
}
/* if (commands.size() >= 1) {
auto cmdDescription = get_description("__command__" + commands[0]);
cmdDescription->changeDefaultValue("true", 1);
commands.erase(commands.begin());
auto filesDescription = get_description("__files__");
filesDescription->changeDefaultValue(serializer::yaml::writeAsString(commands), 1);
}*/
if (argc == 2 && std::string(argv[1]) == "__completion") {
printShellCompl();
exit(0);
}
return not hasError();
}
void loadFile(std::string const& _file) {
std::map<std::string, std::string> options;
serializer::yaml::read(_file, options);
for (auto o : options) {
auto desc = get_description(o.first);
desc->changeValue(o.second);
desc->defaultValueActive = false;
}
Singleton::getInstance().signal_load();
}
/** if _includingSections is empty, include them all
*/
void saveFile(std::string const& _file, std::vector<std::string> const& _includingSections) {
std::map<std::string, std::string> options;
std::set<Section*> allSections;
std::queue<Section*> sectionsToProcess;
// collecting all sections (to remove duplicates)
for (auto const& sectName : _includingSections) {
sectionsToProcess.push(get_section(sectName));
}
if (_includingSections.empty()) {
sectionsToProcess.push(getRootSection());
}
while (not sectionsToProcess.empty()) {
auto sect = sectionsToProcess.front();
sectionsToProcess.pop();
allSections.insert(sect);
for (auto& child : sect->getChildren()) {
sectionsToProcess.push(&child.second);
}
}
// Serialize all OptionDescriptions (if they don't have default value)
for (auto section : allSections) {
auto fullName = section->fullName();
for (auto const& description : section->getDescriptions()) {
auto name = fullName + description.second->optionName;
if (not description.second->defaultValueActive) {
auto const* d = description.second.get();
options[name] = d->value;
}
}
}
serializer::yaml::write(_file, options);
}
Section* get_section(std::string const& _str) {
auto path = splitPath(_str);
Section* section = getRootSection();
for (auto const& p : path) {
section = section->accessChild(p);
}
return section;
}
Section* getRootSection() {
static Section singleton;
return &singleton;
}
auto getUnmatchedParameters() -> std::vector<std::string> {
std::vector<std::string> missing;
std::set<std::string> available;
auto variables = commonOptions::getRootSection()->getVariables();
for (auto v : variables) {
available.insert(v->getSectionName() + v->getName());
}
auto descriptions = commonOptions::getRootSection()->getAllDescriptions();
for (auto const& d : descriptions) {
if (available.count(d.first) == 0) {
missing.push_back(d.first);
}
}
return missing;
}
}
<commit_msg>more strict on default values<commit_after>#include "commonOptions.h"
#include "Option.h"
namespace commonOptions {
bool& hasError() {
static bool error{false};
return error;
}
void print() {
auto allOptions = getRootSection()->getVariables();
for (auto b : allOptions) {
b->print();
}
}
void printShellCompl() {
auto allOptions = getRootSection()->getVariables();
for (auto b : allOptions) {
b->printShellCompl();
}
}
/**
* This is a very simple command line parser
* It can parse stuff like
* --option
* --option value
* --opiton=value
*
* it will ignore everything else on the command line. This is needed because boost::
* program_options is handling unknown options very badly
*/
bool parse(int argc, char const* const* argv) {
std::map<std::string, std::string> options;
for (int i(1); i<argc; ++i) {
std::string arg = argv[i];
if (0 == arg.compare(0, 2, "--")) {
arg = arg.substr(2); // cut of first two symbols
} else {
arg = "__command__" + arg;
}
std::string key = arg;
std::string value = "true";
size_t equalSignPos = arg.find("=");
if (equalSignPos != std::string::npos) {
key = arg.substr(0, equalSignPos);
value = arg.substr(equalSignPos+1);
} else if (has_key(key) and get_option(key)->isListType()) {
if (i+1 < argc) {
value = argv[++i];
while (i+1 < argc) {
value += std::string(", ") + argv[++i];
}
}
value = "[" + value + "]";
} else if (i+1 < argc && std::string(argv[i+1]).compare(0, 2, "--" ) != 0) {
value = argv[++i];
}
auto description = get_description(key);
description->changeDefaultValue(value, 1);
}
/* if (commands.size() >= 1) {
auto cmdDescription = get_description("__command__" + commands[0]);
cmdDescription->changeDefaultValue("true", 1);
commands.erase(commands.begin());
auto filesDescription = get_description("__files__");
filesDescription->changeDefaultValue(serializer::yaml::writeAsString(commands), 1);
}*/
if (argc == 2 && std::string(argv[1]) == "__completion") {
printShellCompl();
exit(0);
}
return not hasError();
}
void loadFile(std::string const& _file) {
std::map<std::string, std::string> options;
serializer::yaml::read(_file, options);
for (auto o : options) {
auto desc = get_description(o.first);
desc->changeValue(o.second);
desc->defaultValueActive = false;
}
Singleton::getInstance().signal_load();
}
/** if _includingSections is empty, include them all
*/
void saveFile(std::string const& _file, std::vector<std::string> const& _includingSections) {
std::map<std::string, std::string> options;
std::set<Section*> allSections;
std::queue<Section*> sectionsToProcess;
// collecting all sections (to remove duplicates)
for (auto const& sectName : _includingSections) {
sectionsToProcess.push(get_section(sectName));
}
if (_includingSections.empty()) {
sectionsToProcess.push(getRootSection());
}
while (not sectionsToProcess.empty()) {
auto sect = sectionsToProcess.front();
sectionsToProcess.pop();
allSections.insert(sect);
for (auto& child : sect->getChildren()) {
sectionsToProcess.push(&child.second);
}
}
// Serialize all OptionDescriptions (if they don't have default value)
for (auto section : allSections) {
auto fullName = section->fullName();
for (auto const& description : section->getDescriptions()) {
auto name = fullName + description.second->optionName;
if (not description.second->defaultValueActive) {
auto const* d = description.second.get();
// TODO hack, if value looks like default value, don't save it
if (description.second->defaultValue != d->value) {
options[name] = d->value;
}
}
}
}
serializer::yaml::write(_file, options);
}
Section* get_section(std::string const& _str) {
auto path = splitPath(_str);
Section* section = getRootSection();
for (auto const& p : path) {
section = section->accessChild(p);
}
return section;
}
Section* getRootSection() {
static Section singleton;
return &singleton;
}
auto getUnmatchedParameters() -> std::vector<std::string> {
std::vector<std::string> missing;
std::set<std::string> available;
auto variables = commonOptions::getRootSection()->getVariables();
for (auto v : variables) {
available.insert(v->getSectionName() + v->getName());
}
auto descriptions = commonOptions::getRootSection()->getAllDescriptions();
for (auto const& d : descriptions) {
if (available.count(d.first) == 0) {
missing.push_back(d.first);
}
}
return missing;
}
}
<|endoftext|> |
<commit_before>#include "thread_manager.h"
#include "core_manager.h"
#include "config.h"
#include "log.h"
#include "transport.h"
#include "simulator.h"
#include "network.h"
#include "message_types.h"
#include "core.h"
#define LOG_DEFAULT_RANK -1
#define LOG_DEFAULT_MODULE THREAD_MANAGER
ThreadManager::ThreadManager(CoreManager *core_manager)
: m_core_manager(core_manager)
{
Config *config = Config::getSingleton();
m_master = config->getCurrentProcessNum() == 0;
if (m_master)
{
m_thread_state.resize(config->getTotalCores());
m_thread_state[0].running = true;
m_thread_state[config->getMCPCoreNum()].running = true;
LOG_PRINT("%d", config->getMCPCoreNum());
}
}
ThreadManager::~ThreadManager()
{
if (m_master)
{
m_thread_state[0].running = false;
m_thread_state[Config::getSingleton()->getMCPCoreNum()].running = false;
for (UInt32 i = 0; i < m_thread_state.size(); i++)
LOG_ASSERT_WARNING(!m_thread_state[i].running, "*WARNING* Thread %d still active when ThreadManager destructs!", i);
}
}
void ThreadManager::onThreadStart(SInt32 core_id)
{
m_core_manager->initializeThread(core_id);
}
void ThreadManager::onThreadExit()
{
// send message to master process to update thread state
Transport::Node *globalNode = Transport::getSingleton()->getGlobalNode();
SInt32 msg[4] = { LCP_MESSAGE_THREAD_EXIT, m_core_manager->getCurrentCoreID(), 0, 0 };
LOG_PRINT("onThreadExit msg: { %d, %d, %u, %u }", msg[0], msg[1], msg[2], msg[3]);
globalNode->globalSend(0, msg, sizeof(msg));
m_core_manager->terminateThread();
}
void ThreadManager::masterOnThreadExit(SInt32 core_id, UInt64 time)
{
LOG_PRINT("masterOnThreadExit : %d %llu", core_id, time);
assert(m_thread_state[core_id].running);
m_thread_state[core_id].running = false;
wakeUpWaiter(core_id);
}
/*
Thread spawning occurs in the following steps:
1. A message is sent from requestor to the master thread manager.
2. The master thread manager finds the destination core and sends a message to its host process.
3. The host process spawns the new thread and returns an ack to the master thread manager.
4. The master thread manager replies to the requestor with the id of the dest core.
*/
SInt32 ThreadManager::spawnThread(void (*func)(void*), void *arg)
{
LOG_PRINT("spawnThread with func: %p and arg: %p", func, arg);
// step 1
Transport::Node *globalNode = Transport::getSingleton()->getGlobalNode();
Core *core = m_core_manager->getCurrentCore();
ThreadSpawnRequest req = { LCP_MESSAGE_THREAD_SPAWN_REQUEST_FROM_REQUESTER,
func, arg, core->getId(), -1 };
globalNode->globalSend(0, &req, sizeof(req));
NetPacket pkt = core->getNetwork()->netRecvType(LCP_SPAWN_THREAD_REPLY_FROM_MASTER_TYPE);
LOG_ASSERT_ERROR(pkt.length == sizeof(SInt32), "*ERROR* Unexpected reply size.");
SInt32 core_id = *((SInt32*)pkt.data);
LOG_PRINT("Thread spawned on core: %d", core_id);
return *((SInt32*)pkt.data);
}
void ThreadManager::masterSpawnThread(ThreadSpawnRequest *req)
{
LOG_PRINT("masterSpawnThread with req: { %p, %p, %d, %d }", req->func, req->arg, req->requester, req->core_id);
// step 2
// find core to use
// FIXME: Load balancing?
for (SInt32 i = 0; i < (SInt32)m_thread_state.size(); i++)
{
if (!m_thread_state[i].running)
{
req->core_id = i;
break;
}
}
LOG_ASSERT_ERROR(req->core_id != -1, "*ERROR* No cores available for spawnThread request.");
// spawn process on child
SInt32 dest_proc = Config::getSingleton()->getProcessNumForCore(req->core_id);
Transport::Node *globalNode = Transport::getSingleton()->getGlobalNode();
req->msg_type = LCP_MESSAGE_THREAD_SPAWN_REQUEST_FROM_MASTER;
globalNode->globalSend(dest_proc, req, sizeof(*req));
m_thread_state[req->core_id].running = true;
}
void ThreadManager::slaveSpawnThread(ThreadSpawnRequest *req)
{
LOG_PRINT("slaveSpawnThread with req: { %p, %p, %d, %d }", req->func, req->arg, req->requester, req->core_id);
// step 3
ThreadSpawnRequest *req_cpy = new ThreadSpawnRequest(*req);
Thread *t = Thread::create(spawnedThreadFunc, req_cpy);
t->run();
Transport::Node *globalNode = Transport::getSingleton()->getGlobalNode();
req->msg_type = LCP_MESSAGE_THREAD_SPAWN_REPLY_FROM_SLAVE;
globalNode->globalSend(0, req, sizeof(*req));
}
void ThreadManager::masterSpawnThreadReply(ThreadSpawnRequest *req)
{
LOG_PRINT("masterSpawnThreadReply with req: { %p, %p, %d, %d }", req->func, req->arg, req->requester, req->core_id);
// step 4
Transport::Node *globalNode = Transport::getSingleton()->getGlobalNode();
NetPacket pkt(0 /*time*/, LCP_SPAWN_THREAD_REPLY_FROM_MASTER_TYPE,
0 /*sender*/, req->requester, sizeof(SInt32), &req->core_id);
Byte *buffer = pkt.makeBuffer();
globalNode->send(req->requester, buffer, pkt.bufferSize());
delete [] buffer;
}
void ThreadManager::spawnedThreadFunc(void *vpreq)
{
ThreadSpawnRequest *req = (ThreadSpawnRequest*) vpreq;
LOG_PRINT("spawnedThreadFunc with req: { %p, %p, %d, %d }", req->func, req->arg, req->requester, req->core_id);
Sim()->getThreadManager()->onThreadStart(req->core_id);
req->func(req->arg);
Sim()->getThreadManager()->onThreadExit();
delete req;
}
void ThreadManager::joinThread(SInt32 core_id)
{
// Obtain the object that allows us to communicate to other processes
Transport::Node *globalNode = Transport::getSingleton()->getGlobalNode();
// create a condition variable to wait for the reply
ThreadJoinRequest msg;
msg.core_id = core_id;
msg.sender = m_core_manager->getCurrentCoreID();
// Send the message to the master process
globalNode->globalSend(0, &msg, sizeof(msg));
// Wait for reply
Core *core = m_core_manager->getCurrentCore();
NetPacket pkt = core->getNetwork()->netRecvType(LCP_JOIN_THREAD_REPLY);
}
void ThreadManager::masterJoinThread(ThreadJoinRequest *req)
{
LOG_PRINT("masterJoinThread called.");
//FIXME: fill in the proper time
LOG_ASSERT_ERROR(m_thread_state[req->core_id].waiter == -1,
"*ERROR* Multiple threads joining on thread: %d", req->core_id);
m_thread_state[req->core_id].waiter = req->sender;
// Core not running, so the thread must have joined
if(m_thread_state[req->core_id].running == false)
{
LOG_PRINT("Not running, sending reply.");
wakeUpWaiter(req->core_id);
}
}
void ThreadManager::wakeUpWaiter(SInt32 core_id)
{
if (m_thread_state[core_id].waiter != -1)
{
Transport::Node *globalNode = Transport::getSingleton()->getGlobalNode();
NetPacket pkt(0 /*time*/, LCP_JOIN_THREAD_REPLY,
0 /*sender*/, m_thread_state[core_id].waiter, 0, NULL);
Byte *buffer = pkt.makeBuffer();
globalNode->send(m_thread_state[core_id].waiter, buffer, pkt.bufferSize());
delete [] buffer;
m_thread_state[core_id].waiter = -1;
}
}
<commit_msg>[thread_manager] Send spawn thread reply from spawned thread (not slave LCP). This ensure thread has started by the time SpawnThread returns.<commit_after>#include "thread_manager.h"
#include "core_manager.h"
#include "config.h"
#include "log.h"
#include "transport.h"
#include "simulator.h"
#include "network.h"
#include "message_types.h"
#include "core.h"
#define LOG_DEFAULT_RANK -1
#define LOG_DEFAULT_MODULE THREAD_MANAGER
ThreadManager::ThreadManager(CoreManager *core_manager)
: m_core_manager(core_manager)
{
Config *config = Config::getSingleton();
m_master = config->getCurrentProcessNum() == 0;
if (m_master)
{
m_thread_state.resize(config->getTotalCores());
m_thread_state[0].running = true;
m_thread_state[config->getMCPCoreNum()].running = true;
LOG_PRINT("%d", config->getMCPCoreNum());
}
}
ThreadManager::~ThreadManager()
{
if (m_master)
{
m_thread_state[0].running = false;
m_thread_state[Config::getSingleton()->getMCPCoreNum()].running = false;
for (UInt32 i = 0; i < m_thread_state.size(); i++)
LOG_ASSERT_WARNING(!m_thread_state[i].running, "*WARNING* Thread %d still active when ThreadManager destructs!", i);
}
}
void ThreadManager::onThreadStart(SInt32 core_id)
{
m_core_manager->initializeThread(core_id);
}
void ThreadManager::onThreadExit()
{
// send message to master process to update thread state
Transport::Node *globalNode = Transport::getSingleton()->getGlobalNode();
SInt32 msg[4] = { LCP_MESSAGE_THREAD_EXIT, m_core_manager->getCurrentCoreID(), 0, 0 };
LOG_PRINT("onThreadExit msg: { %d, %d, %u, %u }", msg[0], msg[1], msg[2], msg[3]);
globalNode->globalSend(0, msg, sizeof(msg));
m_core_manager->terminateThread();
}
void ThreadManager::masterOnThreadExit(SInt32 core_id, UInt64 time)
{
LOG_PRINT("masterOnThreadExit : %d %llu", core_id, time);
assert(m_thread_state[core_id].running);
m_thread_state[core_id].running = false;
wakeUpWaiter(core_id);
}
/*
Thread spawning occurs in the following steps:
1. A message is sent from requestor to the master thread manager.
2. The master thread manager finds the destination core and sends a message to its host process.
3. The host process spawns the new thread and returns an ack to the master thread manager.
4. The master thread manager replies to the requestor with the id of the dest core.
*/
SInt32 ThreadManager::spawnThread(void (*func)(void*), void *arg)
{
LOG_PRINT("spawnThread with func: %p and arg: %p", func, arg);
// step 1
Transport::Node *globalNode = Transport::getSingleton()->getGlobalNode();
Core *core = m_core_manager->getCurrentCore();
ThreadSpawnRequest req = { LCP_MESSAGE_THREAD_SPAWN_REQUEST_FROM_REQUESTER,
func, arg, core->getId(), -1 };
globalNode->globalSend(0, &req, sizeof(req));
NetPacket pkt = core->getNetwork()->netRecvType(LCP_SPAWN_THREAD_REPLY_FROM_MASTER_TYPE);
LOG_ASSERT_ERROR(pkt.length == sizeof(SInt32), "*ERROR* Unexpected reply size.");
SInt32 core_id = *((SInt32*)pkt.data);
LOG_PRINT("Thread spawned on core: %d", core_id);
return *((SInt32*)pkt.data);
}
void ThreadManager::masterSpawnThread(ThreadSpawnRequest *req)
{
LOG_PRINT("masterSpawnThread with req: { %p, %p, %d, %d }", req->func, req->arg, req->requester, req->core_id);
// step 2
// find core to use
// FIXME: Load balancing?
for (SInt32 i = 0; i < (SInt32)m_thread_state.size(); i++)
{
if (!m_thread_state[i].running)
{
req->core_id = i;
break;
}
}
LOG_ASSERT_ERROR(req->core_id != -1, "*ERROR* No cores available for spawnThread request.");
// spawn process on child
SInt32 dest_proc = Config::getSingleton()->getProcessNumForCore(req->core_id);
Transport::Node *globalNode = Transport::getSingleton()->getGlobalNode();
req->msg_type = LCP_MESSAGE_THREAD_SPAWN_REQUEST_FROM_MASTER;
globalNode->globalSend(dest_proc, req, sizeof(*req));
m_thread_state[req->core_id].running = true;
}
void ThreadManager::slaveSpawnThread(ThreadSpawnRequest *req)
{
LOG_PRINT("slaveSpawnThread with req: { %p, %p, %d, %d }", req->func, req->arg, req->requester, req->core_id);
// step 3
ThreadSpawnRequest *req_cpy = new ThreadSpawnRequest(*req);
Thread *t = Thread::create(spawnedThreadFunc, req_cpy);
t->run();
}
void ThreadManager::masterSpawnThreadReply(ThreadSpawnRequest *req)
{
LOG_PRINT("masterSpawnThreadReply with req: { %p, %p, %d, %d }", req->func, req->arg, req->requester, req->core_id);
// step 4
Transport::Node *globalNode = Transport::getSingleton()->getGlobalNode();
NetPacket pkt(0 /*time*/, LCP_SPAWN_THREAD_REPLY_FROM_MASTER_TYPE,
0 /*sender*/, req->requester, sizeof(SInt32), &req->core_id);
Byte *buffer = pkt.makeBuffer();
globalNode->send(req->requester, buffer, pkt.bufferSize());
delete [] buffer;
}
void ThreadManager::spawnedThreadFunc(void *vpreq)
{
ThreadSpawnRequest *req = (ThreadSpawnRequest*) vpreq;
LOG_PRINT("spawnedThreadFunc with req: { %p, %p, %d, %d }", req->func, req->arg, req->requester, req->core_id);
Sim()->getThreadManager()->onThreadStart(req->core_id);
Transport::Node *globalNode = Transport::getSingleton()->getGlobalNode();
req->msg_type = LCP_MESSAGE_THREAD_SPAWN_REPLY_FROM_SLAVE;
globalNode->globalSend(0, req, sizeof(*req));
req->func(req->arg);
Sim()->getThreadManager()->onThreadExit();
delete req;
}
void ThreadManager::joinThread(SInt32 core_id)
{
// Obtain the object that allows us to communicate to other processes
Transport::Node *globalNode = Transport::getSingleton()->getGlobalNode();
// create a condition variable to wait for the reply
ThreadJoinRequest msg;
msg.core_id = core_id;
msg.sender = m_core_manager->getCurrentCoreID();
// Send the message to the master process
globalNode->globalSend(0, &msg, sizeof(msg));
// Wait for reply
Core *core = m_core_manager->getCurrentCore();
NetPacket pkt = core->getNetwork()->netRecvType(LCP_JOIN_THREAD_REPLY);
}
void ThreadManager::masterJoinThread(ThreadJoinRequest *req)
{
LOG_PRINT("masterJoinThread called.");
//FIXME: fill in the proper time
LOG_ASSERT_ERROR(m_thread_state[req->core_id].waiter == -1,
"*ERROR* Multiple threads joining on thread: %d", req->core_id);
m_thread_state[req->core_id].waiter = req->sender;
// Core not running, so the thread must have joined
if(m_thread_state[req->core_id].running == false)
{
LOG_PRINT("Not running, sending reply.");
wakeUpWaiter(req->core_id);
}
}
void ThreadManager::wakeUpWaiter(SInt32 core_id)
{
if (m_thread_state[core_id].waiter != -1)
{
Transport::Node *globalNode = Transport::getSingleton()->getGlobalNode();
NetPacket pkt(0 /*time*/, LCP_JOIN_THREAD_REPLY,
0 /*sender*/, m_thread_state[core_id].waiter, 0, NULL);
Byte *buffer = pkt.makeBuffer();
globalNode->send(m_thread_state[core_id].waiter, buffer, pkt.bufferSize());
delete [] buffer;
m_thread_state[core_id].waiter = -1;
}
}
<|endoftext|> |
<commit_before>/******************************************************************************
*
* Wendy asset manager
* Copyright (c) 2011 Remi Papillie
*
* This software is provided 'as-is', without any express or implied
* warranty. In no event will the authors be held liable for any damages
* arising from the use of this software.
*
* Permission is granted to anyone to use this software for any purpose,
* including commercial applications, and to alter it and redistribute it
* freely, subject to the following restrictions:
*
* 1. The origin of this software must not be misrepresented; you must not
* claim that you wrote the original software. If you use this software
* in a product, an acknowledgment in the product documentation would be
* appreciated but is not required.
*
* 2. Altered source versions must be plainly marked as such, and must not
* be misrepresented as being the original software.
*
* 3. This notice may not be removed or altered from any source
* distribution.
*
*****************************************************************************/
#ifdef _WIN32
#include <windows.h>
#include <winbase.h>
#include <stdio.h>
#include <stdlib.h>
#include <dokan.h>
#include <iostream>
#include <wendy/Project.hpp>
#include "ProjectProxy.hpp"
static ProjectProxy *proxy = NULL;
static std::string wideToUtf8(std::wstring wide)
{
// passing no output buffer return required buffer size
int size = WideCharToMultiByte(CP_UTF8, 0, wide.c_str(), -1, NULL, 0, NULL, NULL);
// convert into a temporary buffer
char *outputBuffer = new char[size];
WideCharToMultiByte(CP_UTF8, 0, wide.c_str(), -1, outputBuffer, size, NULL, NULL);
// create the equivalent string object
std::string utf = outputBuffer;
// destroy temporary buffer
delete outputBuffer;
return utf;
}
static std::wstring utf8ToWide(std::string utf)
{
// passing no output buffer return required buffer size
int size = MultiByteToWideChar(CP_UTF8, 0, utf.c_str(), -1, NULL, 0);
// convert into a temporary buffer
wchar_t *outputBuffer = new wchar_t[size];
MultiByteToWideChar(CP_UTF8, 0, utf.c_str(), -1, outputBuffer, size);
// create the equivalent wstring object
std::wstring wide = outputBuffer;
// destroy temporary buffer
delete outputBuffer;
return wide;
}
// convert to utf-8, change '\\' to '/' and remove leading slash
static std::string makePathStandard(LPCWSTR path)
{
std::string utfPath = wideToUtf8(std::wstring(path));
// change backslashes to forward slashes
size_t slashPos;
while ((slashPos = utfPath.find('\\')) != std::string::npos)
utfPath.replace(slashPos, 1, "/");
// remove leading slash
return utfPath.substr(1);
}
static int DOKAN_CALLBACK WendyCreateFile(LPCWSTR filename, DWORD accessMode, DWORD shareMode, DWORD creationDisposition, DWORD flagsAndAttributes, PDOKAN_FILE_INFO info)
{
wprintf(L"CreateFile: %s\n", filename);
return 0;
}
static int DOKAN_CALLBACK WendyOpenDirectory(LPCWSTR filename, PDOKAN_FILE_INFO info)
{
wprintf(L"OpenDir %s\n", filename);
std::cout << "OpenDir: " << makePathStandard(filename) << std::endl;
std::string path = makePathStandard(filename);
ProjectProxy::FileAttributes attributes;
if (!proxy->getFileAttributes(path, &attributes))
return -ERROR_PATH_NOT_FOUND;
if (!attributes.folder)
return -ERROR_PATH_NOT_FOUND; // TODO: find the right error code for this
return 0;
/*if (wcscmp(filename, L"\\") == 0)
return 0;
else if (wcscmp(filename, L"\\plop") == 0)
return 0;
return -ERROR_PATH_NOT_FOUND;*/
}
static int DOKAN_CALLBACK WendyCleanup(LPCWSTR filename, PDOKAN_FILE_INFO info)
{
wprintf(L"Cleanup %s\n", filename);
return 0;
}
static int DOKAN_CALLBACK WendyFindFiles(LPCWSTR filename, PFillFindData fillFindData, PDOKAN_FILE_INFO info)
{
wprintf(L"FindFiles %s\n", filename);
WIN32_FIND_DATAW entry;
ZeroMemory(&entry, sizeof(WIN32_FIND_DATAW));
std::string path = makePathStandard(filename);
std::vector<std::string> files = proxy->listFolder(path);
for (unsigned int i = 0; i < files.size(); ++i)
{
// filename
const std::string &filename = files[i];
std::wstring wfilename = utf8ToWide(filename);
wcsncpy(entry.cFileName, wfilename.c_str(), MAX_PATH - 1);
// other attributes
ProjectProxy::FileAttributes attributes;
proxy->getFileAttributes(files[i], &attributes);
entry.dwFileAttributes = attributes.folder ? FILE_ATTRIBUTE_DIRECTORY : FILE_ATTRIBUTE_NORMAL;
// send item back to caller
fillFindData(&entry, info);
}
return 0;
}
int __cdecl wmain(ULONG argc, PWCHAR argv[])
{
if (argc < 3)
{
wprintf(L"Usage: %s <drive letter> <project name>\n", argv[0]);
return 0;
}
DOKAN_OPTIONS options;
DOKAN_OPERATIONS operations;
ZeroMemory(&options, sizeof(DOKAN_OPTIONS));
options.Version = DOKAN_VERSION;
options.ThreadCount = 0; // use default
options.MountPoint = argv[1];
options.Options = DOKAN_OPTION_KEEP_ALIVE;
ZeroMemory(&operations, sizeof(DOKAN_OPERATIONS));
operations.CreateFile = WendyCreateFile;
operations.OpenDirectory = WendyOpenDirectory;
operations.Cleanup = WendyCleanup;
operations.FindFiles = WendyFindFiles;
//char projectName[500];
//WideCharToMultiByte(CP_UTF8, 0, argv[2], -1, projectName, 500, NULL, NULL);
proxy = new ProjectProxy();
int result = DokanMain(&options, &operations);
delete proxy;
return result;
}
#endif // _WIN32
<commit_msg>fixed subdirectories under windows<commit_after>/******************************************************************************
*
* Wendy asset manager
* Copyright (c) 2011 Remi Papillie
*
* This software is provided 'as-is', without any express or implied
* warranty. In no event will the authors be held liable for any damages
* arising from the use of this software.
*
* Permission is granted to anyone to use this software for any purpose,
* including commercial applications, and to alter it and redistribute it
* freely, subject to the following restrictions:
*
* 1. The origin of this software must not be misrepresented; you must not
* claim that you wrote the original software. If you use this software
* in a product, an acknowledgment in the product documentation would be
* appreciated but is not required.
*
* 2. Altered source versions must be plainly marked as such, and must not
* be misrepresented as being the original software.
*
* 3. This notice may not be removed or altered from any source
* distribution.
*
*****************************************************************************/
#ifdef _WIN32
#include <windows.h>
#include <winbase.h>
#include <stdio.h>
#include <stdlib.h>
#include <dokan.h>
#include <iostream>
#include <wendy/Project.hpp>
#include "ProjectProxy.hpp"
static ProjectProxy *proxy = NULL;
static std::string wideToUtf8(std::wstring wide)
{
// passing no output buffer return required buffer size
int size = WideCharToMultiByte(CP_UTF8, 0, wide.c_str(), -1, NULL, 0, NULL, NULL);
// convert into a temporary buffer
char *outputBuffer = new char[size];
WideCharToMultiByte(CP_UTF8, 0, wide.c_str(), -1, outputBuffer, size, NULL, NULL);
// create the equivalent string object
std::string utf = outputBuffer;
// destroy temporary buffer
delete outputBuffer;
return utf;
}
static std::wstring utf8ToWide(std::string utf)
{
// passing no output buffer return required buffer size
int size = MultiByteToWideChar(CP_UTF8, 0, utf.c_str(), -1, NULL, 0);
// convert into a temporary buffer
wchar_t *outputBuffer = new wchar_t[size];
MultiByteToWideChar(CP_UTF8, 0, utf.c_str(), -1, outputBuffer, size);
// create the equivalent wstring object
std::wstring wide = outputBuffer;
// destroy temporary buffer
delete outputBuffer;
return wide;
}
// convert to utf-8, change '\\' to '/' and remove leading slash
static std::string makePathStandard(LPCWSTR path)
{
std::string utfPath = wideToUtf8(std::wstring(path));
// change backslashes to forward slashes
size_t slashPos;
while ((slashPos = utfPath.find('\\')) != std::string::npos)
utfPath.replace(slashPos, 1, "/");
// remove leading slash
return utfPath.substr(1);
}
static int DOKAN_CALLBACK WendyCreateFile(LPCWSTR filename, DWORD accessMode, DWORD shareMode, DWORD creationDisposition, DWORD flagsAndAttributes, PDOKAN_FILE_INFO info)
{
//wprintf(L"CreateFile: %s\n", filename);
return 0;
}
static int DOKAN_CALLBACK WendyOpenDirectory(LPCWSTR filename, PDOKAN_FILE_INFO info)
{
//wprintf(L"OpenDir %s\n", filename);
//std::cout << "OpenDir: " << makePathStandard(filename) << std::endl;
std::string path = makePathStandard(filename);
ProjectProxy::FileAttributes attributes;
if (!proxy->getFileAttributes(path, &attributes))
return -ERROR_PATH_NOT_FOUND;
if (!attributes.folder)
return -ERROR_PATH_NOT_FOUND; // TODO: find the right error code for this
return 0;
/*if (wcscmp(filename, L"\\") == 0)
return 0;
else if (wcscmp(filename, L"\\plop") == 0)
return 0;
return -ERROR_PATH_NOT_FOUND;*/
}
static int DOKAN_CALLBACK WendyCleanup(LPCWSTR filename, PDOKAN_FILE_INFO info)
{
//wprintf(L"Cleanup %s\n", filename);
return 0;
}
static int DOKAN_CALLBACK WendyFindFiles(LPCWSTR filename, PFillFindData fillFindData, PDOKAN_FILE_INFO info)
{
//wprintf(L"FindFiles %s\n", filename);
WIN32_FIND_DATAW entry;
ZeroMemory(&entry, sizeof(WIN32_FIND_DATAW));
std::string path = makePathStandard(filename);
std::vector<std::string> files = proxy->listFolder(path);
for (unsigned int i = 0; i < files.size(); ++i)
{
// filename
const std::string &filename = files[i];
std::wstring wfilename = utf8ToWide(filename);
wcsncpy(entry.cFileName, wfilename.c_str(), MAX_PATH - 1);
// other attributes
ProjectProxy::FileAttributes attributes;
std::string fullChildPath = files[i];
if (path.size() > 0)
fullChildPath = path + "/" + files[i];
proxy->getFileAttributes(fullChildPath, &attributes);
entry.dwFileAttributes = attributes.folder ? FILE_ATTRIBUTE_DIRECTORY : FILE_ATTRIBUTE_NORMAL;
// send item back to caller
fillFindData(&entry, info);
}
return 0;
}
int __cdecl wmain(ULONG argc, PWCHAR argv[])
{
if (argc < 3)
{
wprintf(L"Usage: %s <drive letter> <project name>\n", argv[0]);
return 0;
}
DOKAN_OPTIONS options;
DOKAN_OPERATIONS operations;
ZeroMemory(&options, sizeof(DOKAN_OPTIONS));
options.Version = DOKAN_VERSION;
options.ThreadCount = 0; // use default
options.MountPoint = argv[1];
options.Options = DOKAN_OPTION_KEEP_ALIVE;
ZeroMemory(&operations, sizeof(DOKAN_OPERATIONS));
operations.CreateFile = WendyCreateFile;
operations.OpenDirectory = WendyOpenDirectory;
operations.Cleanup = WendyCleanup;
operations.FindFiles = WendyFindFiles;
//char projectName[500];
//WideCharToMultiByte(CP_UTF8, 0, argv[2], -1, projectName, 500, NULL, NULL);
proxy = new ProjectProxy();
int result = DokanMain(&options, &operations);
delete proxy;
return result;
}
#endif // _WIN32
<|endoftext|> |
<commit_before>#include <stingray/toolkit/StringUtils.h>
namespace stingray
{
std::string Utf8ToLower(const std::string& str)
{
std::string result;
for (std::string::const_iterator it = str.begin(); it != str.end(); ++it)
{
if (*it >= 'A' && *it <= 'Z')
result.push_back(*it + 'a' - 'A');
else if ((u8)*it == 0xD0)
{
u16 c0 = (u8)*it & 0x1F;
TOOLKIT_CHECK(++it != str.end(), "Malformed utf-8!");
u16 c = (c0 << 6) | ((u8)*it & 0x3F);
if (c >= 0x410 && c <= 0x42F)
c += 0x20;
result.push_back(0xD0 | (c >> 6));
result.push_back((c & 0x3F) | 0x80);
}
else
result.push_back(*it);
}
return result;
}
}
<commit_msg>reserve space for result in utf8tolower<commit_after>#include <stingray/toolkit/StringUtils.h>
namespace stingray
{
std::string Utf8ToLower(const std::string& str)
{
std::string result;
result.reserve(str.size());
for (std::string::const_iterator it = str.begin(); it != str.end(); ++it)
{
if (*it >= 'A' && *it <= 'Z')
result.push_back(*it + 'a' - 'A');
else if ((u8)*it == 0xD0)
{
u16 c0 = (u8)*it & 0x1F;
TOOLKIT_CHECK(++it != str.end(), "Malformed utf-8!");
u16 c = (c0 << 6) | ((u8)*it & 0x3F);
if (c >= 0x410 && c <= 0x42F)
c += 0x20;
result.push_back(0xD0 | (c >> 6));
result.push_back((c & 0x3F) | 0x80);
}
else
result.push_back(*it);
}
return result;
}
}
<|endoftext|> |
<commit_before>/* Copyright (c) 2000 - 2013 Samsung Electronics Co., Ltd All Rights Reserved
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License
*
*
* @file client-echo.cpp
* @author Bartlomiej Grzelewski (b.grzelewski@samsung.com)
* @version 1.0
* @brief Key implementation.
*/
#include <openssl/bio.h>
#include <openssl/pem.h>
#include <client-key-impl.h>
namespace {
const char PEM_FIRST_CHAR = '-';
} // namespace anonymous
namespace CKM {
KeyImpl::KeyImpl()
: m_type(KeyType::KEY_NONE)
{}
KeyImpl::KeyImpl(const KeyImpl &second)
: m_type(second.m_type)
, m_key(second.m_key)
{}
KeyImpl::KeyImpl(KeyImpl &&second)
: m_type(second.m_type)
, m_key(std::move(second.m_key))
{}
KeyImpl& KeyImpl::operator=(const KeyImpl &second) {
m_type = second.m_type;
m_key = second.m_key;
return *this;
}
KeyImpl& KeyImpl::operator=(KeyImpl &&second) {
m_type = std::move(second.m_type);
m_key = std::move(second.m_key);
return *this;
}
KeyImpl::KeyImpl(const RawBuffer &data, KeyType type, const std::string &password)
: m_type(KeyType::KEY_NONE)
{
int size = 0;
RSA *rsa = NULL;
char *pass = NULL;
std::string passtmp(password);
if (!passtmp.empty()) {
pass = const_cast<char *>(passtmp.c_str());
}
if (data[0] == PEM_FIRST_CHAR && type == KeyType::KEY_RSA_PUBLIC) {
BIO *bio = BIO_new(BIO_s_mem());
BIO_write(bio, data.data(), data.size());
rsa = PEM_read_bio_RSA_PUBKEY(bio, NULL, NULL, pass);
BIO_free_all(bio);
} else if (data[0] == PEM_FIRST_CHAR && type == KeyType::KEY_RSA_PRIVATE) {
BIO *bio = BIO_new(BIO_s_mem());
BIO_write(bio, data.data(), data.size());
rsa = PEM_read_bio_RSAPrivateKey(bio, NULL, NULL, pass);
BIO_free_all(bio);
} else if (type == KeyType::KEY_RSA_PUBLIC) {
const unsigned char *p = (const unsigned char*)data.data();
rsa = d2i_RSA_PUBKEY(NULL, &p, data.size());
} else if (type == KeyType::KEY_RSA_PRIVATE) {
BIO *bio = BIO_new(BIO_s_mem());
BIO_write(bio, data.data(), data.size());
rsa = d2i_RSAPrivateKey_bio(bio, NULL);
BIO_free_all(bio);
} else {
return;
}
if (!rsa)
return;
BIO *bio = BIO_new(BIO_s_mem());
if (type == KeyType::KEY_RSA_PUBLIC) {
size = i2d_RSAPublicKey_bio(bio, rsa);
} else {
size = i2d_RSAPrivateKey_bio(bio, rsa);
}
if (size > 0) {
m_key.resize(size);
BIO_read(bio, m_key.data(), m_key.size());
m_type = type;
}
BIO_free_all(bio);
}
//void KeyImpl::Serialize(IStream &stream) const {
// Serialization::Serialize(stream, static_cast<int>(m_type));
// Serialization::Serialize(stream, m_key);
//}
KeyImpl::~KeyImpl(){}
} // namespace CKM
<commit_msg>Bug fix<commit_after>/* Copyright (c) 2000 - 2013 Samsung Electronics Co., Ltd All Rights Reserved
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License
*
*
* @file client-echo.cpp
* @author Bartlomiej Grzelewski (b.grzelewski@samsung.com)
* @version 1.0
* @brief Key implementation.
*/
#include <openssl/bio.h>
#include <openssl/pem.h>
#include <client-key-impl.h>
namespace {
const char PEM_FIRST_CHAR = '-';
} // namespace anonymous
namespace CKM {
KeyImpl::KeyImpl()
: m_type(KeyType::KEY_NONE)
{}
KeyImpl::KeyImpl(const KeyImpl &second)
: m_type(second.m_type)
, m_key(second.m_key)
{}
KeyImpl::KeyImpl(KeyImpl &&second)
: m_type(second.m_type)
, m_key(std::move(second.m_key))
{}
KeyImpl& KeyImpl::operator=(const KeyImpl &second) {
m_type = second.m_type;
m_key = second.m_key;
return *this;
}
KeyImpl& KeyImpl::operator=(KeyImpl &&second) {
m_type = std::move(second.m_type);
m_key = std::move(second.m_key);
return *this;
}
KeyImpl::KeyImpl(const RawBuffer &data, KeyType type, const std::string &password)
: m_type(KeyType::KEY_NONE)
{
int ret = 0;
RSA *rsa = NULL;
char *pass = NULL;
std::string passtmp(password);
if (!passtmp.empty()) {
pass = const_cast<char *>(passtmp.c_str());
}
if (data[0] == PEM_FIRST_CHAR && type == KeyType::KEY_RSA_PUBLIC) {
BIO *bio = BIO_new(BIO_s_mem());
BIO_write(bio, data.data(), data.size());
rsa = PEM_read_bio_RSA_PUBKEY(bio, NULL, NULL, pass);
BIO_free_all(bio);
} else if (data[0] == PEM_FIRST_CHAR && type == KeyType::KEY_RSA_PRIVATE) {
BIO *bio = BIO_new(BIO_s_mem());
BIO_write(bio, data.data(), data.size());
rsa = PEM_read_bio_RSAPrivateKey(bio, NULL, NULL, pass);
BIO_free_all(bio);
} else if (type == KeyType::KEY_RSA_PUBLIC) {
const unsigned char *p = (const unsigned char*)data.data();
rsa = d2i_RSA_PUBKEY(NULL, &p, data.size());
} else if (type == KeyType::KEY_RSA_PRIVATE) {
BIO *bio = BIO_new(BIO_s_mem());
BIO_write(bio, data.data(), data.size());
rsa = d2i_RSAPrivateKey_bio(bio, NULL);
BIO_free_all(bio);
} else {
return;
}
if (!rsa)
return;
BIO *bio = BIO_new(BIO_s_mem());
if (type == KeyType::KEY_RSA_PUBLIC) {
ret = i2d_RSAPublicKey_bio(bio, rsa);
} else {
ret = i2d_RSAPrivateKey_bio(bio, rsa);
}
if (ret > 0) {
m_key.resize(data.size());
BIO_read(bio, m_key.data(), data.size());
m_type = type;
}
BIO_free_all(bio);
}
//void KeyImpl::Serialize(IStream &stream) const {
// Serialization::Serialize(stream, static_cast<int>(m_type));
// Serialization::Serialize(stream, m_key);
//}
KeyImpl::~KeyImpl(){}
} // namespace CKM
<|endoftext|> |
<commit_before>// Copyright (c) 2011-2012 The Bitcoin developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "sync.h"
#include "util.h"
#include "state.h"
#include <boost/foreach.hpp>
#ifdef DEBUG_LOCKCONTENTION
void PrintLockContention(const char* pszName, const char* pszFile, int nLine)
{
LogPrintf("LOCKCONTENTION: %s\n", pszName);
LogPrintf("Locker: %s:%d\n", pszFile, nLine);
}
#endif /* DEBUG_LOCKCONTENTION */
#ifdef DEBUG_LOCKORDER
//
// Early deadlock detection.
// Problem being solved:
// Thread 1 locks A, then B, then C
// Thread 2 locks D, then C, then A
// --> may result in deadlock between the two threads, depending on when they run.
// Solution implemented here:
// Keep track of pairs of locks: (A before B), (A before C), etc.
// Complain if any thread tries to lock in a different order.
//
struct CLockLocation
{
CLockLocation(const char* pszName, const char* pszFile, int nLine)
{
mutexName = pszName;
sourceFile = pszFile;
sourceLine = nLine;
}
std::string ToString() const
{
return mutexName+" "+sourceFile+":"+itostr(sourceLine);
}
std::string MutexName() const { return mutexName; }
private:
std::string mutexName;
std::string sourceFile;
int sourceLine;
};
typedef std::vector< std::pair<void*, CLockLocation> > LockStack;
static boost::mutex dd_mutex;
static std::map<std::pair<void*, void*>, LockStack> lockorders;
static boost::thread_specific_ptr<LockStack> lockstack;
static void potential_deadlock_detected(const std::pair<void*, void*>& mismatch, const LockStack& s1, const LockStack& s2)
{
LogPrintf("POTENTIAL DEADLOCK DETECTED\n");
LogPrintf("Previous lock order was:\n");
BOOST_FOREACH(const PAIRTYPE(void*, CLockLocation)& i, s2)
{
if (i.first == mismatch.first) LogPrintf(" (1)");
if (i.first == mismatch.second) LogPrintf(" (2)");
LogPrintf(" %s\n", i.second.ToString().c_str());
}
LogPrintf("Current lock order is:\n");
BOOST_FOREACH(const PAIRTYPE(void*, CLockLocation)& i, s1)
{
if (i.first == mismatch.first) LogPrintf(" (1)");
if (i.first == mismatch.second) LogPrintf(" (2)");
LogPrintf(" %s\n", i.second.ToString().c_str());
}
}
static void push_lock(void* c, const CLockLocation& locklocation, bool fTry)
{
if (lockstack.get() == NULL)
lockstack.reset(new LockStack);
if (fDebug) LogPrintf("Locking: %s\n", locklocation.ToString().c_str());
dd_mutex.lock();
(*lockstack).push_back(std::make_pair(c, locklocation));
if (!fTry) {
BOOST_FOREACH(const PAIRTYPE(void*, CLockLocation)& i, (*lockstack)) {
if (i.first == c) break;
std::pair<void*, void*> p1 = std::make_pair(i.first, c);
if (lockorders.count(p1))
continue;
lockorders[p1] = (*lockstack);
std::pair<void*, void*> p2 = std::make_pair(c, i.first);
if (lockorders.count(p2))
{
potential_deadlock_detected(p1, lockorders[p2], lockorders[p1]);
break;
}
}
}
dd_mutex.unlock();
}
static void pop_lock()
{
if (fDebug)
{
const CLockLocation& locklocation = (*lockstack).rbegin()->second;
LogPrintf("Unlocked: %s\n", locklocation.ToString().c_str());
}
dd_mutex.lock();
(*lockstack).pop_back();
dd_mutex.unlock();
}
void EnterCritical(const char* pszName, const char* pszFile, int nLine, void* cs, bool fTry)
{
push_lock(cs, CLockLocation(pszName, pszFile, nLine), fTry);
}
void LeaveCritical()
{
pop_lock();
}
std::string LocksHeld()
{
std::string result;
BOOST_FOREACH(const PAIRTYPE(void*, CLockLocation)&i, *lockstack)
result += i.second.ToString() + std::string("\n");
return result;
}
void AssertLockHeldInternal(const char *pszName, const char* pszFile, int nLine, void *cs)
{
BOOST_FOREACH(const PAIRTYPE(void*, CLockLocation)&i, *lockstack)
if (i.first == cs) return;
fprintf(stderr, "Assertion failed: lock %s not held in %s:%i; locks held:\n%s",
pszName, pszFile, nLine, LocksHeld().c_str());
abort();
}
#endif /* DEBUG_LOCKORDER */
<commit_msg>Log not open at this point<commit_after>// Copyright (c) 2011-2012 The Bitcoin developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "sync.h"
#include "util.h"
#include "state.h"
#include <boost/foreach.hpp>
#ifdef DEBUG_LOCKCONTENTION
void PrintLockContention(const char* pszName, const char* pszFile, int nLine)
{
LogPrintf("LOCKCONTENTION: %s\n", pszName);
LogPrintf("Locker: %s:%d\n", pszFile, nLine);
}
#endif /* DEBUG_LOCKCONTENTION */
#ifdef DEBUG_LOCKORDER
//
// Early deadlock detection.
// Problem being solved:
// Thread 1 locks A, then B, then C
// Thread 2 locks D, then C, then A
// --> may result in deadlock between the two threads, depending on when they run.
// Solution implemented here:
// Keep track of pairs of locks: (A before B), (A before C), etc.
// Complain if any thread tries to lock in a different order.
//
struct CLockLocation
{
CLockLocation(const char* pszName, const char* pszFile, int nLine)
{
mutexName = pszName;
sourceFile = pszFile;
sourceLine = nLine;
}
std::string ToString() const
{
return mutexName+" "+sourceFile+":"+itostr(sourceLine);
}
std::string MutexName() const { return mutexName; }
private:
std::string mutexName;
std::string sourceFile;
int sourceLine;
};
typedef std::vector< std::pair<void*, CLockLocation> > LockStack;
static boost::mutex dd_mutex;
static std::map<std::pair<void*, void*>, LockStack> lockorders;
static boost::thread_specific_ptr<LockStack> lockstack;
static void potential_deadlock_detected(const std::pair<void*, void*>& mismatch, const LockStack& s1, const LockStack& s2)
{
LogPrintf("POTENTIAL DEADLOCK DETECTED\n");
LogPrintf("Previous lock order was:\n");
BOOST_FOREACH(const PAIRTYPE(void*, CLockLocation)& i, s2)
{
if (i.first == mismatch.first) LogPrintf(" (1)");
if (i.first == mismatch.second) LogPrintf(" (2)");
LogPrintf(" %s\n", i.second.ToString().c_str());
}
LogPrintf("Current lock order is:\n");
BOOST_FOREACH(const PAIRTYPE(void*, CLockLocation)& i, s1)
{
if (i.first == mismatch.first) LogPrintf(" (1)");
if (i.first == mismatch.second) LogPrintf(" (2)");
LogPrintf(" %s\n", i.second.ToString().c_str());
}
}
static void push_lock(void* c, const CLockLocation& locklocation, bool fTry)
{
if (lockstack.get() == NULL)
lockstack.reset(new LockStack);
// if (fDebug) LogPrintf("Locking: %s\n", locklocation.ToString().c_str()); Logfile not yet open - causes freeze
dd_mutex.lock();
(*lockstack).push_back(std::make_pair(c, locklocation));
if (!fTry) {
BOOST_FOREACH(const PAIRTYPE(void*, CLockLocation)& i, (*lockstack)) {
if (i.first == c) break;
std::pair<void*, void*> p1 = std::make_pair(i.first, c);
if (lockorders.count(p1))
continue;
lockorders[p1] = (*lockstack);
std::pair<void*, void*> p2 = std::make_pair(c, i.first);
if (lockorders.count(p2))
{
potential_deadlock_detected(p1, lockorders[p2], lockorders[p1]);
break;
}
}
}
dd_mutex.unlock();
}
static void pop_lock()
{
/*
if (fDebug)
{
const CLockLocation& locklocation = (*lockstack).rbegin()->second;
LogPrintf("Unlocked: %s\n", locklocation.ToString().c_str());
}
*/
dd_mutex.lock();
(*lockstack).pop_back();
dd_mutex.unlock();
}
void EnterCritical(const char* pszName, const char* pszFile, int nLine, void* cs, bool fTry)
{
push_lock(cs, CLockLocation(pszName, pszFile, nLine), fTry);
}
void LeaveCritical()
{
pop_lock();
}
std::string LocksHeld()
{
std::string result;
BOOST_FOREACH(const PAIRTYPE(void*, CLockLocation)&i, *lockstack)
result += i.second.ToString() + std::string("\n");
return result;
}
void AssertLockHeldInternal(const char *pszName, const char* pszFile, int nLine, void *cs)
{
BOOST_FOREACH(const PAIRTYPE(void*, CLockLocation)&i, *lockstack)
if (i.first == cs) return;
fprintf(stderr, "Assertion failed: lock %s not held in %s:%i; locks held:\n%s",
pszName, pszFile, nLine, LocksHeld().c_str());
abort();
}
#endif /* DEBUG_LOCKORDER */
<|endoftext|> |
<commit_before>#include <vector>
#include <string>
#include <sstream>
#include <pcl/io/pcd_io.h>
#include <pcl/common/time.h>
#include <pcl/console/parse.h>
#include <pcl/search/kdtree.h>
#include <pcl/search/brute_force.h>
using namespace std;
int
main (int argc, char ** argv)
{
if (argc < 2)
{
pcl::console::print_info ("Syntax is: %s -pcd <pcd-file> (-radius <radius> | -knn <k> )\n", argv[0]);
return (1);
}
string pcd_path;
bool use_pcd_file = pcl::console::find_switch (argc, argv, "-pcd");
if (use_pcd_file)
pcl::console::parse (argc, argv, "-pcd", pcd_path);
float radius = -1;
if (pcl::console::find_switch (argc, argv, "-radius"))
pcl::console::parse (argc, argv, "-radius", radius);
int k = -1;
if (pcl::console::find_switch (argc, argv, "-knn"))
pcl::console::parse (argc, argv, "-knn", k);
if ((radius * k) > 0)
{
cout << "please specify only one of the options -radius and -knn" << endl;
return (1);
}
pcl::PointCloud<pcl::PointXYZRGB>::Ptr cloud (new pcl::PointCloud<pcl::PointXYZRGB>);
if (use_pcd_file)
pcl::io::loadPCDFile (pcd_path, *cloud);
else
{
cloud->resize (1000000);
for (unsigned idx = 0; idx < cloud->size (); ++idx)
{
(*cloud)[idx].x = (double)rand () / (double)RAND_MAX;
(*cloud)[idx].y = (double)rand () / (double)RAND_MAX;
(*cloud)[idx].z = (double)rand () / (double)RAND_MAX;
}
}
pcl::search::KdTree<pcl::PointXYZRGB> tree;
pcl::PointXYZRGB query;
query.x = 0.5;
query.y = 0.5;
query.z = 0.5;
vector<int> kd_indices;
vector<float> kd_distances;
double start, stop;
double kd_setup;
double kd_search;
double bf_setup;
double bf_search;
start = pcl::getTime ();
tree.setInputCloud (cloud);
stop = pcl::getTime ();
cout << "setting up kd tree: " << (kd_setup = stop - start) << endl;
start = pcl::getTime ();
tree.nearestKSearchT (query, k, kd_indices, kd_distances);
stop = pcl::getTime ();
cout << "single search with kd tree; " << (kd_search = stop - start) << " :: " << kd_indices[0] << " , " << kd_distances [0] << endl;
vector<int> bf_indices;
vector<float> bf_distances;
pcl::search::BruteForce<pcl::PointXYZRGB> brute_force;
start = pcl::getTime ();
brute_force.setInputCloud (cloud);
stop = pcl::getTime ();
cout << "setting up brute force search: " << (bf_setup = stop - start) << endl;
start = pcl::getTime ();
brute_force.nearestKSearchT (query, k, bf_indices, bf_distances);
stop = pcl::getTime ();
cout << "single search with brute force; " << (bf_search = stop - start) << " :: " << bf_indices[0] << " , " << bf_distances [0] << endl;
cout << "amortization after searches: " << (kd_setup - bf_setup) / (bf_search - kd_search) << endl;
if (kd_indices.size () != bf_indices.size ())
{
cerr << "number does not match" << endl;
}
else
{
for (unsigned idx = 0; idx < kd_indices.size (); ++idx)
{
if (kd_indices[idx] != bf_indices[idx] && kd_distances[idx] != bf_distances[idx])
{
cerr << "results do not match: " << idx << " nearest neighbor: "
<< kd_indices[idx] << " with distance: " << kd_distances[idx] << " vs. "
<< bf_indices[idx] << " with distance: " << bf_distances[idx] << endl;
}
}
}
return (0);
}
<commit_msg>added radius search to test<commit_after>#include <vector>
#include <string>
#include <sstream>
#include <pcl/io/pcd_io.h>
#include <pcl/common/time.h>
#include <pcl/console/parse.h>
#include <pcl/search/kdtree.h>
#include <pcl/search/brute_force.h>
using namespace std;
int
main (int argc, char ** argv)
{
if (argc < 2)
{
pcl::console::print_info ("Syntax is: %s [-pcd <pcd-file>] (-radius <radius> [-knn <k>] | -knn <k> )\n", argv[0]);
return (1);
}
string pcd_path;
bool use_pcd_file = pcl::console::find_switch (argc, argv, "-pcd");
if (use_pcd_file)
pcl::console::parse (argc, argv, "-pcd", pcd_path);
float radius = -1;
if (pcl::console::find_switch (argc, argv, "-radius"))
pcl::console::parse (argc, argv, "-radius", radius);
int k = -1;
if (pcl::console::find_switch (argc, argv, "-knn"))
pcl::console::parse (argc, argv, "-knn", k);
if (radius < 0 && k < 0)
{
cout << "please specify at least one of the options -radius and -knn" << endl;
return (1);
}
pcl::PointCloud<pcl::PointXYZRGB>::Ptr cloud (new pcl::PointCloud<pcl::PointXYZRGB>);
if (use_pcd_file)
pcl::io::loadPCDFile (pcd_path, *cloud);
else
{
cloud->resize (1000000);
for (unsigned idx = 0; idx < cloud->size (); ++idx)
{
(*cloud)[idx].x = (double)rand () / (double)RAND_MAX;
(*cloud)[idx].y = (double)rand () / (double)RAND_MAX;
(*cloud)[idx].z = (double)rand () / (double)RAND_MAX;
}
}
pcl::search::KdTree<pcl::PointXYZRGB> tree;
pcl::PointXYZRGB query;
query.x = 0.5;
query.y = 0.5;
query.z = 0.5;
vector<int> kd_indices;
vector<float> kd_distances;
vector<int> bf_indices;
vector<float> bf_distances;
double start, stop;
double kd_setup;
double kd_search;
double bf_setup;
double bf_search;
if (k > 0)
{
start = pcl::getTime ();
tree.setInputCloud (cloud);
stop = pcl::getTime ();
cout << "setting up kd tree: " << (kd_setup = stop - start) << endl;
start = pcl::getTime ();
tree.nearestKSearchT (query, k, kd_indices, kd_distances);
stop = pcl::getTime ();
cout << "single search with kd tree; " << (kd_search = stop - start) << " :: " << kd_indices[0] << " , " << kd_distances [0] << endl;
pcl::search::BruteForce<pcl::PointXYZRGB> brute_force;
start = pcl::getTime ();
brute_force.setInputCloud (cloud);
stop = pcl::getTime ();
cout << "setting up brute force search: " << (bf_setup = stop - start) << endl;
start = pcl::getTime ();
brute_force.nearestKSearchT (query, k, bf_indices, bf_distances);
stop = pcl::getTime ();
cout << "single search with brute force; " << (bf_search = stop - start) << " :: " << bf_indices[0] << " , " << bf_distances [0] << endl;
cout << "amortization after searches: " << (kd_setup - bf_setup) / (bf_search - kd_search) << endl;
}
else
{
start = pcl::getTime ();
tree.setInputCloud (cloud);
stop = pcl::getTime ();
cout << "setting up kd tree: " << (kd_setup = stop - start) << endl;
start = pcl::getTime ();
tree.radiusSearch (query, radius, kd_indices, kd_distances, k);
stop = pcl::getTime ();
cout << "single search with kd tree; " << (kd_search = stop - start) << " :: " << kd_indices[0] << " , " << kd_distances [0] << endl;
pcl::search::BruteForce<pcl::PointXYZRGB> brute_force;
start = pcl::getTime ();
brute_force.setInputCloud (cloud);
stop = pcl::getTime ();
cout << "setting up brute force search: " << (bf_setup = stop - start) << endl;
start = pcl::getTime ();
brute_force.radiusSearch (query, radius, bf_indices, bf_distances, k);
stop = pcl::getTime ();
cout << "single search with brute force; " << (bf_search = stop - start) << " :: " << bf_indices[0] << " , " << bf_distances [0] << endl;
cout << "amortization after searches: " << (kd_setup - bf_setup) / (bf_search - kd_search) << endl;
}
if (kd_indices.size () != bf_indices.size ())
{
cerr << "size of results do not match " <<kd_indices.size () << " vs. " << bf_indices.size () << endl;
}
else
{
cerr << "size of result: " <<kd_indices.size () << endl;
for (unsigned idx = 0; idx < kd_indices.size (); ++idx)
{
if (kd_indices[idx] != bf_indices[idx] && kd_distances[idx] != bf_distances[idx])
{
cerr << "results do not match: " << idx << " nearest neighbor: "
<< kd_indices[idx] << " with distance: " << kd_distances[idx] << " vs. "
<< bf_indices[idx] << " with distance: " << bf_distances[idx] << endl;
}
}
}
return (0);
}
<|endoftext|> |
<commit_before>// Filename: binaryXml.cxx
// Created by: drose (13Jul09)
//
////////////////////////////////////////////////////////////////////
//
// PANDA 3D SOFTWARE
// Copyright (c) Carnegie Mellon University. All rights reserved.
//
// All use of this software is subject to the terms of the revised BSD
// license. You should have received a copy of this license along
// with this source code in a file named "LICENSE."
//
////////////////////////////////////////////////////////////////////
#include "binaryXml.h"
#include <sstream>
static const bool debug_xml_output = true;
#define DO_BINARY_XML 1
enum NodeType {
NT_unknown,
NT_document,
NT_element,
NT_text,
};
////////////////////////////////////////////////////////////////////
// Function: write_xml_node
// Description: Recursively writes a node and all of its children to
// the given stream.
////////////////////////////////////////////////////////////////////
static void
write_xml_node(ostream &out, TiXmlNode *xnode) {
NodeType type = NT_element;
if (xnode->ToDocument() != NULL) {
type = NT_document;
} else if (xnode->ToElement() != NULL) {
type = NT_element;
} else if (xnode->ToText() != NULL) {
type = NT_text;
} else {
type = NT_unknown;
}
out.put((char)type);
// We don't bother to write any data for the unknown types.
if (type == NT_unknown) {
return;
}
const string &value = xnode->ValueStr();
size_t value_length = value.length();
out.write((char *)&value_length, sizeof(value_length));
out.write(value.data(), value_length);
if (type == NT_element) {
// Write the element attributes.
TiXmlElement *xelement = xnode->ToElement();
assert(xelement != NULL);
const TiXmlAttribute *xattrib = xelement->FirstAttribute();
while (xattrib != NULL) {
// We have an attribute.
out.put((char)true);
string name = xattrib->Name();
size_t name_length = name.length();
out.write((char *)&name_length, sizeof(name_length));
out.write(name.data(), name_length);
const string &value = xattrib->ValueStr();
size_t value_length = value.length();
out.write((char *)&value_length, sizeof(value_length));
out.write(value.data(), value_length);
xattrib = xattrib->Next();
}
// The end of the attributes list.
out.put((char)false);
}
// Now write all of the children.
TiXmlNode *xchild = xnode->FirstChild();
while (xchild != NULL) {
// We have a child.
out.put((char)true);
write_xml_node(out, xchild);
xchild = xchild->NextSibling();
}
// The end of the children list.
out.put((char)false);
}
////////////////////////////////////////////////////////////////////
// Function: read_xml_node
// Description: Recursively reads a node and all of its children to
// the given stream. Returns the newly-allocated node.
// The caller is responsible for eventually deleting the
// return value. Returns NULL on error.
////////////////////////////////////////////////////////////////////
static TiXmlNode *
read_xml_node(istream &in, char *&buffer, size_t &buffer_length) {
NodeType type = (NodeType)in.get();
if (type == NT_unknown) {
return NULL;
}
size_t value_length;
in.read((char *)&value_length, sizeof(value_length));
if (in.gcount() != sizeof(value_length)) {
return NULL;
}
if (value_length > buffer_length) {
delete[] buffer;
buffer_length = value_length;
buffer = new char[buffer_length];
}
in.read(buffer, value_length);
string value(buffer, value_length);
TiXmlNode *xnode = NULL;
if (type == NT_element) {
xnode = new TiXmlElement(value);
} else if (type == NT_document) {
xnode = new TiXmlDocument;
} else if (type == NT_text) {
xnode = new TiXmlText(value);
} else {
assert(false);
}
if (type == NT_element) {
// Read the element attributes.
TiXmlElement *xelement = xnode->ToElement();
assert(xelement != NULL);
bool got_attrib = (bool)(in.get() != 0);
while (got_attrib && in && !in.eof()) {
// We have an attribute.
size_t name_length;
in.read((char *)&name_length, sizeof(name_length));
if (in.gcount() != sizeof(name_length)) {
delete xnode;
return NULL;
}
if (name_length > buffer_length) {
delete[] buffer;
buffer_length = name_length;
buffer = new char[buffer_length];
}
in.read(buffer, name_length);
string name(buffer, name_length);
size_t value_length;
in.read((char *)&value_length, sizeof(value_length));
if (in.gcount() != sizeof(value_length)) {
delete xnode;
return NULL;
}
if (value_length > buffer_length) {
delete[] buffer;
buffer_length = value_length;
buffer = new char[buffer_length];
}
in.read(buffer, value_length);
string value(buffer, value_length);
xelement->SetAttribute(name, value);
got_attrib = (bool)(in.get() != 0);
}
}
// Now read all of the children.
bool got_child = (bool)(in.get() != 0);
while (got_child && in && !in.eof()) {
// We have a child.
TiXmlNode *xchild = read_xml_node(in, buffer, buffer_length);
if (xchild != NULL) {
xnode->LinkEndChild(xchild);
}
got_child = (bool)(in.get() != 0);
}
return xnode;
}
////////////////////////////////////////////////////////////////////
// Function: write_xml
// Description: Writes the indicated TinyXml document to the given
// stream.
////////////////////////////////////////////////////////////////////
void
write_xml(ostream &out, TiXmlDocument *doc, ostream &logfile) {
#ifdef DO_BINARY_XML
// Binary write.
write_xml_node(out, doc);
#else
// Formatted ASCII write.
// We need a declaration to write it safely.
TiXmlDeclaration decl("1.0", "utf-8", "");
doc->InsertBeforeChild(doc->FirstChild(), decl);
out << *doc;
#endif
out << flush;
if (debug_xml_output) {
// Write via ostringstream, so it all goes in one operation, to
// help out the interleaving from multiple threads.
ostringstream logout;
logout << "sent: " << *doc << "\n";
logfile << logout.str() << flush;
}
}
////////////////////////////////////////////////////////////////////
// Function: read_xml
// Description: Reads a TinyXml document from the given stream, and
// returns it. If the document is not yet available,
// blocks until it is, or until there is an error
// condition on the input.
//
// The return value is NULL if there is an error, or the
// newly-allocated document if it is successfully read.
// If not NULL, the document has been allocated with
// new, and should be eventually freed by the caller
// with delete.
////////////////////////////////////////////////////////////////////
TiXmlDocument *
read_xml(istream &in, ostream &logfile) {
#if DO_BINARY_XML
// binary read.
size_t buffer_length = 128;
char *buffer = new char[buffer_length];
TiXmlNode *xnode = read_xml_node(in, buffer, buffer_length);
delete[] buffer;
if (xnode == NULL) {
return NULL;
}
TiXmlDocument *doc = xnode->ToDocument();
assert(doc != NULL);
#else
// standard ASCII read.
TiXmlDocument *doc = new TiXmlDocument;
in >> *doc;
#endif
if (debug_xml_output) {
// Write via ostringstream, so it all goes in one operation, to
// help out the interleaving from multiple threads.
ostringstream logout;
logout << "received: " << *doc << "\n";
logfile << logout.str() << flush;
}
return doc;
}
<commit_msg>oops, debug output<commit_after>// Filename: binaryXml.cxx
// Created by: drose (13Jul09)
//
////////////////////////////////////////////////////////////////////
//
// PANDA 3D SOFTWARE
// Copyright (c) Carnegie Mellon University. All rights reserved.
//
// All use of this software is subject to the terms of the revised BSD
// license. You should have received a copy of this license along
// with this source code in a file named "LICENSE."
//
////////////////////////////////////////////////////////////////////
#include "binaryXml.h"
#include <sstream>
static const bool debug_xml_output = false;
#define DO_BINARY_XML 1
enum NodeType {
NT_unknown,
NT_document,
NT_element,
NT_text,
};
////////////////////////////////////////////////////////////////////
// Function: write_xml_node
// Description: Recursively writes a node and all of its children to
// the given stream.
////////////////////////////////////////////////////////////////////
static void
write_xml_node(ostream &out, TiXmlNode *xnode) {
NodeType type = NT_element;
if (xnode->ToDocument() != NULL) {
type = NT_document;
} else if (xnode->ToElement() != NULL) {
type = NT_element;
} else if (xnode->ToText() != NULL) {
type = NT_text;
} else {
type = NT_unknown;
}
out.put((char)type);
// We don't bother to write any data for the unknown types.
if (type == NT_unknown) {
return;
}
const string &value = xnode->ValueStr();
size_t value_length = value.length();
out.write((char *)&value_length, sizeof(value_length));
out.write(value.data(), value_length);
if (type == NT_element) {
// Write the element attributes.
TiXmlElement *xelement = xnode->ToElement();
assert(xelement != NULL);
const TiXmlAttribute *xattrib = xelement->FirstAttribute();
while (xattrib != NULL) {
// We have an attribute.
out.put((char)true);
string name = xattrib->Name();
size_t name_length = name.length();
out.write((char *)&name_length, sizeof(name_length));
out.write(name.data(), name_length);
const string &value = xattrib->ValueStr();
size_t value_length = value.length();
out.write((char *)&value_length, sizeof(value_length));
out.write(value.data(), value_length);
xattrib = xattrib->Next();
}
// The end of the attributes list.
out.put((char)false);
}
// Now write all of the children.
TiXmlNode *xchild = xnode->FirstChild();
while (xchild != NULL) {
// We have a child.
out.put((char)true);
write_xml_node(out, xchild);
xchild = xchild->NextSibling();
}
// The end of the children list.
out.put((char)false);
}
////////////////////////////////////////////////////////////////////
// Function: read_xml_node
// Description: Recursively reads a node and all of its children to
// the given stream. Returns the newly-allocated node.
// The caller is responsible for eventually deleting the
// return value. Returns NULL on error.
////////////////////////////////////////////////////////////////////
static TiXmlNode *
read_xml_node(istream &in, char *&buffer, size_t &buffer_length) {
NodeType type = (NodeType)in.get();
if (type == NT_unknown) {
return NULL;
}
size_t value_length;
in.read((char *)&value_length, sizeof(value_length));
if (in.gcount() != sizeof(value_length)) {
return NULL;
}
if (value_length > buffer_length) {
delete[] buffer;
buffer_length = value_length;
buffer = new char[buffer_length];
}
in.read(buffer, value_length);
string value(buffer, value_length);
TiXmlNode *xnode = NULL;
if (type == NT_element) {
xnode = new TiXmlElement(value);
} else if (type == NT_document) {
xnode = new TiXmlDocument;
} else if (type == NT_text) {
xnode = new TiXmlText(value);
} else {
assert(false);
}
if (type == NT_element) {
// Read the element attributes.
TiXmlElement *xelement = xnode->ToElement();
assert(xelement != NULL);
bool got_attrib = (bool)(in.get() != 0);
while (got_attrib && in && !in.eof()) {
// We have an attribute.
size_t name_length;
in.read((char *)&name_length, sizeof(name_length));
if (in.gcount() != sizeof(name_length)) {
delete xnode;
return NULL;
}
if (name_length > buffer_length) {
delete[] buffer;
buffer_length = name_length;
buffer = new char[buffer_length];
}
in.read(buffer, name_length);
string name(buffer, name_length);
size_t value_length;
in.read((char *)&value_length, sizeof(value_length));
if (in.gcount() != sizeof(value_length)) {
delete xnode;
return NULL;
}
if (value_length > buffer_length) {
delete[] buffer;
buffer_length = value_length;
buffer = new char[buffer_length];
}
in.read(buffer, value_length);
string value(buffer, value_length);
xelement->SetAttribute(name, value);
got_attrib = (bool)(in.get() != 0);
}
}
// Now read all of the children.
bool got_child = (bool)(in.get() != 0);
while (got_child && in && !in.eof()) {
// We have a child.
TiXmlNode *xchild = read_xml_node(in, buffer, buffer_length);
if (xchild != NULL) {
xnode->LinkEndChild(xchild);
}
got_child = (bool)(in.get() != 0);
}
return xnode;
}
////////////////////////////////////////////////////////////////////
// Function: write_xml
// Description: Writes the indicated TinyXml document to the given
// stream.
////////////////////////////////////////////////////////////////////
void
write_xml(ostream &out, TiXmlDocument *doc, ostream &logfile) {
#ifdef DO_BINARY_XML
// Binary write.
write_xml_node(out, doc);
#else
// Formatted ASCII write.
// We need a declaration to write it safely.
TiXmlDeclaration decl("1.0", "utf-8", "");
doc->InsertBeforeChild(doc->FirstChild(), decl);
out << *doc;
#endif
out << flush;
if (debug_xml_output) {
// Write via ostringstream, so it all goes in one operation, to
// help out the interleaving from multiple threads.
ostringstream logout;
logout << "sent: " << *doc << "\n";
logfile << logout.str() << flush;
}
}
////////////////////////////////////////////////////////////////////
// Function: read_xml
// Description: Reads a TinyXml document from the given stream, and
// returns it. If the document is not yet available,
// blocks until it is, or until there is an error
// condition on the input.
//
// The return value is NULL if there is an error, or the
// newly-allocated document if it is successfully read.
// If not NULL, the document has been allocated with
// new, and should be eventually freed by the caller
// with delete.
////////////////////////////////////////////////////////////////////
TiXmlDocument *
read_xml(istream &in, ostream &logfile) {
#if DO_BINARY_XML
// binary read.
size_t buffer_length = 128;
char *buffer = new char[buffer_length];
TiXmlNode *xnode = read_xml_node(in, buffer, buffer_length);
delete[] buffer;
if (xnode == NULL) {
return NULL;
}
TiXmlDocument *doc = xnode->ToDocument();
assert(doc != NULL);
#else
// standard ASCII read.
TiXmlDocument *doc = new TiXmlDocument;
in >> *doc;
#endif
if (debug_xml_output) {
// Write via ostringstream, so it all goes in one operation, to
// help out the interleaving from multiple threads.
ostringstream logout;
logout << "received: " << *doc << "\n";
logfile << logout.str() << flush;
}
return doc;
}
<|endoftext|> |
<commit_before>#include <SFML/Graphics.hpp>
#include <cmath>
#include <iostream>
int main()
{
sf::RenderWindow okno(sf::VideoMode(400, 400), "2048", sf::Style::Close);
sf::Clock stoper;
sf::Texture textura;
textura.loadFromFile("klocek.png");
sf::Sprite obraz;
obraz.setTexture(textura);
while (okno.isOpen())
{
sf::Event event;
while (okno.pollEvent(event))
{
if (event.type == sf::Event::Closed)
okno.close();
if (sf::Keyboard::isKeyPressed(sf::Keyboard::Right)) {
if(obraz.getPosition().x != 300.0)
obraz.move(100, 0);
}
if (sf::Keyboard::isKeyPressed(sf::Keyboard::Left)) {
if (obraz.getPosition().x != 0.0)
obraz.move(-100, 0);
}
if (sf::Keyboard::isKeyPressed(sf::Keyboard::Up)) {
if (obraz.getPosition().y != 0.0)
obraz.move(0, -100);
}
if (sf::Keyboard::isKeyPressed(sf::Keyboard::Down)) {
if (obraz.getPosition().y != 300.0)
obraz.move(0, 100);
}
}
okno.clear(sf::Color::Green);
okno.draw(obraz);
okno.display();
}
return 0;
}<commit_msg>Working on random appearance of block<commit_after>#include <SFML/Graphics.hpp>
#include <cmath>
#include <iostream>
#include <cstdlib>
#include <vector>
int main()
{
srand(time(NULL));
float pozX, pozY = 0.0;
//std::vector <float,float> currentPositions;
sf::RenderWindow okno(sf::VideoMode(400, 400), "2048", sf::Style::Close);
//pojedynczy klocek
sf::Texture textura;
textura.loadFromFile("klocek.png");
sf::Sprite obraz;
obraz.setTexture(textura);
while (okno.isOpen())
{
sf::Event event;
while (okno.pollEvent(event))
{
if (event.type == sf::Event::Closed)
okno.close();
}
/*if (event.type == sf::Event::KeyPressed) {
pozX = rand() % 4 + 0;
pozY = rand() % 4 + 0;
okno.draw(obraz);
obraz.setPosition(pozX*100, pozY*100);
currentPositions.emplace_back(pozX, pozY);
}*/
if (sf::Keyboard::isKeyPressed(sf::Keyboard::Right)) {
if (obraz.getPosition().x != 300.0)
obraz.move(0.25, 0);
}
if (sf::Keyboard::isKeyPressed(sf::Keyboard::Left)) {
if (obraz.getPosition().x != 0.0)
obraz.move(-0.25, 0);
}
if (sf::Keyboard::isKeyPressed(sf::Keyboard::Up)) {
if (obraz.getPosition().y != 0.0)
obraz.move(0, -0.25);
}
if (sf::Keyboard::isKeyPressed(sf::Keyboard::Down)) {
if (obraz.getPosition().y != 300.0)
obraz.move(0, 0.25);
}
okno.clear(sf::Color::Green);
okno.draw(obraz);
okno.display();
}
return 0;
}<|endoftext|> |
<commit_before>#ifndef WIGWAG_SIGNAL_POLICIES_HPP
#define WIGWAG_SIGNAL_POLICIES_HPP
// Copyright (c) 2016, Dmitry Koplyarov <koplyarov.da@gmail.com>
//
// Permission to use, copy, modify, and/or distribute this software for any purpose with or without fee is hereby granted,
// provided that the above copyright notice and this permission notice appear in all copies.
//
// THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS.
// IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS,
// WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
#include <wigwag/detail/enabler.hpp>
#include <wigwag/life_token.hpp>
#include <list>
#include <memory>
#include <mutex>
#include <vector>
#include <stdio.h>
namespace wigwag
{
namespace exception_handling
{
struct rethrow
{
void handle_std_exception(const std::exception& ex) const { throw; }
void handle_unknown_exception() const { throw; }
};
struct print_to_stderr
{
void handle_std_exception(const std::exception& ex) const { fprintf(stderr, "std::exception in signal handler: %s\n", ex.what()); }
void handle_unknown_exception() const { fprintf(stderr, "Unknown exception in signal handler!\n"); }
};
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
namespace threading
{
struct own_recursive_mutex
{
class lock_primitive
{
private:
mutable std::recursive_mutex _mutex;
public:
std::recursive_mutex& get_primitive() const { return _mutex; }
void lock_connect() const { _mutex.lock(); }
void unlock_connect() const { _mutex.unlock(); }
void lock_invoke() const { _mutex.lock(); }
void unlock_invoke() const { _mutex.unlock(); }
};
};
struct own_mutex
{
class lock_primitive
{
private:
mutable std::mutex _mutex;
public:
std::mutex& get_primitive() const { return _mutex; }
void lock_connect() const { _mutex.lock(); }
void unlock_connect() const { _mutex.unlock(); }
void lock_invoke() const
{
if (_mutex.try_lock())
{
_mutex.unlock();
throw std::runtime_error("A nonrecursive mutex should be locked outside of signal::operator()!");
}
}
void unlock_invoke() const { }
};
};
struct none
{
class lock_primitive
{
public:
void get_primitive() const { }
void lock_connect() const { }
void unlock_connect() const { }
void lock_invoke() const { }
void unlock_invoke() const { }
};
};
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
namespace state_populating
{
struct populator_only
{
template < typename Signature_ >
class handler_processor
{
using handler_processor_func = std::function<void(const std::function<Signature_>&)>;
private:
handler_processor_func _populator;
public:
handler_processor(handler_processor_func populator = &populator_only::handler_processor<Signature_>::empty_handler)
: _populator(populator)
{ }
void populate_state(const std::function<Signature_>& handler) const { _populator(handler); }
void withdraw_state(const std::function<Signature_>& handler) const { }
static void empty_handler(const std::function<Signature_>&) { }
};
};
struct populator_and_withdrawer
{
template < typename Signature_ >
class handler_processor
{
using handler_processor_func = std::function<void(const std::function<Signature_>&)>;
private:
handler_processor_func _populator;
handler_processor_func _withdrawer;
public:
handler_processor(handler_processor_func populator = &populator_only::handler_processor<Signature_>::empty_handler,
handler_processor_func withdrawer = &populator_only::handler_processor<Signature_>::empty_handler)
: _populator(populator), _withdrawer(withdrawer)
{ }
void populate_state(const std::function<Signature_>& handler) const { _populator(handler); }
void withdraw_state(const std::function<Signature_>& handler) const { _withdrawer(handler); }
static void empty_handler(const std::function<Signature_>&) { }
};
};
struct none
{
template < typename Signature_ >
struct handler_processor
{
void populate_state(const std::function<Signature_>& handler) const { }
void withdraw_state(const std::function<Signature_>& handler) const { }
};
};
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
namespace handlers_stack_container
{
struct vector
{
template < typename HandlerInfo_ >
using handlers_stack_container = std::vector<HandlerInfo_>;
};
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
namespace life_assurance
{
struct life_tokens
{
struct life_checker
{
life_token::checker checker;
life_checker(const life_token::checker& c) : checker(c) { }
};
struct execution_guard
{
life_token::execution_guard guard;
execution_guard(const life_checker& c) : guard(c.checker) { }
bool is_alive() const { return guard.is_alive(); }
};
class life_assurance
{
union life_token_storage
{
life_token token;
life_token_storage(life_token_storage&& other) noexcept
{
new(&token) life_token(std::move(other.token));
other.token.~life_token();
}
life_token_storage() { new(&token) life_token(); }
~life_token_storage() { }
};
life_token_storage _token_storage;
public:
life_checker get_life_checker() const { return life_checker(_token_storage.token); }
void release() { _token_storage.token.~life_token(); }
};
};
struct none
{
struct life_checker
{ };
struct execution_guard
{
execution_guard(const life_checker&) { }
bool is_alive() const { return true; }
};
struct life_assurance
{
life_checker get_life_checker() const { return life_checker(); }
void release() { }
};
};
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
namespace impl_storage
{
struct inplace
{
template < typename ExceptionHandler_, typename LockPrimitive_, typename HandlerProcessor_, typename HandlersContainer_ >
class storage : private ExceptionHandler_, private LockPrimitive_, private HandlerProcessor_, private HandlersContainer_
{
template< typename T_, typename... Args_ >
using con = std::is_constructible<T_, Args_...>;
public:
storage() { }
#define DETAIL_WIGWAG_STORAGE_CTOR_ENABLER(...) typename std::enable_if<__VA_ARGS__, detail::enabler>::type e = detail::enabler()
template < typename T_ > storage(T_ eh, DETAIL_WIGWAG_STORAGE_CTOR_ENABLER(con<ExceptionHandler_, T_&&>::value)) : ExceptionHandler_(std::move(eh)) { }
template < typename T_ > storage(T_ lp, DETAIL_WIGWAG_STORAGE_CTOR_ENABLER(con<LockPrimitive_, T_&&>::value)) : LockPrimitive_(std::move(lp)) { }
template < typename T_ > storage(T_ hp, DETAIL_WIGWAG_STORAGE_CTOR_ENABLER(con<HandlerProcessor_, T_&&>::value)) : HandlerProcessor_(std::move(hp)) { }
template < typename T_ > storage(T_ hc, DETAIL_WIGWAG_STORAGE_CTOR_ENABLER(con<HandlersContainer_, T_&&>::value)) : HandlersContainer_(std::move(hc)) { }
template < typename T_, typename U_ >
storage(T_ eh, U_ lp, DETAIL_WIGWAG_STORAGE_CTOR_ENABLER(con<ExceptionHandler_, T_&&>::value && con<LockPrimitive_, U_&&>::value))
: ExceptionHandler_(std::move(eh)), LockPrimitive_(std::move(lp))
{ }
template < typename T_, typename U_ >
storage(T_ eh, U_ hp, DETAIL_WIGWAG_STORAGE_CTOR_ENABLER(con<ExceptionHandler_, T_&&>::value && con<HandlerProcessor_, U_&&>::value))
: ExceptionHandler_(std::move(eh)), HandlerProcessor_(std::move(hp))
{ }
template < typename T_, typename U_ >
storage(T_ eh, U_ hc, DETAIL_WIGWAG_STORAGE_CTOR_ENABLER(con<ExceptionHandler_, T_&&>::value && con<HandlersContainer_, U_&&>::value))
: ExceptionHandler_(std::move(eh)), LockPrimitive_(std::move(hc))
{ }
template < typename T_, typename U_ >
storage(T_ lp, U_ hp, DETAIL_WIGWAG_STORAGE_CTOR_ENABLER(con<LockPrimitive_, T_&&>::value && con<HandlerProcessor_, U_&&>::value))
: LockPrimitive_(std::move(lp)), HandlerProcessor_(std::move(hp))
{ }
template < typename T_, typename U_ >
storage(T_ lp, U_ hc, DETAIL_WIGWAG_STORAGE_CTOR_ENABLER(con<LockPrimitive_, T_&&>::value && con<HandlersContainer_, U_&&>::value))
: LockPrimitive_(std::move(lp)), HandlersContainer_(std::move(hc))
{ }
template < typename T_, typename U_ >
storage(T_ hp, U_ hc, DETAIL_WIGWAG_STORAGE_CTOR_ENABLER(con<HandlerProcessor_, T_&&>::value && con<HandlersContainer_, U_&&>::value))
: HandlerProcessor_(std::move(hp)), HandlersContainer_(std::move(hc))
{ }
template < typename T_, typename U_, typename V_ >
storage(T_ lp, U_ hp, V_ hc, DETAIL_WIGWAG_STORAGE_CTOR_ENABLER(con<LockPrimitive_, T_&&>::value && con<HandlerProcessor_, U_&&>::value && con<HandlersContainer_, V_&&>::value))
: LockPrimitive_(std::move(lp)), HandlerProcessor_(std::move(hp)), HandlersContainer_(std::move(hc))
{ }
template < typename T_, typename U_, typename V_ >
storage(T_ eh, U_ hp, V_ hc, DETAIL_WIGWAG_STORAGE_CTOR_ENABLER(con<ExceptionHandler_, T_&&>::value && con<HandlerProcessor_, U_&&>::value && con<HandlersContainer_, V_&&>::value))
: ExceptionHandler_(std::move(eh)), HandlerProcessor_(std::move(hp)), HandlersContainer_(std::move(hc))
{ }
template < typename T_, typename U_, typename V_ >
storage(T_ eh, U_ lp, V_ hc, DETAIL_WIGWAG_STORAGE_CTOR_ENABLER(con<ExceptionHandler_, T_&&>::value && con<LockPrimitive_, U_&&>::value && con<HandlersContainer_, V_&&>::value))
: ExceptionHandler_(std::move(eh)), LockPrimitive_(std::move(lp)), HandlersContainer_(std::move(hc))
{ }
template < typename T_, typename U_, typename V_ >
storage(T_ eh, U_ lp, V_ hp, DETAIL_WIGWAG_STORAGE_CTOR_ENABLER(con<ExceptionHandler_, T_&&>::value && con<LockPrimitive_, U_&&>::value && con<HandlerProcessor_, V_&&>::value))
: ExceptionHandler_(std::move(eh)), LockPrimitive_(std::move(lp)), HandlerProcessor_(std::move(hp))
{ }
#undef DETAIL_WIGWAG_STORAGE_CTOR_ENABLER
storage(ExceptionHandler_ eh, LockPrimitive_ lp, HandlerProcessor_ hp, HandlersContainer_ hc) : ExceptionHandler_(std::move(eh)), LockPrimitive_(std::move(lp)), HandlerProcessor_(std::move(hp)), HandlersContainer_(std::move(hc)) { }
HandlersContainer_& get_handlers_container() { return *this; }
const HandlersContainer_& get_handlers_container() const { return *this; }
const LockPrimitive_& get_lock_primitive() const { return *this; }
const ExceptionHandler_& get_exception_handler() const { return *this; }
const HandlerProcessor_& get_handler_processor() const { return *this; }
};
};
struct shared
{
template < typename ExceptionHandler_, typename LockPrimitive_, typename HandlerProcessor_, typename HandlersContainer_ >
class storage
{
private:
using impl = inplace::storage<ExceptionHandler_, LockPrimitive_, HandlerProcessor_, HandlersContainer_>;
std::shared_ptr<impl> _impl;
public:
template < typename... Args_ >
storage(Args_... args)
: _impl(new impl(std::forward<Args_>(args)...))
{ }
HandlersContainer_& get_handlers_container() { return _impl->get_handlers_container(); }
const HandlersContainer_& get_handlers_container() const { return _impl->get_handlers_container(); }
const LockPrimitive_& get_lock_primitive() const { return _impl->get_lock_primitive(); }
const ExceptionHandler_& get_exception_handler() const { return _impl->get_exception_handler(); }
const HandlerProcessor_& get_handler_processor() const { return _impl->get_handler_processor(); }
};
template < typename ExceptionHandlingPolicy_, typename LockPrimitive_, typename HandlerProcessor_,typename HandlersContainer_ >
using storage_ref = storage<ExceptionHandlingPolicy_, LockPrimitive_, HandlerProcessor_, HandlersContainer_>;
};
}
}
#endif
<commit_msg>Removed empty line<commit_after>#ifndef WIGWAG_SIGNAL_POLICIES_HPP
#define WIGWAG_SIGNAL_POLICIES_HPP
// Copyright (c) 2016, Dmitry Koplyarov <koplyarov.da@gmail.com>
//
// Permission to use, copy, modify, and/or distribute this software for any purpose with or without fee is hereby granted,
// provided that the above copyright notice and this permission notice appear in all copies.
//
// THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS.
// IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS,
// WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
#include <wigwag/detail/enabler.hpp>
#include <wigwag/life_token.hpp>
#include <list>
#include <memory>
#include <mutex>
#include <vector>
#include <stdio.h>
namespace wigwag
{
namespace exception_handling
{
struct rethrow
{
void handle_std_exception(const std::exception& ex) const { throw; }
void handle_unknown_exception() const { throw; }
};
struct print_to_stderr
{
void handle_std_exception(const std::exception& ex) const { fprintf(stderr, "std::exception in signal handler: %s\n", ex.what()); }
void handle_unknown_exception() const { fprintf(stderr, "Unknown exception in signal handler!\n"); }
};
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
namespace threading
{
struct own_recursive_mutex
{
class lock_primitive
{
private:
mutable std::recursive_mutex _mutex;
public:
std::recursive_mutex& get_primitive() const { return _mutex; }
void lock_connect() const { _mutex.lock(); }
void unlock_connect() const { _mutex.unlock(); }
void lock_invoke() const { _mutex.lock(); }
void unlock_invoke() const { _mutex.unlock(); }
};
};
struct own_mutex
{
class lock_primitive
{
private:
mutable std::mutex _mutex;
public:
std::mutex& get_primitive() const { return _mutex; }
void lock_connect() const { _mutex.lock(); }
void unlock_connect() const { _mutex.unlock(); }
void lock_invoke() const
{
if (_mutex.try_lock())
{
_mutex.unlock();
throw std::runtime_error("A nonrecursive mutex should be locked outside of signal::operator()!");
}
}
void unlock_invoke() const { }
};
};
struct none
{
class lock_primitive
{
public:
void get_primitive() const { }
void lock_connect() const { }
void unlock_connect() const { }
void lock_invoke() const { }
void unlock_invoke() const { }
};
};
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
namespace state_populating
{
struct populator_only
{
template < typename Signature_ >
class handler_processor
{
using handler_processor_func = std::function<void(const std::function<Signature_>&)>;
private:
handler_processor_func _populator;
public:
handler_processor(handler_processor_func populator = &populator_only::handler_processor<Signature_>::empty_handler)
: _populator(populator)
{ }
void populate_state(const std::function<Signature_>& handler) const { _populator(handler); }
void withdraw_state(const std::function<Signature_>& handler) const { }
static void empty_handler(const std::function<Signature_>&) { }
};
};
struct populator_and_withdrawer
{
template < typename Signature_ >
class handler_processor
{
using handler_processor_func = std::function<void(const std::function<Signature_>&)>;
private:
handler_processor_func _populator;
handler_processor_func _withdrawer;
public:
handler_processor(handler_processor_func populator = &populator_only::handler_processor<Signature_>::empty_handler,
handler_processor_func withdrawer = &populator_only::handler_processor<Signature_>::empty_handler)
: _populator(populator), _withdrawer(withdrawer)
{ }
void populate_state(const std::function<Signature_>& handler) const { _populator(handler); }
void withdraw_state(const std::function<Signature_>& handler) const { _withdrawer(handler); }
static void empty_handler(const std::function<Signature_>&) { }
};
};
struct none
{
template < typename Signature_ >
struct handler_processor
{
void populate_state(const std::function<Signature_>& handler) const { }
void withdraw_state(const std::function<Signature_>& handler) const { }
};
};
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
namespace handlers_stack_container
{
struct vector
{
template < typename HandlerInfo_ >
using handlers_stack_container = std::vector<HandlerInfo_>;
};
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
namespace life_assurance
{
struct life_tokens
{
struct life_checker
{
life_token::checker checker;
life_checker(const life_token::checker& c) : checker(c) { }
};
struct execution_guard
{
life_token::execution_guard guard;
execution_guard(const life_checker& c) : guard(c.checker) { }
bool is_alive() const { return guard.is_alive(); }
};
class life_assurance
{
union life_token_storage
{
life_token token;
life_token_storage(life_token_storage&& other) noexcept
{
new(&token) life_token(std::move(other.token));
other.token.~life_token();
}
life_token_storage() { new(&token) life_token(); }
~life_token_storage() { }
};
life_token_storage _token_storage;
public:
life_checker get_life_checker() const { return life_checker(_token_storage.token); }
void release() { _token_storage.token.~life_token(); }
};
};
struct none
{
struct life_checker
{ };
struct execution_guard
{
execution_guard(const life_checker&) { }
bool is_alive() const { return true; }
};
struct life_assurance
{
life_checker get_life_checker() const { return life_checker(); }
void release() { }
};
};
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
namespace impl_storage
{
struct inplace
{
template < typename ExceptionHandler_, typename LockPrimitive_, typename HandlerProcessor_, typename HandlersContainer_ >
class storage : private ExceptionHandler_, private LockPrimitive_, private HandlerProcessor_, private HandlersContainer_
{
template< typename T_, typename... Args_ >
using con = std::is_constructible<T_, Args_...>;
public:
storage() { }
#define DETAIL_WIGWAG_STORAGE_CTOR_ENABLER(...) typename std::enable_if<__VA_ARGS__, detail::enabler>::type e = detail::enabler()
template < typename T_ > storage(T_ eh, DETAIL_WIGWAG_STORAGE_CTOR_ENABLER(con<ExceptionHandler_, T_&&>::value)) : ExceptionHandler_(std::move(eh)) { }
template < typename T_ > storage(T_ lp, DETAIL_WIGWAG_STORAGE_CTOR_ENABLER(con<LockPrimitive_, T_&&>::value)) : LockPrimitive_(std::move(lp)) { }
template < typename T_ > storage(T_ hp, DETAIL_WIGWAG_STORAGE_CTOR_ENABLER(con<HandlerProcessor_, T_&&>::value)) : HandlerProcessor_(std::move(hp)) { }
template < typename T_ > storage(T_ hc, DETAIL_WIGWAG_STORAGE_CTOR_ENABLER(con<HandlersContainer_, T_&&>::value)) : HandlersContainer_(std::move(hc)) { }
template < typename T_, typename U_ >
storage(T_ eh, U_ lp, DETAIL_WIGWAG_STORAGE_CTOR_ENABLER(con<ExceptionHandler_, T_&&>::value && con<LockPrimitive_, U_&&>::value))
: ExceptionHandler_(std::move(eh)), LockPrimitive_(std::move(lp))
{ }
template < typename T_, typename U_ >
storage(T_ eh, U_ hp, DETAIL_WIGWAG_STORAGE_CTOR_ENABLER(con<ExceptionHandler_, T_&&>::value && con<HandlerProcessor_, U_&&>::value))
: ExceptionHandler_(std::move(eh)), HandlerProcessor_(std::move(hp))
{ }
template < typename T_, typename U_ >
storage(T_ eh, U_ hc, DETAIL_WIGWAG_STORAGE_CTOR_ENABLER(con<ExceptionHandler_, T_&&>::value && con<HandlersContainer_, U_&&>::value))
: ExceptionHandler_(std::move(eh)), LockPrimitive_(std::move(hc))
{ }
template < typename T_, typename U_ >
storage(T_ lp, U_ hp, DETAIL_WIGWAG_STORAGE_CTOR_ENABLER(con<LockPrimitive_, T_&&>::value && con<HandlerProcessor_, U_&&>::value))
: LockPrimitive_(std::move(lp)), HandlerProcessor_(std::move(hp))
{ }
template < typename T_, typename U_ >
storage(T_ lp, U_ hc, DETAIL_WIGWAG_STORAGE_CTOR_ENABLER(con<LockPrimitive_, T_&&>::value && con<HandlersContainer_, U_&&>::value))
: LockPrimitive_(std::move(lp)), HandlersContainer_(std::move(hc))
{ }
template < typename T_, typename U_ >
storage(T_ hp, U_ hc, DETAIL_WIGWAG_STORAGE_CTOR_ENABLER(con<HandlerProcessor_, T_&&>::value && con<HandlersContainer_, U_&&>::value))
: HandlerProcessor_(std::move(hp)), HandlersContainer_(std::move(hc))
{ }
template < typename T_, typename U_, typename V_ >
storage(T_ lp, U_ hp, V_ hc, DETAIL_WIGWAG_STORAGE_CTOR_ENABLER(con<LockPrimitive_, T_&&>::value && con<HandlerProcessor_, U_&&>::value && con<HandlersContainer_, V_&&>::value))
: LockPrimitive_(std::move(lp)), HandlerProcessor_(std::move(hp)), HandlersContainer_(std::move(hc))
{ }
template < typename T_, typename U_, typename V_ >
storage(T_ eh, U_ hp, V_ hc, DETAIL_WIGWAG_STORAGE_CTOR_ENABLER(con<ExceptionHandler_, T_&&>::value && con<HandlerProcessor_, U_&&>::value && con<HandlersContainer_, V_&&>::value))
: ExceptionHandler_(std::move(eh)), HandlerProcessor_(std::move(hp)), HandlersContainer_(std::move(hc))
{ }
template < typename T_, typename U_, typename V_ >
storage(T_ eh, U_ lp, V_ hc, DETAIL_WIGWAG_STORAGE_CTOR_ENABLER(con<ExceptionHandler_, T_&&>::value && con<LockPrimitive_, U_&&>::value && con<HandlersContainer_, V_&&>::value))
: ExceptionHandler_(std::move(eh)), LockPrimitive_(std::move(lp)), HandlersContainer_(std::move(hc))
{ }
template < typename T_, typename U_, typename V_ >
storage(T_ eh, U_ lp, V_ hp, DETAIL_WIGWAG_STORAGE_CTOR_ENABLER(con<ExceptionHandler_, T_&&>::value && con<LockPrimitive_, U_&&>::value && con<HandlerProcessor_, V_&&>::value))
: ExceptionHandler_(std::move(eh)), LockPrimitive_(std::move(lp)), HandlerProcessor_(std::move(hp))
{ }
#undef DETAIL_WIGWAG_STORAGE_CTOR_ENABLER
storage(ExceptionHandler_ eh, LockPrimitive_ lp, HandlerProcessor_ hp, HandlersContainer_ hc) : ExceptionHandler_(std::move(eh)), LockPrimitive_(std::move(lp)), HandlerProcessor_(std::move(hp)), HandlersContainer_(std::move(hc)) { }
HandlersContainer_& get_handlers_container() { return *this; }
const HandlersContainer_& get_handlers_container() const { return *this; }
const LockPrimitive_& get_lock_primitive() const { return *this; }
const ExceptionHandler_& get_exception_handler() const { return *this; }
const HandlerProcessor_& get_handler_processor() const { return *this; }
};
};
struct shared
{
template < typename ExceptionHandler_, typename LockPrimitive_, typename HandlerProcessor_, typename HandlersContainer_ >
class storage
{
private:
using impl = inplace::storage<ExceptionHandler_, LockPrimitive_, HandlerProcessor_, HandlersContainer_>;
std::shared_ptr<impl> _impl;
public:
template < typename... Args_ >
storage(Args_... args)
: _impl(new impl(std::forward<Args_>(args)...))
{ }
HandlersContainer_& get_handlers_container() { return _impl->get_handlers_container(); }
const HandlersContainer_& get_handlers_container() const { return _impl->get_handlers_container(); }
const LockPrimitive_& get_lock_primitive() const { return _impl->get_lock_primitive(); }
const ExceptionHandler_& get_exception_handler() const { return _impl->get_exception_handler(); }
const HandlerProcessor_& get_handler_processor() const { return _impl->get_handler_processor(); }
};
template < typename ExceptionHandlingPolicy_, typename LockPrimitive_, typename HandlerProcessor_,typename HandlersContainer_ >
using storage_ref = storage<ExceptionHandlingPolicy_, LockPrimitive_, HandlerProcessor_, HandlersContainer_>;
};
}
}
#endif
<|endoftext|> |
<commit_before>/*
* yafdb - Yet Another Face Detection and Bluring
*
* Copyright (c) 2014 FOXEL SA - http://foxel.ch
* Please read <http://foxel.ch/license> for more information.
*
*
* Author(s):
*
* Antony Ducommun <nitro@tmsrv.org>
*
*
* This file is part of the FOXEL project <http://foxel.ch>.
*
* This program 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.
*
* 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 Affero 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/>.
*
*
* Additional Terms:
*
* You are required to preserve legal notices and author attributions in
* that material or in the Appropriate Legal Notices displayed by works
* containing it.
*
* You are required to attribute the work as explained in the "Usage and
* Attribution" section of <http://foxel.ch/license>.
*/
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include <errno.h>
#include <getopt.h>
#include <string>
#include <list>
#include <vector>
#include <opencv2/opencv.hpp>
#include <opencv2/highgui/highgui.hpp>
/*
* Program arguments.
*
*/
static const char *source_file = NULL;
static const char *mask_file = NULL;
static const char *objects_file = NULL;
static struct option options[] = {
{"algorithm", required_argument, 0, 'a'},
{0, 0, 0, 0}
};
/**
* Display program usage.
*
*/
void usage() {
printf("yafdb-test input-image.tiff mask-image.tiff input-objects.txt\n\n");
printf("Compute the detection error rate by comparing optimal area given in\n");
printf("reference bitmap mask (black=none, white=object) to the detected area\n");
printf("given in input text file.\n\n");
}
/**
* Program entry-point.
*
*/
int main(int argc, char **argv) {
// parse arguments
while (true) {
int index = -1;
getopt_long(argc, argv, "", options, &index);
if (index == -1) {
if (argc != optind + 3) {
usage();
return 1;
}
source_file = argv[optind++];
if (access(source_file, R_OK)) {
fprintf(stderr, "Error: source file not readable: %s\n", source_file);
return 2;
}
mask_file = argv[optind++];
if (access(mask_file, R_OK)) {
fprintf(stderr, "Error: mask file not readable: %s\n", mask_file);
return 2;
}
objects_file = argv[optind++];
if (access(objects_file, R_OK)) {
fprintf(stderr, "Error: detected objects file not readable: %s\n", objects_file);
return 2;
}
break;
}
usage();
return 1;
}
// read source file
cv::Mat source = cv::imread(source_file);
if (source.rows <= 0 || source.cols <= 0) {
fprintf(stderr, "Error: cannot read image in source file: %s\n", source_file);
return 2;
}
// read mask file
cv::Mat mask = cv::imread(mask_file);
if (mask.rows != source.rows || mask.cols != source.cols) {
fprintf(stderr, "Error: cannot read image in mask file or mask is incompatible: %s\n", mask_file);
return 2;
}
// TODO: read detected objects
// TODO: compute error rate
return 0;
}
<commit_msg>Fixed yafdb-test args<commit_after>/*
* yafdb - Yet Another Face Detection and Bluring
*
* Copyright (c) 2014 FOXEL SA - http://foxel.ch
* Please read <http://foxel.ch/license> for more information.
*
*
* Author(s):
*
* Antony Ducommun <nitro@tmsrv.org>
*
*
* This file is part of the FOXEL project <http://foxel.ch>.
*
* This program 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.
*
* 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 Affero 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/>.
*
*
* Additional Terms:
*
* You are required to preserve legal notices and author attributions in
* that material or in the Appropriate Legal Notices displayed by works
* containing it.
*
* You are required to attribute the work as explained in the "Usage and
* Attribution" section of <http://foxel.ch/license>.
*/
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include <errno.h>
#include <getopt.h>
#include <string>
#include <list>
#include <vector>
#include <opencv2/opencv.hpp>
#include <opencv2/highgui/highgui.hpp>
/*
* Program arguments.
*
*/
static const char *source_file = NULL;
static const char *mask_file = NULL;
static const char *objects_file = NULL;
static struct option options[] = {
{0, 0, 0, 0}
};
/**
* Display program usage.
*
*/
void usage() {
printf("yafdb-test input-image.tiff mask-image.tiff input-objects.txt\n\n");
printf("Compute the detection error rate by comparing optimal area given in\n");
printf("reference bitmap mask (black=none, white=object) to the detected area\n");
printf("given in input text file.\n\n");
}
/**
* Program entry-point.
*
*/
int main(int argc, char **argv) {
// parse arguments
while (true) {
int index = -1;
getopt_long(argc, argv, "", options, &index);
if (index == -1) {
if (argc != optind + 3) {
usage();
return 1;
}
source_file = argv[optind++];
if (access(source_file, R_OK)) {
fprintf(stderr, "Error: source file not readable: %s\n", source_file);
return 2;
}
mask_file = argv[optind++];
if (access(mask_file, R_OK)) {
fprintf(stderr, "Error: mask file not readable: %s\n", mask_file);
return 2;
}
objects_file = argv[optind++];
if (access(objects_file, R_OK)) {
fprintf(stderr, "Error: detected objects file not readable: %s\n", objects_file);
return 2;
}
break;
}
usage();
return 1;
}
// read source file
cv::Mat source = cv::imread(source_file);
if (source.rows <= 0 || source.cols <= 0) {
fprintf(stderr, "Error: cannot read image in source file: %s\n", source_file);
return 2;
}
// read mask file
cv::Mat mask = cv::imread(mask_file);
if (mask.rows != source.rows || mask.cols != source.cols) {
fprintf(stderr, "Error: cannot read image in mask file or mask is incompatible: %s\n", mask_file);
return 2;
}
// TODO: read detected objects
// TODO: compute error rate
return 0;
}
<|endoftext|> |
<commit_before>#include "CD.H"
#include "GAMEWAD.H"
#include "SPECIFIC.H"
#include <stdio.h>
#include <assert.h>
//Number of XA files on disc (XA1-17.XA)
#define NUM_XA_FILES 17
#ifdef PSX
#define XA_FILE_NAME "\XA%d.XA;1"
#else
#define XA_FILE_NAME "XA%d.XA"
#endif
unsigned short XATrackClip[136];
short XAFadeRate;
int current_cd_mode;
int XACurPos;
int XAEndPos;
short XAVolume;
short XAReqVolume;
short XAMasterVolume;
short XATrack;
short XAReqTrack;
char XAFlag;
char XAWait;
static char XARepeat;
int XAStartPos;
static int XATrackList[17][2];
#ifdef PSX
#include <sys/types.h>
#include <LIBCD.H>
#include <LIBSPU.H>
#endif
void cbvsync()//5D884(<), 5DD00(<)
{
int ret;//$a1
unsigned char io[8];//$sp-16
int cnt;//$v0
switch (XAFlag - 1)
{
case 0:
{
if (XAVolume == 0)
{
XAFlag++;
}
goto dflt;
break;
}
case 1:
{
cnt = XATrack = XAReqTrack;
if (XAReqTrack < 0)
{
cnt += 7;
}
//loc_5D8F8
io[0] = 1;
io[1] = XATrack & 7;
XAStartPos = XATrackList[cnt][0];
XAEndPos = XATrackList[cnt][1] + XATrackClip[XAReqTrack];
XACurPos = XAStartPos;
#ifdef PSX
CdControlF(0xD, &io);
#endif
XAFlag++;
//loc_5D8D8
goto dflt;
break;
}
case 2:
{
//loc_5D980
XAReplay();
XAReqVolume = XAMasterVolume;
XAFlag++;
goto dflt;
break;
}
case 3:
{
//loc_5D9AC
if (XAVolume == XAMasterVolume)
{
XAFlag++;
XAWait = 60;
}
goto dflt;
break;
}
case 4:
{
//loc_5D9E0
if (XAWait == 0)
{
XAFlag++;
}
XAWait--;
goto dflt;
break;
}
case 5:
{
//loc_5DA18
#ifdef PSX
VSync(-1);
#endif
if (XAFlag & 7)
{
#ifdef PSX
ret = CdSync(0, &io[0]);
if (ret == 5)
{
XAReplay();
}
else if (ret == 2)
{
if (XACurPos < XAEndPos)
{
//loc_5DAEC
if (CdLastCom() == 0x11);
{
cnt = CdPosToInt(&io[5]);
if (cnt > 0)
{
XACurPos = cnt;
}
CdControlF(&io[5], 0);
}
}
else if (XARepeat == 0)
{
//loc_5DA84
if (CurrentAtmosphere == 0)
{
CdControlB(9, 0, 0);
XAFlag = 7;
}
else
{
//loc_5DAB8
XAVolume = 0;
XARepeat = 1;
XAFlag = ret;
XAReqTrack = CurrentAtmosphere;
CDDA_SetVolume(0);
IsAtmospherePlaying = 1;
}
}
else
{
XAReplay();
}
}
goto dflt;
#endif
}
break;
}
default:
dflt:
//def_5D8B8
if (XAVolume < XAReqVolume)
{
XAVolume += XAFadeRate;
if (XAVolume < XAReqVolume)
{
XAVolume = XAReqVolume;
}//loc_5DB78
CDDA_SetVolume(XAVolume);
}
else
{
//loc_5DB94
if (XAReqVolume < XAVolume)
{
XAVolume -= XAFadeRate;
if (!(XAReqVolume < XAVolume))
{
XAVolume = XAReqVolume;
}
//loc_5DBEC
CDDA_SetVolume(XAVolume);
}//loc_5DC00
}
//loc_5DC00
break;
}
//loc_5DC00
return;
}
void InitNewCDSystem()//5DDE8, 5E264(<)
{
#ifdef PSX
struct CdlFILE fp;
int test;
unsigned char param[8];//FIXME incorrect
DEL_ChangeCDMode(0);
if (CdSearchFile(&fp, GAMEWAD_FILENAME))
{
printf("FOUND:%s\n", GAMEWAD_FILENAME);
}
CdControlB(CdlSetloc, ¶m, 0);//6956C
CdRead(1, &gwHeader, 0x80); //69C4C
//..
//jal sub_5F6AC //memcpy(&gwHeader, sizeof(GAMEWAD_header);
test = 0xDEAD;
test++;
#else
FILE* fileHandle = fopen(GAMEWAD_FILENAME, "rb");
assert(fileHandle);
fread(&gwHeader, sizeof(GAMEWAD_header), 1, fileHandle);
fclose(fileHandle);
//FIXME: CdPosToInt(); returns LBA for GAMEWAD.OBJ on disc.
gwLba = 24;
#ifdef PSX
//jal sub_66270 //CdPosToInt();
#endif
char buf[10];//FIXME
for (int i = 0; i < NUM_XA_FILES; i++)
{
sprintf(buf, XA_FILE_NAME, i + 1);
#ifdef PSX
//jal sub_662F0 //CdSearchFile(&fp, buf);
#endif
FILE* fileHandle = fopen(buf, "rb");
assert(fileHandle);
fseek(fileHandle, 0, SEEK_END);
XATrackList[i][0] = -1;//FIXME: This value is returned by CdPosToInt(); register is v0. It returns the LBA of the XA file on disc.
XATrackList[i][1] = XATrackList[i][0] + ((ftell(fileHandle) + 0x7FF) / CD_SECTOR_SIZE);
fclose(fileHandle);
}
XAFlag = 0;
XAVolume = 0;
XAReqTrack = -1;
XATrack = -1;
#endif
}
void DEL_ChangeCDMode(int mode)//5DEB0(<), ?
{
unsigned char param[4];
if (mode == 0 && current_cd_mode != 0)
{
current_cd_mode = 0;
//param[0] = 0x80;
//CdControlB(0xE, ¶m[0], 0);
//VSync(3);
}
else if (mode == 1 && current_cd_mode != mode)
{
//loc_5DEF8
current_cd_mode = mode;
}
else if (mode == 2 && current_cd_mode != mode)
{
//loc_5DF20
current_cd_mode = mode;
//param[0] = 0x80;
//CdControlB(0xE, ¶m[0], 0);
//VSync(3);
}
//loc_5DF58
return;
}
//Play audio track
void S_CDPlay(short track, int mode)
{
//unsigned char param[4];
S_Warn("[S_CDPlay] - unimplemented!\n");
}
void S_CDStop()
{
S_Warn("[S_CDStop] - unimplemented!\n");
}
void CDDA_SetMasterVolume(int nVolume)//5DDC4(<), 5E240(<) (F)
{
XAMasterVolume = nVolume;
CDDA_SetVolume(nVolume);
}
void CDDA_SetVolume(int nVolume)//5D7FC(<), 5DC78(<) (F)
{
struct SpuCommonAttr attr;
attr.cd.volume.left = nVolume * 64;
attr.cd.volume.right = nVolume * 64;
#ifdef PSX
attr.mask = SPU_COMMON_CDVOLL | SPU_COMMON_CDVOLR | SPU_COMMON_CDMIX;
attr.cd.mix = SPU_ON;
SpuSetCommonAttr(&attr);
#endif
}
void XAReplay()//5D838, ?
{
struct CdlLOC loc;
S_Warn("[XAReplay] - unimplemented!\n");
}<commit_msg>InitNewCDSystem() PSX Support.<commit_after>#include "CD.H"
#include "CONTROL.H"
#include "GAMEWAD.H"
#include "SPECIFIC.H"
#include <stdio.h>
#include <string.h>
#include <assert.h>
//Number of XA files on disc (XA1-17.XA)
#define NUM_XA_FILES 17
#ifdef PSX
#define XA_FILE_NAME "\\XA%d.XA;1"
#else
#define XA_FILE_NAME "XA%d.XA"
#endif
unsigned short XATrackClip[136];
short XAFadeRate;
int current_cd_mode;
int XACurPos;
int XAEndPos;
short XAVolume;
short XAReqVolume;
short XAMasterVolume;
short XATrack;
short XAReqTrack;
char XAFlag;
char XAWait;
static char XARepeat;
int XAStartPos;
static int XATrackList[17][2];
#ifdef PSX
#include <sys/types.h>
#include <LIBCD.H>
#include <LIBSPU.H>
#endif
void cbvsync()//5D884(<), 5DD00(<)
{
int ret;//$a1
unsigned char io[8];//$sp-16
int cnt;//$v0
switch (XAFlag - 1)
{
case 0:
{
if (XAVolume == 0)
{
XAFlag++;
}
goto dflt;
break;
}
case 1:
{
cnt = XATrack = XAReqTrack;
if (XAReqTrack < 0)
{
cnt += 7;
}
//loc_5D8F8
io[0] = 1;
io[1] = XATrack & 7;
XAStartPos = XATrackList[cnt][0];
XAEndPos = XATrackList[cnt][1] + XATrackClip[XAReqTrack];
XACurPos = XAStartPos;
#ifdef PSX
CdControlF(0xD, &io);
#endif
XAFlag++;
//loc_5D8D8
goto dflt;
break;
}
case 2:
{
//loc_5D980
XAReplay();
XAReqVolume = XAMasterVolume;
XAFlag++;
goto dflt;
break;
}
case 3:
{
//loc_5D9AC
if (XAVolume == XAMasterVolume)
{
XAFlag++;
XAWait = 60;
}
goto dflt;
break;
}
case 4:
{
//loc_5D9E0
if (XAWait == 0)
{
XAFlag++;
}
XAWait--;
goto dflt;
break;
}
case 5:
{
//loc_5DA18
#ifdef PSX
VSync(-1);
#endif
if (XAFlag & 7)
{
#ifdef PSX
ret = CdSync(0, &io[0]);
if (ret == 5)
{
XAReplay();
}
else if (ret == 2)
{
if (XACurPos < XAEndPos)
{
//loc_5DAEC
if (CdLastCom() == 0x11);
{
cnt = CdPosToInt(&io[5]);
if (cnt > 0)
{
XACurPos = cnt;
}
CdControlF(&io[5], 0);
}
}
else if (XARepeat == 0)
{
//loc_5DA84
if (CurrentAtmosphere == 0)
{
CdControlB(9, 0, 0);
XAFlag = 7;
}
else
{
//loc_5DAB8
XAVolume = 0;
XARepeat = 1;
XAFlag = ret;
XAReqTrack = CurrentAtmosphere;
CDDA_SetVolume(0);
IsAtmospherePlaying = 1;
}
}
else
{
XAReplay();
}
}
goto dflt;
#endif
}
break;
}
default:
dflt:
//def_5D8B8
if (XAVolume < XAReqVolume)
{
XAVolume += XAFadeRate;
if (XAVolume < XAReqVolume)
{
XAVolume = XAReqVolume;
}//loc_5DB78
CDDA_SetVolume(XAVolume);
}
else
{
//loc_5DB94
if (XAReqVolume < XAVolume)
{
XAVolume -= XAFadeRate;
if (!(XAReqVolume < XAVolume))
{
XAVolume = XAReqVolume;
}
//loc_5DBEC
CDDA_SetVolume(XAVolume);
}//loc_5DC00
}
//loc_5DC00
break;
}
//loc_5DC00
return;
}
#ifdef PSX
struct CdlFILE fp;
#endif
void InitNewCDSystem()//5DDE8, 5E264(<) (F)
{
char buf[10];
int i = 0;
long local_wadfile_header[512];
#ifdef PSX
DEL_ChangeCDMode(0);
CdSearchFile(&fp, GAMEWAD_FILENAME);
CdControlB(CdlSetloc, &fp, 0);//6956C
CdRead(1, &local_wadfile_header, 0x80); //69C4C
while (CdReadSync(1, 0) > 0)
{
VSync(0);
}
memcpy(&gwHeader, &local_wadfile_header, 512);//5F6AC
gwLba = CdPosToInt(&fp.pos);//66270
#else
FILE* fileHandle = fopen(GAMEWAD_FILENAME, "rb");
assert(fileHandle);
fread(&local_wadfile_header, sizeof(GAMEWAD_header), 1, fileHandle);
fclose(fileHandle);
memcpy(&gwHeader, &local_wadfile_header, sizeof(GAMEWAD_header));//5F6AC
//FIXME: CdPosToInt(); returns LBA for GAMEWAD.OBJ on disc.
gwLba = 24;
#endif
//loc_5E2E8
for (i = 0; i < NUM_XA_FILES; i++)
{
sprintf(buf, XA_FILE_NAME, i + 1);
#ifdef PSX
CdSearchFile(&fp, buf);
XATrackList[i][0] = CdPosToInt(&fp.pos);
XATrackList[i][1] = XATrackList[i][0] + ((fp.size + 0x7FF) / CD_SECTOR_SIZE);
#else
FILE* fileHandle = fopen(buf, "rb");
assert(fileHandle);
fseek(fileHandle, 0, SEEK_END);
XATrackList[i][0] = -1;//FIXME: This value is returned by CdPosToInt(); register is v0. It returns the LBA of the XA file on disc.
XATrackList[i][1] = XATrackList[i][0] + ((ftell(fileHandle) + 0x7FF) / CD_SECTOR_SIZE);
fclose(fileHandle);
#endif
}
XAFlag = 0;
XAVolume = 0;
XAReqTrack = -1;
XATrack = -1;
}
void DEL_ChangeCDMode(int mode)//5DEB0(<), ?
{
unsigned char param[4];
if (mode == 0 && current_cd_mode != 0)
{
current_cd_mode = 0;
#ifdef PSX
param[0] = CdlModeSpeed;
CdControlB(CdlSetmode, param, 0);
VSync(3);
#endif
}
else if (mode == 1 && current_cd_mode != mode)
{
//loc_5DEF8
current_cd_mode = mode;
}
else if (mode == 2 && current_cd_mode != mode)
{
//loc_5DF20
current_cd_mode = mode;
#ifdef PSX
param[0] = CdlModeSpeed;
CdControlB(CdlSetmode, param, 0);
VSync(3);
#endif
}
//loc_5DF58
return;
}
//Play audio track
void S_CDPlay(short track, int mode)
{
//unsigned char param[4];
S_Warn("[S_CDPlay] - unimplemented!\n");
}
void S_CDStop()
{
S_Warn("[S_CDStop] - unimplemented!\n");
}
void CDDA_SetMasterVolume(int nVolume)//5DDC4(<), 5E240(<) (F)
{
XAMasterVolume = nVolume;
CDDA_SetVolume(nVolume);
}
void CDDA_SetVolume(int nVolume)//5D7FC(<), 5DC78(<) (F)
{
struct SpuCommonAttr attr;
attr.cd.volume.left = nVolume * 64;
attr.cd.volume.right = nVolume * 64;
#ifdef PSX
attr.mask = SPU_COMMON_CDVOLL | SPU_COMMON_CDVOLR | SPU_COMMON_CDMIX;
attr.cd.mix = SPU_ON;
SpuSetCommonAttr(&attr);
#endif
}
void XAReplay()//5D838, ?
{
struct CdlLOC loc;
S_Warn("[XAReplay] - unimplemented!\n");
}<|endoftext|> |
<commit_before>#include<iostream>
#define _USE_MATH_DEFINES
#include<cmath>
#include<cassert>
#include<thread>
#include<chrono>
#include "ics3/ics"
int main(int argc, char **argv) {
{
ics::ID id(2);
ics::Angle degree = ics::Angle::newDegree();
try {
ics::ICS3 ics("/dev/ttyUSB0", ics::ICSBaudrate::RATE115200);
assert(7500 == degree.getRaw());
ics::Angle nowPos = ics.move(id, degree);
std::cout << nowPos.get() << std::endl;
std::this_thread::sleep_for(std::chrono::milliseconds(1000));
degree.set(50);
nowPos = ics.move(id, degree);
std::cout << nowPos.get() << std::endl;
std::this_thread::sleep_for(std::chrono::milliseconds(1000));
degree.set(-50);
nowPos = ics.move(id, degree);
std::cout << nowPos.get() << std::endl;
std::this_thread::sleep_for(std::chrono::milliseconds(1000));
degree.set(0);
nowPos = ics.move(id, degree);
std::cout << nowPos.get() << std::endl;
nowPos = ics.free(id);
std::cout << nowPos.get() << std::endl;
} catch (std::runtime_error& e) {
std::cout << e.what() << std::endl;
}
}
{
std::cout << std::endl << "ID test section" << std::endl;
ics::ID id {0};
assert(id == 0);
assert(id == 0);
ics::ID id31 {31};
assert(id31 == 31);
assert(id31.get() == 31);
try {
ics::ID id32 {32};
assert(false);
} catch (std::invalid_argument& e) {
std::cout << e.what() << std::endl;
}
}
{
std::cout << std::endl << "EepParam test section" << std::endl;
ics::EepParam speed = ics::EepParam::speed();
assert(127 == speed.get());
speed.set(100);
assert(100 == speed.get());
try {
speed.set(200);
std::cerr << "Never run this" << std::endl;
} catch (std::invalid_argument& e) {
std::cout << e.what() << std::endl;
}
}
{
std::cout << std::endl << "angle test section" << std::endl;
ics::Angle degree = ics::Angle::newDegree();
ics::Angle radian = ics::Angle::newRadian();
assert(degree.getRaw() == radian.getRaw());
degree.set(0);
radian.set(0);
assert(degree.getRaw() == radian.getRaw());
degree.set(90);
radian.set(M_PI / 2);
assert(degree.getRaw() == radian.getRaw());
degree.set(60);
radian.set(M_PI / 3);
assert(degree.getRaw() == radian.getRaw());
try {
degree.set(150);
std::cerr << "Never run this" << std::endl;
} catch (const std::invalid_argument& e) {
std::cout << e.what() << std::endl;
}
try {
radian.set(M_PI);
std::cerr << "Never run this" << std::endl;
} catch (const std::invalid_argument& e) {
std::cout << e.what() << std::endl;
}
}
{
std::cout << std::endl << "angle factory test section" << std::endl;
ics::Angle degree = ics::Angle::newDegree(90);
ics::Angle radian = ics::Angle::newRadian(M_PI / 2);
assert(degree.getRaw() == radian.getRaw());
}
{
std::cout << std::endl << "parameter test section" << std::endl;
ics::Parameter current = ics::Parameter::current();
assert(63 == current.get());
current.set(30);
assert(30 == current.get());
try {
current.set(70);
std::cerr << "Never run this" << std::endl;
} catch (const std::invalid_argument& e) {
std::cout << e.what() << std::endl;
}
}
return 0;
}
<commit_msg>Update testcode for readability<commit_after>#include<iostream>
#define _USE_MATH_DEFINES
#include<cmath>
#include<cassert>
#include<thread>
#include<chrono>
#include "ics3/ics"
int main(int argc, char **argv) {
{
std::cout << std::endl << "ICS3 test section" << std::endl;
ics::ID id(2);
ics::Angle degree = ics::Angle::newDegree();
try {
ics::ICS3 ics("/dev/ttyUSB0");
assert(7500 == degree.getRaw());
ics::Angle nowPos = ics.move(id, degree);
std::cout << nowPos.get() << std::endl;
std::this_thread::sleep_for(std::chrono::milliseconds(1000));
degree.set(50);
nowPos = ics.move(id, degree);
std::cout << nowPos.get() << std::endl;
std::this_thread::sleep_for(std::chrono::milliseconds(1000));
degree.set(-50);
nowPos = ics.move(id, degree);
std::cout << nowPos.get() << std::endl;
std::this_thread::sleep_for(std::chrono::milliseconds(1000));
degree.set(0);
nowPos = ics.move(id, degree);
std::cout << nowPos.get() << std::endl;
nowPos = ics.free(id);
std::cout << nowPos.get() << std::endl;
} catch (std::runtime_error& e) {
std::cout << e.what() << std::endl;
}
}
{
std::cout << std::endl << "ID test section" << std::endl;
ics::ID id {0};
assert(id == 0);
assert(id == 0);
ics::ID id31 {31};
assert(id31 == 31);
assert(id31.get() == 31);
try {
ics::ID id32 {32};
assert(false);
} catch (std::invalid_argument& e) {
std::cout << e.what() << std::endl;
}
}
{
std::cout << std::endl << "EepParam test section" << std::endl;
ics::EepParam speed = ics::EepParam::speed();
assert(127 == speed.get());
speed.set(100);
assert(100 == speed.get());
try {
speed.set(200);
std::cerr << "Never run this" << std::endl;
} catch (std::invalid_argument& e) {
std::cout << e.what() << std::endl;
}
}
{
std::cout << std::endl << "angle test section" << std::endl;
ics::Angle degree = ics::Angle::newDegree();
ics::Angle radian = ics::Angle::newRadian();
assert(degree.getRaw() == radian.getRaw());
degree.set(0);
radian.set(0);
assert(degree.getRaw() == radian.getRaw());
degree.set(90);
radian.set(M_PI / 2);
assert(degree.getRaw() == radian.getRaw());
degree.set(60);
radian.set(M_PI / 3);
assert(degree.getRaw() == radian.getRaw());
try {
degree.set(150);
std::cerr << "Never run this" << std::endl;
} catch (const std::invalid_argument& e) {
std::cout << e.what() << std::endl;
}
try {
radian.set(M_PI);
std::cerr << "Never run this" << std::endl;
} catch (const std::invalid_argument& e) {
std::cout << e.what() << std::endl;
}
}
{
std::cout << std::endl << "angle factory test section" << std::endl;
ics::Angle degree = ics::Angle::newDegree(90);
ics::Angle radian = ics::Angle::newRadian(M_PI / 2);
assert(degree.getRaw() == radian.getRaw());
}
{
std::cout << std::endl << "parameter test section" << std::endl;
ics::Parameter current = ics::Parameter::current();
assert(63 == current.get());
current.set(30);
assert(30 == current.get());
try {
current.set(70);
std::cerr << "Never run this" << std::endl;
} catch (const std::invalid_argument& e) {
std::cout << e.what() << std::endl;
}
}
return 0;
}
<|endoftext|> |
<commit_before>#include <primecount.h>
#include <primesieve/soe/ParallelPrimeSieve.h>
#include <stdint.h>
#include <iostream>
#include <cstdlib>
#include <string>
#include <iomanip>
#include <ctime>
using namespace std;
namespace primecount {
void assert_equal(const std::string& f1_name, int64_t x, int64_t f1_res, int64_t f2_res)
{
if (f1_res != f2_res)
{
cerr << endl << f1_name << "(" << x << ") = " << f1_res
<< " is an error, the correct result is " << f2_res << std::endl;
exit(1);
}
}
/// 0 <= get_rand() < 10^7
int get_rand()
{
return (rand() % 10000) * 1000;
}
template <typename F>
void check_for_equality(const std::string& f1_name, F f1, F f2, int64_t iters)
{
cout << left;
cout << "Testing " << setw(15) << (f1_name + "(x)") << flush;
// test for 0 <= x < iters
for (int64_t x = 0; x < iters; x++)
assert_equal(f1_name, x, f1(x, MAX_THREADS), f2(x, MAX_THREADS));
int64_t x = 0;
// test using random increment
for (int64_t i = 0; i < iters; i++, x += get_rand())
assert_equal(f1_name, x, f1(x, MAX_THREADS), f2(x, MAX_THREADS));
cout << "OK" << endl;
}
int64_t pps_nth_prime(int64_t x, int)
{
ParallelPrimeSieve pps;
int64_t prime = pps.nthPrime(x);
return prime;
}
void test()
{
srand(static_cast<unsigned int>(time(0)));
check_for_equality("pi_legendre", pi_legendre, pi_primesieve, 100);
check_for_equality("pi_meissel", pi_meissel, pi_legendre, 500);
check_for_equality("pi_lehmer", pi_lehmer, pi_meissel, 500);
check_for_equality("nth_prime", nth_prime, pps_nth_prime, 100);
cout << "All tests passed successfully!" << endl;
exit(0);
}
} // namespace primecount
<commit_msg>get_rand() % 2 == 0 is not good for testing<commit_after>#include <primecount.h>
#include <primesieve/soe/ParallelPrimeSieve.h>
#include <stdint.h>
#include <iostream>
#include <cstdlib>
#include <string>
#include <iomanip>
#include <ctime>
using namespace std;
namespace primecount {
void assert_equal(const std::string& f1_name, int64_t x, int64_t f1_res, int64_t f2_res)
{
if (f1_res != f2_res)
{
cerr << endl << f1_name << "(" << x << ") = " << f1_res
<< " is an error, the correct result is " << f2_res << std::endl;
exit(1);
}
}
/// 0 <= get_rand() < 10^7
int get_rand()
{
return (rand() % 10000) * 1000 + 1;
}
template <typename F>
void check_for_equality(const std::string& f1_name, F f1, F f2, int64_t iters)
{
cout << left;
cout << "Testing " << setw(15) << (f1_name + "(x)") << flush;
// test for 0 <= x < iters
for (int64_t x = 0; x < iters; x++)
assert_equal(f1_name, x, f1(x, MAX_THREADS), f2(x, MAX_THREADS));
int64_t x = 0;
// test using random increment
for (int64_t i = 0; i < iters; i++, x += get_rand())
assert_equal(f1_name, x, f1(x, MAX_THREADS), f2(x, MAX_THREADS));
cout << "OK" << endl;
}
int64_t pps_nth_prime(int64_t x, int)
{
ParallelPrimeSieve pps;
int64_t prime = pps.nthPrime(x);
return prime;
}
void test()
{
srand(static_cast<unsigned int>(time(0)));
check_for_equality("pi_legendre", pi_legendre, pi_primesieve, 100);
check_for_equality("pi_meissel", pi_meissel, pi_legendre, 500);
check_for_equality("pi_lehmer", pi_lehmer, pi_meissel, 500);
check_for_equality("nth_prime", nth_prime, pps_nth_prime, 100);
cout << "All tests passed successfully!" << endl;
exit(0);
}
} // namespace primecount
<|endoftext|> |
<commit_before>#include "testApp.h"
#include "CursorFeedback.hpp"
#include "FigureFeedback.hpp"
#include "TapFeedback.hpp"
#include "Calibrator.hpp"
//--------------------------------------------------------------
void testApp::Setup(){
new CursorFeedback();
new FigureFeedback();
new TapFeedback();
new CalibratorObject(1);
}
//--------------------------------------------------------------
void testApp::Update(){
}
//--------------------------------------------------------------
void testApp::Draw(){
}
//--------------------------------------------------------------
void testApp::WindowResized(int w, int h){
}
<commit_msg>Since Calibration Object doesn't work properly I remove it from the example project<commit_after>#include "testApp.h"
#include "CursorFeedback.hpp"
#include "FigureFeedback.hpp"
#include "TapFeedback.hpp"
#include "Calibrator.hpp"
//--------------------------------------------------------------
void testApp::Setup(){
new CursorFeedback();
new FigureFeedback();
new TapFeedback();
}
//--------------------------------------------------------------
void testApp::Update(){
}
//--------------------------------------------------------------
void testApp::Draw(){
}
//--------------------------------------------------------------
void testApp::WindowResized(int w, int h){
}
<|endoftext|> |
<commit_before>
/*
* client.cpp
*
* Handles the client env.
*
* Created by Ryan Faulkner on 2014-06-08
* Copyright (c) 2014. All rights reserved.
*/
#include <iostream>
#include <string>
#include <vector>
#include <regex>
#include <assert.h>
#include "column_types.h"
#include "redis.h"
#include "md5.h"
#include "index.h"
#include "bayes.h"
#include "model.h"
#define REDISHOST "127.0.0.1"
#define REDISPORT 6379
using namespace std;
/** Test to ensure that redis keys are correctly returned */
void testRedisSet() {
RedisHandler r;
r.connect();
r.write("foo", "bar");
}
/** Test to ensure that redis keys are correctly returned */
void testRedisGet() {
RedisHandler r;
r.connect();
cout << endl << "VALUE FOR KEY foo" << endl;
cout << r.read("foo") << endl << endl;
}
/** Test to ensure that redis keys are correctly returned */
void testRedisKeys() {
RedisHandler r;
std::vector<std::string> vec;
r.connect();
vec = r.keys("*");
cout << "KEY LIST FOR *" << endl;
for (std::vector<std::string>::iterator it = vec.begin() ; it != vec.end(); ++it) {
cout << *it << endl;
}
cout << endl;
}
/** Test to ensure that redis keys are correctly returned */
void testRedisIO() {
RedisHandler r;
std::vector<string>* vec;
std::string outTrue, outFalse = "";
r.connect();
r.write("test_key", "test value");
outTrue = r.read("test_key");
assert(std::strcmp(outTrue.c_str(), "test value") == 0);
r.deleteKey("test_key");
assert(!r.exists("test_key"));
}
/** Test to ensure that md5 hashing works */
void testMd5Hashing() {
cout << endl << "md5 of 'mykey': " << md5("mykey") << endl;
}
/** Test to ensure that md5 hashing works */
void testRegexForTypes() {
IntegerColumn ic;
FloatColumn fc;
assert(ic.validate("1981"));
assert(fc.validate("5.2"));
cout << "Passed regex tests." << endl;
}
/** Test to ensure that md5 hashing works */
void testOrderPairAlphaNumeric() {
IndexHandler ih;
assert(std::strcmp(ih.orderPairAlphaNumeric("b", "a").c_str(), "a_b") == 0);
cout << "Passed orderPairAlphaNumeric tests." << endl;
}
/**
* Test to ensure that relation entities are encoded properly
*/
void testJSONEntityEncoding() {
IndexHandler ih;
Json::Value json;
std::vector<std::pair<ColumnBase, std::string>> fields_ent;
fields_ent.push_back(std::make_pair(getColumnType("integer"), "a")); // Create fields
Entity e("test", fields_ent);
ih.writeEntity(e); // Create the entity
ih.fetchEntity("test", json); // Fetch the entity representation
cout << "TEST ENTITY:" << endl << endl << json.toStyledString() << endl;
// Assert that entity as read matches definition
assert(std::strcmp(json["entity"].asCString(), "test") == 0 &&
std::strcmp(json["fields"]["a"].asCString(), "integer") == 0 &&
json["fields"]["_itemcount"].asInt() == 1
);
ih.removeEntity("test"); // Remove the entity
}
/**
* Test to ensure that relation fields are encoded properly
*/
void testJSONRelationEncoding() {
IndexHandler ih;
std::vector<Json::Value> ret;
std::vector<std::pair<ColumnBase, std::string>> fields_ent_1;
std::vector<std::pair<ColumnBase, std::string>> fields_ent_2;
std::vector<std::pair<std::string, std::string>> fields_rel_1;
std::vector<std::pair<std::string, std::string>> fields_rel_2;
// Popualate fields
fields_ent_1.push_back(std::make_pair(getColumnType("integer"), "a"));
fields_ent_2.push_back(std::make_pair(getColumnType("string"), "b"));
fields_rel_1.push_back(std::make_pair("a", "1"));
fields_rel_2.push_back(std::make_pair("b", "hello"));
// Create entities
Entity e1("test_1", fields_ent_1), e2("test_2", fields_ent_2);
ih.writeEntity(e1);
ih.writeEntity(e2);
// Create relation in redis
Relation r("test_1", "test_2", fields_rel_1, fields_rel_2);
ih.writeRelation(r);
// Fetch the entity representation
ret = ih.fetchRelationPrefix("test_1", "test_2");
cout << "TEST RELATION:" << endl << endl << ret[0].toStyledString() << endl;
// Assert that entity as read matches definition
assert(
std::strcmp(ret[0]["entity_left"].asCString(), "test_1") == 0 &&
std::strcmp(ret[0]["entity_right"].asCString(), "test_2") == 0 &&
std::strcmp(ret[0]["fields_left"]["a"].asCString(), "1") == 0 &&
std::strcmp(ret[0]["fields_right"]["b"].asCString(), "hello") == 0 &&
ret[0]["fields_left"]["_itemcount"].asInt() == 1 &&
ret[0]["fields_right"]["_itemcount"].asInt() == 1
);
ih.removeEntity("test_1"); // Remove the entity
ih.removeEntity("test_2"); // Remove the entity
ih.removeRelation(r); // Remove the relation
}
/**
* Tests that parseEntityAssignField correctly flags invalid assignments to integer fields
*/
void testFieldAssignTypeMismatchInteger() {
IndexHandler ih;
Json::Value json;
std::vector<std::pair<ColumnBase, std::string>> fields_ent;
fields_ent.push_back(std::make_pair(getColumnType("integer"), "a")); // Create fields
Entity e("test", fields_ent);
ih.writeEntity(e); // Create the entity
assert(
ih.validateEntityFieldType("test", "a", "1") &&
ih.validateEntityFieldType("test", "a", "12345") &&
!ih.validateEntityFieldType("test", "a", "1.0") &&
!ih.validateEntityFieldType("test", "a", "string")
);
ih.removeEntity("test");
}
/**
* Tests that parseEntityAssignField correctly flags invalid assignments to float fields
*/
void testFieldAssignTypeMismatchFloat() {
IndexHandler ih;
Json::Value json;
std::vector<std::pair<ColumnBase, std::string>> fields_ent;
fields_ent.push_back(std::make_pair(getColumnType("float"), "a")); // Create fields
Entity e("test", fields_ent); // Create the entity
ih.writeEntity(e); // Create the entity
assert(
ih.validateEntityFieldType("test", "a", "1.2") &&
ih.validateEntityFieldType("test", "a", "12.5") &&
!ih.validateEntityFieldType("test", "a", "string")
);
ih.removeEntity("test");
}
/**
* Tests that parseEntityAssignField correctly flags invalid assignments to string fields
*/
void testFieldAssignTypeMismatchString() {
IndexHandler ih;
Json::Value json;
std::vector<std::pair<ColumnBase, std::string>> fields_ent;
fields_ent.push_back(std::make_pair(getColumnType("string"), "a")); // Create fields
Entity e("test", fields_ent);
ih.writeEntity(e); // Create the entity
assert(
ih.validateEntityFieldType("test", "a", "1") &&
ih.validateEntityFieldType("test", "a", "12345") &&
ih.validateEntityFieldType("test", "a", "string")
);
ih.removeEntity("test");
}
/**
* Tests Bayes::countRelations - ensure relation counting is functioning correctly
*/
void testCountRelations() {
Bayes bayes;
IndexHandler ih;
std::vector<Json::Value> ret;
std::vector<std::pair<ColumnBase*, std::string>> fields_ent;
std::vector<std::pair<std::string, std::string>> fields_rel;
// declare three entities
Entity e1("_w", fields_ent), e2("_x", fields_ent), e3("_y", fields_ent), e4("_z", fields_ent);
// construct a number of relations
Relation r1("_x", "_y", fields_rel, fields_rel);
Relation r2("_x", "_y", fields_rel, fields_rel);
Relation r3("_x", "_z", fields_rel, fields_rel);
Relation r4("_x", "_z", fields_rel, fields_rel);
Relation r5("_w", "_y", fields_rel, fields_rel);
ih.removeEntity("_w");
ih.removeEntity("_x");
ih.removeEntity("_y");
ih.removeEntity("_z");
ih.writeEntity(e1);
ih.writeEntity(e2);
ih.writeEntity(e3);
ih.writeEntity(e4);
ih.removeRelation(r1);
ih.removeRelation(r2);
ih.removeRelation(r3);
ih.removeRelation(r4);
ih.removeRelation(r5);
ih.writeRelation(r1);
ih.writeRelation(r2);
ih.writeRelation(r3);
ih.writeRelation(r4);
ih.writeRelation(r5);
AttributeBucket attrs; // empty set of filters
assert(bayes.countEntityInRelations(e1.name, attrs) == 1);
assert(bayes.countEntityInRelations(e2.name, attrs) == 4);
assert(bayes.countEntityInRelations(e3.name, attrs) == 3);
assert(bayes.countEntityInRelations(e4.name, attrs) == 2);
}
/**
* Tests that existsEntityField correctly flags when entity does not contain a field
*/
void testEntityDoesNotContainField() {
// TODO - implement
}
/**
* Tests Bayes::computeMarginal function - ensure the marginal likelihood is correct
*/
void testComputeMarginal() {
Bayes bayes;
IndexHandler ih;
std::vector<Json::Value> ret;
std::vector<std::pair<ColumnBase*, std::string>> fields_ent;
std::vector<std::pair<std::string, std::string>> fields_rel;
ih.setRelationCountTotal(0);
// declare three entities
Entity e1("_w", fields_ent), e2("_x", fields_ent), e3("_y", fields_ent), e4("_z", fields_ent);
// construct a number of relations
Relation r1("_x", "_y", fields_rel, fields_rel);
Relation r2("_x", "_y", fields_rel, fields_rel);
Relation r3("_x", "_z", fields_rel, fields_rel);
Relation r4("_x", "_z", fields_rel, fields_rel);
Relation r5("_w", "_y", fields_rel, fields_rel);
ih.removeEntity("_w");
ih.removeEntity("_x");
ih.removeEntity("_y");
ih.removeEntity("_z");
ih.writeEntity(e1);
ih.writeEntity(e2);
ih.writeEntity(e3);
ih.writeEntity(e4);
ih.removeRelation(r1);
ih.removeRelation(r2);
ih.removeRelation(r3);
ih.removeRelation(r4);
ih.removeRelation(r5);
ih.writeRelation(r1);
ih.writeRelation(r2);
ih.writeRelation(r3);
ih.writeRelation(r4);
ih.writeRelation(r5);
ih.setRelationCountTotal(ih.computeRelationsCount("*", "*"));
// Ensure marginal likelihood reflects the number of relations that contain each entity
AttributeBucket attrs;
assert(bayes.computeMarginal(e1.name, attrs) == (float)0.2);
assert(bayes.computeMarginal(e2.name, attrs) == (float)0.8);
assert(bayes.computeMarginal(e3.name, attrs) == (float)0.6);
assert(bayes.computeMarginal(e4.name, attrs) == (float)0.4);
}
/**
* Tests that removal of entities functions properly
*/
void testEntityRemoval() {
// TODO - implement
}
/**
* Tests that removal of relations functions properly
*/
void testRelationRemoval() {
// TODO - implement
}
/**
* Tests that removal of relations cascading on entities functions properly
*/
void testEntityCascadeRemoval() {
// TODO - implement
}
/**
* Tests that the correct relations are filtered from a set
*/
void testRelationFiltering() {
// TODO - implement
}
/**
* Tests that the correct relations are filtered from a set
*/
void testRelation_toJson() {
valpair left, right;
left.push_back(std::make_pair("x", "1"));
right.push_back(std::make_pair("y", "2"));
Relation rel("x", "y", left, right);
Json::Value json = rel.toJson();
assert(std::atoi(json[JSON_ATTR_REL_FIELDSL]["x"].asCString()) == 1 && std::atoi(json[JSON_ATTR_REL_FIELDSR]["y"].asCString()) == 2);
}
/**
* Ensure sample marginal returns a valid sample
*/
void testSampleMarginal() {
// Define entities and relations
// Generate a sample
// specify filter criteria
// test sample to ensure that it meets criteria
}
/**
* Ensure sample marginal returns a valid sample
*/
void testSamplePairwise() {
// Define entities and relations
// Generate a sample
// specify filter criteria
// test sample to ensure that it meets criteria
}
/**
* Ensure sample marginal returns a valid sample
*/
void testSamplePairwiseCausal() {
// Define entities and relations
// Generate a sample
// specify filter criteria
// test sample to ensure that it meets criteria
}
int main() {
cout << "-- TESTS BEGIN --" << endl << endl;
// testRedisSet();
// testRedisGet();
// testRedisKeys();
// md5Hashing();
// testRedisIO();
// testRegexForTypes();
// testOrderPairAlphaNumeric();
// testJSONEntityEncoding();
// testJSONRelationEncoding();
// testFieldAssignTypeMismatchInteger();
// testFieldAssignTypeMismatchFloat();
// testFieldAssignTypeMismatchString();
// testCountRelations();
testComputeMarginal();
// testRelation_toJson();
cout << endl << "-- TESTS END --" << endl;
return 0;
}
<commit_msg>update tests to be consistent with new relation model<commit_after>
/*
* client.cpp
*
* Handles the client env.
*
* Created by Ryan Faulkner on 2014-06-08
* Copyright (c) 2014. All rights reserved.
*/
#include <iostream>
#include <string>
#include <vector>
#include <regex>
#include <assert.h>
#include "column_types.h"
#include "redis.h"
#include "md5.h"
#include "index.h"
#include "bayes.h"
#include "model.h"
#define REDISHOST "127.0.0.1"
#define REDISPORT 6379
using namespace std;
/** Test to ensure that redis keys are correctly returned */
void testRedisSet() {
RedisHandler r;
r.connect();
r.write("foo", "bar");
}
/** Test to ensure that redis keys are correctly returned */
void testRedisGet() {
RedisHandler r;
r.connect();
cout << endl << "VALUE FOR KEY foo" << endl;
cout << r.read("foo") << endl << endl;
}
/** Test to ensure that redis keys are correctly returned */
void testRedisKeys() {
RedisHandler r;
std::vector<std::string> vec;
r.connect();
vec = r.keys("*");
cout << "KEY LIST FOR *" << endl;
for (std::vector<std::string>::iterator it = vec.begin() ; it != vec.end(); ++it) {
cout << *it << endl;
}
cout << endl;
}
/** Test to ensure that redis keys are correctly returned */
void testRedisIO() {
RedisHandler r;
std::vector<string>* vec;
std::string outTrue, outFalse = "";
r.connect();
r.write("test_key", "test value");
outTrue = r.read("test_key");
assert(std::strcmp(outTrue.c_str(), "test value") == 0);
r.deleteKey("test_key");
assert(!r.exists("test_key"));
}
/** Test to ensure that md5 hashing works */
void testMd5Hashing() {
cout << endl << "md5 of 'mykey': " << md5("mykey") << endl;
}
/** Test to ensure that md5 hashing works */
void testRegexForTypes() {
IntegerColumn ic;
FloatColumn fc;
assert(ic.validate("1981"));
assert(fc.validate("5.2"));
cout << "Passed regex tests." << endl;
}
/** Test to ensure that md5 hashing works */
void testOrderPairAlphaNumeric() {
IndexHandler ih;
assert(std::strcmp(ih.orderPairAlphaNumeric("b", "a").c_str(), "a_b") == 0);
cout << "Passed orderPairAlphaNumeric tests." << endl;
}
/**
* Test to ensure that relation entities are encoded properly
*/
void testJSONEntityEncoding() {
IndexHandler ih;
Json::Value json;
std::vector<std::pair<ColumnBase, std::string>> fields_ent;
fields_ent.push_back(std::make_pair(getColumnType("integer"), "a")); // Create fields
Entity e("test", fields_ent);
ih.writeEntity(e); // Create the entity
ih.fetchEntity("test", json); // Fetch the entity representation
cout << "TEST ENTITY:" << endl << endl << json.toStyledString() << endl;
// Assert that entity as read matches definition
assert(std::strcmp(json["entity"].asCString(), "test") == 0 &&
std::strcmp(json["fields"]["a"].asCString(), "integer") == 0 &&
json["fields"]["_itemcount"].asInt() == 1
);
ih.removeEntity("test"); // Remove the entity
}
/**
* Test to ensure that relation fields are encoded properly
*/
void testJSONRelationEncoding() {
IndexHandler ih;
std::vector<Json::Value> ret;
std::vector<std::pair<ColumnBase, std::string>> fields_ent_1;
std::vector<std::pair<ColumnBase, std::string>> fields_ent_2;
std::vector<std::pair<std::string, std::string>> fields_rel_1;
std::vector<std::pair<std::string, std::string>> fields_rel_2;
// Popualate fields
fields_ent_1.push_back(std::make_pair(getColumnType("integer"), "a"));
fields_ent_2.push_back(std::make_pair(getColumnType("string"), "b"));
fields_rel_1.push_back(std::make_pair("a", "1"));
fields_rel_2.push_back(std::make_pair("b", "hello"));
// Create entities
Entity e1("test_1", fields_ent_1), e2("test_2", fields_ent_2);
ih.writeEntity(e1);
ih.writeEntity(e2);
// Create relation in redis
Relation r("test_1", "test_2", fields_rel_1, fields_rel_2);
ih.writeRelation(r);
// Fetch the entity representation
ret = ih.fetchRelationPrefix("test_1", "test_2");
cout << "TEST RELATION:" << endl << endl << ret[0].toStyledString() << endl;
// Assert that entity as read matches definition
assert(
std::strcmp(ret[0]["entity_left"].asCString(), "test_1") == 0 &&
std::strcmp(ret[0]["entity_right"].asCString(), "test_2") == 0 &&
std::strcmp(ret[0]["fields_left"]["a"].asCString(), "1") == 0 &&
std::strcmp(ret[0]["fields_right"]["b"].asCString(), "hello") == 0 &&
ret[0]["fields_left"]["_itemcount"].asInt() == 1 &&
ret[0]["fields_right"]["_itemcount"].asInt() == 1
);
ih.removeEntity("test_1"); // Remove the entity
ih.removeEntity("test_2"); // Remove the entity
ih.removeRelation(r); // Remove the relation
}
/**
* Tests that parseEntityAssignField correctly flags invalid assignments to integer fields
*/
void testFieldAssignTypeMismatchInteger() {
IndexHandler ih;
Json::Value json;
std::vector<std::pair<ColumnBase, std::string>> fields_ent;
fields_ent.push_back(std::make_pair(getColumnType("integer"), "a")); // Create fields
Entity e("test", fields_ent);
ih.writeEntity(e); // Create the entity
assert(
ih.validateEntityFieldType("test", "a", "1") &&
ih.validateEntityFieldType("test", "a", "12345") &&
!ih.validateEntityFieldType("test", "a", "1.0") &&
!ih.validateEntityFieldType("test", "a", "string")
);
ih.removeEntity("test");
}
/**
* Tests that parseEntityAssignField correctly flags invalid assignments to float fields
*/
void testFieldAssignTypeMismatchFloat() {
IndexHandler ih;
Json::Value json;
std::vector<std::pair<ColumnBase, std::string>> fields_ent;
fields_ent.push_back(std::make_pair(getColumnType("float"), "a")); // Create fields
Entity e("test", fields_ent); // Create the entity
ih.writeEntity(e); // Create the entity
assert(
ih.validateEntityFieldType("test", "a", "1.2") &&
ih.validateEntityFieldType("test", "a", "12.5") &&
!ih.validateEntityFieldType("test", "a", "string")
);
ih.removeEntity("test");
}
/**
* Tests that parseEntityAssignField correctly flags invalid assignments to string fields
*/
void testFieldAssignTypeMismatchString() {
IndexHandler ih;
Json::Value json;
std::vector<std::pair<ColumnBase, std::string>> fields_ent;
fields_ent.push_back(std::make_pair(getColumnType("string"), "a")); // Create fields
Entity e("test", fields_ent);
ih.writeEntity(e); // Create the entity
assert(
ih.validateEntityFieldType("test", "a", "1") &&
ih.validateEntityFieldType("test", "a", "12345") &&
ih.validateEntityFieldType("test", "a", "string")
);
ih.removeEntity("test");
}
/**
* Tests Bayes::countRelations - ensure relation counting is functioning correctly
*/
void testCountRelations() {
Bayes bayes;
IndexHandler ih;
std::vector<Json::Value> ret;
std::vector<std::pair<ColumnBase*, std::string>> fields_ent;
std::vector<std::pair<std::string, std::string>> fields_rel;
std::unordered_map<std::string, std::string> types;
// declare three entities
Entity e1("_w", fields_ent), e2("_x", fields_ent), e3("_y", fields_ent), e4("_z", fields_ent);
// construct a number of relations
Relation r1("_x", "_y", fields_rel, fields_rel, types, types);
Relation r2("_x", "_y", fields_rel, fields_rel, types, types);
Relation r3("_x", "_z", fields_rel, fields_rel, types, types);
Relation r4("_x", "_z", fields_rel, fields_rel, types, types);
Relation r5("_w", "_y", fields_rel, fields_rel, types, types);
ih.removeEntity("_w");
ih.removeEntity("_x");
ih.removeEntity("_y");
ih.removeEntity("_z");
ih.writeEntity(e1);
ih.writeEntity(e2);
ih.writeEntity(e3);
ih.writeEntity(e4);
ih.removeRelation(r1);
ih.removeRelation(r2);
ih.removeRelation(r3);
ih.removeRelation(r4);
ih.removeRelation(r5);
ih.writeRelation(r1);
ih.writeRelation(r2);
ih.writeRelation(r3);
ih.writeRelation(r4);
ih.writeRelation(r5);
AttributeBucket attrs; // empty set of filters
assert(bayes.countEntityInRelations(e1.name, attrs) == 1);
assert(bayes.countEntityInRelations(e2.name, attrs) == 4);
assert(bayes.countEntityInRelations(e3.name, attrs) == 3);
assert(bayes.countEntityInRelations(e4.name, attrs) == 2);
}
/**
* Tests that existsEntityField correctly flags when entity does not contain a field
*/
void testEntityDoesNotContainField() {
// TODO - implement
}
/**
* Tests Bayes::computeMarginal function - ensure the marginal likelihood is correct
*/
void testComputeMarginal() {
Bayes bayes;
IndexHandler ih;
std::vector<Json::Value> ret;
std::vector<std::pair<ColumnBase*, std::string>> fields_ent;
std::vector<std::pair<std::string, std::string>> fields_rel;
std::unordered_map<std::string, std::string> types;
ih.setRelationCountTotal(0);
// declare three entities
Entity e1("_w", fields_ent), e2("_x", fields_ent), e3("_y", fields_ent), e4("_z", fields_ent);
// construct a number of relations
Relation r1("_x", "_y", fields_rel, fields_rel, types, types);
Relation r2("_x", "_y", fields_rel, fields_rel, types, types);
Relation r3("_x", "_z", fields_rel, fields_rel, types, types);
Relation r4("_x", "_z", fields_rel, fields_rel, types, types);
Relation r5("_w", "_y", fields_rel, fields_rel, types, types);
ih.removeEntity("_w");
ih.removeEntity("_x");
ih.removeEntity("_y");
ih.removeEntity("_z");
ih.writeEntity(e1);
ih.writeEntity(e2);
ih.writeEntity(e3);
ih.writeEntity(e4);
ih.removeRelation(r1);
ih.removeRelation(r2);
ih.removeRelation(r3);
ih.removeRelation(r4);
ih.removeRelation(r5);
ih.writeRelation(r1);
ih.writeRelation(r2);
ih.writeRelation(r3);
ih.writeRelation(r4);
ih.writeRelation(r5);
ih.setRelationCountTotal(ih.computeRelationsCount("*", "*"));
// Ensure marginal likelihood reflects the number of relations that contain each entity
AttributeBucket attrs;
assert(bayes.computeMarginal(e1.name, attrs) == (float)0.2);
assert(bayes.computeMarginal(e2.name, attrs) == (float)0.8);
assert(bayes.computeMarginal(e3.name, attrs) == (float)0.6);
assert(bayes.computeMarginal(e4.name, attrs) == (float)0.4);
}
/**
* Tests that removal of entities functions properly
*/
void testEntityRemoval() {
// TODO - implement
}
/**
* Tests that removal of relations functions properly
*/
void testRelationRemoval() {
// TODO - implement
}
/**
* Tests that removal of relations cascading on entities functions properly
*/
void testEntityCascadeRemoval() {
// TODO - implement
}
/**
* Tests that the correct relations are filtered from a set
*/
void testRelationFiltering() {
// TODO - implement
}
/**
* Tests that the correct relations are filtered from a set
*/
void testRelation_toJson() {
valpair left, right;
std::unordered_map<std::string, std::string> typesL, typesR;
left.push_back(std::make_pair("x", "1"));
right.push_back(std::make_pair("y", "2"));
typesL.insert(std::make_pair("x", COLTYPE_NAME_INT));
typesR.insert(std::make_pair("y", COLTYPE_NAME_INT));
Relation rel("x", "y", left, right);
Json::Value json = rel.toJson();
assert(std::atoi(json[JSON_ATTR_REL_FIELDSL]["x"].asCString()) == 1 && std::atoi(json[JSON_ATTR_REL_FIELDSR]["y"].asCString()) == 2);
}
/**
* Ensure sample marginal returns a valid sample
*/
void testSampleMarginal() {
// Define entities and relations
// Generate a sample
// specify filter criteria
// test sample to ensure that it meets criteria
}
/**
* Ensure sample marginal returns a valid sample
*/
void testSamplePairwise() {
// Define entities and relations
// Generate a sample
// specify filter criteria
// test sample to ensure that it meets criteria
}
/**
* Ensure sample marginal returns a valid sample
*/
void testSamplePairwiseCausal() {
// Define entities and relations
// Generate a sample
// specify filter criteria
// test sample to ensure that it meets criteria
}
int main() {
cout << "-- TESTS BEGIN --" << endl << endl;
// testRedisSet();
// testRedisGet();
// testRedisKeys();
// md5Hashing();
// testRedisIO();
// testRegexForTypes();
// testOrderPairAlphaNumeric();
// testJSONEntityEncoding();
// testJSONRelationEncoding();
// testFieldAssignTypeMismatchInteger();
// testFieldAssignTypeMismatchFloat();
// testFieldAssignTypeMismatchString();
// testCountRelations();
testComputeMarginal();
// testRelation_toJson();
cout << endl << "-- TESTS END --" << endl;
return 0;
}
<|endoftext|> |
<commit_before>#include "file.h"
#include "file_p.h"
#include "abstractfileengine.h"
#include "abstractfileengine_p.h"
#include "abstractfileengineplugin.h"
#include "pluginmanager_p.h"
#include <QtCore/QFutureWatcher>
void FilePrivate::init()
{
state = File::Closed;
openMode = QIODevice::NotOpen;
bufferSize = 10*1024*1024; // 10 Mb
chunkSize = 4*1024; // 4 Kb
engine = AbstractFileEngine::emptyEngine();
}
void FilePrivate::openFinished(bool ok)
{
Q_Q(File);
if (ok) {
state = File::Opened;
// size = size;
q->QIODevice::open(openMode);
if (openMode & QIODevice::Unbuffered)
buffer.reserve(chunkSize);
else
buffer.reserve(bufferSize);
if (openMode & QIODevice::ReadOnly)
engine->read(chunkSize);
} else {
state = File::Closed;
}
openMode = QIODevice::NotOpen;
}
void FilePrivate::readFinished(const char *data, qint64 length)
{
Q_Q(File);
if (length <= 0)
return;
int oldSize = buffer.size();
buffer.resize(oldSize + length);
memmove(buffer.data() + oldSize, data, length);
qint64 maxlen = bufferSize - buffer.size();
maxlen = qMin<qint64>(maxlen, chunkSize);
maxlen = qMin(q->size() - (q->pos() + buffer.size()), maxlen);
if (maxlen > 0)
engine->read(maxlen);
emit q->readyRead();
}
File::File(QObject *parent) :
QIODevice(parent),
d_ptr(new FilePrivate(this))
{
Q_D(File);
d->init();
}
File::File(const QUrl &url, QObject *parent) :
QIODevice(parent),
d_ptr(new FilePrivate(this))
{
Q_D(File);
d->init();
setUrl(url);
}
File::~File()
{
Q_D(File);
close();
if (d->engine != AbstractFileEngine::emptyEngine())
delete d->engine;
delete d_ptr;
}
bool File::open(QIODevice::OpenMode mode)
{
Q_D(File);
asyncOpen(mode);
waitForOpened();
return d->state == State::Opened;
}
void File::asyncOpen(QIODevice::OpenMode mode)
{
Q_D(File);
if (d->state != File::Closed)
return;
d->state = File::Opening;
d->openMode = mode;
d->engine->open(mode);
}
bool File::waitForOpened(int msecs)
{
Q_D(File);
return d->engine->waitForOpened(msecs);
}
void File::close()
{
Q_D(File);
d->state = File::Closed;
d->engine->close();
QIODevice::close();
}
qint64 File::size() const
{
Q_D(const File);
return d->engine->size();
}
bool File::seek(qint64 pos)
{
Q_D(File);
QIODevice::seek(pos);
return d->engine->seek(pos);
}
bool File::atEnd() const
{
return pos() == size();
}
qint64 File::bytesAvailable() const
{
Q_D(const File);
return d->buffer.size();
}
qint64 File::bytesToWrite() const
{
return 0;
}
bool File::waitForBytesWritten(int msecs)
{
Q_D(File);
return d->engine->waitForBytesWritten(msecs);
}
bool File::waitForReadyRead(int msecs)
{
Q_D(File);
if (!isOpen())
return false;
if (bytesAvailable() > 0)
return true;
return d->engine->waitForReadyRead(msecs);
}
QUrl File::url() const
{
Q_D(const File);
return d->url;
}
void File::setUrl(const QUrl &url)
{
Q_D(File);
if (d->url == url)
return;
d->url = url;
d->engine = PluginManager::createFileEngine(url);
if (!d->engine) {
d->engine = AbstractFileEngine::emptyEngine();
setErrorString(tr("Unsupported scheme %1").arg(url.scheme()));
} else {
d->engine->d_ptr->file = this;
}
emit urlChanged(url);
}
int File::bufferSize() const
{
Q_D(const File);
return d->bufferSize;
}
void File::setBufferSize(int size)
{
Q_D(File);
if (d->bufferSize == size)
return;
d->bufferSize = size;
emit bufferSizeChanged(size);
}
File::State File::state() const
{
Q_D(const File);
return d->state;
}
qint64 File::readData(char *data, qint64 maxlen)
{
Q_D(File);
maxlen = qMin(qint64(d->buffer.size()), maxlen);
if (maxlen == 0)
return 0;
memmove(data, d->buffer.constData(), maxlen);
d->buffer = d->buffer.mid(maxlen);
// d->engine->read();
return maxlen;
}
qint64 File::writeData(const char *data, qint64 maxlen)
{
return -1;
}
void File::onOpenFinished()
{
Q_D(File);
QFutureWatcher<bool> *watcher = static_cast<QFutureWatcher<bool> *>(sender());
bool ok = watcher->future().result();
if (ok) {
d->state = File::Opened;
// size = size;
QIODevice::open(d->openMode | QIODevice::Unbuffered);
// if (d->openMode & QIODevice::Unbuffered)
// d->buffer.reserve(d->chunkSize);
// else
d->buffer.reserve(d->bufferSize);
if (d->openMode & QIODevice::ReadOnly)
d->engine->read(d->chunkSize);
} else {
d->state = File::Closed;
}
d->openMode = QIODevice::NotOpen;
delete watcher;
}
<commit_msg>Fix maxlen in openFinished.<commit_after>#include "file.h"
#include "file_p.h"
#include "abstractfileengine.h"
#include "abstractfileengine_p.h"
#include "abstractfileengineplugin.h"
#include "pluginmanager_p.h"
#include <QtCore/QFutureWatcher>
void FilePrivate::init()
{
state = File::Closed;
openMode = QIODevice::NotOpen;
bufferSize = 10*1024*1024; // 10 Mb
chunkSize = 4*1024; // 4 Kb
engine = AbstractFileEngine::emptyEngine();
}
void FilePrivate::openFinished(bool ok)
{
Q_Q(File);
if (ok) {
state = File::Opened;
// size = size;
q->QIODevice::open(openMode);
if (openMode & QIODevice::Unbuffered)
buffer.reserve(chunkSize);
else
buffer.reserve(bufferSize);
if (openMode & QIODevice::ReadOnly) {
qint64 maxlen = qMin<qint64>(chunkSize, q->size());
engine->read(maxlen);
}
} else {
state = File::Closed;
}
openMode = QIODevice::NotOpen;
}
void FilePrivate::readFinished(const char *data, qint64 length)
{
Q_Q(File);
if (length <= 0)
return;
int oldSize = buffer.size();
buffer.resize(oldSize + length);
memmove(buffer.data() + oldSize, data, length);
qint64 maxlen = bufferSize - buffer.size();
maxlen = qMin<qint64>(maxlen, chunkSize);
maxlen = qMin(q->size() - (q->pos() + buffer.size()), maxlen);
if (maxlen > 0)
engine->read(maxlen);
emit q->readyRead();
}
File::File(QObject *parent) :
QIODevice(parent),
d_ptr(new FilePrivate(this))
{
Q_D(File);
d->init();
}
File::File(const QUrl &url, QObject *parent) :
QIODevice(parent),
d_ptr(new FilePrivate(this))
{
Q_D(File);
d->init();
setUrl(url);
}
File::~File()
{
Q_D(File);
close();
if (d->engine != AbstractFileEngine::emptyEngine())
delete d->engine;
delete d_ptr;
}
bool File::open(QIODevice::OpenMode mode)
{
Q_D(File);
asyncOpen(mode);
waitForOpened();
return d->state == State::Opened;
}
void File::asyncOpen(QIODevice::OpenMode mode)
{
Q_D(File);
if (d->state != File::Closed)
return;
d->state = File::Opening;
d->openMode = mode;
d->engine->open(mode);
}
bool File::waitForOpened(int msecs)
{
Q_D(File);
return d->engine->waitForOpened(msecs);
}
void File::close()
{
Q_D(File);
d->state = File::Closed;
d->engine->close();
QIODevice::close();
}
qint64 File::size() const
{
Q_D(const File);
return d->engine->size();
}
bool File::seek(qint64 pos)
{
Q_D(File);
QIODevice::seek(pos);
return d->engine->seek(pos);
}
bool File::atEnd() const
{
return pos() == size();
}
qint64 File::bytesAvailable() const
{
Q_D(const File);
return d->buffer.size();
}
qint64 File::bytesToWrite() const
{
return 0;
}
bool File::waitForBytesWritten(int msecs)
{
Q_D(File);
return d->engine->waitForBytesWritten(msecs);
}
bool File::waitForReadyRead(int msecs)
{
Q_D(File);
if (!isOpen())
return false;
if (bytesAvailable() > 0)
return true;
return d->engine->waitForReadyRead(msecs);
}
QUrl File::url() const
{
Q_D(const File);
return d->url;
}
void File::setUrl(const QUrl &url)
{
Q_D(File);
if (d->url == url)
return;
d->url = url;
d->engine = PluginManager::createFileEngine(url);
if (!d->engine) {
d->engine = AbstractFileEngine::emptyEngine();
setErrorString(tr("Unsupported scheme %1").arg(url.scheme()));
} else {
d->engine->d_ptr->file = this;
}
emit urlChanged(url);
}
int File::bufferSize() const
{
Q_D(const File);
return d->bufferSize;
}
void File::setBufferSize(int size)
{
Q_D(File);
if (d->bufferSize == size)
return;
d->bufferSize = size;
emit bufferSizeChanged(size);
}
File::State File::state() const
{
Q_D(const File);
return d->state;
}
qint64 File::readData(char *data, qint64 maxlen)
{
Q_D(File);
maxlen = qMin(qint64(d->buffer.size()), maxlen);
if (maxlen == 0)
return 0;
memmove(data, d->buffer.constData(), maxlen);
d->buffer = d->buffer.mid(maxlen);
// d->engine->read();
return maxlen;
}
qint64 File::writeData(const char *data, qint64 maxlen)
{
return -1;
}
void File::onOpenFinished()
{
Q_D(File);
QFutureWatcher<bool> *watcher = static_cast<QFutureWatcher<bool> *>(sender());
bool ok = watcher->future().result();
if (ok) {
d->state = File::Opened;
// size = size;
QIODevice::open(d->openMode | QIODevice::Unbuffered);
// if (d->openMode & QIODevice::Unbuffered)
// d->buffer.reserve(d->chunkSize);
// else
d->buffer.reserve(d->bufferSize);
if (d->openMode & QIODevice::ReadOnly)
d->engine->read(d->chunkSize);
} else {
d->state = File::Closed;
}
d->openMode = QIODevice::NotOpen;
delete watcher;
}
<|endoftext|> |
<commit_before>////////////////////////////////////////////////////////////////////////////////
// task - a command line task list manager.
//
// Copyright 2006 - 2010, Paul Beckingham.
// All rights reserved.
//
// This program is free software; you can redistribute it and/or modify it under
// the terms of the GNU General Public License as published by the Free Software
// Foundation; either version 2 of the License, or (at your option) any later
// version.
//
// This program is distributed in the hope that it will be useful, but WITHOUT
// ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
// FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
// details.
//
// You should have received a copy of the GNU General Public License along with
// this program; if not, write to the
//
// Free Software Foundation, Inc.,
// 51 Franklin Street, Fifth Floor,
// Boston, MA
// 02110-1301
// USA
//
////////////////////////////////////////////////////////////////////////////////
#include <iostream>
#include <vector>
#include <string>
#include <strings.h>
#include <ctype.h>
#include "Context.h"
#include "util.h"
#include "text.h"
extern Context context;
static const char* newline = "\n";
static const char* noline = "";
///////////////////////////////////////////////////////////////////////////////
void wrapText (
std::vector <std::string>& lines,
const std::string& text,
const int width)
{
std::string copy = text;
std::string line;
while (copy.length ())
{
extractLine (copy, line, width);
lines.push_back (line);
}
}
////////////////////////////////////////////////////////////////////////////////
void split (
std::vector<std::string>& results,
const std::string& input,
const char delimiter)
{
results.clear ();
std::string::size_type start = 0;
std::string::size_type i;
while ((i = input.find (delimiter, start)) != std::string::npos)
{
results.push_back (input.substr (start, i - start));
start = i + 1;
}
if (input.length ())
results.push_back (input.substr (start));
}
////////////////////////////////////////////////////////////////////////////////
void split_minimal (
std::vector<std::string>& results,
const std::string& input,
const char delimiter)
{
results.clear ();
std::string::size_type start = 0;
std::string::size_type i;
while ((i = input.find (delimiter, start)) != std::string::npos)
{
if (i != start)
results.push_back (input.substr (start, i - start));
start = i + 1;
}
if (input.length ())
results.push_back (input.substr (start));
}
////////////////////////////////////////////////////////////////////////////////
void split (
std::vector<std::string>& results,
const std::string& input,
const std::string& delimiter)
{
results.clear ();
std::string::size_type length = delimiter.length ();
std::string::size_type start = 0;
std::string::size_type i;
while ((i = input.find (delimiter, start)) != std::string::npos)
{
results.push_back (input.substr (start, i - start));
start = i + length;
}
if (input.length ())
results.push_back (input.substr (start));
}
////////////////////////////////////////////////////////////////////////////////
void split_minimal (
std::vector<std::string>& results,
const std::string& input,
const std::string& delimiter)
{
results.clear ();
std::string::size_type length = delimiter.length ();
std::string::size_type start = 0;
std::string::size_type i;
while ((i = input.find (delimiter, start)) != std::string::npos)
{
if (i != start)
results.push_back (input.substr (start, i - start));
start = i + length;
}
if (input.length ())
results.push_back (input.substr (start));
}
////////////////////////////////////////////////////////////////////////////////
void join (
std::string& result,
const std::string& separator,
const std::vector<std::string>& items)
{
result = "";
unsigned int size = items.size ();
for (unsigned int i = 0; i < size; ++i)
{
result += items[i];
if (i < size - 1)
result += separator;
}
}
////////////////////////////////////////////////////////////////////////////////
std::string trimLeft (const std::string& in, const std::string& t /*= " "*/)
{
std::string out = in;
return out.erase (0, in.find_first_not_of (t));
}
////////////////////////////////////////////////////////////////////////////////
std::string trimRight (const std::string& in, const std::string& t /*= " "*/)
{
std::string out = in;
return out.erase (out.find_last_not_of (t) + 1);
}
////////////////////////////////////////////////////////////////////////////////
std::string trim (const std::string& in, const std::string& t /*= " "*/)
{
std::string out = in;
return trimLeft (trimRight (out, t), t);
}
////////////////////////////////////////////////////////////////////////////////
// Remove enclosing balanced quotes. Assumes trimmed text.
std::string unquoteText (const std::string& input)
{
std::string output = input;
if (output.length () > 1)
{
char quote = output[0];
if ((quote == '\'' || quote == '"') &&
output[output.length () - 1] == quote)
return output.substr (1, output.length () - 2);
}
return output;
}
////////////////////////////////////////////////////////////////////////////////
void extractLine (std::string& text, std::string& line, int length)
{
size_t eol = text.find ("\n");
// Special case: found \n in first length characters.
if (eol != std::string::npos && eol < (unsigned) length)
{
line = text.substr (0, eol); // strip \n
text = text.substr (eol + 1);
return;
}
// Special case: no \n, and less than length characters total.
// special case: text.find ("\n") == std::string::npos && text.length () < length
if (eol == std::string::npos && text.length () <= (unsigned) length)
{
line = text;
text = "";
return;
}
// Safe to ASSERT text.length () > length
// Look for the last space prior to length
eol = length;
while (eol && text[eol] != ' ' && text[eol] != '\n')
--eol;
// If a space was found, break there.
if (eol)
{
line = text.substr (0, eol);
text = text.substr (eol + 1);
}
// If no space was found, hyphenate.
else
{
if (length > 1)
{
line = text.substr (0, length - 1) + "-";
text = text.substr (length - 1);
}
else
{
line = text.substr (0, 1);
text = text.substr (length);
}
}
}
////////////////////////////////////////////////////////////////////////////////
std::string commify (const std::string& data)
{
// First scan for decimal point and end of digits.
int decimalPoint = -1;
int end = -1;
int i;
for (int i = 0; i < (int) data.length (); ++i)
{
if (isdigit (data[i]))
end = i;
if (data[i] == '.')
decimalPoint = i;
}
std::string result;
if (decimalPoint != -1)
{
// In reverse order, transfer all digits up to, and including the decimal
// point.
for (i = (int) data.length () - 1; i >= decimalPoint; --i)
result += data[i];
int consecutiveDigits = 0;
for (; i >= 0; --i)
{
if (isdigit (data[i]))
{
result += data[i];
if (++consecutiveDigits == 3 && i && isdigit (data[i - 1]))
{
result += ',';
consecutiveDigits = 0;
}
}
else
result += data[i];
}
}
else
{
// In reverse order, transfer all digits up to, but not including the last
// digit.
for (i = (int) data.length () - 1; i > end; --i)
result += data[i];
int consecutiveDigits = 0;
for (; i >= 0; --i)
{
if (isdigit (data[i]))
{
result += data[i];
if (++consecutiveDigits == 3 && i && isdigit (data[i - 1]))
{
result += ',';
consecutiveDigits = 0;
}
}
else
result += data[i];
}
}
// reverse result into data.
std::string done;
for (int i = (int) result.length () - 1; i >= 0; --i)
done += result[i];
return done;
}
////////////////////////////////////////////////////////////////////////////////
std::string lowerCase (const std::string& input)
{
std::string output = input;
for (int i = 0; i < (int) input.length (); ++i)
if (isupper (input[i]))
output[i] = tolower (input[i]);
return output;
}
////////////////////////////////////////////////////////////////////////////////
std::string upperCase (const std::string& input)
{
std::string output = input;
for (int i = 0; i < (int) input.length (); ++i)
if (islower (input[i]))
output[i] = toupper (input[i]);
return output;
}
////////////////////////////////////////////////////////////////////////////////
std::string ucFirst (const std::string& input)
{
std::string output = input;
if (output.length () > 0)
output[0] = toupper (output[0]);
return output;
}
////////////////////////////////////////////////////////////////////////////////
const char* optionalBlankLine ()
{
if (context.config.getBoolean ("blanklines") == true) // no i18n
return newline;
return noline;
}
////////////////////////////////////////////////////////////////////////////////
void guess (
const std::string& type,
std::vector<std::string>& options,
std::string& candidate)
{
std::vector <std::string> matches;
autoComplete (candidate, options, matches);
if (1 == matches.size ())
candidate = matches[0];
else if (0 == matches.size ())
candidate = "";
else
{
std::string error = "Ambiguous "; // TODO i18n
error += type;
error += " '";
error += candidate;
error += "' - could be either of "; // TODO i18n
for (size_t i = 0; i < matches.size (); ++i)
{
if (i)
error += ", ";
error += matches[i];
}
throw error;
}
}
////////////////////////////////////////////////////////////////////////////////
bool digitsOnly (const std::string& input)
{
for (size_t i = 0; i < input.length (); ++i)
if (!isdigit (input[i]))
return false;
return true;
}
////////////////////////////////////////////////////////////////////////////////
bool noSpaces (const std::string& input)
{
for (size_t i = 0; i < input.length (); ++i)
if (isspace (input[i]))
return false;
return true;
}
////////////////////////////////////////////////////////////////////////////////
bool noVerticalSpace (const std::string& input)
{
if (input.find_first_of ("\n\r\f") != std::string::npos)
return false;
return true;
}
////////////////////////////////////////////////////////////////////////////////
// Input: hello, world
// Result for pos: y......y....
bool isWordStart (const std::string& input, std::string::size_type pos)
{
// Short circuit: no input means no word start.
if (input.length () == 0)
return false;
// If pos is the first alphanumeric character of the string.
if (pos == 0 && isalnum (input[pos]))
return true;
// If pos is not the first alphanumeric character, but there is a preceding
// non-alphanumeric character.
if (pos > 0 && isalnum (input[pos]) && !isalnum (input[pos - 1]))
return true;
return false;
}
////////////////////////////////////////////////////////////////////////////////
// Input: hello, world
// Result for pos: ....y......y
bool isWordEnd (const std::string& input, std::string::size_type pos)
{
// Short circuit: no input means no word start.
if (input.length () == 0)
return false;
// If pos is the last alphanumeric character of the string.
if (pos == input.length () - 1 && isalnum (input[pos]))
return true;
// If pos is not the last alphanumeric character, but there is a following
// non-alphanumeric character.
if (pos < input.length () - 1 && isalnum (input[pos]) && !isalnum (input[pos + 1]))
return true;
return false;
}
////////////////////////////////////////////////////////////////////////////////
bool compare (
const std::string& left,
const std::string& right,
bool sensitive /*= true*/)
{
// Use strcasecmp if required.
if (!sensitive)
return strcasecmp (left.c_str (), right.c_str ()) == 0 ? true : false;
// Otherwise, just use std::string::operator==.
return left == right;
}
////////////////////////////////////////////////////////////////////////////////
std::string::size_type find (
const std::string& text,
const std::string& pattern,
bool sensitive /*= true*/)
{
// Implement a sensitive find, which is really just a loop withing a loop,
// comparing lower-case versions of each character in turn.
if (!sensitive)
{
// Handle empty pattern.
const char* p = pattern.c_str ();
size_t len = pattern.length ();
if (len == 0)
return 0;
// Evaluate these once, for performance reasons.
const char* t = text.c_str ();
const char* start = t;
const char* end = start + text.size ();
for (; t < end - len; ++t)
{
int diff;
for (size_t i = 0; i < len; ++i)
if ((diff = tolower (t[i]) - tolower (p[i])))
break;
// diff == 0 means there was no break from the loop, which only occurs
// when a difference is detected. Therefore, the loop terminated, and
// diff is zero.
if (diff == 0)
return t - start;
}
return std::string::npos;
}
// Otherwise, just use std::string::find.
return text.find (pattern);
}
////////////////////////////////////////////////////////////////////////////////
std::string::size_type find (
const std::string& text,
const std::string& pattern,
std::string::size_type begin,
bool sensitive /*= true*/)
{
// Implement a sensitive find, which is really just a loop withing a loop,
// comparing lower-case versions of each character in turn.
if (!sensitive)
{
// Handle empty pattern.
const char* p = pattern.c_str ();
size_t len = pattern.length ();
if (len == 0)
return 0;
// Handle bad begin.
if (begin >= len)
return std::string::npos;
// Evaluate these once, for performance reasons.
const char* t = text.c_str ();
const char* start = t + begin;
const char* end = start + text.size ();
for (; t < end - len; ++t)
{
int diff;
for (size_t i = 0; i < len; ++i)
if ((diff = tolower (t[i]) - tolower (p[i])))
break;
// diff == 0 means there was no break from the loop, which only occurs
// when a difference is detected. Therefore, the loop terminated, and
// diff is zero.
if (diff == 0)
return t - start;
}
return std::string::npos;
}
// Otherwise, just use std::string::find.
return text.find (pattern, begin);
}
////////////////////////////////////////////////////////////////////////////////
<commit_msg>Enhancement - caseless find<commit_after>////////////////////////////////////////////////////////////////////////////////
// task - a command line task list manager.
//
// Copyright 2006 - 2010, Paul Beckingham.
// All rights reserved.
//
// This program is free software; you can redistribute it and/or modify it under
// the terms of the GNU General Public License as published by the Free Software
// Foundation; either version 2 of the License, or (at your option) any later
// version.
//
// This program is distributed in the hope that it will be useful, but WITHOUT
// ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
// FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
// details.
//
// You should have received a copy of the GNU General Public License along with
// this program; if not, write to the
//
// Free Software Foundation, Inc.,
// 51 Franklin Street, Fifth Floor,
// Boston, MA
// 02110-1301
// USA
//
////////////////////////////////////////////////////////////////////////////////
#include <iostream>
#include <vector>
#include <string>
#include <strings.h>
#include <ctype.h>
#include "Context.h"
#include "util.h"
#include "text.h"
extern Context context;
static const char* newline = "\n";
static const char* noline = "";
///////////////////////////////////////////////////////////////////////////////
void wrapText (
std::vector <std::string>& lines,
const std::string& text,
const int width)
{
std::string copy = text;
std::string line;
while (copy.length ())
{
extractLine (copy, line, width);
lines.push_back (line);
}
}
////////////////////////////////////////////////////////////////////////////////
void split (
std::vector<std::string>& results,
const std::string& input,
const char delimiter)
{
results.clear ();
std::string::size_type start = 0;
std::string::size_type i;
while ((i = input.find (delimiter, start)) != std::string::npos)
{
results.push_back (input.substr (start, i - start));
start = i + 1;
}
if (input.length ())
results.push_back (input.substr (start));
}
////////////////////////////////////////////////////////////////////////////////
void split_minimal (
std::vector<std::string>& results,
const std::string& input,
const char delimiter)
{
results.clear ();
std::string::size_type start = 0;
std::string::size_type i;
while ((i = input.find (delimiter, start)) != std::string::npos)
{
if (i != start)
results.push_back (input.substr (start, i - start));
start = i + 1;
}
if (input.length ())
results.push_back (input.substr (start));
}
////////////////////////////////////////////////////////////////////////////////
void split (
std::vector<std::string>& results,
const std::string& input,
const std::string& delimiter)
{
results.clear ();
std::string::size_type length = delimiter.length ();
std::string::size_type start = 0;
std::string::size_type i;
while ((i = input.find (delimiter, start)) != std::string::npos)
{
results.push_back (input.substr (start, i - start));
start = i + length;
}
if (input.length ())
results.push_back (input.substr (start));
}
////////////////////////////////////////////////////////////////////////////////
void split_minimal (
std::vector<std::string>& results,
const std::string& input,
const std::string& delimiter)
{
results.clear ();
std::string::size_type length = delimiter.length ();
std::string::size_type start = 0;
std::string::size_type i;
while ((i = input.find (delimiter, start)) != std::string::npos)
{
if (i != start)
results.push_back (input.substr (start, i - start));
start = i + length;
}
if (input.length ())
results.push_back (input.substr (start));
}
////////////////////////////////////////////////////////////////////////////////
void join (
std::string& result,
const std::string& separator,
const std::vector<std::string>& items)
{
result = "";
unsigned int size = items.size ();
for (unsigned int i = 0; i < size; ++i)
{
result += items[i];
if (i < size - 1)
result += separator;
}
}
////////////////////////////////////////////////////////////////////////////////
std::string trimLeft (const std::string& in, const std::string& t /*= " "*/)
{
std::string out = in;
return out.erase (0, in.find_first_not_of (t));
}
////////////////////////////////////////////////////////////////////////////////
std::string trimRight (const std::string& in, const std::string& t /*= " "*/)
{
std::string out = in;
return out.erase (out.find_last_not_of (t) + 1);
}
////////////////////////////////////////////////////////////////////////////////
std::string trim (const std::string& in, const std::string& t /*= " "*/)
{
std::string out = in;
return trimLeft (trimRight (out, t), t);
}
////////////////////////////////////////////////////////////////////////////////
// Remove enclosing balanced quotes. Assumes trimmed text.
std::string unquoteText (const std::string& input)
{
std::string output = input;
if (output.length () > 1)
{
char quote = output[0];
if ((quote == '\'' || quote == '"') &&
output[output.length () - 1] == quote)
return output.substr (1, output.length () - 2);
}
return output;
}
////////////////////////////////////////////////////////////////////////////////
void extractLine (std::string& text, std::string& line, int length)
{
size_t eol = text.find ("\n");
// Special case: found \n in first length characters.
if (eol != std::string::npos && eol < (unsigned) length)
{
line = text.substr (0, eol); // strip \n
text = text.substr (eol + 1);
return;
}
// Special case: no \n, and less than length characters total.
// special case: text.find ("\n") == std::string::npos && text.length () < length
if (eol == std::string::npos && text.length () <= (unsigned) length)
{
line = text;
text = "";
return;
}
// Safe to ASSERT text.length () > length
// Look for the last space prior to length
eol = length;
while (eol && text[eol] != ' ' && text[eol] != '\n')
--eol;
// If a space was found, break there.
if (eol)
{
line = text.substr (0, eol);
text = text.substr (eol + 1);
}
// If no space was found, hyphenate.
else
{
if (length > 1)
{
line = text.substr (0, length - 1) + "-";
text = text.substr (length - 1);
}
else
{
line = text.substr (0, 1);
text = text.substr (length);
}
}
}
////////////////////////////////////////////////////////////////////////////////
std::string commify (const std::string& data)
{
// First scan for decimal point and end of digits.
int decimalPoint = -1;
int end = -1;
int i;
for (int i = 0; i < (int) data.length (); ++i)
{
if (isdigit (data[i]))
end = i;
if (data[i] == '.')
decimalPoint = i;
}
std::string result;
if (decimalPoint != -1)
{
// In reverse order, transfer all digits up to, and including the decimal
// point.
for (i = (int) data.length () - 1; i >= decimalPoint; --i)
result += data[i];
int consecutiveDigits = 0;
for (; i >= 0; --i)
{
if (isdigit (data[i]))
{
result += data[i];
if (++consecutiveDigits == 3 && i && isdigit (data[i - 1]))
{
result += ',';
consecutiveDigits = 0;
}
}
else
result += data[i];
}
}
else
{
// In reverse order, transfer all digits up to, but not including the last
// digit.
for (i = (int) data.length () - 1; i > end; --i)
result += data[i];
int consecutiveDigits = 0;
for (; i >= 0; --i)
{
if (isdigit (data[i]))
{
result += data[i];
if (++consecutiveDigits == 3 && i && isdigit (data[i - 1]))
{
result += ',';
consecutiveDigits = 0;
}
}
else
result += data[i];
}
}
// reverse result into data.
std::string done;
for (int i = (int) result.length () - 1; i >= 0; --i)
done += result[i];
return done;
}
////////////////////////////////////////////////////////////////////////////////
std::string lowerCase (const std::string& input)
{
std::string output = input;
for (int i = 0; i < (int) input.length (); ++i)
if (isupper (input[i]))
output[i] = tolower (input[i]);
return output;
}
////////////////////////////////////////////////////////////////////////////////
std::string upperCase (const std::string& input)
{
std::string output = input;
for (int i = 0; i < (int) input.length (); ++i)
if (islower (input[i]))
output[i] = toupper (input[i]);
return output;
}
////////////////////////////////////////////////////////////////////////////////
std::string ucFirst (const std::string& input)
{
std::string output = input;
if (output.length () > 0)
output[0] = toupper (output[0]);
return output;
}
////////////////////////////////////////////////////////////////////////////////
const char* optionalBlankLine ()
{
if (context.config.getBoolean ("blanklines") == true) // no i18n
return newline;
return noline;
}
////////////////////////////////////////////////////////////////////////////////
void guess (
const std::string& type,
std::vector<std::string>& options,
std::string& candidate)
{
std::vector <std::string> matches;
autoComplete (candidate, options, matches);
if (1 == matches.size ())
candidate = matches[0];
else if (0 == matches.size ())
candidate = "";
else
{
std::string error = "Ambiguous "; // TODO i18n
error += type;
error += " '";
error += candidate;
error += "' - could be either of "; // TODO i18n
for (size_t i = 0; i < matches.size (); ++i)
{
if (i)
error += ", ";
error += matches[i];
}
throw error;
}
}
////////////////////////////////////////////////////////////////////////////////
bool digitsOnly (const std::string& input)
{
for (size_t i = 0; i < input.length (); ++i)
if (!isdigit (input[i]))
return false;
return true;
}
////////////////////////////////////////////////////////////////////////////////
bool noSpaces (const std::string& input)
{
for (size_t i = 0; i < input.length (); ++i)
if (isspace (input[i]))
return false;
return true;
}
////////////////////////////////////////////////////////////////////////////////
bool noVerticalSpace (const std::string& input)
{
if (input.find_first_of ("\n\r\f") != std::string::npos)
return false;
return true;
}
////////////////////////////////////////////////////////////////////////////////
// Input: hello, world
// Result for pos: y......y....
bool isWordStart (const std::string& input, std::string::size_type pos)
{
// Short circuit: no input means no word start.
if (input.length () == 0)
return false;
// If pos is the first alphanumeric character of the string.
if (pos == 0 && isalnum (input[pos]))
return true;
// If pos is not the first alphanumeric character, but there is a preceding
// non-alphanumeric character.
if (pos > 0 && isalnum (input[pos]) && !isalnum (input[pos - 1]))
return true;
return false;
}
////////////////////////////////////////////////////////////////////////////////
// Input: hello, world
// Result for pos: ....y......y
bool isWordEnd (const std::string& input, std::string::size_type pos)
{
// Short circuit: no input means no word start.
if (input.length () == 0)
return false;
// If pos is the last alphanumeric character of the string.
if (pos == input.length () - 1 && isalnum (input[pos]))
return true;
// If pos is not the last alphanumeric character, but there is a following
// non-alphanumeric character.
if (pos < input.length () - 1 && isalnum (input[pos]) && !isalnum (input[pos + 1]))
return true;
return false;
}
////////////////////////////////////////////////////////////////////////////////
bool compare (
const std::string& left,
const std::string& right,
bool sensitive /*= true*/)
{
// Use strcasecmp if required.
if (!sensitive)
return strcasecmp (left.c_str (), right.c_str ()) == 0 ? true : false;
// Otherwise, just use std::string::operator==.
return left == right;
}
////////////////////////////////////////////////////////////////////////////////
std::string::size_type find (
const std::string& text,
const std::string& pattern,
bool sensitive /*= true*/)
{
// Implement a sensitive find, which is really just a loop withing a loop,
// comparing lower-case versions of each character in turn.
if (!sensitive)
{
// Handle empty pattern.
const char* p = pattern.c_str ();
size_t len = pattern.length ();
if (len == 0)
return 0;
// Evaluate these once, for performance reasons.
const char* t = text.c_str ();
const char* start = t;
const char* end = start + text.size ();
for (; t < end - len; ++t)
{
int diff;
for (size_t i = 0; i < len; ++i)
if ((diff = tolower (t[i]) - tolower (p[i])))
break;
// diff == 0 means there was no break from the loop, which only occurs
// when a difference is detected. Therefore, the loop terminated, and
// diff is zero.
if (diff == 0)
return t - start;
}
return std::string::npos;
}
// Otherwise, just use std::string::find.
return text.find (pattern);
}
////////////////////////////////////////////////////////////////////////////////
std::string::size_type find (
const std::string& text,
const std::string& pattern,
std::string::size_type begin,
bool sensitive /*= true*/)
{
// Implement a sensitive find, which is really just a loop withing a loop,
// comparing lower-case versions of each character in turn.
if (!sensitive)
{
// Handle empty pattern.
const char* p = pattern.c_str ();
size_t len = pattern.length ();
if (len == 0)
return 0;
// Handle bad begin.
if (begin >= text.length ())
return std::string::npos;
// Evaluate these once, for performance reasons.
const char* start = text.c_str ();
const char* t = start + begin;
const char* end = start + text.size ();
for (; t < end - len; ++t)
{
int diff;
for (size_t i = 0; i < len; ++i)
if ((diff = tolower (t[i]) - tolower (p[i])))
break;
// diff == 0 means there was no break from the loop, which only occurs
// when a difference is detected. Therefore, the loop terminated, and
// diff is zero.
if (diff == 0)
return t - start;
}
return std::string::npos;
}
// Otherwise, just use std::string::find.
return text.find (pattern, begin);
}
////////////////////////////////////////////////////////////////////////////////
<|endoftext|> |
<commit_before>#include "token.h"
namespace flora {
Token Tokens::LookupKeyword(const std::string &identifier) {
auto result = lookup_table_.find(identifier);
return result == lookup_table_.end() ? result->second : Token::Identifier;
}
#define T(name, literal, precedence) #name,
const char *Tokens::name_[Tokens::TOKEN_COUNT] = {
TOKEN_LIST(T, T)
};
#undef T
#define T(name, literal, precedence) #literal,
const char *Tokens::literal_[Tokens::TOKEN_COUNT] = {
TOKEN_LIST(T, T)
};
#undef T
#define T(name, literal, precedence) precedence,
const int Tokens::precedence_[Tokens::TOKEN_COUNT] = {
TOKEN_LIST(T, T)
};
#undef T
std::unordered_map<std::string, Token> Tokens::lookup_table_;
void Tokens::InitializeKeywordLookupTable() {
#define K(name, literal, precedence) lookup_table_[std::string(literal)] = Token::name;
#define T(name, literal, precedence)
TOKEN_LIST(K, T)
#undef K
#undef T
}
Tokens::Tokens() {
InitializeKeywordLookupTable();
}
}<commit_msg>Fixed a logical error that cause segment fault.<commit_after>#include "token.h"
namespace flora {
Token Tokens::LookupKeyword(const std::string &identifier) {
auto result = lookup_table_.find(identifier);
return result == lookup_table_.end() ? Token::Identifier : result->second;
}
#define T(name, literal, precedence) #name,
const char *Tokens::name_[Tokens::TOKEN_COUNT] = {
TOKEN_LIST(T, T)
};
#undef T
#define T(name, literal, precedence) #literal,
const char *Tokens::literal_[Tokens::TOKEN_COUNT] = {
TOKEN_LIST(T, T)
};
#undef T
#define T(name, literal, precedence) precedence,
const int Tokens::precedence_[Tokens::TOKEN_COUNT] = {
TOKEN_LIST(T, T)
};
#undef T
std::unordered_map<std::string, Token> Tokens::lookup_table_;
void Tokens::InitializeKeywordLookupTable() {
#define K(name, literal, precedence) lookup_table_[std::string(literal)] = Token::name;
#define T(name, literal, precedence)
TOKEN_LIST(K, T)
#undef K
#undef T
}
Tokens::Tokens() {
InitializeKeywordLookupTable();
}
Tokens Tokens::singleton;
}<|endoftext|> |
<commit_before>#include "tree.h"
#include "entry_points.h"
#include "oid.h"
#include "repository.h"
/******************************************************************************/
// Tree
static void _git_tree_free(git_tree *tree)
{
git_object_free((git_object *)tree);
}
Tree::Tree(git_tree *_tree)
{
tree = boost::shared_ptr<git_tree>(_tree, _git_tree_free);
}
Rcpp::Reference Tree::id()
{
const git_oid *result = git_tree_id(tree.get());
return OID::create(result);
}
size_t Tree::entry_count()
{
return git_tree_entrycount(tree.get());
}
static int walk_cb(const char *root, const git_tree_entry *entry, void *payload)
{
Rcpp::Function *f = (Rcpp::Function *)payload;
int r = Rcpp::as<int>((*f)(std::string(root)));
return r;
}
int Tree::walk_pre(Rcpp::Function fcall)
{
git_tree_walk(tree.get(), GIT_TREEWALK_PRE, &walk_cb, &fcall);
}
int Tree::walk_post(Rcpp::Function fcall)
{
git_tree_walk(tree.get(), GIT_TREEWALK_POST, &walk_cb, &fcall);
}
Rcpp::Reference Tree::entry_by_index(size_t idx)
{
BEGIN_RCPP
const git_tree_entry *entry = git_tree_entry_byindex(tree.get(), idx);
if (entry == NULL)
throw Rcpp::exception("entry not found");
git_tree_entry *dup;
int err = git_tree_entry_dup(&dup, entry);
if (err)
throw Rcpp::exception("entry duplication failed");
return TreeEntry::create(dup);
END_RCPP
}
Rcpp::Reference Tree::entry_by_name(std::string name)
{
BEGIN_RCPP
const git_tree_entry *entry = git_tree_entry_byname(tree.get(), name.c_str());
if (entry == NULL)
throw Rcpp::exception("entry not found");
git_tree_entry *dup;
int err = git_tree_entry_dup(&dup, entry);
if (err)
throw Rcpp::exception("entry duplication failed");
return TreeEntry::create(dup);
END_RCPP
}
Rcpp::Reference Tree::entry_by_path(std::string name)
{
BEGIN_RCPP
git_tree_entry *entry;
int err = git_tree_entry_bypath(&entry, tree.get(), name.c_str());
if (err)
throw Rcpp::exception("entry not found");
return TreeEntry::create(entry);
END_RCPP
}
Rcpp::Reference Tree::entry_by_oid(SEXP oid)
{
BEGIN_RCPP
const git_tree_entry *entry = git_tree_entry_byid(tree.get(), OID::from_sexp(oid));
if (entry == NULL)
throw Rcpp::exception("entry not found");
git_tree_entry *dup;
int err = git_tree_entry_dup(&dup, entry);
if (err)
throw Rcpp::exception("entry duplication failed");
return TreeEntry::create(dup);
END_RCPP
}
/******************************************************************************/
// TreeEntry
TreeEntry::TreeEntry(git_tree_entry *_entry)
{
tree_entry = boost::shared_ptr<git_tree_entry>(_entry, git_tree_entry_free);
}
int TreeEntry::file_mode()
{
return git_tree_entry_filemode(tree_entry.get());
}
Rcpp::Reference TreeEntry::id()
{
return OID::create(git_tree_entry_id(tree_entry.get()));
}
std::string TreeEntry::name()
{
return std::string(git_tree_entry_name(tree_entry.get()));
}
SEXP TreeEntry::object(SEXP _repo)
{
BEGIN_RCPP
git_repository *repo = (git_repository*)Repository::from_sexp(_repo);
git_object *result;
int err = git_tree_entry_to_object(&result, repo, tree_entry.get());
if (err)
throw Rcpp::exception("object lookup failed");
return object_to_sexp(result);
END_RCPP
}
int TreeEntry::type()
{
return git_tree_entry_type(tree_entry.get());
}
RCPP_MODULE(guitar_tree) {
using namespace Rcpp;
class_<Tree>("Tree")
.method("id", &Tree::id)
.method("entry_count", &Tree::entry_count)
.method("walk_pre", &Tree::walk_pre)
.method("walk_post", &Tree::walk_post)
.method("entry_by_index", &Tree::entry_by_index)
.method("entry_by_name", &Tree::entry_by_name)
.method("entry_by_oid", &Tree::entry_by_oid)
.method("entry_by_path", &Tree::entry_by_path)
;
class_<TreeEntry>("TreeEntry")
.method("file_mode", &TreeEntry::file_mode)
.method("id", &TreeEntry::id)
.method("name", &TreeEntry::name)
.method("object", &TreeEntry::object)
.method("type", &TreeEntry::type)
;
}
<commit_msg>fix missing return<commit_after>#include "tree.h"
#include "entry_points.h"
#include "oid.h"
#include "repository.h"
/******************************************************************************/
// Tree
static void _git_tree_free(git_tree *tree)
{
git_object_free((git_object *)tree);
}
Tree::Tree(git_tree *_tree)
{
tree = boost::shared_ptr<git_tree>(_tree, _git_tree_free);
}
Rcpp::Reference Tree::id()
{
const git_oid *result = git_tree_id(tree.get());
return OID::create(result);
}
size_t Tree::entry_count()
{
return git_tree_entrycount(tree.get());
}
static int walk_cb(const char *root, const git_tree_entry *entry, void *payload)
{
Rcpp::Function *f = (Rcpp::Function *)payload;
int r = Rcpp::as<int>((*f)(std::string(root)));
return r;
}
int Tree::walk_pre(Rcpp::Function fcall)
{
return git_tree_walk(tree.get(), GIT_TREEWALK_PRE, &walk_cb, &fcall);
}
int Tree::walk_post(Rcpp::Function fcall)
{
return git_tree_walk(tree.get(), GIT_TREEWALK_POST, &walk_cb, &fcall);
}
Rcpp::Reference Tree::entry_by_index(size_t idx)
{
BEGIN_RCPP
const git_tree_entry *entry = git_tree_entry_byindex(tree.get(), idx);
if (entry == NULL)
throw Rcpp::exception("entry not found");
git_tree_entry *dup;
int err = git_tree_entry_dup(&dup, entry);
if (err)
throw Rcpp::exception("entry duplication failed");
return TreeEntry::create(dup);
END_RCPP
}
Rcpp::Reference Tree::entry_by_name(std::string name)
{
BEGIN_RCPP
const git_tree_entry *entry = git_tree_entry_byname(tree.get(), name.c_str());
if (entry == NULL)
throw Rcpp::exception("entry not found");
git_tree_entry *dup;
int err = git_tree_entry_dup(&dup, entry);
if (err)
throw Rcpp::exception("entry duplication failed");
return TreeEntry::create(dup);
END_RCPP
}
Rcpp::Reference Tree::entry_by_path(std::string name)
{
BEGIN_RCPP
git_tree_entry *entry;
int err = git_tree_entry_bypath(&entry, tree.get(), name.c_str());
if (err)
throw Rcpp::exception("entry not found");
return TreeEntry::create(entry);
END_RCPP
}
Rcpp::Reference Tree::entry_by_oid(SEXP oid)
{
BEGIN_RCPP
const git_tree_entry *entry = git_tree_entry_byid(tree.get(), OID::from_sexp(oid));
if (entry == NULL)
throw Rcpp::exception("entry not found");
git_tree_entry *dup;
int err = git_tree_entry_dup(&dup, entry);
if (err)
throw Rcpp::exception("entry duplication failed");
return TreeEntry::create(dup);
END_RCPP
}
/******************************************************************************/
// TreeEntry
TreeEntry::TreeEntry(git_tree_entry *_entry)
{
tree_entry = boost::shared_ptr<git_tree_entry>(_entry, git_tree_entry_free);
}
int TreeEntry::file_mode()
{
return git_tree_entry_filemode(tree_entry.get());
}
Rcpp::Reference TreeEntry::id()
{
return OID::create(git_tree_entry_id(tree_entry.get()));
}
std::string TreeEntry::name()
{
return std::string(git_tree_entry_name(tree_entry.get()));
}
SEXP TreeEntry::object(SEXP _repo)
{
BEGIN_RCPP
git_repository *repo = (git_repository*)Repository::from_sexp(_repo);
git_object *result;
int err = git_tree_entry_to_object(&result, repo, tree_entry.get());
if (err)
throw Rcpp::exception("object lookup failed");
return object_to_sexp(result);
END_RCPP
}
int TreeEntry::type()
{
return git_tree_entry_type(tree_entry.get());
}
RCPP_MODULE(guitar_tree) {
using namespace Rcpp;
class_<Tree>("Tree")
.method("id", &Tree::id)
.method("entry_count", &Tree::entry_count)
.method("walk_pre", &Tree::walk_pre)
.method("walk_post", &Tree::walk_post)
.method("entry_by_index", &Tree::entry_by_index)
.method("entry_by_name", &Tree::entry_by_name)
.method("entry_by_oid", &Tree::entry_by_oid)
.method("entry_by_path", &Tree::entry_by_path)
;
class_<TreeEntry>("TreeEntry")
.method("file_mode", &TreeEntry::file_mode)
.method("id", &TreeEntry::id)
.method("name", &TreeEntry::name)
.method("object", &TreeEntry::object)
.method("type", &TreeEntry::type)
;
}
<|endoftext|> |
<commit_before>#ifndef units_hh_INCLUDED
#define units_hh_INCLUDED
#include "hash.hh"
#include <type_traits>
namespace Kakoune
{
template<typename RealType, typename ValueType = int>
class StronglyTypedNumber
{
public:
[[gnu::always_inline]]
explicit constexpr StronglyTypedNumber(ValueType value)
: m_value(value)
{
static_assert(std::is_base_of<StronglyTypedNumber, RealType>::value,
"RealType is not derived from StronglyTypedNumber");
}
[[gnu::always_inline]]
constexpr friend RealType operator+(RealType lhs, RealType rhs)
{ return RealType(lhs.m_value + rhs.m_value); }
[[gnu::always_inline]]
constexpr friend RealType operator-(RealType lhs, RealType rhs)
{ return RealType(lhs.m_value - rhs.m_value); }
[[gnu::always_inline]]
constexpr friend RealType operator*(RealType lhs, RealType rhs)
{ return RealType(lhs.m_value * rhs.m_value); }
[[gnu::always_inline]]
constexpr friend RealType operator/(RealType lhs, RealType rhs)
{ return RealType(lhs.m_value / rhs.m_value); }
[[gnu::always_inline]]
RealType& operator+=(RealType other)
{ m_value += other.m_value; return static_cast<RealType&>(*this); }
[[gnu::always_inline]]
RealType& operator-=(RealType other)
{ m_value -= other.m_value; return static_cast<RealType&>(*this); }
[[gnu::always_inline]]
RealType& operator*=(RealType other)
{ m_value *= other.m_value; return static_cast<RealType&>(*this); }
[[gnu::always_inline]]
RealType& operator/=(RealType other)
{ m_value /= other.m_value; return static_cast<RealType&>(*this); }
[[gnu::always_inline]]
RealType& operator++()
{ ++m_value; return static_cast<RealType&>(*this); }
[[gnu::always_inline]]
RealType& operator--()
{ --m_value; return static_cast<RealType&>(*this); }
[[gnu::always_inline]]
RealType operator++(int)
{ RealType backup(static_cast<RealType&>(*this)); ++m_value; return backup; }
[[gnu::always_inline]]
RealType operator--(int)
{ RealType backup(static_cast<RealType&>(*this)); --m_value; return backup; }
[[gnu::always_inline]]
constexpr RealType operator-() const { return RealType(-m_value); }
[[gnu::always_inline]]
constexpr friend RealType operator%(RealType lhs, RealType rhs)
{ return RealType(lhs.m_value % rhs.m_value); }
[[gnu::always_inline]]
RealType& operator%=(RealType other)
{ m_value %= other.m_value; return static_cast<RealType&>(*this); }
[[gnu::always_inline]]
constexpr friend bool operator==(RealType lhs, RealType rhs)
{ return lhs.m_value == rhs.m_value; }
[[gnu::always_inline]]
constexpr friend bool operator!=(RealType lhs, RealType rhs)
{ return lhs.m_value != rhs.m_value; }
[[gnu::always_inline]]
constexpr friend bool operator<(RealType lhs, RealType rhs)
{ return lhs.m_value < rhs.m_value; }
[[gnu::always_inline]]
constexpr friend bool operator<=(RealType lhs, RealType rhs)
{ return lhs.m_value <= rhs.m_value; }
[[gnu::always_inline]]
constexpr friend bool operator>(RealType lhs, RealType rhs)
{ return lhs.m_value > rhs.m_value; }
[[gnu::always_inline]]
constexpr friend bool operator>=(RealType lhs, RealType rhs)
{ return lhs.m_value >= rhs.m_value; }
[[gnu::always_inline]]
constexpr bool operator!() const
{ return not m_value; }
[[gnu::always_inline]]
explicit constexpr operator ValueType() const { return m_value; }
[[gnu::always_inline]]
explicit constexpr operator bool() const { return m_value; }
friend size_t hash_value(RealType val) { return hash_value(val.m_value); }
friend size_t abs(RealType val) { return val.m_value < ValueType(0) ? -val.m_value : val.m_value; }
private:
ValueType m_value;
};
struct LineCount : public StronglyTypedNumber<LineCount, int>
{
[[gnu::always_inline]]
constexpr LineCount(int value = 0) : StronglyTypedNumber<LineCount>(value) {}
};
[[gnu::always_inline]]
inline constexpr LineCount operator"" _line(unsigned long long int value)
{
return LineCount(value);
}
struct ByteCount : public StronglyTypedNumber<ByteCount, int>
{
[[gnu::always_inline]]
constexpr ByteCount(int value = 0) : StronglyTypedNumber<ByteCount>(value) {}
};
[[gnu::always_inline]]
inline constexpr ByteCount operator"" _byte(unsigned long long int value)
{
return ByteCount(value);
}
struct CharCount : public StronglyTypedNumber<CharCount, int>
{
[[gnu::always_inline]]
constexpr CharCount(int value = 0) : StronglyTypedNumber<CharCount>(value) {}
};
[[gnu::always_inline]]
inline constexpr CharCount operator"" _char(unsigned long long int value)
{
return CharCount(value);
}
}
#endif // units_hh_INCLUDED
<commit_msg>Add checked, explicit conversion from strongly typed number for size_t<commit_after>#ifndef units_hh_INCLUDED
#define units_hh_INCLUDED
#include "assert.hh"
#include "hash.hh"
#include <type_traits>
namespace Kakoune
{
template<typename RealType, typename ValueType = int>
class StronglyTypedNumber
{
public:
[[gnu::always_inline]]
explicit constexpr StronglyTypedNumber(ValueType value)
: m_value(value)
{
static_assert(std::is_base_of<StronglyTypedNumber, RealType>::value,
"RealType is not derived from StronglyTypedNumber");
}
[[gnu::always_inline]]
constexpr friend RealType operator+(RealType lhs, RealType rhs)
{ return RealType(lhs.m_value + rhs.m_value); }
[[gnu::always_inline]]
constexpr friend RealType operator-(RealType lhs, RealType rhs)
{ return RealType(lhs.m_value - rhs.m_value); }
[[gnu::always_inline]]
constexpr friend RealType operator*(RealType lhs, RealType rhs)
{ return RealType(lhs.m_value * rhs.m_value); }
[[gnu::always_inline]]
constexpr friend RealType operator/(RealType lhs, RealType rhs)
{ return RealType(lhs.m_value / rhs.m_value); }
[[gnu::always_inline]]
RealType& operator+=(RealType other)
{ m_value += other.m_value; return static_cast<RealType&>(*this); }
[[gnu::always_inline]]
RealType& operator-=(RealType other)
{ m_value -= other.m_value; return static_cast<RealType&>(*this); }
[[gnu::always_inline]]
RealType& operator*=(RealType other)
{ m_value *= other.m_value; return static_cast<RealType&>(*this); }
[[gnu::always_inline]]
RealType& operator/=(RealType other)
{ m_value /= other.m_value; return static_cast<RealType&>(*this); }
[[gnu::always_inline]]
RealType& operator++()
{ ++m_value; return static_cast<RealType&>(*this); }
[[gnu::always_inline]]
RealType& operator--()
{ --m_value; return static_cast<RealType&>(*this); }
[[gnu::always_inline]]
RealType operator++(int)
{ RealType backup(static_cast<RealType&>(*this)); ++m_value; return backup; }
[[gnu::always_inline]]
RealType operator--(int)
{ RealType backup(static_cast<RealType&>(*this)); --m_value; return backup; }
[[gnu::always_inline]]
constexpr RealType operator-() const { return RealType(-m_value); }
[[gnu::always_inline]]
constexpr friend RealType operator%(RealType lhs, RealType rhs)
{ return RealType(lhs.m_value % rhs.m_value); }
[[gnu::always_inline]]
RealType& operator%=(RealType other)
{ m_value %= other.m_value; return static_cast<RealType&>(*this); }
[[gnu::always_inline]]
constexpr friend bool operator==(RealType lhs, RealType rhs)
{ return lhs.m_value == rhs.m_value; }
[[gnu::always_inline]]
constexpr friend bool operator!=(RealType lhs, RealType rhs)
{ return lhs.m_value != rhs.m_value; }
[[gnu::always_inline]]
constexpr friend bool operator<(RealType lhs, RealType rhs)
{ return lhs.m_value < rhs.m_value; }
[[gnu::always_inline]]
constexpr friend bool operator<=(RealType lhs, RealType rhs)
{ return lhs.m_value <= rhs.m_value; }
[[gnu::always_inline]]
constexpr friend bool operator>(RealType lhs, RealType rhs)
{ return lhs.m_value > rhs.m_value; }
[[gnu::always_inline]]
constexpr friend bool operator>=(RealType lhs, RealType rhs)
{ return lhs.m_value >= rhs.m_value; }
[[gnu::always_inline]]
constexpr bool operator!() const
{ return not m_value; }
[[gnu::always_inline]]
explicit constexpr operator ValueType() const { return m_value; }
[[gnu::always_inline]]
explicit constexpr operator bool() const { return m_value; }
friend size_t hash_value(RealType val) { return hash_value(val.m_value); }
friend size_t abs(RealType val) { return val.m_value < ValueType(0) ? -val.m_value : val.m_value; }
explicit operator size_t() { kak_assert(m_value >= 0); return (size_t)m_value; }
protected:
ValueType m_value;
};
struct LineCount : public StronglyTypedNumber<LineCount, int>
{
[[gnu::always_inline]]
constexpr LineCount(int value = 0) : StronglyTypedNumber<LineCount>(value) {}
};
[[gnu::always_inline]]
inline constexpr LineCount operator"" _line(unsigned long long int value)
{
return LineCount(value);
}
struct ByteCount : public StronglyTypedNumber<ByteCount, int>
{
[[gnu::always_inline]]
constexpr ByteCount(int value = 0) : StronglyTypedNumber<ByteCount>(value) {}
};
[[gnu::always_inline]]
inline constexpr ByteCount operator"" _byte(unsigned long long int value)
{
return ByteCount(value);
}
struct CharCount : public StronglyTypedNumber<CharCount, int>
{
[[gnu::always_inline]]
constexpr CharCount(int value = 0) : StronglyTypedNumber<CharCount>(value) {}
};
[[gnu::always_inline]]
inline constexpr CharCount operator"" _char(unsigned long long int value)
{
return CharCount(value);
}
}
#endif // units_hh_INCLUDED
<|endoftext|> |
<commit_before>/**
* Released under the same permissive MIT-license as Urho3D.
* https://raw.githubusercontent.com/urho3d/Urho3D/master/License.txt
*/
#include <string>
#include <Urho3D/Urho3D.h>
#include <Urho3D/Core/CoreEvents.h>
#include <Urho3D/Engine/Application.h>
#include <Urho3D/Engine/Engine.h>
#include <Urho3D/Input/Input.h>
#include <Urho3D/Input/InputEvents.h>
#include <Urho3D/Resource/ResourceCache.h>
#include <Urho3D/Resource/XMLFile.h>
#include <Urho3D/IO/Log.h>
#include <Urho3D/UI/UI.h>
#include <Urho3D/UI/Text.h>
#include <Urho3D/UI/Font.h>
#include <Urho3D/UI/Button.h>
#include <Urho3D/UI/UIEvents.h>
#include <Urho3D/Scene/Scene.h>
#include <Urho3D/Scene/SceneEvents.h>
#include <Urho3D/Graphics/Graphics.h>
#include <Urho3D/Graphics/Camera.h>
#include <Urho3D/Graphics/Geometry.h>
#include <Urho3D/Graphics/Renderer.h>
#include <Urho3D/Graphics/DebugRenderer.h>
#include <Urho3D/Graphics/Octree.h>
#include <Urho3D/Graphics/Light.h>
#include <Urho3D/Graphics/Model.h>
#include <Urho3D/Graphics/StaticModel.h>
#include <Urho3D/Graphics/Material.h>
#include <Urho3D/Graphics/Skybox.h>
using namespace Urho3D;
class MyApp : public Application
{
public:
int framecount_;
float time_;
SharedPtr<Text> text_;
SharedPtr<Scene> scene_;
SharedPtr<Node> boxNode_;
Node* cameraNode_;
MyApp(Context * context) : Application(context),framecount_(0),time_(0)
{
}
virtual void Setup()
{
engineParameters_["FullScreen"]=false;
engineParameters_["WindowWidth"]=1280;
engineParameters_["WindowHeight"]=720;
engineParameters_["WindowResizable"]=true;
}
virtual void Start()
{
ResourceCache* cache=GetSubsystem<ResourceCache>();
GetSubsystem<Input>()->SetMouseVisible(true);
GetSubsystem<Input>()->SetMouseGrabbed(false);
GetSubsystem<UI>()->GetRoot()->SetDefaultStyle(cache->GetResource<XMLFile>("UI/DefaultStyle.xml"));
text_=new Text(context_);
text_->SetText("Keys: tab = toggle mouse, AWSD = move camera, Shift = fast mode, Esc = quit.\nWait a bit to see FPS.");
text_->SetFont(cache->GetResource<Font>("Fonts/Anonymous Pro.ttf"),20);
text_->SetColor(Color(.3,0,.3));
text_->SetHorizontalAlignment(HA_CENTER);
text_->SetVerticalAlignment(VA_TOP);
GetSubsystem<UI>()->GetRoot()->AddChild(text_);
Button* button=new Button(context_);
GetSubsystem<UI>()->GetRoot()->AddChild(button);
button->SetName("Button Quit");
button->SetStyle("Button");
button->SetSize(32,32);
button->SetPosition(16,16);
GetSubsystem<Input>()->SetMouseVisible(false);
GetSubsystem<Input>()->SetMouseGrabbed(true);
scene_=new Scene(context_);
scene_->CreateComponent<Octree>();
scene_->CreateComponent<DebugRenderer>();
Node* skyNode=scene_->CreateChild("Sky");
skyNode->SetScale(500.0f); // The scale actually does not matter
Skybox* skybox=skyNode->CreateComponent<Skybox>();
skybox->SetModel(cache->GetResource<Model>("Models/Box.mdl"));
skybox->SetMaterial(cache->GetResource<Material>("Materials/Skybox.xml"));
boxNode_=scene_->CreateChild("Box");
boxNode_->SetPosition(Vector3(0,0,5));
StaticModel* boxObject=boxNode_->CreateComponent<StaticModel>();
boxObject->SetModel(cache->GetResource<Model>("Models/Box.mdl"));
boxObject->SetMaterial(cache->GetResource<Material>("Materials/Stone.xml"));
for(int x=-30;x<30;x+=3)
for(int y=-30;y<30;y+=3)
{
Node* boxNode_=scene_->CreateChild("Box");
boxNode_->SetPosition(Vector3(x,-3,y));
StaticModel* boxObject=boxNode_->CreateComponent<StaticModel>();
boxObject->SetModel(cache->GetResource<Model>("Models/Box.mdl"));
boxObject->SetMaterial(cache->GetResource<Material>("Materials/Stone.xml"));
boxObject->SetCastShadows(true);
}
cameraNode_=scene_->CreateChild("Camera");
Camera* camera=cameraNode_->CreateComponent<Camera>();
camera->SetFarClip(2000);
{
Node* lightNode=scene_->CreateChild("Light");
lightNode->SetPosition(Vector3(-5,10,5));
Light* light=lightNode->CreateComponent<Light>();
light->SetLightType(LIGHT_POINT);
light->SetRange(50);
light->SetBrightness(1.2);
light->SetColor(Color(1,.5,.8,1));
}
{
Node* lightNode=scene_->CreateChild("Light");
lightNode->SetPosition(Vector3(5,-3,5));
Light* light=lightNode->CreateComponent<Light>();
light->SetLightType(LIGHT_POINT);
light->SetRange(50);
light->SetBrightness(1.2);
light->SetColor(Color(.5,.8,1,1));
}
{
Light* light=cameraNode_->CreateComponent<Light>();
light->SetLightType(LIGHT_POINT);
light->SetRange(10);
light->SetBrightness(2.0);
light->SetColor(Color(.8,1,.8,1.0));
}
Renderer* renderer=GetSubsystem<Renderer>();
SharedPtr<Viewport> viewport(new Viewport(context_,scene_,cameraNode_->GetComponent<Camera>()));
renderer->SetViewport(0,viewport);
SubscribeToEvent(E_BEGINFRAME,HANDLER(MyApp,HandleBeginFrame));
SubscribeToEvent(E_KEYDOWN,HANDLER(MyApp,HandleKeyDown));
SubscribeToEvent(E_UIMOUSECLICK,HANDLER(MyApp,HandleControlClicked));
SubscribeToEvent(E_UPDATE,HANDLER(MyApp,HandleUpdate));
SubscribeToEvent(E_POSTUPDATE,HANDLER(MyApp,HandlePostUpdate));
SubscribeToEvent(E_RENDERUPDATE,HANDLER(MyApp,HandleRenderUpdate));
SubscribeToEvent(E_POSTRENDERUPDATE,HANDLER(MyApp,HandlePostRenderUpdate));
SubscribeToEvent(E_ENDFRAME,HANDLER(MyApp,HandleEndFrame));
}
virtual void Stop()
{
}
void HandleKeyDown(StringHash eventType,VariantMap& eventData)
{
using namespace KeyDown;
int key=eventData[P_KEY].GetInt();
if(key==KEY_ESC)
engine_->Exit();
if(key==KEY_TAB)
{
GetSubsystem<Input>()->SetMouseVisible(!GetSubsystem<Input>()->IsMouseVisible());
GetSubsystem<Input>()->SetMouseGrabbed(!GetSubsystem<Input>()->IsMouseGrabbed());
}
}
void HandleControlClicked(StringHash eventType,VariantMap& eventData)
{
// Query the clicked UI element.
UIElement* clicked=static_cast<UIElement*>(eventData[UIMouseClick::P_ELEMENT].GetPtr());
if(clicked)
if(clicked->GetName()=="Button Quit") // check if the quit button was clicked
engine_->Exit();
}
void HandleUpdate(StringHash eventType,VariantMap& eventData)
{
float timeStep=eventData[Update::P_TIMESTEP].GetFloat();
framecount_++;
time_+=timeStep;
// Movement speed as world units per second
float MOVE_SPEED=10.0f;
// Mouse sensitivity as degrees per pixel
const float MOUSE_SENSITIVITY=0.1f;
if(time_ >=1)
{
std::string str;
str.append("Keys: tab = toggle mouse, AWSD = move camera, Shift = fast mode, Esc = quit.\n");
str.append(std::to_string(framecount_));
str.append(" frames in ");
str.append(std::to_string(time_));
str.append(" seconds = ");
str.append(std::to_string((float)framecount_ / time_));
str.append(" fps");
String s(str.c_str(),str.size());
text_->SetText(s);
framecount_=0;
time_=0;
}
// Rotate the box thingy.
// A much nicer way of doing this would be with a LogicComponent.
// With LogicComponents it is easy to control things like movement
// and animation from some IDE, console or just in game.
// Alas, it is out of the scope for our simple example.
boxNode_->Rotate(Quaternion(8*timeStep,16*timeStep,0));
Input* input=GetSubsystem<Input>();
if(input->GetQualifierDown(1)) // 1 is shift, 2 is ctrl, 4 is alt
MOVE_SPEED*=10;
if(input->GetKeyDown('W'))
cameraNode_->Translate(Vector3(0,0, 1)*MOVE_SPEED*timeStep);
if(input->GetKeyDown('S'))
cameraNode_->Translate(Vector3(0,0,-1)*MOVE_SPEED*timeStep);
if(input->GetKeyDown('A'))
cameraNode_->Translate(Vector3(-1,0,0)*MOVE_SPEED*timeStep);
if(input->GetKeyDown('D'))
cameraNode_->Translate(Vector3( 1,0,0)*MOVE_SPEED*timeStep);
if(!GetSubsystem<Input>()->IsMouseVisible())
{
// Use this frame's mouse motion to adjust camera node yaw and pitch. Clamp the pitch between -90 and 90 degrees
IntVector2 mouseMove=input->GetMouseMove();
// avoid the weird extrem values before moving the mouse
if(mouseMove.x_>-2000000000&&mouseMove.y_>-2000000000)
{
static float yaw_=0;
static float pitch_=0;
yaw_+=MOUSE_SENSITIVITY*mouseMove.x_;
pitch_+=MOUSE_SENSITIVITY*mouseMove.y_;
pitch_=Clamp(pitch_,-90.0f,90.0f);
// Reset rotation and set yaw and pitch again
cameraNode_->SetDirection(Vector3::FORWARD);
cameraNode_->Yaw(yaw_);
cameraNode_->Pitch(pitch_);
}
}
}
void HandleBeginFrame(StringHash eventType,VariantMap& eventData)
{
}
void HandlePostUpdate(StringHash eventType,VariantMap& eventData)
{
}
void HandleRenderUpdate(StringHash eventType, VariantMap & eventData)
{
}
void HandlePostRenderUpdate(StringHash eventType, VariantMap & eventData)
{
}
void HandleEndFrame(StringHash eventType,VariantMap& eventData)
{
}
};
/**
* This macro is expaneded to (roughly, depending on OS) this:
*
* > int RunApplication()
* > {
* > Urho3D::SharedPtr<Urho3D::Context> context(new Urho3D::Context());
* > Urho3D::SharedPtr<className> application(new className(context));
* > return application->Run();
* > }
* >
* > int main(int argc, char** argv)
* > {
* > Urho3D::ParseArguments(argc, argv);
* > return function;
* > }
*/
DEFINE_APPLICATION_MAIN(MyApp)
<commit_msg>...missed a comment<commit_after>/**
* Released under the same permissive MIT-license as Urho3D.
* https://raw.githubusercontent.com/urho3d/Urho3D/master/License.txt
*/
#include <string>
#include <Urho3D/Urho3D.h>
#include <Urho3D/Core/CoreEvents.h>
#include <Urho3D/Engine/Application.h>
#include <Urho3D/Engine/Engine.h>
#include <Urho3D/Input/Input.h>
#include <Urho3D/Input/InputEvents.h>
#include <Urho3D/Resource/ResourceCache.h>
#include <Urho3D/Resource/XMLFile.h>
#include <Urho3D/IO/Log.h>
#include <Urho3D/UI/UI.h>
#include <Urho3D/UI/Text.h>
#include <Urho3D/UI/Font.h>
#include <Urho3D/UI/Button.h>
#include <Urho3D/UI/UIEvents.h>
#include <Urho3D/Scene/Scene.h>
#include <Urho3D/Scene/SceneEvents.h>
#include <Urho3D/Graphics/Graphics.h>
#include <Urho3D/Graphics/Camera.h>
#include <Urho3D/Graphics/Geometry.h>
#include <Urho3D/Graphics/Renderer.h>
#include <Urho3D/Graphics/DebugRenderer.h>
#include <Urho3D/Graphics/Octree.h>
#include <Urho3D/Graphics/Light.h>
#include <Urho3D/Graphics/Model.h>
#include <Urho3D/Graphics/StaticModel.h>
#include <Urho3D/Graphics/Material.h>
#include <Urho3D/Graphics/Skybox.h>
using namespace Urho3D;
class MyApp : public Application
{
public:
int framecount_;
float time_;
SharedPtr<Text> text_;
SharedPtr<Scene> scene_;
SharedPtr<Node> boxNode_;
Node* cameraNode_;
MyApp(Context * context) : Application(context),framecount_(0),time_(0)
{
}
virtual void Setup()
{
engineParameters_["FullScreen"]=false;
engineParameters_["WindowWidth"]=1280;
engineParameters_["WindowHeight"]=720;
engineParameters_["WindowResizable"]=true;
}
virtual void Start()
{
ResourceCache* cache=GetSubsystem<ResourceCache>();
GetSubsystem<Input>()->SetMouseVisible(true);
GetSubsystem<Input>()->SetMouseGrabbed(false);
GetSubsystem<UI>()->GetRoot()->SetDefaultStyle(cache->GetResource<XMLFile>("UI/DefaultStyle.xml"));
text_=new Text(context_);
text_->SetText("Keys: tab = toggle mouse, AWSD = move camera, Shift = fast mode, Esc = quit.\nWait a bit to see FPS.");
text_->SetFont(cache->GetResource<Font>("Fonts/Anonymous Pro.ttf"),20);
text_->SetColor(Color(.3,0,.3));
text_->SetHorizontalAlignment(HA_CENTER);
text_->SetVerticalAlignment(VA_TOP);
GetSubsystem<UI>()->GetRoot()->AddChild(text_);
Button* button=new Button(context_);
GetSubsystem<UI>()->GetRoot()->AddChild(button);
button->SetName("Button Quit");
button->SetStyle("Button");
button->SetSize(32,32);
button->SetPosition(16,16);
GetSubsystem<Input>()->SetMouseVisible(false);
GetSubsystem<Input>()->SetMouseGrabbed(true);
scene_=new Scene(context_);
scene_->CreateComponent<Octree>();
scene_->CreateComponent<DebugRenderer>();
Node* skyNode=scene_->CreateChild("Sky");
skyNode->SetScale(500.0f); // The scale actually does not matter
Skybox* skybox=skyNode->CreateComponent<Skybox>();
skybox->SetModel(cache->GetResource<Model>("Models/Box.mdl"));
skybox->SetMaterial(cache->GetResource<Material>("Materials/Skybox.xml"));
boxNode_=scene_->CreateChild("Box");
boxNode_->SetPosition(Vector3(0,0,5));
StaticModel* boxObject=boxNode_->CreateComponent<StaticModel>();
boxObject->SetModel(cache->GetResource<Model>("Models/Box.mdl"));
boxObject->SetMaterial(cache->GetResource<Material>("Materials/Stone.xml"));
for(int x=-30;x<30;x+=3)
for(int y=-30;y<30;y+=3)
{
Node* boxNode_=scene_->CreateChild("Box");
boxNode_->SetPosition(Vector3(x,-3,y));
StaticModel* boxObject=boxNode_->CreateComponent<StaticModel>();
boxObject->SetModel(cache->GetResource<Model>("Models/Box.mdl"));
boxObject->SetMaterial(cache->GetResource<Material>("Materials/Stone.xml"));
boxObject->SetCastShadows(true);
}
cameraNode_=scene_->CreateChild("Camera");
Camera* camera=cameraNode_->CreateComponent<Camera>();
camera->SetFarClip(2000);
{
Node* lightNode=scene_->CreateChild("Light");
lightNode->SetPosition(Vector3(-5,10,5));
Light* light=lightNode->CreateComponent<Light>();
light->SetLightType(LIGHT_POINT);
light->SetRange(50);
light->SetBrightness(1.2);
light->SetColor(Color(1,.5,.8,1));
}
{
Node* lightNode=scene_->CreateChild("Light");
lightNode->SetPosition(Vector3(5,-3,5));
Light* light=lightNode->CreateComponent<Light>();
light->SetLightType(LIGHT_POINT);
light->SetRange(50);
light->SetBrightness(1.2);
light->SetColor(Color(.5,.8,1,1));
}
{
Light* light=cameraNode_->CreateComponent<Light>();
light->SetLightType(LIGHT_POINT);
light->SetRange(10);
light->SetBrightness(2.0);
light->SetColor(Color(.8,1,.8,1.0));
}
Renderer* renderer=GetSubsystem<Renderer>();
SharedPtr<Viewport> viewport(new Viewport(context_,scene_,cameraNode_->GetComponent<Camera>()));
renderer->SetViewport(0,viewport);
SubscribeToEvent(E_BEGINFRAME,HANDLER(MyApp,HandleBeginFrame));
SubscribeToEvent(E_KEYDOWN,HANDLER(MyApp,HandleKeyDown));
SubscribeToEvent(E_UIMOUSECLICK,HANDLER(MyApp,HandleControlClicked));
SubscribeToEvent(E_UPDATE,HANDLER(MyApp,HandleUpdate));
SubscribeToEvent(E_POSTUPDATE,HANDLER(MyApp,HandlePostUpdate));
SubscribeToEvent(E_RENDERUPDATE,HANDLER(MyApp,HandleRenderUpdate));
SubscribeToEvent(E_POSTRENDERUPDATE,HANDLER(MyApp,HandlePostRenderUpdate));
SubscribeToEvent(E_ENDFRAME,HANDLER(MyApp,HandleEndFrame));
}
virtual void Stop()
{
}
void HandleKeyDown(StringHash eventType,VariantMap& eventData)
{
using namespace KeyDown;
int key=eventData[P_KEY].GetInt();
if(key==KEY_ESC)
engine_->Exit();
if(key==KEY_TAB)
{
GetSubsystem<Input>()->SetMouseVisible(!GetSubsystem<Input>()->IsMouseVisible());
GetSubsystem<Input>()->SetMouseGrabbed(!GetSubsystem<Input>()->IsMouseGrabbed());
}
}
void HandleControlClicked(StringHash eventType,VariantMap& eventData)
{
// Query the clicked UI element.
UIElement* clicked=static_cast<UIElement*>(eventData[UIMouseClick::P_ELEMENT].GetPtr());
if(clicked)
if(clicked->GetName()=="Button Quit") // check if the quit button was clicked
engine_->Exit();
}
void HandleUpdate(StringHash eventType,VariantMap& eventData)
{
float timeStep=eventData[Update::P_TIMESTEP].GetFloat();
framecount_++;
time_+=timeStep;
// Movement speed as world units per second
float MOVE_SPEED=10.0f;
// Mouse sensitivity as degrees per pixel
const float MOUSE_SENSITIVITY=0.1f;
if(time_ >=1)
{
std::string str;
str.append("Keys: tab = toggle mouse, AWSD = move camera, Shift = fast mode, Esc = quit.\n");
str.append(std::to_string(framecount_));
str.append(" frames in ");
str.append(std::to_string(time_));
str.append(" seconds = ");
str.append(std::to_string((float)framecount_ / time_));
str.append(" fps");
String s(str.c_str(),str.size());
text_->SetText(s);
framecount_=0;
time_=0;
}
// Rotate the box thingy.
// A much nicer way of doing this would be with a LogicComponent.
// With LogicComponents it is easy to control things like movement
// and animation from some IDE, console or just in game.
// Alas, it is out of the scope for our simple example.
boxNode_->Rotate(Quaternion(8*timeStep,16*timeStep,0));
Input* input=GetSubsystem<Input>();
if(input->GetQualifierDown(1)) // 1 is shift, 2 is ctrl, 4 is alt
MOVE_SPEED*=10;
if(input->GetKeyDown('W'))
cameraNode_->Translate(Vector3(0,0, 1)*MOVE_SPEED*timeStep);
if(input->GetKeyDown('S'))
cameraNode_->Translate(Vector3(0,0,-1)*MOVE_SPEED*timeStep);
if(input->GetKeyDown('A'))
cameraNode_->Translate(Vector3(-1,0,0)*MOVE_SPEED*timeStep);
if(input->GetKeyDown('D'))
cameraNode_->Translate(Vector3( 1,0,0)*MOVE_SPEED*timeStep);
if(!GetSubsystem<Input>()->IsMouseVisible())
{
// Use this frame's mouse motion to adjust camera node yaw and pitch. Clamp the pitch between -90 and 90 degrees
IntVector2 mouseMove=input->GetMouseMove();
// avoid the weird extrem values before moving the mouse
if(mouseMove.x_>-2000000000&&mouseMove.y_>-2000000000)
{
static float yaw_=0;
static float pitch_=0;
yaw_+=MOUSE_SENSITIVITY*mouseMove.x_;
pitch_+=MOUSE_SENSITIVITY*mouseMove.y_;
pitch_=Clamp(pitch_,-90.0f,90.0f);
// Reset rotation and set yaw and pitch again
cameraNode_->SetDirection(Vector3::FORWARD);
cameraNode_->Yaw(yaw_);
cameraNode_->Pitch(pitch_);
}
}
}
void HandleBeginFrame(StringHash eventType,VariantMap& eventData)
{
}
void HandlePostUpdate(StringHash eventType,VariantMap& eventData)
{
}
void HandleRenderUpdate(StringHash eventType, VariantMap & eventData)
{
}
void HandlePostRenderUpdate(StringHash eventType, VariantMap & eventData)
{
}
void HandleEndFrame(StringHash eventType,VariantMap& eventData)
{
}
};
DEFINE_APPLICATION_MAIN(MyApp)
<|endoftext|> |
<commit_before>/***
Copyright 2013-2016 Dave Cridland
Copyright 2014-2016 Surevine Ltd
Permission is hereby granted, free of charge, to any person obtaining a copy of
this software and associated documentation files (the "Software"), to deal in
the Software without restriction, including without limitation the rights to
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
of the Software, and to permit persons to whom the Software is furnished to do
so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
***/
#include <string>
#include <config.h>
#include <unistd.h>
#include <iostream>
#include <string.h>
#include <log.h>
#include <signal.h>
#include <fstream>
#include <router.h>
#define UNW_LOCAL_ONLY
#include <libunwind.h>
namespace {
class BootConfig {
public:
std::string config_file = "./metre.conf.xml";
std::string boot_method = "";
BootConfig(int argc, char *argv[]) {
for (int i = 1; argv[i]; ++i) {
char opt;
switch (argv[i][0]) {
case '-':
case '/':
opt = argv[i][1];
break;
default:
std::cerr << "Don't understand commandline arg " << argv[i] << std::endl;
exit(2);
}
++i;
if (!argv[i]) {
std::cerr << "Missing argument for option '" << opt << "'" << std::endl;
exit(2);
}
switch (opt) {
case 'c':
config_file = argv[i];
break;
case 'd':
boot_method = argv[i];
break;
default:
std::cerr << "Unknown switch " << opt << std::endl;
exit(2);
}
}
}
};
std::unique_ptr<BootConfig> bc;
std::unique_ptr<Metre::Config> config;
void hup_handler(int) {
//config.reset(new Metre::Config(bc->config_file));
//Metre::Router::reload();
METRE_LOG(Metre::Log::INFO, "NOT Reloading config.");
}
void term_handler(int) {
METRE_LOG(Metre::Log::INFO, "Shutdown received.");
Metre::Router::quit();
}
void terminate_handler() {
unw_cursor_t cursor;
unw_context_t uc;
unw_getcontext(&uc);
unw_init_local(&cursor, &uc);
auto eptr = std::current_exception();
if (eptr) {
try {
std::rethrow_exception(eptr);
} catch(const std::runtime_error & e) {
std::cerr << "Uncaught runtime_error: " << e.what() << std::endl;
} catch(const std::exception & e) {
std::cerr << "Uncaught exception: " << e.what() << std::endl;
} catch(...) {
std::cerr << "Unknown exception caught" << std::endl;
}
} else {
std::cerr << "std::terminate called with no exception" << std::endl;
}
while (unw_step(&cursor) > 0) {
unw_word_t ip;
unw_word_t sp;
unw_get_reg(&cursor, UNW_REG_IP, &ip);
unw_get_reg(&cursor, UNW_REG_SP, &sp);
std::array<char, 1024> buffer;
unw_word_t offset;
unw_get_proc_name(&cursor, buffer.data(), buffer.size(), &offset);
std::string proc_name(buffer.data());
std::cerr << "ip = " << std::ios::hex << ip << ", sp = " << sp << ", " << proc_name << "+" << offset << std::ios::dec << std::endl;
}
std::abort();
}
}
int main(int argc, char *argv[]) {
try {
// Firstly, load up the configuration.
std::set_terminate(terminate_handler);
bc = std::make_unique<BootConfig>(argc, argv);
config = std::make_unique<Metre::Config>(bc->config_file);
if (bc->boot_method.empty()) {
bc->boot_method = config->boot_method();
}
} catch (std::runtime_error &e) {
std::cout << "Error while loading config: " << e.what() << std::endl;
return 1;
}
try {
if (bc->boot_method == "sysv") {
pid_t child = fork();
if (child == -1) {
std::cerr << "Fork failed: " << strerror(errno) << std::endl;
exit(1);
}
if (child != 0) {
// This is the parent; we exit here.
return 0;
}
// We are the new child. Close fds, session, etc.
close(0);
close(1);
close(2);
config->log_init();
config->write_runtime_config();
if (-1 == setsid()) {
METRE_LOG(Metre::Log::CRIT, "setsid() failed with " << strerror(errno));
}
// Now fork again. Like we did last summer.
child = fork();
if (child == -1) {
METRE_LOG(Metre::Log::CRIT, "fork(2) failed with " << strerror(errno));
exit(1);
}
if (child != 0) {
std::ofstream pidfile(config->pidfile(), std::ios_base::trunc);
pidfile << child << std::endl;
return 0;
}
chdir(config->runtime_dir().c_str());
signal(SIGPIPE, SIG_IGN);
signal(SIGHUP, hup_handler);
signal(SIGTERM, term_handler);
Metre::Router::main([]() { return false; });
} else if (bc->boot_method == "none") {
config->log_init(true);
config->write_runtime_config();
signal(SIGPIPE, SIG_IGN);
signal(SIGHUP, hup_handler);
signal(SIGTERM, term_handler);
signal(SIGINT, term_handler);
Metre::Router::main([]() { return false; });
} else if (bc->boot_method == "docker") {
config->docker_setup();
config->write_runtime_config();
signal(SIGPIPE, SIG_IGN);
signal(SIGHUP, hup_handler);
signal(SIGTERM, term_handler);
signal(SIGINT, term_handler);
Metre::Router::main([]() { return false; });
} else if (bc->boot_method == "systemd") {
config->log_init(true);
config->write_runtime_config();
signal(SIGPIPE, SIG_IGN);
signal(SIGHUP, hup_handler);
signal(SIGTERM, term_handler);
Metre::Router::main([]() { return false; });
} else {
std::cerr << "I don't know what " << bc->boot_method << " means." << std::endl;
return 1;
}
} catch (std::runtime_error const &e) {
std::cerr << "Error while loading config: " << e.what() << std::endl;
return 2;
}
config.reset(nullptr);
bc.reset(nullptr);
return 0;
}
<commit_msg>Handle SEGV/BUS signals<commit_after>/***
Copyright 2013-2016 Dave Cridland
Copyright 2014-2016 Surevine Ltd
Permission is hereby granted, free of charge, to any person obtaining a copy of
this software and associated documentation files (the "Software"), to deal in
the Software without restriction, including without limitation the rights to
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
of the Software, and to permit persons to whom the Software is furnished to do
so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
***/
#include <string>
#include <config.h>
#include <unistd.h>
#include <iostream>
#include <string.h>
#include <log.h>
#include <signal.h>
#include <fstream>
#include <router.h>
#define UNW_LOCAL_ONLY
#include <libunwind.h>
namespace {
class BootConfig {
public:
std::string config_file = "./metre.conf.xml";
std::string boot_method = "";
BootConfig(int argc, char *argv[]) {
for (int i = 1; argv[i]; ++i) {
char opt;
switch (argv[i][0]) {
case '-':
case '/':
opt = argv[i][1];
break;
default:
std::cerr << "Don't understand commandline arg " << argv[i] << std::endl;
exit(2);
}
++i;
if (!argv[i]) {
std::cerr << "Missing argument for option '" << opt << "'" << std::endl;
exit(2);
}
switch (opt) {
case 'c':
config_file = argv[i];
break;
case 'd':
boot_method = argv[i];
break;
default:
std::cerr << "Unknown switch " << opt << std::endl;
exit(2);
}
}
}
};
std::unique_ptr<BootConfig> bc;
std::unique_ptr<Metre::Config> config;
void hup_handler(int) {
//config.reset(new Metre::Config(bc->config_file));
//Metre::Router::reload();
METRE_LOG(Metre::Log::INFO, "NOT Reloading config.");
}
void term_handler(int) {
METRE_LOG(Metre::Log::INFO, "Shutdown received.");
Metre::Router::quit();
}
void terminate_handler() {
unw_cursor_t cursor;
unw_context_t uc;
unw_getcontext(&uc);
unw_init_local(&cursor, &uc);
auto eptr = std::current_exception();
if (eptr) {
try {
std::rethrow_exception(eptr);
} catch(const std::runtime_error & e) {
std::cerr << "Uncaught runtime_error: " << e.what() << std::endl;
} catch(const std::exception & e) {
std::cerr << "Uncaught exception: " << e.what() << std::endl;
} catch(...) {
std::cerr << "Unknown exception caught" << std::endl;
}
} else {
std::cerr << "std::terminate called with no exception" << std::endl;
}
while (unw_step(&cursor) > 0) {
unw_word_t ip;
unw_word_t sp;
unw_get_reg(&cursor, UNW_REG_IP, &ip);
unw_get_reg(&cursor, UNW_REG_SP, &sp);
std::array<char, 1024> buffer;
unw_word_t offset;
unw_get_proc_name(&cursor, buffer.data(), buffer.size(), &offset);
std::string proc_name(buffer.data());
std::cerr << "ip = " << std::ios::hex << ip << ", sp = " << sp << ", " << proc_name << "+" << offset << std::ios::dec << std::endl;
}
std::abort();
}
void segv_handler(int s) {
METRE_LOG(Metre::Log::INFO, "Fatal signal " << s);
terminate_handler();
}
}
int main(int argc, char *argv[]) {
try {
// Firstly, load up the configuration.
std::set_terminate(terminate_handler);
bc = std::make_unique<BootConfig>(argc, argv);
config = std::make_unique<Metre::Config>(bc->config_file);
if (bc->boot_method.empty()) {
bc->boot_method = config->boot_method();
}
} catch (std::runtime_error &e) {
std::cout << "Error while loading config: " << e.what() << std::endl;
return 1;
}
try {
if (bc->boot_method == "sysv") {
pid_t child = fork();
if (child == -1) {
std::cerr << "Fork failed: " << strerror(errno) << std::endl;
exit(1);
}
if (child != 0) {
// This is the parent; we exit here.
return 0;
}
// We are the new child. Close fds, session, etc.
close(0);
close(1);
close(2);
config->log_init();
config->write_runtime_config();
if (-1 == setsid()) {
METRE_LOG(Metre::Log::CRIT, "setsid() failed with " << strerror(errno));
}
// Now fork again. Like we did last summer.
child = fork();
if (child == -1) {
METRE_LOG(Metre::Log::CRIT, "fork(2) failed with " << strerror(errno));
exit(1);
}
if (child != 0) {
std::ofstream pidfile(config->pidfile(), std::ios_base::trunc);
pidfile << child << std::endl;
return 0;
}
chdir(config->runtime_dir().c_str());
signal(SIGPIPE, SIG_IGN);
signal(SIGHUP, hup_handler);
signal(SIGTERM, term_handler);
signal(SIGSEGV, segv_handler);
signal(SIGBUS, segv_handler);
Metre::Router::main([]() { return false; });
} else if (bc->boot_method == "none") {
config->log_init(true);
config->write_runtime_config();
signal(SIGPIPE, SIG_IGN);
signal(SIGHUP, hup_handler);
signal(SIGTERM, term_handler);
signal(SIGINT, term_handler);
signal(SIGSEGV, segv_handler);
signal(SIGBUS, segv_handler);
Metre::Router::main([]() { return false; });
} else if (bc->boot_method == "docker") {
config->docker_setup();
config->write_runtime_config();
signal(SIGPIPE, SIG_IGN);
signal(SIGHUP, hup_handler);
signal(SIGTERM, term_handler);
signal(SIGINT, term_handler);
signal(SIGSEGV, segv_handler);
signal(SIGBUS, segv_handler);
Metre::Router::main([]() { return false; });
} else if (bc->boot_method == "systemd") {
config->log_init(true);
config->write_runtime_config();
signal(SIGPIPE, SIG_IGN);
signal(SIGHUP, hup_handler);
signal(SIGTERM, term_handler);
signal(SIGSEGV, segv_handler);
signal(SIGBUS, segv_handler);
Metre::Router::main([]() { return false; });
} else {
std::cerr << "I don't know what " << bc->boot_method << " means." << std::endl;
return 1;
}
} catch (std::runtime_error const &e) {
std::cerr << "Error while loading config: " << e.what() << std::endl;
return 2;
}
config.reset(nullptr);
bc.reset(nullptr);
return 0;
}
<|endoftext|> |
<commit_before>#include "SteamWebAPI.h"
std::string SteamWebAPI::getMatchHistory(std::string numMatches){
std::string url = std::string("https://api.steampowered.com/IDOTA2Match_570/GetMatchHistory/V001/?format=XML");
url.append(std::string("&key=").append(API_KEY));
url.append(std::string("&account_id=").append(ACCOUNT_ID));
url.append(std::string("&matches_requested=").append(numMatches));
return getSteamXML(url, "DOTARAIN-MatchHistory.xml");
}
std::string SteamWebAPI::getMatchDetails(std::string matchID){
std::string url = std::string("https://api.steampowered.com/IDOTA2Match_570/GetMatchDetails/V001/?format=XML");
url.append(std::string("&key=").append(API_KEY));
url.append(std::string("&match_id=").append(matchID));
return getSteamXML(url, "DOTARAIN-MatchDetails");
}
std::string SteamWebAPI::getHeroes(){
std::string url = std::string("https://api.steampowered.com/IEconDOTA2_570/GetHeroes/v0001/?format=XML");
url.append(std::string("&key=").append(API_KEY));
url.append("&language=en_us");
return getSteamXML(url, "DOTARAIN-Heroes.xml");
}
/*Returns full path to file.
TODO: Check if the file is older than 5-10 minutes, if not just return file path
*/
std::string SteamWebAPI::getSteamXML(std::string URL, std::string filename){
std::string path = std::string("C:\\Windows\\Temp\\").append(filename);
HANDLE file = CreateFile(s2ws(path).c_str(),(GENERIC_READ | GENERIC_WRITE), 0, NULL, OPEN_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
//checking to see if the file is still relatively new, new meaning ~10 minutes here
//TODO: break this into another function
if(pastThreshold(file)){
CloseHandle(file);
return path;
}
HINTERNET hOpen = InternetOpen(L"DotaRain", NULL, NULL, NULL, NULL);
HINTERNET hURL = InternetOpenUrl(hOpen, s2ws(URL).c_str(), NULL, NULL, INTERNET_FLAG_RELOAD | INTERNET_FLAG_DONT_CACHE, NULL);
DWORD dwBytesRead =0;
DWORD dwBytesWritten = 0;
do {
char* lpBuffer = new char[2000];
ZeroMemory(lpBuffer, 2000);
InternetReadFile(hURL, (LPVOID)lpBuffer, 2000, &dwBytesRead);
WriteFile(file, (LPVOID)lpBuffer, dwBytesRead, &dwBytesWritten, NULL);
delete[] lpBuffer;
lpBuffer = NULL;
} while (dwBytesRead);
InternetCloseHandle(hURL);
InternetCloseHandle(hOpen);
CloseHandle(file);
return path;
}
bool SteamWebAPI::pastThreshold(HANDLE file){
FILETIME modTime;
SYSTEMTIME modSysTime;
GetFileTime(file, 0, 0, &modTime);
FileTimeToSystemTime(&modTime, &modSysTime);
SYSTEMTIME currentTime;
GetSystemTime(¤tTime);
if(currentTime.wDay > modSysTime.wDay)
return false;
else if(currentTime.wHour == modSysTime.wHour && currentTime.wMinute-modSysTime.wMinute < threshhold)
return false;
else if(currentTime.wHour > modSysTime.wHour && (currentTime.wMinute-60)+(modSysTime.wMinute) < threshhold)
return false;
return true;
}<commit_msg>fixed bug in threshhold function<commit_after>#include "SteamWebAPI.h"
std::string SteamWebAPI::getMatchHistory(std::string numMatches){
std::string url = std::string("https://api.steampowered.com/IDOTA2Match_570/GetMatchHistory/V001/?format=XML");
url.append(std::string("&key=").append(API_KEY));
url.append(std::string("&account_id=").append(ACCOUNT_ID));
url.append(std::string("&matches_requested=").append(numMatches));
return getSteamXML(url, "DOTARAIN-MatchHistory.xml");
}
std::string SteamWebAPI::getMatchDetails(std::string matchID){
std::string url = std::string("https://api.steampowered.com/IDOTA2Match_570/GetMatchDetails/V001/?format=XML");
url.append(std::string("&key=").append(API_KEY));
url.append(std::string("&match_id=").append(matchID));
return getSteamXML(url, "DOTARAIN-MatchDetails");
}
std::string SteamWebAPI::getHeroes(){
std::string url = std::string("https://api.steampowered.com/IEconDOTA2_570/GetHeroes/v0001/?format=XML");
url.append(std::string("&key=").append(API_KEY));
url.append("&language=en_us");
return getSteamXML(url, "DOTARAIN-Heroes.xml");
}
/*Returns full path to file.
TODO: Check if the file is older than 5-10 minutes, if not just return file path
*/
std::string SteamWebAPI::getSteamXML(std::string URL, std::string filename){
std::string path = std::string("C:\\Windows\\Temp\\").append(filename);
HANDLE file = CreateFile(s2ws(path).c_str(),(GENERIC_READ | GENERIC_WRITE), 0, NULL, OPEN_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
//checking to see if the file is still relatively new, new meaning ~10 minutes here
//TODO: break this into another function
if(!pastThreshold(file)){
std::cout << "No need to create new file" << std::endl;
CloseHandle(file);
return path;
}
std::cout << "Creating new file" << std::endl;
HINTERNET hOpen = InternetOpen(L"DotaRain", NULL, NULL, NULL, NULL);
HINTERNET hURL = InternetOpenUrl(hOpen, s2ws(URL).c_str(), NULL, NULL, INTERNET_FLAG_RELOAD | INTERNET_FLAG_DONT_CACHE, NULL);
DWORD dwBytesRead =0;
DWORD dwBytesWritten = 0;
do {
char* lpBuffer = new char[2000];
ZeroMemory(lpBuffer, 2000);
InternetReadFile(hURL, (LPVOID)lpBuffer, 2000, &dwBytesRead);
WriteFile(file, (LPVOID)lpBuffer, dwBytesRead, &dwBytesWritten, NULL);
delete[] lpBuffer;
lpBuffer = NULL;
} while (dwBytesRead);
InternetCloseHandle(hURL);
InternetCloseHandle(hOpen);
CloseHandle(file);
return path;
}
bool SteamWebAPI::pastThreshold(HANDLE file){
FILETIME modTime;
SYSTEMTIME modSysTime;
GetFileTime(file, 0, 0, &modTime);
FileTimeToSystemTime(&modTime, &modSysTime);
SYSTEMTIME currentTime;
GetSystemTime(¤tTime);
if(currentTime.wDay > modSysTime.wDay)
return false;
else if(currentTime.wHour == modSysTime.wHour && currentTime.wMinute-modSysTime.wMinute < threshhold)
return false;
else if(currentTime.wHour > modSysTime.wHour && (currentTime.wMinute)+(60-modSysTime.wMinute) < threshhold)
return false;
return true;
}<|endoftext|> |
<commit_before>/*
* cclive Copyright (C) 2009 Toni Gundogdu. This file is part of cclive.
*
* cclive is free software: you can redistribute it and/or modify it under the
* terms of the GNU General Public License as published by the Free Software
* Foundation, either version 3 of the License, or (at your option) any later
* version.
*
* cclive is distributed in the hope that it will be useful, but WITHOUT ANY
* WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
* details.
*
* You should have received a copy of the GNU General Public License along with
* this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <string>
#include <vector>
#include "except.h"
#include "video.h"
#include "util.h"
#include "singleton.h"
#include "curl.h"
#include "hosthandler.h"
const bool
LiveleakHandler::isHost(std::string url) {
props.setHost ("lleak");
props.setDomain ("liveleak.com");
return Util::toLower(url).find(props.getDomain())
!= std::string::npos;
}
void
LiveleakHandler::parseId() {
const char *begin = "token=";
const char *end = "&";
props.setId( Util::subStr(pageContent, begin, end) );
}
void
LiveleakHandler::parseLink() {
const char *cpathBegin = "'config','";
const char *cpathEnd = "'";
std::string confPath =
Util::subStr(pageContent, cpathBegin, cpathEnd);
curlmgr.unescape(confPath);
std::string config =
curlmgr.fetchToMem(confPath, "config");
const char *plBegin = "<file>";
const char *plEnd = "</file>";
std::string plPath =
Util::subStr(config, plBegin, plEnd);
curlmgr.unescape(plPath);
std::string playlist =
curlmgr.fetchToMem(plPath, "playlist");
const char *linkBegin = "<location>";
const char *linkEnd = "</location>";
props.setLink( Util::subStr(playlist, linkBegin, linkEnd) );
}
<commit_msg>Fix: liveleak id parsing.<commit_after>/*
* cclive Copyright (C) 2009 Toni Gundogdu. This file is part of cclive.
*
* cclive is free software: you can redistribute it and/or modify it under the
* terms of the GNU General Public License as published by the Free Software
* Foundation, either version 3 of the License, or (at your option) any later
* version.
*
* cclive is distributed in the hope that it will be useful, but WITHOUT ANY
* WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
* details.
*
* You should have received a copy of the GNU General Public License along with
* this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <string>
#include <vector>
#include "except.h"
#include "video.h"
#include "util.h"
#include "singleton.h"
#include "curl.h"
#include "hosthandler.h"
const bool
LiveleakHandler::isHost(std::string url) {
props.setHost ("lleak");
props.setDomain ("liveleak.com");
return Util::toLower(url).find(props.getDomain())
!= std::string::npos;
}
void
LiveleakHandler::parseId() {
const char *begin = "token=";
const char *end = "'";
props.setId( Util::subStr(pageContent, begin, end) );
}
void
LiveleakHandler::parseLink() {
const char *cpathBegin = "'config','";
const char *cpathEnd = "'";
std::string confPath =
Util::subStr(pageContent, cpathBegin, cpathEnd);
curlmgr.unescape(confPath);
std::string config =
curlmgr.fetchToMem(confPath, "config");
const char *plBegin = "<file>";
const char *plEnd = "</file>";
std::string plPath =
Util::subStr(config, plBegin, plEnd);
curlmgr.unescape(plPath);
std::string playlist =
curlmgr.fetchToMem(plPath, "playlist");
const char *linkBegin = "<location>";
const char *linkEnd = "</location>";
props.setLink( Util::subStr(playlist, linkBegin, linkEnd) );
}
<|endoftext|> |
<commit_before>/// \file AddTaskEMCALPi0Calibration.C
/// \brief Configuration of task AliAnalysisTaskEMCALPi0CalibSelection.
///
/// Configuration of task AliAnalysisTaskEMCALPi0CalibSelection, which fills invariant mass
/// histograms for each of the EMCal channels. It has to be executed in several iterations.
///
/// The parameters for the analysis are:
/// \param calibPath : TString with full path and name of file with calibration factors from previous iteration.
/// \param trigger : TString, event that triggered must contain this string.
/// \param recalE : Bool, recalibrate EMCal energy
/// \param recalT : Bool, recalibrate EMCal time
/// \param rmBad : Bool, remove bad channels
/// \param nonLin : Bool, correct cluster non linearity
/// \param simu : Bool, simulation or data.
/// \param outputFile: TString with name of output file (AnalysisResults.root).
///
/// \author : Gustavo Conesa Balbastre <Gustavo.Conesa.Balbastre@cern.ch>, (LPSC-CNRS)
///
AliAnalysisTaskEMCALPi0CalibSelection * AddTaskEMCALPi0Calibration(TString calibPath = "", // "alienpath/RecalibrationFactors.root"
TString trigger ="CEMC7",
Bool_t recalE = kFALSE,
Bool_t recalT = kFALSE,
Bool_t rmBad = kFALSE,
Bool_t nonlin = kTRUE,
Bool_t simu = kFALSE,
TString outputFile = "") // AnalysisResults.root
{
// Get the pointer to the existing analysis manager via the static access method.
//==============================================================================
AliAnalysisManager *mgr = AliAnalysisManager::GetAnalysisManager();
if (!mgr)
{
::Error("AddTaskEMCALTriggerQA", "No analysis manager to connect to.");
return NULL;
}
// Check the analysis type using the event handlers connected to the analysis manager.
//==============================================================================
if (!mgr->GetInputEventHandler())
{
::Error("AddTaskEMCALPi0Calibration", "This task requires an input event handler");
return NULL;
}
// Create containers for input/output
AliAnalysisDataContainer *cinput1 = mgr->GetCommonInputContainer();
AliAnalysisTaskEMCALPi0CalibSelection * pi0calib = new AliAnalysisTaskEMCALPi0CalibSelection ("EMCALPi0Calibration");
//pi0calib->SetDebugLevel(10);
//pi0calib->UseFilteredEventAsInput();
pi0calib->SetClusterMinEnergy(0.3);
pi0calib->SetClusterMaxEnergy(10.);
pi0calib->SetClusterLambda0Cuts(0.1,0.5);
pi0calib->SetAsymmetryCut(1.);
pi0calib->SetClusterMinNCells(1);
pi0calib->SetNCellsGroup(0);
pi0calib->SwitchOnSameSM();
// Timing cuts
pi0calib->SetPairDTimeCut(100); // 20 ns in Run1
pi0calib->SetClusterMinTime(300); // 560 ns in Run1
pi0calib->SetClusterMaxTime(800); // 610 ns in Run1
pi0calib->SetTriggerName(trigger);
// Cluster recalculation, Reco Utils configuration
AliEMCALRecoUtils * reco = pi0calib->GetEMCALRecoUtils();
gROOT->LoadMacro("$ALICE_PHYSICS/PWGPP/EMCAL/macros/ConfigureEMCALRecoUtils.C");
ConfigureEMCALRecoUtils(reco,
simu,
kTRUE, // exotic
nonlin,
recalE,
rmBad,
recalT);
reco->SetNumberOfCellsFromEMCALBorder(0); // Do not remove clusters in borders!
// recalibrate energy and do corrections because of Temperature corrections
pi0calib->SwitchOnClusterCorrection();
reco->SwitchOnRecalibration();
reco->SwitchOnRunDepCorrection();
//reco->Print("");
//---------------------
// Geometry alignment
//---------------------
pi0calib->SetGeometryName("EMCAL_COMPLETE12SMV1_DCAL_8SM");
pi0calib->SwitchOnLoadOwnGeometryMatrices();
//---------------------
// Pass recalibration factors
// Do it here or inside the task
// If previous pass not available (first) avoid recalculate clusters
//---------------------
pi0calib->SetCalibrationFilePath(calibPath);
pi0calib->InitEnergyCalibrationFactors();
if(calibPath == "")
{
if(recalE)
{
printf("Get the calibration file from AddTask!!!\n");
TFile * calibFile = TFile::Open("RecalibrationFactors.root");
if(!calibFile)
{
printf("File %d not found!\n",calibPath.Data());
return;
}
for(Int_t ism = 0; ism < 20; ism++)
{
TH2F * h = (TH2F*)calibFile->Get(Form("EMCALRecalFactors_SM%d",ism));
if(h) reco->SetEMCALChannelRecalibrationFactors(ism,h);
else printf("Null histogram with calibration factors for SM%d, 1 will be used in the full SM\n",ism);
}
}
else
{
// First iteration, just fill histograms, switch off recalculation
reco->SwitchOffRecalibration();
reco->SwitchOffRunDepCorrection(); // Careful!!!, activate when T corrections are available.
pi0calib->SwitchOffLoadOwnGeometryMatrices();
pi0calib->SwitchOffRecalculatePosition();
printf("Pi0 Calibration: Do not recalculate the clusters! First iteration. \n");
}
}
pi0calib->PrintInfo();
mgr->AddTask(pi0calib);
if(outputFile.Length()==0) outputFile = AliAnalysisManager::GetCommonFileName();
AliAnalysisDataContainer *cinput1 = mgr->GetCommonInputContainer();
AliAnalysisDataContainer *coutput = mgr->CreateContainer(Form("Pi0Calibration_Trig%s",trigger.Data()),
TList::Class(), AliAnalysisManager::kOutputContainer,
outputFile.Data());
// AliAnalysisDataContainer *cout_cuts = mgr->CreateContainer(Form("ParamsPi0Calibration_Trig%s",trigger.Data()),
// TList::Class(), AliAnalysisManager::kOutputContainer,
// "AnalysisParameters.root");
mgr->AddTask(pi0calib);
mgr->ConnectInput (pi0calib, 0, cinput1);
mgr->ConnectOutput (pi0calib, 1, coutput);
// mgr->ConnectOutput (pi0calib, 2, cout_cuts);
return pi0calib;
}
<commit_msg>simplify the logic on the loading of the calibration parameters<commit_after>/// \file AddTaskEMCALPi0Calibration.C
/// \brief Configuration of task AliAnalysisTaskEMCALPi0CalibSelection.
///
/// Configuration of task AliAnalysisTaskEMCALPi0CalibSelection, which fills invariant mass
/// histograms for each of the EMCal channels. It has to be executed in several iterations.
///
/// The parameters for the analysis are:
/// \param calibPath : TString with full path and name of file with calibration factors from previous iteration.
/// \param trigger : TString, event that triggered must contain this string.
/// \param recalE : Bool, recalibrate EMCal energy
/// \param recalT : Bool, recalibrate EMCal time
/// \param rmBad : Bool, remove bad channels
/// \param nonLin : Bool, correct cluster non linearity
/// \param simu : Bool, simulation or data.
/// \param outputFile: TString with name of output file (AnalysisResults.root).
///
/// \author : Gustavo Conesa Balbastre <Gustavo.Conesa.Balbastre@cern.ch>, (LPSC-CNRS)
///
AliAnalysisTaskEMCALPi0CalibSelection * AddTaskEMCALPi0Calibration(TString calibPath = "", // "alienpath/RecalibrationFactors.root"
TString trigger ="CEMC7",
Bool_t recalE = kFALSE,
Bool_t recalT = kFALSE,
Bool_t rmBad = kFALSE,
Bool_t nonlin = kTRUE,
Bool_t simu = kFALSE,
TString outputFile = "") // AnalysisResults.root
{
// Get the pointer to the existing analysis manager via the static access method.
//==============================================================================
AliAnalysisManager *mgr = AliAnalysisManager::GetAnalysisManager();
if (!mgr)
{
::Error("AddTaskEMCALTriggerQA", "No analysis manager to connect to.");
return NULL;
}
// Check the analysis type using the event handlers connected to the analysis manager.
//==============================================================================
if (!mgr->GetInputEventHandler())
{
::Error("AddTaskEMCALPi0Calibration", "This task requires an input event handler");
return NULL;
}
// Create containers for input/output
AliAnalysisDataContainer *cinput1 = mgr->GetCommonInputContainer();
AliAnalysisTaskEMCALPi0CalibSelection * pi0calib = new AliAnalysisTaskEMCALPi0CalibSelection ("EMCALPi0Calibration");
//pi0calib->SetDebugLevel(10);
//pi0calib->UseFilteredEventAsInput();
pi0calib->SetClusterMinEnergy(0.3);
pi0calib->SetClusterMaxEnergy(10.);
pi0calib->SetClusterLambda0Cuts(0.1,0.5);
pi0calib->SetAsymmetryCut(1.);
pi0calib->SetClusterMinNCells(1);
pi0calib->SetNCellsGroup(0);
pi0calib->SwitchOnSameSM();
// Timing cuts
pi0calib->SetPairDTimeCut(100); // 20 ns in Run1
pi0calib->SetClusterMinTime(300); // 560 ns in Run1
pi0calib->SetClusterMaxTime(800); // 610 ns in Run1
pi0calib->SetTriggerName(trigger);
// Cluster recalculation, Reco Utils configuration
AliEMCALRecoUtils * reco = pi0calib->GetEMCALRecoUtils();
gROOT->LoadMacro("$ALICE_PHYSICS/PWGPP/EMCAL/macros/ConfigureEMCALRecoUtils.C");
ConfigureEMCALRecoUtils(reco,
simu,
kTRUE, // exotic
nonlin,
recalE,
rmBad,
recalT);
reco->SetNumberOfCellsFromEMCALBorder(0); // Do not remove clusters in borders!
// recalibrate energy and do corrections because of Temperature corrections
pi0calib->SwitchOnClusterCorrection();
reco->SwitchOnRecalibration();
reco->SwitchOnRunDepCorrection();
//reco->Print("");
//---------------------
// Geometry alignment
//---------------------
pi0calib->SetGeometryName("EMCAL_COMPLETE12SMV1_DCAL_8SM");
pi0calib->SwitchOnLoadOwnGeometryMatrices();
//---------------------
// Pass recalibration factors
// Do it here or inside the task
// If previous pass not available (first) avoid recalculate clusters
//---------------------
pi0calib->SetCalibrationFilePath(calibPath);
if(calibPath != "" && recalE)
{
printf("AddTaskEMCALPi0Calibration - Get the energy calibration factors from: \n %s \n",calibPath.Data());
pi0calib->InitEnergyCalibrationFactors();
}
if(!recalE)
{
// Do not calibrate anything
// First iteration, just fill histograms, switch off recalculation
reco->SwitchOffRecalibration();
reco->SwitchOffRunDepCorrection(); // Careful!!!, activate when T corrections are available.
pi0calib->SwitchOffLoadOwnGeometryMatrices();
pi0calib->SwitchOffRecalculatePosition();
printf("AddTaskEMCALPi0Calibration - Pi0 Calibration: Do not recalculate the clusters! First iteration. \n");
// check if time is corrected in case of calibration available!!!
}
pi0calib->PrintInfo();
mgr->AddTask(pi0calib);
if(outputFile.Length()==0) outputFile = AliAnalysisManager::GetCommonFileName();
AliAnalysisDataContainer *cinput1 = mgr->GetCommonInputContainer();
AliAnalysisDataContainer *coutput = mgr->CreateContainer(Form("Pi0Calibration_Trig%s",trigger.Data()),
TList::Class(), AliAnalysisManager::kOutputContainer,
outputFile.Data());
// AliAnalysisDataContainer *cout_cuts = mgr->CreateContainer(Form("ParamsPi0Calibration_Trig%s",trigger.Data()),
// TList::Class(), AliAnalysisManager::kOutputContainer,
// "AnalysisParameters.root");
mgr->AddTask(pi0calib);
mgr->ConnectInput (pi0calib, 0, cinput1);
mgr->ConnectOutput (pi0calib, 1, coutput);
// mgr->ConnectOutput (pi0calib, 2, cout_cuts);
return pi0calib;
}
<|endoftext|> |
<commit_before>#include "Python.h"
#include "orbit_mpi.hh"
#include <iostream>
//modules headers
#include "wrap_orbit_mpi.hh"
#include "wrap_bunch.hh"
#include "wrap_utils.hh"
#include "wrap_teapotbase.hh"
#include "wrap_trackerrk4.hh"
#include "wrap_spacecharge.hh"
#include "wrap_linacmodule.hh"
#include "wrap_collimator.hh"
#include "wrap_foil.hh"
#include "wrap_rfcavities.hh"
#include "wrap_aperture.hh"
/**
* The main function that will initialize the MPI and will
* call the python interpreter: Py_Main(argc,argv).
*/
int main (int argc, char **argv)
{
// for(int i = 0; i < argc; i++){
// std::cout<<"before i="<<i<<" arg="<<argv[i]<<std::endl;
// }
ORBIT_MPI_Init(&argc,&argv);
// for(int i = 0; i < argc; i++){
// std::cout<<"after i="<<i<<" arg="<<argv[i]<<std::endl;
// }
//int rank = 0;
//int size = 0;
//ORBIT_MPI_Comm_rank(MPI_COMM_WORLD,&rank);
//ORBIT_MPI_Comm_size(MPI_COMM_WORLD,&size);
//std::cout<<"rank="<< rank <<" size="<< size <<std::endl;
//we need this to initialize the extra ORBIT modules
Py_Initialize();
//ORBIT module initializations
wrap_orbit_mpi::initorbit_mpi();
wrap_orbit_bunch::initbunch();
wrap_orbit_utils::initutils();
wrap_teapotbase::initteapotbase();
wrap_linac::initlinac();
wrap_collimator::initcollimator();
wrap_aperture::initaperture();
wrap_foil::initfoil();
wrap_rfcavities::initrfcavities();
//Runge-Kutta tracker package
inittrackerrk4();
//space-charge package
initspacecharge();
//the python interpreter
//It will call Py_Initialize() again, but there is no harm
Py_Main(argc,argv);
//std::cout << "MPI - stopped" << std::endl;
ORBIT_MPI_Finalize();
return 0;
}
<commit_msg>Added field tracker<commit_after>#include "Python.h"
#include "orbit_mpi.hh"
#include <iostream>
//modules headers
#include "wrap_orbit_mpi.hh"
#include "wrap_bunch.hh"
#include "wrap_utils.hh"
#include "wrap_teapotbase.hh"
#include "wrap_trackerrk4.hh"
#include "wrap_spacecharge.hh"
#include "wrap_linacmodule.hh"
#include "wrap_collimator.hh"
#include "wrap_foil.hh"
#include "wrap_rfcavities.hh"
#include "wrap_aperture.hh"
#include "wrap_fieldtracker.hh"
/**
* The main function that will initialize the MPI and will
* call the python interpreter: Py_Main(argc,argv).
*/
int main (int argc, char **argv)
{
// for(int i = 0; i < argc; i++){
// std::cout<<"before i="<<i<<" arg="<<argv[i]<<std::endl;
// }
ORBIT_MPI_Init(&argc,&argv);
// for(int i = 0; i < argc; i++){
// std::cout<<"after i="<<i<<" arg="<<argv[i]<<std::endl;
// }
//int rank = 0;
//int size = 0;
//ORBIT_MPI_Comm_rank(MPI_COMM_WORLD,&rank);
//ORBIT_MPI_Comm_size(MPI_COMM_WORLD,&size);
//std::cout<<"rank="<< rank <<" size="<< size <<std::endl;
//we need this to initialize the extra ORBIT modules
Py_Initialize();
//ORBIT module initializations
wrap_orbit_mpi::initorbit_mpi();
wrap_orbit_bunch::initbunch();
wrap_orbit_utils::initutils();
wrap_teapotbase::initteapotbase();
wrap_linac::initlinac();
wrap_collimator::initcollimator();
wrap_aperture::initaperture();
wrap_foil::initfoil();
wrap_rfcavities::initrfcavities();
wrap_fieldtracker::initfieldtracker();
//Runge-Kutta tracker package
inittrackerrk4();
//space-charge package
initspacecharge();
//the python interpreter
//It will call Py_Initialize() again, but there is no harm
Py_Main(argc,argv);
//std::cout << "MPI - stopped" << std::endl;
ORBIT_MPI_Finalize();
return 0;
}
<|endoftext|> |
<commit_before>/* Copyright (C) The LinBox group
* ========LICENCE========
* This file is part of the library LinBox.
*
* LinBox is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
* ========LICENCE========
*/
/**\file examples/dixondenseelim.C
@example examples/dixondenseelim.C
@author Jean-Guillaume.Dumas@univ-grenoble-alpes.fr
* \brief Dixon System Solving Lifting using dense LU
* \ingroup examples
*/
#include <iostream>
#include <omp.h>
#include "linbox/matrix/dense-matrix.h"
#include "linbox/solutions/solve.h"
#include "linbox/util/matrix-stream.h"
#include "linbox/solutions/methods.h"
using namespace LinBox;
typedef Givaro::ZRing<Givaro::Integer> Ints;
typedef DenseVector<Ints> ZVector;
struct FixPrime {
typedef Givaro::Integer Prime_Type;
const Prime_Type _myprime;
FixPrime(const Givaro::Integer& i) : _myprime(i) {}
inline FixPrime &operator ++ () { return *this; }
const Prime_Type &operator * () const { return randomPrime(); }
const Prime_Type & randomPrime() const { return _myprime; }
void setBits(uint64_t bits) {}
template<class _ModField> void setBitsField() { }
};
int main (int argc, char **argv) {
// Usage
if (argc < 2 || argc > 4) {
std::cerr << "Usage: solve <matrix-file-in-supported-format> [<dense-vector-file>]" << std::endl;
return 0;
}
// File
std::ifstream input (argv[1]);
if (!input) { std::cerr << "Error opening matrix file " << argv[1] << std::endl; return -1; }
std::ifstream invect;
bool createB = false;
if (argc == 2) {
createB = true;
}
if (argc == 3) {
invect.open (argv[2], std::ifstream::in);
if (!invect) {
createB = true;
} else {
createB = false;
}
}
// Read Integral matrix from File
Ints ZZ;
MatrixStream< Ints > ms( ZZ, input );
DenseMatrix<Ints> A (ms);
Ints::Element d;
std::cout << "A is " << A.rowdim() << " by " << A.coldim() << std::endl;
{
// Print Matrix
// Matrix Market
// std::cout << "A is " << A << std::endl;
// Maple
if ( (A.rowdim() < 100) && (A.coldim() < 100) )
A.write(std::cout << "Pretty A is ", Tag::FileFormat::Maple) << std::endl;
}
// Vectors
ZVector X(ZZ, A.coldim()),B(ZZ, A.rowdim());
if (createB) {
std::cerr << "Creating a random {-1,1} vector " << std::endl;
srand48( BaseTimer::seed() );
for(ZVector::iterator it=B.begin();
it != B.end(); ++it)
if (drand48() <0.5)
*it = -1;
else
*it = 1;
} else {
for(ZVector::iterator it=B.begin();
it != B.end(); ++it)
invect >> *it;
}
{
// Print RHS
std::cout << "B is [";
for(auto it:B) ZZ.write(std::cout, it) << " ";
std::cout << "]" << std::endl;
}
std::cout << "B is " << B.size() << "x1" << std::endl;
Timer chrono;
// BlasElimination
Method::DenseElimination M;
M.singularity = Singularity::NonSingular;
//====================================================
// BEGIN Replacement solve with fixed prime
Method::Dixon m(M);
typedef Givaro::Modular<double> Field;
// 0.7213475205 is an upper approximation of 1/(2log(2))
size_t bitsize((size_t)( 26-(int)ceil(log((double)A.rowdim())*0.7213475205)));
Givaro::Integer randomPrime( *(PrimeIterator<>(bitsize)) );
FixPrime fixedprime( randomPrime );
DixonSolver<Ints, Field, FixPrime, Method::DenseElimination> rsolve(A.field(), fixedprime);
std::cout << "Using: " << *fixedprime << " as the fixed p-adic." << std::endl;
chrono.start();
rsolve.solveNonsingular(X, d, A, B, false,(int)m.trialsBeforeFailure);
// END Replacement solve with fixed prime
//====================================================
// solve (X, d, A, B, M);
chrono.stop();
std::cout << "CPU time (seconds): " << chrono.usertime() << std::endl;
{
// Solution size
std::cout<<"Reduced solution: \n";
size_t maxbits=0;
for (size_t i=0;i<A.coldim();++i){
maxbits=(maxbits > X[i].bitsize() ? maxbits: X[i].bitsize());
}
std::cout<<" numerators of size "<<maxbits<<" bits" << std::endl
<<" denominators hold over "<<d.bitsize()<<" bits\n";
}
{
// Check Solution
VectorDomain<Ints> VD(ZZ);
MatrixDomain<Ints> MD(ZZ);
ZVector LHS(ZZ, A.rowdim()), RHS(ZZ, B);
// check that Ax = d.b
MD.vectorMul(LHS, A, X);
VD.mulin(RHS, d);
if (VD.areEqual(LHS, RHS))
std::cout << "Ax=b : Yes" << std::endl;
else
std::cout << "Ax=b : No" << std::endl;
}
{
// Print Solution
std::cout << "(DenseElimination) Solution is [";
for(auto it:X) ZZ.write(std::cout, it) << " ";
std::cout << "] / ";
ZZ.write(std::cout, d)<< std::endl;
}
return 0;
}
// Local Variables:
// mode: C++
// tab-width: 4
// indent-tabs-mode: nil
// c-basic-offset: 4
// End:
// vim:sts=4:sw=4:ts=4:et:sr:cino=>s,f0,{0,g0,(0,\:0,t0,+0,=s
<commit_msg>upd text<commit_after>/* Copyright (C) The LinBox group
* ========LICENCE========
* This file is part of the library LinBox.
*
* LinBox is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
* ========LICENCE========
*/
/**\file examples/dixondenseelim.C
@example examples/dixondenseelim.C
@author Jean-Guillaume.Dumas@univ-grenoble-alpes.fr
* \brief Dixon System Solving Lifting using dense LU
* \ingroup examples
*/
#include <iostream>
#include <omp.h>
#include "linbox/matrix/dense-matrix.h"
#include "linbox/solutions/solve.h"
#include "linbox/util/matrix-stream.h"
#include "linbox/solutions/methods.h"
using namespace LinBox;
typedef Givaro::ZRing<Givaro::Integer> Ints;
typedef DenseVector<Ints> ZVector;
struct FixPrime {
typedef Givaro::Integer Prime_Type;
const Prime_Type _myprime;
FixPrime(const Givaro::Integer& i) : _myprime(i) {}
inline FixPrime &operator ++ () { return *this; }
const Prime_Type &operator * () const { return randomPrime(); }
const Prime_Type & randomPrime() const { return _myprime; }
void setBits(uint64_t bits) {}
template<class _ModField> void setBitsField() { }
};
int main (int argc, char **argv) {
// Usage
if (argc < 2 || argc > 4) {
std::cerr << "Usage: solve <matrix-file-in-supported-format> [<dense-vector-file>]" << std::endl;
return 0;
}
// File
std::ifstream input (argv[1]);
if (!input) { std::cerr << "Error opening matrix file " << argv[1] << std::endl; return -1; }
std::ifstream invect;
bool createB = false;
if (argc == 2) {
createB = true;
}
if (argc == 3) {
invect.open (argv[2], std::ifstream::in);
if (!invect) {
createB = true;
} else {
createB = false;
}
}
// Read Integral matrix from File
Ints ZZ;
MatrixStream< Ints > ms( ZZ, input );
DenseMatrix<Ints> A (ms);
Ints::Element d;
std::cout << "A is " << A.rowdim() << " by " << A.coldim() << std::endl;
{
// Print Matrix
// Matrix Market
// std::cout << "A is " << A << std::endl;
// Maple
if ( (A.rowdim() < 100) && (A.coldim() < 100) )
A.write(std::cout << "Pretty A is ", Tag::FileFormat::Maple) << std::endl;
}
// Vectors
ZVector X(ZZ, A.coldim()),B(ZZ, A.rowdim());
if (createB) {
std::cerr << "Creating a random {-1,1} vector " << std::endl;
srand48( BaseTimer::seed() );
for(ZVector::iterator it=B.begin();
it != B.end(); ++it)
if (drand48() <0.5)
*it = -1;
else
*it = 1;
} else {
for(ZVector::iterator it=B.begin();
it != B.end(); ++it)
invect >> *it;
}
{
// Print RHS
std::cout << "B is [";
for(auto it:B) ZZ.write(std::cout, it) << " ";
std::cout << "]" << std::endl;
}
std::cout << "B is " << B.size() << "x1" << std::endl;
Timer chrono;
// BlasElimination
Method::DenseElimination M;
M.singularity = Singularity::NonSingular;
//====================================================
// BEGIN Replacement solve with fixed prime
Method::Dixon m(M);
typedef Givaro::Modular<double> Field;
// 0.7213475205 is an upper approximation of 1/(2log(2))
size_t bitsize((size_t)( 26-(int)ceil(log((double)A.rowdim())*0.7213475205)));
Givaro::Integer randomPrime( *(PrimeIterator<>(bitsize)) );
FixPrime fixedprime( randomPrime );
DixonSolver<Ints, Field, FixPrime, Method::DenseElimination> rsolve(A.field(), fixedprime);
std::cout << "Using: " << *fixedprime << " as the fixed p-adic." << std::endl;
chrono.start();
rsolve.solveNonsingular(X, d, A, B, false,(int)m.trialsBeforeFailure);
// END Replacement solve with fixed prime
//====================================================
// solve (X, d, A, B, M);
chrono.stop();
std::cout << "CPU time (seconds): " << chrono.usertime() << std::endl;
{
// Solution size
std::cout<<"Reduced solution: \n";
size_t maxbits=0;
for (size_t i=0;i<A.coldim();++i){
maxbits=(maxbits > X[i].bitsize() ? maxbits: X[i].bitsize());
}
std::cout<<" numerators of size "<<maxbits<<" bits" << std::endl
<<" denominators hold over "<<d.bitsize()<<" bits\n";
}
{
// Check Solution
VectorDomain<Ints> VD(ZZ);
MatrixDomain<Ints> MD(ZZ);
ZVector LHS(ZZ, A.rowdim()), RHS(ZZ, B);
// check that Ax = d.b
MD.vectorMul(LHS, A, X);
VD.mulin(RHS, d);
if (VD.areEqual(LHS, RHS))
std::cout << "Ax=d.b : Yes" << std::endl;
else
std::cout << "Ax=d.b : No" << std::endl;
}
{
// Print Solution
std::cout << "(DenseElimination) Solution is [";
for(auto it:X) ZZ.write(std::cout, it) << " ";
std::cout << "] / ";
ZZ.write(std::cout, d)<< std::endl;
}
return 0;
}
// Local Variables:
// mode: C++
// tab-width: 4
// indent-tabs-mode: nil
// c-basic-offset: 4
// End:
// vim:sts=4:sw=4:ts=4:et:sr:cino=>s,f0,{0,g0,(0,\:0,t0,+0,=s
<|endoftext|> |
<commit_before>
#include "polyimport.h"
#include "PolyPolygon.h"
#include "OSBasics.h"
using namespace Polycode;
const struct aiScene* scene = NULL;
bool hasWeights = false;
vector<aiBone*> bones;
unsigned int numBones = 0;
unsigned int addBone(aiBone *bone) {
for(int i=0; i < bones.size(); i++) {
if(bones[i]->mName == bone->mName)
return i;
}
bones.push_back(bone);
return bones.size()-1;
}
void addToMesh(Polycode::Mesh *tmesh, const struct aiScene *sc, const struct aiNode* nd, bool swapZY) {
int i;
unsigned int n = 0, t;
// draw all meshes assigned to this node
for (; n < nd->mNumMeshes; ++n) {
const struct aiMesh* mesh = scene->mMeshes[nd->mMeshes[n]];
printf("Importing mesh:%s\n", mesh->mName.data);
//apply_material(sc->mMaterials[mesh->mMaterialIndex]);
for (t = 0; t < mesh->mNumFaces; ++t) {
const struct aiFace* face = &mesh->mFaces[t];
Polycode::Polygon *poly = new Polycode::Polygon();
for(i = 0; i < face->mNumIndices; i++) {
Vertex *vertex = new Vertex();
int index = face->mIndices[i];
if(mesh->mColors[0] != NULL) {
vertex->vertexColor.setColorRGBA(mesh->mColors[0][index].r, mesh->mColors[0][index].g, mesh->mColors[0][index].b, mesh->mColors[0][index].a);
}
if(mesh->mNormals != NULL) {
if(swapZY)
vertex->setNormal(mesh->mNormals[index].x, mesh->mNormals[index].z, -mesh->mNormals[index].y);
else
vertex->setNormal(mesh->mNormals[index].x, mesh->mNormals[index].y, mesh->mNormals[index].z);
}
if(mesh->HasTextureCoords(0))
{
vertex->setTexCoord(mesh->mTextureCoords[0][index].x, mesh->mTextureCoords[0][index].y);
}
for( unsigned int a = 0; a < mesh->mNumBones; a++) {
aiBone* bone = mesh->mBones[a];
unsigned int boneIndex = addBone(bone);
for( unsigned int b = 0; b < bone->mNumWeights; b++) {
if(bone->mWeights[b].mVertexId == index) {
vertex->addBoneAssignment(boneIndex, bone->mWeights[b].mWeight);
hasWeights = true;
}
}
}
if(swapZY)
vertex->set(mesh->mVertices[index].x, mesh->mVertices[index].z, -mesh->mVertices[index].y);
else
vertex->set(mesh->mVertices[index].x, mesh->mVertices[index].y, mesh->mVertices[index].z);
poly->addVertex(vertex);
}
tmesh->addPolygon(poly);
}
}
// draw all children
for (n = 0; n < nd->mNumChildren; ++n) {
addToMesh(tmesh, sc, nd->mChildren[n], swapZY);
}
}
int getBoneID(aiString name) {
for(int i=0; i < bones.size(); i++) {
if(bones[i]->mName == name) {
return i;
}
}
return 666;
}
void addToISkeleton(ISkeleton *skel, IBone *parent, const struct aiScene *sc, const struct aiNode* nd) {
IBone *bone = new IBone();
bone->parent = parent;
bone->name = nd->mName;
bone->t = nd->mTransformation;
for(int i=0; i < bones.size(); i++) {
if(bones[i]->mName == bone->name) {
bone->bindMatrix = bones[i]->mOffsetMatrix;
}
}
for (int n = 0; n < nd->mNumChildren; ++n) {
addToISkeleton(skel, bone, sc, nd->mChildren[n]);
}
skel->addIBone(bone, getBoneID(bone->name));
}
int exportToFile(const char *fileName, bool swapZY) {
String fileNameMesh = String(fileName)+".mesh";
OSFILE *outFile = OSBasics::open(fileNameMesh.c_str(), "wb");
Polycode::Mesh *mesh = new Polycode::Mesh(Mesh::TRI_MESH);
addToMesh(mesh, scene, scene->mRootNode, swapZY);
mesh->saveToFile(outFile);
OSBasics::close(outFile);
if(hasWeights) {
printf("Mesh has weights, exporting skeleton...\n");
String fileNameSkel = String(fileName)+".skeleton";
ISkeleton *skeleton = new ISkeleton();
for (int n = 0; n < scene->mRootNode->mNumChildren; ++n) {
if(scene->mRootNode->mChildren[n]->mNumChildren > 0) {
addToISkeleton(skeleton, NULL, scene, scene->mRootNode->mChildren[n]);
}
}
if(scene->HasAnimations()) {
printf("Importing animations...\n");
for(int i=0; i < scene->mNumAnimations;i++) {
aiAnimation *a = scene->mAnimations[i];
printf("Importing '%s' (%d tracks)\n", a->mName.data, a->mNumChannels);
IAnimation *anim = new IAnimation();
anim->tps = a->mTicksPerSecond;
anim->name = a->mName.data;
anim->numTracks = a->mNumChannels;
anim->length = a->mDuration/a->mTicksPerSecond;
for(int c=0; c < a->mNumChannels; c++) {
aiNodeAnim *nodeAnim = a->mChannels[c];
ITrack *track = new ITrack();
track->nodeAnim = nodeAnim;
anim->tracks.push_back(track);
}
skeleton->addAnimation(anim);
}
} else {
printf("No animations in file...\n");
}
skeleton->saveToFile(fileName, swapZY);
} else {
printf("No weight data, skipping skeleton export...\n");
}
delete mesh;
return 1;
}
int main(int argc, char **argv) {
printf("Polycode import tool v0.8.2\n");
if(argc != 4) {
printf("\n\nInvalid arguments!\n");
printf("usage: polyimport <source_file> <output_file> (Swap Z/Y:<true>/<false>) \n\n");
return 0;
}
struct aiLogStream stream;
stream = aiGetPredefinedLogStream(aiDefaultLogStream_STDOUT,NULL);
aiAttachLogStream(&stream);
printf("Loading %s...\n", argv[1]);
scene = aiImportFile(argv[1],aiProcessPreset_TargetRealtime_Quality);
exportToFile(argv[2], strcmp(argv[3], "true") == 0);
aiReleaseImport(scene);
return 1;
}
<commit_msg>Fix for polyimport on Linux<commit_after>
#include "polyimport.h"
#include "PolyPolygon.h"
#include "OSBasics.h"
using namespace Polycode;
const struct aiScene* scene = NULL;
bool hasWeights = false;
vector<aiBone*> bones;
unsigned int numBones = 0;
unsigned int addBone(aiBone *bone) {
for(int i=0; i < bones.size(); i++) {
if(bones[i]->mName == bone->mName)
return i;
}
bones.push_back(bone);
return bones.size()-1;
}
void addToMesh(Polycode::Mesh *tmesh, const struct aiScene *sc, const struct aiNode* nd, bool swapZY) {
int i;
unsigned int n = 0, t;
// draw all meshes assigned to this node
for (; n < nd->mNumMeshes; ++n) {
const struct aiMesh* mesh = scene->mMeshes[nd->mMeshes[n]];
printf("Importing mesh:%s\n", mesh->mName.data);
//apply_material(sc->mMaterials[mesh->mMaterialIndex]);
for (t = 0; t < mesh->mNumFaces; ++t) {
const struct aiFace* face = &mesh->mFaces[t];
Polycode::Polygon *poly = new Polycode::Polygon();
for(i = 0; i < face->mNumIndices; i++) {
Vertex *vertex = new Vertex();
int index = face->mIndices[i];
if(mesh->mColors[0] != NULL) {
vertex->vertexColor.setColorRGBA(mesh->mColors[0][index].r, mesh->mColors[0][index].g, mesh->mColors[0][index].b, mesh->mColors[0][index].a);
}
if(mesh->mNormals != NULL) {
if(swapZY)
vertex->setNormal(mesh->mNormals[index].x, mesh->mNormals[index].z, -mesh->mNormals[index].y);
else
vertex->setNormal(mesh->mNormals[index].x, mesh->mNormals[index].y, mesh->mNormals[index].z);
}
if(mesh->HasTextureCoords(0))
{
vertex->setTexCoord(mesh->mTextureCoords[0][index].x, mesh->mTextureCoords[0][index].y);
}
for( unsigned int a = 0; a < mesh->mNumBones; a++) {
aiBone* bone = mesh->mBones[a];
unsigned int boneIndex = addBone(bone);
for( unsigned int b = 0; b < bone->mNumWeights; b++) {
if(bone->mWeights[b].mVertexId == index) {
vertex->addBoneAssignment(boneIndex, bone->mWeights[b].mWeight);
hasWeights = true;
}
}
}
if(swapZY)
vertex->set(mesh->mVertices[index].x, mesh->mVertices[index].z, -mesh->mVertices[index].y);
else
vertex->set(mesh->mVertices[index].x, mesh->mVertices[index].y, mesh->mVertices[index].z);
poly->addVertex(vertex);
}
tmesh->addPolygon(poly);
}
}
// draw all children
for (n = 0; n < nd->mNumChildren; ++n) {
addToMesh(tmesh, sc, nd->mChildren[n], swapZY);
}
}
int getBoneID(aiString name) {
for(int i=0; i < bones.size(); i++) {
if(bones[i]->mName == name) {
return i;
}
}
return 666;
}
void addToISkeleton(ISkeleton *skel, IBone *parent, const struct aiScene *sc, const struct aiNode* nd) {
IBone *bone = new IBone();
bone->parent = parent;
bone->name = nd->mName;
bone->t = nd->mTransformation;
for(int i=0; i < bones.size(); i++) {
if(bones[i]->mName == bone->name) {
bone->bindMatrix = bones[i]->mOffsetMatrix;
}
}
for (int n = 0; n < nd->mNumChildren; ++n) {
addToISkeleton(skel, bone, sc, nd->mChildren[n]);
}
skel->addIBone(bone, getBoneID(bone->name));
}
int exportToFile(const char *fileName, bool swapZY) {
String fileNameMesh = String(fileName)+".mesh";
OSFILE *outFile = OSBasics::open(fileNameMesh.c_str(), "wb");
Polycode::Mesh *mesh = new Polycode::Mesh(Mesh::TRI_MESH);
addToMesh(mesh, scene, scene->mRootNode, swapZY);
mesh->saveToFile(outFile);
OSBasics::close(outFile);
if(hasWeights) {
printf("Mesh has weights, exporting skeleton...\n");
String fileNameSkel = String(fileName)+".skeleton";
ISkeleton *skeleton = new ISkeleton();
for (int n = 0; n < scene->mRootNode->mNumChildren; ++n) {
if(scene->mRootNode->mChildren[n]->mNumChildren > 0) {
addToISkeleton(skeleton, NULL, scene, scene->mRootNode->mChildren[n]);
}
}
if(scene->HasAnimations()) {
printf("Importing animations...\n");
for(int i=0; i < scene->mNumAnimations;i++) {
aiAnimation *a = scene->mAnimations[i];
printf("Importing '%s' (%d tracks)\n", a->mName.data, a->mNumChannels);
IAnimation *anim = new IAnimation();
anim->tps = a->mTicksPerSecond;
anim->name = a->mName.data;
anim->numTracks = a->mNumChannels;
anim->length = a->mDuration/a->mTicksPerSecond;
for(int c=0; c < a->mNumChannels; c++) {
aiNodeAnim *nodeAnim = a->mChannels[c];
ITrack *track = new ITrack();
track->nodeAnim = nodeAnim;
anim->tracks.push_back(track);
}
skeleton->addAnimation(anim);
}
} else {
printf("No animations in file...\n");
}
skeleton->saveToFile(fileName, swapZY);
} else {
printf("No weight data, skipping skeleton export...\n");
}
delete mesh;
return 1;
}
int main(int argc, char **argv) {
printf("Polycode import tool v0.8.2\n");
if(argc != 4) {
printf("\n\nInvalid arguments!\n");
printf("usage: polyimport <source_file> <output_file> (Swap Z/Y:<true>/<false>) \n\n");
return 0;
}
PHYSFS_init(argv[0]);
struct aiLogStream stream;
stream = aiGetPredefinedLogStream(aiDefaultLogStream_STDOUT,NULL);
aiAttachLogStream(&stream);
printf("Loading %s...\n", argv[1]);
scene = aiImportFile(argv[1],aiProcessPreset_TargetRealtime_Quality);
exportToFile(argv[2], strcmp(argv[3], "true") == 0);
aiReleaseImport(scene);
return 1;
}
<|endoftext|> |
<commit_before>//
// CRT.cpp
// Clock Signal
//
// Created by Thomas Harte on 19/07/2015.
// Copyright © 2015 Thomas Harte. All rights reserved.
//
#include "CRT.hpp"
#include <stdarg.h>
static const int bufferWidth = 512;
static const int bufferHeight = 512;
using namespace Outputs;
CRT::CRT(int cycles_per_line, int height_of_display, int number_of_buffers, ...)
{
static const int syncCapacityLineChargeThreshold = 3;
static const int millisecondsHorizontalRetraceTime = 16;
static const int scanlinesVerticalRetraceTime = 26;
// store fundamental display configuration properties
_height_of_display = height_of_display;
_cycles_per_line = cycles_per_line;
// generate timing values implied by the given arbuments
_hsync_error_window = cycles_per_line >> 5;
_sync_capacitor_charge_threshold = syncCapacityLineChargeThreshold * cycles_per_line;
_horizontal_retrace_time = (millisecondsHorizontalRetraceTime * cycles_per_line) >> 6;
_vertical_retrace_time = scanlinesVerticalRetraceTime * cycles_per_line;
_scanSpeed.x = 1.0f / (float)cycles_per_line;
_scanSpeed.y = 1.0f / (float)height_of_display;
_retraceSpeed.x = 1.0f / (float)_horizontal_retrace_time;
_retraceSpeed.y = 1.0f / (float)_vertical_retrace_time;
// generate buffers for signal storage as requested — format is
// number of buffers, size of buffer 1, size of buffer 2...
_numberOfBuffers = number_of_buffers;
_bufferSizes = new int[_numberOfBuffers];
_buffers = new uint8_t *[_numberOfBuffers];
va_list va;
va_start(va, number_of_buffers);
for(int c = 0; c < _numberOfBuffers; c++)
{
_bufferSizes[c] = va_arg(va, int);
_buffers[c] = new uint8_t[bufferHeight * bufferWidth * _bufferSizes[c]];
}
va_end(va);
// reset pointer into output buffers
_write_allocation_pointer = 0;
// reset the run buffer pointer
_run_pointer = 0;
// reset raster position
_rasterPosition.x = _rasterPosition.y = 0.0f;
// reset flywheel sync
_expected_next_hsync = cycles_per_line;
_horizontal_counter = 0;
// reset the vertical charge capacitor
_sync_capacitor_charge_level = 0;
// start off not in horizontal sync, not receiving a sync signal
_is_receiving_sync = false;
_is_in_hsync = false;
_vretrace_counter = 0;
}
CRT::~CRT()
{
delete[] _bufferSizes;
for(int c = 0; c < _numberOfBuffers; c++)
{
delete[] _buffers[c];
}
delete[] _buffers;
}
#pragma mark - Sync loop
CRT::SyncEvent CRT::advance_to_next_sync_event(bool hsync_is_requested, bool vsync_is_charging, int cycles_to_run_for, int *cycles_advanced)
{
// do we recognise this hsync, thereby adjusting time expectations?
if ((_horizontal_counter < _hsync_error_window || _horizontal_counter >= _expected_next_hsync - _hsync_error_window) && hsync_is_requested) {
_did_detect_hsync = true;
int time_now = (_horizontal_counter < _hsync_error_window) ? _expected_next_hsync + _horizontal_counter : _horizontal_counter;
_expected_next_hsync = (_expected_next_hsync + time_now) >> 1;
// printf("to %d for %d\n", _expected_next_hsync, time_now);
}
SyncEvent proposedEvent = SyncEvent::None;
int proposedSyncTime = cycles_to_run_for;
// have we overrun the maximum permitted number of horizontal syncs for this frame?
if (!_vretrace_counter)
{
float raster_distance = _scanSpeed.y * (float)proposedSyncTime;
if(_rasterPosition.y < 1.02f && _rasterPosition.y + raster_distance >= 1.02f) {
proposedSyncTime = (int)(1.02f - _rasterPosition.y) / _scanSpeed.y;
proposedEvent = SyncEvent::StartVSync;
}
}
// will we end an ongoing hsync?
if (_horizontal_counter < _horizontal_retrace_time && _horizontal_counter+proposedSyncTime >= _horizontal_retrace_time) {
proposedSyncTime = _horizontal_retrace_time - _horizontal_counter;
proposedEvent = SyncEvent::EndHSync;
}
// will we start an hsync?
if (_horizontal_counter + proposedSyncTime >= _expected_next_hsync) {
proposedSyncTime = _expected_next_hsync - _horizontal_counter;
proposedEvent = SyncEvent::StartHSync;
}
// will an acceptable vertical sync be triggered?
if (vsync_is_charging && !_vretrace_counter) {
if (_sync_capacitor_charge_level < _sync_capacitor_charge_threshold && _sync_capacitor_charge_level + proposedSyncTime >= _sync_capacitor_charge_threshold) {
proposedSyncTime = _sync_capacitor_charge_threshold - _sync_capacitor_charge_level;
proposedEvent = SyncEvent::StartVSync;
}
}
// will an ongoing vertical sync end?
if (_vretrace_counter > 0) {
if (_vretrace_counter < proposedSyncTime) {
proposedSyncTime = _vretrace_counter;
proposedEvent = SyncEvent::EndVSync;
}
}
*cycles_advanced = proposedSyncTime;
return proposedEvent;
}
void CRT::advance_cycles(int number_of_cycles, bool hsync_requested, const bool vsync_charging, const CRTRun::Type type, const char *data_type)
{
// this is safe to keep locally because it accumulates over this run of cycles only
int buffer_offset = 0;
while(number_of_cycles) {
// get the next sync event and its timing; hsync request is instantaneous (being edge triggered) so
// set it to false for the next run through this loop (if any)
int next_run_length;
SyncEvent next_event = advance_to_next_sync_event(hsync_requested, vsync_charging, number_of_cycles, &next_run_length);
hsync_requested = false;
// get a run from the allocated list, allocating more if we're about to overrun
if(_run_pointer >= _all_runs.size())
{
_all_runs.resize((_all_runs.size() * 2)+1);
}
CRTRun *nextRun = &_all_runs[_run_pointer];
_run_pointer++;
// set the type, initial raster position and type of this run
nextRun->type = type;
nextRun->start_point.dst_x = _rasterPosition.x;
nextRun->start_point.dst_y = _rasterPosition.y;
nextRun->data_type = data_type;
// if this is a data or level run then store a starting data position
if(type == CRTRun::Type::Data || type == CRTRun::Type::Level)
{
nextRun->start_point.src_x = (_write_target_pointer + buffer_offset) & (bufferWidth - 1);
nextRun->start_point.src_y = (_write_target_pointer + buffer_offset) / bufferWidth;
}
// advance the raster position as dictated by current sync status
if (_is_in_hsync)
_rasterPosition.x = std::max(0.0f, _rasterPosition.x - (float)number_of_cycles * _retraceSpeed.x);
else
_rasterPosition.x = std::min(1.0f, _rasterPosition.x + (float)number_of_cycles * _scanSpeed.x);
if (_vretrace_counter > 0)
_rasterPosition.y = std::max(0.0f, _rasterPosition.y - (float)number_of_cycles * _retraceSpeed.y);
else
_rasterPosition.y = std::min(1.0f, _rasterPosition.y + (float)number_of_cycles * _scanSpeed.y);
// store the final raster position
nextRun->end_point.dst_x = _rasterPosition.x;
nextRun->end_point.dst_y = _rasterPosition.y;
// if this is a data run then advance the buffer pointer
if(type == CRTRun::Type::Data)
{
buffer_offset += next_run_length;
}
// if this is a data or level run then store the end point
if(type == CRTRun::Type::Data || type == CRTRun::Type::Level)
{
nextRun->end_point.src_x = (_write_target_pointer + buffer_offset) & (bufferWidth - 1);
nextRun->end_point.src_y = (_write_target_pointer + buffer_offset) / bufferWidth;
}
// decrement the number of cycles left to run for and increment the
// horizontal counter appropriately
number_of_cycles -= next_run_length;
_horizontal_counter += next_run_length;
// either charge or deplete the vertical retrace capacitor (making sure it stops at 0)
if (vsync_charging)
_sync_capacitor_charge_level += next_run_length;
else
_sync_capacitor_charge_level = std::max(_sync_capacitor_charge_level - next_run_length, 0);
// decrement the vertical retrace counter, making sure it stops at 0
_vretrace_counter = std::max(_vretrace_counter - next_run_length, 0);
// react to the incoming event...
switch(next_event) {
// start of hsync: zero the scanline counter, note that we're now in
// horizontal sync, increment the lines-in-this-frame counter
case SyncEvent::StartHSync:
_horizontal_counter = 0;
_is_in_hsync = true;
break;
// end of horizontal sync: update the flywheel's velocity, note that we're no longer
// in horizontal sync
case SyncEvent::EndHSync:
if (!_did_detect_hsync) {
_expected_next_hsync = (_expected_next_hsync + (_hsync_error_window >> 1) + _cycles_per_line) >> 1;
}
_did_detect_hsync = false;
_is_in_hsync = false;
break;
// start of vertical sync: reset the lines-in-this-frame counter,
// load the retrace counter with the amount of time it'll take to retrace
case SyncEvent::StartVSync:
_vretrace_counter = _vertical_retrace_time;
break;
// end of vertical sync: tell the delegate that we finished vertical sync,
// releasing all runs back into the common pool
case SyncEvent::EndVSync:
if(_delegate != nullptr)
_delegate->crt_did_start_vertical_retrace_with_runs(&_all_runs[0], _run_pointer);
_run_pointer = 0;
break;
default: break;
}
}
}
#pragma mark - delegate
void CRT::set_delegate(CRTDelegate *delegate)
{
_delegate = delegate;
}
#pragma mark - stream feeding methods
/*
These all merely channel into advance_cycles, supplying appropriate arguments
*/
void CRT::output_sync(int number_of_cycles)
{
bool _hsync_requested = !_is_receiving_sync; // ensure this really is edge triggered; someone calling output_sync twice in succession shouldn't trigger it twice
_is_receiving_sync = true;
advance_cycles(number_of_cycles, _hsync_requested, true, CRTRun::Type::Sync, nullptr);
}
void CRT::output_blank(int number_of_cycles)
{
_is_receiving_sync = false;
advance_cycles(number_of_cycles, false, false, CRTRun::Type::Blank, nullptr);
}
void CRT::output_level(int number_of_cycles, const char *type)
{
_is_receiving_sync = false;
advance_cycles(number_of_cycles, false, false, CRTRun::Type::Level, type);
}
void CRT::output_data(int number_of_cycles, const char *type)
{
_is_receiving_sync = false;
advance_cycles(number_of_cycles, false, false, CRTRun::Type::Data, type);
}
#pragma mark - Buffer supply
void CRT::allocate_write_area(int required_length)
{
int xPos = _write_allocation_pointer & (bufferWidth - 1);
if (xPos + required_length > bufferWidth)
{
_write_allocation_pointer &= ~(bufferWidth - 1);
_write_allocation_pointer = (_write_allocation_pointer + bufferWidth) & ((bufferHeight-1) * bufferWidth);
}
_write_target_pointer = _write_allocation_pointer;
_write_allocation_pointer += required_length;
}
uint8_t *CRT::get_write_target_for_buffer(int buffer)
{
return &_buffers[buffer][_write_target_pointer * _bufferSizes[buffer]];
}
<commit_msg>Fix one: vertical scan speed was failing to allow for the number of cycles in a line.<commit_after>//
// CRT.cpp
// Clock Signal
//
// Created by Thomas Harte on 19/07/2015.
// Copyright © 2015 Thomas Harte. All rights reserved.
//
#include "CRT.hpp"
#include <stdarg.h>
static const int bufferWidth = 512;
static const int bufferHeight = 512;
using namespace Outputs;
CRT::CRT(int cycles_per_line, int height_of_display, int number_of_buffers, ...)
{
static const int syncCapacityLineChargeThreshold = 3;
static const int millisecondsHorizontalRetraceTime = 16;
static const int scanlinesVerticalRetraceTime = 26;
// store fundamental display configuration properties
_height_of_display = height_of_display;
_cycles_per_line = cycles_per_line;
// generate timing values implied by the given arbuments
_hsync_error_window = cycles_per_line >> 5;
_sync_capacitor_charge_threshold = syncCapacityLineChargeThreshold * cycles_per_line;
_horizontal_retrace_time = (millisecondsHorizontalRetraceTime * cycles_per_line) >> 6;
_vertical_retrace_time = scanlinesVerticalRetraceTime * cycles_per_line;
_scanSpeed.x = 1.0f / (float)cycles_per_line;
_scanSpeed.y = 1.0f / (float)(height_of_display * cycles_per_line);
_retraceSpeed.x = 1.0f / (float)_horizontal_retrace_time;
_retraceSpeed.y = 1.0f / (float)_vertical_retrace_time;
// generate buffers for signal storage as requested — format is
// number of buffers, size of buffer 1, size of buffer 2...
_numberOfBuffers = number_of_buffers;
_bufferSizes = new int[_numberOfBuffers];
_buffers = new uint8_t *[_numberOfBuffers];
va_list va;
va_start(va, number_of_buffers);
for(int c = 0; c < _numberOfBuffers; c++)
{
_bufferSizes[c] = va_arg(va, int);
_buffers[c] = new uint8_t[bufferHeight * bufferWidth * _bufferSizes[c]];
}
va_end(va);
// reset pointer into output buffers
_write_allocation_pointer = 0;
// reset the run buffer pointer
_run_pointer = 0;
// reset raster position
_rasterPosition.x = _rasterPosition.y = 0.0f;
// reset flywheel sync
_expected_next_hsync = cycles_per_line;
_horizontal_counter = 0;
// reset the vertical charge capacitor
_sync_capacitor_charge_level = 0;
// start off not in horizontal sync, not receiving a sync signal
_is_receiving_sync = false;
_is_in_hsync = false;
_vretrace_counter = 0;
}
CRT::~CRT()
{
delete[] _bufferSizes;
for(int c = 0; c < _numberOfBuffers; c++)
{
delete[] _buffers[c];
}
delete[] _buffers;
}
#pragma mark - Sync loop
CRT::SyncEvent CRT::advance_to_next_sync_event(bool hsync_is_requested, bool vsync_is_charging, int cycles_to_run_for, int *cycles_advanced)
{
// do we recognise this hsync, thereby adjusting time expectations?
if ((_horizontal_counter < _hsync_error_window || _horizontal_counter >= _expected_next_hsync - _hsync_error_window) && hsync_is_requested) {
_did_detect_hsync = true;
int time_now = (_horizontal_counter < _hsync_error_window) ? _expected_next_hsync + _horizontal_counter : _horizontal_counter;
_expected_next_hsync = (_expected_next_hsync + time_now) >> 1;
// printf("to %d for %d\n", _expected_next_hsync, time_now);
}
SyncEvent proposedEvent = SyncEvent::None;
int proposedSyncTime = cycles_to_run_for;
// have we overrun the maximum permitted number of horizontal syncs for this frame?
if (!_vretrace_counter)
{
float raster_distance = _scanSpeed.y * (float)proposedSyncTime;
if(_rasterPosition.y < 1.02f && _rasterPosition.y + raster_distance >= 1.02f) {
proposedSyncTime = (int)(1.02f - _rasterPosition.y) / _scanSpeed.y;
proposedEvent = SyncEvent::StartVSync;
}
}
// will we end an ongoing hsync?
if (_horizontal_counter < _horizontal_retrace_time && _horizontal_counter+proposedSyncTime >= _horizontal_retrace_time) {
proposedSyncTime = _horizontal_retrace_time - _horizontal_counter;
proposedEvent = SyncEvent::EndHSync;
}
// will we start an hsync?
if (_horizontal_counter + proposedSyncTime >= _expected_next_hsync) {
proposedSyncTime = _expected_next_hsync - _horizontal_counter;
proposedEvent = SyncEvent::StartHSync;
}
// will an acceptable vertical sync be triggered?
if (vsync_is_charging && !_vretrace_counter) {
if (_sync_capacitor_charge_level < _sync_capacitor_charge_threshold && _sync_capacitor_charge_level + proposedSyncTime >= _sync_capacitor_charge_threshold) {
proposedSyncTime = _sync_capacitor_charge_threshold - _sync_capacitor_charge_level;
proposedEvent = SyncEvent::StartVSync;
}
}
// will an ongoing vertical sync end?
if (_vretrace_counter > 0) {
if (_vretrace_counter < proposedSyncTime) {
proposedSyncTime = _vretrace_counter;
proposedEvent = SyncEvent::EndVSync;
}
}
*cycles_advanced = proposedSyncTime;
return proposedEvent;
}
void CRT::advance_cycles(int number_of_cycles, bool hsync_requested, const bool vsync_charging, const CRTRun::Type type, const char *data_type)
{
// this is safe to keep locally because it accumulates over this run of cycles only
int buffer_offset = 0;
while(number_of_cycles) {
// get the next sync event and its timing; hsync request is instantaneous (being edge triggered) so
// set it to false for the next run through this loop (if any)
int next_run_length;
SyncEvent next_event = advance_to_next_sync_event(hsync_requested, vsync_charging, number_of_cycles, &next_run_length);
hsync_requested = false;
// get a run from the allocated list, allocating more if we're about to overrun
if(_run_pointer >= _all_runs.size())
{
_all_runs.resize((_all_runs.size() * 2)+1);
}
CRTRun *nextRun = &_all_runs[_run_pointer];
_run_pointer++;
// set the type, initial raster position and type of this run
nextRun->type = type;
nextRun->start_point.dst_x = _rasterPosition.x;
nextRun->start_point.dst_y = _rasterPosition.y;
nextRun->data_type = data_type;
// if this is a data or level run then store a starting data position
if(type == CRTRun::Type::Data || type == CRTRun::Type::Level)
{
nextRun->start_point.src_x = (_write_target_pointer + buffer_offset) & (bufferWidth - 1);
nextRun->start_point.src_y = (_write_target_pointer + buffer_offset) / bufferWidth;
}
// advance the raster position as dictated by current sync status
if (_is_in_hsync)
_rasterPosition.x = std::max(0.0f, _rasterPosition.x - (float)number_of_cycles * _retraceSpeed.x);
else
_rasterPosition.x = std::min(1.0f, _rasterPosition.x + (float)number_of_cycles * _scanSpeed.x);
if (_vretrace_counter > 0)
_rasterPosition.y = std::max(0.0f, _rasterPosition.y - (float)number_of_cycles * _retraceSpeed.y);
else
_rasterPosition.y = std::min(1.0f, _rasterPosition.y + (float)number_of_cycles * _scanSpeed.y);
// store the final raster position
nextRun->end_point.dst_x = _rasterPosition.x;
nextRun->end_point.dst_y = _rasterPosition.y;
// if this is a data run then advance the buffer pointer
if(type == CRTRun::Type::Data)
{
buffer_offset += next_run_length;
}
// if this is a data or level run then store the end point
if(type == CRTRun::Type::Data || type == CRTRun::Type::Level)
{
nextRun->end_point.src_x = (_write_target_pointer + buffer_offset) & (bufferWidth - 1);
nextRun->end_point.src_y = (_write_target_pointer + buffer_offset) / bufferWidth;
}
// decrement the number of cycles left to run for and increment the
// horizontal counter appropriately
number_of_cycles -= next_run_length;
_horizontal_counter += next_run_length;
// either charge or deplete the vertical retrace capacitor (making sure it stops at 0)
if (vsync_charging)
_sync_capacitor_charge_level += next_run_length;
else
_sync_capacitor_charge_level = std::max(_sync_capacitor_charge_level - next_run_length, 0);
// decrement the vertical retrace counter, making sure it stops at 0
_vretrace_counter = std::max(_vretrace_counter - next_run_length, 0);
// react to the incoming event...
switch(next_event) {
// start of hsync: zero the scanline counter, note that we're now in
// horizontal sync, increment the lines-in-this-frame counter
case SyncEvent::StartHSync:
_horizontal_counter = 0;
_is_in_hsync = true;
break;
// end of horizontal sync: update the flywheel's velocity, note that we're no longer
// in horizontal sync
case SyncEvent::EndHSync:
if (!_did_detect_hsync) {
_expected_next_hsync = (_expected_next_hsync + (_hsync_error_window >> 1) + _cycles_per_line) >> 1;
}
_did_detect_hsync = false;
_is_in_hsync = false;
break;
// start of vertical sync: reset the lines-in-this-frame counter,
// load the retrace counter with the amount of time it'll take to retrace
case SyncEvent::StartVSync:
_vretrace_counter = _vertical_retrace_time;
break;
// end of vertical sync: tell the delegate that we finished vertical sync,
// releasing all runs back into the common pool
case SyncEvent::EndVSync:
if(_delegate != nullptr)
_delegate->crt_did_start_vertical_retrace_with_runs(&_all_runs[0], _run_pointer);
_run_pointer = 0;
break;
default: break;
}
}
}
#pragma mark - delegate
void CRT::set_delegate(CRTDelegate *delegate)
{
_delegate = delegate;
}
#pragma mark - stream feeding methods
/*
These all merely channel into advance_cycles, supplying appropriate arguments
*/
void CRT::output_sync(int number_of_cycles)
{
bool _hsync_requested = !_is_receiving_sync; // ensure this really is edge triggered; someone calling output_sync twice in succession shouldn't trigger it twice
_is_receiving_sync = true;
advance_cycles(number_of_cycles, _hsync_requested, true, CRTRun::Type::Sync, nullptr);
}
void CRT::output_blank(int number_of_cycles)
{
_is_receiving_sync = false;
advance_cycles(number_of_cycles, false, false, CRTRun::Type::Blank, nullptr);
}
void CRT::output_level(int number_of_cycles, const char *type)
{
_is_receiving_sync = false;
advance_cycles(number_of_cycles, false, false, CRTRun::Type::Level, type);
}
void CRT::output_data(int number_of_cycles, const char *type)
{
_is_receiving_sync = false;
advance_cycles(number_of_cycles, false, false, CRTRun::Type::Data, type);
}
#pragma mark - Buffer supply
void CRT::allocate_write_area(int required_length)
{
int xPos = _write_allocation_pointer & (bufferWidth - 1);
if (xPos + required_length > bufferWidth)
{
_write_allocation_pointer &= ~(bufferWidth - 1);
_write_allocation_pointer = (_write_allocation_pointer + bufferWidth) & ((bufferHeight-1) * bufferWidth);
}
_write_target_pointer = _write_allocation_pointer;
_write_allocation_pointer += required_length;
}
uint8_t *CRT::get_write_target_for_buffer(int buffer)
{
return &_buffers[buffer][_write_target_pointer * _bufferSizes[buffer]];
}
<|endoftext|> |
<commit_before>/*******************************************************
* Copyright (c) 2014, ArrayFire
* All rights reserved.
*
* This file is distributed under 3-clause BSD license.
* The complete license agreement can be obtained at:
* http://arrayfire.com/licenses/BSD-3-Clause
********************************************************/
#include <arrayfire.h>
#include <af/exception.h>
#include <iostream>
using namespace af;
int main(int argc, char *argv[])
{
try {
int device = argc > 1 ? atoi(argv[1]) : 0;
af::setDevice(device);
af::info();
printf("\ncreate a 5-by-3 matrix of random floats on the GPU\n");
array A = randu(5,3, f32);
af_print(A);
printf("element-wise arithmetic\n");
array B = sin(A) + 1.5;
af_print(B);
printf("Fourier transform the result\n");
array C = fft(B);
af_print(C);
printf("grab last row\n");
array c = C.row(end);
af_print(c);
printf("zero out every other column\n");
B(span, seq(0, end, 2)) = 0;
printf("negate the first three elements of second column\n");
B(seq(0, 2), 1) = B(seq(0, 2), 1) * -1;
af_print(B);
printf("create 2-by-3 matrix from host data\n");
float d[] = { 1, 2, 3, 4, 5, 6 };
array D(2, 3, d, af::afHost);
af_print(D);
printf("copy last column onto first\n");
D.col(0) = D.col(end);
af_print(D);
// Sort A
printf("sort A and print sorted array and corresponding indices\n");
array E, F;
sort(E, F, A);
af_print(E);
af_print(F);
} catch (af::exception& e) {
fprintf(stderr, "%s\n", e.what());
throw;
}
#ifdef WIN32 // pause in Windows
if (!(argc == 2 && argv[1][0] == '-')) {
printf("hit [enter]...");
fflush(stdout);
getchar();
}
#endif
return 0;
}
<commit_msg>Reorganizing helloworld.cpp<commit_after>/*******************************************************
* Copyright (c) 2014, ArrayFire
* All rights reserved.
*
* This file is distributed under 3-clause BSD license.
* The complete license agreement can be obtained at:
* http://arrayfire.com/licenses/BSD-3-Clause
********************************************************/
#include <arrayfire.h>
#include <cstdio>
using namespace af;
int main(int argc, char *argv[])
{
try {
// Select a device and display arrayfire info
int device = argc > 1 ? atoi(argv[1]) : 0;
af::setDevice(device);
af::info();
printf("Create a 5-by-3 matrix of random floats on the GPU\n");
array A = randu(5,3, f32);
af_print(A);
printf("Element-wise arithmetic\n");
array B = sin(A) + 1.5;
af_print(B);
printf("Negate the first three elements of second column\n");
B(seq(0, 2), 1) = B(seq(0, 2), 1) * -1;
af_print(B);
printf("Fourier transform the result\n");
array C = fft(B);
af_print(C);
printf("Grab last row\n");
array c = C.row(end);
af_print(c);
printf("Create 2-by-3 matrix from host data\n");
float d[] = { 1, 2, 3, 4, 5, 6 };
array D(2, 3, d, af::afHost);
af_print(D);
printf("Copy last column onto first\n");
D.col(0) = D.col(end);
af_print(D);
// Sort A
printf("Sort A and print sorted array and corresponding indices\n");
array vals, inds;
sort(vals, inds, A);
af_print(vals);
af_print(inds);
} catch (af::exception& e) {
fprintf(stderr, "%s\n", e.what());
throw;
}
#ifdef WIN32 // pause in Windows
if (!(argc == 2 && argv[1][0] == '-')) {
printf("hit [enter]...");
fflush(stdout);
getchar();
}
#endif
return 0;
}
<|endoftext|> |
<commit_before>/* bid_request_endpoint_test.cc
Eric Robert, 9 May 2013
Copyright (c) 2013 Datacratic Inc. All rights reserved.
Tool to test a bid request endpoint.
*/
#include <memory>
#include <boost/program_options/cmdline.hpp>
#include <boost/program_options/options_description.hpp>
#include <boost/program_options/positional_options.hpp>
#include <boost/program_options/parsers.hpp>
#include <boost/program_options/variables_map.hpp>
#include "rtbkit/core/router/router.h"
#include "rtbkit/core/agent_configuration/agent_configuration_service.h"
#include "rtbkit/core/banker/null_banker.h"
#include "rtbkit/plugins/bidding_agent/bidding_agent_cluster.h"
#include "rtbkit/testing/test_agent.h"
#include "rtbkit/soa/service/message_loop.h"
#include "jml/utils/file_functions.h"
using namespace Datacratic;
using namespace RTBKIT;
using namespace std ;
static Json::Value loadJsonFromFile(const std::string & filename) {
ML::File_Read_Buffer buf(filename);
return Json::parse(std::string(buf.start(), buf.end()));
}
string tid()
{
ostringstream oss ;
oss << "0x" << hex << this_thread::get_id();
return oss.str();
}
int main(int argc, char ** argv)
{
using namespace boost::program_options;
int recordCount = 1000;
std::string recordFile;
std::string exchangeConfigurationFile = "rtbkit/examples/router-config.json";
options_description endpoint_options("Bid request endpoint options");
endpoint_options.add_options()
("record-request,r", value<std::string>(&recordFile),
"filename prefix to record incoming bid request")
("record-count,n", value<int>(&recordCount),
"number of bid request recorded by file")
("exchange-configuration,x", value<std::string>(&exchangeConfigurationFile),
"configuration file with exchange data");
options_description all_opt;
all_opt
.add(endpoint_options);
all_opt.add_options()
("help,h", "print this message");
variables_map vm;
store(command_line_parser(argc, argv)
.options(all_opt)
.run(),
vm);
notify(vm);
if(vm.count("help")) {
std::cerr << all_opt << std::endl;
exit(1);
}
std::shared_ptr<ServiceProxies> proxies(new ServiceProxies());
// The agent config service lets the router know how our agent is
// configured
AgentConfigurationService agentConfig(proxies, "config");
agentConfig.unsafeDisableMonitor();
agentConfig.init();
agentConfig.bindTcp();
agentConfig.start();
// We need a router for our exchange connector to work
Router router(proxies, "router");
router.unsafeDisableMonitor();
router.init();
// Set a null banker that blindly approves all bids so that we can
// bid.
router.setBanker(std::make_shared<NullBanker>(true));
// Start the router up
router.bindTcp();
router.start();
// Configure exchange connectors
Json::Value exchangeConfiguration = loadJsonFromFile(exchangeConfigurationFile);
for(auto & exchange : exchangeConfiguration) {
router.startExchange(exchange);
}
router.forAllExchanges([&](std::shared_ptr<ExchangeConnector> const & item) {
item->enableUntil(Date::positiveInfinity());
if(!recordFile.empty()) {
std::string filename = item->exchangeName() + "-" + recordFile;
item->startRequestLogging(filename, recordCount);
}
});
RTBKIT::AgentConfig config;
config.maxInFlight = 20000;
config.creatives.push_back(RTBKIT::Creative::sampleLB);
config.creatives.push_back(RTBKIT::Creative::sampleWS);
config.creatives.push_back(RTBKIT::Creative::sampleBB);
// create a router proxy and start it.
BiddingAgentCluster cluster (proxies, "BAC");
cluster.start ();
// create/start/configure 1st agent
auto bob = make_shared<TestAgent>(proxies, "BOB") ;
bob->onBidRequest = [&] (
double timestamp,
const Id & id,
std::shared_ptr<BidRequest> br,
Bids bids,
double timeLeftMs,
const Json::Value & augmentations,
const WinCostModel & wcm)
{
Bid& bid = bids[0];
bid.bid(bid.availableCreatives[0], USD_CPM(1.234));
bob->doBid(id, bids, Json::Value(), wcm);
ML::atomic_inc(bob->numBidRequests);
cerr << bob->serviceName() << "(" << tid() << ") bid count=" << bob->numBidRequests << endl;
};
// create/start/configure 2nd agent
auto alice = make_shared<TestAgent>(proxies, "ALICE") ;
alice->onBidRequest = [&] (
double timestamp,
const Id & id,
std::shared_ptr<BidRequest> br,
Bids bids,
double timeLeftMs,
const Json::Value & augmentations,
const WinCostModel & wcm)
{
Bid& bid = bids[0];
bid.bid(bid.availableCreatives[0], USD_CPM(1.233));
alice->doBid(id, bids, Json::Value(), wcm);
ML::atomic_inc(bob->numBidRequests);
cerr << alice->serviceName() << "(" << tid() << ") bid count=" << alice->numBidRequests << endl;
};
// join agents to our cluster
// joined agents will be added as source to
// our the cluster's poll loop;
cluster.join (bob);
cluster.join (alice);
// for each agent A in cluster, will call A.init()
cluster.init();
// will start polling in a dedicated thread
cluster.start ();
config.account = {"testCampaign", "bobStrategy"};
cluster[bob]->doConfig(config);
config.account = {"testCampaign", "aliceStrategy"};
cluster[alice]->doConfig(config);
for(;;)
{
ML::sleep(10.0);
std::cerr << "----------[ REPORT ]----------" << std::endl;
proxies->events->dump(std::cerr);
}
}
<commit_msg>do not start twice the cluster<commit_after>/* bid_request_endpoint_test.cc
Eric Robert, 9 May 2013
Copyright (c) 2013 Datacratic Inc. All rights reserved.
Tool to test a bid request endpoint.
*/
#include <memory>
#include <boost/program_options/cmdline.hpp>
#include <boost/program_options/options_description.hpp>
#include <boost/program_options/positional_options.hpp>
#include <boost/program_options/parsers.hpp>
#include <boost/program_options/variables_map.hpp>
#include "rtbkit/core/router/router.h"
#include "rtbkit/core/agent_configuration/agent_configuration_service.h"
#include "rtbkit/core/banker/null_banker.h"
#include "rtbkit/plugins/bidding_agent/bidding_agent_cluster.h"
#include "rtbkit/testing/test_agent.h"
#include "rtbkit/soa/service/message_loop.h"
#include "jml/utils/file_functions.h"
using namespace Datacratic;
using namespace RTBKIT;
using namespace std ;
static Json::Value loadJsonFromFile(const std::string & filename) {
ML::File_Read_Buffer buf(filename);
return Json::parse(std::string(buf.start(), buf.end()));
}
string tid()
{
ostringstream oss ;
oss << "0x" << hex << this_thread::get_id();
return oss.str();
}
int main(int argc, char ** argv)
{
using namespace boost::program_options;
int recordCount = 1000;
std::string recordFile;
std::string exchangeConfigurationFile = "rtbkit/examples/router-config.json";
options_description endpoint_options("Bid request endpoint options");
endpoint_options.add_options()
("record-request,r", value<std::string>(&recordFile),
"filename prefix to record incoming bid request")
("record-count,n", value<int>(&recordCount),
"number of bid request recorded by file")
("exchange-configuration,x", value<std::string>(&exchangeConfigurationFile),
"configuration file with exchange data");
options_description all_opt;
all_opt
.add(endpoint_options);
all_opt.add_options()
("help,h", "print this message");
variables_map vm;
store(command_line_parser(argc, argv)
.options(all_opt)
.run(),
vm);
notify(vm);
if(vm.count("help")) {
std::cerr << all_opt << std::endl;
exit(1);
}
std::shared_ptr<ServiceProxies> proxies(new ServiceProxies());
// The agent config service lets the router know how our agent is
// configured
AgentConfigurationService agentConfig(proxies, "config");
agentConfig.unsafeDisableMonitor();
agentConfig.init();
agentConfig.bindTcp();
agentConfig.start();
// We need a router for our exchange connector to work
Router router(proxies, "router");
router.unsafeDisableMonitor();
router.init();
// Set a null banker that blindly approves all bids so that we can
// bid.
router.setBanker(std::make_shared<NullBanker>(true));
// Start the router up
router.bindTcp();
router.start();
// Configure exchange connectors
Json::Value exchangeConfiguration = loadJsonFromFile(exchangeConfigurationFile);
for(auto & exchange : exchangeConfiguration) {
router.startExchange(exchange);
}
router.forAllExchanges([&](std::shared_ptr<ExchangeConnector> const & item) {
item->enableUntil(Date::positiveInfinity());
if(!recordFile.empty()) {
std::string filename = item->exchangeName() + "-" + recordFile;
item->startRequestLogging(filename, recordCount);
}
});
RTBKIT::AgentConfig config;
config.maxInFlight = 20000;
config.creatives.push_back(RTBKIT::Creative::sampleLB);
config.creatives.push_back(RTBKIT::Creative::sampleWS);
config.creatives.push_back(RTBKIT::Creative::sampleBB);
// create a router proxy and start it.
// will start polling in a dedicated thread
BiddingAgentCluster cluster (proxies, "BAC");
cluster.start ();
// create/start/configure 1st agent
auto bob = make_shared<TestAgent>(proxies, "BOB") ;
bob->onBidRequest = [&] (
double timestamp,
const Id & id,
std::shared_ptr<BidRequest> br,
Bids bids,
double timeLeftMs,
const Json::Value & augmentations,
const WinCostModel & wcm)
{
Bid& bid = bids[0];
bid.bid(bid.availableCreatives[0], USD_CPM(1.234));
bob->doBid(id, bids, Json::Value(), wcm);
ML::atomic_inc(bob->numBidRequests);
cerr << bob->serviceName() << "(" << tid() << ") bid count=" << bob->numBidRequests << endl;
};
// create/start/configure 2nd agent
auto alice = make_shared<TestAgent>(proxies, "ALICE") ;
alice->onBidRequest = [&] (
double timestamp,
const Id & id,
std::shared_ptr<BidRequest> br,
Bids bids,
double timeLeftMs,
const Json::Value & augmentations,
const WinCostModel & wcm)
{
Bid& bid = bids[0];
bid.bid(bid.availableCreatives[0], USD_CPM(1.233));
alice->doBid(id, bids, Json::Value(), wcm);
ML::atomic_inc(bob->numBidRequests);
cerr << alice->serviceName() << "(" << tid() << ") bid count=" << alice->numBidRequests << endl;
};
// join agents to our cluster
// joined agents will be added as source to
// our the cluster's poll loop;
cluster.join (bob);
cluster.join (alice);
// for each agent A in cluster, will call A.init()
cluster.init();
config.account = {"testCampaign", "bobStrategy"};
cluster[bob]->doConfig(config);
config.account = {"testCampaign", "aliceStrategy"};
cluster[alice]->doConfig(config);
for(;;)
{
ML::sleep(10.0);
std::cerr << "----------[ REPORT ]----------" << std::endl;
proxies->events->dump(std::cerr);
}
}
<|endoftext|> |
<commit_before>/*************************************************************************
* Copyright (C) 1995-2000, Rene Brun and Fons Rademakers. *
* All rights reserved. *
* *
* For the licensing terms see $ROOTSYS/LICENSE. *
* For the list of contributors see $ROOTSYS/README/CREDITS. *
*************************************************************************/
#include <TPieSlice.h>
#include <Riostream.h>
#include <TError.h>
#include <TROOT.h>
#include <TVirtualPad.h>
#include <TArc.h>
#include <TMath.h>
#include <TStyle.h>
#include <TLatex.h>
#include <TPaveText.h>
#include <TH1.h>
ClassImp(TPieSlice)
//______________________________________________________________________________
//
// A slice of a piechart, see the TPie class.
//
// This class describe the property of single
//
//______________________________________________________________________________
TPieSlice::TPieSlice() : TNamed(), TAttFill(), TAttLine()
{
// This is the default constructor, used to create the standard.
fPie = 0;
fValue = 1;
fRadiusOffset = 0;
fIsActive = kFALSE;
}
//______________________________________________________________________________
TPieSlice::TPieSlice(const char *name, const char *title,
TPie *pie, Double_t val) :
TNamed(name, title), TAttFill(), TAttLine()
{
// This constructor create a slice with a particular value.
fPie = pie;
fValue = val;
fRadiusOffset = 0;
fIsActive = kFALSE;
}
//______________________________________________________________________________
Int_t TPieSlice::DistancetoPrimitive(Int_t /*px*/, Int_t /*py*/)
{
// Eval if the mouse is over the area associated with this slice.
Int_t dist = 9999;
if (fIsActive) {
dist = 0;
fIsActive = kFALSE;
gPad->SetCursor(kCross);
}
return dist;
}
//______________________________________________________________________________
Double_t TPieSlice::GetRadiusOffset()
{
// return the value of the offset in radial direction for this slice.
return fRadiusOffset;
}
//______________________________________________________________________________
Double_t TPieSlice::GetValue()
{
// Return the value of this slice.
return fValue;
}
//______________________________________________________________________________
void TPieSlice::SavePrimitive(ostream &/*out*/, Option_t * /*opts*/)
{
// Do nothing.
}
//______________________________________________________________________________
void TPieSlice::SetRadiusOffset(Double_t val)
{
// Set the radial offset of this slice.
fRadiusOffset = val;
if (fRadiusOffset<.0) fRadiusOffset = .0;
}
//______________________________________________________________________________
void TPieSlice::SetValue(Double_t val)
{
// Set the value for this slice.
// Negative values are changed with its absolute value.
fValue = val;
if (fValue<.0) {
Warning("SetValue","Invalid negative value. Absolute value taken");
fValue *= -1;
}
fPie->MakeSlices(kTRUE);
}
<commit_msg>- From Guido Volpi: Change the cursor shape to point on a slice (Hand instead of Cross)<commit_after>/*************************************************************************
* Copyright (C) 1995-2000, Rene Brun and Fons Rademakers. *
* All rights reserved. *
* *
* For the licensing terms see $ROOTSYS/LICENSE. *
* For the list of contributors see $ROOTSYS/README/CREDITS. *
*************************************************************************/
#include <TPieSlice.h>
#include <Riostream.h>
#include <TError.h>
#include <TROOT.h>
#include <TVirtualPad.h>
#include <TArc.h>
#include <TMath.h>
#include <TStyle.h>
#include <TLatex.h>
#include <TPaveText.h>
#include <TH1.h>
ClassImp(TPieSlice)
//______________________________________________________________________________
//
// A slice of a piechart, see the TPie class.
//
// This class describe the property of single
//
//______________________________________________________________________________
TPieSlice::TPieSlice() : TNamed(), TAttFill(), TAttLine()
{
// This is the default constructor, used to create the standard.
fPie = 0;
fValue = 1;
fRadiusOffset = 0;
fIsActive = kFALSE;
}
//______________________________________________________________________________
TPieSlice::TPieSlice(const char *name, const char *title,
TPie *pie, Double_t val) :
TNamed(name, title), TAttFill(), TAttLine()
{
// This constructor create a slice with a particular value.
fPie = pie;
fValue = val;
fRadiusOffset = 0;
fIsActive = kFALSE;
}
//______________________________________________________________________________
Int_t TPieSlice::DistancetoPrimitive(Int_t /*px*/, Int_t /*py*/)
{
// Eval if the mouse is over the area associated with this slice.
Int_t dist = 9999;
if (fIsActive) {
dist = 0;
fIsActive = kFALSE;
gPad->SetCursor(kHand);
}
return dist;
}
//______________________________________________________________________________
Double_t TPieSlice::GetRadiusOffset()
{
// return the value of the offset in radial direction for this slice.
return fRadiusOffset;
}
//______________________________________________________________________________
Double_t TPieSlice::GetValue()
{
// Return the value of this slice.
return fValue;
}
//______________________________________________________________________________
void TPieSlice::SavePrimitive(ostream &/*out*/, Option_t * /*opts*/)
{
// Do nothing.
}
//______________________________________________________________________________
void TPieSlice::SetRadiusOffset(Double_t val)
{
// Set the radial offset of this slice.
fRadiusOffset = val;
if (fRadiusOffset<.0) fRadiusOffset = .0;
}
//______________________________________________________________________________
void TPieSlice::SetValue(Double_t val)
{
// Set the value for this slice.
// Negative values are changed with its absolute value.
fValue = val;
if (fValue<.0) {
Warning("SetValue","Invalid negative value. Absolute value taken");
fValue *= -1;
}
fPie->MakeSlices(kTRUE);
}
<|endoftext|> |
<commit_before>// MFEM Example 2 - Parallel Version
// PETSc Modification
//
// Compile with: make ex2p
//
// Sample runs:
// mpirun -np 4 ex2p -m ../../data/beam-quad.mesh --petscopts rc_ex2p
//
// Description: This example code solves a simple linear elasticity problem
// describing a multi-material cantilever beam.
//
// Specifically, we approximate the weak form of -div(sigma(u))=0
// where sigma(u)=lambda*div(u)*I+mu*(grad*u+u*grad) is the stress
// tensor corresponding to displacement field u, and lambda and mu
// are the material Lame constants. The boundary conditions are
// u=0 on the fixed part of the boundary with attribute 1, and
// sigma(u).n=f on the remainder with f being a constant pull down
// vector on boundary elements with attribute 2, and zero
// otherwise. The geometry of the domain is assumed to be as
// follows:
//
// +----------+----------+
// boundary --->| material | material |<--- boundary
// attribute 1 | 1 | 2 | attribute 2
// (fixed) +----------+----------+ (pull down)
//
// The example demonstrates the use of high-order and NURBS vector
// finite element spaces with the linear elasticity bilinear form,
// meshes with curved elements, and the definition of piece-wise
// constant and vector coefficient objects. Static condensation is
// also illustrated. The example also shows how to form a linear
// system using a PETSc matrix and solve with a PETSc solver.
//
// We recommend viewing Example 1 before viewing this example.
#include "mfem.hpp"
#include <fstream>
#include <iostream>
#ifndef MFEM_USE_PETSC
#error This example requires that MFEM is built with MFEM_USE_PETSC=YES
#endif
using namespace std;
using namespace mfem;
int main(int argc, char *argv[])
{
// 1. Initialize MPI.
int num_procs, myid;
MPI_Init(&argc, &argv);
MPI_Comm_size(MPI_COMM_WORLD, &num_procs);
MPI_Comm_rank(MPI_COMM_WORLD, &myid);
// 2. Parse command-line options.
const char *mesh_file = "../../data/beam-tri.mesh";
int order = 1;
bool static_cond = false;
bool visualization = 1;
bool amg_elast = 0;
bool use_petsc = true;
const char *petscrc_file = "";
bool use_nonoverlapping = false;
OptionsParser args(argc, argv);
args.AddOption(&mesh_file, "-m", "--mesh",
"Mesh file to use.");
args.AddOption(&order, "-o", "--order",
"Finite element order (polynomial degree).");
args.AddOption(&amg_elast, "-elast", "--amg-for-elasticity", "-sys",
"--amg-for-systems",
"Use the special AMG elasticity solver (GM/LN approaches), "
"or standard AMG for systems (unknown approach).");
args.AddOption(&static_cond, "-sc", "--static-condensation", "-no-sc",
"--no-static-condensation", "Enable static condensation.");
args.AddOption(&visualization, "-vis", "--visualization", "-no-vis",
"--no-visualization",
"Enable or disable GLVis visualization.");
args.AddOption(&use_petsc, "-usepetsc", "--usepetsc", "-no-petsc",
"--no-petsc",
"Use or not PETSc to solve the linear system.");
args.AddOption(&petscrc_file, "-petscopts", "--petscopts",
"PetscOptions file to use.");
args.AddOption(&use_nonoverlapping, "-nonoverlapping", "--nonoverlapping",
"-no-nonoverlapping", "--no-nonoverlapping",
"Use or not the block diagonal PETSc's matrix format "
"for non-overlapping domain decomposition.");
args.Parse();
if (!args.Good())
{
if (myid == 0)
{
args.PrintUsage(cout);
}
MPI_Finalize();
return 1;
}
if (myid == 0)
{
args.PrintOptions(cout);
}
// 2b. We initialize PETSc
if (use_petsc) { MFEMInitializePetsc(NULL,NULL,petscrc_file,NULL); }
// 3. Read the (serial) mesh from the given mesh file on all processors. We
// can handle triangular, quadrilateral, tetrahedral, hexahedral, surface
// and volume meshes with the same code.
Mesh *mesh = new Mesh(mesh_file, 1, 1);
int dim = mesh->Dimension();
if (mesh->attributes.Max() < 2 || mesh->bdr_attributes.Max() < 2)
{
if (myid == 0)
cerr << "\nInput mesh should have at least two materials and "
<< "two boundary attributes! (See schematic in ex2.cpp)\n"
<< endl;
MPI_Finalize();
return 3;
}
// 4. Select the order of the finite element discretization space. For NURBS
// meshes, we increase the order by degree elevation.
if (mesh->NURBSext)
{
mesh->DegreeElevate(order, order);
}
// 5. Refine the serial mesh on all processors to increase the resolution. In
// this example we do 'ref_levels' of uniform refinement. We choose
// 'ref_levels' to be the largest number that gives a final mesh with no
// more than 1,000 elements.
{
int ref_levels =
(int)floor(log(1000./mesh->GetNE())/log(2.)/dim);
for (int l = 0; l < ref_levels; l++)
{
mesh->UniformRefinement();
}
}
// 6. Define a parallel mesh by a partitioning of the serial mesh. Refine
// this mesh further in parallel to increase the resolution. Once the
// parallel mesh is defined, the serial mesh can be deleted.
ParMesh *pmesh = new ParMesh(MPI_COMM_WORLD, *mesh);
delete mesh;
{
int par_ref_levels = 1;
for (int l = 0; l < par_ref_levels; l++)
{
pmesh->UniformRefinement();
}
}
// 7. Define a parallel finite element space on the parallel mesh. Here we
// use vector finite elements, i.e. dim copies of a scalar finite element
// space. We use the ordering by vector dimension (the last argument of
// the FiniteElementSpace constructor) which is expected in the systems
// version of BoomerAMG preconditioner. For NURBS meshes, we use the
// (degree elevated) NURBS space associated with the mesh nodes.
FiniteElementCollection *fec;
ParFiniteElementSpace *fespace;
const bool use_nodal_fespace = pmesh->NURBSext && !amg_elast;
if (use_nodal_fespace)
{
fec = NULL;
fespace = (ParFiniteElementSpace *)pmesh->GetNodes()->FESpace();
}
else
{
fec = new H1_FECollection(order, dim);
fespace = new ParFiniteElementSpace(pmesh, fec, dim, Ordering::byVDIM);
}
HYPRE_Int size = fespace->GlobalTrueVSize();
if (myid == 0)
{
cout << "Number of finite element unknowns: " << size << endl
<< "Assembling: " << flush;
}
// 8. Determine the list of true (i.e. parallel conforming) essential
// boundary dofs. In this example, the boundary conditions are defined by
// marking only boundary attribute 1 from the mesh as essential and
// converting it to a list of true dofs.
Array<int> ess_tdof_list, ess_bdr(pmesh->bdr_attributes.Max());
ess_bdr = 0;
ess_bdr[0] = 1;
fespace->GetEssentialTrueDofs(ess_bdr, ess_tdof_list);
// 9. Set up the parallel linear form b(.) which corresponds to the
// right-hand side of the FEM linear system. In this case, b_i equals the
// boundary integral of f*phi_i where f represents a "pull down" force on
// the Neumann part of the boundary and phi_i are the basis functions in
// the finite element fespace. The force is defined by the object f, which
// is a vector of Coefficient objects. The fact that f is non-zero on
// boundary attribute 2 is indicated by the use of piece-wise constants
// coefficient for its last component.
VectorArrayCoefficient f(dim);
for (int i = 0; i < dim-1; i++)
{
f.Set(i, new ConstantCoefficient(0.0));
}
{
Vector pull_force(pmesh->bdr_attributes.Max());
pull_force = 0.0;
pull_force(1) = -1.0e-2;
f.Set(dim-1, new PWConstCoefficient(pull_force));
}
ParLinearForm *b = new ParLinearForm(fespace);
b->AddBoundaryIntegrator(new VectorBoundaryLFIntegrator(f));
if (myid == 0)
{
cout << "r.h.s. ... " << flush;
}
b->Assemble();
// 10. Define the solution vector x as a parallel finite element grid
// function corresponding to fespace. Initialize x with initial guess of
// zero, which satisfies the boundary conditions.
ParGridFunction x(fespace);
x = 0.0;
// 11. Set up the parallel bilinear form a(.,.) on the finite element space
// corresponding to the linear elasticity integrator with piece-wise
// constants coefficient lambda and mu.
Vector lambda(pmesh->attributes.Max());
lambda = 1.0;
lambda(0) = lambda(1)*50;
PWConstCoefficient lambda_func(lambda);
Vector mu(pmesh->attributes.Max());
mu = 1.0;
mu(0) = mu(1)*50;
PWConstCoefficient mu_func(mu);
ParBilinearForm *a = new ParBilinearForm(fespace);
a->AddDomainIntegrator(new ElasticityIntegrator(lambda_func, mu_func));
// 12. Assemble the parallel bilinear form and the corresponding linear
// system, applying any necessary transformations such as: parallel
// assembly, eliminating boundary conditions, applying conforming
// constraints for non-conforming AMR, static condensation, etc.
if (myid == 0) { cout << "matrix ... " << flush; }
if (static_cond) { a->EnableStaticCondensation(); }
a->Assemble();
Vector B, X;
if (!use_petsc)
{
HypreParMatrix A;
a->FormLinearSystem(ess_tdof_list, x, *b, A, X, B);
if (myid == 0)
{
cout << "done." << endl;
cout << "Size of linear system: " << A.GetGlobalNumRows() << endl;
}
// 13. Define and apply a parallel PCG solver for A X = B with the BoomerAMG
// preconditioner from hypre.
HypreBoomerAMG *amg = new HypreBoomerAMG(A);
if (amg_elast && !a->StaticCondensationIsEnabled())
{
amg->SetElasticityOptions(fespace);
}
else
{
amg->SetSystemsOptions(dim);
}
HyprePCG *pcg = new HyprePCG(A);
pcg->SetTol(1e-8);
pcg->SetMaxIter(500);
pcg->SetPrintLevel(2);
pcg->SetPreconditioner(*amg);
pcg->Mult(B, X);
delete pcg;
delete amg;
}
else
{
// 13b. Use PETSc to solve the linear system.
// Assemble a PETSc matrix, so that PETSc solvers can be used natively.
PetscParMatrix A;
a->SetOperatorType(use_nonoverlapping ?
Operator::PETSC_MATIS : Operator::PETSC_MATAIJ);
a->FormLinearSystem(ess_tdof_list, x, *b, A, X, B);
if (myid == 0)
{
cout << "done." << endl;
cout << "Size of linear system: " << A.M() << endl;
}
// The preconditioner for the PCG solver defined below is specified in the
// PETSc config file, rc_ex2p, since a Krylov solver in PETSc can also
// customize its preconditioner.
PetscPCGSolver *pcg = new PetscPCGSolver(A);
pcg->SetMaxIter(500);
pcg->SetTol(1e-8);
pcg->SetPrintLevel(2);
pcg->Mult(B, X);
delete pcg;
}
// 14. Recover the parallel grid function corresponding to X. This is the
// local finite element solution on each processor.
a->RecoverFEMSolution(X, *b, x);
// 15. For non-NURBS meshes, make the mesh curved based on the finite element
// space. This means that we define the mesh elements through a fespace
// based transformation of the reference element. This allows us to save
// the displaced mesh as a curved mesh when using high-order finite
// element displacement field. We assume that the initial mesh (read from
// the file) is not higher order curved mesh compared to the chosen FE
// space.
if (!use_nodal_fespace)
{
pmesh->SetNodalFESpace(fespace);
}
// 16. Save in parallel the displaced mesh and the inverted solution (which
// gives the backward displacements to the original grid). This output
// can be viewed later using GLVis: "glvis -np <np> -m mesh -g sol".
{
GridFunction *nodes = pmesh->GetNodes();
*nodes += x;
x *= -1;
ostringstream mesh_name, sol_name;
mesh_name << "mesh." << setfill('0') << setw(6) << myid;
sol_name << "sol." << setfill('0') << setw(6) << myid;
ofstream mesh_ofs(mesh_name.str().c_str());
mesh_ofs.precision(8);
pmesh->Print(mesh_ofs);
ofstream sol_ofs(sol_name.str().c_str());
sol_ofs.precision(8);
x.Save(sol_ofs);
}
// 17. Send the above data by socket to a GLVis server. Use the "n" and "b"
// keys in GLVis to visualize the displacements.
if (visualization)
{
char vishost[] = "localhost";
int visport = 19916;
socketstream sol_sock(vishost, visport);
sol_sock << "parallel " << num_procs << " " << myid << "\n";
sol_sock.precision(8);
sol_sock << "solution\n" << *pmesh << x << flush;
}
// 18. Free the used memory.
delete a;
delete b;
if (fec)
{
delete fespace;
delete fec;
}
delete pmesh;
// We finalize PETSc
if (use_petsc) { MFEMFinalizePetsc(); }
MPI_Finalize();
return 0;
}
<commit_msg>PETSc example ex2p: add support for BDDC<commit_after>// MFEM Example 2 - Parallel Version
// PETSc Modification
//
// Compile with: make ex2p
//
// Sample runs:
// mpirun -np 4 ex2p -m ../../data/beam-quad.mesh --petscopts rc_ex2p
//
// Description: This example code solves a simple linear elasticity problem
// describing a multi-material cantilever beam.
//
// Specifically, we approximate the weak form of -div(sigma(u))=0
// where sigma(u)=lambda*div(u)*I+mu*(grad*u+u*grad) is the stress
// tensor corresponding to displacement field u, and lambda and mu
// are the material Lame constants. The boundary conditions are
// u=0 on the fixed part of the boundary with attribute 1, and
// sigma(u).n=f on the remainder with f being a constant pull down
// vector on boundary elements with attribute 2, and zero
// otherwise. The geometry of the domain is assumed to be as
// follows:
//
// +----------+----------+
// boundary --->| material | material |<--- boundary
// attribute 1 | 1 | 2 | attribute 2
// (fixed) +----------+----------+ (pull down)
//
// The example demonstrates the use of high-order and NURBS vector
// finite element spaces with the linear elasticity bilinear form,
// meshes with curved elements, and the definition of piece-wise
// constant and vector coefficient objects. Static condensation is
// also illustrated. The example also shows how to form a linear
// system using a PETSc matrix and solve with a PETSc solver.
//
// We recommend viewing Example 1 before viewing this example.
#include "mfem.hpp"
#include <fstream>
#include <iostream>
#ifndef MFEM_USE_PETSC
#error This example requires that MFEM is built with MFEM_USE_PETSC=YES
#endif
using namespace std;
using namespace mfem;
int main(int argc, char *argv[])
{
// 1. Initialize MPI.
int num_procs, myid;
MPI_Init(&argc, &argv);
MPI_Comm_size(MPI_COMM_WORLD, &num_procs);
MPI_Comm_rank(MPI_COMM_WORLD, &myid);
// 2. Parse command-line options.
const char *mesh_file = "../../data/beam-tri.mesh";
int order = 1;
bool static_cond = false;
bool visualization = 1;
bool amg_elast = 0;
bool use_petsc = true;
const char *petscrc_file = "";
bool use_nonoverlapping = false;
OptionsParser args(argc, argv);
args.AddOption(&mesh_file, "-m", "--mesh",
"Mesh file to use.");
args.AddOption(&order, "-o", "--order",
"Finite element order (polynomial degree).");
args.AddOption(&amg_elast, "-elast", "--amg-for-elasticity", "-sys",
"--amg-for-systems",
"Use the special AMG elasticity solver (GM/LN approaches), "
"or standard AMG for systems (unknown approach).");
args.AddOption(&static_cond, "-sc", "--static-condensation", "-no-sc",
"--no-static-condensation", "Enable static condensation.");
args.AddOption(&visualization, "-vis", "--visualization", "-no-vis",
"--no-visualization",
"Enable or disable GLVis visualization.");
args.AddOption(&use_petsc, "-usepetsc", "--usepetsc", "-no-petsc",
"--no-petsc",
"Use or not PETSc to solve the linear system.");
args.AddOption(&petscrc_file, "-petscopts", "--petscopts",
"PetscOptions file to use.");
args.AddOption(&use_nonoverlapping, "-nonoverlapping", "--nonoverlapping",
"-no-nonoverlapping", "--no-nonoverlapping",
"Use or not the block diagonal PETSc's matrix format "
"for non-overlapping domain decomposition.");
args.Parse();
if (!args.Good())
{
if (myid == 0)
{
args.PrintUsage(cout);
}
MPI_Finalize();
return 1;
}
if (myid == 0)
{
args.PrintOptions(cout);
}
// 2b. We initialize PETSc
if (use_petsc) { MFEMInitializePetsc(NULL,NULL,petscrc_file,NULL); }
// 3. Read the (serial) mesh from the given mesh file on all processors. We
// can handle triangular, quadrilateral, tetrahedral, hexahedral, surface
// and volume meshes with the same code.
Mesh *mesh = new Mesh(mesh_file, 1, 1);
int dim = mesh->Dimension();
if (mesh->attributes.Max() < 2 || mesh->bdr_attributes.Max() < 2)
{
if (myid == 0)
cerr << "\nInput mesh should have at least two materials and "
<< "two boundary attributes! (See schematic in ex2.cpp)\n"
<< endl;
MPI_Finalize();
return 3;
}
// 4. Select the order of the finite element discretization space. For NURBS
// meshes, we increase the order by degree elevation.
if (mesh->NURBSext)
{
mesh->DegreeElevate(order, order);
}
// 5. Refine the serial mesh on all processors to increase the resolution. In
// this example we do 'ref_levels' of uniform refinement. We choose
// 'ref_levels' to be the largest number that gives a final mesh with no
// more than 1,000 elements.
{
int ref_levels =
(int)floor(log(1000./mesh->GetNE())/log(2.)/dim);
for (int l = 0; l < ref_levels; l++)
{
mesh->UniformRefinement();
}
}
// 6. Define a parallel mesh by a partitioning of the serial mesh. Refine
// this mesh further in parallel to increase the resolution. Once the
// parallel mesh is defined, the serial mesh can be deleted.
ParMesh *pmesh = new ParMesh(MPI_COMM_WORLD, *mesh);
delete mesh;
{
int par_ref_levels = 1;
for (int l = 0; l < par_ref_levels; l++)
{
pmesh->UniformRefinement();
}
}
// 7. Define a parallel finite element space on the parallel mesh. Here we
// use vector finite elements, i.e. dim copies of a scalar finite element
// space. We use the ordering by vector dimension (the last argument of
// the FiniteElementSpace constructor) which is expected in the systems
// version of BoomerAMG preconditioner. For NURBS meshes, we use the
// (degree elevated) NURBS space associated with the mesh nodes.
FiniteElementCollection *fec;
ParFiniteElementSpace *fespace;
const bool use_nodal_fespace = pmesh->NURBSext && !amg_elast;
if (use_nodal_fespace)
{
fec = NULL;
fespace = (ParFiniteElementSpace *)pmesh->GetNodes()->FESpace();
}
else
{
fec = new H1_FECollection(order, dim);
fespace = new ParFiniteElementSpace(pmesh, fec, dim, Ordering::byVDIM);
}
HYPRE_Int size = fespace->GlobalTrueVSize();
if (myid == 0)
{
cout << "Number of finite element unknowns: " << size << endl
<< "Assembling: " << flush;
}
// 8. Determine the list of true (i.e. parallel conforming) essential
// boundary dofs. In this example, the boundary conditions are defined by
// marking only boundary attribute 1 from the mesh as essential and
// converting it to a list of true dofs.
Array<int> ess_tdof_list, ess_bdr(pmesh->bdr_attributes.Max());
ess_bdr = 0;
ess_bdr[0] = 1;
fespace->GetEssentialTrueDofs(ess_bdr, ess_tdof_list);
// 9. Set up the parallel linear form b(.) which corresponds to the
// right-hand side of the FEM linear system. In this case, b_i equals the
// boundary integral of f*phi_i where f represents a "pull down" force on
// the Neumann part of the boundary and phi_i are the basis functions in
// the finite element fespace. The force is defined by the object f, which
// is a vector of Coefficient objects. The fact that f is non-zero on
// boundary attribute 2 is indicated by the use of piece-wise constants
// coefficient for its last component.
VectorArrayCoefficient f(dim);
for (int i = 0; i < dim-1; i++)
{
f.Set(i, new ConstantCoefficient(0.0));
}
{
Vector pull_force(pmesh->bdr_attributes.Max());
pull_force = 0.0;
pull_force(1) = -1.0e-2;
f.Set(dim-1, new PWConstCoefficient(pull_force));
}
ParLinearForm *b = new ParLinearForm(fespace);
b->AddBoundaryIntegrator(new VectorBoundaryLFIntegrator(f));
if (myid == 0)
{
cout << "r.h.s. ... " << flush;
}
b->Assemble();
// 10. Define the solution vector x as a parallel finite element grid
// function corresponding to fespace. Initialize x with initial guess of
// zero, which satisfies the boundary conditions.
ParGridFunction x(fespace);
x = 0.0;
// 11. Set up the parallel bilinear form a(.,.) on the finite element space
// corresponding to the linear elasticity integrator with piece-wise
// constants coefficient lambda and mu.
Vector lambda(pmesh->attributes.Max());
lambda = 1.0;
lambda(0) = lambda(1)*50;
PWConstCoefficient lambda_func(lambda);
Vector mu(pmesh->attributes.Max());
mu = 1.0;
mu(0) = mu(1)*50;
PWConstCoefficient mu_func(mu);
ParBilinearForm *a = new ParBilinearForm(fespace);
a->AddDomainIntegrator(new ElasticityIntegrator(lambda_func, mu_func));
// 12. Assemble the parallel bilinear form and the corresponding linear
// system, applying any necessary transformations such as: parallel
// assembly, eliminating boundary conditions, applying conforming
// constraints for non-conforming AMR, static condensation, etc.
if (myid == 0) { cout << "matrix ... " << flush; }
if (static_cond) { a->EnableStaticCondensation(); }
a->Assemble();
Vector B, X;
if (!use_petsc)
{
HypreParMatrix A;
a->FormLinearSystem(ess_tdof_list, x, *b, A, X, B);
if (myid == 0)
{
cout << "done." << endl;
cout << "Size of linear system: " << A.GetGlobalNumRows() << endl;
}
// 13. Define and apply a parallel PCG solver for A X = B with the BoomerAMG
// preconditioner from hypre.
HypreBoomerAMG *amg = new HypreBoomerAMG(A);
if (amg_elast && !a->StaticCondensationIsEnabled())
{
amg->SetElasticityOptions(fespace);
}
else
{
amg->SetSystemsOptions(dim);
}
HyprePCG *pcg = new HyprePCG(A);
pcg->SetTol(1e-8);
pcg->SetMaxIter(500);
pcg->SetPrintLevel(2);
pcg->SetPreconditioner(*amg);
pcg->Mult(B, X);
delete pcg;
delete amg;
}
else
{
// 13b. Use PETSc to solve the linear system.
// Assemble a PETSc matrix, so that PETSc solvers can be used natively.
PetscParMatrix A;
a->SetOperatorType(use_nonoverlapping ?
Operator::PETSC_MATIS : Operator::PETSC_MATAIJ);
a->FormLinearSystem(ess_tdof_list, x, *b, A, X, B);
if (myid == 0)
{
cout << "done." << endl;
cout << "Size of linear system: " << A.M() << endl;
}
PetscPCGSolver *pcg = new PetscPCGSolver(A);
// The preconditioner for the PCG solver defined below is specified in the
// PETSc config file, rc_ex2p, since a Krylov solver in PETSc can also
// customize its preconditioner.
PetscPreconditioner *prec = NULL;
if (use_nonoverlapping)
{
// Auxiliary class for BDDC customization
PetscBDDCSolverParams opts;
// Inform the solver about the finite element space
opts.SetSpace(fespace);
// Inform the solver about essential dofs
opts.SetEssBdrDofs(&ess_tdof_list);
// Create a BDDC solver with parameters
prec = new PetscBDDCSolver(A,opts);
pcg->SetPreconditioner(*prec);
}
pcg->SetMaxIter(500);
pcg->SetTol(1e-8);
pcg->SetPrintLevel(2);
pcg->Mult(B, X);
delete pcg;
delete prec;
}
// 14. Recover the parallel grid function corresponding to X. This is the
// local finite element solution on each processor.
a->RecoverFEMSolution(X, *b, x);
// 15. For non-NURBS meshes, make the mesh curved based on the finite element
// space. This means that we define the mesh elements through a fespace
// based transformation of the reference element. This allows us to save
// the displaced mesh as a curved mesh when using high-order finite
// element displacement field. We assume that the initial mesh (read from
// the file) is not higher order curved mesh compared to the chosen FE
// space.
if (!use_nodal_fespace)
{
pmesh->SetNodalFESpace(fespace);
}
// 16. Save in parallel the displaced mesh and the inverted solution (which
// gives the backward displacements to the original grid). This output
// can be viewed later using GLVis: "glvis -np <np> -m mesh -g sol".
{
GridFunction *nodes = pmesh->GetNodes();
*nodes += x;
x *= -1;
ostringstream mesh_name, sol_name;
mesh_name << "mesh." << setfill('0') << setw(6) << myid;
sol_name << "sol." << setfill('0') << setw(6) << myid;
ofstream mesh_ofs(mesh_name.str().c_str());
mesh_ofs.precision(8);
pmesh->Print(mesh_ofs);
ofstream sol_ofs(sol_name.str().c_str());
sol_ofs.precision(8);
x.Save(sol_ofs);
}
// 17. Send the above data by socket to a GLVis server. Use the "n" and "b"
// keys in GLVis to visualize the displacements.
if (visualization)
{
char vishost[] = "localhost";
int visport = 19916;
socketstream sol_sock(vishost, visport);
sol_sock << "parallel " << num_procs << " " << myid << "\n";
sol_sock.precision(8);
sol_sock << "solution\n" << *pmesh << x << flush;
}
// 18. Free the used memory.
delete a;
delete b;
if (fec)
{
delete fespace;
delete fec;
}
delete pmesh;
// We finalize PETSc
if (use_petsc) { MFEMFinalizePetsc(); }
MPI_Finalize();
return 0;
}
<|endoftext|> |
<commit_before><commit_msg>[drape] remove extra copy in gpu_mem_tracker<commit_after><|endoftext|> |
<commit_before>
#include "Main.h"
int main(int argc, char **argv)
{
//Create window, do basic setup
if (SDL_Init(SDL_INIT_EVERYTHING) != 0)
quit("SDL_Init", 1);
SDL_Window *win = SDL_CreateWindow("NPC-Game", 10, 30, SCREEN_WIDTH, SCREEN_HEIGHT, SDL_WINDOW_SHOWN);
if (win == nullptr)
quit("SDL_CreateWindow", 2);
SDL_Renderer *ren = SDL_CreateRenderer(win, -1, SDL_RENDERER_ACCELERATED | SDL_RENDERER_PRESENTVSYNC);
if (ren == nullptr)
quit("SDL_CreateRenderer", 3);
if (TTF_Init() != 0)
quit("TTF_Init", 4);
TTF_Font *font = TTF_OpenFont("ClearSans-Light.ttf", 20);
if (font == nullptr)
quit("TTF_OpenFont", 5);
//SDL vars
SDL_Event e;
bool quit = false;
//backend vars
Terr* terr = new Terr("");
Party* party = new Party(ren);
Sprite* npc = new Sprite(ren, "npc.png");
vector<Button *> buttons;
npc->setType("test");
gameState state = TITLE;
//spritesheets
SDL_Texture *tiles = loadTexture("tiles.png", ren);
loadKeys();
while (!quit)
while (SDL_PollEvent(&e))
quit = mainLoop(ren, e, font, tiles, terr, party, npc, state, buttons);
SDL_DestroyTexture(tiles);
SDL_DestroyRenderer(ren);
SDL_DestroyWindow(win);
TTF_CloseFont(font);
delete terr;
delete party;
delete npc;
TTF_Quit();
IMG_Quit();
SDL_Quit();
return 0;
}//int main(int argc, char **argv)
bool loopAnyState(SDL_Renderer *ren, SDL_Event &e, Terr *terr, Party* party, Sprite *npc, gameState &state)
{
switch (e.type)
{
case SDL_KEYDOWN:
if (e.key.keysym == stateBattle)
state = BATTLE; //debug command startbattle
if (e.key.keysym == stateMap1)
{
delete terr;
terr = new Terr("map1.txt");
state = MAP;
party->getSprite()->setTile(terr->getTile(4, 3));
npc->setTile(terr->getTile(5, 4));
}//debug command map1
if (e.key.keysym == stateMap2)
{
delete terr;
terr = new Terr("map2.txt");
state = MAP;
party->getSprite()->setTile(terr->getTile(1, 1));
}//debug command map2
if (e.key.keysym == stateRebind)
state = REBIND; //debug command go to rebind menu
if (e.key.keysym == stateQuit)
return true;
break;
default:
break;
}//switch (event type)
return false;
}//bool loopAnyState(SDL_Renderer *ren, SDL_Event &e, Terr *terr, Party* party, Sprite *npc, gameState &state)
bool loopBattle(SDL_Event &e)
{
switch (e.type)
{
default:
break;
}
return false;
}//bool loopBattle(SDL_Event &e)
bool loopMap(SDL_Renderer *ren, SDL_Texture* tiles, Terr* terr, SDL_Event &e, Party* party)
{
drawMap(ren, tiles, terr, party->getSprite());
switch (e.type)
{
case SDL_KEYDOWN:
if (e.key.keysym == dirUp)
party->getSprite()->move(NORTH);
if (e.key.keysym == dirLeft)
party->getSprite()->move(WEST);
if (e.key.keysym == dirDown)
party->getSprite()->move(SOUTH);
if (e.key.keysym == dirRight)
party->getSprite()->move(EAST);
if (e.key.keysym == interact)
party->getSprite()->interact();
break;
default:
break;
}
return false;
}//bool loopMap(SDL_Event &e, Party* party)
bool loopRebind(SDL_Renderer *ren, SDL_Event &e, TTF_Font *font, gameState &state)
{
drawRebind(ren, font);
switch (e.type)
{
default:
break;
}
state = TITLE;
return false;
}//bool loopRebind(SDL_Renderer *ren, SDL_Event &e, TTF_Font *font, gameState &state)
bool loopTitle(SDL_Renderer *ren, SDL_Event &e, TTF_Font *font, Terr *terr, gameState &state, Party *party, Sprite *npc, vector<Button *> buttons)
{
Button *toGame = new Button(ren, "button.png", SCREEN_WIDTH / 2 - 120, 300, 240, 100, font, "To Game");
drawTitle(ren, toGame);
switch (e.type)
{
case SDL_KEYDOWN:
//use arrow keys to select button; enter/interact to depress button
break;
case SDL_MOUSEBUTTONDOWN:
if (toGame->buttonClick(e.button))
{
delete terr;
terr = new Terr("map1.txt");
state = MAP;
party->getSprite()->setTile(terr->getTile(4, 3));
npc->setTile(terr->getTile(5, 4));
SDL_Event* wait = new SDL_Event();
SDL_PushEvent(wait); //push an empty event to cause an immediate state update
}
//click on button to depress button
break;
case SDL_MOUSEBUTTONUP:
//actually follow through on buttonclick iff buttonup is also in button area
break;
case SDL_MOUSEMOTION:
//mouseover button to select button
break;
default:
break;
}
return false;
}//bool loopTitle(SDL_Renderer *ren, SDL_Event &e, TTF_Font *font, Terr *terr, gameState &state, Party *party, Sprite *npc)
bool mainLoop(SDL_Renderer *ren, SDL_Event &e, TTF_Font *font, SDL_Texture *tiles, Terr *terr, Party* party, Sprite *npc, gameState &state, vector<Button *> buttons)
{
bool quit = false;
quit = loopAnyState(ren, e, terr, party, npc, state);
if (quit)
return true;
switch (state)
{
case BATTLE:
quit = loopBattle(e);
break;
case MAP:
quit = loopMap(ren, tiles, terr, e, party);
break;
case REBIND:
quit = loopRebind(ren, e, font, state);
break;
case TITLE:
quit = loopTitle(ren, e, font, terr, state, party, npc, buttons);
break;
default:
break;
}//switch (state)
return quit;
}//bool mainLoop(SDL_Renderer *ren, SDL_Event &e, TTF_Font *font, SDL_Texture *tiles, Terr *terr, Party* party, Sprite *npc, gameState &state)
<commit_msg>Further move to Resources<commit_after>
#include "Main.h"
int main(int argc, char **argv)
{
//Create window, do basic setup
if (SDL_Init(SDL_INIT_EVERYTHING) != 0)
quit("SDL_Init", 1);
SDL_Window *win = SDL_CreateWindow("NPC-Game", 10, 30, SCREEN_WIDTH, SCREEN_HEIGHT, SDL_WINDOW_SHOWN);
if (win == nullptr)
quit("SDL_CreateWindow", 2);
SDL_Renderer *ren = SDL_CreateRenderer(win, -1, SDL_RENDERER_ACCELERATED | SDL_RENDERER_PRESENTVSYNC);
if (ren == nullptr)
quit("SDL_CreateRenderer", 3);
if (TTF_Init() != 0)
quit("TTF_Init", 4);
TTF_Font *font = TTF_OpenFont("resources/ClearSans-Light.ttf", 20);
if (font == nullptr)
quit("TTF_OpenFont", 5);
//SDL vars
SDL_Event e;
bool quit = false;
//backend vars
Terr* terr = new Terr("");
Party* party = new Party(ren);
Sprite* npc = new Sprite(ren, "npc.png");
vector<Button *> buttons;
npc->setType("test");
gameState state = TITLE;
//spritesheets
SDL_Texture *tiles = loadTexture("tiles.png", ren);
loadKeys();
while (!quit)
while (SDL_PollEvent(&e))
quit = mainLoop(ren, e, font, tiles, terr, party, npc, state, buttons);
SDL_DestroyTexture(tiles);
SDL_DestroyRenderer(ren);
SDL_DestroyWindow(win);
TTF_CloseFont(font);
delete terr;
delete party;
delete npc;
TTF_Quit();
IMG_Quit();
SDL_Quit();
return 0;
}//int main(int argc, char **argv)
bool loopAnyState(SDL_Renderer *ren, SDL_Event &e, Terr *terr, Party* party, Sprite *npc, gameState &state)
{
switch (e.type)
{
case SDL_KEYDOWN:
if (e.key.keysym == stateBattle)
state = BATTLE; //debug command startbattle
if (e.key.keysym == stateMap1)
{
delete terr;
terr = new Terr("map1.txt");
state = MAP;
party->getSprite()->setTile(terr->getTile(4, 3));
npc->setTile(terr->getTile(5, 4));
}//debug command map1
if (e.key.keysym == stateMap2)
{
delete terr;
terr = new Terr("map2.txt");
state = MAP;
party->getSprite()->setTile(terr->getTile(1, 1));
}//debug command map2
if (e.key.keysym == stateRebind)
state = REBIND; //debug command go to rebind menu
if (e.key.keysym == stateQuit)
return true;
break;
default:
break;
}//switch (event type)
return false;
}//bool loopAnyState(SDL_Renderer *ren, SDL_Event &e, Terr *terr, Party* party, Sprite *npc, gameState &state)
bool loopBattle(SDL_Event &e)
{
switch (e.type)
{
default:
break;
}
return false;
}//bool loopBattle(SDL_Event &e)
bool loopMap(SDL_Renderer *ren, SDL_Texture* tiles, Terr* terr, SDL_Event &e, Party* party)
{
drawMap(ren, tiles, terr, party->getSprite());
switch (e.type)
{
case SDL_KEYDOWN:
if (e.key.keysym == dirUp)
party->getSprite()->move(NORTH);
if (e.key.keysym == dirLeft)
party->getSprite()->move(WEST);
if (e.key.keysym == dirDown)
party->getSprite()->move(SOUTH);
if (e.key.keysym == dirRight)
party->getSprite()->move(EAST);
if (e.key.keysym == interact)
party->getSprite()->interact();
break;
default:
break;
}
return false;
}//bool loopMap(SDL_Event &e, Party* party)
bool loopRebind(SDL_Renderer *ren, SDL_Event &e, TTF_Font *font, gameState &state)
{
drawRebind(ren, font);
switch (e.type)
{
default:
break;
}
state = TITLE;
return false;
}//bool loopRebind(SDL_Renderer *ren, SDL_Event &e, TTF_Font *font, gameState &state)
bool loopTitle(SDL_Renderer *ren, SDL_Event &e, TTF_Font *font, Terr *terr, gameState &state, Party *party, Sprite *npc, vector<Button *> buttons)
{
Button *toGame = new Button(ren, "button.png", SCREEN_WIDTH / 2 - 120, 300, 240, 100, font, "To Game");
drawTitle(ren, toGame);
switch (e.type)
{
case SDL_KEYDOWN:
//use arrow keys to select button; enter/interact to depress button
break;
case SDL_MOUSEBUTTONDOWN:
if (toGame->buttonClick(e.button))
{
delete terr;
terr = new Terr("map1.txt");
state = MAP;
party->getSprite()->setTile(terr->getTile(4, 3));
npc->setTile(terr->getTile(5, 4));
SDL_Event* wait = new SDL_Event();
SDL_PushEvent(wait); //push an empty event to cause an immediate state update
}
//click on button to depress button
break;
case SDL_MOUSEBUTTONUP:
//actually follow through on buttonclick iff buttonup is also in button area
break;
case SDL_MOUSEMOTION:
//mouseover button to select button
break;
default:
break;
}
return false;
}//bool loopTitle(SDL_Renderer *ren, SDL_Event &e, TTF_Font *font, Terr *terr, gameState &state, Party *party, Sprite *npc)
bool mainLoop(SDL_Renderer *ren, SDL_Event &e, TTF_Font *font, SDL_Texture *tiles, Terr *terr, Party* party, Sprite *npc, gameState &state, vector<Button *> buttons)
{
bool quit = false;
quit = loopAnyState(ren, e, terr, party, npc, state);
if (quit)
return true;
switch (state)
{
case BATTLE:
quit = loopBattle(e);
break;
case MAP:
quit = loopMap(ren, tiles, terr, e, party);
break;
case REBIND:
quit = loopRebind(ren, e, font, state);
break;
case TITLE:
quit = loopTitle(ren, e, font, terr, state, party, npc, buttons);
break;
default:
break;
}//switch (state)
return quit;
}//bool mainLoop(SDL_Renderer *ren, SDL_Event &e, TTF_Font *font, SDL_Texture *tiles, Terr *terr, Party* party, Sprite *npc, gameState &state)
<|endoftext|> |
<commit_before>/*
kopeteaway.cpp - Kopete Away
Copyright (c) 2002 by Hendrik vom Lehn <hvl@linux-4-ever.de>
Copyright (c) 2003 Olivier Goffart <ogoffart@tiscalinet.be>
Kopete (c) 2002-2003 by the Kopete developers <kopete-devel@kde.org>
*************************************************************************
* *
* 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 of the License, or (at your option) any later version. *
* *
*************************************************************************
*/
#ifdef HAVE_CONFIG_H
#include <config.h>
#endif
#include "kopeteaway.h"
#include "kopeteaccountmanager.h"
#include "kopeteaccount.h"
#include "kopeteonlinestatus.h"
#include "kopetecontact.h"
#include "kopeteprefs.h"
#include <kconfig.h>
#include <qtimer.h>
#include <kapplication.h>
#include <klocale.h>
#include <kglobal.h>
#include <kdebug.h>
#include <ksettings/dispatcher.h>
#ifdef Q_WS_X11
#include <X11/Xlib.h>
#include <X11/Xatom.h>
#include <X11/Xresource.h>
// The following include is to make --enable-final work
#include <X11/Xutil.h>
#ifdef HAVE_XSCREENSAVER
#define HasScreenSaver
#include <X11/extensions/scrnsaver.h>
#endif
#endif // Q_WS_X11
// As this is an untested X extension we better leave it off
#undef HAVE_XIDLE
#undef HasXidle
struct KopeteAwayPrivate
{
QString awayMessage;
bool globalAway;
QStringList awayMessageList;
QTime idleTime;
QTimer *timer;
bool autoaway;
bool goAvailable;
int awayTimeout;
bool useAutoAway;
QPtrList<Kopete::Account> autoAwayAccounts;
int mouse_x;
int mouse_y;
unsigned int mouse_mask;
#ifdef Q_WS_X11
Window root; /* root window the pointer is on */
Screen* screen; /* screen the pointer is on */
Time xIdleTime;
#endif
bool useXidle;
bool useMit;
};
Kopete::Away *Kopete::Away::instance = 0L;
Kopete::Away::Away() : QObject( kapp , "Kopete::Away")
{
int dummy = 0;
dummy = dummy; // shut up
d = new KopeteAwayPrivate;
// Set up the away messages
d->awayMessage = QString::null;
d->globalAway = false;
d->autoaway = false;
d->useAutoAway = true;
// Empty the list
d->awayMessageList.clear();
// set the XAutoLock info
#ifdef Q_WS_X11
Display *dsp = qt_xdisplay();
#endif
d->mouse_x = d->mouse_y=0;
d->mouse_mask = 0;
#ifdef Q_WS_X11
d->root = DefaultRootWindow (dsp);
d->screen = ScreenOfDisplay (dsp, DefaultScreen (dsp));
#endif
d->useXidle = false;
d->useMit = false;
#ifdef HasXidle
d->useXidle = XidleQueryExtension(qt_xdisplay(), &dummy, &dummy);
#endif
#ifdef HasScreenSaver
if(!d->useXidle)
d->useMit = XScreenSaverQueryExtension(qt_xdisplay(), &dummy, &dummy);
#endif
#ifdef Q_WS_X11
d->xIdleTime = 0;
#endif
if (d->useXidle)
kdDebug(14010) << "using X11 Xidle extension" << endl;
if(d->useMit)
kdDebug(14010) << "using X11 MIT Screensaver extension" << endl;
load();
KSettings::Dispatcher::self()->registerInstance( KGlobal::instance(), this, SLOT( load() ) );
// Set up the config object
KConfig *config = KGlobal::config();
/* Load the saved away messages */
config->setGroup("Away Messages");
/*
* Old config format
*/
if(config->hasKey("Titles"))
{
QStringList titles = config->readListEntry("Titles"); // Get the titles
for(QStringList::iterator i = titles.begin(); i != titles.end(); ++i)
{
d->awayMessageList.append( config->readEntry(*i) ); // And add it to the list
}
/* Save this list to disk */
save();
}
else if(config->hasKey("Messages"))
{
d->awayMessageList = config->readListEntry("Messages");
}
else
{
d->awayMessageList.append( i18n( "Sorry, I am busy right now" ) );
d->awayMessageList.append( i18n( "I am gone right now, but I will be back later" ) );
/* Save this list to disk */
save();
}
// init the timer
d->timer = new QTimer(this, "AwayTimer");
connect(d->timer, SIGNAL(timeout()), this, SLOT(slotTimerTimeout()));
d->timer->start(4000);
//init the time and other
setActivity();
}
Kopete::Away::~Away()
{
delete d;
}
QString Kopete::Away::message()
{
return getInstance()->d->awayMessage;
}
void Kopete::Away::setGlobalAwayMessage(const QString &message)
{
if( !message.isEmpty() )
{
kdDebug(14010) << k_funcinfo <<
"Setting global away message: " << message << endl;
d->awayMessage = message;
}
}
Kopete::Away *Kopete::Away::getInstance()
{
if (!instance)
instance = new Kopete::Away;
return instance;
}
bool Kopete::Away::globalAway()
{
return getInstance()->d->globalAway;
}
void Kopete::Away::setGlobalAway(bool status)
{
getInstance()->d->globalAway = status;
}
void Kopete::Away::save()
{
KConfig *config = KGlobal::config();
/* Set the away message settings in the Away Messages config group */
config->setGroup("Away Messages");
config->writeEntry("Messages", d->awayMessageList);
config->sync();
emit( messagesChanged() );
}
void Kopete::Away::load()
{
KConfig *config = KGlobal::config();
config->setGroup("AutoAway");
d->awayTimeout=config->readNumEntry("Timeout", 600);
d->goAvailable=config->readBoolEntry("GoAvailable", true);
d->useAutoAway=config->readBoolEntry("UseAutoAway", true);
}
QStringList Kopete::Away::getMessages()
{
return d->awayMessageList;
}
QString Kopete::Away::getMessage( uint messageNumber )
{
QStringList::iterator it = d->awayMessageList.at( messageNumber );
if( it != d->awayMessageList.end() )
{
QString str = *it;
d->awayMessageList.prepend( str );
d->awayMessageList.remove( it );
save();
return str;
}
else
{
return QString::null;
}
}
void Kopete::Away::addMessage(const QString &message)
{
d->awayMessageList.prepend( message );
if( (int)d->awayMessageList.count() > KopetePrefs::prefs()->rememberedMessages() )
d->awayMessageList.pop_back();
save();
}
long int Kopete::Away::idleTime()
{
//FIXME: the time is reset to zero if more than 24 hours are elapsed
// we can imagine someone who leave his PC for several weeks
return (d->idleTime.elapsed() / 1000);
}
void Kopete::Away::slotTimerTimeout()
{
// Copyright (c) 1999 Martin R. Jones <mjones@kde.org>
//
// KDE screensaver engine
//
// This module is a heavily modified xautolock.
// In fact as of KDE 2.0 this code is practically unrecognisable as xautolock.
#ifdef Q_WS_X11
Display *dsp = qt_xdisplay();
Window dummy_w;
int dummy_c;
unsigned int mask; /* modifier mask */
int root_x;
int root_y;
/*
* Find out whether the pointer has moved. Using XQueryPointer for this
* is gross, but it also is the only way never to mess up propagation
* of pointer events.
*
* Remark : Unlike XNextEvent(), XPending () doesn't notice if the
* connection to the server is lost. For this reason, earlier
* versions of xautolock periodically called XNoOp (). But
* why not let XQueryPointer () do the job for us, since
* we now call that periodically anyway?
*/
if (!XQueryPointer (dsp, d->root, &(d->root), &dummy_w, &root_x, &root_y,
&dummy_c, &dummy_c, &mask))
{
/*
* Pointer has moved to another screen, so let's find out which one.
*/
for (int i = 0; i < ScreenCount(dsp); i++)
{
if (d->root == RootWindow(dsp, i))
{
d->screen = ScreenOfDisplay (dsp, i);
break;
}
}
}
#endif
// =================================================================================
#ifdef Q_WS_X11
Time xIdleTime = 0; // millisecs since last input event
#ifdef HasXidle
if (d->useXidle)
{
XGetIdleTime(dsp, &xIdleTime);
}
else
#endif /* HasXIdle */
{
#ifdef HasScreenSaver
if(d->useMit)
{
static XScreenSaverInfo* mitInfo = 0;
if (!mitInfo) mitInfo = XScreenSaverAllocInfo();
XScreenSaverQueryInfo (dsp, d->root, mitInfo);
xIdleTime = mitInfo->idle;
}
#endif /* HasScreenSaver */
}
// =================================================================================
if (root_x != d->mouse_x || root_y != d->mouse_y || mask != d->mouse_mask || xIdleTime < d->xIdleTime+2000)
{
if(d->mouse_x!=-1) //we just gone autoaway, not activity this time
setActivity();
d->mouse_x = root_x;
d->mouse_y = root_y;
d->mouse_mask = mask;
d->xIdleTime = xIdleTime;
}
#endif // Q_WS_X11
// =================================================================================
if(!d->autoaway && d->useAutoAway && idleTime() > d->awayTimeout)
{
setAutoAway();
}
}
void Kopete::Away::setActivity()
{
// kdDebug(14010) << k_funcinfo << "Found activity on desktop, resetting away timer" << endl;
d->idleTime.start();
if(d->autoaway)
{
d->autoaway = false;
emit activity();
if (d->goAvailable)
{
d->autoAwayAccounts.setAutoDelete(false);
for(Kopete::Account *i=d->autoAwayAccounts.first() ; i; i=d->autoAwayAccounts.current() )
{
if(i->isConnected() && i->isAway()) {
i->setAway(false);
}
// remove() makes the next entry in the list the current one,
// that's why we use current() above
d->autoAwayAccounts.remove();
}
}
}
}
void Kopete::Away::setAutoAway()
{
d->mouse_x=-1; //do not go availiable automaticaly after
// kdDebug(14010) << k_funcinfo << "Going AutoAway!" << endl;
d->autoaway = true;
// Set all accounts that are not away already to away.
// We remember them so later we only set the accounts to
// available that we set to away (and not the user).
QPtrList<Kopete::Account> accounts = Kopete::AccountManager::self()->accounts();
for(Kopete::Account *i=accounts.first() ; i; i=accounts.next() )
{
if(i->myself()->onlineStatus().status() == Kopete::OnlineStatus::Online)
{
d->autoAwayAccounts.append(i);
i->setAway( true, getInstance()->d->awayMessage);
}
}
}
#include "kopeteaway.moc"
// vim: set et ts=4 sts=4 sw=4:
<commit_msg>Fix Bug 97857: away messages aren't saved between sessions BUG: 97857<commit_after>/*
kopeteaway.cpp - Kopete Away
Copyright (c) 2002 by Hendrik vom Lehn <hvl@linux-4-ever.de>
Copyright (c) 2003 Olivier Goffart <ogoffart@tiscalinet.be>
Kopete (c) 2002-2003 by the Kopete developers <kopete-devel@kde.org>
*************************************************************************
* *
* 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 of the License, or (at your option) any later version. *
* *
*************************************************************************
*/
#ifdef HAVE_CONFIG_H
#include <config.h>
#endif
#include "kopeteaway.h"
#include "kopeteaccountmanager.h"
#include "kopeteaccount.h"
#include "kopeteonlinestatus.h"
#include "kopetecontact.h"
#include "kopeteprefs.h"
#include <kconfig.h>
#include <qtimer.h>
#include <kapplication.h>
#include <klocale.h>
#include <kglobal.h>
#include <kdebug.h>
#include <ksettings/dispatcher.h>
#ifdef Q_WS_X11
#include <X11/Xlib.h>
#include <X11/Xatom.h>
#include <X11/Xresource.h>
// The following include is to make --enable-final work
#include <X11/Xutil.h>
#ifdef HAVE_XSCREENSAVER
#define HasScreenSaver
#include <X11/extensions/scrnsaver.h>
#endif
#endif // Q_WS_X11
// As this is an untested X extension we better leave it off
#undef HAVE_XIDLE
#undef HasXidle
struct KopeteAwayPrivate
{
QString awayMessage;
bool globalAway;
QStringList awayMessageList;
QTime idleTime;
QTimer *timer;
bool autoaway;
bool goAvailable;
int awayTimeout;
bool useAutoAway;
QPtrList<Kopete::Account> autoAwayAccounts;
int mouse_x;
int mouse_y;
unsigned int mouse_mask;
#ifdef Q_WS_X11
Window root; /* root window the pointer is on */
Screen* screen; /* screen the pointer is on */
Time xIdleTime;
#endif
bool useXidle;
bool useMit;
};
Kopete::Away *Kopete::Away::instance = 0L;
Kopete::Away::Away() : QObject( kapp , "Kopete::Away")
{
int dummy = 0;
dummy = dummy; // shut up
d = new KopeteAwayPrivate;
// Set up the away messages
d->awayMessage = QString::null;
d->globalAway = false;
d->autoaway = false;
d->useAutoAway = true;
// Empty the list
d->awayMessageList.clear();
// set the XAutoLock info
#ifdef Q_WS_X11
Display *dsp = qt_xdisplay();
#endif
d->mouse_x = d->mouse_y=0;
d->mouse_mask = 0;
#ifdef Q_WS_X11
d->root = DefaultRootWindow (dsp);
d->screen = ScreenOfDisplay (dsp, DefaultScreen (dsp));
#endif
d->useXidle = false;
d->useMit = false;
#ifdef HasXidle
d->useXidle = XidleQueryExtension(qt_xdisplay(), &dummy, &dummy);
#endif
#ifdef HasScreenSaver
if(!d->useXidle)
d->useMit = XScreenSaverQueryExtension(qt_xdisplay(), &dummy, &dummy);
#endif
#ifdef Q_WS_X11
d->xIdleTime = 0;
#endif
if (d->useXidle)
kdDebug(14010) << "using X11 Xidle extension" << endl;
if(d->useMit)
kdDebug(14010) << "using X11 MIT Screensaver extension" << endl;
load();
KSettings::Dispatcher::self()->registerInstance( KGlobal::instance(), this, SLOT( load() ) );
// Set up the config object
KConfig *config = KGlobal::config();
/* Load the saved away messages */
config->setGroup("Away Messages");
if(config->hasKey("Messages"))
{
d->awayMessageList = config->readListEntry("Messages");
}
else if(config->hasKey("Titles")) // Old config format
{
QStringList titles = config->readListEntry("Titles"); // Get the titles
for(QStringList::iterator i = titles.begin(); i != titles.end(); ++i)
{
d->awayMessageList.append( config->readEntry(*i) ); // And add it to the list
}
/* Save this list to disk */
save();
}
else
{
d->awayMessageList.append( i18n( "Sorry, I am busy right now" ) );
d->awayMessageList.append( i18n( "I am gone right now, but I will be back later" ) );
/* Save this list to disk */
save();
}
// init the timer
d->timer = new QTimer(this, "AwayTimer");
connect(d->timer, SIGNAL(timeout()), this, SLOT(slotTimerTimeout()));
d->timer->start(4000);
//init the time and other
setActivity();
}
Kopete::Away::~Away()
{
delete d;
}
QString Kopete::Away::message()
{
return getInstance()->d->awayMessage;
}
void Kopete::Away::setGlobalAwayMessage(const QString &message)
{
if( !message.isEmpty() )
{
kdDebug(14010) << k_funcinfo <<
"Setting global away message: " << message << endl;
d->awayMessage = message;
}
}
Kopete::Away *Kopete::Away::getInstance()
{
if (!instance)
instance = new Kopete::Away;
return instance;
}
bool Kopete::Away::globalAway()
{
return getInstance()->d->globalAway;
}
void Kopete::Away::setGlobalAway(bool status)
{
getInstance()->d->globalAway = status;
}
void Kopete::Away::save()
{
KConfig *config = KGlobal::config();
/* Set the away message settings in the Away Messages config group */
config->setGroup("Away Messages");
config->writeEntry("Messages", d->awayMessageList);
config->sync();
emit( messagesChanged() );
}
void Kopete::Away::load()
{
KConfig *config = KGlobal::config();
config->setGroup("AutoAway");
d->awayTimeout=config->readNumEntry("Timeout", 600);
d->goAvailable=config->readBoolEntry("GoAvailable", true);
d->useAutoAway=config->readBoolEntry("UseAutoAway", true);
}
QStringList Kopete::Away::getMessages()
{
return d->awayMessageList;
}
QString Kopete::Away::getMessage( uint messageNumber )
{
QStringList::iterator it = d->awayMessageList.at( messageNumber );
if( it != d->awayMessageList.end() )
{
QString str = *it;
d->awayMessageList.prepend( str );
d->awayMessageList.remove( it );
save();
return str;
}
else
{
return QString::null;
}
}
void Kopete::Away::addMessage(const QString &message)
{
d->awayMessageList.prepend( message );
if( (int)d->awayMessageList.count() > KopetePrefs::prefs()->rememberedMessages() )
d->awayMessageList.pop_back();
save();
}
long int Kopete::Away::idleTime()
{
//FIXME: the time is reset to zero if more than 24 hours are elapsed
// we can imagine someone who leave his PC for several weeks
return (d->idleTime.elapsed() / 1000);
}
void Kopete::Away::slotTimerTimeout()
{
// Copyright (c) 1999 Martin R. Jones <mjones@kde.org>
//
// KDE screensaver engine
//
// This module is a heavily modified xautolock.
// In fact as of KDE 2.0 this code is practically unrecognisable as xautolock.
#ifdef Q_WS_X11
Display *dsp = qt_xdisplay();
Window dummy_w;
int dummy_c;
unsigned int mask; /* modifier mask */
int root_x;
int root_y;
/*
* Find out whether the pointer has moved. Using XQueryPointer for this
* is gross, but it also is the only way never to mess up propagation
* of pointer events.
*
* Remark : Unlike XNextEvent(), XPending () doesn't notice if the
* connection to the server is lost. For this reason, earlier
* versions of xautolock periodically called XNoOp (). But
* why not let XQueryPointer () do the job for us, since
* we now call that periodically anyway?
*/
if (!XQueryPointer (dsp, d->root, &(d->root), &dummy_w, &root_x, &root_y,
&dummy_c, &dummy_c, &mask))
{
/*
* Pointer has moved to another screen, so let's find out which one.
*/
for (int i = 0; i < ScreenCount(dsp); i++)
{
if (d->root == RootWindow(dsp, i))
{
d->screen = ScreenOfDisplay (dsp, i);
break;
}
}
}
#endif
// =================================================================================
#ifdef Q_WS_X11
Time xIdleTime = 0; // millisecs since last input event
#ifdef HasXidle
if (d->useXidle)
{
XGetIdleTime(dsp, &xIdleTime);
}
else
#endif /* HasXIdle */
{
#ifdef HasScreenSaver
if(d->useMit)
{
static XScreenSaverInfo* mitInfo = 0;
if (!mitInfo) mitInfo = XScreenSaverAllocInfo();
XScreenSaverQueryInfo (dsp, d->root, mitInfo);
xIdleTime = mitInfo->idle;
}
#endif /* HasScreenSaver */
}
// =================================================================================
if (root_x != d->mouse_x || root_y != d->mouse_y || mask != d->mouse_mask || xIdleTime < d->xIdleTime+2000)
{
if(d->mouse_x!=-1) //we just gone autoaway, not activity this time
setActivity();
d->mouse_x = root_x;
d->mouse_y = root_y;
d->mouse_mask = mask;
d->xIdleTime = xIdleTime;
}
#endif // Q_WS_X11
// =================================================================================
if(!d->autoaway && d->useAutoAway && idleTime() > d->awayTimeout)
{
setAutoAway();
}
}
void Kopete::Away::setActivity()
{
// kdDebug(14010) << k_funcinfo << "Found activity on desktop, resetting away timer" << endl;
d->idleTime.start();
if(d->autoaway)
{
d->autoaway = false;
emit activity();
if (d->goAvailable)
{
d->autoAwayAccounts.setAutoDelete(false);
for(Kopete::Account *i=d->autoAwayAccounts.first() ; i; i=d->autoAwayAccounts.current() )
{
if(i->isConnected() && i->isAway()) {
i->setAway(false);
}
// remove() makes the next entry in the list the current one,
// that's why we use current() above
d->autoAwayAccounts.remove();
}
}
}
}
void Kopete::Away::setAutoAway()
{
d->mouse_x=-1; //do not go availiable automaticaly after
// kdDebug(14010) << k_funcinfo << "Going AutoAway!" << endl;
d->autoaway = true;
// Set all accounts that are not away already to away.
// We remember them so later we only set the accounts to
// available that we set to away (and not the user).
QPtrList<Kopete::Account> accounts = Kopete::AccountManager::self()->accounts();
for(Kopete::Account *i=accounts.first() ; i; i=accounts.next() )
{
if(i->myself()->onlineStatus().status() == Kopete::OnlineStatus::Online)
{
d->autoAwayAccounts.append(i);
i->setAway( true, getInstance()->d->awayMessage);
}
}
}
#include "kopeteaway.moc"
// vim: set et ts=4 sts=4 sw=4:
<|endoftext|> |
<commit_before>/* libscratch - Multipurpose objective C++ library.
Copyright (C) 2012 - 2013 Angelo Geels
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>. */
#include <cstdio> // for printf
#include <iostream> // for std::cin.get
#include <Scratch.h>
static INDEX _ctTests = 0;
static INDEX _ctFailed = 0;
#define TEST(expr) { \
BOOL bSuccess = (expr); \
_ctTests++; \
ASSERT(bSuccess); \
printf(" Test #%d: (%s) ", _ctTests, #expr); \
if(!bSuccess) { \
_ctFailed++; \
printf("FAILED!\n"); \
} else { \
printf("OK\n"); \
} \
}
/// String testing
void TestString()
{
printf("Testing strings\n");
CString strTest;
strTest += "Lib";
strTest += "Scratch";
strTest = strTest.ToLower();
TEST(strTest == "libscratch");
strTest += " is great";
CStackArray<CString> astrParse = strTest.Split(" ");
TEST(astrParse[2] == "great");
TEST(astrParse[2][1] == 'r');
CString strTest2 = strTest.Replace("great", "cool");
TEST(strTest2 == "libscratch is cool");
}
/// Stack array testing
void TestStackArray()
{
printf("Testing stack arrays\n");
CStackArray<INDEX> aiNumbers;
TEST(aiNumbers.Count() == 0);
aiNumbers.Push() = 5;
aiNumbers.Push() = 10;
aiNumbers.Push() = 15;
TEST(aiNumbers.Count() == 3);
TEST(aiNumbers[0] == 5);
TEST(aiNumbers[1] == 10);
TEST(aiNumbers[2] + aiNumbers[0] == 20);
TEST(aiNumbers.Pop() == 15);
TEST(aiNumbers.Count() == 2);
}
/// Dictionary testing
void TestDictionary()
{
printf("Testing dictionary\n");
CDictionary<CString, INDEX> diTest;
TEST(!diTest.HasKey("Test"));
diTest["Test"] = 100;
diTest["Test2"] = 200;
TEST(diTest.HasKey("Test"));
TEST(diTest["Test"] == 100);
diTest.RemoveByKey("Test");
TEST(diTest.Count() == 1);
TEST(!diTest.HasKey("Test"));
}
/// Test file stream
void TestFilestream()
{
printf("Testing file streams\n");
// this test will create a Test.bin file, containing an integer 5 and the text "Hello!"
CFileStream fsTest;
fsTest.Open("Test.bin", "w");
fsTest << INDEX(5);
fsTest << "Hello!";
fsTest.Close();
// as a follow-up, we will read the same file from a seperate file stream
CFileStream fsTestRead;
fsTestRead.Open("Test.bin", "r");
INDEX iTest = 0;
fsTestRead >> iTest;
TEST(iTest == 5);
CString strTest;
fsTestRead >> strTest;
TEST(strTest == "Hello!");
// note that closing the stream is optional (destructor does it for us), however we need to have it closed for the unlink below
fsTestRead.Close();
// remove the test file from the system
unlink("Test.bin");
}
int main()
{
// perform tests
TestString();
TestStackArray();
TestDictionary();
TestFilestream();
// report test results
printf("\n\nResults: %d out of %d went OK.\n\n", _ctTests - _ctFailed, _ctTests);
// check if all went OK
if(_ctFailed == 0) {
// it did! no failures. :)
printf("All OK!\n");
} else {
// oops, there's a bug somewhere. please report!
printf("Some problems seem to have popped up. Please report a bug.\n");
}
std::cin.get();
return 0;
}
<commit_msg>Added vector tests<commit_after>/* libscratch - Multipurpose objective C++ library.
Copyright (C) 2012 - 2013 Angelo Geels
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>. */
#include <cstdio> // for printf
#include <iostream> // for std::cin.get
#include <Scratch.h>
static INDEX _ctTests = 0;
static INDEX _ctFailed = 0;
#define TEST(expr) { \
BOOL bSuccess = (expr); \
_ctTests++; \
ASSERT(bSuccess); \
printf(" Test #%d: (%s) ", _ctTests, #expr); \
if(!bSuccess) { \
_ctFailed++; \
printf("FAILED!\n"); \
} else { \
printf("OK\n"); \
} \
}
/// String testing
void TestString()
{
printf("Testing strings\n");
CString strTest;
strTest += "Lib";
strTest += "Scratch";
strTest = strTest.ToLower();
TEST(strTest == "libscratch");
strTest += " is great";
CStackArray<CString> astrParse = strTest.Split(" ");
TEST(astrParse[2] == "great");
TEST(astrParse[2][1] == 'r');
CString strTest2 = strTest.Replace("great", "cool");
TEST(strTest2 == "libscratch is cool");
}
/// Stack array testing
void TestStackArray()
{
printf("Testing stack arrays\n");
CStackArray<INDEX> aiNumbers;
TEST(aiNumbers.Count() == 0);
aiNumbers.Push() = 5;
aiNumbers.Push() = 10;
aiNumbers.Push() = 15;
TEST(aiNumbers.Count() == 3);
TEST(aiNumbers[0] == 5);
TEST(aiNumbers[1] == 10);
TEST(aiNumbers[2] + aiNumbers[0] == 20);
TEST(aiNumbers.Pop() == 15);
TEST(aiNumbers.Count() == 2);
}
/// Dictionary testing
void TestDictionary()
{
printf("Testing dictionary\n");
CDictionary<CString, INDEX> diTest;
TEST(!diTest.HasKey("Test"));
diTest["Test"] = 100;
diTest["Test2"] = 200;
TEST(diTest.HasKey("Test"));
TEST(diTest["Test"] == 100);
diTest.RemoveByKey("Test");
TEST(diTest.Count() == 1);
TEST(!diTest.HasKey("Test"));
}
/// Test file stream
void TestFilestream()
{
printf("Testing file streams\n");
// this test will create a Test.bin file, containing an integer 5 and the text "Hello!"
CFileStream fsTest;
fsTest.Open("Test.bin", "w");
fsTest << INDEX(5);
fsTest << "Hello!";
fsTest.Close();
// as a follow-up, we will read the same file from a seperate file stream
CFileStream fsTestRead;
fsTestRead.Open("Test.bin", "r");
INDEX iTest = 0;
fsTestRead >> iTest;
TEST(iTest == 5);
CString strTest;
fsTestRead >> strTest;
TEST(strTest == "Hello!");
// note that closing the stream is optional (destructor does it for us), however we need to have it closed for the unlink below
fsTestRead.Close();
// remove the test file from the system
unlink("Test.bin");
}
/// Vector tests
void TestVectors()
{
printf("Testing vectors\n");
Vector3f vTest(1, 0, 0);
TEST(vTest.Length() == 1.0f);
vTest *= 5.0f;
TEST(vTest.Length() == 5.0f);
vTest.x = 3;
vTest.y = 4;
TEST(vTest.Length() == 5.0f);
vTest.Normalize();
TEST(vTest.Length() == 1.0f);
}
int main()
{
// perform tests
TestString();
TestStackArray();
TestDictionary();
TestFilestream();
TestVectors();
// report test results
printf("\n\nResults: %d out of %d went OK.\n\n", _ctTests - _ctFailed, _ctTests);
// check if all went OK
if(_ctFailed == 0) {
// it did! no failures. :)
printf("All OK!\n");
} else {
// oops, there's a bug somewhere. please report!
printf("Some problems seem to have popped up. Please report a bug.\n");
}
std::cin.get();
return 0;
}
<|endoftext|> |
<commit_before>// This file is part of the dune-gdt project:
// http://users.dune-project.org/projects/dune-gdt
// Copyright holders: Felix Albrecht
// License: BSD 2-Clause License (http://opensource.org/licenses/BSD-2-Clause)
#ifndef DUNE_GDT_BASEFUNCTIONSET_FEM_HH
#define DUNE_GDT_BASEFUNCTIONSET_FEM_HH
#include <dune/common/fvector.hh>
#include <dune/common/fmatrix.hh>
#include <dune/fem/space/basefunctions/basefunctionsetinterface.hh>
#include <dune/fem/space/common/discretefunctionspace.hh>
#include <dune/stuff/common/memory.hh>
#include "interface.hh"
namespace Dune {
namespace GDT {
namespace BaseFunctionSet {
// forward, to be used in the traits and to allow for specialization
template <class FemBaseFunctionSetTraits, class EntityImp, class DomainFieldImp, int domainDim, class RangeFieldImp,
int rangeDim, int rangeDimCols = 1>
class FemWrapper;
template <class FemBaseFunctionSetTraits, class EntityImp, class DomainFieldImp, int domainDim, class RangeFieldImp,
int rangeDim, int rangeDimCols = 1>
class FemWrapperTraits
{
public:
typedef FemWrapper<FemBaseFunctionSetTraits, EntityImp, DomainFieldImp, domainDim, RangeFieldImp, rangeDim,
rangeDimCols> derived_type;
typedef typename Dune::Fem::BaseFunctionSetInterface<FemBaseFunctionSetTraits>::BaseFunctionSetType BackendType;
typedef EntityImp EntityType;
};
template <class FemBaseFunctionSetTraits, class EntityImp, class DomainFieldImp, int domainDim, class RangeFieldImp,
int rangeDim>
class FemWrapper<FemBaseFunctionSetTraits, EntityImp, DomainFieldImp, domainDim, RangeFieldImp, rangeDim, 1>
: public BaseFunctionSetInterface<FemWrapperTraits<FemBaseFunctionSetTraits, EntityImp, DomainFieldImp, domainDim,
RangeFieldImp, rangeDim, 1>,
DomainFieldImp, domainDim, RangeFieldImp, rangeDim, 1>
{
typedef FemWrapper<FemBaseFunctionSetTraits, EntityImp, DomainFieldImp, domainDim, RangeFieldImp, rangeDim, 1>
ThisType;
typedef BaseFunctionSetInterface<FemWrapperTraits<FemBaseFunctionSetTraits, EntityImp, DomainFieldImp, domainDim,
RangeFieldImp, rangeDim, 1>,
DomainFieldImp, domainDim, RangeFieldImp, rangeDim, 1> BaseType;
public:
typedef FemWrapperTraits<FemBaseFunctionSetTraits, EntityImp, DomainFieldImp, domainDim, RangeFieldImp, rangeDim, 1>
Traits;
typedef typename Traits::BackendType BackendType;
typedef typename Traits::EntityType EntityType;
typedef DomainFieldImp DomainFieldType;
static const unsigned int dimDomain = domainDim;
typedef Dune::FieldVector<DomainFieldType, dimDomain> DomainType;
typedef RangeFieldImp RangeFieldType;
static const unsigned int dimRange = rangeDim;
static const unsigned int dimRangeCols = 1;
typedef Dune::FieldVector<RangeFieldType, dimRange> RangeType;
typedef Dune::FieldMatrix<RangeFieldType, dimRange, dimDomain> JacobianRangeType;
template <class S>
FemWrapper(const Dune::Fem::DiscreteFunctionSpaceInterface<S>& femSpace, const EntityType& ent)
: BaseType(ent)
, order_(femSpace.order())
, backend_(new BackendType(femSpace.baseFunctionSet(this->entity())))
{
}
FemWrapper(ThisType&& source)
: BaseType(source.entity())
, order_(std::move(source.order_))
, backend_(std::move(source.backend_))
{
}
FemWrapper(const ThisType& /*other*/) = delete;
ThisType& operator=(const ThisType& /*other*/) = delete;
const BackendType& backend() const
{
return *backend_;
}
virtual size_t size() const DS_OVERRIDE
{
return backend_->size();
}
virtual size_t order() const DS_OVERRIDE
{
return order_;
}
virtual void evaluate(const DomainType& xx, std::vector<RangeType>& ret) const DS_OVERRIDE
{
assert(ret.size() >= backend_->size());
backend_->evaluateAll(xx, ret);
}
using BaseType::evaluate;
virtual void jacobian(const DomainType& xx, std::vector<JacobianRangeType>& ret) const DS_OVERRIDE
{
assert(ret.size() >= backend_->size());
backend_->jacobianAll(xx, this->entity().geometry().jacobianInverseTransposed(xx), ret);
}
using BaseType::jacobian;
private:
const size_t order_;
std::unique_ptr<const BackendType> backend_;
}; // class FemWrapper
} // namespace BaseFunctionSet
} // namespace GDT
} // namespace Dune
#endif // DUNE_GDT_BASEFUNCTIONSET_FEM_HH
<commit_msg>[basefunctionset.fem] add proper guards<commit_after>// This file is part of the dune-gdt project:
// http://users.dune-project.org/projects/dune-gdt
// Copyright holders: Felix Albrecht
// License: BSD 2-Clause License (http://opensource.org/licenses/BSD-2-Clause)
#ifndef DUNE_GDT_BASEFUNCTIONSET_FEM_HH
#define DUNE_GDT_BASEFUNCTIONSET_FEM_HH
#include <type_traits>
#include <dune/common/typetraits.hh>
#include <dune/common/fvector.hh>
#include <dune/common/fmatrix.hh>
#ifdef HAVE_DUNE_FEM
#include <dune/fem/space/basefunctions/basefunctionsetinterface.hh>
#include <dune/fem/space/common/discretefunctionspace.hh>
#endif // HAVE_DUNE_FEM
#include <dune/stuff/common/memory.hh>
#include "interface.hh"
namespace Dune {
namespace GDT {
namespace BaseFunctionSet {
#ifdef HAVE_DUNE_FEM
// forward, to be used in the traits and to allow for specialization
template <class FemBaseFunctionSetTraits, class EntityImp, class DomainFieldImp, int domainDim, class RangeFieldImp,
int rangeDim, int rangeDimCols = 1>
class FemWrapper
{
static_assert(Dune::AlwaysFalse<FemBaseFunctionSetTraits>::value, "Untested for these dimensions!");
};
template <class FemBaseFunctionSetTraits, class EntityImp, class DomainFieldImp, int domainDim, class RangeFieldImp,
int rangeDim, int rangeDimCols = 1>
class FemWrapperTraits
{
public:
typedef FemWrapper<FemBaseFunctionSetTraits, EntityImp, DomainFieldImp, domainDim, RangeFieldImp, rangeDim,
rangeDimCols> derived_type;
typedef typename Dune::Fem::BaseFunctionSetInterface<FemBaseFunctionSetTraits>::BaseFunctionSetType BackendType;
typedef EntityImp EntityType;
};
template <class FemBaseFunctionSetTraits, class EntityImp, class DomainFieldImp, int domainDim, class RangeFieldImp,
int rangeDim>
class FemWrapper<FemBaseFunctionSetTraits, EntityImp, DomainFieldImp, domainDim, RangeFieldImp, rangeDim, 1>
: public BaseFunctionSetInterface<FemWrapperTraits<FemBaseFunctionSetTraits, EntityImp, DomainFieldImp, domainDim,
RangeFieldImp, rangeDim, 1>,
DomainFieldImp, domainDim, RangeFieldImp, rangeDim, 1>
{
typedef FemWrapper<FemBaseFunctionSetTraits, EntityImp, DomainFieldImp, domainDim, RangeFieldImp, rangeDim, 1>
ThisType;
typedef BaseFunctionSetInterface<FemWrapperTraits<FemBaseFunctionSetTraits, EntityImp, DomainFieldImp, domainDim,
RangeFieldImp, rangeDim, 1>,
DomainFieldImp, domainDim, RangeFieldImp, rangeDim, 1> BaseType;
public:
typedef FemWrapperTraits<FemBaseFunctionSetTraits, EntityImp, DomainFieldImp, domainDim, RangeFieldImp, rangeDim, 1>
Traits;
typedef typename Traits::BackendType BackendType;
typedef typename Traits::EntityType EntityType;
typedef DomainFieldImp DomainFieldType;
static const unsigned int dimDomain = domainDim;
typedef Dune::FieldVector<DomainFieldType, dimDomain> DomainType;
typedef RangeFieldImp RangeFieldType;
static const unsigned int dimRange = rangeDim;
static const unsigned int dimRangeCols = 1;
typedef Dune::FieldVector<RangeFieldType, dimRange> RangeType;
typedef Dune::FieldMatrix<RangeFieldType, dimRange, dimDomain> JacobianRangeType;
template <class S>
FemWrapper(const Dune::Fem::DiscreteFunctionSpaceInterface<S>& femSpace, const EntityType& ent)
: BaseType(ent)
, order_(femSpace.order())
, backend_(new BackendType(femSpace.baseFunctionSet(this->entity())))
{
}
FemWrapper(ThisType&& source)
: BaseType(source.entity())
, order_(std::move(source.order_))
, backend_(std::move(source.backend_))
{
}
FemWrapper(const ThisType& /*other*/) = delete;
ThisType& operator=(const ThisType& /*other*/) = delete;
const BackendType& backend() const
{
return *backend_;
}
virtual size_t size() const DS_OVERRIDE
{
return backend_->size();
}
virtual size_t order() const DS_OVERRIDE
{
return order_;
}
virtual void evaluate(const DomainType& xx, std::vector<RangeType>& ret) const DS_OVERRIDE
{
assert(ret.size() >= backend_->size());
backend_->evaluateAll(xx, ret);
}
using BaseType::evaluate;
virtual void jacobian(const DomainType& xx, std::vector<JacobianRangeType>& ret) const DS_OVERRIDE
{
assert(ret.size() >= backend_->size());
backend_->jacobianAll(xx, this->entity().geometry().jacobianInverseTransposed(xx), ret);
}
using BaseType::jacobian;
private:
const size_t order_;
std::unique_ptr<const BackendType> backend_;
}; // class FemWrapper
#else // HAVE_DUNE_FEM
template <class FemBaseFunctionSetTraits, class EntityImp, class DomainFieldImp, int domainDim, class RangeFieldImp,
int rangeDim, int rangeDimCols = 1>
class FemWrapper
{
static_assert(Dune::AlwaysFalse<FemBaseFunctionSetTraits>::value, "You are missing dune-fem!");
};
#endif // HAVE_DUNE_FEM
} // namespace BaseFunctionSet
} // namespace GDT
} // namespace Dune
#endif // DUNE_GDT_BASEFUNCTIONSET_FEM_HH
<|endoftext|> |
<commit_before>#ifndef DUNE_HELPER_TOOLS_GRID_INTERSECTION_HH
#define DUNE_FEMTOOLS_GRID_INTERSECTION_HH
#ifdef HAVE_CMAKE_CONFIG
#include "cmake_config.h"
#else
#include "config.h"
#endif // ifdef HAVE_CMAKE_CONFIG
// dune-common includes
#include <dune/common/fvector.hh>
#include <dune/common/static_assert.hh>
// dune-stuff
#include <dune/stuff/common/string.hh>
namespace Dune {
namespace Stuff {
namespace Grid {
/**
\brief prints some basic information about a Dune::Intersection, namely the number of its corners and the
coordinates of those corners.
\tparam IntersectionType
Dune::Intersection compatible
\param[in] intersection
Dune::Intersection, whose information should be printed
\param[out] stream
std::ostream, into which the information is printed
**/
template< class IntersectionType >
void printIntersection( const IntersectionType& intersection, std::ostream& stream = std::cout )
{
typedef typename IntersectionType::Geometry
GeometryType;
typedef typename GeometryType::GlobalCoordinate
GlobalPointType;
const GeometryType& geometry = intersection.geometry();
const int numCorners = geometry.corners();
std::string prefix = "Dune::Intersection (" + Dune::Stuff::Common::toString( numCorners ) + " corner";
if( numCorners != 1 )
{
prefix += "s";
}
prefix += "): ";
const unsigned int missing = 32 - prefix.size();
if( missing > 0 )
{
for( unsigned int i = 0; i < missing; ++i )
{
prefix += " ";
}
}
const std::string whitespace = Dune::Stuff::Common::whitespaceify( prefix );
stream << prefix << "[ (";
for( int i = 0; i < numCorners; ++i )
{
const GlobalPointType corner = geometry.corner( i );
for( unsigned int j = 0; j < corner.size(); ++ j )
{
stream << corner[j];
if( j < corner.size() - 1 )
{
stream << ", " ;
}
}
stream << ")";
if( i < geometry.corners() - 1 )
{
stream << "," << std::endl << whitespace << " (";
}
else{
stream << " ]" << std::endl;
}
}
} // end function print
template< class IntersectionType, class FieldType, int size >
bool intersectionContains( const IntersectionType& /*intersection*/, const Dune::FieldVector< FieldType, size >& /*globalPoint*/ )
{
dune_static_assert( size < 3, "Dune::FemTools::Grid::Intersection::contains() not implemented for more than 2 dimension!" );
return false;
}
template< class IntersectionType, class FieldType >
bool intersectionContains( const IntersectionType& intersection, const Dune::FieldVector< FieldType, 1 >& globalPoint )
{
typedef Dune::FieldVector< FieldType, 1 >
GlobalPointType;
typedef typename IntersectionType::Geometry
GeometryType;
const GeometryType& geometry = intersection.geometry();
// get the only corner
const GlobalPointType corner = geometry.corner( 0 );
// check if the point is the corner
if( corner == globalPoint )
{
return true;
}
return false;
} // end function contains
template< class IntersectionType, class FieldType >
bool intersectionContains( const IntersectionType& intersection, const Dune::FieldVector< FieldType, 2 > & globalPoint )
{
typedef Dune::FieldVector< FieldType, 2 >
GlobalPointType;
typedef typename IntersectionType::Geometry
GeometryType;
const GeometryType& geometry = intersection.geometry();
// get the two corners
const GlobalPointType firstCorner = geometry.corner( 0 );
const GlobalPointType secondCorner = geometry.corner( 1 );
// check, that point is on the line between the two points
const FieldType x1 = ( globalPoint[0] - firstCorner[0] ) / ( secondCorner[0] - firstCorner[0] );
const FieldType x2 = ( globalPoint[1] - firstCorner[1] ) / ( secondCorner[1] - firstCorner[1] );
if( !( x1 > x2 ) && !( x1 < x2 ) && !( x1 < 0.0 ) && !( x1 > 1.0 ) )
{
return true;
}
return false;
} // end function contains
} // end namespace Grid
} // end of namespace Stuff
} // end namespace Dune
#endif // DUNE_FEMTOOLS_GRID_INTERSECTION_HH
/** Copyright (c) 2012, Felix Albrecht
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
* ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
* The views and conclusions contained in the software and documentation are those
* of the authors and should not be interpreted as representing official policies,
* either expressed or implied, of the FreeBSD Project.
**/
<commit_msg>[grid] fix headerguard snafu<commit_after>#ifndef DUNE_STUFF_GRID_INTERSECTION_HH
#define DUNE_STUFF_GRID_INTERSECTION_HH
#ifdef HAVE_CMAKE_CONFIG
#include "cmake_config.h"
#else
#include "config.h"
#endif // ifdef HAVE_CMAKE_CONFIG
// dune-common includes
#include <dune/common/fvector.hh>
#include <dune/common/static_assert.hh>
// dune-stuff
#include <dune/stuff/common/string.hh>
namespace Dune {
namespace Stuff {
namespace Grid {
/**
\brief prints some basic information about a Dune::Intersection, namely the number of its corners and the
coordinates of those corners.
\tparam IntersectionType
Dune::Intersection compatible
\param[in] intersection
Dune::Intersection, whose information should be printed
\param[out] stream
std::ostream, into which the information is printed
**/
template< class IntersectionType >
void printIntersection( const IntersectionType& intersection, std::ostream& stream = std::cout )
{
typedef typename IntersectionType::Geometry
GeometryType;
typedef typename GeometryType::GlobalCoordinate
GlobalPointType;
const GeometryType& geometry = intersection.geometry();
const int numCorners = geometry.corners();
std::string prefix = "Dune::Intersection (" + Dune::Stuff::Common::toString( numCorners ) + " corner";
if( numCorners != 1 )
{
prefix += "s";
}
prefix += "): ";
const unsigned int missing = 32 - prefix.size();
if( missing > 0 )
{
for( unsigned int i = 0; i < missing; ++i )
{
prefix += " ";
}
}
const std::string whitespace = Dune::Stuff::Common::whitespaceify( prefix );
stream << prefix << "[ (";
for( int i = 0; i < numCorners; ++i )
{
const GlobalPointType corner = geometry.corner( i );
for( unsigned int j = 0; j < corner.size(); ++ j )
{
stream << corner[j];
if( j < corner.size() - 1 )
{
stream << ", " ;
}
}
stream << ")";
if( i < geometry.corners() - 1 )
{
stream << "," << std::endl << whitespace << " (";
}
else{
stream << " ]" << std::endl;
}
}
} // end function print
template< class IntersectionType, class FieldType, int size >
bool intersectionContains( const IntersectionType& /*intersection*/, const Dune::FieldVector< FieldType, size >& /*globalPoint*/ )
{
dune_static_assert( size < 3, "Dune::FemTools::Grid::Intersection::contains() not implemented for more than 2 dimension!" );
return false;
}
template< class IntersectionType, class FieldType >
bool intersectionContains( const IntersectionType& intersection, const Dune::FieldVector< FieldType, 1 >& globalPoint )
{
typedef Dune::FieldVector< FieldType, 1 >
GlobalPointType;
typedef typename IntersectionType::Geometry
GeometryType;
const GeometryType& geometry = intersection.geometry();
// get the only corner
const GlobalPointType corner = geometry.corner( 0 );
// check if the point is the corner
if( corner == globalPoint )
{
return true;
}
return false;
} // end function contains
template< class IntersectionType, class FieldType >
bool intersectionContains( const IntersectionType& intersection, const Dune::FieldVector< FieldType, 2 > & globalPoint )
{
typedef Dune::FieldVector< FieldType, 2 >
GlobalPointType;
typedef typename IntersectionType::Geometry
GeometryType;
const GeometryType& geometry = intersection.geometry();
// get the two corners
const GlobalPointType firstCorner = geometry.corner( 0 );
const GlobalPointType secondCorner = geometry.corner( 1 );
// check, that point is on the line between the two points
const FieldType x1 = ( globalPoint[0] - firstCorner[0] ) / ( secondCorner[0] - firstCorner[0] );
const FieldType x2 = ( globalPoint[1] - firstCorner[1] ) / ( secondCorner[1] - firstCorner[1] );
if( !( x1 > x2 ) && !( x1 < x2 ) && !( x1 < 0.0 ) && !( x1 > 1.0 ) )
{
return true;
}
return false;
} // end function contains
} // end namespace Grid
} // end of namespace Stuff
} // end namespace Dune
#endif // DUNE_STUFF_GRID_INTERSECTION_HH
/** Copyright (c) 2012, Felix Albrecht
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
* ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
* The views and conclusions contained in the software and documentation are those
* of the authors and should not be interpreted as representing official policies,
* either expressed or implied, of the FreeBSD Project.
**/
<|endoftext|> |
<commit_before>/*
* Copyright (c) 2012,2017-2018 ARM Limited
* All rights reserved
*
* The license below extends only to copyright in the software and shall
* not be construed as granting a license to any other intellectual
* property including but not limited to intellectual property relating
* to a hardware implementation of the functionality of the software
* licensed hereunder. You may use the software subject to the license
* terms below provided that you ensure that this notice is replicated
* unmodified and in its entirety in all distributions of the software,
* modified or unmodified, in source code or in binary form.
*
* Copyright (c) 2006 The Regents of The University of Michigan
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met: redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer;
* redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution;
* neither the name of the copyright holders nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
* Authors: Ali Saidi
*/
#ifndef __BASE_COMPILER_HH__
#define __BASE_COMPILER_HH__
#include <memory>
// http://gcc.gnu.org/onlinedocs/gcc/Function-Attributes.html
#if defined(__GNUC__) // clang or gcc
# define M5_ATTR_NORETURN __attribute__((noreturn))
# define M5_DUMMY_RETURN
# define M5_VAR_USED __attribute__((unused))
# define M5_ATTR_PACKED __attribute__ ((__packed__))
# define M5_NO_INLINE __attribute__ ((__noinline__))
# define M5_DEPRECATED __attribute__((deprecated))
# define M5_DEPRECATED_MSG(MSG) __attribute__((deprecated(MSG)))
# define M5_UNREACHABLE __builtin_unreachable()
# define M5_PUBLIC __attribute__ ((visibility ("default")))
# define M5_LOCAL __attribute__ ((visibility ("hidden")))
#endif
#if defined(__clang__)
# define M5_CLASS_VAR_USED M5_VAR_USED
#else
# define M5_CLASS_VAR_USED
#endif
// This can be removed once all compilers support C++17
#if defined __has_cpp_attribute
// Note: We must separate this if statement because GCC < 5.0 doesn't
// support the function-like syntax in #if statements.
#if __has_cpp_attribute(fallthrough)
#define M5_FALLTHROUGH [[fallthrough]]
#else
#define M5_FALLTHROUGH
#endif
#if __has_cpp_attribute(nodiscard)
#define M5_NODISCARD [[nodiscard]]
#else
#define M5_NODISCARD
#endif
#else
// Unsupported (and no warning) on GCC < 7.
#define M5_FALLTHROUGH
#define M5_NODISCARD
#endif
// std::make_unique redefined for C++11 compilers
namespace m5
{
#if __cplusplus == 201402L // C++14
using std::make_unique;
#else // C++11
/** Defining custom version of make_unique: m5::make_unique<>() */
template<typename T, typename... Args>
std::unique_ptr<T>
make_unique( Args&&... constructor_args )
{
return std::unique_ptr<T>(
new T( std::forward<Args>(constructor_args)... )
);
}
#endif // __cplusplus == 201402L
} //namespace m5
#endif // __BASE_COMPILER_HH__
<commit_msg>base: Replace cppversion == version with >= version<commit_after>/*
* Copyright (c) 2012,2017-2018 ARM Limited
* All rights reserved
*
* The license below extends only to copyright in the software and shall
* not be construed as granting a license to any other intellectual
* property including but not limited to intellectual property relating
* to a hardware implementation of the functionality of the software
* licensed hereunder. You may use the software subject to the license
* terms below provided that you ensure that this notice is replicated
* unmodified and in its entirety in all distributions of the software,
* modified or unmodified, in source code or in binary form.
*
* Copyright (c) 2006 The Regents of The University of Michigan
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met: redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer;
* redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution;
* neither the name of the copyright holders nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
* Authors: Ali Saidi
*/
#ifndef __BASE_COMPILER_HH__
#define __BASE_COMPILER_HH__
#include <memory>
// http://gcc.gnu.org/onlinedocs/gcc/Function-Attributes.html
#if defined(__GNUC__) // clang or gcc
# define M5_ATTR_NORETURN __attribute__((noreturn))
# define M5_DUMMY_RETURN
# define M5_VAR_USED __attribute__((unused))
# define M5_ATTR_PACKED __attribute__ ((__packed__))
# define M5_NO_INLINE __attribute__ ((__noinline__))
# define M5_DEPRECATED __attribute__((deprecated))
# define M5_DEPRECATED_MSG(MSG) __attribute__((deprecated(MSG)))
# define M5_UNREACHABLE __builtin_unreachable()
# define M5_PUBLIC __attribute__ ((visibility ("default")))
# define M5_LOCAL __attribute__ ((visibility ("hidden")))
#endif
#if defined(__clang__)
# define M5_CLASS_VAR_USED M5_VAR_USED
#else
# define M5_CLASS_VAR_USED
#endif
// This can be removed once all compilers support C++17
#if defined __has_cpp_attribute
// Note: We must separate this if statement because GCC < 5.0 doesn't
// support the function-like syntax in #if statements.
#if __has_cpp_attribute(fallthrough)
#define M5_FALLTHROUGH [[fallthrough]]
#else
#define M5_FALLTHROUGH
#endif
#if __has_cpp_attribute(nodiscard)
#define M5_NODISCARD [[nodiscard]]
#else
#define M5_NODISCARD
#endif
#else
// Unsupported (and no warning) on GCC < 7.
#define M5_FALLTHROUGH
#define M5_NODISCARD
#endif
// std::make_unique redefined for C++11 compilers
namespace m5
{
#if __cplusplus >= 201402L // C++14
using std::make_unique;
#else // C++11
/** Defining custom version of make_unique: m5::make_unique<>() */
template<typename T, typename... Args>
std::unique_ptr<T>
make_unique( Args&&... constructor_args )
{
return std::unique_ptr<T>(
new T( std::forward<Args>(constructor_args)... )
);
}
#endif // __cplusplus >= 201402L
} //namespace m5
#endif // __BASE_COMPILER_HH__
<|endoftext|> |
<commit_before>// Copyright (c) 2009-2020 The Bitcoin Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#if defined(HAVE_CONFIG_H)
#include <config/bitcoin-config.h>
#endif
#include <arith_uint256.h>
#include <clientversion.h>
#include <coins.h>
#include <consensus/consensus.h>
#include <core_io.h>
#include <key_io.h>
#include <policy/rbf.h>
#include <primitives/transaction.h>
#include <script/script.h>
#include <script/sign.h>
#include <script/signingprovider.h>
#include <univalue.h>
#include <util/moneystr.h>
#include <util/rbf.h>
#include <util/strencodings.h>
#include <util/string.h>
#include <util/system.h>
#include <util/translation.h>
#include <functional>
#include <memory>
#include <stdio.h>
#include <thread>
#include <boost/algorithm/string.hpp>
static const int CONTINUE_EXECUTION=-1;
const std::function<std::string(const char*)> G_TRANSLATION_FUN = nullptr;
static void SetupBitcoinUtilArgs(ArgsManager &argsman)
{
SetupHelpOptions(argsman);
argsman.AddArg("-version", "Print version and exit", ArgsManager::ALLOW_ANY, OptionsCategory::OPTIONS);
SetupChainParamsBaseOptions(argsman);
}
// This function returns either one of EXIT_ codes when it's expected to stop the process or
// CONTINUE_EXECUTION when it's expected to continue further.
static int AppInitUtil(int argc, char* argv[])
{
SetupBitcoinUtilArgs(gArgs);
std::string error;
if (!gArgs.ParseParameters(argc, argv, error)) {
tfm::format(std::cerr, "Error parsing command line arguments: %s\n", error);
return EXIT_FAILURE;
}
// Check for chain settings (Params() calls are only valid after this clause)
try {
SelectParams(gArgs.GetChainName());
} catch (const std::exception& e) {
tfm::format(std::cerr, "Error: %s\n", e.what());
return EXIT_FAILURE;
}
if (argc < 2 || HelpRequested(gArgs) || gArgs.IsArgSet("-version")) {
// First part of help message is specific to this utility
std::string strUsage = PACKAGE_NAME " bitcoin-util utility version " + FormatFullVersion() + "\n";
if (!gArgs.IsArgSet("-version")) {
strUsage += "\n"
"Usage: bitcoin-util [options] [commands] Do stuff\n";
strUsage += "\n" + gArgs.GetHelpMessage();
}
tfm::format(std::cout, "%s", strUsage);
if (argc < 2) {
tfm::format(std::cerr, "Error: too few parameters\n");
return EXIT_FAILURE;
}
return EXIT_SUCCESS;
}
return CONTINUE_EXECUTION;
}
static void grind_task(uint32_t nBits, CBlockHeader& header_orig, uint32_t offset, uint32_t step, std::atomic<bool>& found)
{
arith_uint256 target;
bool neg, over;
target.SetCompact(nBits, &neg, &over);
if (target == 0 || neg || over) return;
CBlockHeader header = header_orig; // working copy
header.nNonce = offset;
uint32_t finish = std::numeric_limits<uint32_t>::max() - step;
finish = finish - (finish % step) + offset;
while (!found && header.nNonce < finish) {
const uint32_t next = (finish - header.nNonce < 5000*step) ? finish : header.nNonce + 5000*step;
do {
if (UintToArith256(header.GetHash()) <= target) {
if (!found.exchange(true)) {
header_orig.nNonce = header.nNonce;
}
return;
}
header.nNonce += step;
} while(header.nNonce != next);
}
}
static int Grind(int argc, char* argv[], std::string& strPrint)
{
if (argc != 1) {
strPrint = "Must specify block header to grind";
return 1;
}
CBlockHeader header;
if (!DecodeHexBlockHeader(header, argv[0])) {
strPrint = "Could not decode block header";
return 1;
}
uint32_t nBits = header.nBits;
std::atomic<bool> found{false};
std::vector<std::thread> threads;
int n_tasks = std::max(1u, std::thread::hardware_concurrency());
for (int i = 0; i < n_tasks; ++i) {
threads.emplace_back( grind_task, nBits, std::ref(header), i, n_tasks, std::ref(found) );
}
for (auto& t : threads) {
t.join();
}
if (!found) {
strPrint = "Could not satisfy difficulty target";
return 1;
}
CDataStream ss(SER_NETWORK, PROTOCOL_VERSION);
ss << header;
strPrint = HexStr(ss);
return 0;
}
static int CommandLineUtil(int argc, char* argv[])
{
if (argc <= 1) return 1;
std::string strPrint;
int nRet = 0;
try {
while (argc > 1 && IsSwitchChar(argv[1][0]) && (argv[1][1] != 0)) {
--argc;
++argv;
}
char* command = argv[1];
if (strcmp(command, "grind") == 0) {
nRet = Grind(argc-2, argv+2, strPrint);
} else {
strPrint = strprintf("Unknown command %s", command);
nRet = 1;
}
}
catch (const std::exception& e) {
strPrint = std::string("error: ") + e.what();
nRet = EXIT_FAILURE;
}
catch (...) {
PrintExceptionContinue(nullptr, "CommandLineUtil()");
throw;
}
if (strPrint != "") {
tfm::format(nRet == 0 ? std::cout : std::cerr, "%s\n", strPrint);
}
return nRet;
}
int main(int argc, char* argv[])
{
SetupEnvironment();
try {
int ret = AppInitUtil(argc, argv);
if (ret != CONTINUE_EXECUTION)
return ret;
}
catch (const std::exception& e) {
PrintExceptionContinue(&e, "AppInitUtil()");
return EXIT_FAILURE;
} catch (...) {
PrintExceptionContinue(nullptr, "AppInitUtil()");
return EXIT_FAILURE;
}
int ret = EXIT_FAILURE;
try {
ret = CommandLineUtil(argc, argv);
}
catch (const std::exception& e) {
PrintExceptionContinue(&e, "CommandLineUtil()");
} catch (...) {
PrintExceptionContinue(nullptr, "CommandLineUtil()");
}
return ret;
}
<commit_msg>add std::atomic include to bitcoin-util.cpp<commit_after>// Copyright (c) 2009-2020 The Bitcoin Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#if defined(HAVE_CONFIG_H)
#include <config/bitcoin-config.h>
#endif
#include <arith_uint256.h>
#include <clientversion.h>
#include <coins.h>
#include <consensus/consensus.h>
#include <core_io.h>
#include <key_io.h>
#include <policy/rbf.h>
#include <primitives/transaction.h>
#include <script/script.h>
#include <script/sign.h>
#include <script/signingprovider.h>
#include <univalue.h>
#include <util/moneystr.h>
#include <util/rbf.h>
#include <util/strencodings.h>
#include <util/string.h>
#include <util/system.h>
#include <util/translation.h>
#include <atomic>
#include <functional>
#include <memory>
#include <stdio.h>
#include <thread>
#include <boost/algorithm/string.hpp>
static const int CONTINUE_EXECUTION=-1;
const std::function<std::string(const char*)> G_TRANSLATION_FUN = nullptr;
static void SetupBitcoinUtilArgs(ArgsManager &argsman)
{
SetupHelpOptions(argsman);
argsman.AddArg("-version", "Print version and exit", ArgsManager::ALLOW_ANY, OptionsCategory::OPTIONS);
SetupChainParamsBaseOptions(argsman);
}
// This function returns either one of EXIT_ codes when it's expected to stop the process or
// CONTINUE_EXECUTION when it's expected to continue further.
static int AppInitUtil(int argc, char* argv[])
{
SetupBitcoinUtilArgs(gArgs);
std::string error;
if (!gArgs.ParseParameters(argc, argv, error)) {
tfm::format(std::cerr, "Error parsing command line arguments: %s\n", error);
return EXIT_FAILURE;
}
// Check for chain settings (Params() calls are only valid after this clause)
try {
SelectParams(gArgs.GetChainName());
} catch (const std::exception& e) {
tfm::format(std::cerr, "Error: %s\n", e.what());
return EXIT_FAILURE;
}
if (argc < 2 || HelpRequested(gArgs) || gArgs.IsArgSet("-version")) {
// First part of help message is specific to this utility
std::string strUsage = PACKAGE_NAME " bitcoin-util utility version " + FormatFullVersion() + "\n";
if (!gArgs.IsArgSet("-version")) {
strUsage += "\n"
"Usage: bitcoin-util [options] [commands] Do stuff\n";
strUsage += "\n" + gArgs.GetHelpMessage();
}
tfm::format(std::cout, "%s", strUsage);
if (argc < 2) {
tfm::format(std::cerr, "Error: too few parameters\n");
return EXIT_FAILURE;
}
return EXIT_SUCCESS;
}
return CONTINUE_EXECUTION;
}
static void grind_task(uint32_t nBits, CBlockHeader& header_orig, uint32_t offset, uint32_t step, std::atomic<bool>& found)
{
arith_uint256 target;
bool neg, over;
target.SetCompact(nBits, &neg, &over);
if (target == 0 || neg || over) return;
CBlockHeader header = header_orig; // working copy
header.nNonce = offset;
uint32_t finish = std::numeric_limits<uint32_t>::max() - step;
finish = finish - (finish % step) + offset;
while (!found && header.nNonce < finish) {
const uint32_t next = (finish - header.nNonce < 5000*step) ? finish : header.nNonce + 5000*step;
do {
if (UintToArith256(header.GetHash()) <= target) {
if (!found.exchange(true)) {
header_orig.nNonce = header.nNonce;
}
return;
}
header.nNonce += step;
} while(header.nNonce != next);
}
}
static int Grind(int argc, char* argv[], std::string& strPrint)
{
if (argc != 1) {
strPrint = "Must specify block header to grind";
return 1;
}
CBlockHeader header;
if (!DecodeHexBlockHeader(header, argv[0])) {
strPrint = "Could not decode block header";
return 1;
}
uint32_t nBits = header.nBits;
std::atomic<bool> found{false};
std::vector<std::thread> threads;
int n_tasks = std::max(1u, std::thread::hardware_concurrency());
for (int i = 0; i < n_tasks; ++i) {
threads.emplace_back( grind_task, nBits, std::ref(header), i, n_tasks, std::ref(found) );
}
for (auto& t : threads) {
t.join();
}
if (!found) {
strPrint = "Could not satisfy difficulty target";
return 1;
}
CDataStream ss(SER_NETWORK, PROTOCOL_VERSION);
ss << header;
strPrint = HexStr(ss);
return 0;
}
static int CommandLineUtil(int argc, char* argv[])
{
if (argc <= 1) return 1;
std::string strPrint;
int nRet = 0;
try {
while (argc > 1 && IsSwitchChar(argv[1][0]) && (argv[1][1] != 0)) {
--argc;
++argv;
}
char* command = argv[1];
if (strcmp(command, "grind") == 0) {
nRet = Grind(argc-2, argv+2, strPrint);
} else {
strPrint = strprintf("Unknown command %s", command);
nRet = 1;
}
}
catch (const std::exception& e) {
strPrint = std::string("error: ") + e.what();
nRet = EXIT_FAILURE;
}
catch (...) {
PrintExceptionContinue(nullptr, "CommandLineUtil()");
throw;
}
if (strPrint != "") {
tfm::format(nRet == 0 ? std::cout : std::cerr, "%s\n", strPrint);
}
return nRet;
}
int main(int argc, char* argv[])
{
SetupEnvironment();
try {
int ret = AppInitUtil(argc, argv);
if (ret != CONTINUE_EXECUTION)
return ret;
}
catch (const std::exception& e) {
PrintExceptionContinue(&e, "AppInitUtil()");
return EXIT_FAILURE;
} catch (...) {
PrintExceptionContinue(nullptr, "AppInitUtil()");
return EXIT_FAILURE;
}
int ret = EXIT_FAILURE;
try {
ret = CommandLineUtil(argc, argv);
}
catch (const std::exception& e) {
PrintExceptionContinue(&e, "CommandLineUtil()");
} catch (...) {
PrintExceptionContinue(nullptr, "CommandLineUtil()");
}
return ret;
}
<|endoftext|> |
<commit_before>/*
* Copyright 2014 National ICT Australia Limited (NICTA)
*
* 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 "bonmin_model.hpp"
#include "bonmin_minlp.hpp"
#include "common.hpp"
using namespace MadOpt;
namespace MadOpt {
struct BonminModelImpl {
BonminModelImpl(BonminModel* model){
Bapp = new Bonmin::BonminSetup();
Bapp->initializeOptionsAndJournalist();
bonmin_callback = new BonminUserClass(model);
}
~BonminModelImpl(){
delete Bapp;
}
Bonmin::BonminSetup* Bapp;
Ipopt::SmartPtr<Bonmin::TMINLP> bonmin_callback;
};
}
BonminModel::BonminModel(): Model(){
impl = new BonminModelImpl(this);
}
BonminModel::~BonminModel(){
delete impl;
}
void BonminModel::solve(){
if (timelimit >= 0)
setNumericOption("bonmin.time_limit", timelimit);
if (not show_solver){
setIntegerOption("print_level", 0);
setIntegerOption("bonmin.bb_log_level", 0);
setIntegerOption("bonmin.nlp_log_level", 0);
setStringOption("sb", "yes");
}
try {
impl->Bapp->initialize(GetRawPtr(impl->bonmin_callback));
Bonmin::Bab bb;
bb(impl->Bapp);
}
catch(Bonmin::TNLPSolver::UnsolvedError &E) {
solution.setStatus(Solution::SolverStatus::UNSOLVED_ERROR);
}
// impl->Bapp->initialize(GetRawPtr(impl->bonmin_callback));
// Bonmin::Bab bb;
// bb(impl->Bapp);
model_changed = false;
}
void BonminModel::setStringOption(std::string key, std::string value){
impl->Bapp->options()->SetStringValue(key, value);
}
void BonminModel::setNumericOption(std::string key, double value){
impl->Bapp->options()->SetNumericValue(key, value);
}
void BonminModel::setIntegerOption(std::string key, int value){
impl->Bapp->options()->SetIntegerValue(key, value);
}
<commit_msg>Solved #12<commit_after>/*
* Copyright 2014 National ICT Australia Limited (NICTA)
*
* 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 "bonmin_model.hpp"
#include "bonmin_minlp.hpp"
#include "common.hpp"
using namespace MadOpt;
namespace MadOpt {
struct BonminModelImpl {
BonminModelImpl(BonminModel* model){
Bapp = new Bonmin::BonminSetup();
Bapp->initializeOptionsAndJournalist();
bonmin_callback = new BonminUserClass(model);
}
~BonminModelImpl(){
delete Bapp;
}
Bonmin::BonminSetup* Bapp;
Ipopt::SmartPtr<Bonmin::TMINLP> bonmin_callback;
};
}
BonminModel::BonminModel(): Model(){
impl = new BonminModelImpl(this);
}
BonminModel::~BonminModel(){
delete impl;
}
void BonminModel::solve(){
if (timelimit >= 0)
setNumericOption("bonmin.time_limit", timelimit);
if (not show_solver){
setIntegerOption("print_level", 0);
setIntegerOption("bonmin.bb_log_level", 0);
setIntegerOption("bonmin.nlp_log_level", 0);
setStringOption("sb", "yes");
}
try {
impl->Bapp->initialize(GetRawPtr(impl->bonmin_callback));
Bonmin::Bab bb;
bb(impl->Bapp);
}
catch(Bonmin::TNLPSolver::UnsolvedError *E) {
solution.setStatus(Solution::SolverStatus::UNSOLVED_ERROR);
delete E;
}
catch(Bonmin::TNLPSolver::UnsolvedError &E) {
solution.setStatus(Solution::SolverStatus::UNSOLVED_ERROR);
}
// Other possible exceptions we may want to catch here:
// OsiTMINLPInterface::SimpleError &E
// CoinError &E
model_changed = false;
}
void BonminModel::setStringOption(std::string key, std::string value){
impl->Bapp->options()->SetStringValue(key, value);
}
void BonminModel::setNumericOption(std::string key, double value){
impl->Bapp->options()->SetNumericValue(key, value);
}
void BonminModel::setIntegerOption(std::string key, int value){
impl->Bapp->options()->SetIntegerValue(key, value);
}
<|endoftext|> |
<commit_before>/******
ootree: An easy to use and highly configurable C++ template tree class,
using STL container style interfaces.
Copyright (c) 2010 Erik Erlandson
Author: Erik Erlandson <erikerlandson@yahoo.com>
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
******/
#include <iostream>
using namespace std;
// use the mtree header and namespace
#include "ootree.h"
using namespace ootree;
int main(int argc, char** argv) {
return 0;
}
<commit_msg>Added 1st example -- hello world<commit_after>/******
ootree: An easy to use and highly configurable C++ template tree class,
using STL container style interfaces.
Copyright (c) 2010 Erik Erlandson
Author: Erik Erlandson <erikerlandson@yahoo.com>
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
******/
#include <iostream>
using namespace std;
// use the mtree header and namespace
#include "ootree.h"
using namespace ootree;
int main(int argc, char** argv) {
// declare a tree of strings
tree<const char*> t;
typedef tree<const char*>::bf_iterator bf_iterator;
// insert a string at root (ply 0)
t.insert("Hello");
// insert strings at ply 1
t.root().insert(" ");
t.root().insert("world");
// insert strings at ply 2
t.root()[0].insert("!");
t.root()[1].insert("\n");
// output data in breadth first order to print a traditional message
for (bf_iterator j(t.bf_begin()); j != t.bf_end(); ++j)
cout << j->data();
return 0;
}
<|endoftext|> |
<commit_before>/*
* Copyright (c) 2014 Advanced Micro Devices, Inc.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met: redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer;
* redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution;
* neither the name of the copyright holders nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
* Authors: Alexandru Dutu
*/
/**
* @file
* Definitions of page table
*/
#include <fstream>
#include <map>
#include <string>
#include "base/bitfield.hh"
#include "base/intmath.hh"
#include "base/trace.hh"
#include "config/the_isa.hh"
#include "debug/MMU.hh"
#include "mem/multi_level_page_table.hh"
#include "sim/faults.hh"
#include "sim/sim_object.hh"
using namespace std;
using namespace TheISA;
template <class ISAOps>
MultiLevelPageTable<ISAOps>::MultiLevelPageTable(const std::string &__name,
uint64_t _pid, System *_sys)
: PageTableBase(__name, _pid), system(_sys),
logLevelSize(PageTableLayout),
numLevels(logLevelSize.size())
{
}
template <class ISAOps>
MultiLevelPageTable<ISAOps>::~MultiLevelPageTable()
{
}
template <class ISAOps>
void
MultiLevelPageTable<ISAOps>::initState(ThreadContext* tc)
{
basePtr = pTableISAOps.getBasePtr(tc);
if (basePtr == 0) basePtr++;
DPRINTF(MMU, "basePtr: %d\n", basePtr);
system->pagePtr = basePtr;
/* setting first level of the page table */
uint64_t log_req_size = floorLog2(sizeof(PageTableEntry)) +
logLevelSize[numLevels-1];
assert(log_req_size >= PageShift);
uint64_t npages = 1 << (log_req_size - PageShift);
Addr paddr = system->allocPhysPages(npages);
PortProxy &p = system->physProxy;
p.memsetBlob(paddr, 0, npages << PageShift);
}
template <class ISAOps>
bool
MultiLevelPageTable<ISAOps>::walk(Addr vaddr, bool allocate, Addr &PTE_addr)
{
std::vector<uint64_t> offsets = pTableISAOps.getOffsets(vaddr);
Addr level_base = basePtr;
for (int i = numLevels - 1; i > 0; i--) {
Addr entry_addr = (level_base<<PageShift) +
offsets[i] * sizeof(PageTableEntry);
PortProxy &p = system->physProxy;
PageTableEntry entry = p.read<PageTableEntry>(entry_addr);
Addr next_entry_pnum = pTableISAOps.getPnum(entry);
if (next_entry_pnum == 0) {
if (!allocate) return false;
uint64_t log_req_size = floorLog2(sizeof(PageTableEntry)) +
logLevelSize[i-1];
assert(log_req_size >= PageShift);
uint64_t npages = 1 << (log_req_size - PageShift);
DPRINTF(MMU, "Allocating %d pages needed for entry in level %d\n",
npages, i - 1);
/* allocate new entry */
Addr next_entry_paddr = system->allocPhysPages(npages);
p.memsetBlob(next_entry_paddr, 0, npages << PageShift);
next_entry_pnum = next_entry_paddr >> PageShift;
pTableISAOps.setPnum(entry, next_entry_pnum);
pTableISAOps.setPTEFields(entry);
p.write<PageTableEntry>(entry_addr, entry);
}
DPRINTF(MMU, "Level %d base: %d offset: %d entry: %d\n",
i, level_base, offsets[i], next_entry_pnum);
level_base = next_entry_pnum;
}
PTE_addr = (level_base<<PageShift) +
offsets[0] * sizeof(PageTableEntry);
DPRINTF(MMU, "Returning PTE_addr: %x\n", PTE_addr);
return true;
}
template <class ISAOps>
void
MultiLevelPageTable<ISAOps>::map(Addr vaddr, Addr paddr,
int64_t size, bool clobber)
{
// starting address must be page aligned
assert(pageOffset(vaddr) == 0);
DPRINTF(MMU, "Allocating Page: %#x-%#x\n", vaddr, vaddr + size);
PortProxy &p = system->physProxy;
for (; size > 0; size -= pageSize, vaddr += pageSize, paddr += pageSize) {
Addr PTE_addr;
if (walk(vaddr, true, PTE_addr)) {
PageTableEntry PTE = p.read<PageTableEntry>(PTE_addr);
Addr entry_paddr = pTableISAOps.getPnum(PTE);
if (!clobber && entry_paddr == 0) {
pTableISAOps.setPnum(PTE, paddr >> PageShift);
pTableISAOps.setPTEFields(PTE);
p.write<PageTableEntry>(PTE_addr, PTE);
DPRINTF(MMU, "New mapping: %#x-%#x\n", vaddr, paddr);
} else {
fatal("addr 0x%x already mapped to %x", vaddr, entry_paddr);
}
eraseCacheEntry(vaddr);
updateCache(vaddr, TlbEntry(pid, vaddr, paddr));
}
}
}
template <class ISAOps>
void
MultiLevelPageTable<ISAOps>::remap(Addr vaddr, int64_t size, Addr new_vaddr)
{
assert(pageOffset(vaddr) == 0);
assert(pageOffset(new_vaddr) == 0);
DPRINTF(MMU, "moving pages from vaddr %08p to %08p, size = %d\n", vaddr,
new_vaddr, size);
PortProxy &p = system->physProxy;
for (; size > 0;
size -= pageSize, vaddr += pageSize, new_vaddr += pageSize)
{
Addr PTE_addr;
if (walk(vaddr, false, PTE_addr)) {
PageTableEntry PTE = p.read<PageTableEntry>(PTE_addr);
Addr paddr = pTableISAOps.getPnum(PTE);
if (paddr == 0) {
fatal("Page fault while remapping");
} else {
/* unmapping vaddr */
pTableISAOps.setPnum(PTE, 0);
p.write<PageTableEntry>(PTE_addr, PTE);
/* maping new_vaddr */
Addr new_PTE_addr;
walk(new_vaddr, true, new_PTE_addr);
PageTableEntry new_PTE = p.read<PageTableEntry>(new_PTE_addr);
pTableISAOps.setPnum(new_PTE, paddr>>PageShift);
pTableISAOps.setPTEFields(new_PTE);
p.write<PageTableEntry>(new_PTE_addr, new_PTE);
DPRINTF(MMU, "Remapping: %#x-%#x\n", vaddr, new_PTE_addr);
}
eraseCacheEntry(vaddr);
updateCache(new_vaddr, TlbEntry(pid, new_vaddr, paddr));
} else {
fatal("Page fault while remapping");
}
}
}
template <class ISAOps>
void
MultiLevelPageTable<ISAOps>::unmap(Addr vaddr, int64_t size)
{
assert(pageOffset(vaddr) == 0);
DPRINTF(MMU, "Unmapping page: %#x-%#x\n", vaddr, vaddr+ size);
PortProxy &p = system->physProxy;
for (; size > 0; size -= pageSize, vaddr += pageSize) {
Addr PTE_addr;
if (walk(vaddr, false, PTE_addr)) {
PageTableEntry PTE = p.read<PageTableEntry>(PTE_addr);
Addr paddr = pTableISAOps.getPnum(PTE);
if (paddr == 0) {
fatal("PageTable::allocate: address 0x%x not mapped", vaddr);
} else {
pTableISAOps.setPnum(PTE, 0);
p.write<PageTableEntry>(PTE_addr, PTE);
DPRINTF(MMU, "Unmapping: %#x\n", vaddr);
}
eraseCacheEntry(vaddr);
} else {
fatal("Page fault while unmapping");
}
}
}
template <class ISAOps>
bool
MultiLevelPageTable<ISAOps>::isUnmapped(Addr vaddr, int64_t size)
{
// starting address must be page aligned
assert(pageOffset(vaddr) == 0);
PortProxy &p = system->physProxy;
for (; size > 0; size -= pageSize, vaddr += pageSize) {
Addr PTE_addr;
if (walk(vaddr, false, PTE_addr)) {
PageTableEntry PTE = p.read<PageTableEntry>(PTE_addr);
if (pTableISAOps.getPnum(PTE) != 0)
return false;
}
}
return true;
}
template <class ISAOps>
bool
MultiLevelPageTable<ISAOps>::lookup(Addr vaddr, TlbEntry &entry)
{
Addr page_addr = pageAlign(vaddr);
if (pTableCache[0].valid && pTableCache[0].vaddr == page_addr) {
entry = pTableCache[0].entry;
return true;
}
if (pTableCache[1].valid && pTableCache[1].vaddr == page_addr) {
entry = pTableCache[1].entry;
return true;
}
if (pTableCache[2].valid && pTableCache[2].vaddr == page_addr) {
entry = pTableCache[2].entry;
return true;
}
DPRINTF(MMU, "lookup page_addr: %#x\n", page_addr);
Addr PTE_addr;
if (walk(page_addr, false, PTE_addr)) {
PortProxy &p = system->physProxy;
PageTableEntry PTE = p.read<PageTableEntry>(PTE_addr);
Addr pnum = pTableISAOps.getPnum(PTE);
if (pnum == 0)
return false;
entry = TlbEntry(pid, vaddr, pnum << PageShift);
updateCache(page_addr, entry);
} else {
return false;
}
return true;
}
template <class ISAOps>
void
MultiLevelPageTable<ISAOps>::serialize(std::ostream &os)
{
/** Since, the page table is stored in system memory
* which is serialized separately, we will serialize
* just the base pointer
*/
paramOut(os, "ptable.pointer", basePtr);
}
template <class ISAOps>
void
MultiLevelPageTable<ISAOps>::unserialize(Checkpoint *cp,
const std::string §ion)
{
paramIn(cp, section, "ptable.pointer", basePtr);
}
<commit_msg>mem: Multi Level Page Table bug fix<commit_after>/*
* Copyright (c) 2014 Advanced Micro Devices, Inc.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met: redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer;
* redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution;
* neither the name of the copyright holders nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
* Authors: Alexandru Dutu
*/
/**
* @file
* Definitions of page table
*/
#include <fstream>
#include <map>
#include <string>
#include "base/bitfield.hh"
#include "base/intmath.hh"
#include "base/trace.hh"
#include "config/the_isa.hh"
#include "debug/MMU.hh"
#include "mem/multi_level_page_table.hh"
#include "sim/faults.hh"
#include "sim/sim_object.hh"
using namespace std;
using namespace TheISA;
template <class ISAOps>
MultiLevelPageTable<ISAOps>::MultiLevelPageTable(const std::string &__name,
uint64_t _pid, System *_sys)
: PageTableBase(__name, _pid), system(_sys),
logLevelSize(PageTableLayout),
numLevels(logLevelSize.size())
{
}
template <class ISAOps>
MultiLevelPageTable<ISAOps>::~MultiLevelPageTable()
{
}
template <class ISAOps>
void
MultiLevelPageTable<ISAOps>::initState(ThreadContext* tc)
{
basePtr = pTableISAOps.getBasePtr(tc);
if (basePtr == 0) basePtr++;
DPRINTF(MMU, "basePtr: %d\n", basePtr);
system->pagePtr = basePtr;
/* setting first level of the page table */
uint64_t log_req_size = floorLog2(sizeof(PageTableEntry)) +
logLevelSize[numLevels-1];
assert(log_req_size >= PageShift);
uint64_t npages = 1 << (log_req_size - PageShift);
Addr paddr = system->allocPhysPages(npages);
PortProxy &p = system->physProxy;
p.memsetBlob(paddr, 0, npages << PageShift);
}
template <class ISAOps>
bool
MultiLevelPageTable<ISAOps>::walk(Addr vaddr, bool allocate, Addr &PTE_addr)
{
std::vector<uint64_t> offsets = pTableISAOps.getOffsets(vaddr);
Addr level_base = basePtr;
for (int i = numLevels - 1; i > 0; i--) {
Addr entry_addr = (level_base<<PageShift) +
offsets[i] * sizeof(PageTableEntry);
PortProxy &p = system->physProxy;
PageTableEntry entry = p.read<PageTableEntry>(entry_addr);
Addr next_entry_pnum = pTableISAOps.getPnum(entry);
if (next_entry_pnum == 0) {
if (!allocate) return false;
uint64_t log_req_size = floorLog2(sizeof(PageTableEntry)) +
logLevelSize[i-1];
assert(log_req_size >= PageShift);
uint64_t npages = 1 << (log_req_size - PageShift);
DPRINTF(MMU, "Allocating %d pages needed for entry in level %d\n",
npages, i - 1);
/* allocate new entry */
Addr next_entry_paddr = system->allocPhysPages(npages);
p.memsetBlob(next_entry_paddr, 0, npages << PageShift);
next_entry_pnum = next_entry_paddr >> PageShift;
pTableISAOps.setPnum(entry, next_entry_pnum);
pTableISAOps.setPTEFields(entry);
p.write<PageTableEntry>(entry_addr, entry);
}
DPRINTF(MMU, "Level %d base: %d offset: %d entry: %d\n",
i, level_base, offsets[i], next_entry_pnum);
level_base = next_entry_pnum;
}
PTE_addr = (level_base<<PageShift) +
offsets[0] * sizeof(PageTableEntry);
DPRINTF(MMU, "Returning PTE_addr: %x\n", PTE_addr);
return true;
}
template <class ISAOps>
void
MultiLevelPageTable<ISAOps>::map(Addr vaddr, Addr paddr,
int64_t size, bool clobber)
{
// starting address must be page aligned
assert(pageOffset(vaddr) == 0);
DPRINTF(MMU, "Allocating Page: %#x-%#x\n", vaddr, vaddr + size);
PortProxy &p = system->physProxy;
for (; size > 0; size -= pageSize, vaddr += pageSize, paddr += pageSize) {
Addr PTE_addr;
if (walk(vaddr, true, PTE_addr)) {
PageTableEntry PTE = p.read<PageTableEntry>(PTE_addr);
Addr entry_paddr = pTableISAOps.getPnum(PTE);
if (!clobber && entry_paddr != 0) {
fatal("addr 0x%x already mapped to %x", vaddr, entry_paddr);
}
pTableISAOps.setPnum(PTE, paddr >> PageShift);
pTableISAOps.setPTEFields(PTE);
p.write<PageTableEntry>(PTE_addr, PTE);
DPRINTF(MMU, "New mapping: %#x-%#x\n", vaddr, paddr);
eraseCacheEntry(vaddr);
updateCache(vaddr, TlbEntry(pid, vaddr, paddr));
}
}
}
template <class ISAOps>
void
MultiLevelPageTable<ISAOps>::remap(Addr vaddr, int64_t size, Addr new_vaddr)
{
assert(pageOffset(vaddr) == 0);
assert(pageOffset(new_vaddr) == 0);
DPRINTF(MMU, "moving pages from vaddr %08p to %08p, size = %d\n", vaddr,
new_vaddr, size);
PortProxy &p = system->physProxy;
for (; size > 0;
size -= pageSize, vaddr += pageSize, new_vaddr += pageSize)
{
Addr PTE_addr;
if (walk(vaddr, false, PTE_addr)) {
PageTableEntry PTE = p.read<PageTableEntry>(PTE_addr);
Addr paddr = pTableISAOps.getPnum(PTE);
if (paddr == 0) {
fatal("Page fault while remapping");
} else {
/* unmapping vaddr */
pTableISAOps.setPnum(PTE, 0);
p.write<PageTableEntry>(PTE_addr, PTE);
/* maping new_vaddr */
Addr new_PTE_addr;
walk(new_vaddr, true, new_PTE_addr);
PageTableEntry new_PTE = p.read<PageTableEntry>(new_PTE_addr);
pTableISAOps.setPnum(new_PTE, paddr>>PageShift);
pTableISAOps.setPTEFields(new_PTE);
p.write<PageTableEntry>(new_PTE_addr, new_PTE);
DPRINTF(MMU, "Remapping: %#x-%#x\n", vaddr, new_PTE_addr);
}
eraseCacheEntry(vaddr);
updateCache(new_vaddr, TlbEntry(pid, new_vaddr, paddr));
} else {
fatal("Page fault while remapping");
}
}
}
template <class ISAOps>
void
MultiLevelPageTable<ISAOps>::unmap(Addr vaddr, int64_t size)
{
assert(pageOffset(vaddr) == 0);
DPRINTF(MMU, "Unmapping page: %#x-%#x\n", vaddr, vaddr+ size);
PortProxy &p = system->physProxy;
for (; size > 0; size -= pageSize, vaddr += pageSize) {
Addr PTE_addr;
if (walk(vaddr, false, PTE_addr)) {
PageTableEntry PTE = p.read<PageTableEntry>(PTE_addr);
Addr paddr = pTableISAOps.getPnum(PTE);
if (paddr == 0) {
fatal("PageTable::allocate: address 0x%x not mapped", vaddr);
} else {
pTableISAOps.setPnum(PTE, 0);
p.write<PageTableEntry>(PTE_addr, PTE);
DPRINTF(MMU, "Unmapping: %#x\n", vaddr);
}
eraseCacheEntry(vaddr);
} else {
fatal("Page fault while unmapping");
}
}
}
template <class ISAOps>
bool
MultiLevelPageTable<ISAOps>::isUnmapped(Addr vaddr, int64_t size)
{
// starting address must be page aligned
assert(pageOffset(vaddr) == 0);
PortProxy &p = system->physProxy;
for (; size > 0; size -= pageSize, vaddr += pageSize) {
Addr PTE_addr;
if (walk(vaddr, false, PTE_addr)) {
PageTableEntry PTE = p.read<PageTableEntry>(PTE_addr);
if (pTableISAOps.getPnum(PTE) != 0)
return false;
}
}
return true;
}
template <class ISAOps>
bool
MultiLevelPageTable<ISAOps>::lookup(Addr vaddr, TlbEntry &entry)
{
Addr page_addr = pageAlign(vaddr);
if (pTableCache[0].valid && pTableCache[0].vaddr == page_addr) {
entry = pTableCache[0].entry;
return true;
}
if (pTableCache[1].valid && pTableCache[1].vaddr == page_addr) {
entry = pTableCache[1].entry;
return true;
}
if (pTableCache[2].valid && pTableCache[2].vaddr == page_addr) {
entry = pTableCache[2].entry;
return true;
}
DPRINTF(MMU, "lookup page_addr: %#x\n", page_addr);
Addr PTE_addr;
if (walk(page_addr, false, PTE_addr)) {
PortProxy &p = system->physProxy;
PageTableEntry PTE = p.read<PageTableEntry>(PTE_addr);
Addr pnum = pTableISAOps.getPnum(PTE);
if (pnum == 0)
return false;
entry = TlbEntry(pid, vaddr, pnum << PageShift);
updateCache(page_addr, entry);
} else {
return false;
}
return true;
}
template <class ISAOps>
void
MultiLevelPageTable<ISAOps>::serialize(std::ostream &os)
{
/** Since, the page table is stored in system memory
* which is serialized separately, we will serialize
* just the base pointer
*/
paramOut(os, "ptable.pointer", basePtr);
}
template <class ISAOps>
void
MultiLevelPageTable<ISAOps>::unserialize(Checkpoint *cp,
const std::string §ion)
{
paramIn(cp, section, "ptable.pointer", basePtr);
}
<|endoftext|> |
<commit_before>// UiaDll.cpp : Defines the exported functions for the DLL application.
//
#include "stdafx.h"
#include "Locator.h"
#include "DynamicAssemblyResolver.h"
#include "StringHelper.h"
IUIAutomation* getGlobalIUIAutomation() ;
using namespace RAutomation::UIA;
using namespace RAutomation::UIA::Controls;
using namespace RAutomation::UIA::Extensions;
using namespace System::Diagnostics;
extern "C" {
__declspec(dllexport) void initialize(char* privateAssemblyDirectory) {
DynamicAssemblyResolver::PrivatePath = gcnew String(privateAssemblyDirectory);
}
__declspec ( dllexport ) bool ElementExists(const FindInformation& findInformation) {
return Element::Exists(Locator::FindFor(findInformation));
}
__declspec ( dllexport ) int NativeWindowHandle(const FindInformation& findInformation) {
return Element::NativeWindowHandle(Locator::FindFor(findInformation));
}
__declspec ( dllexport ) int HandleFromPoint(int xCoord, int yCoord) {
auto element = AutomationElement::FromPoint(Point((double)xCoord, (double)yCoord));
return Element::NativeWindowHandle(element);
}
__declspec ( dllexport ) int BoundingRectangle(const FindInformation& findInformation, long *rectangle) {
try {
auto boundary = Element::BoundingRectangle(Locator::FindFor(findInformation));
rectangle[0] = (long)boundary.Left;
rectangle[1] = (long)boundary.Top;
rectangle[2] = (long)boundary.Right;
rectangle[3] = (long)boundary.Bottom;
return 1;
}
catch(Exception^ e) {
Console::WriteLine("BoundingRectangle: {0}", e->Message);
return 0;
}
}
__declspec ( dllexport ) int ControlType(const FindInformation& findInformation) {
try {
return Element::ControlType(Locator::FindFor(findInformation))->Id;
} catch(Exception^ e) {
Console::WriteLine("ControlType: {0}", e->Message);
return 0;
}
}
__declspec ( dllexport ) int ProcessId(const FindInformation& findInformation) {
try {
return Element::ProcessId(Locator::FindFor(findInformation));
} catch(Exception^ e) {
Console::WriteLine("ProcessId: {0}", e->Message);
return 0;
}
}
__declspec ( dllexport ) void Name(const FindInformation& findInformation, char* name, const int nameLength) {
try {
auto currentName = Element::Name(Locator::FindFor(findInformation));
StringHelper::CopyToUnmanagedString(currentName, name, nameLength);
} catch(Exception^ e) {
Console::WriteLine("Name: {0}", e->Message);
}
}
__declspec ( dllexport ) void ClassName(const FindInformation& findInformation, char* className, const int classNameLength) {
try {
auto currentClassName = Element::ClassName(Locator::FindFor(findInformation));
StringHelper::CopyToUnmanagedString(currentClassName, className, classNameLength);
} catch(Exception^ e) {
Console::WriteLine("ClassName: {0}", e->Message);
}
}
__declspec ( dllexport ) bool IsEnabled(const FindInformation& findInformation) {
try {
return Element::IsEnabled(Locator::FindFor(findInformation));
} catch(Exception^ e) {
Console::WriteLine("IsEnabled: {0}", e->Message);
return false;
}
}
__declspec ( dllexport ) bool IsFocused(const FindInformation& findInformation) {
try {
return Element::IsFocused(Locator::FindFor(findInformation));
} catch(Exception^ e) {
Console::WriteLine("IsFocused: {0}", e->Message);
return false;
}
}
__declspec ( dllexport ) bool SetControlFocus(const FindInformation& findInformation) {
try {
Locator::FindFor(findInformation)->SetFocus();
return true;
} catch(Exception^ e) {
Console::WriteLine("IsFocused: {0}", e->Message);
return false;
}
}
__declspec ( dllexport ) int GetClassNames(const FindInformation& findInformation, const char* classNames[]) {
auto allChildren = Locator::FindFor(findInformation)->FindAll(System::Windows::Automation::TreeScope::Subtree, Condition::TrueCondition);
if( NULL != classNames ) {
StringHelper::CopyClassNames(allChildren, classNames);
}
return allChildren->Count;
}
__declspec ( dllexport ) IUIAutomationElement *RA_ElementFromHandle(HWND hwnd) {
IUIAutomationElement *pElement ;
HRESULT hr = getGlobalIUIAutomation()->ElementFromHandle(hwnd, &pElement) ;
if (SUCCEEDED(hr))
return pElement ;
else {
printf("RA_ElementFromHandle: Cannot find element from handle 0x%x. HRESULT was 0x%x\r\n", hwnd, hr) ;
return NULL ;
}
}
__declspec ( dllexport ) int RA_CurrentIsOffscreen(IUIAutomationElement *pElement, int *visible) {
BOOL offscreen;
HRESULT hr = pElement->get_CurrentIsOffscreen(&offscreen) ;
if (SUCCEEDED(hr)) {
if(offscreen){
*visible = 1;
}
else
{
*visible = 0;
}
return 1;
}
else {
printf("RA_CurrentIsOffscreen: get_CurrentIsOffscreen failed 0x%x\r\n", hr) ;
return 0 ;
}
}
__declspec ( dllexport ) bool IsSet(const FindInformation& findInformation) {
try {
return Element::IsToggled(Locator::FindFor(findInformation));
} catch(Exception^ e) {
Debug::WriteLine("IsSet: {0}", e->Message);
return false;
}
}
__declspec ( dllexport ) bool IsSelected(const FindInformation& findInformation) {
try {
return Element::IsSelected(Locator::FindFor(findInformation));
} catch(Exception^ e) {
Debug::WriteLine("IsSelected: {0}", e->Message);
return false;
}
}
__declspec ( dllexport ) bool RA_Click(const FindInformation& findInformation, char* errorInfo, const int errorInfoSize) {
try {
return Clicker::Click(Locator::FindFor(findInformation));
} catch(Exception^ e) {
if( errorInfo ) {
StringHelper::CopyToUnmanagedString(e->ToString(), errorInfo, errorInfoSize);
}
return false;
}
}
__declspec ( dllexport ) void RA_ExpandItemByValue(const FindInformation& findInformation, const char* whichItem) {
try {
auto expander = gcnew Expander(Locator::FindFor(findInformation));
expander->Expand(gcnew String(whichItem));
} catch(Exception^ e) {
Console::WriteLine(e->ToString());
}
}
__declspec ( dllexport ) void RA_ExpandItemByIndex(const FindInformation& findInformation, const int whichItemIndex) {
try {
auto expander = gcnew Expander(Locator::FindFor(findInformation));
expander->Expand(whichItemIndex);
} catch(Exception^ e) {
Console::WriteLine(e->ToString());
}
}
__declspec ( dllexport ) void RA_CollapseItemByValue(const FindInformation& findInformation, const char* whichItem) {
try {
auto collapser = gcnew Collapser(Locator::FindFor(findInformation));
collapser->Collapse(gcnew String(whichItem));
} catch(Exception^ e) {
Console::WriteLine(e->ToString());
}
}
__declspec ( dllexport ) void RA_CollapseItemByIndex(const FindInformation& findInformation, const int whichItemIndex) {
try {
auto collapser = gcnew Collapser(Locator::FindFor(findInformation));
collapser->Collapse(whichItemIndex);
} catch(Exception^ e) {
Console::WriteLine(e->ToString());
}
}
}
<commit_msg>Revert "get rid of RA_ClickMouse / RA_MoveMouse"<commit_after>// UiaDll.cpp : Defines the exported functions for the DLL application.
//
#include "stdafx.h"
#include "Locator.h"
#include "DynamicAssemblyResolver.h"
#include "StringHelper.h"
IUIAutomation* getGlobalIUIAutomation() ;
using namespace RAutomation::UIA;
using namespace RAutomation::UIA::Controls;
using namespace RAutomation::UIA::Extensions;
using namespace System::Diagnostics;
extern "C" {
__declspec(dllexport) void initialize(char* privateAssemblyDirectory) {
DynamicAssemblyResolver::PrivatePath = gcnew String(privateAssemblyDirectory);
}
__declspec ( dllexport ) bool ElementExists(const FindInformation& findInformation) {
return Element::Exists(Locator::FindFor(findInformation));
}
__declspec ( dllexport ) int NativeWindowHandle(const FindInformation& findInformation) {
return Element::NativeWindowHandle(Locator::FindFor(findInformation));
}
__declspec ( dllexport ) int HandleFromPoint(int xCoord, int yCoord) {
auto element = AutomationElement::FromPoint(Point((double)xCoord, (double)yCoord));
return Element::NativeWindowHandle(element);
}
__declspec ( dllexport ) int BoundingRectangle(const FindInformation& findInformation, long *rectangle) {
try {
auto boundary = Element::BoundingRectangle(Locator::FindFor(findInformation));
rectangle[0] = (long)boundary.Left;
rectangle[1] = (long)boundary.Top;
rectangle[2] = (long)boundary.Right;
rectangle[3] = (long)boundary.Bottom;
return 1;
}
catch(Exception^ e) {
Console::WriteLine("BoundingRectangle: {0}", e->Message);
return 0;
}
}
__declspec ( dllexport ) int ControlType(const FindInformation& findInformation) {
try {
return Element::ControlType(Locator::FindFor(findInformation))->Id;
} catch(Exception^ e) {
Console::WriteLine("ControlType: {0}", e->Message);
return 0;
}
}
__declspec ( dllexport ) int ProcessId(const FindInformation& findInformation) {
try {
return Element::ProcessId(Locator::FindFor(findInformation));
} catch(Exception^ e) {
Console::WriteLine("ProcessId: {0}", e->Message);
return 0;
}
}
__declspec ( dllexport ) void Name(const FindInformation& findInformation, char* name, const int nameLength) {
try {
auto currentName = Element::Name(Locator::FindFor(findInformation));
StringHelper::CopyToUnmanagedString(currentName, name, nameLength);
} catch(Exception^ e) {
Console::WriteLine("Name: {0}", e->Message);
}
}
__declspec ( dllexport ) void ClassName(const FindInformation& findInformation, char* className, const int classNameLength) {
try {
auto currentClassName = Element::ClassName(Locator::FindFor(findInformation));
StringHelper::CopyToUnmanagedString(currentClassName, className, classNameLength);
} catch(Exception^ e) {
Console::WriteLine("ClassName: {0}", e->Message);
}
}
__declspec ( dllexport ) bool IsEnabled(const FindInformation& findInformation) {
try {
return Element::IsEnabled(Locator::FindFor(findInformation));
} catch(Exception^ e) {
Console::WriteLine("IsEnabled: {0}", e->Message);
return false;
}
}
__declspec ( dllexport ) bool IsFocused(const FindInformation& findInformation) {
try {
return Element::IsFocused(Locator::FindFor(findInformation));
} catch(Exception^ e) {
Console::WriteLine("IsFocused: {0}", e->Message);
return false;
}
}
__declspec ( dllexport ) bool SetControlFocus(const FindInformation& findInformation) {
try {
Locator::FindFor(findInformation)->SetFocus();
return true;
} catch(Exception^ e) {
Console::WriteLine("IsFocused: {0}", e->Message);
return false;
}
}
__declspec ( dllexport ) int GetClassNames(const FindInformation& findInformation, const char* classNames[]) {
auto allChildren = Locator::FindFor(findInformation)->FindAll(System::Windows::Automation::TreeScope::Subtree, Condition::TrueCondition);
if( NULL != classNames ) {
StringHelper::CopyClassNames(allChildren, classNames);
}
return allChildren->Count;
}
__declspec ( dllexport ) IUIAutomationElement *RA_ElementFromHandle(HWND hwnd) {
IUIAutomationElement *pElement ;
HRESULT hr = getGlobalIUIAutomation()->ElementFromHandle(hwnd, &pElement) ;
if (SUCCEEDED(hr))
return pElement ;
else {
printf("RA_ElementFromHandle: Cannot find element from handle 0x%x. HRESULT was 0x%x\r\n", hwnd, hr) ;
return NULL ;
}
}
__declspec ( dllexport ) long RA_ClickMouse() {
mouse_event(MOUSEEVENTF_LEFTDOWN, 0, 0, 0, 0);
mouse_event(MOUSEEVENTF_LEFTUP, 0, 0, 0, 0);
return 0;
}
__declspec ( dllexport ) long RA_MoveMouse(int x, int y) {
return SetCursorPos(x,y);
}
__declspec ( dllexport ) int RA_CurrentIsOffscreen(IUIAutomationElement *pElement, int *visible) {
BOOL offscreen;
HRESULT hr = pElement->get_CurrentIsOffscreen(&offscreen) ;
if (SUCCEEDED(hr)) {
if(offscreen){
*visible = 1;
}
else
{
*visible = 0;
}
return 1;
}
else {
printf("RA_CurrentIsOffscreen: get_CurrentIsOffscreen failed 0x%x\r\n", hr) ;
return 0 ;
}
}
__declspec ( dllexport ) bool IsSet(const FindInformation& findInformation) {
try {
return Element::IsToggled(Locator::FindFor(findInformation));
} catch(Exception^ e) {
Debug::WriteLine("IsSet: {0}", e->Message);
return false;
}
}
__declspec ( dllexport ) bool IsSelected(const FindInformation& findInformation) {
try {
return Element::IsSelected(Locator::FindFor(findInformation));
} catch(Exception^ e) {
Debug::WriteLine("IsSelected: {0}", e->Message);
return false;
}
}
__declspec ( dllexport ) bool RA_Click(const FindInformation& findInformation, char* errorInfo, const int errorInfoSize) {
try {
return Clicker::Click(Locator::FindFor(findInformation));
} catch(Exception^ e) {
if( errorInfo ) {
StringHelper::CopyToUnmanagedString(e->ToString(), errorInfo, errorInfoSize);
}
return false;
}
}
__declspec ( dllexport ) void RA_ExpandItemByValue(const FindInformation& findInformation, const char* whichItem) {
try {
auto expander = gcnew Expander(Locator::FindFor(findInformation));
expander->Expand(gcnew String(whichItem));
} catch(Exception^ e) {
Console::WriteLine(e->ToString());
}
}
__declspec ( dllexport ) void RA_ExpandItemByIndex(const FindInformation& findInformation, const int whichItemIndex) {
try {
auto expander = gcnew Expander(Locator::FindFor(findInformation));
expander->Expand(whichItemIndex);
} catch(Exception^ e) {
Console::WriteLine(e->ToString());
}
}
__declspec ( dllexport ) void RA_CollapseItemByValue(const FindInformation& findInformation, const char* whichItem) {
try {
auto collapser = gcnew Collapser(Locator::FindFor(findInformation));
collapser->Collapse(gcnew String(whichItem));
} catch(Exception^ e) {
Console::WriteLine(e->ToString());
}
}
__declspec ( dllexport ) void RA_CollapseItemByIndex(const FindInformation& findInformation, const int whichItemIndex) {
try {
auto collapser = gcnew Collapser(Locator::FindFor(findInformation));
collapser->Collapse(whichItemIndex);
} catch(Exception^ e) {
Console::WriteLine(e->ToString());
}
}
}
<|endoftext|> |
<commit_before>#include "calc.h"
#include <stdexcept>
#include <sstream>
#include <istream>
#include <limits>
int sign(const int i) {
return (int(0) < i) - (i < int(0));
}
void throw_overflow_if(const bool condition) {
if (condition) throw std::invalid_argument { "overflow" };
}
// Calculates the result of two numbers a and b and basic math operator.
int calc(const int a, const int b, const char operator_symbol) {
using int_limits = std::numeric_limits<int>;
const int int_max { int_limits::max() }, int_min { int_limits::min() };
switch (operator_symbol) {
case '*': {
int result { a * b };
throw_overflow_if((sign(a) * sign(b) != sign(result)) || (a != 0 && result / a != b));
return result;
}
case '/':
if (b == 0) throw std::domain_error{"division by zero"};
return a / b;
case '+':
throw_overflow_if((a >= 0) && (int_max - a < b));
throw_overflow_if((a < 0) && (b < int_min - a));
return a + b;
case '-': {
throw_overflow_if((a >= 0) && (int_max - a < -b));
throw_overflow_if((a < 0) && (-b < int_min - a));
return a - b;
}
case '%':
if (b == 0) throw std::domain_error{"division by zero"};
return a % b;
}
auto reason = std::string("invalid operator: ");
reason.push_back(operator_symbol);
throw std::invalid_argument{reason};
}
int calc(std::istream &input) {
int a {0}, b {0};
char operator_symbol { };
input >> a >> operator_symbol >> b;
if (input.fail())
throw std::invalid_argument{ "malformed input term"};
return calc(a, b, operator_symbol);
}
<commit_msg>recognize malformed input terms<commit_after>#include "calc.h"
#include <stdexcept>
#include <sstream>
#include <istream>
#include <limits>
int sign(const int i) {
return (int(0) < i) - (i < int(0));
}
void throw_overflow_if(const bool condition) {
if (condition) throw std::invalid_argument { "overflow" };
}
// Calculates the result of two numbers a and b and basic math operator.
int calc(const int a, const int b, const char operator_symbol) {
using int_limits = std::numeric_limits<int>;
const int int_max { int_limits::max() }, int_min { int_limits::min() };
switch (operator_symbol) {
case '*': {
int result { a * b };
throw_overflow_if((sign(a) * sign(b) != sign(result)) || (a != 0 && result / a != b));
return result;
}
case '/':
if (b == 0) throw std::domain_error{"division by zero"};
return a / b;
case '+':
throw_overflow_if((a >= 0) && (int_max - a < b));
throw_overflow_if((a < 0) && (b < int_min - a));
return a + b;
case '-': {
throw_overflow_if((a >= 0) && (int_max - a < -b));
throw_overflow_if((a < 0) && (-b < int_min - a));
return a - b;
}
case '%':
if (b == 0) throw std::domain_error{"division by zero"};
return a % b;
}
auto reason = std::string("invalid operator: ");
reason.push_back(operator_symbol);
throw std::invalid_argument{reason};
}
int calc(std::istream &input) {
int a {0}, b {0};
char operator_symbol { };
std::string term {};
std::getline(input, term);
std::istringstream term_input { term };
term_input >> a >> operator_symbol >> b;
if (term_input.fail() || !term_input.eof())
throw std::invalid_argument{ "malformed input term"};
return calc(a, b, operator_symbol);
}
<|endoftext|> |
<commit_before>/************************************************************
cvcontourtree.cpp -
$Author: lsxi $
Copyright (C) 2007 Masakazu Yonekura
************************************************************/
#include "cvcontour.h"
/*
* Document-class: OpenCV::CvContourTree
*
* Contour tree. CvContour#create_tree
*
* C structure is here.
* typedef struct CvContourTree {
* CV_SEQUENCE_FIELDS()
* CvPoint p1;
* CvPoint p2;
* } CvContourTree;
*
*/
__NAMESPACE_BEGIN_OPENCV
__NAMESPACE_BEGIN_CVCONTOURTREE
VALUE rb_klass;
VALUE
rb_class()
{
return rb_klass;
}
void
define_ruby_class()
{
if (rb_klass)
return;
/*
* opencv = rb_define_module("OpenCV");
* cvseq = rb_define_class_under(opencv, "CvSeq");
*
* note: this comment is used by rdoc.
*/
VALUE opencv = rb_module_opencv();
VALUE cvseq = cCvSeq::rb_class();
rb_klass = rb_define_class_under(opencv, "CvContourTree", cvseq);
rb_define_method(rb_klass, "p1", RUBY_METHOD_FUNC(rb_p1), 0);
rb_define_method(rb_klass, "p2", RUBY_METHOD_FUNC(rb_p2), 0);
rb_define_method(rb_klass, "contour", RUBY_METHOD_FUNC(rb_contour), 1);
}
VALUE
rb_p1(VALUE self)
{
return REFER_OBJECT(cCvPoint::rb_class(), &CVCONTOURTREE(self)->p1, self);
}
VALUE
rb_p2(VALUE self)
{
return REFER_OBJECT(cCvPoint::rb_class(), &CVCONTOURTREE(self)->p2, self);
}
/*
* call-seq:
* contour(<i>[criteria = 0]</i>) -> cvcontour
*
* Restores the contour from its binary tree representation.
* The parameter criteria determines the accuracy and/or the number of tree levels
* used for reconstruction, so it is possible to build approximated contour.
*/
VALUE
rb_contour(VALUE self, VALUE criteria)
{
VALUE storage = cCvMemStorage::new_object();
CvSeq *contour = NULL;
try {
contour = cvContourFromContourTree(CVCONTOURTREE(self), CVMEMSTORAGE(storage),
VALUE_TO_CVTERMCRITERIA(criteria));
}
catch (cv::Exception& e) {
raise_cverror(e);
}
return cCvSeq::new_sequence(cCvContour::rb_class(), contour, cCvPoint::rb_class(), storage);
}
__NAMESPACE_END_CVCONTOURTREE
__NAMESPACE_END_OPENCV
<commit_msg>add documents of CvContourTree<commit_after>/************************************************************
cvcontourtree.cpp -
$Author: lsxi $
Copyright (C) 2007 Masakazu Yonekura
************************************************************/
#include "cvcontour.h"
/*
* Document-class: OpenCV::CvContourTree
*
* Contour tree
* @see CvContour#create_tree
*/
__NAMESPACE_BEGIN_OPENCV
__NAMESPACE_BEGIN_CVCONTOURTREE
VALUE rb_klass;
VALUE
rb_class()
{
return rb_klass;
}
void
define_ruby_class()
{
if (rb_klass)
return;
/*
* opencv = rb_define_module("OpenCV");
* cvseq = rb_define_class_under(opencv, "CvSeq");
*
* note: this comment is used by rdoc.
*/
VALUE opencv = rb_module_opencv();
VALUE cvseq = cCvSeq::rb_class();
rb_klass = rb_define_class_under(opencv, "CvContourTree", cvseq);
rb_define_method(rb_klass, "p1", RUBY_METHOD_FUNC(rb_p1), 0);
rb_define_method(rb_klass, "p2", RUBY_METHOD_FUNC(rb_p2), 0);
rb_define_method(rb_klass, "contour", RUBY_METHOD_FUNC(rb_contour), 1);
}
/*
* Returns the first point of the binary tree root segment
* @overload p1
* @return [CvPoint] First point of the binary tree root segment
*/
VALUE
rb_p1(VALUE self)
{
return REFER_OBJECT(cCvPoint::rb_class(), &CVCONTOURTREE(self)->p1, self);
}
/*
* Returns the last point of the binary tree root segment
* @overload p2
* @return [CvPoint] Last point of the binary tree root segment
*/
VALUE
rb_p2(VALUE self)
{
return REFER_OBJECT(cCvPoint::rb_class(), &CVCONTOURTREE(self)->p2, self);
}
/*
* Restores the contour from its binary tree representation.
*
* The parameter +criteria+ determines the accuracy and/or the number of tree levels
* used for reconstruction, so it is possible to build approximated contour.
* @overload contour(criteria = 0)
* @param criteria [Integer] Criteria, where to stop reconstruction
* @return [CvContour] Contour tree
* @opencv_func cvContourFromContourTree
*/
VALUE
rb_contour(VALUE self, VALUE criteria)
{
VALUE storage = cCvMemStorage::new_object();
CvSeq *contour = NULL;
try {
contour = cvContourFromContourTree(CVCONTOURTREE(self), CVMEMSTORAGE(storage),
VALUE_TO_CVTERMCRITERIA(criteria));
}
catch (cv::Exception& e) {
raise_cverror(e);
}
return cCvSeq::new_sequence(cCvContour::rb_class(), contour, cCvPoint::rb_class(), storage);
}
__NAMESPACE_END_CVCONTOURTREE
__NAMESPACE_END_OPENCV
<|endoftext|> |
<commit_before>
#include "view.hpp"
#include "view/shade.hpp"
namespace View {
void printErrors(const char *prefix = "OpenGL error(s): ") {
GLenum err;
bool once = false;
std::ostringstream oss;
while(!(err = glGetError())) {
once = true;
switch(err) {
case GL_INVALID_ENUM:
oss << "invalid enum; ";
break;
case GL_INVALID_VALUE:
oss << "invalid value; ";
break;
case GL_INVALID_OPERATION:
oss << "invalid operation; ";
break;
case GL_STACK_OVERFLOW:
oss << "stack overflow; ";
break;
case GL_STACK_UNDERFLOW:
oss << "stack underflow; ";
break;
case GL_OUT_OF_MEMORY:
oss << "out of memory; ";
break;
case GL_INVALID_FRAMEBUFFER_OPERATION:
oss << "invalid framebuffer operation; ";
break;
default:
break;
}
}
if(once) {
std::cout << prefix << oss.str() << std::endl;
}
}
void view::setUniforms(void) {
int w, h;
glfwGetFramebufferSize(win, &w, &h);
float mag = float(1/tan(fov*M_PI/180));
float projection[]{
mag*h/w, 0, 0, 0, 0, mag, 0, 0,
0, 0, (far+near)/(far-near), -1,
0, 0, 2*far*near/(far-near), 0
};
glUniformMatrix4fv(projID, 1, GL_TRUE, projection);
/* TODO - static not intended, just persistence;
* all of the data here should be passed or shared */
static float theta = 0;
theta += M_PI/180;
float c = cos(theta), s = sin(theta);
float modelData[]{
c, 0,-s, 0,
0, 1, 0, 0,
s, 0, c, c,
0, 0, 0, 1
}, viewData[]{
1, 0, 0, 0,
0, 1, 0, 0,
0, 0, 1, 0,
0, 0, 2, 1
};
glUniformMatrix4fv(modelID, 1, GL_TRUE, modelData);
glUniformMatrix4fv(viewID, 1, GL_FALSE, viewData);
}
void view::redraw(void) {
setUniforms();
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
glEnableVertexAttribArray(0);
glEnableVertexAttribArray(1);
static long int offset = 3*sizeof(float),
stride = 2*offset;
glBindBuffer(GL_ARRAY_BUFFER, vbuf);
glVertexAttribPointer(0, 3, GL_FLOAT,
GL_FALSE, stride, nullptr);
glVertexAttribPointer(1, 3, GL_FLOAT,
GL_FALSE, stride, (void*) offset);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, ibuf);
glDrawElements(GL_TRIANGLES, nTriangles*3,
GL_UNSIGNED_INT, nullptr);
glDisableVertexAttribArray(1);
glDisableVertexAttribArray(0);
glfwSwapBuffers(win);
static int nFrames = -1;
nFrames++;
static double t0 = glfwGetTime();
double t1 = glfwGetTime(), dt = t1-t0;
if(dt >= 1) {
std::cout << (nFrames/dt) << "FPS" << std::endl;
t0 = t1;
nFrames = -1;
}
}
void view::run(std::function<bool()> update,
std::function<void()> quit) {
if(valid && win) {
glfwMakeContextCurrent(win);
while(true) {
glfwPollEvents();
if(glfwWindowShouldClose(win)) {
quit();
} else if(update()) {
redraw();
continue;
}
break;
}
}
}
view::view(void) {
using Header = Model::Ply::Header;
using Element = Model::Ply::Element;
static constexpr const char
*vpath = "resources/shade.vert",
*fpath = "resources/shade.frag",
*mpath = "resources/bunny.ply";
Header model(mpath);
if(!glfwInit()) {
std::cout << "Could not initialize GLFW." << std::endl;
return;
}
glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3);
glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3);
glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);
win = glfwCreateWindow(512, 512, "View", NULL, NULL);
if(!win) {
std::cout << "Could not create window." << std::endl;
return;
}
glfwMakeContextCurrent(win);
if(gl3wInit()) {
std::cout << "Could not initialize gl3w." << std::endl;
return;
}
glfwSetWindowSizeCallback(win,
[](GLFWwindow*, int w, int h){
glViewport(0, 0, w, h);
}
);
glEnable(GL_DEPTH_TEST);
glEnable(GL_CULL_FACE);
glGenVertexArrays(1, &vaID);
glBindVertexArray(vaID);
if(model.status) {
std::cout << model.statusContext << std::endl;
return;
}
auto start = begin(model.elements),
stop = end(model.elements);
auto getVertices = [](Element const& el) -> bool {
return el.name == "vertex" && !el.has_list
&& el.properties.size() == 6;
};
auto getIndices = [](Element const& el) -> bool {
int sz = el.properties.size();
return el.name == "face"
&& (el.has_list ? sz==1 : sz==3);
};
auto vertices = std::find_if(start, stop, getVertices),
indices = std::find_if(start, stop, getIndices);
if(vertices == stop || indices == stop) {
valid = false;
std::cout << "The model is valid, but does not match "
"the anticipated structure." << std::endl;
return;
}
glGenBuffers(1, &vbuf);
glBindBuffer(GL_ARRAY_BUFFER, vbuf);
glBufferData(GL_ARRAY_BUFFER, vertices->data.size(),
(void*)(&vertices->data[0]), GL_STATIC_DRAW);
glGenBuffers(1, &ibuf);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, ibuf);
glBufferData(GL_ELEMENT_ARRAY_BUFFER, indices->data.size(),
(void*)(&indices->data[0]), GL_STATIC_DRAW);
nTriangles = indices -> instances;
progID = glCreateProgram();
if(!link(vpath, fpath, progID)) {
std::cout << "Could not compile/link shader(s)." << std::endl;
return;
}
modelID = glGetUniformLocation(progID, "model");
viewID = glGetUniformLocation(progID, "view");
projID = glGetUniformLocation(progID, "proj");
glUseProgram(progID);
valid = true;
}
view::~view(void) {
if(progID) {
glDeleteProgram(progID);
}
glfwDestroyWindow(win);
}
}
<commit_msg>Added TODO to view<commit_after>
#include "view.hpp"
#include "view/shade.hpp"
namespace View {
void printErrors(const char *prefix = "OpenGL error(s): ") {
GLenum err;
bool once = false;
std::ostringstream oss;
while(!(err = glGetError())) {
once = true;
switch(err) {
case GL_INVALID_ENUM:
oss << "invalid enum; ";
break;
case GL_INVALID_VALUE:
oss << "invalid value; ";
break;
case GL_INVALID_OPERATION:
oss << "invalid operation; ";
break;
case GL_STACK_OVERFLOW:
oss << "stack overflow; ";
break;
case GL_STACK_UNDERFLOW:
oss << "stack underflow; ";
break;
case GL_OUT_OF_MEMORY:
oss << "out of memory; ";
break;
case GL_INVALID_FRAMEBUFFER_OPERATION:
oss << "invalid framebuffer operation; ";
break;
default:
break;
}
}
if(once) {
std::cout << prefix << oss.str() << std::endl;
}
}
void view::setUniforms(void) {
int w, h;
glfwGetFramebufferSize(win, &w, &h);
float mag = float(1/tan(fov*M_PI/180));
float projection[]{
mag*h/w, 0, 0, 0, 0, mag, 0, 0,
0, 0, (far+near)/(far-near), -1,
0, 0, 2*far*near/(far-near), 0
};
glUniformMatrix4fv(projID, 1, GL_TRUE, projection);
/* TODO - static not intended, just persistence;
* all of the data here should be passed or shared */
static float theta = 0;
theta += M_PI/180;
float c = cos(theta), s = sin(theta);
float modelData[]{
c, 0,-s, 0,
0, 1, 0, 0,
s, 0, c, c,
0, 0, 0, 1
}, viewData[]{
1, 0, 0, 0,
0, 1, 0, 0,
0, 0, 1, 0,
0, 0, 2, 1
};
glUniformMatrix4fv(modelID, 1, GL_TRUE, modelData);
glUniformMatrix4fv(viewID, 1, GL_FALSE, viewData);
}
void view::redraw(void) {
setUniforms();
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
glEnableVertexAttribArray(0);
glEnableVertexAttribArray(1);
static long int offset = 3*sizeof(float),
stride = 2*offset;
glBindBuffer(GL_ARRAY_BUFFER, vbuf);
glVertexAttribPointer(0, 3, GL_FLOAT,
GL_FALSE, stride, nullptr);
glVertexAttribPointer(1, 3, GL_FLOAT,
GL_FALSE, stride, (void*) offset);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, ibuf);
glDrawElements(GL_TRIANGLES, nTriangles*3,
GL_UNSIGNED_INT, nullptr);
glDisableVertexAttribArray(1);
glDisableVertexAttribArray(0);
glfwSwapBuffers(win);
static int nFrames = -1;
nFrames++;
static double t0 = glfwGetTime();
double t1 = glfwGetTime(), dt = t1-t0;
if(dt >= 1) {
std::cout << (nFrames/dt) << "FPS" << std::endl;
t0 = t1;
nFrames = -1;
}
}
void view::run(std::function<bool()> update,
std::function<void()> quit) {
if(valid && win) {
glfwMakeContextCurrent(win);
while(true) {
glfwPollEvents();
if(glfwWindowShouldClose(win)) {
quit();
} else if(update()) {
redraw();
continue;
}
break;
}
}
}
view::view(void) {
using Header = Model::Ply::Header;
using Element = Model::Ply::Element;
// TODO - safe model and shader loading at runtime
static constexpr const char
*vpath = "resources/shade.vert",
*fpath = "resources/shade.frag",
*mpath = "resources/bunny.ply";
Header model(mpath);
if(!glfwInit()) {
std::cout << "Could not initialize GLFW." << std::endl;
return;
}
glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3);
glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3);
glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);
win = glfwCreateWindow(512, 512, "View", NULL, NULL);
if(!win) {
std::cout << "Could not create window." << std::endl;
return;
}
glfwMakeContextCurrent(win);
if(gl3wInit()) {
std::cout << "Could not initialize gl3w." << std::endl;
return;
}
glfwSetWindowSizeCallback(win,
[](GLFWwindow*, int w, int h){
glViewport(0, 0, w, h);
}
);
glEnable(GL_DEPTH_TEST);
glEnable(GL_CULL_FACE);
glGenVertexArrays(1, &vaID);
glBindVertexArray(vaID);
if(model.status) {
std::cout << model.statusContext << std::endl;
return;
}
auto start = begin(model.elements),
stop = end(model.elements);
auto getVertices = [](Element const& el) -> bool {
return el.name == "vertex" && !el.has_list
&& el.properties.size() == 6;
};
auto getIndices = [](Element const& el) -> bool {
int sz = el.properties.size();
return el.name == "face"
&& (el.has_list ? sz==1 : sz==3);
};
auto vertices = std::find_if(start, stop, getVertices),
indices = std::find_if(start, stop, getIndices);
if(vertices == stop || indices == stop) {
valid = false;
std::cout << "The model is valid, but does not match "
"the anticipated structure." << std::endl;
return;
}
glGenBuffers(1, &vbuf);
glBindBuffer(GL_ARRAY_BUFFER, vbuf);
glBufferData(GL_ARRAY_BUFFER, vertices->data.size(),
(void*)(&vertices->data[0]), GL_STATIC_DRAW);
glGenBuffers(1, &ibuf);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, ibuf);
glBufferData(GL_ELEMENT_ARRAY_BUFFER, indices->data.size(),
(void*)(&indices->data[0]), GL_STATIC_DRAW);
nTriangles = indices -> instances;
progID = glCreateProgram();
if(!link(vpath, fpath, progID)) {
std::cout << "Could not compile/link shader(s)." << std::endl;
return;
}
modelID = glGetUniformLocation(progID, "model");
viewID = glGetUniformLocation(progID, "view");
projID = glGetUniformLocation(progID, "proj");
glUseProgram(progID);
valid = true;
}
view::~view(void) {
if(progID) {
glDeleteProgram(progID);
}
glfwDestroyWindow(win);
}
}
<|endoftext|> |
<commit_before><commit_msg>Adapt loplugin:derefnullptr to old Clang versions<commit_after><|endoftext|> |
<commit_before>// Copyright (C) 2017, 2018 Rob Caelers <rob.caelers@gmail.com>
//
// 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 "loopp/net/TLSStream.hpp"
#include <string>
#include <system_error>
#include <netdb.h>
#include <string.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <unistd.h>
#include "loopp/net/NetworkErrors.hpp"
#include "lwip/sockets.h"
#include "lwip/sys.h"
extern "C"
{
#include "esp_heap_caps.h"
#include "mbedtls/esp_debug.h"
}
#include "esp_log.h"
static const char tag[] = "NET";
using namespace loopp;
using namespace loopp::net;
TLSStream::TLSStream(std::shared_ptr<loopp::core::MainLoop> loop) : Stream(loop), loop(loop)
{
mbedtls_net_init(&server_fd);
mbedtls_ssl_init(&ssl);
mbedtls_ssl_config_init(&config);
mbedtls_x509_crt_init(&client_crt);
mbedtls_x509_crt_init(&ca_crt);
mbedtls_pk_init(&client_key);
#ifdef CONFIG_MBEDTLS_DEBUG
mbedtls_esp_enable_debug_log(&config, 4);
#endif
init_entropy();
}
TLSStream::~TLSStream()
{
if (server_fd.fd != -1)
{
::close(server_fd.fd);
loop->unnotify(server_fd.fd);
}
mbedtls_net_free(&server_fd);
mbedtls_x509_crt_free(&client_crt);
mbedtls_x509_crt_free(&ca_crt);
mbedtls_pk_free(&client_key);
mbedtls_ssl_config_free(&config);
mbedtls_ctr_drbg_free(&ctr_drbg);
mbedtls_entropy_free(&entropy);
}
void
TLSStream::set_client_certificate(const char *cert, const char *key)
{
parse_cert(&client_crt, cert);
parse_key(&client_key, key);
}
void
TLSStream::set_ca_certificate(const char *cert)
{
parse_cert(&ca_crt, cert);
}
void
TLSStream::init_entropy()
{
mbedtls_entropy_init(&entropy);
mbedtls_ctr_drbg_init(&ctr_drbg);
int ret = mbedtls_ctr_drbg_seed(&ctr_drbg, mbedtls_entropy_func, &entropy, NULL, 0);
throw_if_failure("mbedtls_ctr_drbg_seed", ret);
}
void
TLSStream::parse_cert(mbedtls_x509_crt *crt, const char *cert_str)
{
mbedtls_x509_crt_init(crt);
int ret = mbedtls_x509_crt_parse(crt, (const unsigned char *)cert_str, strlen(cert_str) + 1);
throw_if_failure("mbedtls_x509_crt_parse", ret);
}
void
TLSStream::parse_key(mbedtls_pk_context *key, const char *key_str)
{
mbedtls_pk_init(key);
int ret = mbedtls_pk_parse_key(key, (const unsigned char *)key_str, strlen(key_str) + 1, (const unsigned char *)"", 0);
throw_if_failure("mbedtls_x509_crt_parse", ret);
}
int
TLSStream::socket_read(uint8_t *buffer, std::size_t count)
{
int ret = mbedtls_ssl_read(&ssl, buffer, count);
if (ret == MBEDTLS_ERR_SSL_WANT_READ)
{
ret = -EAGAIN;
}
return ret;
}
int
TLSStream::socket_write(uint8_t *buffer, std::size_t count)
{
int ret = mbedtls_ssl_write(&ssl, buffer, count);
if (ret == MBEDTLS_ERR_SSL_WANT_WRITE)
{
ret = -EAGAIN;
}
return ret;
}
void
TLSStream::socket_close()
{
int ret = 0;
do
{
ret = mbedtls_ssl_close_notify(&ssl);
}
while (ret == MBEDTLS_ERR_SSL_WANT_WRITE);
}
void
TLSStream::socket_on_connected(std::string host, connect_slot_t slot)
{
ESP_LOGD(tag, "Connected. Starting handshake");
server_fd.fd = get_socket();
try
{
int ret = mbedtls_ssl_set_hostname(&ssl, host.c_str());
throw_if_failure("mbedtls_ssl_set_hostname", ret);
ret = mbedtls_ssl_config_defaults(&config, MBEDTLS_SSL_IS_CLIENT, MBEDTLS_SSL_TRANSPORT_STREAM,
MBEDTLS_SSL_PRESET_DEFAULT);
throw_if_failure("mbedtls_ssl_config_defaults", ret);
mbedtls_ssl_conf_verify(&config, verify_certificate, NULL);
mbedtls_ssl_conf_rng(&config, mbedtls_ctr_drbg_random, &ctr_drbg);
mbedtls_ssl_conf_authmode(&config, have_ca_cert ? MBEDTLS_SSL_VERIFY_REQUIRED : MBEDTLS_SSL_VERIFY_OPTIONAL);
if (have_ca_cert)
{
mbedtls_ssl_conf_ca_chain(&config, &ca_crt, NULL);
}
if (have_ca_cert)
{
ret = mbedtls_ssl_conf_own_cert(&config, &client_crt, &client_key);
throw_if_failure("mbedtls_ssl_conf_own_cert", ret);
}
mbedtls_ssl_set_bio(&ssl, &server_fd, mbedtls_net_send, mbedtls_net_recv, NULL);
ret = mbedtls_ssl_setup(&ssl, &config);
throw_if_failure("mbedtls_ssl_setup", ret);
on_handshake(slot);
}
catch (const std::system_error &ex)
{
slot.call(ex.code());
}
}
void
TLSStream::on_handshake(connect_slot_t slot)
{
try
{
auto self = shared_from_this();
int ret = mbedtls_ssl_handshake(&ssl);
ESP_LOGD(tag, "Handshake ret = %x", -ret);
switch (ret)
{
case 0:
ESP_LOGD(tag, "TLS Handshake complete");
break;
case MBEDTLS_ERR_SSL_WANT_READ:
loop->notify_read(server_fd.fd, [this, self, slot](std::error_code ec) {
if (!ec)
{
on_handshake(slot);
}
else
{
slot.call(ec);
}
});
break;
case MBEDTLS_ERR_SSL_WANT_WRITE:
loop->notify_write(server_fd.fd, [this, self, slot](std::error_code ec) {
if (!ec)
{
on_handshake(slot);
}
else
{
slot.call(ec);
}
});
break;
default:
ESP_LOGE(tag, "TLS Handshake failed: %x", -ret);
throw_if_failure("mbedtls_ssl_handshake", ret);
}
if (ret == 0)
{
ret = mbedtls_ssl_get_verify_result(&ssl);
if (ret != 0)
{
char buf[512];
mbedtls_x509_crt_verify_info(buf, sizeof(buf), "", ret);
ESP_LOGE(tag, "TLS Verify failed: %s", buf);
}
if (mbedtls_ssl_get_peer_cert(&ssl) != NULL)
{
char buf[512];
mbedtls_x509_crt_info((char *)buf, sizeof(buf) - 1, "", mbedtls_ssl_get_peer_cert(&ssl));
ESP_LOGD(tag, "Peer certificate information: %s", buf);
}
connected_property.set(true);
slot.call(std::error_code());
}
}
catch (const std::system_error &ex)
{
slot.call(ex.code());
}
}
void
TLSStream::log_failure(std::string msg, int error_code)
{
if (error_code != 0)
{
char error_msg[512];
mbedtls_strerror(error_code, error_msg, sizeof(error_msg));
ESP_LOGE(tag, "Error: %s %s %d", msg.c_str(), error_msg, error_code);
}
}
void
TLSStream::throw_if_failure(std::string msg, int error_code)
{
if (error_code != 0)
{
char error_msg[512];
mbedtls_strerror(error_code, error_msg, sizeof(error_msg));
ESP_LOGE(tag, "Error: %s %s %d", msg.c_str(), error_msg, error_code);
// TODO: convert errors.
std::error_code ec(NetworkErrc::TLSProtocolError);
throw std::system_error(ec, msg);
}
}
int
TLSStream::verify_certificate(void *data, mbedtls_x509_crt *crt, int depth, uint32_t *flags)
{
char buf[1024];
((void)data);
ESP_LOGD(tag, "Verify requested for (depth %d):", depth);
mbedtls_x509_crt_info(buf, sizeof(buf) - 1, "", crt);
ESP_LOGD(tag, "%s", buf);
return 0;
}
<commit_msg>Fix use of certificate<commit_after>// Copyright (C) 2017, 2018 Rob Caelers <rob.caelers@gmail.com>
//
// 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 "loopp/net/TLSStream.hpp"
#include <string>
#include <system_error>
#include <netdb.h>
#include <string.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <unistd.h>
#include "loopp/net/NetworkErrors.hpp"
#include "lwip/sockets.h"
#include "lwip/sys.h"
extern "C"
{
#include "esp_heap_caps.h"
#include "mbedtls/esp_debug.h"
}
#include "esp_log.h"
static const char tag[] = "NET";
using namespace loopp;
using namespace loopp::net;
TLSStream::TLSStream(std::shared_ptr<loopp::core::MainLoop> loop) : Stream(loop), loop(loop)
{
mbedtls_net_init(&server_fd);
mbedtls_ssl_init(&ssl);
mbedtls_ssl_config_init(&config);
mbedtls_x509_crt_init(&client_crt);
mbedtls_x509_crt_init(&ca_crt);
mbedtls_pk_init(&client_key);
#ifdef CONFIG_MBEDTLS_DEBUG
mbedtls_esp_enable_debug_log(&config, 4);
#endif
init_entropy();
}
TLSStream::~TLSStream()
{
if (server_fd.fd != -1)
{
::close(server_fd.fd);
loop->unnotify(server_fd.fd);
}
mbedtls_net_free(&server_fd);
mbedtls_x509_crt_free(&client_crt);
mbedtls_x509_crt_free(&ca_crt);
mbedtls_pk_free(&client_key);
mbedtls_ssl_config_free(&config);
mbedtls_ctr_drbg_free(&ctr_drbg);
mbedtls_entropy_free(&entropy);
}
void
TLSStream::set_client_certificate(const char *cert, const char *key)
{
assert(cert != nullptr && key != nullptr);
parse_cert(&client_crt, cert);
parse_key(&client_key, key);
have_client_cert = true;
}
void
TLSStream::set_ca_certificate(const char *cert)
{
assert(cert != nullptr);
parse_cert(&ca_crt, cert);
have_ca_cert = true;
}
void
TLSStream::init_entropy()
{
mbedtls_entropy_init(&entropy);
mbedtls_ctr_drbg_init(&ctr_drbg);
int ret = mbedtls_ctr_drbg_seed(&ctr_drbg, mbedtls_entropy_func, &entropy, NULL, 0);
throw_if_failure("mbedtls_ctr_drbg_seed", ret);
}
void
TLSStream::parse_cert(mbedtls_x509_crt *crt, const char *cert_str)
{
mbedtls_x509_crt_init(crt);
int ret = mbedtls_x509_crt_parse(crt, (const unsigned char *)cert_str, strlen(cert_str) + 1);
throw_if_failure("mbedtls_x509_crt_parse", ret);
}
void
TLSStream::parse_key(mbedtls_pk_context *key, const char *key_str)
{
mbedtls_pk_init(key);
int ret = mbedtls_pk_parse_key(key, (const unsigned char *)key_str, strlen(key_str) + 1, (const unsigned char *)"", 0);
throw_if_failure("mbedtls_x509_crt_parse", ret);
}
int
TLSStream::socket_read(uint8_t *buffer, std::size_t count)
{
int ret = mbedtls_ssl_read(&ssl, buffer, count);
if (ret == MBEDTLS_ERR_SSL_WANT_READ)
{
ret = -EAGAIN;
}
return ret;
}
int
TLSStream::socket_write(uint8_t *buffer, std::size_t count)
{
int ret = mbedtls_ssl_write(&ssl, buffer, count);
if (ret == MBEDTLS_ERR_SSL_WANT_WRITE)
{
ret = -EAGAIN;
}
return ret;
}
void
TLSStream::socket_close()
{
int ret = 0;
do
{
ret = mbedtls_ssl_close_notify(&ssl);
}
while (ret == MBEDTLS_ERR_SSL_WANT_WRITE);
}
void
TLSStream::socket_on_connected(std::string host, connect_slot_t slot)
{
ESP_LOGD(tag, "Connected. Starting handshake");
server_fd.fd = get_socket();
try
{
int ret = mbedtls_ssl_set_hostname(&ssl, host.c_str());
throw_if_failure("mbedtls_ssl_set_hostname", ret);
ret = mbedtls_ssl_config_defaults(&config, MBEDTLS_SSL_IS_CLIENT, MBEDTLS_SSL_TRANSPORT_STREAM,
MBEDTLS_SSL_PRESET_DEFAULT);
throw_if_failure("mbedtls_ssl_config_defaults", ret);
mbedtls_ssl_conf_verify(&config, verify_certificate, NULL);
mbedtls_ssl_conf_rng(&config, mbedtls_ctr_drbg_random, &ctr_drbg);
mbedtls_ssl_conf_authmode(&config, have_ca_cert ? MBEDTLS_SSL_VERIFY_REQUIRED : MBEDTLS_SSL_VERIFY_OPTIONAL);
if (have_ca_cert)
{
ESP_LOGD(tag, "Using CA cert");
mbedtls_ssl_conf_ca_chain(&config, &ca_crt, NULL);
}
if (have_client_cert)
{
ESP_LOGD(tag, "Using Client cert");
ret = mbedtls_ssl_conf_own_cert(&config, &client_crt, &client_key);
throw_if_failure("mbedtls_ssl_conf_own_cert", ret);
}
mbedtls_ssl_set_bio(&ssl, &server_fd, mbedtls_net_send, mbedtls_net_recv, NULL);
ret = mbedtls_ssl_setup(&ssl, &config);
throw_if_failure("mbedtls_ssl_setup", ret);
on_handshake(slot);
}
catch (const std::system_error &ex)
{
slot.call(ex.code());
}
}
void
TLSStream::on_handshake(connect_slot_t slot)
{
try
{
auto self = shared_from_this();
int ret = mbedtls_ssl_handshake(&ssl);
ESP_LOGD(tag, "Handshake ret = %x", -ret);
switch (ret)
{
case 0:
ESP_LOGD(tag, "TLS Handshake complete");
break;
case MBEDTLS_ERR_SSL_WANT_READ:
loop->notify_read(server_fd.fd, [this, self, slot](std::error_code ec) {
if (!ec)
{
on_handshake(slot);
}
else
{
slot.call(ec);
}
});
break;
case MBEDTLS_ERR_SSL_WANT_WRITE:
loop->notify_write(server_fd.fd, [this, self, slot](std::error_code ec) {
if (!ec)
{
on_handshake(slot);
}
else
{
slot.call(ec);
}
});
break;
default:
ESP_LOGE(tag, "TLS Handshake failed: %x", -ret);
throw_if_failure("mbedtls_ssl_handshake", ret);
}
if (ret == 0)
{
ret = mbedtls_ssl_get_verify_result(&ssl);
if (ret != 0)
{
char buf[512];
mbedtls_x509_crt_verify_info(buf, sizeof(buf), "", ret);
ESP_LOGE(tag, "TLS Verify failed: %s", buf);
}
if (mbedtls_ssl_get_peer_cert(&ssl) != NULL)
{
char buf[512];
mbedtls_x509_crt_info((char *)buf, sizeof(buf) - 1, "", mbedtls_ssl_get_peer_cert(&ssl));
ESP_LOGD(tag, "Peer certificate information: %s", buf);
}
connected_property.set(true);
slot.call(std::error_code());
}
}
catch (const std::system_error &ex)
{
slot.call(ex.code());
}
}
void
TLSStream::log_failure(std::string msg, int error_code)
{
if (error_code != 0)
{
char error_msg[512];
mbedtls_strerror(error_code, error_msg, sizeof(error_msg));
ESP_LOGE(tag, "Error: %s %s %d", msg.c_str(), error_msg, error_code);
}
}
void
TLSStream::throw_if_failure(std::string msg, int error_code)
{
if (error_code != 0)
{
char error_msg[512];
mbedtls_strerror(error_code, error_msg, sizeof(error_msg));
ESP_LOGE(tag, "Error: %s %s %d", msg.c_str(), error_msg, error_code);
// TODO: convert errors.
std::error_code ec(NetworkErrc::TLSProtocolError);
throw std::system_error(ec, msg);
}
}
int
TLSStream::verify_certificate(void *data, mbedtls_x509_crt *crt, int depth, uint32_t *flags)
{
char buf[1024];
((void)data);
ESP_LOGD(tag, "Verify requested for (depth %d):", depth);
mbedtls_x509_crt_info(buf, sizeof(buf) - 1, "", crt);
ESP_LOGD(tag, "%s", buf);
return 0;
}
<|endoftext|> |
<commit_before>/* ---------------------------------------------------------------------
* Numenta Platform for Intelligent Computing (NuPIC)
* Copyright (C) 2013, Numenta, Inc. Unless you have an agreement
* with Numenta, Inc., for a separate license for this software code, the
* following terms and conditions apply:
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 3 as
* published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
* See the GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see http://www.gnu.org/licenses.
*
* http://numenta.org/licenses/
* ---------------------------------------------------------------------
*/
#include <stdexcept>
#include <nupic/engine/RegionImplFactory.hpp>
#include <nupic/engine/RegionImpl.hpp>
#include <nupic/engine/Region.hpp>
#include <nupic/engine/Spec.hpp>
#include <nupic/os/DynamicLibrary.hpp>
#include <nupic/os/Path.hpp>
#include <nupic/os/OS.hpp>
#include <nupic/os/Env.hpp>
#include <nupic/ntypes/Value.hpp>
#include <nupic/ntypes/BundleIO.hpp>
#include <nupic/engine/YAMLUtils.hpp>
#include <nupic/engine/TestNode.hpp>
#include <nupic/regions/VectorFileEffector.hpp>
#include <nupic/regions/VectorFileSensor.hpp>
#include <nupic/utils/Log.hpp>
#include <nupic/utils/StringUtils.hpp>
// from http://stackoverflow.com/a/9096509/1781435
#define stringify(x) #x
#define expand_and_stringify(x) stringify(x)
// Path from site-packages to packages that contain NuPIC Python regions
static std::vector<const char *> packages { "nupic.regions", "nupic.regions.extra" };
namespace nupic
{
// Allows the user to add custom regions to the package list
void RegionImplFactory::registerRegionPackage(const char * path)
{
packages.push_back(path);
}
class DynamicPythonLibrary
{
typedef void (*initPythonFunc)();
typedef void (*finalizePythonFunc)();
typedef void * (*createSpecFunc)(const char *, void **);
typedef int (*destroySpecFunc)(const char *);
typedef void * (*createPyNodeFunc)(const char *, void *, void *, void **);
typedef void * (*deserializePyNodeFunc)(const char *, void *, void *, void *);
public:
DynamicPythonLibrary() :
initPython_(nullptr),
finalizePython_(nullptr),
createSpec_(nullptr),
destroySpec_(nullptr),
createPyNode_(nullptr)
{
// To find the pynode plugin we need the nupic
// installation directory.
#if defined(NTA_OS_WINDOWS)
std::string command = "python -c \"import sys;import os;import nupic;sys.stdout.write(os.path.abspath(os.path.join(nupic.__file__, \"\"../..\"\")))\"";
#else
std::string command = "python -c 'import sys;import os;import nupic;sys.stdout.write(os.path.abspath(os.path.join(nupic.__file__, \"../..\")))'";
#endif
rootDir_ = OS::executeCommand(command);
if (!Path::exists(rootDir_))
NTA_THROW << "Unable to find NuPIC library in '" << rootDir_ << "'";
#if defined(NTA_OS_WINDOWS)
const char * filename = "cpp_region.dll";
#else
const char * filename = "libcpp_region.so";
#endif
std::string libName = Path::join(rootDir_, "nupic", filename);
if (!Path::exists(libName))
NTA_THROW << "Unable to find library '" << libName << "'";
std::string errorString;
DynamicLibrary * p =
DynamicLibrary::load(libName,
// export as LOCAL because we don't want
// the symbols to be globally visible;
// But the python module that we load
// has to be able to access symbols from
// libpython.so; Since libpython.so is linked
// to the pynode shared library, it appears
// we have to make the pynode shared library
// symbols global. TODO: investigate
DynamicLibrary::GLOBAL|
// Evaluate them NOW instead of LAZY to catch
// errors up front, even though this takes
// a little longer to load the library.
// However -- the current dependency chain
// PyNode->Region->RegionImplFactory apparently
// creates never-used dependencies on YAML
// so until this is resolved use LAZY
DynamicLibrary::LAZY,
errorString);
NTA_CHECK(p) << "Unable to load the pynode library: " << errorString;
pynodeLibrary_ = boost::shared_ptr<DynamicLibrary>(p);
initPython_ = (initPythonFunc)pynodeLibrary_->getSymbol("NTA_initPython");
NTA_CHECK(initPython_) << "Unable to find NTA_initPython symbol in " << filename;
finalizePython_ = (finalizePythonFunc)pynodeLibrary_->getSymbol("NTA_finalizePython");
NTA_CHECK(finalizePython_) << "Unable to find NTA_finalizePython symbol in " << filename;
createPyNode_ = (createPyNodeFunc)pynodeLibrary_->getSymbol("NTA_createPyNode");
NTA_CHECK(createPyNode_) << "Unable to find NTA_createPyNode symbol in " << filename;
deserializePyNode_ = (deserializePyNodeFunc)pynodeLibrary_->getSymbol("NTA_deserializePyNode");
NTA_CHECK(createPyNode_) << "Unable to find NTA_createPyNode symbol in " << filename;
createSpec_ = (createSpecFunc)pynodeLibrary_->getSymbol("NTA_createSpec");
NTA_CHECK(createSpec_) << "Unable to find NTA_createSpec symbol in " << filename;
destroySpec_ = (destroySpecFunc)pynodeLibrary_->getSymbol("NTA_destroySpec");
NTA_CHECK(destroySpec_) << "Unable to find NTA_destroySpec symbol in " << filename;
(*initPython_)();
}
~DynamicPythonLibrary()
{
//NTA_DEBUG << "In DynamicPythonLibrary Destructor";
if (finalizePython_)
finalizePython_();
}
void * createSpec(std::string nodeType, void ** exception)
{
//NTA_DEBUG << "RegionImplFactory::createSpec(" << nodeType << ")";
return (*createSpec_)(nodeType.c_str(), exception);
}
int destroySpec(std::string nodeType)
{
NTA_INFO << "destroySpec(" << nodeType << ")";
return (*destroySpec_)(nodeType.c_str());
}
void * createPyNode(const std::string& nodeType,
ValueMap * nodeParams,
Region * region,
void ** exception)
{
//NTA_DEBUG << "RegionImplFactory::createPyNode(" << nodeType << ")";
return (*createPyNode_)(nodeType.c_str(),
reinterpret_cast<void *>(nodeParams),
reinterpret_cast<void*>(region),
exception);
}
void * deserializePyNode(const std::string& nodeType,
BundleIO* bundle,
Region * region,
void ** exception)
{
//NTA_DEBUG << "RegionImplFactory::deserializePyNode(" << nodeType << ")";
return (*deserializePyNode_)(nodeType.c_str(),
reinterpret_cast<void*>(bundle),
reinterpret_cast<void*>(region),
exception);
}
const std::string& getRootDir() const
{
return rootDir_;
}
private:
std::string rootDir_;
boost::shared_ptr<DynamicLibrary> pynodeLibrary_;
initPythonFunc initPython_;
finalizePythonFunc finalizePython_;
createSpecFunc createSpec_;
destroySpecFunc destroySpec_;
createPyNodeFunc createPyNode_;
deserializePyNodeFunc deserializePyNode_;
};
RegionImplFactory & RegionImplFactory::getInstance()
{
static RegionImplFactory instance;
return instance;
}
// This function creates either a NuPIC 2 or NuPIC 1 Python node
static RegionImpl * createPyNode(DynamicPythonLibrary * pyLib,
const std::string & nodeType,
ValueMap * nodeParams,
Region * region)
{
for (auto package : packages)
{
// Construct the full module path to the requested node
std::string fullNodeType = std::string(package);
if (!fullNodeType.empty()) // Not in current directory
fullNodeType += std::string(".");
fullNodeType += std::string(nodeType.c_str() + 3);
void * exception = nullptr;
void * node = pyLib->createPyNode(fullNodeType, nodeParams, region, &exception);
if (node)
return static_cast<RegionImpl*>(node);
}
NTA_THROW << "Unable to create region " << region->getName() << " of type " << nodeType;
return nullptr;
}
// This function deserializes either a NuPIC 2 or NuPIC 1 Python node
static RegionImpl * deserializePyNode(DynamicPythonLibrary * pyLib,
const std::string & nodeType,
BundleIO & bundle,
Region * region)
{
// We need to find the module so that we know if it is NuPIC 1 or NuPIC 2
for (auto package : packages)
{
// Construct the full module path to the requested node
std::string fullNodeType = std::string(package);
if (!fullNodeType.empty()) // Not in current directory
fullNodeType += std::string(".");
fullNodeType += std::string(nodeType.c_str() + 3);
void *exception = nullptr;
void * node = pyLib->deserializePyNode(fullNodeType, &bundle, region, &exception);
if (node)
return static_cast<RegionImpl*>(node);
}
NTA_THROW << "Unable to deserialize region " << region->getName() << " of type " << nodeType;
return nullptr;
}
RegionImpl* RegionImplFactory::createRegionImpl(const std::string nodeType,
const std::string nodeParams,
Region* region)
{
RegionImpl *mn = nullptr;
Spec *ns = getSpec(nodeType);
ValueMap vm = YAMLUtils::toValueMap(
nodeParams.c_str(),
ns->parameters,
nodeType,
region->getName());
if (nodeType == "TestNode")
{
mn = new TestNode(vm, region);
} else if (nodeType == "VectorFileEffector")
{
mn = new VectorFileEffector(vm, region);
} else if (nodeType == "VectorFileSensor")
{
mn = new VectorFileSensor(vm, region);
} else if ((nodeType.find(std::string("py.")) == 0))
{
if (!pyLib_)
pyLib_ = boost::shared_ptr<DynamicPythonLibrary>(new DynamicPythonLibrary());
mn = createPyNode(pyLib_.get(), nodeType, &vm, region);
} else
{
NTA_THROW << "Unsupported node type '" << nodeType << "'";
}
return mn;
}
RegionImpl* RegionImplFactory::deserializeRegionImpl(const std::string nodeType,
BundleIO& bundle,
Region* region)
{
RegionImpl *mn = nullptr;
if (nodeType == "TestNode")
{
mn = new TestNode(bundle, region);
} else if (nodeType == "VectorFileEffector")
{
mn = new VectorFileEffector(bundle, region);
} else if (nodeType == "VectorFileSensor")
{
mn = new VectorFileSensor(bundle, region);
} else if (StringUtils::startsWith(nodeType, "py."))
{
if (!pyLib_)
pyLib_ = boost::shared_ptr<DynamicPythonLibrary>(new DynamicPythonLibrary());
mn = deserializePyNode(pyLib_.get(), nodeType, bundle, region);
} else
{
NTA_THROW << "Unsupported node type '" << nodeType << "'";
}
return mn;
}
// This function returns the node spec of a NuPIC 2 or NuPIC 1 Python node
static Spec * getPySpec(DynamicPythonLibrary * pyLib,
const std::string & nodeType)
{
for (auto package : packages)
{
// Construct the full module path to the requested node
std::string fullNodeType = std::string(package);
if (!fullNodeType.empty()) // Not in current directory
fullNodeType += std::string(".");
fullNodeType += std::string(nodeType.c_str() + 3);
std::cout << fullNodeType << std::endl;
void * exception = nullptr;
void * ns = pyLib->createSpec(fullNodeType, &exception);
if (ns) {
return (Spec *)ns;
}
}
NTA_THROW << "Matching Python module for " << nodeType << " not found.";
}
Spec * RegionImplFactory::getSpec(const std::string nodeType)
{
std::map<std::string, Spec*>::iterator it;
// return from cache if we already have it
it = nodespecCache_.find(nodeType);
if (it != nodespecCache_.end())
return it->second;
// grab the nodespec and cache it
// one entry per supported node type
Spec * ns = nullptr;
if (nodeType == "TestNode")
{
ns = TestNode::createSpec();
}
else if (nodeType == "VectorFileEffector")
{
ns = VectorFileEffector::createSpec();
}
else if (nodeType == "VectorFileSensor")
{
ns = VectorFileSensor::createSpec();
}
else if (nodeType.find(std::string("py.")) == 0)
{
if (!pyLib_)
pyLib_ = boost::shared_ptr<DynamicPythonLibrary>(new DynamicPythonLibrary());
ns = getPySpec(pyLib_.get(), nodeType);
}
else
{
NTA_THROW << "getSpec() -- Unsupported node type '" << nodeType << "'";
}
if (!ns)
NTA_THROW << "Unable to get node spec for: " << nodeType;
nodespecCache_[nodeType] = ns;
return ns;
}
void RegionImplFactory::cleanup()
{
std::map<std::string, Spec*>::iterator ns;
// destroy all nodespecs
for (ns = nodespecCache_.begin(); ns != nodespecCache_.end(); ns++)
{
assert(ns->second != nullptr);
// PyNode node specs are destroyed by the C++ PyNode
if (ns->first.substr(0, 3) == "py.")
{
pyLib_->destroySpec(ns->first);
}
else
{
delete ns->second;
}
ns->second = nullptr;
}
nodespecCache_.clear();
// Never release the Python dynamic library!
// This is due to cleanup issues of Python itself
// See: http://docs.python.org/c-api/init.html#Py_Finalize
//pyLib_.reset();
}
}
<commit_msg>removed print statement<commit_after>/* ---------------------------------------------------------------------
* Numenta Platform for Intelligent Computing (NuPIC)
* Copyright (C) 2013, Numenta, Inc. Unless you have an agreement
* with Numenta, Inc., for a separate license for this software code, the
* following terms and conditions apply:
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 3 as
* published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
* See the GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see http://www.gnu.org/licenses.
*
* http://numenta.org/licenses/
* ---------------------------------------------------------------------
*/
#include <stdexcept>
#include <nupic/engine/RegionImplFactory.hpp>
#include <nupic/engine/RegionImpl.hpp>
#include <nupic/engine/Region.hpp>
#include <nupic/engine/Spec.hpp>
#include <nupic/os/DynamicLibrary.hpp>
#include <nupic/os/Path.hpp>
#include <nupic/os/OS.hpp>
#include <nupic/os/Env.hpp>
#include <nupic/ntypes/Value.hpp>
#include <nupic/ntypes/BundleIO.hpp>
#include <nupic/engine/YAMLUtils.hpp>
#include <nupic/engine/TestNode.hpp>
#include <nupic/regions/VectorFileEffector.hpp>
#include <nupic/regions/VectorFileSensor.hpp>
#include <nupic/utils/Log.hpp>
#include <nupic/utils/StringUtils.hpp>
// from http://stackoverflow.com/a/9096509/1781435
#define stringify(x) #x
#define expand_and_stringify(x) stringify(x)
// Path from site-packages to packages that contain NuPIC Python regions
static std::vector<const char *> packages { "nupic.regions", "nupic.regions.extra" };
namespace nupic
{
// Allows the user to add custom regions to the package list
void RegionImplFactory::registerRegionPackage(const char * path)
{
packages.push_back(path);
}
class DynamicPythonLibrary
{
typedef void (*initPythonFunc)();
typedef void (*finalizePythonFunc)();
typedef void * (*createSpecFunc)(const char *, void **);
typedef int (*destroySpecFunc)(const char *);
typedef void * (*createPyNodeFunc)(const char *, void *, void *, void **);
typedef void * (*deserializePyNodeFunc)(const char *, void *, void *, void *);
public:
DynamicPythonLibrary() :
initPython_(nullptr),
finalizePython_(nullptr),
createSpec_(nullptr),
destroySpec_(nullptr),
createPyNode_(nullptr)
{
// To find the pynode plugin we need the nupic
// installation directory.
#if defined(NTA_OS_WINDOWS)
std::string command = "python -c \"import sys;import os;import nupic;sys.stdout.write(os.path.abspath(os.path.join(nupic.__file__, \"\"../..\"\")))\"";
#else
std::string command = "python -c 'import sys;import os;import nupic;sys.stdout.write(os.path.abspath(os.path.join(nupic.__file__, \"../..\")))'";
#endif
rootDir_ = OS::executeCommand(command);
if (!Path::exists(rootDir_))
NTA_THROW << "Unable to find NuPIC library in '" << rootDir_ << "'";
#if defined(NTA_OS_WINDOWS)
const char * filename = "cpp_region.dll";
#else
const char * filename = "libcpp_region.so";
#endif
std::string libName = Path::join(rootDir_, "nupic", filename);
if (!Path::exists(libName))
NTA_THROW << "Unable to find library '" << libName << "'";
std::string errorString;
DynamicLibrary * p =
DynamicLibrary::load(libName,
// export as LOCAL because we don't want
// the symbols to be globally visible;
// But the python module that we load
// has to be able to access symbols from
// libpython.so; Since libpython.so is linked
// to the pynode shared library, it appears
// we have to make the pynode shared library
// symbols global. TODO: investigate
DynamicLibrary::GLOBAL|
// Evaluate them NOW instead of LAZY to catch
// errors up front, even though this takes
// a little longer to load the library.
// However -- the current dependency chain
// PyNode->Region->RegionImplFactory apparently
// creates never-used dependencies on YAML
// so until this is resolved use LAZY
DynamicLibrary::LAZY,
errorString);
NTA_CHECK(p) << "Unable to load the pynode library: " << errorString;
pynodeLibrary_ = boost::shared_ptr<DynamicLibrary>(p);
initPython_ = (initPythonFunc)pynodeLibrary_->getSymbol("NTA_initPython");
NTA_CHECK(initPython_) << "Unable to find NTA_initPython symbol in " << filename;
finalizePython_ = (finalizePythonFunc)pynodeLibrary_->getSymbol("NTA_finalizePython");
NTA_CHECK(finalizePython_) << "Unable to find NTA_finalizePython symbol in " << filename;
createPyNode_ = (createPyNodeFunc)pynodeLibrary_->getSymbol("NTA_createPyNode");
NTA_CHECK(createPyNode_) << "Unable to find NTA_createPyNode symbol in " << filename;
deserializePyNode_ = (deserializePyNodeFunc)pynodeLibrary_->getSymbol("NTA_deserializePyNode");
NTA_CHECK(createPyNode_) << "Unable to find NTA_createPyNode symbol in " << filename;
createSpec_ = (createSpecFunc)pynodeLibrary_->getSymbol("NTA_createSpec");
NTA_CHECK(createSpec_) << "Unable to find NTA_createSpec symbol in " << filename;
destroySpec_ = (destroySpecFunc)pynodeLibrary_->getSymbol("NTA_destroySpec");
NTA_CHECK(destroySpec_) << "Unable to find NTA_destroySpec symbol in " << filename;
(*initPython_)();
}
~DynamicPythonLibrary()
{
//NTA_DEBUG << "In DynamicPythonLibrary Destructor";
if (finalizePython_)
finalizePython_();
}
void * createSpec(std::string nodeType, void ** exception)
{
//NTA_DEBUG << "RegionImplFactory::createSpec(" << nodeType << ")";
return (*createSpec_)(nodeType.c_str(), exception);
}
int destroySpec(std::string nodeType)
{
NTA_INFO << "destroySpec(" << nodeType << ")";
return (*destroySpec_)(nodeType.c_str());
}
void * createPyNode(const std::string& nodeType,
ValueMap * nodeParams,
Region * region,
void ** exception)
{
//NTA_DEBUG << "RegionImplFactory::createPyNode(" << nodeType << ")";
return (*createPyNode_)(nodeType.c_str(),
reinterpret_cast<void *>(nodeParams),
reinterpret_cast<void*>(region),
exception);
}
void * deserializePyNode(const std::string& nodeType,
BundleIO* bundle,
Region * region,
void ** exception)
{
//NTA_DEBUG << "RegionImplFactory::deserializePyNode(" << nodeType << ")";
return (*deserializePyNode_)(nodeType.c_str(),
reinterpret_cast<void*>(bundle),
reinterpret_cast<void*>(region),
exception);
}
const std::string& getRootDir() const
{
return rootDir_;
}
private:
std::string rootDir_;
boost::shared_ptr<DynamicLibrary> pynodeLibrary_;
initPythonFunc initPython_;
finalizePythonFunc finalizePython_;
createSpecFunc createSpec_;
destroySpecFunc destroySpec_;
createPyNodeFunc createPyNode_;
deserializePyNodeFunc deserializePyNode_;
};
RegionImplFactory & RegionImplFactory::getInstance()
{
static RegionImplFactory instance;
return instance;
}
// This function creates either a NuPIC 2 or NuPIC 1 Python node
static RegionImpl * createPyNode(DynamicPythonLibrary * pyLib,
const std::string & nodeType,
ValueMap * nodeParams,
Region * region)
{
for (auto package : packages)
{
// Construct the full module path to the requested node
std::string fullNodeType = std::string(package);
if (!fullNodeType.empty()) // Not in current directory
fullNodeType += std::string(".");
fullNodeType += std::string(nodeType.c_str() + 3);
void * exception = nullptr;
void * node = pyLib->createPyNode(fullNodeType, nodeParams, region, &exception);
if (node)
return static_cast<RegionImpl*>(node);
}
NTA_THROW << "Unable to create region " << region->getName() << " of type " << nodeType;
return nullptr;
}
// This function deserializes either a NuPIC 2 or NuPIC 1 Python node
static RegionImpl * deserializePyNode(DynamicPythonLibrary * pyLib,
const std::string & nodeType,
BundleIO & bundle,
Region * region)
{
// We need to find the module so that we know if it is NuPIC 1 or NuPIC 2
for (auto package : packages)
{
// Construct the full module path to the requested node
std::string fullNodeType = std::string(package);
if (!fullNodeType.empty()) // Not in current directory
fullNodeType += std::string(".");
fullNodeType += std::string(nodeType.c_str() + 3);
void *exception = nullptr;
void * node = pyLib->deserializePyNode(fullNodeType, &bundle, region, &exception);
if (node)
return static_cast<RegionImpl*>(node);
}
NTA_THROW << "Unable to deserialize region " << region->getName() << " of type " << nodeType;
return nullptr;
}
RegionImpl* RegionImplFactory::createRegionImpl(const std::string nodeType,
const std::string nodeParams,
Region* region)
{
RegionImpl *mn = nullptr;
Spec *ns = getSpec(nodeType);
ValueMap vm = YAMLUtils::toValueMap(
nodeParams.c_str(),
ns->parameters,
nodeType,
region->getName());
if (nodeType == "TestNode")
{
mn = new TestNode(vm, region);
} else if (nodeType == "VectorFileEffector")
{
mn = new VectorFileEffector(vm, region);
} else if (nodeType == "VectorFileSensor")
{
mn = new VectorFileSensor(vm, region);
} else if ((nodeType.find(std::string("py.")) == 0))
{
if (!pyLib_)
pyLib_ = boost::shared_ptr<DynamicPythonLibrary>(new DynamicPythonLibrary());
mn = createPyNode(pyLib_.get(), nodeType, &vm, region);
} else
{
NTA_THROW << "Unsupported node type '" << nodeType << "'";
}
return mn;
}
RegionImpl* RegionImplFactory::deserializeRegionImpl(const std::string nodeType,
BundleIO& bundle,
Region* region)
{
RegionImpl *mn = nullptr;
if (nodeType == "TestNode")
{
mn = new TestNode(bundle, region);
} else if (nodeType == "VectorFileEffector")
{
mn = new VectorFileEffector(bundle, region);
} else if (nodeType == "VectorFileSensor")
{
mn = new VectorFileSensor(bundle, region);
} else if (StringUtils::startsWith(nodeType, "py."))
{
if (!pyLib_)
pyLib_ = boost::shared_ptr<DynamicPythonLibrary>(new DynamicPythonLibrary());
mn = deserializePyNode(pyLib_.get(), nodeType, bundle, region);
} else
{
NTA_THROW << "Unsupported node type '" << nodeType << "'";
}
return mn;
}
// This function returns the node spec of a NuPIC 2 or NuPIC 1 Python node
static Spec * getPySpec(DynamicPythonLibrary * pyLib,
const std::string & nodeType)
{
for (auto package : packages)
{
// Construct the full module path to the requested node
std::string fullNodeType = std::string(package);
if (!fullNodeType.empty()) // Not in current directory
fullNodeType += std::string(".");
fullNodeType += std::string(nodeType.c_str() + 3);
void * exception = nullptr;
void * ns = pyLib->createSpec(fullNodeType, &exception);
if (ns) {
return (Spec *)ns;
}
}
NTA_THROW << "Matching Python module for " << nodeType << " not found.";
}
Spec * RegionImplFactory::getSpec(const std::string nodeType)
{
std::map<std::string, Spec*>::iterator it;
// return from cache if we already have it
it = nodespecCache_.find(nodeType);
if (it != nodespecCache_.end())
return it->second;
// grab the nodespec and cache it
// one entry per supported node type
Spec * ns = nullptr;
if (nodeType == "TestNode")
{
ns = TestNode::createSpec();
}
else if (nodeType == "VectorFileEffector")
{
ns = VectorFileEffector::createSpec();
}
else if (nodeType == "VectorFileSensor")
{
ns = VectorFileSensor::createSpec();
}
else if (nodeType.find(std::string("py.")) == 0)
{
if (!pyLib_)
pyLib_ = boost::shared_ptr<DynamicPythonLibrary>(new DynamicPythonLibrary());
ns = getPySpec(pyLib_.get(), nodeType);
}
else
{
NTA_THROW << "getSpec() -- Unsupported node type '" << nodeType << "'";
}
if (!ns)
NTA_THROW << "Unable to get node spec for: " << nodeType;
nodespecCache_[nodeType] = ns;
return ns;
}
void RegionImplFactory::cleanup()
{
std::map<std::string, Spec*>::iterator ns;
// destroy all nodespecs
for (ns = nodespecCache_.begin(); ns != nodespecCache_.end(); ns++)
{
assert(ns->second != nullptr);
// PyNode node specs are destroyed by the C++ PyNode
if (ns->first.substr(0, 3) == "py.")
{
pyLib_->destroySpec(ns->first);
}
else
{
delete ns->second;
}
ns->second = nullptr;
}
nodespecCache_.clear();
// Never release the Python dynamic library!
// This is due to cleanup issues of Python itself
// See: http://docs.python.org/c-api/init.html#Py_Finalize
//pyLib_.reset();
}
}
<|endoftext|> |
<commit_before>/* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2006 Robert Osfield
*
* This application is open source and may be redistributed and/or modified
* freely and without restriction, both in commericial and non commericial
* applications, as long as this copyright notice is maintained.
*
* This application 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.
*
*/
#include <sstream>
#include <osg/Notify>
#include <osgDB/ReaderWriter>
#include <osgDB/FileNameUtils>
#include <osgDB/Registry>
#include "daeReader.h"
#include "daeWriter.h"
#define EXTENSION_NAME "dae"
///////////////////////////////////////////////////////////////////////////
// OSG reader/writer plugin for the COLLADA 1.4.x ".dae" format.
// See http://collada.org/ and http://khronos.org/collada/
class ReaderWriterDAE : public osgDB::ReaderWriter
{
public:
ReaderWriterDAE() : dae_(NULL)
{
}
~ReaderWriterDAE()
{
if(dae_ != NULL){
delete dae_;
DAE::cleanup();
dae_ = NULL;
}
}
const char* className() const { return "COLLADA 1.4.x DAE reader/writer"; }
bool acceptsExtension(const std::string& extension) const
{
return osgDB::equalCaseInsensitive( extension, EXTENSION_NAME );
}
ReadResult readNode(const std::string&, const Options*) const;
WriteResult writeNode(const osg::Node&, const std::string&, const Options*) const;
private:
DAE *dae_;
};
///////////////////////////////////////////////////////////////////////////
osgDB::ReaderWriter::ReadResult
ReaderWriterDAE::readNode(const std::string& fname,
const osgDB::ReaderWriter::Options* options) const
{
std::string ext( osgDB::getLowerCaseFileExtension(fname) );
if( ! acceptsExtension(ext) ) return ReadResult::FILE_NOT_HANDLED;
std::string fileName( osgDB::findDataFile( fname, options ) );
if( fileName.empty() ) return ReadResult::FILE_NOT_FOUND;
osg::notify(osg::INFO) << "ReaderWriterDAE( \"" << fileName << "\" )" << std::endl;
if (dae_ == NULL)
const_cast<ReaderWriterDAE *>(this)->dae_ = new DAE();
osgdae::daeReader daeReader(dae_);
std::string fileURI( osgDB::convertFileNameToUnixStyle(fileName) );
if ( ! daeReader.convert( fileURI ) )
{
osg::notify( osg::WARN ) << "Load failed in COLLADA DOM conversion" << std::endl;
return ReadResult::ERROR_IN_READING_FILE;
}
osg::Node* rootNode( daeReader.getRootNode() );
return rootNode;
}
///////////////////////////////////////////////////////////////////////////
osgDB::ReaderWriter::WriteResult
ReaderWriterDAE::writeNode( const osg::Node& node,
const std::string& fname, const osgDB::ReaderWriter::Options* options ) const
{
std::string ext( osgDB::getLowerCaseFileExtension(fname) );
if( ! acceptsExtension(ext) ) return WriteResult::FILE_NOT_HANDLED;
// Process options
bool usePolygon(false);
if( options )
{
std::istringstream iss( options->getOptionString() );
std::string opt;
while( std::getline( iss, opt, ',' ) )
{
if( opt == "polygon") usePolygon = true;
else
{
osg::notify(osg::WARN)
<< "\n" "COLLADA dae plugin: unrecognized option \"" << opt << "\"\n"
<< "comma-delimited options:\n"
<< "\tpolygon = use polygons instead of polylists for element\n"
<< "example: osgviewer -O polygon bar.dae" "\n"
<< std::endl;
}
}
}
if (dae_ == NULL)
const_cast<ReaderWriterDAE *>(this)->dae_ = new DAE();
osgdae::daeWriter daeWriter(dae_, fname, usePolygon );
daeWriter.setRootNode( node );
const_cast<osg::Node*>(&node)->accept( daeWriter );
osgDB::ReaderWriter::WriteResult retVal( WriteResult::ERROR_IN_WRITING_FILE );
if ( daeWriter.isSuccess() )
{
if ( daeWriter.writeFile() )
{
retVal = WriteResult::FILE_SAVED;
}
}
return retVal;
}
///////////////////////////////////////////////////////////////////////////
// Add ourself to the Registry to instantiate the reader/writer.
osgDB::RegisterReaderWriterProxy<ReaderWriterDAE> g_readerWriter_DAE_Proxy;
// vim: set sw=4 ts=8 et ic ai:
<commit_msg>Added SERIALIZER to ReaderWriterDAE to make sure initialization is thread safe.<commit_after>/* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2006 Robert Osfield
*
* This application is open source and may be redistributed and/or modified
* freely and without restriction, both in commericial and non commericial
* applications, as long as this copyright notice is maintained.
*
* This application 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.
*
*/
#include <sstream>
#include <osg/Notify>
#include <osgDB/ReaderWriter>
#include <osgDB/FileNameUtils>
#include <osgDB/Registry>
#include <OpenThreads/ScopedLock>
#include <osgDB/ReentrantMutex>
#include "daeReader.h"
#include "daeWriter.h"
#define EXTENSION_NAME "dae"
#define SERIALIZER() OpenThreads::ScopedLock<osgDB::ReentrantMutex> lock(_serializerMutex)
///////////////////////////////////////////////////////////////////////////
// OSG reader/writer plugin for the COLLADA 1.4.x ".dae" format.
// See http://collada.org/ and http://khronos.org/collada/
class ReaderWriterDAE : public osgDB::ReaderWriter
{
public:
ReaderWriterDAE() : _dae(NULL)
{
}
~ReaderWriterDAE()
{
if(_dae != NULL){
delete _dae;
DAE::cleanup();
_dae = NULL;
}
}
const char* className() const { return "COLLADA 1.4.x DAE reader/writer"; }
bool acceptsExtension(const std::string& extension) const
{
return osgDB::equalCaseInsensitive( extension, EXTENSION_NAME );
}
ReadResult readNode(const std::string&, const Options*) const;
WriteResult writeNode(const osg::Node&, const std::string&, const Options*) const;
private:
mutable DAE *_dae;
mutable osgDB::ReentrantMutex _serializerMutex;
};
///////////////////////////////////////////////////////////////////////////
osgDB::ReaderWriter::ReadResult
ReaderWriterDAE::readNode(const std::string& fname,
const osgDB::ReaderWriter::Options* options) const
{
SERIALIZER();
std::string ext( osgDB::getLowerCaseFileExtension(fname) );
if( ! acceptsExtension(ext) ) return ReadResult::FILE_NOT_HANDLED;
std::string fileName( osgDB::findDataFile( fname, options ) );
if( fileName.empty() ) return ReadResult::FILE_NOT_FOUND;
osg::notify(osg::INFO) << "ReaderWriterDAE( \"" << fileName << "\" )" << std::endl;
if (_dae == NULL)
_dae = new DAE();
osgdae::daeReader daeReader(_dae);
std::string fileURI( osgDB::convertFileNameToUnixStyle(fileName) );
if ( ! daeReader.convert( fileURI ) )
{
osg::notify( osg::WARN ) << "Load failed in COLLADA DOM conversion" << std::endl;
return ReadResult::ERROR_IN_READING_FILE;
}
osg::Node* rootNode( daeReader.getRootNode() );
return rootNode;
}
///////////////////////////////////////////////////////////////////////////
osgDB::ReaderWriter::WriteResult
ReaderWriterDAE::writeNode( const osg::Node& node,
const std::string& fname, const osgDB::ReaderWriter::Options* options ) const
{
SERIALIZER();
std::string ext( osgDB::getLowerCaseFileExtension(fname) );
if( ! acceptsExtension(ext) ) return WriteResult::FILE_NOT_HANDLED;
// Process options
bool usePolygon(false);
if( options )
{
std::istringstream iss( options->getOptionString() );
std::string opt;
while( std::getline( iss, opt, ',' ) )
{
if( opt == "polygon") usePolygon = true;
else
{
osg::notify(osg::WARN)
<< "\n" "COLLADA dae plugin: unrecognized option \"" << opt << "\"\n"
<< "comma-delimited options:\n"
<< "\tpolygon = use polygons instead of polylists for element\n"
<< "example: osgviewer -O polygon bar.dae" "\n"
<< std::endl;
}
}
}
if (_dae == NULL)
_dae = new DAE();
osgdae::daeWriter daeWriter(_dae, fname, usePolygon );
daeWriter.setRootNode( node );
const_cast<osg::Node*>(&node)->accept( daeWriter );
osgDB::ReaderWriter::WriteResult retVal( WriteResult::ERROR_IN_WRITING_FILE );
if ( daeWriter.isSuccess() )
{
if ( daeWriter.writeFile() )
{
retVal = WriteResult::FILE_SAVED;
}
}
return retVal;
}
///////////////////////////////////////////////////////////////////////////
// Add ourself to the Registry to instantiate the reader/writer.
osgDB::RegisterReaderWriterProxy<ReaderWriterDAE> g_readerWriter_DAE_Proxy;
// vim: set sw=4 ts=8 et ic ai:
<|endoftext|> |
<commit_before>#include "MatrixTransform.h"
#include "Group.h"
#include <osg/Notify>
#include <osgDB/FileNameUtils>
#include <osgDB/FileUtils>
#include <osgDB/Registry>
using namespace osg;
using namespace osgDB;
class IVEReaderWriter : public ReaderWriter
{
public:
virtual const char* className() const { return "IVE Reader/Writer"; }
virtual bool acceptsExtension(const std::string& extension) const
{
return equalCaseInsensitive(extension,"ive");
}
virtual ReadResult readObject(const std::string& file, const Options* options) const
{
return readNode(file, options);
}
virtual ReadResult readNode(const std::string& file, const Options* options) const
{
std::string ext = osgDB::getLowerCaseFileExtension(file);
if (!acceptsExtension(ext)) return ReadResult::FILE_NOT_HANDLED;
std::string fileName = osgDB::findDataFile( file, options );
if (fileName.empty()) return ReadResult::FILE_NOT_FOUND;
// code for setting up the database path so that internally referenced file are searched for on relative paths.
osg::ref_ptr<Options> local_opt = options ? static_cast<Options*>(options->clone(osg::CopyOp::SHALLOW_COPY)) : new Options;
local_opt->setDatabasePath(osgDB::getFilePath(fileName));
std::ifstream istream(fileName.c_str(), std::ios::in | std::ios::binary);
return readNode(istream,local_opt.get());
}
virtual ReadResult readObject(std::istream& fin, const Options* options) const
{
return readNode(fin, options);
}
virtual ReadResult readNode(std::istream& fin, const Options* options) const
{
try{
// Create datainputstream.
ive::DataInputStream in(&fin);
in.setOptions(options);
return in.readNode();
}
catch(ive::Exception e)
{
osg::notify(osg::NOTICE)<<"Error reading file: "<< e.getError()<<std::endl;
return ReadResult::FILE_NOT_HANDLED;
}
}
virtual WriteResult writeObject(const Object& object,const std::string& fileName, const osgDB::ReaderWriter::Options* options) const
{
const Node* node = dynamic_cast<const Node*>(&object);
if (node) return writeNode( *node, fileName, options );
return WriteResult::FILE_NOT_HANDLED;
}
virtual WriteResult writeNode(const Node& node,const std::string& fileName, const osgDB::ReaderWriter::Options* options) const
{
std::string ext = getFileExtension(fileName);
if (!acceptsExtension(ext)) return WriteResult::FILE_NOT_HANDLED;
// code for setting up the database path so that internally referenced file are searched for on relative paths.
osg::ref_ptr<Options> local_opt = options ? static_cast<Options*>(options->clone(osg::CopyOp::SHALLOW_COPY)) : new Options;
if(local_opt->getDatabasePathList().empty())
local_opt->setDatabasePath(osgDB::getFilePath(fileName));
std::ofstream fout(fileName.c_str(), std::ios::out | std::ios::binary);
if (!fout) return WriteResult::ERROR_IN_WRITING_FILE;
WriteResult result = writeNode(node, fout, local_opt.get());
fout.close();
return result;
}
virtual WriteResult writeObject(const Object& object,std::ostream& fout, const osgDB::ReaderWriter::Options* options) const
{
const Node* node = dynamic_cast<const Node*>(&object);
if (node) return writeNode( *node, fout, options );
return WriteResult::FILE_NOT_HANDLED;
}
virtual WriteResult writeNode(const Node& node,std::ostream& fout, const osgDB::ReaderWriter::Options* options) const
{
try
{
ive::DataOutputStream out(&fout);
out.setOptions(options);
out.writeNode(const_cast<osg::Node*>(&node));
if ( fout.fail() ) return WriteResult::ERROR_IN_WRITING_FILE;
return WriteResult::FILE_SAVED;
}
catch(ive::Exception e)
{
osg::notify(osg::WARN)<<"Error writing IVE file: "<< e.getError() << std::endl;
}
return WriteResult::FILE_NOT_HANDLED;
}
};
// now register with Registry to instantiate the above
// reader/writer.
RegisterReaderWriterProxy<IVEReaderWriter> g_IVEReaderWriterProxy;
<commit_msg>From Eric Sokolowski, "Added the ability to read and write images directly in the ive plugin, through the osgDB::readImageFile and osgDB::writeImageFile functions. This is useful for storing compressed textures on disk for rapid playback for animations."<commit_after>#include "MatrixTransform.h"
#include "Group.h"
#include <osg/Notify>
#include <osgDB/FileNameUtils>
#include <osgDB/FileUtils>
#include <osgDB/Registry>
using namespace osg;
using namespace osgDB;
class IVEReaderWriter : public ReaderWriter
{
public:
virtual const char* className() const { return "IVE Reader/Writer"; }
virtual bool acceptsExtension(const std::string& extension) const
{
return equalCaseInsensitive(extension,"ive");
}
virtual ReadResult readObject(const std::string& file, const Options* options) const
{
return readNode(file, options);
}
virtual ReadResult readImage(const std::string& file, const Options* options) const
{
std::string ext = osgDB::getLowerCaseFileExtension(file);
if (!acceptsExtension(ext)) return ReadResult::FILE_NOT_HANDLED;
std::string fileName = osgDB::findDataFile(file, options);
if (fileName.empty()) return ReadResult::FILE_NOT_FOUND;
// code for setting up the database path so that internally referenced files are searched for on relative paths.
osg::ref_ptr<Options> local_opt = options ? static_cast<Options*>(options->clone(osg::CopyOp::SHALLOW_COPY)) : new Options;
local_opt->setDatabasePath(osgDB::getFilePath(fileName));
std::ifstream istream(fileName.c_str(), std::ios::in | std::ios::binary);
return readImage(istream, local_opt.get());
}
virtual ReadResult readNode(const std::string& file, const Options* options) const
{
std::string ext = osgDB::getLowerCaseFileExtension(file);
if (!acceptsExtension(ext)) return ReadResult::FILE_NOT_HANDLED;
std::string fileName = osgDB::findDataFile( file, options );
if (fileName.empty()) return ReadResult::FILE_NOT_FOUND;
// code for setting up the database path so that internally referenced file are searched for on relative paths.
osg::ref_ptr<Options> local_opt = options ? static_cast<Options*>(options->clone(osg::CopyOp::SHALLOW_COPY)) : new Options;
local_opt->setDatabasePath(osgDB::getFilePath(fileName));
std::ifstream istream(fileName.c_str(), std::ios::in | std::ios::binary);
return readNode(istream,local_opt.get());
}
virtual ReadResult readObject(std::istream& fin, const Options* options) const
{
return readNode(fin, options);
}
virtual ReadResult readImage(std::istream& fin, const Options* options) const
{
try{
ive::DataInputStream in(&fin);
in.setOptions(options);
return in.readImage(ive::IMAGE_INCLUDE_DATA);
}
catch(ive::Exception e)
{
osg::notify(osg::NOTICE)<<"Error reading image: "<<e.getError()<<std::endl;
return ReadResult::FILE_NOT_HANDLED;
}
}
virtual ReadResult readNode(std::istream& fin, const Options* options) const
{
try{
// Create datainputstream.
ive::DataInputStream in(&fin);
in.setOptions(options);
return in.readNode();
}
catch(ive::Exception e)
{
osg::notify(osg::NOTICE)<<"Error reading file: "<< e.getError()<<std::endl;
return ReadResult::FILE_NOT_HANDLED;
}
}
virtual WriteResult writeObject(const Object& object,const std::string& fileName, const osgDB::ReaderWriter::Options* options) const
{
const Node* node = dynamic_cast<const Node*>(&object);
if (node) return writeNode( *node, fileName, options );
const Image* image = dynamic_cast<const Image*>(&object);
if (image) return writeImage(*image, fileName, options);
return WriteResult::FILE_NOT_HANDLED;
}
virtual WriteResult writeImage(const Image& image,const std::string& fileName, const osgDB::ReaderWriter::Options* options) const
{
std::string ext = getFileExtension(fileName);
if (!acceptsExtension(ext)) return WriteResult::FILE_NOT_HANDLED;
// code for setting up the database path so that internally referenced file are searched for on relative paths.
osg::ref_ptr<Options> local_opt = options ? static_cast<Options*>(options->clone(osg::CopyOp::SHALLOW_COPY)) : new Options;
if(local_opt->getDatabasePathList().empty())
local_opt->setDatabasePath(osgDB::getFilePath(fileName));
std::ofstream fout(fileName.c_str(), std::ios::out | std::ios::binary);
if (!fout) return WriteResult::ERROR_IN_WRITING_FILE;
WriteResult result = writeImage(image, fout, local_opt.get());
fout.close();
return result;
}
virtual WriteResult writeNode(const Node& node,const std::string& fileName, const osgDB::ReaderWriter::Options* options) const
{
std::string ext = getFileExtension(fileName);
if (!acceptsExtension(ext)) return WriteResult::FILE_NOT_HANDLED;
// code for setting up the database path so that internally referenced file are searched for on relative paths.
osg::ref_ptr<Options> local_opt = options ? static_cast<Options*>(options->clone(osg::CopyOp::SHALLOW_COPY)) : new Options;
if(local_opt->getDatabasePathList().empty())
local_opt->setDatabasePath(osgDB::getFilePath(fileName));
std::ofstream fout(fileName.c_str(), std::ios::out | std::ios::binary);
if (!fout) return WriteResult::ERROR_IN_WRITING_FILE;
WriteResult result = writeNode(node, fout, local_opt.get());
fout.close();
return result;
}
virtual WriteResult writeObject(const Object& object,std::ostream& fout, const osgDB::ReaderWriter::Options* options) const
{
const Node* node = dynamic_cast<const Node*>(&object);
if (node) return writeNode( *node, fout, options );
const Image* image = dynamic_cast<const Image*>(&object);
if (image) return writeImage(*image, fout, options);
return WriteResult::FILE_NOT_HANDLED;
}
virtual WriteResult writeImage(const Image& image,std::ostream& fout, const osgDB::ReaderWriter::Options* options) const
{
try
{
ive::DataOutputStream out(&fout);
out.setOptions(options);
out.writeImage(ive::IMAGE_INCLUDE_DATA, const_cast<osg::Image*>(&image));
if (fout.fail()) return WriteResult::ERROR_IN_WRITING_FILE;
return WriteResult::FILE_SAVED;
}
catch(ive::Exception e)
{
osg::notify(osg::WARN)<<"Error writing IVE image: "<< e.getError() << std::endl;
}
return WriteResult::FILE_NOT_HANDLED;
}
virtual WriteResult writeNode(const Node& node,std::ostream& fout, const osgDB::ReaderWriter::Options* options) const
{
try
{
ive::DataOutputStream out(&fout);
out.setOptions(options);
out.writeNode(const_cast<osg::Node*>(&node));
if ( fout.fail() ) return WriteResult::ERROR_IN_WRITING_FILE;
return WriteResult::FILE_SAVED;
}
catch(ive::Exception e)
{
osg::notify(osg::WARN)<<"Error writing IVE file: "<< e.getError() << std::endl;
}
return WriteResult::FILE_NOT_HANDLED;
}
};
// now register with Registry to instantiate the above
// reader/writer.
RegisterReaderWriterProxy<IVEReaderWriter> g_IVEReaderWriterProxy;
<|endoftext|> |
<commit_before>#include <iostream>
#include <fstream>
#include <sstream>
#include <osg/Notify>
#include <osgDB/Input>
#include <osgDB/Registry>
#include <osgDB/FileUtils>
#include <osgDB/FileNameUtils>
#include <osgDB/ReadFile>
#include <osgDB/WriteFile>
#include <osgDB/FileUtils>
#include <osg/MatrixTransform>
#include <osg/Group>
#include <osg/Timer>
#include "sockinet.h"
/*
* Semantics:
* Two methods for using the .net loader.
* 1) Add a hostname prefix and a '.net' suffix on a model when passing
* to osgDB::readNodeFile()
* e.g: osgDB::readNodeFile( "openscenegraph.org:cow.osg.net" );
*
* 2) Explicitely load the .net plugin and pass the plugin options including
* hostname=<hostname>
*
* Method #1 takes precedence. SO, if the hostname option is passed the
* plugin, but the name also contains a hostname prefix, the hostname
* prefix on the file name will override the option
*
* Plugin options:
* hostname=<hostname> - Specify the host where the data file is to
* be fetched from.
*
* prefix=<prefix> - Specify a server directory to prefix the
* file name with.
*
* local_cache_dir=<dir> - Specify a directory in which to cache files
* on the local machine once they've been fetched.
* This directory is also searched before fetching
* the file from the server when Read mode is
* enabled on the cache.
*
* cache_mode=<mode> - Set the mode for the local cache if local_cache
* was specified. If local_cache was not specified
* this directive is ignored. <mode> may
* be specified with ReadOnly, WriteOnly, or
* ReadWrite. Behavior for the different modes is
* defined as:
*
* ReadOnly - When retrieving files, cache is
* searched first, and if the file is
* not present, it is fetched from the
* server. If it is fetched from the
* server it is not stored in local cache
*
* WriteOnly - When retrieving files, cache is not
* searched, file is always retrieved
* from the server and always written to
* cache.
*
* ReadWrite - (the default). When retrieving files
* cache is searched first, if file is
* not present in cache, it is fetched from
* the server. If fetched, it is written
* to cache.
*
*/
class NetReader : public osgDB::ReaderWriter
{
public:
NetReader() {}
virtual const char* className() { return "HTTP Protocol Model Reader"; }
virtual bool acceptsExtension(const std::string& extension)
{
return osgDB::equalCaseInsensitive(extension,"net");
}
enum ObjectType
{
OBJECT,
IMAGE,
HEIGHTFIELD,
NODE
};
virtual ReadResult readObject(const std::string& fileName, const Options* options)
{
return readFile(OBJECT,fileName,options);
}
virtual ReadResult readImage(const std::string& fileName, const Options *options)
{
return readFile(IMAGE,fileName,options);
}
virtual ReadResult readHeightField(const std::string& fileName, const Options *options)
{
return readFile(HEIGHTFIELD,fileName,options);
}
virtual ReadResult readNode(const std::string& fileName, const Options *options)
{
return readFile(NODE,fileName,options);
}
ReadResult readFile(ObjectType objectType, ReaderWriter* rw, std::istream& fin, const Options *options)
{
switch(objectType)
{
case(OBJECT): return rw->readObject(fin,options);
case(IMAGE): return rw->readImage(fin,options);
case(HEIGHTFIELD): return rw->readHeightField(fin,options);
case(NODE): return rw->readNode(fin,options);
default: break;
}
}
virtual ReadResult readFile(ObjectType objectType, const std::string& inFileName, const Options *options)
{
osg::Timer_t start = osg::Timer::instance()->tick();
osg::notify(osg::DEBUG_INFO) << "osgPlugin .net: start load" << inFileName << std::endl;
std::string hostname;
std::string serverPrefix;
std::string localCacheDir;
int port = 80;
enum CacheMode {
Read = 1,
Write = 2,
ReadWrite = 3
};
CacheMode cacheMode = ReadWrite;
if (options)
{
std::istringstream iss(options->getOptionString());
std::string opt;
while (iss >> opt)
{
int index = opt.find( "=" );
if( opt.substr( 0, index ) == "hostname" ||
opt.substr( 0, index ) == "HOSTNAME" )
{
hostname = opt.substr( index+1 );
}
else if( opt.substr( 0, index ) == "port" ||
opt.substr( 0, index ) == "PORT" )
{
port = atoi( opt.substr(index+1).c_str() );
}
else if( opt.substr( 0, index ) == "server_prefix" ||
opt.substr( 0, index ) == "SERVER_PREFIX" ||
opt.substr( 0, index ) == "prefix" ||
opt.substr( 0, index ) == "PREFIX" )
{
serverPrefix = opt.substr(index+1);
}
else if( opt.substr( 0, index ) == "local_cache_dir" ||
opt.substr( 0, index ) == "LOCAL_CACHE_DIR" )
{
localCacheDir = opt.substr(index+1);
}
else if( opt.substr( 0, index ) == "cache_mode" ||
opt.substr( 0, index ) == "CACHE_MODE" )
{
if( opt.substr(index+1) == "ReadOnly" )
cacheMode = Read;
else if( opt.substr(index+1) == "WriteOnly" )
cacheMode = Write;
else if( opt.substr(index+1) == "ReadWrite" )
cacheMode = ReadWrite;
else
osg::notify(osg::WARN) <<
"NET plug-in warning: cache_mode " << opt.substr(index+1) <<
" not understood. Defaulting to ReadWrite." << std::endl;
}
}
}
ReadResult readResult = ReadResult::FILE_NOT_HANDLED;
/* * we accept all extensions
std::string ext = osgDB::getFileExtension(inFileName);
if (!acceptsExtension(ext))
return ReadResult::FILE_NOT_HANDLED;
*/
std::string fileName;
int index = inFileName.find(":");
// If we haven't been given a hostname as an option
// and it hasn't been prefixed to the name, we fail
if( index != -1 )
{
hostname = inFileName.substr( 0, index);
// need to strip the inFileName of the hostname prefix
fileName = inFileName.substr( index+1 );
}
else
{
if( hostname.empty() )
return ReadResult::FILE_NOT_HANDLED;
else
fileName = inFileName;
}
// Let's also strip the possible .net extension
if( osgDB::getFileExtension( fileName ) == "net" )
{
int rindex = fileName.rfind( "." );
fileName = fileName.substr( 0, rindex );
}
if( !serverPrefix.empty() )
fileName = serverPrefix + '/' + fileName;
// Invoke the reader corresponding to the extension
osgDB::ReaderWriter *reader =
osgDB::Registry::instance()->getReaderWriterForExtension( osgDB::getFileExtension(fileName));
if( reader == 0L )
return ReadResult::FILE_NOT_HANDLED;
// Before we go to the network, lets see if it is in local cache, if cache
// was specified and Read bit is set
if( !localCacheDir.empty() && (cacheMode & Read) )
{
std::string cacheFile = localCacheDir + '/' + fileName;
if( osgDB::fileExists( cacheFile ))
{
std::ifstream in(cacheFile.c_str());
readResult = readFile(objectType, reader, in, options );
in.close();
osg::notify(osg::DEBUG_INFO) << "osgPlugin .net: " << fileName <<
" fetched from local cache." << std::endl;
return readResult;
}
}
// Fetch from the network
iosockinet sio (sockbuf::sock_stream);
try {
sio->connect( hostname.c_str(), port );
}
catch( sockerr e )
{
osg::notify(osg::WARN) << "osgPlugin .net reader: Unable to connect to host " << hostname << std::endl;
return ReadResult::FILE_NOT_FOUND;
}
sio << "GET /" << fileName << " HTTP/1.1\n" << "Host:\n\n";
sio.flush();
char linebuff[256];
do
{
sio.getline( linebuff, sizeof( linebuff ));
std::istringstream iss(linebuff);
std::string directive;
iss >> directive;
if( directive.substr(0,4) == "HTTP" )
{
iss >> directive;
// Code 200. We be ok.
if( directive == "200" )
;
// Code 400 Bad Request
else if( directive == "400" )
{
osg::notify(osg::WARN) <<
"osgPlugin .net: http server response 400 - Bad Request" << std::endl;
return ReadResult::FILE_NOT_FOUND;
}
// Code 401 Bad Request
else if( directive == "401" )
{
osg::notify(osg::WARN) <<
"osgPlugin .net: http server response 401 - Unauthorized Access" << std::endl;
return ReadResult::FILE_NOT_FOUND;
}
// Code 403 Bad Request
else if( directive == "403" )
{
osg::notify(osg::WARN) <<
"osgPlugin .net: http server response 403 - Access Forbidden" << std::endl;
return ReadResult::FILE_NOT_FOUND;
}
// Code 404 File not found
else if( directive == "404" )
{
osg::notify(osg::WARN) <<
"osgPlugin .net: http server response 404 - File Not Found" << std::endl;
return ReadResult::FILE_NOT_FOUND;
}
// Code 405 Method not allowed
else if( directive == "405" )
{
osg::notify(osg::WARN) <<
"osgPlugin .net: http server response 405 - Method Not Allowed" << std::endl;
return ReadResult::FILE_NOT_FOUND;
}
// There's more....
}
} while( linebuff[0] != '\r' );
// code for setting up the database path so that any paged
// databases can be automatically located.
osg::ref_ptr<Options> local_opt = const_cast<Options*>(options);
if (!local_opt) local_opt = new Options;
if (local_opt.valid() && local_opt->getDatabasePath().empty())
{
local_opt->setDatabasePath(osgDB::getFilePath(inFileName));
}
if( reader != 0L )
readResult = readFile(objectType, reader, sio, local_opt.get() );
double ms = osg::Timer::instance()->delta_m(start,osg::Timer::instance()->tick());
osg::notify(osg::DEBUG_INFO) << "osgPlugin .net: " << fileName <<
" fetched from server. in" << ms <<" ms"<< std::endl;
if( !localCacheDir.empty() && cacheMode & Write )
{
std::string cacheFile = localCacheDir + '/' + fileName;
if( osgDB::makeDirectoryForFile( cacheFile ) )
{
switch(objectType)
{
case(OBJECT): osgDB::writeObjectFile( *(readResult.getObject()), cacheFile );
case(IMAGE): osgDB::writeImageFile( *(readResult.getImage()), cacheFile );
case(HEIGHTFIELD): osgDB::writeHeightFieldFile( *(readResult.getHeightField()), cacheFile );
case(NODE): osgDB::writeNodeFile( *(readResult.getNode()), cacheFile );;
default: break;
}
osg::notify(osg::DEBUG_INFO) << "osgPlugin .net: " << fileName <<
" stored to local cache." << std::endl;
}
}
return readResult;
}
};
osgDB::RegisterReaderWriterProxy<NetReader> g_netReader_Proxy;
<commit_msg>Small warning fix by Marco.<commit_after>#include <iostream>
#include <fstream>
#include <sstream>
#include <osg/Notify>
#include <osgDB/Input>
#include <osgDB/Registry>
#include <osgDB/FileUtils>
#include <osgDB/FileNameUtils>
#include <osgDB/ReadFile>
#include <osgDB/WriteFile>
#include <osgDB/FileUtils>
#include <osg/MatrixTransform>
#include <osg/Group>
#include <osg/Timer>
#include "sockinet.h"
/*
* Semantics:
* Two methods for using the .net loader.
* 1) Add a hostname prefix and a '.net' suffix on a model when passing
* to osgDB::readNodeFile()
* e.g: osgDB::readNodeFile( "openscenegraph.org:cow.osg.net" );
*
* 2) Explicitely load the .net plugin and pass the plugin options including
* hostname=<hostname>
*
* Method #1 takes precedence. SO, if the hostname option is passed the
* plugin, but the name also contains a hostname prefix, the hostname
* prefix on the file name will override the option
*
* Plugin options:
* hostname=<hostname> - Specify the host where the data file is to
* be fetched from.
*
* prefix=<prefix> - Specify a server directory to prefix the
* file name with.
*
* local_cache_dir=<dir> - Specify a directory in which to cache files
* on the local machine once they've been fetched.
* This directory is also searched before fetching
* the file from the server when Read mode is
* enabled on the cache.
*
* cache_mode=<mode> - Set the mode for the local cache if local_cache
* was specified. If local_cache was not specified
* this directive is ignored. <mode> may
* be specified with ReadOnly, WriteOnly, or
* ReadWrite. Behavior for the different modes is
* defined as:
*
* ReadOnly - When retrieving files, cache is
* searched first, and if the file is
* not present, it is fetched from the
* server. If it is fetched from the
* server it is not stored in local cache
*
* WriteOnly - When retrieving files, cache is not
* searched, file is always retrieved
* from the server and always written to
* cache.
*
* ReadWrite - (the default). When retrieving files
* cache is searched first, if file is
* not present in cache, it is fetched from
* the server. If fetched, it is written
* to cache.
*
*/
class NetReader : public osgDB::ReaderWriter
{
public:
NetReader() {}
virtual const char* className() { return "HTTP Protocol Model Reader"; }
virtual bool acceptsExtension(const std::string& extension)
{
return osgDB::equalCaseInsensitive(extension,"net");
}
enum ObjectType
{
OBJECT,
IMAGE,
HEIGHTFIELD,
NODE
};
virtual ReadResult readObject(const std::string& fileName, const Options* options)
{
return readFile(OBJECT,fileName,options);
}
virtual ReadResult readImage(const std::string& fileName, const Options *options)
{
return readFile(IMAGE,fileName,options);
}
virtual ReadResult readHeightField(const std::string& fileName, const Options *options)
{
return readFile(HEIGHTFIELD,fileName,options);
}
virtual ReadResult readNode(const std::string& fileName, const Options *options)
{
return readFile(NODE,fileName,options);
}
ReadResult readFile(ObjectType objectType, ReaderWriter* rw, std::istream& fin, const Options *options)
{
switch(objectType)
{
case(OBJECT): return rw->readObject(fin,options);
case(IMAGE): return rw->readImage(fin,options);
case(HEIGHTFIELD): return rw->readHeightField(fin,options);
case(NODE): return rw->readNode(fin,options);
default: break;
}
return ReadResult::FILE_NOT_HANDLED;
}
virtual ReadResult readFile(ObjectType objectType, const std::string& inFileName, const Options *options)
{
osg::Timer_t start = osg::Timer::instance()->tick();
osg::notify(osg::DEBUG_INFO) << "osgPlugin .net: start load" << inFileName << std::endl;
std::string hostname;
std::string serverPrefix;
std::string localCacheDir;
int port = 80;
enum CacheMode {
Read = 1,
Write = 2,
ReadWrite = 3
};
CacheMode cacheMode = ReadWrite;
if (options)
{
std::istringstream iss(options->getOptionString());
std::string opt;
while (iss >> opt)
{
int index = opt.find( "=" );
if( opt.substr( 0, index ) == "hostname" ||
opt.substr( 0, index ) == "HOSTNAME" )
{
hostname = opt.substr( index+1 );
}
else if( opt.substr( 0, index ) == "port" ||
opt.substr( 0, index ) == "PORT" )
{
port = atoi( opt.substr(index+1).c_str() );
}
else if( opt.substr( 0, index ) == "server_prefix" ||
opt.substr( 0, index ) == "SERVER_PREFIX" ||
opt.substr( 0, index ) == "prefix" ||
opt.substr( 0, index ) == "PREFIX" )
{
serverPrefix = opt.substr(index+1);
}
else if( opt.substr( 0, index ) == "local_cache_dir" ||
opt.substr( 0, index ) == "LOCAL_CACHE_DIR" )
{
localCacheDir = opt.substr(index+1);
}
else if( opt.substr( 0, index ) == "cache_mode" ||
opt.substr( 0, index ) == "CACHE_MODE" )
{
if( opt.substr(index+1) == "ReadOnly" )
cacheMode = Read;
else if( opt.substr(index+1) == "WriteOnly" )
cacheMode = Write;
else if( opt.substr(index+1) == "ReadWrite" )
cacheMode = ReadWrite;
else
osg::notify(osg::WARN) <<
"NET plug-in warning: cache_mode " << opt.substr(index+1) <<
" not understood. Defaulting to ReadWrite." << std::endl;
}
}
}
ReadResult readResult = ReadResult::FILE_NOT_HANDLED;
/* * we accept all extensions
std::string ext = osgDB::getFileExtension(inFileName);
if (!acceptsExtension(ext))
return ReadResult::FILE_NOT_HANDLED;
*/
std::string fileName;
int index = inFileName.find(":");
// If we haven't been given a hostname as an option
// and it hasn't been prefixed to the name, we fail
if( index != -1 )
{
hostname = inFileName.substr( 0, index);
// need to strip the inFileName of the hostname prefix
fileName = inFileName.substr( index+1 );
}
else
{
if( hostname.empty() )
return ReadResult::FILE_NOT_HANDLED;
else
fileName = inFileName;
}
// Let's also strip the possible .net extension
if( osgDB::getFileExtension( fileName ) == "net" )
{
int rindex = fileName.rfind( "." );
fileName = fileName.substr( 0, rindex );
}
if( !serverPrefix.empty() )
fileName = serverPrefix + '/' + fileName;
// Invoke the reader corresponding to the extension
osgDB::ReaderWriter *reader =
osgDB::Registry::instance()->getReaderWriterForExtension( osgDB::getFileExtension(fileName));
if( reader == 0L )
return ReadResult::FILE_NOT_HANDLED;
// Before we go to the network, lets see if it is in local cache, if cache
// was specified and Read bit is set
if( !localCacheDir.empty() && (cacheMode & Read) )
{
std::string cacheFile = localCacheDir + '/' + fileName;
if( osgDB::fileExists( cacheFile ))
{
std::ifstream in(cacheFile.c_str());
readResult = readFile(objectType, reader, in, options );
in.close();
osg::notify(osg::DEBUG_INFO) << "osgPlugin .net: " << fileName <<
" fetched from local cache." << std::endl;
return readResult;
}
}
// Fetch from the network
iosockinet sio (sockbuf::sock_stream);
try {
sio->connect( hostname.c_str(), port );
}
catch( sockerr e )
{
osg::notify(osg::WARN) << "osgPlugin .net reader: Unable to connect to host " << hostname << std::endl;
return ReadResult::FILE_NOT_FOUND;
}
sio << "GET /" << fileName << " HTTP/1.1\n" << "Host:\n\n";
sio.flush();
char linebuff[256];
do
{
sio.getline( linebuff, sizeof( linebuff ));
std::istringstream iss(linebuff);
std::string directive;
iss >> directive;
if( directive.substr(0,4) == "HTTP" )
{
iss >> directive;
// Code 200. We be ok.
if( directive == "200" )
;
// Code 400 Bad Request
else if( directive == "400" )
{
osg::notify(osg::WARN) <<
"osgPlugin .net: http server response 400 - Bad Request" << std::endl;
return ReadResult::FILE_NOT_FOUND;
}
// Code 401 Bad Request
else if( directive == "401" )
{
osg::notify(osg::WARN) <<
"osgPlugin .net: http server response 401 - Unauthorized Access" << std::endl;
return ReadResult::FILE_NOT_FOUND;
}
// Code 403 Bad Request
else if( directive == "403" )
{
osg::notify(osg::WARN) <<
"osgPlugin .net: http server response 403 - Access Forbidden" << std::endl;
return ReadResult::FILE_NOT_FOUND;
}
// Code 404 File not found
else if( directive == "404" )
{
osg::notify(osg::WARN) <<
"osgPlugin .net: http server response 404 - File Not Found" << std::endl;
return ReadResult::FILE_NOT_FOUND;
}
// Code 405 Method not allowed
else if( directive == "405" )
{
osg::notify(osg::WARN) <<
"osgPlugin .net: http server response 405 - Method Not Allowed" << std::endl;
return ReadResult::FILE_NOT_FOUND;
}
// There's more....
}
} while( linebuff[0] != '\r' );
// code for setting up the database path so that any paged
// databases can be automatically located.
osg::ref_ptr<Options> local_opt = const_cast<Options*>(options);
if (!local_opt) local_opt = new Options;
if (local_opt.valid() && local_opt->getDatabasePath().empty())
{
local_opt->setDatabasePath(osgDB::getFilePath(inFileName));
}
if( reader != 0L )
readResult = readFile(objectType, reader, sio, local_opt.get() );
double ms = osg::Timer::instance()->delta_m(start,osg::Timer::instance()->tick());
osg::notify(osg::DEBUG_INFO) << "osgPlugin .net: " << fileName <<
" fetched from server. in" << ms <<" ms"<< std::endl;
if( !localCacheDir.empty() && cacheMode & Write )
{
std::string cacheFile = localCacheDir + '/' + fileName;
if( osgDB::makeDirectoryForFile( cacheFile ) )
{
switch(objectType)
{
case(OBJECT): osgDB::writeObjectFile( *(readResult.getObject()), cacheFile );
case(IMAGE): osgDB::writeImageFile( *(readResult.getImage()), cacheFile );
case(HEIGHTFIELD): osgDB::writeHeightFieldFile( *(readResult.getHeightField()), cacheFile );
case(NODE): osgDB::writeNodeFile( *(readResult.getNode()), cacheFile );;
default: break;
}
osg::notify(osg::DEBUG_INFO) << "osgPlugin .net: " << fileName <<
" stored to local cache." << std::endl;
}
}
return readResult;
}
};
osgDB::RegisterReaderWriterProxy<NetReader> g_netReader_Proxy;
<|endoftext|> |
<commit_before>#include <iostream>
#include <fstream>
#include <sstream>
#include <osg/Notify>
#include <osgDB/Input>
#include <osgDB/Registry>
#include <osgDB/FileUtils>
#include <osgDB/FileNameUtils>
#include <osgDB/ReadFile>
#include <osgDB/WriteFile>
#include <osgDB/FileUtils>
#include <osg/MatrixTransform>
#include <osg/Group>
#include <osg/Timer>
#include "sockinet.h"
/*
* Semantics:
* Two methods for using the .net loader.
* 1) Add a hostname prefix and a '.net' suffix on a model when passing
* to osgDB::readNodeFile()
* e.g: osgDB::readNodeFile( "openscenegraph.org:cow.osg.net" );
*
* 2) Explicitely load the .net plugin and pass the plugin options including
* hostname=<hostname>
*
* Method #1 takes precedence. SO, if the hostname option is passed the
* plugin, but the name also contains a hostname prefix, the hostname
* prefix on the file name will override the option
*
* Plugin options:
* hostname=<hostname> - Specify the host where the data file is to
* be fetched from.
*
* prefix=<prefix> - Specify a server directory to prefix the
* file name with.
*
* local_cache_dir=<dir> - Specify a directory in which to cache files
* on the local machine once they've been fetched.
* This directory is also searched before fetching
* the file from the server when Read mode is
* enabled on the cache.
*
* cache_mode=<mode> - Set the mode for the local cache if local_cache
* was specified. If local_cache was not specified
* this directive is ignored. <mode> may
* be specified with ReadOnly, WriteOnly, or
* ReadWrite. Behavior for the different modes is
* defined as:
*
* ReadOnly - When retrieving files, cache is
* searched first, and if the file is
* not present, it is fetched from the
* server. If it is fetched from the
* server it is not stored in local cache
*
* WriteOnly - When retrieving files, cache is not
* searched, file is always retrieved
* from the server and always written to
* cache.
*
* ReadWrite - (the default). When retrieving files
* cache is searched first, if file is
* not present in cache, it is fetched from
* the server. If fetched, it is written
* to cache.
*
*/
class NetReader : public osgDB::ReaderWriter
{
public:
NetReader() {}
virtual const char* className() { return "HTTP Protocol Model Reader"; }
virtual bool acceptsExtension(const std::string& extension)
{
return osgDB::equalCaseInsensitive(extension,"net");
}
enum ObjectType
{
OBJECT,
IMAGE,
HEIGHTFIELD,
NODE
};
virtual ReadResult readObject(const std::string& fileName, const Options* options)
{
return readFile(OBJECT,fileName,options);
}
virtual ReadResult readImage(const std::string& fileName, const Options *options)
{
return readFile(IMAGE,fileName,options);
}
virtual ReadResult readHeightField(const std::string& fileName, const Options *options)
{
return readFile(HEIGHTFIELD,fileName,options);
}
virtual ReadResult readNode(const std::string& fileName, const Options *options)
{
return readFile(NODE,fileName,options);
}
ReadResult readFile(ObjectType objectType, ReaderWriter* rw, std::istream& fin, const Options *options)
{
switch(objectType)
{
case(OBJECT): return rw->readObject(fin,options);
case(IMAGE): return rw->readImage(fin,options);
case(HEIGHTFIELD): return rw->readHeightField(fin,options);
case(NODE): return rw->readNode(fin,options);
}
}
virtual ReadResult readFile(ObjectType objectType, const std::string& inFileName, const Options *options)
{
osg::Timer_t start = osg::Timer::instance()->tick();
osg::notify(osg::DEBUG_INFO) << "osgPlugin .net: start load" << inFileName << std::endl;
std::string hostname;
std::string serverPrefix;
std::string localCacheDir;
int port = 80;
enum CacheMode {
Read = 1,
Write = 2,
ReadWrite = 3
};
CacheMode cacheMode = ReadWrite;
if (options)
{
std::istringstream iss(options->getOptionString());
std::string opt;
while (iss >> opt)
{
int index = opt.find( "=" );
if( opt.substr( 0, index ) == "hostname" ||
opt.substr( 0, index ) == "HOSTNAME" )
{
hostname = opt.substr( index+1 );
}
else if( opt.substr( 0, index ) == "port" ||
opt.substr( 0, index ) == "PORT" )
{
port = atoi( opt.substr(index+1).c_str() );
}
else if( opt.substr( 0, index ) == "server_prefix" ||
opt.substr( 0, index ) == "SERVER_PREFIX" ||
opt.substr( 0, index ) == "prefix" ||
opt.substr( 0, index ) == "PREFIX" )
{
serverPrefix = opt.substr(index+1);
}
else if( opt.substr( 0, index ) == "local_cache_dir" ||
opt.substr( 0, index ) == "LOCAL_CACHE_DIR" )
{
localCacheDir = opt.substr(index+1);
}
else if( opt.substr( 0, index ) == "cache_mode" ||
opt.substr( 0, index ) == "CACHE_MODE" )
{
if( opt.substr(index+1) == "ReadOnly" )
cacheMode = Read;
else if( opt.substr(index+1) == "WriteOnly" )
cacheMode = Write;
else if( opt.substr(index+1) == "ReadWrite" )
cacheMode = ReadWrite;
else
osg::notify(osg::WARN) <<
"NET plug-in warning: cache_mode " << opt.substr(index+1) <<
" not understood. Defaulting to ReadWrite." << std::endl;
}
}
}
ReadResult readResult = ReadResult::FILE_NOT_HANDLED;
/* * we accept all extensions
std::string ext = osgDB::getFileExtension(inFileName);
if (!acceptsExtension(ext))
return ReadResult::FILE_NOT_HANDLED;
*/
std::string fileName;
int index = inFileName.find(":");
// If we haven't been given a hostname as an option
// and it hasn't been prefixed to the name, we fail
if( index != -1 )
{
hostname = inFileName.substr( 0, index);
// need to strip the inFileName of the hostname prefix
fileName = inFileName.substr( index+1 );
}
else
{
if( hostname.empty() )
return ReadResult::FILE_NOT_HANDLED;
else
fileName = inFileName;
}
// Let's also strip the possible .net extension
if( osgDB::getFileExtension( fileName ) == "net" )
{
int rindex = fileName.rfind( "." );
fileName = fileName.substr( 0, rindex );
}
if( !serverPrefix.empty() )
fileName = serverPrefix + '/' + fileName;
// Invoke the reader corresponding to the extension
osgDB::ReaderWriter *reader =
osgDB::Registry::instance()->getReaderWriterForExtension( osgDB::getFileExtension(fileName));
if( reader == 0L )
return ReadResult::FILE_NOT_HANDLED;
// Before we go to the network, lets see if it is in local cache, if cache
// was specified and Read bit is set
if( !localCacheDir.empty() && (cacheMode & Read) )
{
std::string cacheFile = localCacheDir + '/' + fileName;
if( osgDB::fileExists( cacheFile ))
{
std::ifstream in(cacheFile.c_str());
readResult = readFile(objectType, reader, in, options );
in.close();
osg::notify(osg::DEBUG_INFO) << "osgPlugin .net: " << fileName <<
" fetched from local cache." << std::endl;
return readResult;
}
}
// Fetch from the network
iosockinet sio (sockbuf::sock_stream);
try {
sio->connect( hostname.c_str(), port );
}
catch( sockerr e )
{
osg::notify(osg::WARN) << "osgPlugin .net reader: Unable to connect to host " << hostname << std::endl;
return ReadResult::FILE_NOT_FOUND;
}
sio << "GET /" << fileName << " HTTP/1.1\n" << "Host:\n\n";
sio.flush();
char linebuff[256];
do
{
sio.getline( linebuff, sizeof( linebuff ));
std::istringstream iss(linebuff);
std::string directive;
iss >> directive;
if( directive.substr(0,4) == "HTTP" )
{
iss >> directive;
// Code 200. We be ok.
if( directive == "200" )
;
// Code 400 Bad Request
else if( directive == "400" )
{
osg::notify(osg::WARN) <<
"osgPlugin .net: http server response 400 - Bad Request" << std::endl;
return ReadResult::FILE_NOT_FOUND;
}
// Code 401 Bad Request
else if( directive == "401" )
{
osg::notify(osg::WARN) <<
"osgPlugin .net: http server response 401 - Unauthorized Access" << std::endl;
return ReadResult::FILE_NOT_FOUND;
}
// Code 403 Bad Request
else if( directive == "403" )
{
osg::notify(osg::WARN) <<
"osgPlugin .net: http server response 403 - Access Forbidden" << std::endl;
return ReadResult::FILE_NOT_FOUND;
}
// Code 404 File not found
else if( directive == "404" )
{
osg::notify(osg::WARN) <<
"osgPlugin .net: http server response 404 - File Not Found" << std::endl;
return ReadResult::FILE_NOT_FOUND;
}
// Code 405 Method not allowed
else if( directive == "405" )
{
osg::notify(osg::WARN) <<
"osgPlugin .net: http server response 405 - Method Not Allowed" << std::endl;
return ReadResult::FILE_NOT_FOUND;
}
// There's more....
}
} while( linebuff[0] != '\r' );
// code for setting up the database path so that any paged
// databases can be automatically located.
osg::ref_ptr<Options> local_opt = const_cast<Options*>(options);
if (!local_opt) local_opt = new Options;
if (local_opt.valid() && local_opt->getDatabasePath().empty())
{
local_opt->setDatabasePath(osgDB::getFilePath(inFileName));
}
if( reader != 0L )
readResult = readFile(objectType, reader, sio, local_opt.get() );
double ms = osg::Timer::instance()->delta_m(start,osg::Timer::instance()->tick());
osg::notify(osg::DEBUG_INFO) << "osgPlugin .net: " << fileName <<
" fetched from server. in" << ms <<" ms"<< std::endl;
if( !localCacheDir.empty() && cacheMode & Write )
{
std::string cacheFile = localCacheDir + '/' + fileName;
if( osgDB::makeDirectoryForFile( cacheFile ) )
{
switch(objectType)
{
case(OBJECT): osgDB::writeObjectFile( *(readResult.getObject()), cacheFile );
case(IMAGE): osgDB::writeImageFile( *(readResult.getImage()), cacheFile );
case(HEIGHTFIELD): osgDB::writeHeightFieldFile( *(readResult.getHeightField()), cacheFile );
case(NODE): osgDB::writeNodeFile( *(readResult.getNode()), cacheFile );;
}
osg::notify(osg::DEBUG_INFO) << "osgPlugin .net: " << fileName <<
" stored to local cache." << std::endl;
}
}
return readResult;
}
};
osgDB::RegisterReaderWriterProxy<NetReader> g_netReader_Proxy;
<commit_msg>Added default: case for both switch() statements<commit_after>#include <iostream>
#include <fstream>
#include <sstream>
#include <osg/Notify>
#include <osgDB/Input>
#include <osgDB/Registry>
#include <osgDB/FileUtils>
#include <osgDB/FileNameUtils>
#include <osgDB/ReadFile>
#include <osgDB/WriteFile>
#include <osgDB/FileUtils>
#include <osg/MatrixTransform>
#include <osg/Group>
#include <osg/Timer>
#include "sockinet.h"
/*
* Semantics:
* Two methods for using the .net loader.
* 1) Add a hostname prefix and a '.net' suffix on a model when passing
* to osgDB::readNodeFile()
* e.g: osgDB::readNodeFile( "openscenegraph.org:cow.osg.net" );
*
* 2) Explicitely load the .net plugin and pass the plugin options including
* hostname=<hostname>
*
* Method #1 takes precedence. SO, if the hostname option is passed the
* plugin, but the name also contains a hostname prefix, the hostname
* prefix on the file name will override the option
*
* Plugin options:
* hostname=<hostname> - Specify the host where the data file is to
* be fetched from.
*
* prefix=<prefix> - Specify a server directory to prefix the
* file name with.
*
* local_cache_dir=<dir> - Specify a directory in which to cache files
* on the local machine once they've been fetched.
* This directory is also searched before fetching
* the file from the server when Read mode is
* enabled on the cache.
*
* cache_mode=<mode> - Set the mode for the local cache if local_cache
* was specified. If local_cache was not specified
* this directive is ignored. <mode> may
* be specified with ReadOnly, WriteOnly, or
* ReadWrite. Behavior for the different modes is
* defined as:
*
* ReadOnly - When retrieving files, cache is
* searched first, and if the file is
* not present, it is fetched from the
* server. If it is fetched from the
* server it is not stored in local cache
*
* WriteOnly - When retrieving files, cache is not
* searched, file is always retrieved
* from the server and always written to
* cache.
*
* ReadWrite - (the default). When retrieving files
* cache is searched first, if file is
* not present in cache, it is fetched from
* the server. If fetched, it is written
* to cache.
*
*/
class NetReader : public osgDB::ReaderWriter
{
public:
NetReader() {}
virtual const char* className() { return "HTTP Protocol Model Reader"; }
virtual bool acceptsExtension(const std::string& extension)
{
return osgDB::equalCaseInsensitive(extension,"net");
}
enum ObjectType
{
OBJECT,
IMAGE,
HEIGHTFIELD,
NODE
};
virtual ReadResult readObject(const std::string& fileName, const Options* options)
{
return readFile(OBJECT,fileName,options);
}
virtual ReadResult readImage(const std::string& fileName, const Options *options)
{
return readFile(IMAGE,fileName,options);
}
virtual ReadResult readHeightField(const std::string& fileName, const Options *options)
{
return readFile(HEIGHTFIELD,fileName,options);
}
virtual ReadResult readNode(const std::string& fileName, const Options *options)
{
return readFile(NODE,fileName,options);
}
ReadResult readFile(ObjectType objectType, ReaderWriter* rw, std::istream& fin, const Options *options)
{
switch(objectType)
{
case(OBJECT): return rw->readObject(fin,options);
case(IMAGE): return rw->readImage(fin,options);
case(HEIGHTFIELD): return rw->readHeightField(fin,options);
case(NODE): return rw->readNode(fin,options);
default: break;
}
}
virtual ReadResult readFile(ObjectType objectType, const std::string& inFileName, const Options *options)
{
osg::Timer_t start = osg::Timer::instance()->tick();
osg::notify(osg::DEBUG_INFO) << "osgPlugin .net: start load" << inFileName << std::endl;
std::string hostname;
std::string serverPrefix;
std::string localCacheDir;
int port = 80;
enum CacheMode {
Read = 1,
Write = 2,
ReadWrite = 3
};
CacheMode cacheMode = ReadWrite;
if (options)
{
std::istringstream iss(options->getOptionString());
std::string opt;
while (iss >> opt)
{
int index = opt.find( "=" );
if( opt.substr( 0, index ) == "hostname" ||
opt.substr( 0, index ) == "HOSTNAME" )
{
hostname = opt.substr( index+1 );
}
else if( opt.substr( 0, index ) == "port" ||
opt.substr( 0, index ) == "PORT" )
{
port = atoi( opt.substr(index+1).c_str() );
}
else if( opt.substr( 0, index ) == "server_prefix" ||
opt.substr( 0, index ) == "SERVER_PREFIX" ||
opt.substr( 0, index ) == "prefix" ||
opt.substr( 0, index ) == "PREFIX" )
{
serverPrefix = opt.substr(index+1);
}
else if( opt.substr( 0, index ) == "local_cache_dir" ||
opt.substr( 0, index ) == "LOCAL_CACHE_DIR" )
{
localCacheDir = opt.substr(index+1);
}
else if( opt.substr( 0, index ) == "cache_mode" ||
opt.substr( 0, index ) == "CACHE_MODE" )
{
if( opt.substr(index+1) == "ReadOnly" )
cacheMode = Read;
else if( opt.substr(index+1) == "WriteOnly" )
cacheMode = Write;
else if( opt.substr(index+1) == "ReadWrite" )
cacheMode = ReadWrite;
else
osg::notify(osg::WARN) <<
"NET plug-in warning: cache_mode " << opt.substr(index+1) <<
" not understood. Defaulting to ReadWrite." << std::endl;
}
}
}
ReadResult readResult = ReadResult::FILE_NOT_HANDLED;
/* * we accept all extensions
std::string ext = osgDB::getFileExtension(inFileName);
if (!acceptsExtension(ext))
return ReadResult::FILE_NOT_HANDLED;
*/
std::string fileName;
int index = inFileName.find(":");
// If we haven't been given a hostname as an option
// and it hasn't been prefixed to the name, we fail
if( index != -1 )
{
hostname = inFileName.substr( 0, index);
// need to strip the inFileName of the hostname prefix
fileName = inFileName.substr( index+1 );
}
else
{
if( hostname.empty() )
return ReadResult::FILE_NOT_HANDLED;
else
fileName = inFileName;
}
// Let's also strip the possible .net extension
if( osgDB::getFileExtension( fileName ) == "net" )
{
int rindex = fileName.rfind( "." );
fileName = fileName.substr( 0, rindex );
}
if( !serverPrefix.empty() )
fileName = serverPrefix + '/' + fileName;
// Invoke the reader corresponding to the extension
osgDB::ReaderWriter *reader =
osgDB::Registry::instance()->getReaderWriterForExtension( osgDB::getFileExtension(fileName));
if( reader == 0L )
return ReadResult::FILE_NOT_HANDLED;
// Before we go to the network, lets see if it is in local cache, if cache
// was specified and Read bit is set
if( !localCacheDir.empty() && (cacheMode & Read) )
{
std::string cacheFile = localCacheDir + '/' + fileName;
if( osgDB::fileExists( cacheFile ))
{
std::ifstream in(cacheFile.c_str());
readResult = readFile(objectType, reader, in, options );
in.close();
osg::notify(osg::DEBUG_INFO) << "osgPlugin .net: " << fileName <<
" fetched from local cache." << std::endl;
return readResult;
}
}
// Fetch from the network
iosockinet sio (sockbuf::sock_stream);
try {
sio->connect( hostname.c_str(), port );
}
catch( sockerr e )
{
osg::notify(osg::WARN) << "osgPlugin .net reader: Unable to connect to host " << hostname << std::endl;
return ReadResult::FILE_NOT_FOUND;
}
sio << "GET /" << fileName << " HTTP/1.1\n" << "Host:\n\n";
sio.flush();
char linebuff[256];
do
{
sio.getline( linebuff, sizeof( linebuff ));
std::istringstream iss(linebuff);
std::string directive;
iss >> directive;
if( directive.substr(0,4) == "HTTP" )
{
iss >> directive;
// Code 200. We be ok.
if( directive == "200" )
;
// Code 400 Bad Request
else if( directive == "400" )
{
osg::notify(osg::WARN) <<
"osgPlugin .net: http server response 400 - Bad Request" << std::endl;
return ReadResult::FILE_NOT_FOUND;
}
// Code 401 Bad Request
else if( directive == "401" )
{
osg::notify(osg::WARN) <<
"osgPlugin .net: http server response 401 - Unauthorized Access" << std::endl;
return ReadResult::FILE_NOT_FOUND;
}
// Code 403 Bad Request
else if( directive == "403" )
{
osg::notify(osg::WARN) <<
"osgPlugin .net: http server response 403 - Access Forbidden" << std::endl;
return ReadResult::FILE_NOT_FOUND;
}
// Code 404 File not found
else if( directive == "404" )
{
osg::notify(osg::WARN) <<
"osgPlugin .net: http server response 404 - File Not Found" << std::endl;
return ReadResult::FILE_NOT_FOUND;
}
// Code 405 Method not allowed
else if( directive == "405" )
{
osg::notify(osg::WARN) <<
"osgPlugin .net: http server response 405 - Method Not Allowed" << std::endl;
return ReadResult::FILE_NOT_FOUND;
}
// There's more....
}
} while( linebuff[0] != '\r' );
// code for setting up the database path so that any paged
// databases can be automatically located.
osg::ref_ptr<Options> local_opt = const_cast<Options*>(options);
if (!local_opt) local_opt = new Options;
if (local_opt.valid() && local_opt->getDatabasePath().empty())
{
local_opt->setDatabasePath(osgDB::getFilePath(inFileName));
}
if( reader != 0L )
readResult = readFile(objectType, reader, sio, local_opt.get() );
double ms = osg::Timer::instance()->delta_m(start,osg::Timer::instance()->tick());
osg::notify(osg::DEBUG_INFO) << "osgPlugin .net: " << fileName <<
" fetched from server. in" << ms <<" ms"<< std::endl;
if( !localCacheDir.empty() && cacheMode & Write )
{
std::string cacheFile = localCacheDir + '/' + fileName;
if( osgDB::makeDirectoryForFile( cacheFile ) )
{
switch(objectType)
{
case(OBJECT): osgDB::writeObjectFile( *(readResult.getObject()), cacheFile );
case(IMAGE): osgDB::writeImageFile( *(readResult.getImage()), cacheFile );
case(HEIGHTFIELD): osgDB::writeHeightFieldFile( *(readResult.getHeightField()), cacheFile );
case(NODE): osgDB::writeNodeFile( *(readResult.getNode()), cacheFile );;
default: break;
}
osg::notify(osg::DEBUG_INFO) << "osgPlugin .net: " << fileName <<
" stored to local cache." << std::endl;
}
}
return readResult;
}
};
osgDB::RegisterReaderWriterProxy<NetReader> g_netReader_Proxy;
<|endoftext|> |
<commit_before>#include <sstream>
#include <osg/Image>
#include <osg/Group>
#include <osg/Notify>
#include <osgDB/FileNameUtils>
#include <osgDB/FileUtils>
#include <osgDB/fstream>
#include <osgDB/Registry>
#include <osgDB/Input>
#include <osgDB/Output>
using namespace osg;
using namespace osgDB;
// pull in symbols from individual .o's to enable the static build to work
USE_DOTOSGWRAPPER(AlphaFunc)
USE_DOTOSGWRAPPER(AnimationPath)
USE_DOTOSGWRAPPER(AutoTransform)
USE_DOTOSGWRAPPER(Billboard)
USE_DOTOSGWRAPPER(BlendColor)
USE_DOTOSGWRAPPER(BlendEquation)
USE_DOTOSGWRAPPER(BlendFunc)
USE_DOTOSGWRAPPER(Camera)
USE_DOTOSGWRAPPER(CameraView)
USE_DOTOSGWRAPPER(ClearNode)
USE_DOTOSGWRAPPER(ClipNode)
USE_DOTOSGWRAPPER(ClipPlane)
USE_DOTOSGWRAPPER(ClusterCullingCallback)
USE_DOTOSGWRAPPER(ColorMask)
USE_DOTOSGWRAPPER(ColorMatrix)
USE_DOTOSGWRAPPER(ConvexPlanarOccluder)
USE_DOTOSGWRAPPER(CoordinateSystemNode)
USE_DOTOSGWRAPPER(CullFace)
USE_DOTOSGWRAPPER(Depth)
USE_DOTOSGWRAPPER(Drawable)
USE_DOTOSGWRAPPER(EllipsoidModel)
USE_DOTOSGWRAPPER(Fog)
USE_DOTOSGWRAPPER(FragmentProgram)
USE_DOTOSGWRAPPER(FrontFace)
USE_DOTOSGWRAPPER(Geode)
USE_DOTOSGWRAPPER(Geometry)
USE_DOTOSGWRAPPER(Group)
USE_DOTOSGWRAPPER(Image)
USE_DOTOSGWRAPPER(ImageSequence)
USE_DOTOSGWRAPPER(Light)
USE_DOTOSGWRAPPER(LightModel)
USE_DOTOSGWRAPPER(LightSource)
USE_DOTOSGWRAPPER(LineStipple)
USE_DOTOSGWRAPPER(LineWidth)
USE_DOTOSGWRAPPER(LOD)
USE_DOTOSGWRAPPER(Material)
USE_DOTOSGWRAPPER(MatrixTransform)
USE_DOTOSGWRAPPER(NodeCallback)
USE_DOTOSGWRAPPER(Node)
USE_DOTOSGWRAPPER(Object)
USE_DOTOSGWRAPPER(OccluderNode)
USE_DOTOSGWRAPPER(OcclusionQueryNode)
USE_DOTOSGWRAPPER(PagedLOD)
USE_DOTOSGWRAPPER(Point)
USE_DOTOSGWRAPPER(PointSprite)
USE_DOTOSGWRAPPER(PolygonMode)
USE_DOTOSGWRAPPER(PolygonOffset)
USE_DOTOSGWRAPPER(PositionAttitudeTransform)
USE_DOTOSGWRAPPER(Program)
USE_DOTOSGWRAPPER(Projection)
USE_DOTOSGWRAPPER(ProxyNode)
USE_DOTOSGWRAPPER(Scissor)
USE_DOTOSGWRAPPER(Sequence)
USE_DOTOSGWRAPPER(ShadeModel)
USE_DOTOSGWRAPPER(Shader)
USE_DOTOSGWRAPPER(Sphere)
USE_DOTOSGWRAPPER(Cone)
USE_DOTOSGWRAPPER(Capsule)
USE_DOTOSGWRAPPER(Box)
USE_DOTOSGWRAPPER(HeightField)
USE_DOTOSGWRAPPER(CompositeShape)
USE_DOTOSGWRAPPER(Cylinder)
USE_DOTOSGWRAPPER(ShapeDrawable)
USE_DOTOSGWRAPPER(StateAttribute)
USE_DOTOSGWRAPPER(StateSet)
USE_DOTOSGWRAPPER(Stencil)
USE_DOTOSGWRAPPER(Switch)
USE_DOTOSGWRAPPER(TessellationHints)
USE_DOTOSGWRAPPER(TexEnvCombine)
USE_DOTOSGWRAPPER(TexEnv)
USE_DOTOSGWRAPPER(TexEnvFilter)
USE_DOTOSGWRAPPER(TexGen)
USE_DOTOSGWRAPPER(TexGenNode)
USE_DOTOSGWRAPPER(TexMat)
USE_DOTOSGWRAPPER(Texture1D)
USE_DOTOSGWRAPPER(Texture2D)
USE_DOTOSGWRAPPER(Texture3D)
USE_DOTOSGWRAPPER(Texture)
USE_DOTOSGWRAPPER(TextureCubeMap)
USE_DOTOSGWRAPPER(TextureRectangle)
USE_DOTOSGWRAPPER(Transform)
USE_DOTOSGWRAPPER(Uniform)
USE_DOTOSGWRAPPER(VertexProgram)
USE_DOTOSGWRAPPER(Viewport)
class OSGReaderWriter : public ReaderWriter
{
public:
OSGReaderWriter()
{
supportsExtension("osg","OpenSceneGraph Ascii file format");
supportsExtension("osgs","Psuedo OpenSceneGraph file loaded, with file encoded in filename string");
supportsOption("precision","Set the floating point precision when writing out files");
supportsOption("OutputTextureFiles","Write out the texture images to file");
}
virtual const char* className() const { return "OSG Reader/Writer"; }
virtual ReadResult readObject(const std::string& file, const Options* opt) const
{
std::string ext = osgDB::getLowerCaseFileExtension(file);
if (equalCaseInsensitive(ext,"osgs"))
{
std::istringstream fin(osgDB::getNameLessExtension(file));
if (fin) return readNode(fin,opt);
return ReadResult::ERROR_IN_READING_FILE;
}
if (!acceptsExtension(ext)) return ReadResult::FILE_NOT_HANDLED;
std::string fileName = osgDB::findDataFile( file, opt );
if (fileName.empty()) return ReadResult::FILE_NOT_FOUND;
// code for setting up the database path so that internally referenced file are searched for on relative paths.
osg::ref_ptr<Options> local_opt = opt ? static_cast<Options*>(opt->clone(osg::CopyOp::SHALLOW_COPY)) : new Options;
local_opt->getDatabasePathList().push_front(osgDB::getFilePath(fileName));
osgDB::ifstream fin(fileName.c_str());
if (fin)
{
return readObject(fin, local_opt.get());
}
return 0L;
}
virtual ReadResult readObject(std::istream& fin, const Options* options) const
{
fin.imbue(std::locale::classic());
Input fr;
fr.attach(&fin);
fr.setOptions(options);
typedef std::vector<osg::Object*> ObjectList;
ObjectList objectList;
// load all nodes in file, placing them in a group.
while(!fr.eof())
{
Object *object = fr.readObject();
if (object) objectList.push_back(object);
else fr.advanceOverCurrentFieldOrBlock();
}
if (objectList.empty())
{
return ReadResult("No data loaded");
}
else if (objectList.size()==1)
{
return objectList.front();
}
else
{
return objectList.front();
}
}
virtual ReadResult readNode(const std::string& file, const Options* opt) const
{
std::string ext = osgDB::getLowerCaseFileExtension(file);
if (equalCaseInsensitive(ext,"osgs"))
{
std::istringstream fin(osgDB::getNameLessExtension(file));
if (fin) return readNode(fin,opt);
return ReadResult::ERROR_IN_READING_FILE;
}
if (!acceptsExtension(ext)) return ReadResult::FILE_NOT_HANDLED;
std::string fileName = osgDB::findDataFile( file, opt );
if (fileName.empty()) return ReadResult::FILE_NOT_FOUND;
// code for setting up the database path so that internally referenced file are searched for on relative paths.
osg::ref_ptr<Options> local_opt = opt ? static_cast<Options*>(opt->clone(osg::CopyOp::SHALLOW_COPY)) : new Options;
local_opt->getDatabasePathList().push_front(osgDB::getFilePath(fileName));
osgDB::ifstream fin(fileName.c_str());
if (fin)
{
return readNode(fin, local_opt.get());
}
return 0L;
}
virtual ReadResult readNode(std::istream& fin, const Options* options) const
{
fin.imbue(std::locale::classic());
Input fr;
fr.attach(&fin);
fr.setOptions(options);
typedef std::vector<osg::Node*> NodeList;
NodeList nodeList;
// load all nodes in file, placing them in a group.
while(!fr.eof())
{
Node *node = fr.readNode();
if (node) nodeList.push_back(node);
else fr.advanceOverCurrentFieldOrBlock();
}
if (nodeList.empty())
{
return ReadResult("No data loaded");
}
else if (nodeList.size()==1)
{
return nodeList.front();
}
else
{
Group* group = new Group;
group->setName("import group");
for(NodeList::iterator itr=nodeList.begin();
itr!=nodeList.end();
++itr)
{
group->addChild(*itr);
}
return group;
}
}
void setPrecision(Output& fout, const osgDB::ReaderWriter::Options* options) const
{
if (options)
{
std::istringstream iss(options->getOptionString());
std::string opt;
while (iss >> opt)
{
if(opt=="PRECISION" || opt=="precision")
{
int prec;
iss >> prec;
fout.precision(prec);
}
if (opt=="OutputTextureFiles")
{
fout.setOutputTextureFiles(true);
}
}
}
}
virtual WriteResult writeObject(const Object& obj, const std::string& fileName, const osgDB::ReaderWriter::Options* options) const
{
std::string ext = osgDB::getLowerCaseFileExtension(fileName);
if (!acceptsExtension(ext)) return WriteResult::FILE_NOT_HANDLED;
Output fout(fileName.c_str());
if (fout)
{
fout.setOptions(options);
setPrecision(fout,options);
fout.imbue(std::locale::classic());
fout.writeObject(obj);
fout.close();
return WriteResult::FILE_SAVED;
}
return WriteResult("Unable to open file for output");
}
virtual WriteResult writeObject(const Object& obj,std::ostream& fout, const osgDB::ReaderWriter::Options* options) const
{
if (fout)
{
Output foutput;
foutput.setOptions(options);
std::ios &fios = foutput;
fios.rdbuf(fout.rdbuf());
fout.imbue(std::locale::classic());
setPrecision(foutput,options);
foutput.writeObject(obj);
return WriteResult::FILE_SAVED;
}
return WriteResult("Unable to write to output stream");
}
virtual WriteResult writeNode(const Node& node, const std::string& fileName, const osgDB::ReaderWriter::Options* options) const
{
std::string ext = getFileExtension(fileName);
if (!acceptsExtension(ext)) return WriteResult::FILE_NOT_HANDLED;
Output fout(fileName.c_str());
if (fout)
{
fout.setOptions(options);
fout.imbue(std::locale::classic());
setPrecision(fout,options);
fout.writeObject(node);
fout.close();
return WriteResult::FILE_SAVED;
}
return WriteResult("Unable to open file for output");
}
virtual WriteResult writeNode(const Node& node, std::ostream& fout, const osgDB::ReaderWriter::Options* options) const
{
if (fout)
{
Output foutput;
foutput.setOptions(options);
std::ios &fios = foutput;
fios.rdbuf(fout.rdbuf());
foutput.imbue(std::locale::classic());
setPrecision(foutput,options);
foutput.writeObject(node);
return WriteResult::FILE_SAVED;
}
return WriteResult("Unable to write to output stream");
}
};
// now register with Registry to instantiate the above
// reader/writer.
REGISTER_OSGPLUGIN(osg, OSGReaderWriter)
<commit_msg>From Bryan Thrall, "The .osg plugin doesn't seem to support an option to write shader files separately, so it always inlines them in the .osg file (as far as I can tell). This change adds that ability. "<commit_after>#include <sstream>
#include <osg/Image>
#include <osg/Group>
#include <osg/Notify>
#include <osgDB/FileNameUtils>
#include <osgDB/FileUtils>
#include <osgDB/fstream>
#include <osgDB/Registry>
#include <osgDB/Input>
#include <osgDB/Output>
using namespace osg;
using namespace osgDB;
// pull in symbols from individual .o's to enable the static build to work
USE_DOTOSGWRAPPER(AlphaFunc)
USE_DOTOSGWRAPPER(AnimationPath)
USE_DOTOSGWRAPPER(AutoTransform)
USE_DOTOSGWRAPPER(Billboard)
USE_DOTOSGWRAPPER(BlendColor)
USE_DOTOSGWRAPPER(BlendEquation)
USE_DOTOSGWRAPPER(BlendFunc)
USE_DOTOSGWRAPPER(Camera)
USE_DOTOSGWRAPPER(CameraView)
USE_DOTOSGWRAPPER(ClearNode)
USE_DOTOSGWRAPPER(ClipNode)
USE_DOTOSGWRAPPER(ClipPlane)
USE_DOTOSGWRAPPER(ClusterCullingCallback)
USE_DOTOSGWRAPPER(ColorMask)
USE_DOTOSGWRAPPER(ColorMatrix)
USE_DOTOSGWRAPPER(ConvexPlanarOccluder)
USE_DOTOSGWRAPPER(CoordinateSystemNode)
USE_DOTOSGWRAPPER(CullFace)
USE_DOTOSGWRAPPER(Depth)
USE_DOTOSGWRAPPER(Drawable)
USE_DOTOSGWRAPPER(EllipsoidModel)
USE_DOTOSGWRAPPER(Fog)
USE_DOTOSGWRAPPER(FragmentProgram)
USE_DOTOSGWRAPPER(FrontFace)
USE_DOTOSGWRAPPER(Geode)
USE_DOTOSGWRAPPER(Geometry)
USE_DOTOSGWRAPPER(Group)
USE_DOTOSGWRAPPER(Image)
USE_DOTOSGWRAPPER(ImageSequence)
USE_DOTOSGWRAPPER(Light)
USE_DOTOSGWRAPPER(LightModel)
USE_DOTOSGWRAPPER(LightSource)
USE_DOTOSGWRAPPER(LineStipple)
USE_DOTOSGWRAPPER(LineWidth)
USE_DOTOSGWRAPPER(LOD)
USE_DOTOSGWRAPPER(Material)
USE_DOTOSGWRAPPER(MatrixTransform)
USE_DOTOSGWRAPPER(NodeCallback)
USE_DOTOSGWRAPPER(Node)
USE_DOTOSGWRAPPER(Object)
USE_DOTOSGWRAPPER(OccluderNode)
USE_DOTOSGWRAPPER(OcclusionQueryNode)
USE_DOTOSGWRAPPER(PagedLOD)
USE_DOTOSGWRAPPER(Point)
USE_DOTOSGWRAPPER(PointSprite)
USE_DOTOSGWRAPPER(PolygonMode)
USE_DOTOSGWRAPPER(PolygonOffset)
USE_DOTOSGWRAPPER(PositionAttitudeTransform)
USE_DOTOSGWRAPPER(Program)
USE_DOTOSGWRAPPER(Projection)
USE_DOTOSGWRAPPER(ProxyNode)
USE_DOTOSGWRAPPER(Scissor)
USE_DOTOSGWRAPPER(Sequence)
USE_DOTOSGWRAPPER(ShadeModel)
USE_DOTOSGWRAPPER(Shader)
USE_DOTOSGWRAPPER(Sphere)
USE_DOTOSGWRAPPER(Cone)
USE_DOTOSGWRAPPER(Capsule)
USE_DOTOSGWRAPPER(Box)
USE_DOTOSGWRAPPER(HeightField)
USE_DOTOSGWRAPPER(CompositeShape)
USE_DOTOSGWRAPPER(Cylinder)
USE_DOTOSGWRAPPER(ShapeDrawable)
USE_DOTOSGWRAPPER(StateAttribute)
USE_DOTOSGWRAPPER(StateSet)
USE_DOTOSGWRAPPER(Stencil)
USE_DOTOSGWRAPPER(Switch)
USE_DOTOSGWRAPPER(TessellationHints)
USE_DOTOSGWRAPPER(TexEnvCombine)
USE_DOTOSGWRAPPER(TexEnv)
USE_DOTOSGWRAPPER(TexEnvFilter)
USE_DOTOSGWRAPPER(TexGen)
USE_DOTOSGWRAPPER(TexGenNode)
USE_DOTOSGWRAPPER(TexMat)
USE_DOTOSGWRAPPER(Texture1D)
USE_DOTOSGWRAPPER(Texture2D)
USE_DOTOSGWRAPPER(Texture3D)
USE_DOTOSGWRAPPER(Texture)
USE_DOTOSGWRAPPER(TextureCubeMap)
USE_DOTOSGWRAPPER(TextureRectangle)
USE_DOTOSGWRAPPER(Transform)
USE_DOTOSGWRAPPER(Uniform)
USE_DOTOSGWRAPPER(VertexProgram)
USE_DOTOSGWRAPPER(Viewport)
class OSGReaderWriter : public ReaderWriter
{
public:
OSGReaderWriter()
{
supportsExtension("osg","OpenSceneGraph Ascii file format");
supportsExtension("osgs","Psuedo OpenSceneGraph file loaded, with file encoded in filename string");
supportsOption("precision","Set the floating point precision when writing out files");
supportsOption("OutputTextureFiles","Write out the texture images to file");
}
virtual const char* className() const { return "OSG Reader/Writer"; }
virtual ReadResult readObject(const std::string& file, const Options* opt) const
{
std::string ext = osgDB::getLowerCaseFileExtension(file);
if (equalCaseInsensitive(ext,"osgs"))
{
std::istringstream fin(osgDB::getNameLessExtension(file));
if (fin) return readNode(fin,opt);
return ReadResult::ERROR_IN_READING_FILE;
}
if (!acceptsExtension(ext)) return ReadResult::FILE_NOT_HANDLED;
std::string fileName = osgDB::findDataFile( file, opt );
if (fileName.empty()) return ReadResult::FILE_NOT_FOUND;
// code for setting up the database path so that internally referenced file are searched for on relative paths.
osg::ref_ptr<Options> local_opt = opt ? static_cast<Options*>(opt->clone(osg::CopyOp::SHALLOW_COPY)) : new Options;
local_opt->getDatabasePathList().push_front(osgDB::getFilePath(fileName));
osgDB::ifstream fin(fileName.c_str());
if (fin)
{
return readObject(fin, local_opt.get());
}
return 0L;
}
virtual ReadResult readObject(std::istream& fin, const Options* options) const
{
fin.imbue(std::locale::classic());
Input fr;
fr.attach(&fin);
fr.setOptions(options);
typedef std::vector<osg::Object*> ObjectList;
ObjectList objectList;
// load all nodes in file, placing them in a group.
while(!fr.eof())
{
Object *object = fr.readObject();
if (object) objectList.push_back(object);
else fr.advanceOverCurrentFieldOrBlock();
}
if (objectList.empty())
{
return ReadResult("No data loaded");
}
else if (objectList.size()==1)
{
return objectList.front();
}
else
{
return objectList.front();
}
}
virtual ReadResult readNode(const std::string& file, const Options* opt) const
{
std::string ext = osgDB::getLowerCaseFileExtension(file);
if (equalCaseInsensitive(ext,"osgs"))
{
std::istringstream fin(osgDB::getNameLessExtension(file));
if (fin) return readNode(fin,opt);
return ReadResult::ERROR_IN_READING_FILE;
}
if (!acceptsExtension(ext)) return ReadResult::FILE_NOT_HANDLED;
std::string fileName = osgDB::findDataFile( file, opt );
if (fileName.empty()) return ReadResult::FILE_NOT_FOUND;
// code for setting up the database path so that internally referenced file are searched for on relative paths.
osg::ref_ptr<Options> local_opt = opt ? static_cast<Options*>(opt->clone(osg::CopyOp::SHALLOW_COPY)) : new Options;
local_opt->getDatabasePathList().push_front(osgDB::getFilePath(fileName));
osgDB::ifstream fin(fileName.c_str());
if (fin)
{
return readNode(fin, local_opt.get());
}
return 0L;
}
virtual ReadResult readNode(std::istream& fin, const Options* options) const
{
fin.imbue(std::locale::classic());
Input fr;
fr.attach(&fin);
fr.setOptions(options);
typedef std::vector<osg::Node*> NodeList;
NodeList nodeList;
// load all nodes in file, placing them in a group.
while(!fr.eof())
{
Node *node = fr.readNode();
if (node) nodeList.push_back(node);
else fr.advanceOverCurrentFieldOrBlock();
}
if (nodeList.empty())
{
return ReadResult("No data loaded");
}
else if (nodeList.size()==1)
{
return nodeList.front();
}
else
{
Group* group = new Group;
group->setName("import group");
for(NodeList::iterator itr=nodeList.begin();
itr!=nodeList.end();
++itr)
{
group->addChild(*itr);
}
return group;
}
}
void setPrecision(Output& fout, const osgDB::ReaderWriter::Options* options) const
{
if (options)
{
std::istringstream iss(options->getOptionString());
std::string opt;
while (iss >> opt)
{
if(opt=="PRECISION" || opt=="precision")
{
int prec;
iss >> prec;
fout.precision(prec);
}
if (opt=="OutputTextureFiles")
{
fout.setOutputTextureFiles(true);
}
if (opt=="OutputShaderFiles")
{
fout.setOutputShaderFiles(true);
}
}
}
}
virtual WriteResult writeObject(const Object& obj, const std::string& fileName, const osgDB::ReaderWriter::Options* options) const
{
std::string ext = osgDB::getLowerCaseFileExtension(fileName);
if (!acceptsExtension(ext)) return WriteResult::FILE_NOT_HANDLED;
Output fout(fileName.c_str());
if (fout)
{
fout.setOptions(options);
setPrecision(fout,options);
fout.imbue(std::locale::classic());
fout.writeObject(obj);
fout.close();
return WriteResult::FILE_SAVED;
}
return WriteResult("Unable to open file for output");
}
virtual WriteResult writeObject(const Object& obj,std::ostream& fout, const osgDB::ReaderWriter::Options* options) const
{
if (fout)
{
Output foutput;
foutput.setOptions(options);
std::ios &fios = foutput;
fios.rdbuf(fout.rdbuf());
fout.imbue(std::locale::classic());
setPrecision(foutput,options);
foutput.writeObject(obj);
return WriteResult::FILE_SAVED;
}
return WriteResult("Unable to write to output stream");
}
virtual WriteResult writeNode(const Node& node, const std::string& fileName, const osgDB::ReaderWriter::Options* options) const
{
std::string ext = getFileExtension(fileName);
if (!acceptsExtension(ext)) return WriteResult::FILE_NOT_HANDLED;
Output fout(fileName.c_str());
if (fout)
{
fout.setOptions(options);
fout.imbue(std::locale::classic());
setPrecision(fout,options);
fout.writeObject(node);
fout.close();
return WriteResult::FILE_SAVED;
}
return WriteResult("Unable to open file for output");
}
virtual WriteResult writeNode(const Node& node, std::ostream& fout, const osgDB::ReaderWriter::Options* options) const
{
if (fout)
{
Output foutput;
foutput.setOptions(options);
std::ios &fios = foutput;
fios.rdbuf(fout.rdbuf());
foutput.imbue(std::locale::classic());
setPrecision(foutput,options);
foutput.writeObject(node);
return WriteResult::FILE_SAVED;
}
return WriteResult("Unable to write to output stream");
}
};
// now register with Registry to instantiate the above
// reader/writer.
REGISTER_OSGPLUGIN(osg, OSGReaderWriter)
<|endoftext|> |
<commit_before>//-----------------------------------------------------------------------------
//
// This source file is part of the YETI open source package under the
// BSD (2-clause) licence (see LICENCE file for details).
//
// (c) H Hathrell, R F L Evans 2014. All rights reserved.
//
//-----------------------------------------------------------------------------
// System headers
#include <iostream>
// Program headers
#include "material.hpp"
#include "object.hpp"
#include "yeti.hpp"
namespace yeti{
//-----------------------------------------------------------------------------
// Function to determine material properties as a function of position
//-----------------------------------------------------------------------------
material_t get_material_properties(double x,double y,double z){ //determine pAZ from inshape
// declare temporary object to store result
material_t result;
// define negative starting order
int maxorder = -1;
// loop over all objects in list
for (unsigned int i=0; i<objects::object_list.size(); i++){
// Test if point x,y,z is within object
bool test_inside = objects::object_list[i]->inshape(x,y,z);
// Test if object has greater hierarchy
bool test_hierarchy = objects::object_list[i]->order>maxorder;
// check for both conditions true
if (test_inside && test_hierarchy ){
// update result with copy of object
result.p = objects::object_list[i]->p;
// update max order
maxorder=objects::object_list[i]->order;
}
}
// return final parameters
return result;
}
}
<commit_msg>Bugfix: Corrected missing pointers to Z and A values in material properties function<commit_after>//-----------------------------------------------------------------------------
//
// This source file is part of the YETI open source package under the
// BSD (2-clause) licence (see LICENCE file for details).
//
// (c) H Hathrell, R F L Evans 2014. All rights reserved.
//
//-----------------------------------------------------------------------------
// System headers
#include <iostream>
// Program headers
#include "material.hpp"
#include "object.hpp"
#include "yeti.hpp"
namespace yeti{
//-----------------------------------------------------------------------------
// Function to determine material properties as a function of position
//-----------------------------------------------------------------------------
material_t get_material_properties(double x,double y,double z){ //determine pAZ from inshape
// declare temporary object to store result
material_t result;
// define negative starting order
int maxorder = -1;
// loop over all objects in list
for (unsigned int i=0; i<objects::object_list.size(); i++){
// Test if point x,y,z is within object
bool test_inside = objects::object_list[i]->inshape(x,y,z);
// Test if object has greater hierarchy
bool test_hierarchy = objects::object_list[i]->order>maxorder;
// check for both conditions true
if (test_inside && test_hierarchy ){
// update result with copy of object
result.p = objects::object_list[i]->p;
result.Z = objects::object_list[i]->Z;
result.A = objects::object_list[i]->A;
// update max order
maxorder=objects::object_list[i]->order;
}
}
// return final parameters
return result;
}
}
<|endoftext|> |
<commit_before>#include <node_version.h>
#if NODE_VERSION_AT_LEAST(0, 11, 1) && !defined(_MSC_VER)
#include <sys/types.h>
#endif
#include <errno.h>
#include <napi.h>
#if defined(_MSC_VER)
#include <time.h>
#include <windows.h>
// Pick GetSystemTimePreciseAsFileTime or GetSystemTimeAsFileTime depending
// on which is available at runtime.
typedef VOID(WINAPI *WinGetSystemTime)(LPFILETIME);
static WinGetSystemTime getSystemTime = NULL;
struct timezone {
int tz_minuteswest;
int tz_dsttime;
};
int gettimeofday(struct timeval *tv, struct timezone *tz) {
FILETIME ft;
(*getSystemTime)(&ft);
unsigned long long t = ft.dwHighDateTime;
t <<= 32;
t |= ft.dwLowDateTime;
t /= 10;
t -= 11644473600000000ULL;
tv->tv_sec = (long)(t / 1000000UL);
tv->tv_usec = (long)(t % 1000000UL);
return 0;
}
#else
#include <sys/time.h>
#endif
Napi::Value Now(const Napi::CallbackInfo &info) {
timeval t;
int r = gettimeofday(&t, NULL);
if (r < 0) {
Napi::Error e = Napi::Error::New(info.Env(), "gettimeofday");
e.Set("code", Napi::Number::New(info.Env(), errno));
throw e;
}
return Napi::Number::New(info.Env(), ((t.tv_sec * 1000000.0) + t.tv_usec));
}
Napi::Value NowDouble(const Napi::CallbackInfo &info) {
timeval t;
int r = gettimeofday(&t, NULL);
if (r < 0) {
Napi::Error e = Napi::Error::New(info.Env(), "gettimeofday");
e.Set("code", Napi::Number::New(info.Env(), errno));
throw e;
}
return Napi::Number::New(info.Env(), t.tv_sec + (t.tv_usec * 0.000001));
}
Napi::Value NowStruct(const Napi::CallbackInfo &info) {
timeval t;
int r = gettimeofday(&t, NULL);
if (r < 0) {
Napi::Error e = Napi::Error::New(info.Env(), "gettimeofday");
e.Set("code", Napi::Number::New(info.Env(), errno));
throw e;
}
Napi::Array array = Napi::Array::New(info.Env(), 2);
array.Set((uint32_t)0, (double)t.tv_sec);
array.Set((uint32_t)1, (double)t.tv_usec);
return array;
}
Napi::Object Init(Napi::Env env, Napi::Object exports) {
exports.Set(Napi::String::New(env, "now"), Napi::Function::New(env, Now));
exports.Set(Napi::String::New(env, "nowDouble"),
Napi::Function::New(env, NowDouble));
exports.Set(Napi::String::New(env, "nowStruct"),
Napi::Function::New(env, NowStruct));
#if defined(_MSC_VER)
getSystemTime = (WinGetSystemTime)GetProcAddress(
GetModuleHandle(TEXT("kernel32.dll")), "GetSystemTimePreciseAsFileTime");
if (getSystemTime == NULL) {
getSystemTime = &GetSystemTimeAsFileTime;
}
#endif
return exports;
}
NODE_API_MODULE(NODE_GYP_MODULE_NAME, Init);
<commit_msg>Add more robust ErrnoException<commit_after>#include <node_version.h>
#if NODE_VERSION_AT_LEAST(0, 11, 1) && !defined(_MSC_VER)
#include <sys/types.h>
#endif
#include <errno.h>
#include <napi.h>
#if defined(_MSC_VER)
#include <time.h>
#include <windows.h>
// Pick GetSystemTimePreciseAsFileTime or GetSystemTimeAsFileTime depending
// on which is available at runtime.
typedef VOID(WINAPI *WinGetSystemTime)(LPFILETIME);
static WinGetSystemTime getSystemTime = NULL;
struct timezone {
int tz_minuteswest;
int tz_dsttime;
};
int gettimeofday(struct timeval *tv, struct timezone *tz) {
FILETIME ft;
(*getSystemTime)(&ft);
unsigned long long t = ft.dwHighDateTime;
t <<= 32;
t |= ft.dwLowDateTime;
t /= 10;
t -= 11644473600000000ULL;
tv->tv_sec = (long)(t / 1000000UL);
tv->tv_usec = (long)(t % 1000000UL);
return 0;
}
#else
#include <sys/time.h>
#endif
// A very basic version of Node::ErrnoException since Napi doesn't expose it
Napi::Error ErrnoException(Napi::Env env, int errorno) {
Napi::Error e = Napi::Error::New(env, strerror(errorno));
e.Set("syscall", Napi::String::New(env, "gettimeofday"));
e.Set("errno", Napi::Number::New(env, errno));
// NOTE: in Node::ErrnoException this would be the string of the code
// like "EFAULT", just simplify with the number here.
e.Set("code", Napi::Number::New(env, errno));
return e;
}
Napi::Value Now(const Napi::CallbackInfo &info) {
timeval t;
int r = gettimeofday(&t, NULL);
if (r < 0) {
throw ErrnoException(info.Env(), errno);
}
return Napi::Number::New(info.Env(), ((t.tv_sec * 1000000.0) + t.tv_usec));
}
Napi::Value NowDouble(const Napi::CallbackInfo &info) {
timeval t;
int r = gettimeofday(&t, NULL);
if (r < 0) {
throw ErrnoException(info.Env(), errno);
}
return Napi::Number::New(info.Env(), t.tv_sec + (t.tv_usec * 0.000001));
}
Napi::Value NowStruct(const Napi::CallbackInfo &info) {
timeval t;
int r = gettimeofday(&t, NULL);
if (r < 0) {
throw ErrnoException(info.Env(), errno);
}
Napi::Array array = Napi::Array::New(info.Env(), 2);
array.Set((uint32_t)0, (double)t.tv_sec);
array.Set((uint32_t)1, (double)t.tv_usec);
return array;
}
Napi::Object Init(Napi::Env env, Napi::Object exports) {
exports.Set(Napi::String::New(env, "now"), Napi::Function::New(env, Now));
exports.Set(Napi::String::New(env, "nowDouble"),
Napi::Function::New(env, NowDouble));
exports.Set(Napi::String::New(env, "nowStruct"),
Napi::Function::New(env, NowStruct));
#if defined(_MSC_VER)
getSystemTime = (WinGetSystemTime)GetProcAddress(
GetModuleHandle(TEXT("kernel32.dll")), "GetSystemTimePreciseAsFileTime");
if (getSystemTime == NULL) {
getSystemTime = &GetSystemTimeAsFileTime;
}
#endif
return exports;
}
NODE_API_MODULE(NODE_GYP_MODULE_NAME, Init);
<|endoftext|> |
<commit_before>// Copyright 2016 Las Venturas Playground. All rights reserved.
// Use of this source code is governed by the MIT license, a copy of which can
// be found in the LICENSE file.
#include "playground/plugin/native_parser.h"
#include <algorithm>
#include <fstream>
#include <set>
#include <streambuf>
#include <string.h>
#include "base/file_path.h"
#include "base/logging.h"
#include "base/string_piece.h"
#include "bindings/provided_natives.h"
#include "plugin/native_parameters.h"
#include "plugin/sdk/amx.h"
#if defined(LINUX)
#define _strdup strdup
#endif
namespace plugin {
namespace {
// The whitespace characters as specified by CSS 2.1.
const char kWhitespaceCharacters[] = "\x09\x0A\x0C\x0D\x20";
// The global instance of the NativeParser object. Required for the native functions themselves.
NativeParser* g_native_parser = nullptr;
// Removes all whitespace from the front and back of |string|, and returns the result.
base::StringPiece Trim(const base::StringPiece& input) {
if (input.empty())
return input;
const size_t first_good_char = input.find_first_not_of(kWhitespaceCharacters);
const size_t last_good_char = input.find_last_not_of(kWhitespaceCharacters);
if (first_good_char == base::StringPiece::npos ||
last_good_char == base::StringPiece::npos)
return base::StringPiece();
return input.substr(first_good_char, last_good_char - first_good_char + 1);
}
// Returns whether |character| is valid for use in a native function name.
bool IsValidCharacter(char character) {
return (character >= 'A' && character <= 'Z') ||
(character >= 'a' && character <= 'z') || character == '_';
}
// Registers |N| native functions, creates |N| functions that will automagically forward the call
// to the ProvidedNatives bindings class when called with minimal overhead.
template <size_t N> struct NativeRegistrar {
static void Register() {
DCHECK(g_native_parser);
constexpr size_t native_index = NativeParser::kMaxNatives - N;
if (native_index < g_native_parser->size()) {
AMX_NATIVE_INFO* native = &g_native_parser->GetNativeTable()[native_index];
native->name = _strdup(g_native_parser->at(native_index).c_str());
native->func = &NativeRegistrar<N>::Invoke;
}
NativeRegistrar<N - 1>::Register();
}
static int32_t AMX_NATIVE_CALL Invoke(AMX* amx, cell* params) {
DCHECK(g_native_parser);
constexpr size_t native_index = NativeParser::kMaxNatives - N;
NativeParameters parameters(amx, params);
return bindings::ProvidedNatives::GetInstance()->Call(g_native_parser->at(native_index), parameters);
}
};
template <> struct NativeRegistrar<0> {
static void Register() {}
};
} // namespace
std::unique_ptr<NativeParser> NativeParser::FromFile(const base::FilePath& filename) {
std::ifstream file(filename.value().c_str());
if (!file.is_open() || file.fail())
return nullptr;
std::string content((std::istreambuf_iterator<char>(file)),
std::istreambuf_iterator<char>());
std::unique_ptr<NativeParser> parser(new NativeParser);
if (!parser->Parse(content))
return nullptr;
return parser;
}
NativeParser::NativeParser() {
g_native_parser = this;
memset(native_table_, 0, sizeof(native_table_));
}
NativeParser::~NativeParser() {
g_native_parser = nullptr;
}
size_t NativeParser::size() const {
return natives_.size();
}
const std::string& NativeParser::at(size_t index) const {
DCHECK(natives_.size() > index);
return natives_[index];
}
bool NativeParser::Parse(const std::string& content) {
base::StringPiece content_lines(content);
if (!content_lines.length())
return true; // empty contents
size_t start = 0;
while (start != base::StringPiece::npos) {
size_t end = content_lines.find_first_of("\n", start);
base::StringPiece line;
if (end == base::StringPiece::npos) {
line = content_lines.substr(start);
start = end;
}
else {
line = content_lines.substr(start, end - start);
start = end + 1;
}
line = Trim(line);
if (line.empty())
continue; // do not process empty lines.
if (line.starts_with("#") || line.starts_with("//"))
continue; // comment line.
if (!ParseLine(line))
return false;
}
if (natives_.size() > kMaxNatives) {
LOG(ERROR) << "No more than " << kMaxNatives << " may be defined in natives.txt.";
return false;
}
bindings::ProvidedNatives::GetInstance()->SetNatives(natives_);
BuildNativeTable();
return true;
}
bool NativeParser::ParseLine(base::StringPiece line) {
for (size_t i = 0; i < line.length(); ++i) {
if (!IsValidCharacter(line[i])) {
LOG(ERROR) << "Invalid native function name: " << line.as_string();
return false;
}
}
const std::string name = line.as_string();
if (std::find(natives_.begin(), natives_.end(), name) != natives_.end()) {
LOG(ERROR) << "Native has been listed multiple times: " << line.as_string();
return false;
}
natives_.push_back(name);
return true;
}
void NativeParser::BuildNativeTable() {
NativeRegistrar<kMaxNatives>::Register();
}
} // namespace plugin
<commit_msg>Allow numbers in native names too<commit_after>// Copyright 2016 Las Venturas Playground. All rights reserved.
// Use of this source code is governed by the MIT license, a copy of which can
// be found in the LICENSE file.
#include "playground/plugin/native_parser.h"
#include <algorithm>
#include <fstream>
#include <set>
#include <streambuf>
#include <string.h>
#include "base/file_path.h"
#include "base/logging.h"
#include "base/string_piece.h"
#include "bindings/provided_natives.h"
#include "plugin/native_parameters.h"
#include "plugin/sdk/amx.h"
#if defined(LINUX)
#define _strdup strdup
#endif
namespace plugin {
namespace {
// The whitespace characters as specified by CSS 2.1.
const char kWhitespaceCharacters[] = "\x09\x0A\x0C\x0D\x20";
// The global instance of the NativeParser object. Required for the native functions themselves.
NativeParser* g_native_parser = nullptr;
// Removes all whitespace from the front and back of |string|, and returns the result.
base::StringPiece Trim(const base::StringPiece& input) {
if (input.empty())
return input;
const size_t first_good_char = input.find_first_not_of(kWhitespaceCharacters);
const size_t last_good_char = input.find_last_not_of(kWhitespaceCharacters);
if (first_good_char == base::StringPiece::npos ||
last_good_char == base::StringPiece::npos)
return base::StringPiece();
return input.substr(first_good_char, last_good_char - first_good_char + 1);
}
// Returns whether |character| is valid for use in a native function name.
bool IsValidCharacter(char character) {
return (character >= 'A' && character <= 'Z') ||
(character >= 'a' && character <= 'z') ||
(character >= '0' && character <= '9') || character == '_';
}
// Registers |N| native functions, creates |N| functions that will automagically forward the call
// to the ProvidedNatives bindings class when called with minimal overhead.
template <size_t N> struct NativeRegistrar {
static void Register() {
DCHECK(g_native_parser);
constexpr size_t native_index = NativeParser::kMaxNatives - N;
if (native_index < g_native_parser->size()) {
AMX_NATIVE_INFO* native = &g_native_parser->GetNativeTable()[native_index];
native->name = _strdup(g_native_parser->at(native_index).c_str());
native->func = &NativeRegistrar<N>::Invoke;
}
NativeRegistrar<N - 1>::Register();
}
static int32_t AMX_NATIVE_CALL Invoke(AMX* amx, cell* params) {
DCHECK(g_native_parser);
constexpr size_t native_index = NativeParser::kMaxNatives - N;
NativeParameters parameters(amx, params);
return bindings::ProvidedNatives::GetInstance()->Call(g_native_parser->at(native_index), parameters);
}
};
template <> struct NativeRegistrar<0> {
static void Register() {}
};
} // namespace
std::unique_ptr<NativeParser> NativeParser::FromFile(const base::FilePath& filename) {
std::ifstream file(filename.value().c_str());
if (!file.is_open() || file.fail())
return nullptr;
std::string content((std::istreambuf_iterator<char>(file)),
std::istreambuf_iterator<char>());
std::unique_ptr<NativeParser> parser(new NativeParser);
if (!parser->Parse(content))
return nullptr;
return parser;
}
NativeParser::NativeParser() {
g_native_parser = this;
memset(native_table_, 0, sizeof(native_table_));
}
NativeParser::~NativeParser() {
g_native_parser = nullptr;
}
size_t NativeParser::size() const {
return natives_.size();
}
const std::string& NativeParser::at(size_t index) const {
DCHECK(natives_.size() > index);
return natives_[index];
}
bool NativeParser::Parse(const std::string& content) {
base::StringPiece content_lines(content);
if (!content_lines.length())
return true; // empty contents
size_t start = 0;
while (start != base::StringPiece::npos) {
size_t end = content_lines.find_first_of("\n", start);
base::StringPiece line;
if (end == base::StringPiece::npos) {
line = content_lines.substr(start);
start = end;
}
else {
line = content_lines.substr(start, end - start);
start = end + 1;
}
line = Trim(line);
if (line.empty())
continue; // do not process empty lines.
if (line.starts_with("#") || line.starts_with("//"))
continue; // comment line.
if (!ParseLine(line))
return false;
}
if (natives_.size() > kMaxNatives) {
LOG(ERROR) << "No more than " << kMaxNatives << " may be defined in natives.txt.";
return false;
}
bindings::ProvidedNatives::GetInstance()->SetNatives(natives_);
BuildNativeTable();
return true;
}
bool NativeParser::ParseLine(base::StringPiece line) {
for (size_t i = 0; i < line.length(); ++i) {
if (!IsValidCharacter(line[i])) {
LOG(ERROR) << "Invalid native function name: " << line.as_string();
return false;
}
}
const std::string name = line.as_string();
if (std::find(natives_.begin(), natives_.end(), name) != natives_.end()) {
LOG(ERROR) << "Native has been listed multiple times: " << line.as_string();
return false;
}
natives_.push_back(name);
return true;
}
void NativeParser::BuildNativeTable() {
NativeRegistrar<kMaxNatives>::Register();
}
} // namespace plugin
<|endoftext|> |
<commit_before>#include "assembly_reader.h"
#include <cstring>
#include "../common/ptr_util.h"
#include "opcodes.h"
#include "../pe/coded_index.h"
#include "../pe/pe_image_reader.h"
#include "assembly.h"
namespace stereo {
namespace assemblies {
AssemblyReader::AssemblyReader(const char* file_path)
:
logger_(std::make_unique<logging::ConsoleLogger>()),
image_(pe::PEImageReader::load_image(file_path))
{
}
u32 AssemblyReader::get_entry_point()
{
auto ept = pe::MetadataToken(image_->cli_header.entry_point_token);
return ept.rid();
}
const ModuleDef* AssemblyReader::read_module_def()
{
if (module_ != nullptr)
return module_.get();
auto module = std::make_unique<ModuleDef>();
auto table_row_ptr = get_table_row_ptr(pe::MetadataTable::Module, 1);
// Skip the generation column since it's always zero
table_row_ptr += 2;
module->name = read_string(&table_row_ptr);
// TODO: Read the mvid guid
module_ = std::move(module);
return module_.get();
}
const MethodDef* AssemblyReader::read_method_def(u32 rid)
{
if (already_read(method_defs_, rid))
return method_defs_[get_index_from_rid(rid)].get();
resize_if_needed(method_defs_, pe::MetadataTable::Method);
auto table_row_ptr = get_table_row_ptr(pe::MetadataTable::Method, rid);
auto method_def = std::make_unique<MethodDef>();
// RVA (a 4-byte constant)
method_def->rva = ptrutil::read32(&table_row_ptr);
// ImplFlags (a 2-byte bitmask of type MethodImplAttributes, II.23.1.10)
method_def->impl_attributes = static_cast<MethodImplAttributes>(ptrutil::read16(&table_row_ptr));
// Flags (a 2-byte bitmask of type MethodAttributes, II.23.1.10)
method_def->attributes = static_cast<MethodAttributes>(ptrutil::read16(&table_row_ptr));
// Name (an index into the String heap)
method_def->name = read_string(&table_row_ptr);
// TODO: Read signature, parameters etc
read_method_body(method_def.get());
method_defs_[get_index_from_rid(rid)] = std::move(method_def);
return method_defs_[get_index_from_rid(rid)].get();
}
const MemberRef* AssemblyReader::read_member_ref(u32 rid)
{
if (already_read(member_refs_, rid))
return member_refs_[get_index_from_rid(rid)].get();
resize_if_needed(member_refs_, pe::MetadataTable::MemberRef);
auto table_row_ptr = get_table_row_ptr(pe::MetadataTable::MemberRef, rid);
auto member_ref = std::make_unique<MemberRef>();
// Class (an index into the MethodDef, ModuleRef, TypeDef, TypeRef, or TypeSpec tables; more precisely, a MemberRefParent(II.24.2.6) coded index)
auto token = read_metadata_token(&table_row_ptr, pe::CodedIndexType::MemberRefParent);
// Name (an index into the String heap)
member_ref->name = read_string(&table_row_ptr);
// Signature (an index into the Blob heap)
auto signature = read_blob(&table_row_ptr);
// TODO: Implement all token type cases
if (token.type() == pe::MetadataTokenType::TypeRef)
{
member_ref->type_ref = read_type_ref(token.rid());
}
else
{
throw "read_member_ref -> unsupported token type";
}
member_refs_[get_index_from_rid(rid)] = std::move(member_ref);
return member_refs_[get_index_from_rid(rid)].get();
}
const TypeRef* AssemblyReader::read_type_ref(u32 rid)
{
if (already_read(type_refs_, rid))
return type_refs_[get_index_from_rid(rid)].get();
resize_if_needed(type_refs_, pe::MetadataTable::TypeRef);
auto table_row_ptr = get_table_row_ptr(pe::MetadataTable::TypeRef, rid);
auto type_ref = std::make_unique<TypeRef>();
// ResolutionScope (an index into a Module, ModuleRef, AssemblyRef or TypeRef table, or null; more precisely, a ResolutionScope(II.24.2.6) coded index)
auto res_scope = read_metadata_token(&table_row_ptr, pe::CodedIndexType::ResolutionScope);
if (res_scope.type() == pe::MetadataTokenType::AssemblyRef)
{
type_ref->resolution_scope = read_assembly_ref(res_scope.rid());
}
else
{
throw "read_type_ref -> unsupported ResolutionScope type";
}
// TypeName(an index into the String heap)
type_ref->name = read_string(&table_row_ptr);
// TypeNamespace(an index into the String heap)
type_ref->name_space = read_string(&table_row_ptr);
type_refs_[get_index_from_rid(rid)] = std::make_unique<TypeRef>();
return type_refs_[get_index_from_rid(rid)].get();
}
const AssemblyRef* AssemblyReader::read_assembly_ref(u32 rid)
{
if (already_read(assembly_refs_, rid))
{
return assembly_refs_[get_index_from_rid(rid)].get();
}
resize_if_needed(assembly_refs_, pe::MetadataTable::AssemblyRef);
auto table_row_ptr = get_table_row_ptr(pe::MetadataTable::AssemblyRef, rid);
auto asm_ref = std::make_unique<AssemblyRef>();
// MajorVersion, MinorVersion, BuildNumber, RevisionNumber (each being 2-byte constants)
asm_ref->major_version = ptrutil::read16(&table_row_ptr);
asm_ref->minor_version = ptrutil::read16(&table_row_ptr);
asm_ref->build_number = ptrutil::read16(&table_row_ptr);
asm_ref->revision_number = ptrutil::read16(&table_row_ptr);
auto flags = ptrutil::read32(&table_row_ptr);
auto key_or_token_blob = read_blob(&table_row_ptr);
//PublicKeyOrToken (an index into the Blob heap, indicating the public key or token that identifies the author of this Assembly)
if ((static_cast<u32>(asm_ref->flags) & static_cast<u32>(AssemblyFlags::PublicKey)) != 0)
{
asm_ref->public_key = std::move(key_or_token_blob);
}
else
{
asm_ref->token = std::move(key_or_token_blob);
}
// Name (an index into the String heap)
asm_ref->name = read_string(&table_row_ptr);
// Culture (an index into the String heap)
asm_ref->culture = read_string(&table_row_ptr);
// HashValue (an index into the Blob heap)
asm_ref->hash_value = read_blob(&table_row_ptr);
assembly_refs_[get_index_from_rid(rid)] = std::move(asm_ref);
return assembly_refs_[get_index_from_rid(rid)].get();
}
void AssemblyReader::read_method_body(MethodDef* method)
{
method->body = std::make_unique<MethodBody>();
auto method_body_ptr = get_method_body_ptr(method->rva);
// The two least significant bits of the first byte of the method header indicate what type of header is present.
auto header_flag = *method_body_ptr;
method_body_ptr++;
auto tiny_header = (header_flag & 0x3) == CorILMethod_TinyFormat;
if (tiny_header)
{
// Tiny headers use a 6-bit length encoding
method->body->code_size = header_flag >> 2;
// The operand stack shall be no bigger than 8 entries
method->body->max_stack_size = 8;
read_method_body_instructions(method, method_body_ptr);
}
else
{
// TODO: Implement fat header reading
}
}
void AssemblyReader::read_method_body_instructions(MethodDef* method, u8* method_body_ptr)
{
auto opcode = read_opcode(&method_body_ptr);
auto stop_addr = method_body_ptr + method->body->code_size;
while (method_body_ptr != stop_addr)
{
switch (opcode.code)
{
case Code::LDSTR: {
auto str_token = read_metadata_token(&method_body_ptr);
auto str = read_us_string(str_token.rid());
method->body->instructions.push_back(std::make_unique<Instruction>(opcode, str));
break;
}
case Code::CALL: {
auto token = read_metadata_token(&method_body_ptr);
auto rid = token.rid();
auto type = token.type();
method->body->instructions.push_back(std::make_unique<Instruction>(opcode, read_member_ref(rid)));
break;
}
case Code::RET: {
method->body->instructions.push_back(std::make_unique<Instruction>(opcode));
break;
}
default:
logger_->LogError(L"AssemblyReader::read_method_body_instructions -> Unhandled opcode");
break;
}
opcode = read_opcode(&method_body_ptr);
}
}
const Opcode& AssemblyReader::read_opcode(u8** method_body_ptr)
{
auto code = ptrutil::read8(method_body_ptr);
return code == 0xff ? opcodes::get_two_byte_code(ptrutil::read8(method_body_ptr)) : opcodes::get_one_byte_code(code);
}
const InlineString* AssemblyReader::read_us_string(u32 index)
{
auto size = index + 1;
if (us_strings_.size() < size)
us_strings_.resize(size);
if (us_strings_[index] != nullptr)
return us_strings_[index].get();
if (index == 0)
return nullptr;
auto str_ptr = image_->heap_us.data + index;
// II.24.2.4 #US and #Blob heaps
auto length = read_us_or_blob_length(&str_ptr) & 0xfffffffe;
us_strings_[index] = std::make_unique<InlineString>(strutil::to_utf16wstr(str_ptr, length));
return us_strings_[index].get();
}
std::wstring AssemblyReader::read_string(u8** index_ptr)
{
auto index = read_string_index(index_ptr);
std::wstring value;
if (index == 0)
return value;
auto string_ptr = image_->heap_strings.data + index;
auto utf8_str = std::string(reinterpret_cast<const char*>(string_ptr));
return strutil::utf8str_to_utf16wstr(utf8_str);
}
u32 AssemblyReader::read_string_index(u8** index_ptr)
{
auto index_size = image_->string_idx_size;
u32 str_index = 0;
if (index_size == 2)
{
str_index = ptrutil::read16(index_ptr);
}
else
{
str_index = ptrutil::read32(index_ptr);
}
return str_index;
}
u32 AssemblyReader::read_blob_index(u8** index_ptr)
{
if (image_->blob_idx_size == 2)
return ptrutil::read16(index_ptr);
return ptrutil::read32(index_ptr);
}
std::unique_ptr<BlobEntry> AssemblyReader::read_blob(u8** index_ptr)
{
auto index = read_blob_index(index_ptr);
auto blob_ptr = image_->heap_blob.data + index;
auto length = read_us_or_blob_length(&blob_ptr);
auto buffer = new u8[length];
std::memcpy(buffer, blob_ptr, length);
return std::make_unique<BlobEntry>(buffer, length);
}
pe::MetadataToken AssemblyReader::read_metadata_token(u8** ptr)
{
auto value = ptrutil::read32(ptr);
return pe::MetadataToken(value);
}
pe::MetadataToken AssemblyReader::read_metadata_token(u8** ptr, pe::CodedIndexType index_type)
{
auto coded_index_info = pe::get_coded_index_info(index_type, image_->tables);
u32 token;
if (coded_index_info.size == 2)
token = ptrutil::read16(ptr);
else
token = ptrutil::read32(ptr);
return pe::get_metadata_token_from_coded_index(coded_index_info, token);
}
u8* AssemblyReader::get_table_row_ptr(pe::MetadataTable table_type, u32 rid)
{
auto table = image_->tables[static_cast<int>(table_type)];
if (table.rows == 0)
return nullptr;
return const_cast<u8*>(table.base + (table.row_size * (rid - 1)));
}
u8* AssemblyReader::get_method_body_ptr(u32 rva)
{
return const_cast<u8*>(image_->raw_data) + resolve_rva(rva);
}
u32 AssemblyReader::read_us_or_blob_length(const u8** blob_ptr)
{
u32 length;
auto ptr = *blob_ptr;
// II.24.2.4 #US and #Blob heaps
if ((ptr[0] & 0x80) == 0)
{
*blob_ptr += 1;
length = ptr[0];
}
else if ((ptr[0] & 0x40) == 0)
{
*blob_ptr += 2;
length = (u32)(ptr[0] & ~0x80) << 8;
length |= ptr[1];
}
else
{
*blob_ptr += 4;
length = (u32)(ptr[0] & ~0xc0) << 24;
length |= (u32)ptr[1] << 16;
length |= (u32)ptr[2] << 8;
length |= (u32)ptr[3];
}
return length;
}
u32 AssemblyReader::resolve_rva(u32 rva)
{
auto section = resolve_rva_section(rva);
return rva + section->raw_data_ptr - section->virtual_address;
}
const pe::SectionTable* AssemblyReader::resolve_rva_section(u32 rva)
{
for (auto& s : image_->cli_section_tables)
{
if (rva >= s->virtual_address && rva < s->virtual_address + s->raw_data_size)
return s.get();
}
return nullptr;
}
u32 AssemblyReader::get_num_entries(pe::MetadataTable table)
{
auto table_info = image_->tables[static_cast<int>(table)];
return table_info.rows;
}
u32 AssemblyReader::get_index_from_rid(u32 rid)
{
return rid - 1;
}
}
}
<commit_msg>move the read type ref<commit_after>#include "assembly_reader.h"
#include <cstring>
#include "../common/ptr_util.h"
#include "opcodes.h"
#include "../pe/coded_index.h"
#include "../pe/pe_image_reader.h"
#include "assembly.h"
namespace stereo {
namespace assemblies {
AssemblyReader::AssemblyReader(const char* file_path)
:
logger_(std::make_unique<logging::ConsoleLogger>()),
image_(pe::PEImageReader::load_image(file_path))
{
}
const pe::PEImage * AssemblyReader::get_image()
{
return image_.get();
}
u32 AssemblyReader::get_entry_point()
{
auto ept = pe::MetadataToken(image_->cli_header.entry_point_token);
return ept.rid();
}
const ModuleDef* AssemblyReader::read_module_def()
{
if (module_ != nullptr)
return module_.get();
auto module = std::make_unique<ModuleDef>();
auto table_row_ptr = get_table_row_ptr(pe::MetadataTable::Module, 1);
// Skip the generation column since it's always zero
table_row_ptr += 2;
module->name = read_string(&table_row_ptr);
// TODO: Read the mvid guid
module_ = std::move(module);
return module_.get();
}
const MethodDef* AssemblyReader::read_method_def(u32 rid)
{
if (already_read(method_defs_, rid))
return method_defs_[get_index_from_rid(rid)].get();
resize_if_needed(method_defs_, pe::MetadataTable::Method);
auto table_row_ptr = get_table_row_ptr(pe::MetadataTable::Method, rid);
auto method_def = std::make_unique<MethodDef>();
// RVA (a 4-byte constant)
method_def->rva = ptrutil::read32(&table_row_ptr);
// ImplFlags (a 2-byte bitmask of type MethodImplAttributes, II.23.1.10)
method_def->impl_attributes = static_cast<MethodImplAttributes>(ptrutil::read16(&table_row_ptr));
// Flags (a 2-byte bitmask of type MethodAttributes, II.23.1.10)
method_def->attributes = static_cast<MethodAttributes>(ptrutil::read16(&table_row_ptr));
// Name (an index into the String heap)
method_def->name = read_string(&table_row_ptr);
// TODO: Read signature, parameters etc
read_method_body(method_def.get());
method_defs_[get_index_from_rid(rid)] = std::move(method_def);
return method_defs_[get_index_from_rid(rid)].get();
}
const MemberRef* AssemblyReader::read_member_ref(u32 rid)
{
if (already_read(member_refs_, rid))
return member_refs_[get_index_from_rid(rid)].get();
resize_if_needed(member_refs_, pe::MetadataTable::MemberRef);
auto table_row_ptr = get_table_row_ptr(pe::MetadataTable::MemberRef, rid);
auto member_ref = std::make_unique<MemberRef>();
// Class (an index into the MethodDef, ModuleRef, TypeDef, TypeRef, or TypeSpec tables; more precisely, a MemberRefParent(II.24.2.6) coded index)
auto token = read_metadata_token(&table_row_ptr, pe::CodedIndexType::MemberRefParent);
// Name (an index into the String heap)
member_ref->name = read_string(&table_row_ptr);
// Signature (an index into the Blob heap)
auto signature = read_blob(&table_row_ptr);
// TODO: Implement all token type cases
if (token.type() == pe::MetadataTokenType::TypeRef)
{
member_ref->type_ref = read_type_ref(token.rid());
}
else
{
throw "read_member_ref -> unsupported token type";
}
member_refs_[get_index_from_rid(rid)] = std::move(member_ref);
return member_refs_[get_index_from_rid(rid)].get();
}
const TypeRef* AssemblyReader::read_type_ref(u32 rid)
{
if (already_read(type_refs_, rid))
return type_refs_[get_index_from_rid(rid)].get();
resize_if_needed(type_refs_, pe::MetadataTable::TypeRef);
auto table_row_ptr = get_table_row_ptr(pe::MetadataTable::TypeRef, rid);
auto type_ref = std::make_unique<TypeRef>();
// ResolutionScope (an index into a Module, ModuleRef, AssemblyRef or TypeRef table, or null; more precisely, a ResolutionScope(II.24.2.6) coded index)
auto res_scope = read_metadata_token(&table_row_ptr, pe::CodedIndexType::ResolutionScope);
if (res_scope.type() == pe::MetadataTokenType::AssemblyRef)
{
type_ref->resolution_scope = read_assembly_ref(res_scope.rid());
}
else
{
throw "read_type_ref -> unsupported ResolutionScope type";
}
// TypeName(an index into the String heap)
type_ref->name = read_string(&table_row_ptr);
// TypeNamespace(an index into the String heap)
type_ref->name_space = read_string(&table_row_ptr);
type_refs_[get_index_from_rid(rid)] = std::move(type_ref);
return type_refs_[get_index_from_rid(rid)].get();
}
const AssemblyRef* AssemblyReader::read_assembly_ref(u32 rid)
{
if (already_read(assembly_refs_, rid))
{
return assembly_refs_[get_index_from_rid(rid)].get();
}
resize_if_needed(assembly_refs_, pe::MetadataTable::AssemblyRef);
auto table_row_ptr = get_table_row_ptr(pe::MetadataTable::AssemblyRef, rid);
auto asm_ref = std::make_unique<AssemblyRef>();
// MajorVersion, MinorVersion, BuildNumber, RevisionNumber (each being 2-byte constants)
asm_ref->major_version = ptrutil::read16(&table_row_ptr);
asm_ref->minor_version = ptrutil::read16(&table_row_ptr);
asm_ref->build_number = ptrutil::read16(&table_row_ptr);
asm_ref->revision_number = ptrutil::read16(&table_row_ptr);
auto flags = ptrutil::read32(&table_row_ptr);
auto key_or_token_blob = read_blob(&table_row_ptr);
//PublicKeyOrToken (an index into the Blob heap, indicating the public key or token that identifies the author of this Assembly)
if ((static_cast<u32>(asm_ref->flags) & static_cast<u32>(AssemblyFlags::PublicKey)) != 0)
{
asm_ref->public_key = std::move(key_or_token_blob);
}
else
{
asm_ref->token = std::move(key_or_token_blob);
}
// Name (an index into the String heap)
asm_ref->name = read_string(&table_row_ptr);
// Culture (an index into the String heap)
asm_ref->culture = read_string(&table_row_ptr);
// HashValue (an index into the Blob heap)
asm_ref->hash_value = read_blob(&table_row_ptr);
assembly_refs_[get_index_from_rid(rid)] = std::move(asm_ref);
return assembly_refs_[get_index_from_rid(rid)].get();
}
void AssemblyReader::read_method_body(MethodDef* method)
{
method->body = std::make_unique<MethodBody>();
auto method_body_ptr = get_method_body_ptr(method->rva);
// The two least significant bits of the first byte of the method header indicate what type of header is present.
auto header_flag = *method_body_ptr;
method_body_ptr++;
auto tiny_header = (header_flag & 0x3) == CorILMethod_TinyFormat;
if (tiny_header)
{
// Tiny headers use a 6-bit length encoding
method->body->code_size = header_flag >> 2;
// The operand stack shall be no bigger than 8 entries
method->body->max_stack_size = 8;
read_method_body_instructions(method, method_body_ptr);
}
else
{
// TODO: Implement fat header reading
}
}
void AssemblyReader::read_method_body_instructions(MethodDef* method, u8* method_body_ptr)
{
auto opcode = read_opcode(&method_body_ptr);
auto stop_addr = method_body_ptr + method->body->code_size;
while (method_body_ptr != stop_addr)
{
switch (opcode.code)
{
case Code::LDSTR: {
auto str_token = read_metadata_token(&method_body_ptr);
auto str = read_us_string(str_token.rid());
method->body->instructions.push_back(std::make_unique<Instruction>(opcode, str));
break;
}
case Code::CALL: {
auto token = read_metadata_token(&method_body_ptr);
auto rid = token.rid();
auto type = token.type();
method->body->instructions.push_back(std::make_unique<Instruction>(opcode, read_member_ref(rid)));
break;
}
case Code::RET: {
method->body->instructions.push_back(std::make_unique<Instruction>(opcode));
break;
}
default:
logger_->LogError(L"AssemblyReader::read_method_body_instructions -> Unhandled opcode");
break;
}
opcode = read_opcode(&method_body_ptr);
}
}
const Opcode& AssemblyReader::read_opcode(u8** method_body_ptr)
{
auto code = ptrutil::read8(method_body_ptr);
return code == 0xff ? opcodes::get_two_byte_code(ptrutil::read8(method_body_ptr)) : opcodes::get_one_byte_code(code);
}
const InlineString* AssemblyReader::read_us_string(u32 index)
{
auto size = index + 1;
if (us_strings_.size() < size)
us_strings_.resize(size);
if (us_strings_[index] != nullptr)
return us_strings_[index].get();
if (index == 0)
return nullptr;
auto str_ptr = image_->heap_us.data + index;
// II.24.2.4 #US and #Blob heaps
auto length = read_us_or_blob_length(&str_ptr) & 0xfffffffe;
us_strings_[index] = std::make_unique<InlineString>(strutil::to_utf16wstr(str_ptr, length));
return us_strings_[index].get();
}
std::wstring AssemblyReader::read_string(u8** index_ptr)
{
auto index = read_string_index(index_ptr);
std::wstring value;
if (index == 0)
return value;
auto string_ptr = image_->heap_strings.data + index;
auto utf8_str = std::string(reinterpret_cast<const char*>(string_ptr));
return strutil::utf8str_to_utf16wstr(utf8_str);
}
u32 AssemblyReader::read_string_index(u8** index_ptr)
{
auto index_size = image_->string_idx_size;
u32 str_index = 0;
if (index_size == 2)
{
str_index = ptrutil::read16(index_ptr);
}
else
{
str_index = ptrutil::read32(index_ptr);
}
return str_index;
}
u32 AssemblyReader::read_blob_index(u8** index_ptr)
{
if (image_->blob_idx_size == 2)
return ptrutil::read16(index_ptr);
return ptrutil::read32(index_ptr);
}
std::unique_ptr<BlobEntry> AssemblyReader::read_blob(u8** index_ptr)
{
auto index = read_blob_index(index_ptr);
auto blob_ptr = image_->heap_blob.data + index;
auto length = read_us_or_blob_length(&blob_ptr);
auto buffer = new u8[length];
std::memcpy(buffer, blob_ptr, length);
return std::make_unique<BlobEntry>(buffer, length);
}
pe::MetadataToken AssemblyReader::read_metadata_token(u8** ptr)
{
auto value = ptrutil::read32(ptr);
return pe::MetadataToken(value);
}
pe::MetadataToken AssemblyReader::read_metadata_token(u8** ptr, pe::CodedIndexType index_type)
{
auto coded_index_info = pe::get_coded_index_info(index_type, image_->tables);
u32 token;
if (coded_index_info.size == 2)
token = ptrutil::read16(ptr);
else
token = ptrutil::read32(ptr);
return pe::get_metadata_token_from_coded_index(coded_index_info, token);
}
u8* AssemblyReader::get_table_row_ptr(pe::MetadataTable table_type, u32 rid)
{
auto table = image_->tables[static_cast<int>(table_type)];
if (table.rows == 0)
return nullptr;
return const_cast<u8*>(table.base + (table.row_size * (rid - 1)));
}
u8* AssemblyReader::get_method_body_ptr(u32 rva)
{
return const_cast<u8*>(image_->raw_data) + resolve_rva(rva);
}
u32 AssemblyReader::read_us_or_blob_length(const u8** blob_ptr)
{
u32 length;
auto ptr = *blob_ptr;
// II.24.2.4 #US and #Blob heaps
if ((ptr[0] & 0x80) == 0)
{
*blob_ptr += 1;
length = ptr[0];
}
else if ((ptr[0] & 0x40) == 0)
{
*blob_ptr += 2;
length = (u32)(ptr[0] & ~0x80) << 8;
length |= ptr[1];
}
else
{
*blob_ptr += 4;
length = (u32)(ptr[0] & ~0xc0) << 24;
length |= (u32)ptr[1] << 16;
length |= (u32)ptr[2] << 8;
length |= (u32)ptr[3];
}
return length;
}
u32 AssemblyReader::resolve_rva(u32 rva)
{
auto section = resolve_rva_section(rva);
return rva + section->raw_data_ptr - section->virtual_address;
}
const pe::SectionTable* AssemblyReader::resolve_rva_section(u32 rva)
{
for (auto& s : image_->cli_section_tables)
{
if (rva >= s->virtual_address && rva < s->virtual_address + s->raw_data_size)
return s.get();
}
return nullptr;
}
u32 AssemblyReader::get_num_entries(pe::MetadataTable table)
{
auto table_info = image_->tables[static_cast<int>(table)];
return table_info.rows;
}
u32 AssemblyReader::get_index_from_rid(u32 rid)
{
return rid - 1;
}
}
}
<|endoftext|> |
<commit_before>#include <iostream>
#include <QtGui>
#include <limits>
#include <cmath>
#include <bitset>
#include "./nbt.h"
#include "./settings.h"
#include "./colors.h"
int main(int ac, const char* av[]) {
if (ac != 2) {
std::cerr << "Usage: ./nbtparse [filename | world number]" << std::endl;
exit(1);
}
int world = atoi(av[1]);
nbt bf;
if (world == 0) {
bf = nbt(av[1]);
} else {
bf = nbt(world);
}
std::cout << bf.string();
Settings set;
set.topview = true;
set.heightmap = false;
set.color = false;
QImage img((bf.xPos_max() - bf.xPos_min() + 1) * 16,
(bf.zPos_max() - bf.zPos_min() + 1) * 16,
QImage::Format_ARGB32_Premultiplied);
img.fill(0);
int min = 300, max = -10;
for (int i = bf.zPos_min(); i <= bf.zPos_max(); ++i) {
for (int j = bf.xPos_min(); j <= bf.xPos_max(); ++j) {
const nbt::tag_ptr tag = bf.tag_at(j, i);
if (tag) {
nbt::tag_ptr comp(tag->sub("Level"));
int32_t xPos = comp->sub("xPos")->pay_<int32_t>();
int32_t zPos = comp->sub("zPos")->pay_<int32_t>();
const std::string& heightMap = comp->sub("HeightMap")->
pay_<tag::byte_array>().p;
const std::string& blocks = comp->sub("Blocks")->
pay_<tag::byte_array>().p;
const std::string& skylight = comp->sub("SkyLight")->
pay_<tag::byte_array>().p;
uint64_t xtmp = (xPos - bf.xPos_min()) * 16;
uint64_t ztmp = (zPos - bf.zPos_min()) * 16;
int32_t max_int = std::numeric_limits<int32_t>::max();
if (xtmp + 15 > static_cast<uint64_t>(max_int)
|| ztmp + 15 > static_cast<uint64_t>(max_int)) {
std::cerr << "Map is too large for an image!" << std::endl;
exit(1);
}
int32_t xPos_img = static_cast<int32_t>(xtmp);
int32_t zPos_img = static_cast<int32_t>(ztmp);
int index = 0;
for (int32_t ii = zPos_img; ii < zPos_img + 16; ++ii) {
for (int32_t jj = xPos_img; jj < xPos_img + 16; ++jj) {
int32_t ii0 = ii - zPos_img;
int32_t jj0 = jj - xPos_img;
uint8_t height = heightMap[index++];
QColor color;
if (set.heightmap) {
if (set.color) {
color.setHsvF(atan(((1.0 - height / 127.0) - 0.5) * 10) / M_PI + 0.5, 1.0, 1.0, 1.0);
} else {
color.setRgba(QColor(height, height, height, 255).rgba());
}
} else {
int height_low_bound = height;
while (colors[blocks[height_low_bound-- + ii0 * 128
+ jj0 * 128 * 16]].alpha() != 255);
for (int h = height_low_bound; h <= height; ++h) {
uint8_t blknr = blocks[h + ii0 * 128 + jj0 * 128 * 16];
color = blend(colors[blknr], color);
}
img.setPixel(static_cast<int32_t>(jj), static_cast<int32_t>(ii),
color.lighter((height - 64) / 2 + 64).rgba());
}
// uint8_t light = skylight[(height + ii0 * 128 + jj0 * 128 * 16) / 2];
// if (height % 2 == 1) {
// light >>= 4;
// } else {
// light &= 0x0F;
// }
// light <<= 4;
}
}
// std::cout << j << " " << xPos << " "
// << i << " " << zPos << std::endl;
}
}
}
img.save("test.png");
return 0;
}
<commit_msg>remove those<commit_after>#include <iostream>
#include <QtGui>
#include <limits>
#include <cmath>
#include <bitset>
#include "./nbt.h"
#include "./settings.h"
#include "./colors.h"
int main(int ac, const char* av[]) {
if (ac != 2) {
std::cerr << "Usage: ./nbtparse [filename | world number]" << std::endl;
exit(1);
}
int world = atoi(av[1]);
nbt bf;
if (world == 0) {
bf = nbt(av[1]);
} else {
bf = nbt(world);
}
std::cout << bf.string();
Settings set;
set.topview = true;
set.heightmap = false;
set.color = false;
QImage img((bf.xPos_max() - bf.xPos_min() + 1) * 16,
(bf.zPos_max() - bf.zPos_min() + 1) * 16,
QImage::Format_ARGB32_Premultiplied);
img.fill(0);
for (int i = bf.zPos_min(); i <= bf.zPos_max(); ++i) {
for (int j = bf.xPos_min(); j <= bf.xPos_max(); ++j) {
const nbt::tag_ptr tag = bf.tag_at(j, i);
if (tag) {
nbt::tag_ptr comp(tag->sub("Level"));
int32_t xPos = comp->sub("xPos")->pay_<int32_t>();
int32_t zPos = comp->sub("zPos")->pay_<int32_t>();
const std::string& heightMap = comp->sub("HeightMap")->
pay_<tag::byte_array>().p;
const std::string& blocks = comp->sub("Blocks")->
pay_<tag::byte_array>().p;
const std::string& skylight = comp->sub("SkyLight")->
pay_<tag::byte_array>().p;
uint64_t xtmp = (xPos - bf.xPos_min()) * 16;
uint64_t ztmp = (zPos - bf.zPos_min()) * 16;
int32_t max_int = std::numeric_limits<int32_t>::max();
if (xtmp + 15 > static_cast<uint64_t>(max_int)
|| ztmp + 15 > static_cast<uint64_t>(max_int)) {
std::cerr << "Map is too large for an image!" << std::endl;
exit(1);
}
int32_t xPos_img = static_cast<int32_t>(xtmp);
int32_t zPos_img = static_cast<int32_t>(ztmp);
int index = 0;
for (int32_t ii = zPos_img; ii < zPos_img + 16; ++ii) {
for (int32_t jj = xPos_img; jj < xPos_img + 16; ++jj) {
int32_t ii0 = ii - zPos_img;
int32_t jj0 = jj - xPos_img;
uint8_t height = heightMap[index++];
QColor color;
if (set.heightmap) {
if (set.color) {
color.setHsvF(atan(((1.0 - height / 127.0) - 0.5) * 10) / M_PI + 0.5, 1.0, 1.0, 1.0);
} else {
color.setRgba(QColor(height, height, height, 255).rgba());
}
} else {
int height_low_bound = height;
while (colors[blocks[height_low_bound-- + ii0 * 128
+ jj0 * 128 * 16]].alpha() != 255);
for (int h = height_low_bound; h <= height; ++h) {
uint8_t blknr = blocks[h + ii0 * 128 + jj0 * 128 * 16];
color = blend(colors[blknr], color);
}
img.setPixel(static_cast<int32_t>(jj), static_cast<int32_t>(ii),
color.lighter((height - 64) / 2 + 64).rgba());
}
// uint8_t light = skylight[(height + ii0 * 128 + jj0 * 128 * 16) / 2];
// if (height % 2 == 1) {
// light >>= 4;
// } else {
// light &= 0x0F;
// }
// light <<= 4;
}
}
// std::cout << j << " " << xPos << " "
// << i << " " << zPos << std::endl;
}
}
}
img.save("test.png");
return 0;
}
<|endoftext|> |
<commit_before>/*-------------------------------------------------------------------------
*
* stack_trace.cpp
* file description
*
* Copyright(c) 2015, CMU
*
* /peloton/src/backend/bridge/stack_trace.cpp
*
*-------------------------------------------------------------------------
*/
#include <cstdio>
#include <cstdlib>
#include <cassert>
#include <stdexcept>
#include <execinfo.h>
#include <errno.h>
#include <cxxabi.h>
#include <signal.h>
#include <sys/types.h>
#include <unistd.h>
#include <sstream>
#include <thread>
#include <iomanip>
#include "backend/common/stack_trace.h"
#include "backend/common/logger.h"
namespace peloton {
// Based on :: http://panthema.net/2008/0901-stacktrace-demangled/
void GetStackTrace(){
std::stringstream stack_trace;
std::stringstream internal_info;
unsigned int max_frames = 63;
/// storage array for stack trace address data
void* addrlist[max_frames+1];
/// retrieve current stack addresses
int addrlen = backtrace(addrlist, sizeof(addrlist) / sizeof(void*));
if (addrlen == 0) {
stack_trace << "<empty, possibly corrupt>\n";
return;
}
/// resolve addresses into strings containing "filename(function+address)",
/// this array must be free()-ed
char** symbol_list = backtrace_symbols(addrlist, addrlen);
/// allocate string which will be filled with the demangled function name
size_t func_name_size = 1024;
char* func_name = (char*) malloc(func_name_size);
/// iterate over the returned symbol lines. skip the first, it is the
/// address of this function.
for (int i = 1; i < addrlen; i++){
char *begin_name = 0, *begin_offset = 0, *end_offset = 0;
/// find parentheses and +address offset surrounding the mangled name:
/// ./module(function+0x15c) [0x8048a6d]
for (char *p = symbol_list[i]; *p; ++p){
if (*p == '(')
begin_name = p;
else if (*p == '+')
begin_offset = p;
else if (*p == ')' && begin_offset) {
end_offset = p;
break;
}
}
if (begin_name && begin_offset && end_offset && begin_name < begin_offset){
*begin_name++ = '\0';
*begin_offset++ = '\0';
*end_offset = '\0';
/// mangled name is now in [begin_name, begin_offset) and caller
/// offset in [begin_offset, end_offset). now apply __cxa_demangle():
int status;
char* ret = abi::__cxa_demangle(begin_name, func_name, &func_name_size, &status);
if (status == 0) {
func_name = ret; // use possibly realloc()-ed string
stack_trace << symbol_list[i] << ": " << func_name << " + " << begin_offset << "\n";
}
else {
/// demangling failed. Output function name as a C function with
/// no arguments.
stack_trace << symbol_list[i] << ": " << begin_name << " + " << begin_offset << "\n";
}
}
else
{
/// couldn't parse the line ? print the whole line.
stack_trace << symbol_list[i] << "\n";
}
}
internal_info << "process : " << getpid() << " thread : " << std::this_thread::get_id();
LOG_INFO("segmentation fault");
LOG_INFO("info : %s", internal_info.str().c_str());
LOG_INFO("stack trace :\n%s", stack_trace.str().c_str());
free(func_name);
free(symbol_list);
}
} // namespace peloton
<commit_msg>Clean up stack trace.<commit_after>/*-------------------------------------------------------------------------
*
* stack_trace.cpp
* file description
*
* Copyright(c) 2015, CMU
*
* /peloton/src/backend/bridge/stack_trace.cpp
*
*-------------------------------------------------------------------------
*/
#include <cstdio>
#include <cstdlib>
#include <cassert>
#include <stdexcept>
#include <execinfo.h>
#include <errno.h>
#include <cxxabi.h>
#include <signal.h>
#include <sys/types.h>
#include <unistd.h>
#include <sstream>
#include <thread>
#include <iomanip>
#include "backend/common/stack_trace.h"
#include "backend/common/logger.h"
namespace peloton {
// Based on :: http://panthema.net/2008/0901-stacktrace-demangled/
void GetStackTrace(){
std::stringstream stack_trace;
std::stringstream internal_info;
unsigned int max_frames = 63;
/// storage array for stack trace address data
void* addrlist[max_frames+1];
/// retrieve current stack addresses
int addrlen = backtrace(addrlist, sizeof(addrlist) / sizeof(void*));
if (addrlen == 0) {
stack_trace << "<empty, possibly corrupt>\n";
return;
}
/// resolve addresses into strings containing "filename(function+address)",
/// this array must be free()-ed
char** symbol_list = backtrace_symbols(addrlist, addrlen);
/// allocate string which will be filled with the demangled function name
size_t func_name_size = 4096;
char* func_name = (char*) malloc(func_name_size);
/// iterate over the returned symbol lines. skip the first, it is the
/// address of this function.
for (int i = 1; i < addrlen; i++){
char *begin_name = 0, *begin_offset = 0, *end_offset = 0;
/// find parentheses and +address offset surrounding the mangled name:
/// ./module(function+0x15c) [0x8048a6d]
for (char *p = symbol_list[i]; *p; ++p){
if (*p == '(')
begin_name = p;
else if (*p == '+')
begin_offset = p;
else if (*p == ')' && begin_offset) {
end_offset = p;
break;
}
}
if (begin_name && begin_offset && end_offset && begin_name < begin_offset){
*begin_name++ = '\0';
*begin_offset++ = '\0';
*end_offset = '\0';
/// mangled name is now in [begin_name, begin_offset) and caller
/// offset in [begin_offset, end_offset). now apply __cxa_demangle():
int status;
char* ret = abi::__cxa_demangle(begin_name, func_name, &func_name_size, &status);
if (status == 0) {
func_name = ret; // use possibly realloc()-ed string
stack_trace << std::left << std::setw(15) << addrlist[i] << " :: "
<< symbol_list[i] << " [ "
<< func_name << " "
<< begin_offset << " ]\n";
}
else {
/// demangling failed. Output function name as a C function with
/// no arguments.
stack_trace << std::left << std::setw(15) << addrlist[i] << " :: "
<< symbol_list[i] << " [ "
<< begin_name << " "
<< begin_offset << " ]\n";
}
}
else {
/// couldn't parse the line ? print the whole line.
stack_trace << std::left << std::setw(15) << addrlist[i] << " :: "
<< std::setw(30) << symbol_list[i] << "\n";
}
}
internal_info << "process : " << getpid() << " thread : " << std::this_thread::get_id();
LOG_INFO("segmentation fault");
LOG_INFO("%s", internal_info.str().c_str());
LOG_INFO("stack trace :\n");
LOG_INFO("+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++\n");
LOG_INFO("%s", stack_trace.str().c_str());
LOG_INFO("+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++\n");
free(func_name);
free(symbol_list);
}
} // namespace peloton
<|endoftext|> |
<commit_before>/*******************************************************
* Copyright (c) 2015, ArrayFire
* All rights reserved.
*
* This file is distributed under 3-clause BSD license.
* The complete license agreement can be obtained at:
* http://arrayfire.com/licenses/BSD-3-Clause
********************************************************/
#pragma once
#include <Array.hpp>
namespace cpu
{
namespace kernel
{
template<typename T>
class LabelNode
{
private:
T label;
T minLabel;
unsigned rank;
LabelNode* parent;
public:
LabelNode() : label(0), minLabel(0), rank(0), parent(this) { }
LabelNode(T label) : label(label), minLabel(label), rank(0), parent(this) { }
T getLabel()
{
return label;
}
T getMinLabel()
{
return minLabel;
}
LabelNode* getParent()
{
return parent;
}
unsigned getRank()
{
return rank;
}
void setMinLabel(T l)
{
minLabel = l;
}
void setParent(LabelNode* p)
{
parent = p;
}
void setRank(unsigned r)
{
rank = r;
}
};
template<typename T>
static LabelNode<T>* find(LabelNode<T>* x)
{
if (x->getParent() != x)
x->setParent(find(x->getParent()));
return x->getParent();
}
template<typename T>
static void setUnion(LabelNode<T>* x, LabelNode<T>* y)
{
LabelNode<T>* xRoot = find(x);
LabelNode<T>* yRoot = find(y);
if (xRoot == yRoot)
return;
T xMinLabel = xRoot->getMinLabel();
T yMinLabel = yRoot->getMinLabel();
xRoot->setMinLabel(min(xMinLabel, yMinLabel));
yRoot->setMinLabel(min(xMinLabel, yMinLabel));
if (xRoot->getRank() < yRoot->getRank())
xRoot->setParent(yRoot);
else if (xRoot->getRank() > yRoot->getRank())
yRoot->setParent(xRoot);
else {
yRoot->setParent(xRoot);
xRoot->setRank(xRoot->getRank() + 1);
}
}
template<typename T>
void regions(Array<T> out, const Array<char> in, af_connectivity connectivity)
{
const af::dim4 in_dims = in.dims();
const char *in_ptr = in.get();
T *out_ptr = out.get();
// Map labels
typedef typename std::map<T, LabelNode<T>* > label_map_t;
typedef typename label_map_t::iterator label_map_iterator_t;
label_map_t lmap;
// Initial label
T label = (T)1;
for (int j = 0; j < (int)in_dims[1]; j++) {
for (int i = 0; i < (int)in_dims[0]; i++) {
int idx = j * in_dims[0] + i;
if (in_ptr[idx] != 0) {
std::vector<T> l;
// Test neighbors
if (i > 0 && out_ptr[j * (int)in_dims[0] + i-1] > 0)
l.push_back(out_ptr[j * in_dims[0] + i-1]);
if (j > 0 && out_ptr[(j-1) * (int)in_dims[0] + i] > 0)
l.push_back(out_ptr[(j-1) * in_dims[0] + i]);
if (connectivity == AF_CONNECTIVITY_8 && i > 0 &&
j > 0 && out_ptr[(j-1) * in_dims[0] + i-1] > 0)
l.push_back(out_ptr[(j-1) * in_dims[0] + i-1]);
if (connectivity == AF_CONNECTIVITY_8 &&
i < (int)in_dims[0] - 1 && j > 0 && out_ptr[(j-1) * in_dims[0] + i+1] != 0)
l.push_back(out_ptr[(j-1) * in_dims[0] + i+1]);
if (!l.empty()) {
T minl = l[0];
for (size_t k = 0; k < l.size(); k++) {
minl = min(l[k], minl);
label_map_iterator_t cur_map = lmap.find(l[k]);
LabelNode<T> *node = cur_map->second;
// Group labels of the same region under a disjoint set
for (size_t m = k+1; m < l.size(); m++)
setUnion(node, lmap.find(l[m])->second);
}
// Set label to smallest neighbor label
out_ptr[idx] = minl;
}
else {
// Insert new label in map
LabelNode<T> *node = new LabelNode<T>(label);
lmap.insert(std::pair<T, LabelNode<T>* >(label, node));
out_ptr[idx] = label++;
}
}
}
}
std::set<T> removed;
for (int j = 0; j < (int)in_dims[1]; j++) {
for (int i = 0; i < (int)in_dims[0]; i++) {
int idx = j * (int)in_dims[0] + i;
if (in_ptr[idx] != 0) {
T l = out_ptr[idx];
label_map_iterator_t cur_map = lmap.find(l);
if (cur_map != lmap.end()) {
LabelNode<T>* node = cur_map->second;
LabelNode<T>* node_root = find(node);
out_ptr[idx] = node_root->getMinLabel();
// Mark removed labels (those that are part of a region
// that contains a smaller label)
if (node->getMinLabel() < l || node_root->getMinLabel() < l)
removed.insert(l);
if (node->getLabel() > node->getMinLabel())
removed.insert(node->getLabel());
}
}
}
}
// Calculate final neighbors (ensure final labels are sequential)
for (int j = 0; j < (int)in_dims[1]; j++) {
for (int i = 0; i < (int)in_dims[0]; i++) {
int idx = j * (int)in_dims[0] + i;
if (out_ptr[idx] > 0) {
out_ptr[idx] -= distance(removed.begin(), removed.lower_bound(out_ptr[idx]));
}
}
}
}
}
}
<commit_msg>fix memory leak in regions cpu backend<commit_after>/*******************************************************
* Copyright (c) 2015, ArrayFire
* All rights reserved.
*
* This file is distributed under 3-clause BSD license.
* The complete license agreement can be obtained at:
* http://arrayfire.com/licenses/BSD-3-Clause
********************************************************/
#pragma once
#include <Array.hpp>
#include <memory.hpp>
namespace cpu
{
namespace kernel
{
template<typename T>
class LabelNode
{
private:
T label;
T minLabel;
unsigned rank;
LabelNode* parent;
public:
LabelNode() : label(0), minLabel(0), rank(0), parent(this) { }
LabelNode(T label) : label(label), minLabel(label), rank(0), parent(this) { }
T getLabel()
{
return label;
}
T getMinLabel()
{
return minLabel;
}
LabelNode* getParent()
{
return parent;
}
unsigned getRank()
{
return rank;
}
void setMinLabel(T l)
{
minLabel = l;
}
void setParent(LabelNode* p)
{
parent = p;
}
void setRank(unsigned r)
{
rank = r;
}
};
template<typename T>
static LabelNode<T>* find(LabelNode<T>* x)
{
if (x->getParent() != x)
x->setParent(find(x->getParent()));
return x->getParent();
}
template<typename T>
static void setUnion(LabelNode<T>* x, LabelNode<T>* y)
{
LabelNode<T>* xRoot = find(x);
LabelNode<T>* yRoot = find(y);
if (xRoot == yRoot)
return;
T xMinLabel = xRoot->getMinLabel();
T yMinLabel = yRoot->getMinLabel();
xRoot->setMinLabel(min(xMinLabel, yMinLabel));
yRoot->setMinLabel(min(xMinLabel, yMinLabel));
if (xRoot->getRank() < yRoot->getRank())
xRoot->setParent(yRoot);
else if (xRoot->getRank() > yRoot->getRank())
yRoot->setParent(xRoot);
else {
yRoot->setParent(xRoot);
xRoot->setRank(xRoot->getRank() + 1);
}
}
template<typename T>
void regions(Array<T> out, const Array<char> in, af_connectivity connectivity)
{
const af::dim4 inDims = in.dims();
const char *inPtr = in.get();
T *outPtr = out.get();
// Map labels
typedef typename std::unique_ptr< LabelNode<T> > UnqLabelPtr;
typedef typename std::map<T, UnqLabelPtr > LabelMap;
typedef typename LabelMap::iterator LabelMapIterator;
LabelMap lmap;
// Initial label
T label = (T)1;
for (int j = 0; j < (int)inDims[1]; j++) {
for (int i = 0; i < (int)inDims[0]; i++) {
int idx = j * inDims[0] + i;
if (inPtr[idx] != 0) {
std::vector<T> l;
// Test neighbors
if (i > 0 && outPtr[j * (int)inDims[0] + i-1] > 0)
l.push_back(outPtr[j * inDims[0] + i-1]);
if (j > 0 && outPtr[(j-1) * (int)inDims[0] + i] > 0)
l.push_back(outPtr[(j-1) * inDims[0] + i]);
if (connectivity == AF_CONNECTIVITY_8 && i > 0 &&
j > 0 && outPtr[(j-1) * inDims[0] + i-1] > 0)
l.push_back(outPtr[(j-1) * inDims[0] + i-1]);
if (connectivity == AF_CONNECTIVITY_8 &&
i < (int)inDims[0] - 1 && j > 0 && outPtr[(j-1) * inDims[0] + i+1] != 0)
l.push_back(outPtr[(j-1) * inDims[0] + i+1]);
if (!l.empty()) {
T minl = l[0];
for (size_t k = 0; k < l.size(); k++) {
minl = min(l[k], minl);
LabelMapIterator currentMap = lmap.find(l[k]);
LabelNode<T> *node = currentMap->second.get();
// Group labels of the same region under a disjoint set
for (size_t m = k+1; m < l.size(); m++)
setUnion(node, lmap.find(l[m])->second.get());
}
// Set label to smallest neighbor label
outPtr[idx] = minl;
} else {
// Insert new label in map
lmap.insert(std::make_pair(label, UnqLabelPtr(new LabelNode<T>(label))));
outPtr[idx] = label++;
}
}
}
}
std::set<T> removed;
for (int j = 0; j < (int)inDims[1]; j++) {
for (int i = 0; i < (int)inDims[0]; i++) {
int idx = j * (int)inDims[0] + i;
if (inPtr[idx] != 0) {
T l = outPtr[idx];
LabelMapIterator currentMap = lmap.find(l);
if (currentMap != lmap.end()) {
LabelNode<T>* node = currentMap->second.get();
LabelNode<T>* nodeRoot = find(node);
outPtr[idx] = nodeRoot->getMinLabel();
// Mark removed labels (those that are part of a region
// that contains a smaller label)
if (node->getMinLabel() < l || nodeRoot->getMinLabel() < l)
removed.insert(l);
if (node->getLabel() > node->getMinLabel())
removed.insert(node->getLabel());
}
}
}
}
// Calculate final neighbors (ensure final labels are sequential)
for (int j = 0; j < (int)inDims[1]; j++) {
for (int i = 0; i < (int)inDims[0]; i++) {
int idx = j * (int)inDims[0] + i;
if (outPtr[idx] > 0) {
outPtr[idx] -= distance(removed.begin(), removed.lower_bound(outPtr[idx]));
}
}
}
}
}
}
<|endoftext|> |
<commit_before>/*
* Copyright (c) 2012 Aldebaran Robotics. All rights reserved.
* Use of this source code is governed by a BSD-style license that can be
* found in the COPYING file.
*/
#include <boost/filesystem.hpp>
#include <locale>
#include <cstdio>
#include <cstdlib>
#include <algorithm>
#include <fcntl.h>
#include <sys/stat.h>
#ifdef _WIN32
# include <io.h> //_wopen
# include <windows.h> //Sleep
#else
# include <pwd.h>
# include <sys/time.h>
#endif
#include <qi/os.hpp>
#include <qi/error.hpp>
#include <qi/qi.hpp>
#include "src/filesystem.hpp"
namespace qi {
namespace os {
FILE* fopen(const char *filename, const char *mode) {
return ::fopen(boost::filesystem::path(filename, qi::unicodeFacet()).string(qi::unicodeFacet()).c_str(),
boost::filesystem::path(mode, qi::unicodeFacet()).string(qi::unicodeFacet()).c_str());
}
int stat(const char *filename, struct ::stat* status) {
return ::stat(boost::filesystem::path(filename, qi::unicodeFacet()).string(qi::unicodeFacet()).c_str(), status);
}
std::string getenv(const char *var) {
char *res = ::getenv(boost::filesystem::path(var, qi::unicodeFacet()).string(qi::unicodeFacet()).c_str());
if (res == NULL)
return "";
return std::string(res);
}
int setenv(const char *var, const char *value) {
return ::setenv(boost::filesystem::path(var, qi::unicodeFacet()).string(qi::unicodeFacet()).c_str(),
boost::filesystem::path(value, qi::unicodeFacet()).string(qi::unicodeFacet()).c_str(), 1);
}
void sleep(unsigned int seconds) {
// In case sleep was interrupted by a signal,
// keep sleeping until we have slept the correct amount
// of time.
while (seconds != 0) {
seconds = ::sleep(seconds);
}
}
void msleep(unsigned int milliseconds) {
// Not the same for usleep: it returns a non-zero
// error code if it was interupted...
usleep(milliseconds * 1000);
}
std::string home()
{
std::string envHome = qi::os::getenv("HOME");
if (envHome != "")
{
return boost::filesystem::path(envHome, qi::unicodeFacet()).make_preferred().string(qi::unicodeFacet());
}
// $HOME environment variable not defined:
char *lgn;
struct passwd *pw;
if ((lgn = getlogin()) == NULL || (pw = getpwnam(lgn)) == NULL)
{
return boost::filesystem::path(pw->pw_dir, qi::unicodeFacet()).make_preferred().string(qi::unicodeFacet());
}
// Give up:
return "";
}
std::string tmpdir(const char *prefix) {
char buffer[L_tmpnam];
memset(buffer, 0, L_tmpnam);
tmpnam(buffer);
boost::filesystem::path path;
if (buffer == NULL)
{
#ifdef __APPLE__
path = boost::filesystem::path(::qi::os::home(),
qi::unicodeFacet()).append("Cache", qi::unicodeFacet());
#else
path = boost::filesystem::path(::qi::os::home(),
qi::unicodeFacet()).append(".cache", qi::unicodeFacet());
#endif
}
else
{
path = buffer;
}
std::string filename(prefix);
filename += path.filename().string(qi::unicodeFacet());
path = path.parent_path().append(filename, qi::unicodeFacet());
try
{
if (!boost::filesystem::exists(path))
boost::filesystem::create_directories(path);
}
catch (const boost::filesystem::filesystem_error &e)
{
throw qi::os::QiException(e.what());
}
return path.string(qi::unicodeFacet());
}
std::string tmp()
{
std::string temp = ::qi::os::getenv("TMPDIR");
if (temp.empty())
temp = "/tmp/";
boost::filesystem::path p = boost::filesystem::path(temp, qi::unicodeFacet());
return p.string(qi::unicodeFacet());
}
int gettimeofday(qi::os::timeval *tp) {
struct ::timeval tv;
int ret = ::gettimeofday(&tv, 0);
tp->tv_sec = tv.tv_sec;
tp->tv_usec = tv.tv_usec;
return ret;
}
};
};
<commit_msg>Fix wrong behavior of tmpdir (linux) when tmpnam fail.<commit_after>/*
* Copyright (c) 2012 Aldebaran Robotics. All rights reserved.
* Use of this source code is governed by a BSD-style license that can be
* found in the COPYING file.
*/
#include <boost/filesystem.hpp>
#include <locale>
#include <cstdio>
#include <cstdlib>
#include <algorithm>
#include <fcntl.h>
#include <sys/stat.h>
#ifdef _WIN32
# include <io.h> //_wopen
# include <windows.h> //Sleep
#else
# include <pwd.h>
# include <sys/time.h>
#endif
#include <qi/os.hpp>
#include <qi/error.hpp>
#include <qi/qi.hpp>
#include "src/filesystem.hpp"
namespace qi {
namespace os {
FILE* fopen(const char *filename, const char *mode) {
return ::fopen(boost::filesystem::path(filename, qi::unicodeFacet()).string(qi::unicodeFacet()).c_str(),
boost::filesystem::path(mode, qi::unicodeFacet()).string(qi::unicodeFacet()).c_str());
}
int stat(const char *filename, struct ::stat* status) {
return ::stat(boost::filesystem::path(filename, qi::unicodeFacet()).string(qi::unicodeFacet()).c_str(), status);
}
std::string getenv(const char *var) {
char *res = ::getenv(boost::filesystem::path(var, qi::unicodeFacet()).string(qi::unicodeFacet()).c_str());
if (res == NULL)
return "";
return std::string(res);
}
int setenv(const char *var, const char *value) {
return ::setenv(boost::filesystem::path(var, qi::unicodeFacet()).string(qi::unicodeFacet()).c_str(),
boost::filesystem::path(value, qi::unicodeFacet()).string(qi::unicodeFacet()).c_str(), 1);
}
void sleep(unsigned int seconds) {
// In case sleep was interrupted by a signal,
// keep sleeping until we have slept the correct amount
// of time.
while (seconds != 0) {
seconds = ::sleep(seconds);
}
}
void msleep(unsigned int milliseconds) {
// Not the same for usleep: it returns a non-zero
// error code if it was interupted...
usleep(milliseconds * 1000);
}
std::string home()
{
std::string envHome = qi::os::getenv("HOME");
if (envHome != "")
{
return boost::filesystem::path(envHome, qi::unicodeFacet()).make_preferred().string(qi::unicodeFacet());
}
// $HOME environment variable not defined:
char *lgn;
struct passwd *pw;
if ((lgn = getlogin()) == NULL || (pw = getpwnam(lgn)) == NULL)
{
return boost::filesystem::path(pw->pw_dir, qi::unicodeFacet()).make_preferred().string(qi::unicodeFacet());
}
// Give up:
return "";
}
std::string tmpdir(const char *prefix) {
char buffer[L_tmpnam];
memset(buffer, 0, L_tmpnam);
tmpnam(buffer);
boost::filesystem::path path;
if (buffer == NULL)
{
#ifdef __APPLE__
path = boost::filesystem::path(::qi::os::home(),
qi::unicodeFacet()).append("Cache", qi::unicodeFacet());
#else
path = boost::filesystem::path(::qi::os::home(),
qi::unicodeFacet()).append(".cache", qi::unicodeFacet());
#endif
path.append(prefix, qi::unicodeFacet());
// FIXME Add random value for unique dir name.
}
else
{
path = buffer;
std::string filename = prefix;
filename += path.filename().string(qi::unicodeFacet());
path = path.parent_path().append(filename, qi::unicodeFacet());
}
try
{
if (!boost::filesystem::exists(path))
boost::filesystem::create_directories(path);
}
catch (const boost::filesystem::filesystem_error &e)
{
throw qi::os::QiException(e.what());
}
return path.string(qi::unicodeFacet());
}
std::string tmp()
{
std::string temp = ::qi::os::getenv("TMPDIR");
if (temp.empty())
temp = "/tmp/";
boost::filesystem::path p = boost::filesystem::path(temp, qi::unicodeFacet());
return p.string(qi::unicodeFacet());
}
int gettimeofday(qi::os::timeval *tp) {
struct ::timeval tv;
int ret = ::gettimeofday(&tv, 0);
tp->tv_sec = tv.tv_sec;
tp->tv_usec = tv.tv_usec;
return ret;
}
};
};
<|endoftext|> |
<commit_before>/**
* @copyright Copyright 2016 The J-PET Framework Authors. All rights reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may find a copy of the License in the LICENCE file.
*
* 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 JPetScopeTask.cpp
* @brief Module for oscilloscope data
* Reads oscilloscope ASCII files and produces JPetRecoSignal objects.
*/
#include "JPetScopeTask.h"
#include "../JPetParamManager/JPetParamManager.h"
#include <iostream>
#include <string>
#include "JPetScopeTaskUtils.h"
#include <boost/filesystem.hpp>
using namespace boost::filesystem;
JPetScopeTask::JPetScopeTask(const char * name, const char * description):
JPetTask(name, description),
fWriter(0)
{
}
int JPetScopeTask::getTimeWindowIndex(const std::string& pathAndFileName) const
{
int time_window_index = -1;
sscanf(path(pathAndFileName).filename().string().c_str(), "%*3s %d", &time_window_index);
return time_window_index;
}
void JPetScopeTask::exec()
{
assert(fParamManager);
DEBUG("JPetScopeTask - getParamBank() called");
const std::vector<JPetPM*> pms = fParamManager->getParamBank().getPMs();
assert(pms.size() == 4);
for(size_t i = 0u; i < pms.size(); ++i ) {
JPetPM* pm = pms[i];
assert(pm);
if (fInputFiles.find(i) != fInputFiles.end()) {
const auto& files = fInputFiles.find(i)->second;
for (const auto& file: files) {
JPetRecoSignal sig = RecoSignalUtils::generateSignal(file.c_str());
sig.setTimeWindowIndex(getTimeWindowIndex(file));
sig.setPM(*pm);
assert(fWriter);
fWriter->write(sig);
}
} else {
ERROR("Could not find the Input Files for given set");
}
}
}
<commit_msg>Add more protective conditions to JPetScopeTask<commit_after>/**
* @copyright Copyright 2016 The J-PET Framework Authors. All rights reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may find a copy of the License in the LICENCE file.
*
* 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 JPetScopeTask.cpp
* @brief Module for oscilloscope data
* Reads oscilloscope ASCII files and produces JPetRecoSignal objects.
*/
#include "JPetScopeTask.h"
#include "../JPetParamManager/JPetParamManager.h"
#include <iostream>
#include <string>
#include "JPetScopeTaskUtils.h"
#include "../JPetCommonTools/JPetCommonTools.h"
#include <boost/filesystem.hpp>
using namespace boost::filesystem;
JPetScopeTask::JPetScopeTask(const char * name, const char * description):
JPetTask(name, description),
fWriter(0)
{
}
int JPetScopeTask::getTimeWindowIndex(const std::string& pathAndFileName) const
{
DEBUG("JPetScopeTask");
int time_window_index = -1;
if (!boost::filesystem::exists(pathAndFileName)) {
ERROR("File does not exist ");
}
int res = sscanf(JPetCommonTools::extractFileNameFromFullPath(pathAndFileName).c_str(), "%*3s %d", &time_window_index);
if (res <= 0) {
ERROR("scanf failed");
return -1;
} else {
return time_window_index;
}
}
void JPetScopeTask::exec()
{
DEBUG("JPetScopeTask getParamBank() called");
assert(fParamManager);
auto& bank = fParamManager->getParamBank();
if (bank.isDummy()) {
ERROR("bank is Dummy");
} else {
const std::vector<JPetPM*> pms = bank.getPMs();
assert(pms.size() == 4);
for(size_t i = 0u; i < pms.size(); ++i ) {
JPetPM* pm = pms[i];
assert(pm);
if (fInputFiles.find(i) != fInputFiles.end()) {
const auto& files = fInputFiles.find(i)->second;
for (const auto& file: files) {
DEBUG(std::string("file to open:")+file);
JPetRecoSignal sig = RecoSignalUtils::generateSignal(file.c_str());
sig.setTimeWindowIndex(getTimeWindowIndex(file));
DEBUG("before setPM");
sig.setPM(*pm);
DEBUG("after setPM");
assert(fWriter);
fWriter->write(sig);
}
} else {
ERROR("Could not find the Input Files for given set");
}
}
}
}
<|endoftext|> |
<commit_before>
#pragma once
#include <map>
#include <string>
#include <vector>
#include "Werk/Commands/Command.hpp"
#include "Werk/Commands/EchoCommand.hpp"
#include "Werk/Logging/Logger.hpp"
namespace werk
{
class CommandManager
{
public:
CommandManager(Logger *log) : _log(log) {
//Default commands
_commands["echo"] = new EchoCommand(log);
_commands["error"] = new EchoCommand(log, LogLevel::ERROR);
_commands["null"] = new NullCommand();
_commands["warning"] = new EchoCommand(log, LogLevel::WARNING);
}
std::map<std::string, Command *> &commands() { return _commands; }
const std::map<std::string, Command *> &commands() const { return _commands; }
bool execute(const std::string &commandLine);
bool execute(const std::vector<std::string> &arguments);
private:
Logger *_log;
std::map<std::string, Command *> _commands;
};
}
<commit_msg>Make default commands optional<commit_after>
#pragma once
#include <map>
#include <string>
#include <vector>
#include "Werk/Commands/Command.hpp"
#include "Werk/Commands/EchoCommand.hpp"
#include "Werk/Logging/Logger.hpp"
namespace werk
{
class CommandManager
{
public:
CommandManager(Logger *log, bool defaultCommands=true) : _log(log) {
//Default commands
if (defaultCommands) {
_commands["echo"] = new EchoCommand(log);
_commands["error"] = new EchoCommand(log, LogLevel::ERROR);
_commands["null"] = new NullCommand();
_commands["warning"] = new EchoCommand(log, LogLevel::WARNING);
}
}
std::map<std::string, Command *> &commands() { return _commands; }
const std::map<std::string, Command *> &commands() const { return _commands; }
bool execute(const std::string &commandLine);
bool execute(const std::vector<std::string> &arguments);
private:
Logger *_log;
std::map<std::string, Command *> _commands;
};
}
<|endoftext|> |
<commit_before>#include "dsa_common.h"
#include "broker_config.h"
#include <boost/filesystem.hpp>
#include <iostream>
#include "module/logger.h"
namespace fs = boost::filesystem;
namespace dsa {
BrokerConfig::BrokerConfig(int argc, const char* argv[]) {
init();
load();
}
const string_& BrokerConfig::get_file_path() {
static string_ default_path = "broker.json";
if (_file_path.empty()) {
return default_path;
}
return _file_path;
}
// init all the config properties
void BrokerConfig::init() {
add_item("thread", Var(2), VarValidatorInt(1, 100));
add_item("host", Var("0.0.0.0"), [](const Var& var) {
return var.is_string() && !var.get_string().empty();
});
add_item("port", Var(4120), VarValidatorInt(1, 65535));
add_item("secure-port", Var(4128), VarValidatorInt(1, 65535));
add_item("http-port", Var(80), VarValidatorInt(1, 65535));
add_item("https-port", Var(443), VarValidatorInt(1, 65535));
add_item("log-level", Var("warn"), [](const Var& var) {
string_ str = var.to_string();
return str == "trace" || str == "debug" || str == "info" || str == "warn" ||
str == "error" || str == "fatal";
});
}
// load config json from file
void BrokerConfig::load() {
auto& path = get_file_path();
if (fs::exists(path)) {
if (fs::is_regular_file(path)) {
std::ifstream config_file(get_file_path(), std::ios::in);
if (config_file.is_open()) {
std::stringstream buffer;
buffer << config_file.rdbuf();
Var data = Var::from_json(buffer.str());
if (data.is_map()) {
try {
// allows config to be stored in different location
if (_file_path.empty() && data.get_map().count("config-path") > 0 &&
!data["config-path"].to_string().empty()) {
// load broker config from different path
_file_path = data["config-path"].get_string();
load();
return;
}
} catch (std::exception& e) {
// config-path doesn't exist, use default
}
for (auto& it : data.get_map()) {
auto search = _items.find(it.first);
if (search != _items.end()) {
search->second.set_value(std::move(it.second));
}
}
return;
}
}
}
LOG_FATAL(LOG << "failed to open broker config file: " << path);
} else {
// config doesn't exist, write a default config file
save();
}
}
void BrokerConfig::save() {
auto& path = get_file_path();
std::ofstream config_file(path, std::ios::out | std::ios::trunc);
if (config_file.is_open()) {
config_file << "{\n"
<< R"("dsa-version": ")" << int(DSA_MAJOR_VERSION) << "."
<< int(DSA_MINOR_VERSION) << "\",\n";
#ifdef DSA_DEBUG
config_file << R"("broker-build": "debug")";
#else
config_file << R"("broker-build": "release")";
#endif
for (auto& name : _names) {
config_file << ",\n\"" << name << "\": ";
config_file << _items[name].get_value().to_json(2);
}
config_file << "\n}";
} else {
LOG_ERROR(Logger::_(), LOG << "failed to write the broker config file");
}
}
void BrokerConfig::add_item(const string_& name, Var&& value,
VarValidator&& validator) {
_names.emplace_back(name);
_items.emplace(name,
BrokerConfigItem(std::move(value), std::move(validator)));
}
}
<commit_msg>default http port shouldn't be 80 to avoid port in use error in test<commit_after>#include "dsa_common.h"
#include "broker_config.h"
#include <boost/filesystem.hpp>
#include <iostream>
#include "module/logger.h"
namespace fs = boost::filesystem;
namespace dsa {
BrokerConfig::BrokerConfig(int argc, const char* argv[]) {
init();
load();
}
const string_& BrokerConfig::get_file_path() {
static string_ default_path = "broker.json";
if (_file_path.empty()) {
return default_path;
}
return _file_path;
}
// init all the config properties
void BrokerConfig::init() {
add_item("thread", Var(2), VarValidatorInt(1, 100));
add_item("host", Var("0.0.0.0"), [](const Var& var) {
return var.is_string() && !var.get_string().empty();
});
add_item("port", Var(4120), VarValidatorInt(1, 65535));
add_item("secure-port", Var(4128), VarValidatorInt(1, 65535));
add_item("http-port", Var(8080), VarValidatorInt(1, 65535));
add_item("https-port", Var(8443), VarValidatorInt(1, 65535));
add_item("log-level", Var("warn"), [](const Var& var) {
string_ str = var.to_string();
return str == "trace" || str == "debug" || str == "info" || str == "warn" ||
str == "error" || str == "fatal";
});
}
// load config json from file
void BrokerConfig::load() {
auto& path = get_file_path();
if (fs::exists(path)) {
if (fs::is_regular_file(path)) {
std::ifstream config_file(get_file_path(), std::ios::in);
if (config_file.is_open()) {
std::stringstream buffer;
buffer << config_file.rdbuf();
Var data = Var::from_json(buffer.str());
if (data.is_map()) {
try {
// allows config to be stored in different location
if (_file_path.empty() && data.get_map().count("config-path") > 0 &&
!data["config-path"].to_string().empty()) {
// load broker config from different path
_file_path = data["config-path"].get_string();
load();
return;
}
} catch (std::exception& e) {
// config-path doesn't exist, use default
}
for (auto& it : data.get_map()) {
auto search = _items.find(it.first);
if (search != _items.end()) {
search->second.set_value(std::move(it.second));
}
}
return;
}
}
}
LOG_FATAL(LOG << "failed to open broker config file: " << path);
} else {
// config doesn't exist, write a default config file
save();
}
}
void BrokerConfig::save() {
auto& path = get_file_path();
std::ofstream config_file(path, std::ios::out | std::ios::trunc);
if (config_file.is_open()) {
config_file << "{\n"
<< R"("dsa-version": ")" << int(DSA_MAJOR_VERSION) << "."
<< int(DSA_MINOR_VERSION) << "\",\n";
#ifdef DSA_DEBUG
config_file << R"("broker-build": "debug")";
#else
config_file << R"("broker-build": "release")";
#endif
for (auto& name : _names) {
config_file << ",\n\"" << name << "\": ";
config_file << _items[name].get_value().to_json(2);
}
config_file << "\n}";
} else {
LOG_ERROR(Logger::_(), LOG << "failed to write the broker config file");
}
}
void BrokerConfig::add_item(const string_& name, Var&& value,
VarValidator&& validator) {
_names.emplace_back(name);
_items.emplace(name,
BrokerConfigItem(std::move(value), std::move(validator)));
}
}
<|endoftext|> |
<commit_before>/*
* Copyright (c) 2021 Samsung Electronics Co., Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
// CLASS HEADER
#include <dali-toolkit/internal/text/rendering/vector-based/vector-blob-atlas.h>
// EXTERNAL INCLUDES
#include <dali/integration-api/debug.h>
namespace
{
#if defined(DEBUG_ENABLED)
Debug::Filter* gLogFilter = Debug::Filter::New(Debug::Concise, true, "LOG_TEXT_RENDERING");
#endif
} // namespace
namespace Dali
{
namespace Toolkit
{
namespace Text
{
static void
EncodeBlobCoordinate(unsigned int cornerX, unsigned int cornerY, unsigned int atlasX, unsigned int atlasY, unsigned int nominalWidth, unsigned int nominalHeight, BlobCoordinate* v)
{
DALI_ASSERT_DEBUG(0 == (atlasX & ~0x7F));
DALI_ASSERT_DEBUG(0 == (atlasY & ~0x7F));
DALI_ASSERT_DEBUG(0 == (cornerX & ~1));
DALI_ASSERT_DEBUG(0 == (cornerY & ~1));
DALI_ASSERT_DEBUG(0 == (nominalWidth & ~0x3F));
DALI_ASSERT_DEBUG(0 == (nominalHeight & ~0x3F));
unsigned int x = (((atlasX << 6) | nominalWidth) << 1) | cornerX;
unsigned int y = (((atlasY << 6) | nominalHeight) << 1) | cornerY;
unsigned int encoded = (x << 16) | y;
v->u = encoded >> 16;
v->v = encoded & 0xFFFF;
}
VectorBlobAtlas::VectorBlobAtlas(unsigned int textureWidth,
unsigned int textureHeight,
unsigned int itemWidth,
unsigned int itemHeightQuantum)
: mTextureWidth(textureWidth),
mTextureHeight(textureHeight),
mItemWidth(itemWidth),
mItemHeightQuantum(itemHeightQuantum),
mCursorX(0),
mCursorY(0),
mIsFull(false)
{
DALI_LOG_INFO(gLogFilter, Debug::General, "Blob atlas %p size %dx%d, item width %d, height quantum %d\n", this, textureWidth, textureHeight, itemWidth, itemHeightQuantum);
mAtlasTexture = Texture::New(TextureType::TEXTURE_2D, Pixel::RGBA8888, textureWidth, textureHeight);
mTextureSet = TextureSet::New();
mTextureSet.SetTexture(0, mAtlasTexture);
}
bool VectorBlobAtlas::IsFull() const
{
return mIsFull;
}
bool VectorBlobAtlas::FindGlyph(FontId fontId,
GlyphIndex glyphIndex,
BlobCoordinate* coords)
{
const unsigned int size(mItemLookup.size());
for(unsigned int i = 0; i < size; ++i)
{
if(mItemLookup[i].fontId == fontId &&
mItemLookup[i].glyphIndex == glyphIndex)
{
const Item& item = mItemCache[mItemLookup[i].cacheIndex];
coords[0] = item.coords[0];
coords[1] = item.coords[1];
coords[2] = item.coords[2];
coords[3] = item.coords[3];
return true;
}
}
return false;
}
bool VectorBlobAtlas::AddGlyph(unsigned int fontId,
unsigned int glyphIndex,
VectorBlob* blob,
unsigned int length,
unsigned int nominalWidth,
unsigned int nominalHeight,
BlobCoordinate* coords)
{
if(mIsFull)
{
return false;
}
unsigned int w, h, x, y;
w = mItemWidth;
h = (length + w - 1) / w;
if(mCursorY + h > mTextureHeight)
{
// Go to next column
mCursorX += mItemWidth;
mCursorY = 0;
}
if(mCursorX + w <= mTextureWidth && mCursorY + h <= mTextureHeight)
{
x = mCursorX;
y = mCursorY;
mCursorY += (h + mItemHeightQuantum - 1) & ~(mItemHeightQuantum - 1);
}
else
{
DALI_LOG_INFO(gLogFilter, Debug::General, "Blob atlas %p is now FULL\n", this);
// The atlas is now considered to be full
mIsFull = true;
return false;
}
if(w * h == length)
{
TexSubImage(x, y, w, h, blob);
}
else
{
TexSubImage(x, y, w, h - 1, blob);
// Upload the last row separately
TexSubImage(x, y + h - 1, length - (w * (h - 1)), 1, blob + w * (h - 1));
}
DALI_LOG_INFO(gLogFilter, Debug::General, "Blob atlas %p capacity %d filled %d %f\%\n", this, mTextureWidth * mTextureHeight, mCursorY * mItemWidth + mCursorX * mTextureHeight, 100.0f * (float)(mCursorY * mItemWidth + mCursorX * mTextureHeight) / (float)(mTextureWidth * mTextureHeight));
Key key;
key.fontId = fontId;
key.glyphIndex = glyphIndex;
key.cacheIndex = mItemCache.size();
mItemLookup.push_back(key);
x /= mItemWidth;
y /= mItemHeightQuantum;
Item item;
EncodeBlobCoordinate(0, 0, x, y, nominalWidth, nominalHeight, &item.coords[0]); // BOTTOM_LEFT
EncodeBlobCoordinate(0, 1, x, y, nominalWidth, nominalHeight, &item.coords[1]); // TOP_LEFT
EncodeBlobCoordinate(1, 0, x, y, nominalWidth, nominalHeight, &item.coords[2]); // BOTTOM_RIGHT
EncodeBlobCoordinate(1, 1, x, y, nominalWidth, nominalHeight, &item.coords[3]); // TOP_RIGHT
mItemCache.push_back(item);
coords[0] = item.coords[0];
coords[1] = item.coords[1];
coords[2] = item.coords[2];
coords[3] = item.coords[3];
return true;
}
void VectorBlobAtlas::TexSubImage(unsigned int offsetX,
unsigned int offsetY,
unsigned int width,
unsigned int height,
VectorBlob* blob)
{
const size_t size = width * height * 4;
uint8_t* pixbuf = new uint8_t[size];
size_t pos;
size_t dataIndex = 0;
for(size_t y = 0; y < height; y++)
{
pos = y * mTextureWidth * 4;
for(size_t x = 0; x < width; x++)
{
pixbuf[pos + x * 4] = 0xFF & blob[dataIndex].r;
pixbuf[pos + x * 4 + 1] = 0xFF & blob[dataIndex].g;
pixbuf[pos + x * 4 + 2] = 0xFF & blob[dataIndex].b;
pixbuf[pos + x * 4 + 3] = 0xFF & blob[dataIndex].a;
dataIndex++;
}
}
PixelData pixelData = PixelData::New(pixbuf, size, width, height, Pixel::RGBA8888, PixelData::DELETE_ARRAY);
mAtlasTexture.Upload(pixelData, 0u, 0u, offsetX, offsetY, width, height);
}
} // namespace Text
} // namespace Toolkit
} // namespace Dali
<commit_msg>Fixed memory scribbler in text vector blob<commit_after>/*
* Copyright (c) 2021 Samsung Electronics Co., Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
// CLASS HEADER
#include <dali-toolkit/internal/text/rendering/vector-based/vector-blob-atlas.h>
// EXTERNAL INCLUDES
#include <dali/integration-api/debug.h>
namespace
{
#if defined(DEBUG_ENABLED)
Debug::Filter* gLogFilter = Debug::Filter::New(Debug::Concise, true, "LOG_TEXT_RENDERING");
#endif
} // namespace
namespace Dali
{
namespace Toolkit
{
namespace Text
{
static void
EncodeBlobCoordinate(unsigned int cornerX, unsigned int cornerY, unsigned int atlasX, unsigned int atlasY, unsigned int nominalWidth, unsigned int nominalHeight, BlobCoordinate* v)
{
DALI_ASSERT_DEBUG(0 == (atlasX & ~0x7F));
DALI_ASSERT_DEBUG(0 == (atlasY & ~0x7F));
DALI_ASSERT_DEBUG(0 == (cornerX & ~1));
DALI_ASSERT_DEBUG(0 == (cornerY & ~1));
DALI_ASSERT_DEBUG(0 == (nominalWidth & ~0x3F));
DALI_ASSERT_DEBUG(0 == (nominalHeight & ~0x3F));
unsigned int x = (((atlasX << 6) | nominalWidth) << 1) | cornerX;
unsigned int y = (((atlasY << 6) | nominalHeight) << 1) | cornerY;
unsigned int encoded = (x << 16) | y;
v->u = encoded >> 16;
v->v = encoded & 0xFFFF;
}
VectorBlobAtlas::VectorBlobAtlas(unsigned int textureWidth,
unsigned int textureHeight,
unsigned int itemWidth,
unsigned int itemHeightQuantum)
: mTextureWidth(textureWidth),
mTextureHeight(textureHeight),
mItemWidth(itemWidth),
mItemHeightQuantum(itemHeightQuantum),
mCursorX(0),
mCursorY(0),
mIsFull(false)
{
DALI_LOG_INFO(gLogFilter, Debug::General, "Blob atlas %p size %dx%d, item width %d, height quantum %d\n", this, textureWidth, textureHeight, itemWidth, itemHeightQuantum);
mAtlasTexture = Texture::New(TextureType::TEXTURE_2D, Pixel::RGBA8888, textureWidth, textureHeight);
mTextureSet = TextureSet::New();
mTextureSet.SetTexture(0, mAtlasTexture);
}
bool VectorBlobAtlas::IsFull() const
{
return mIsFull;
}
bool VectorBlobAtlas::FindGlyph(FontId fontId,
GlyphIndex glyphIndex,
BlobCoordinate* coords)
{
const unsigned int size(mItemLookup.size());
for(unsigned int i = 0; i < size; ++i)
{
if(mItemLookup[i].fontId == fontId &&
mItemLookup[i].glyphIndex == glyphIndex)
{
const Item& item = mItemCache[mItemLookup[i].cacheIndex];
coords[0] = item.coords[0];
coords[1] = item.coords[1];
coords[2] = item.coords[2];
coords[3] = item.coords[3];
return true;
}
}
return false;
}
bool VectorBlobAtlas::AddGlyph(unsigned int fontId,
unsigned int glyphIndex,
VectorBlob* blob,
unsigned int length,
unsigned int nominalWidth,
unsigned int nominalHeight,
BlobCoordinate* coords)
{
if(mIsFull)
{
return false;
}
unsigned int w, h, x, y;
w = mItemWidth;
h = (length + w - 1) / w;
if(mCursorY + h > mTextureHeight)
{
// Go to next column
mCursorX += mItemWidth;
mCursorY = 0;
}
if(mCursorX + w <= mTextureWidth && mCursorY + h <= mTextureHeight)
{
x = mCursorX;
y = mCursorY;
mCursorY += (h + mItemHeightQuantum - 1) & ~(mItemHeightQuantum - 1);
}
else
{
DALI_LOG_INFO(gLogFilter, Debug::General, "Blob atlas %p is now FULL\n", this);
// The atlas is now considered to be full
mIsFull = true;
return false;
}
if(w * h == length)
{
TexSubImage(x, y, w, h, blob);
}
else
{
TexSubImage(x, y, w, h - 1, blob);
// Upload the last row separately
TexSubImage(x, y + h - 1, length - (w * (h - 1)), 1, blob + w * (h - 1));
}
DALI_LOG_INFO(gLogFilter, Debug::General, "Blob atlas %p capacity %d filled %d %f\%\n", this, mTextureWidth * mTextureHeight, mCursorY * mItemWidth + mCursorX * mTextureHeight, 100.0f * (float)(mCursorY * mItemWidth + mCursorX * mTextureHeight) / (float)(mTextureWidth * mTextureHeight));
Key key;
key.fontId = fontId;
key.glyphIndex = glyphIndex;
key.cacheIndex = mItemCache.size();
mItemLookup.push_back(key);
x /= mItemWidth;
y /= mItemHeightQuantum;
Item item;
EncodeBlobCoordinate(0, 0, x, y, nominalWidth, nominalHeight, &item.coords[0]); // BOTTOM_LEFT
EncodeBlobCoordinate(0, 1, x, y, nominalWidth, nominalHeight, &item.coords[1]); // TOP_LEFT
EncodeBlobCoordinate(1, 0, x, y, nominalWidth, nominalHeight, &item.coords[2]); // BOTTOM_RIGHT
EncodeBlobCoordinate(1, 1, x, y, nominalWidth, nominalHeight, &item.coords[3]); // TOP_RIGHT
mItemCache.push_back(item);
coords[0] = item.coords[0];
coords[1] = item.coords[1];
coords[2] = item.coords[2];
coords[3] = item.coords[3];
return true;
}
void VectorBlobAtlas::TexSubImage(unsigned int offsetX,
unsigned int offsetY,
unsigned int width,
unsigned int height,
VectorBlob* blob)
{
const size_t size = width * height * 4;
uint8_t* pixbuf = new uint8_t[size];
size_t pos;
size_t dataIndex = 0;
for(size_t y = 0; y < height; y++)
{
pos = y * width * 4;
for(size_t x = 0; x < width; x++)
{
pixbuf[pos + x * 4] = 0xFF & blob[dataIndex].r;
pixbuf[pos + x * 4 + 1] = 0xFF & blob[dataIndex].g;
pixbuf[pos + x * 4 + 2] = 0xFF & blob[dataIndex].b;
pixbuf[pos + x * 4 + 3] = 0xFF & blob[dataIndex].a;
dataIndex++;
}
}
PixelData pixelData = PixelData::New(pixbuf, size, width, height, Pixel::RGBA8888, PixelData::DELETE_ARRAY);
mAtlasTexture.Upload(pixelData, 0u, 0u, offsetX, offsetY, width, height);
}
} // namespace Text
} // namespace Toolkit
} // namespace Dali
<|endoftext|> |
<commit_before>// Copyright (c) 2009 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
//
// This test performs a series false positive checks using a list of URLs
// against a known set of SafeBrowsing data.
//
// It uses a normal SafeBrowsing database to create a bloom filter where it
// looks up all the URLs in the url file. A URL that has a prefix found in the
// bloom filter and found in the database is considered a hit: a valid lookup
// that will result in a gethash request. A URL that has a prefix found in the
// bloom filter but not in the database is a miss: a false positive lookup that
// will result in an unnecessary gethash request.
//
// By varying the size of the bloom filter and using a constant set of
// SafeBrowsing data, we can check a known set of URLs against the filter and
// determine the false positive rate.
//
// Usage:
// $ ./perf_tests.exe --gtest_filter=SafeBrowsingBloomFilter.FalsePositives
// --filter-start=<integer>
// --filter-steps=<integer>
// --filter-verbose
//
// --filter-start: The filter multiplier to begin with. This represents the
// number of bits per prefix of memory to use in the filter.
// The default value is identical to the current SafeBrowsing
// database value.
// --filter-steps: The number of iterations to run, with each iteration
// increasing the filter multiplier by 1. The default value
// is 1.
// --filter-verbose: Used to print out the hit / miss results per URL.
// --filter-csv: The URL file contains information about the number of
// unique views (the popularity) of each URL. See the format
// description below.
//
// Data files:
// chrome/test/data/safe_browsing/filter/database
// chrome/test/data/safe_browsing/filter/urls
//
// database: A normal SafeBrowsing database.
// urls: A text file containing a list of URLs, one per line. If the option
// --filter-csv is specified, the format of each line in the file is
// <url>,<weight> where weight is an integer indicating the number of
// unique views for the URL.
#include <fstream>
#include <iostream>
#include <vector>
#include "base/command_line.h"
#include "base/file_path.h"
#include "base/file_util.h"
#include "base/logging.h"
#include "base/path_service.h"
#include "base/scoped_ptr.h"
#include "base/sha2.h"
#include "base/string_util.h"
#include "chrome/browser/safe_browsing/bloom_filter.h"
#include "chrome/browser/safe_browsing/safe_browsing_util.h"
#include "chrome/common/chrome_paths.h"
#include "chrome/common/sqlite_compiled_statement.h"
#include "chrome/common/sqlite_utils.h"
#include "googleurl/src/gurl.h"
#include "testing/gtest/include/gtest/gtest.h"
namespace {
// Ensures the SafeBrowsing database is closed properly.
class ScopedPerfDatabase {
public:
explicit ScopedPerfDatabase(sqlite3* db) : db_(db) {}
~ScopedPerfDatabase() {
sqlite3_close(db_);
}
private:
sqlite3* db_;
DISALLOW_COPY_AND_ASSIGN(ScopedPerfDatabase);
};
// Command line flags.
const wchar_t kFilterVerbose[] = L"filter-verbose";
const wchar_t kFilterStart[] = L"filter-start";
const wchar_t kFilterSteps[] = L"filter-steps";
const wchar_t kFilterCsv[] = L"filter-csv";
// Returns the path to the data used in this test, relative to the top of the
// source directory.
FilePath GetFullDataPath() {
FilePath full_path;
CHECK(PathService::Get(chrome::DIR_TEST_DATA, &full_path));
full_path = full_path.Append(FILE_PATH_LITERAL("safe_browsing"));
full_path = full_path.Append(FILE_PATH_LITERAL("filter"));
CHECK(file_util::PathExists(full_path));
return full_path;
}
// Constructs a bloom filter of the appropriate size from the provided prefixes.
void BuildBloomFilter(int size_multiplier,
const std::vector<SBPrefix>& prefixes,
BloomFilter** bloom_filter) {
// Create a BloomFilter with the specified size.
const int key_count = std::max(static_cast<int>(prefixes.size()), 250000);
const int filter_size = key_count * size_multiplier;
*bloom_filter = new BloomFilter(filter_size);
// Add the prefixes to it.
for (size_t i = 0; i < prefixes.size(); ++i)
(*bloom_filter)->Insert(prefixes[i]);
std::cout << "Bloom filter with prefixes: " << prefixes.size()
<< ", multiplier: " << size_multiplier
<< ", size (bytes): " << (*bloom_filter)->size()
<< std::endl;
}
// Reads the set of add prefixes contained in a SafeBrowsing database into a
// sorted array suitable for fast searching. This takes significantly less time
// to look up a given prefix than performing SQL queries.
bool ReadDatabase(const FilePath& path, std::vector<SBPrefix>* prefixes) {
FilePath database_file = path.Append(FILE_PATH_LITERAL("database"));
sqlite3* db = NULL;
if (OpenSqliteDb(database_file, &db) != SQLITE_OK) {
sqlite3_close(db);
return false;
}
ScopedPerfDatabase database(db);
scoped_ptr<SqliteStatementCache> sql_cache(new SqliteStatementCache(db));
// Get the number of items in the add_prefix table.
std::string sql = "SELECT COUNT(*) FROM add_prefix";
SQLITE_UNIQUE_STATEMENT(count_statement, *sql_cache, sql.c_str());
if (!count_statement.is_valid())
return false;
if (count_statement->step() != SQLITE_ROW)
return false;
const int count = count_statement->column_int(0);
// Load them into a prefix vector and sort
prefixes->reserve(count);
sql = "SELECT prefix FROM add_prefix";
SQLITE_UNIQUE_STATEMENT(prefix_statement, *sql_cache, sql.c_str());
if (!prefix_statement.is_valid())
return false;
while (prefix_statement->step() == SQLITE_ROW)
prefixes->push_back(prefix_statement->column_int(0));
DCHECK(static_cast<int>(prefixes->size()) == count);
sort(prefixes->begin(), prefixes->end());
return true;
}
// Generates all legal SafeBrowsing prefixes for the specified URL, and returns
// the set of Prefixes that exist in the bloom filter. The function returns the
// number of host + path combinations checked.
int GeneratePrefixHits(const std::string url,
BloomFilter* bloom_filter,
std::vector<SBPrefix>* prefixes) {
GURL url_check(url);
std::vector<std::string> hosts;
if (url_check.HostIsIPAddress()) {
hosts.push_back(url_check.host());
} else {
safe_browsing_util::GenerateHostsToCheck(url_check, &hosts);
}
std::vector<std::string> paths;
safe_browsing_util::GeneratePathsToCheck(url_check, &paths);
for (size_t i = 0; i < hosts.size(); ++i) {
for (size_t j = 0; j < paths.size(); ++j) {
SBPrefix prefix;
base::SHA256HashString(hosts[i] + paths[j], &prefix, sizeof(prefix));
if (bloom_filter->Exists(prefix))
prefixes->push_back(prefix);
}
}
return hosts.size() * paths.size();
}
// Binary search of sorted prefixes.
bool IsPrefixInDatabase(SBPrefix prefix,
const std::vector<SBPrefix>& prefixes) {
if (prefixes.empty())
return false;
int low = 0;
int high = prefixes.size() - 1;
while (low <= high) {
int mid = ((unsigned int)low + (unsigned int)high) >> 1;
SBPrefix prefix_mid = prefixes[mid];
if (prefix_mid == prefix)
return true;
if (prefix_mid < prefix)
low = mid + 1;
else
high = mid - 1;
}
return false;
}
// Construct a bloom filter with the given prefixes and multiplier, and test the
// false positive rate (misses) against a URL list.
void CalculateBloomFilterFalsePositives(
int size_multiplier,
const FilePath& data_dir,
const std::vector<SBPrefix>& prefix_list) {
BloomFilter* bloom_filter = NULL;
BuildBloomFilter(size_multiplier, prefix_list, &bloom_filter);
scoped_refptr<BloomFilter> scoped_filter(bloom_filter);
// Read in data file line at a time.
FilePath url_file = data_dir.Append(FILE_PATH_LITERAL("urls"));
std::ifstream url_stream(WideToASCII(url_file.ToWStringHack()).c_str());
// Keep track of stats
int hits = 0;
int misses = 0;
int weighted_hits = 0;
int weighted_misses = 0;
int url_count = 0;
int prefix_count = 0;
// Print out volumes of data (per URL hit and miss information).
bool verbose = CommandLine::ForCurrentProcess()->HasSwitch(kFilterVerbose);
bool use_weights = CommandLine::ForCurrentProcess()->HasSwitch(kFilterCsv);
std::string url;
while (std::getline(url_stream, url)) {
++url_count;
// Handle a format that contains URLs weighted by unique views.
int weight = 1;
if (use_weights) {
std::string::size_type pos = url.find_last_of(",");
if (pos != std::string::npos) {
weight = StringToInt(std::string(url, pos + 1));
url = url.substr(0, pos);
}
}
// See if the URL is in the bloom filter.
std::vector<SBPrefix> prefixes;
prefix_count += GeneratePrefixHits(url, bloom_filter, &prefixes);
// See if the prefix is actually in the database (in-memory prefix list).
for (size_t i = 0; i < prefixes.size(); ++i) {
if (IsPrefixInDatabase(prefixes[i], prefix_list)) {
++hits;
weighted_hits += weight;
if (verbose) {
std::cout << "Hit for URL: " << url
<< " (prefix = " << prefixes[i] << ")"
<< std::endl;
}
} else {
++misses;
weighted_misses += weight;
if (verbose) {
std::cout << "Miss for URL: " << url
<< " (prefix = " << prefixes[i] << ")"
<< std::endl;
}
}
}
}
// Print out the results for this test.
std::cout << "URLs checked: " << url_count
<< ", prefix compares: " << prefix_count
<< ", hits: " << hits
<< ", misses: " << misses;
if (use_weights) {
std::cout << ", weighted hits: " << weighted_hits
<< ", weighted misses: " << weighted_misses;
}
std::cout << std::endl;
}
} // namespace
// This test can take several minutes to perform its calculations, so it should
// be disabled until you need to run it.
TEST(SafeBrowsingBloomFilter, FalsePositives) {
std::vector<SBPrefix> prefix_list;
FilePath data_dir = GetFullDataPath();
if (!ReadDatabase(data_dir, &prefix_list))
return;
int start = BloomFilter::kBloomFilterSizeRatio;
if (CommandLine::ForCurrentProcess()->HasSwitch(kFilterStart)) {
start = StringToInt(
CommandLine::ForCurrentProcess()->GetSwitchValue(kFilterStart));
}
int steps = 1;
if (CommandLine::ForCurrentProcess()->HasSwitch(kFilterSteps)) {
steps = StringToInt(
CommandLine::ForCurrentProcess()->GetSwitchValue(kFilterSteps));
}
int stop = start + steps;
for (int multiplier = start; multiplier < stop; ++multiplier)
CalculateBloomFilterFalsePositives(multiplier, data_dir, prefix_list);
}
<commit_msg>Add a performance test for measuring hash implementation time.<commit_after>// Copyright (c) 2009 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
//
// This test performs a series false positive checks using a list of URLs
// against a known set of SafeBrowsing data.
//
// It uses a normal SafeBrowsing database to create a bloom filter where it
// looks up all the URLs in the url file. A URL that has a prefix found in the
// bloom filter and found in the database is considered a hit: a valid lookup
// that will result in a gethash request. A URL that has a prefix found in the
// bloom filter but not in the database is a miss: a false positive lookup that
// will result in an unnecessary gethash request.
//
// By varying the size of the bloom filter and using a constant set of
// SafeBrowsing data, we can check a known set of URLs against the filter and
// determine the false positive rate.
//
// False positive calculation usage:
// $ ./perf_tests.exe --gtest_filter=SafeBrowsingBloomFilter.FalsePositives
// --filter-start=<integer>
// --filter-steps=<integer>
// --filter-verbose
//
// --filter-start: The filter multiplier to begin with. This represents the
// number of bits per prefix of memory to use in the filter.
// The default value is identical to the current SafeBrowsing
// database value.
// --filter-steps: The number of iterations to run, with each iteration
// increasing the filter multiplier by 1. The default value
// is 1.
// --filter-verbose: Used to print out the hit / miss results per URL.
// --filter-csv: The URL file contains information about the number of
// unique views (the popularity) of each URL. See the format
// description below.
//
//
// Hash compute time usage:
// $ ./perf_tests.exe --gtest_filter=SafeBrowsingBloomFilter.HashTime
// --filter-num-checks=<integer>
//
// --filter-num-checks: The number of hash look ups to perform on the bloom
// filter. The default is 10 million.
//
// Data files:
// chrome/test/data/safe_browsing/filter/database
// chrome/test/data/safe_browsing/filter/urls
//
// database: A normal SafeBrowsing database.
// urls: A text file containing a list of URLs, one per line. If the option
// --filter-csv is specified, the format of each line in the file is
// <url>,<weight> where weight is an integer indicating the number of
// unique views for the URL.
#include <fstream>
#include <iostream>
#include <vector>
#include "base/command_line.h"
#include "base/file_path.h"
#include "base/file_util.h"
#include "base/logging.h"
#include "base/path_service.h"
#include "base/rand_util.h"
#include "base/scoped_ptr.h"
#include "base/sha2.h"
#include "base/string_util.h"
#include "base/time.h"
#include "chrome/browser/safe_browsing/bloom_filter.h"
#include "chrome/browser/safe_browsing/safe_browsing_util.h"
#include "chrome/common/chrome_paths.h"
#include "chrome/common/sqlite_compiled_statement.h"
#include "chrome/common/sqlite_utils.h"
#include "googleurl/src/gurl.h"
#include "testing/gtest/include/gtest/gtest.h"
using base::Time;
using base::TimeDelta;
namespace {
// Ensures the SafeBrowsing database is closed properly.
class ScopedPerfDatabase {
public:
explicit ScopedPerfDatabase(sqlite3* db) : db_(db) {}
~ScopedPerfDatabase() {
sqlite3_close(db_);
}
private:
sqlite3* db_;
DISALLOW_COPY_AND_ASSIGN(ScopedPerfDatabase);
};
// Command line flags.
const wchar_t kFilterVerbose[] = L"filter-verbose";
const wchar_t kFilterStart[] = L"filter-start";
const wchar_t kFilterSteps[] = L"filter-steps";
const wchar_t kFilterCsv[] = L"filter-csv";
const wchar_t kFilterNumChecks[] = L"filter-num-checks";
// Number of hash checks to make during performance testing.
static const int kNumHashChecks = 10000000;
// Returns the path to the data used in this test, relative to the top of the
// source directory.
FilePath GetFullDataPath() {
FilePath full_path;
CHECK(PathService::Get(chrome::DIR_TEST_DATA, &full_path));
full_path = full_path.Append(FILE_PATH_LITERAL("safe_browsing"));
full_path = full_path.Append(FILE_PATH_LITERAL("filter"));
CHECK(file_util::PathExists(full_path));
return full_path;
}
// Constructs a bloom filter of the appropriate size from the provided prefixes.
void BuildBloomFilter(int size_multiplier,
const std::vector<SBPrefix>& prefixes,
BloomFilter** bloom_filter) {
// Create a BloomFilter with the specified size.
const int key_count = std::max(static_cast<int>(prefixes.size()),
BloomFilter::kBloomFilterMinSize);
const int filter_size = key_count * size_multiplier;
*bloom_filter = new BloomFilter(filter_size);
// Add the prefixes to it.
for (size_t i = 0; i < prefixes.size(); ++i)
(*bloom_filter)->Insert(prefixes[i]);
std::cout << "Bloom filter with prefixes: " << prefixes.size()
<< ", multiplier: " << size_multiplier
<< ", size (bytes): " << (*bloom_filter)->size()
<< std::endl;
}
// Reads the set of add prefixes contained in a SafeBrowsing database into a
// sorted array suitable for fast searching. This takes significantly less time
// to look up a given prefix than performing SQL queries.
bool ReadDatabase(const FilePath& path, std::vector<SBPrefix>* prefixes) {
FilePath database_file = path.Append(FILE_PATH_LITERAL("database"));
sqlite3* db = NULL;
if (OpenSqliteDb(database_file, &db) != SQLITE_OK) {
sqlite3_close(db);
return false;
}
ScopedPerfDatabase database(db);
scoped_ptr<SqliteStatementCache> sql_cache(new SqliteStatementCache(db));
// Get the number of items in the add_prefix table.
std::string sql = "SELECT COUNT(*) FROM add_prefix";
SQLITE_UNIQUE_STATEMENT(count_statement, *sql_cache, sql.c_str());
if (!count_statement.is_valid())
return false;
if (count_statement->step() != SQLITE_ROW)
return false;
const int count = count_statement->column_int(0);
// Load them into a prefix vector and sort
prefixes->reserve(count);
sql = "SELECT prefix FROM add_prefix";
SQLITE_UNIQUE_STATEMENT(prefix_statement, *sql_cache, sql.c_str());
if (!prefix_statement.is_valid())
return false;
while (prefix_statement->step() == SQLITE_ROW)
prefixes->push_back(prefix_statement->column_int(0));
DCHECK(static_cast<int>(prefixes->size()) == count);
sort(prefixes->begin(), prefixes->end());
return true;
}
// Generates all legal SafeBrowsing prefixes for the specified URL, and returns
// the set of Prefixes that exist in the bloom filter. The function returns the
// number of host + path combinations checked.
int GeneratePrefixHits(const std::string url,
BloomFilter* bloom_filter,
std::vector<SBPrefix>* prefixes) {
GURL url_check(url);
std::vector<std::string> hosts;
if (url_check.HostIsIPAddress()) {
hosts.push_back(url_check.host());
} else {
safe_browsing_util::GenerateHostsToCheck(url_check, &hosts);
}
std::vector<std::string> paths;
safe_browsing_util::GeneratePathsToCheck(url_check, &paths);
for (size_t i = 0; i < hosts.size(); ++i) {
for (size_t j = 0; j < paths.size(); ++j) {
SBPrefix prefix;
base::SHA256HashString(hosts[i] + paths[j], &prefix, sizeof(prefix));
if (bloom_filter->Exists(prefix))
prefixes->push_back(prefix);
}
}
return hosts.size() * paths.size();
}
// Binary search of sorted prefixes.
bool IsPrefixInDatabase(SBPrefix prefix,
const std::vector<SBPrefix>& prefixes) {
if (prefixes.empty())
return false;
int low = 0;
int high = prefixes.size() - 1;
while (low <= high) {
int mid = ((unsigned int)low + (unsigned int)high) >> 1;
SBPrefix prefix_mid = prefixes[mid];
if (prefix_mid == prefix)
return true;
if (prefix_mid < prefix)
low = mid + 1;
else
high = mid - 1;
}
return false;
}
// Construct a bloom filter with the given prefixes and multiplier, and test the
// false positive rate (misses) against a URL list.
void CalculateBloomFilterFalsePositives(
int size_multiplier,
const FilePath& data_dir,
const std::vector<SBPrefix>& prefix_list) {
BloomFilter* bloom_filter = NULL;
BuildBloomFilter(size_multiplier, prefix_list, &bloom_filter);
scoped_refptr<BloomFilter> scoped_filter(bloom_filter);
// Read in data file line at a time.
FilePath url_file = data_dir.Append(FILE_PATH_LITERAL("urls"));
std::ifstream url_stream(WideToASCII(url_file.ToWStringHack()).c_str());
// Keep track of stats
int hits = 0;
int misses = 0;
int weighted_hits = 0;
int weighted_misses = 0;
int url_count = 0;
int prefix_count = 0;
// Print out volumes of data (per URL hit and miss information).
bool verbose = CommandLine::ForCurrentProcess()->HasSwitch(kFilterVerbose);
bool use_weights = CommandLine::ForCurrentProcess()->HasSwitch(kFilterCsv);
std::string url;
while (std::getline(url_stream, url)) {
++url_count;
// Handle a format that contains URLs weighted by unique views.
int weight = 1;
if (use_weights) {
std::string::size_type pos = url.find_last_of(",");
if (pos != std::string::npos) {
weight = StringToInt(std::string(url, pos + 1));
url = url.substr(0, pos);
}
}
// See if the URL is in the bloom filter.
std::vector<SBPrefix> prefixes;
prefix_count += GeneratePrefixHits(url, bloom_filter, &prefixes);
// See if the prefix is actually in the database (in-memory prefix list).
for (size_t i = 0; i < prefixes.size(); ++i) {
if (IsPrefixInDatabase(prefixes[i], prefix_list)) {
++hits;
weighted_hits += weight;
if (verbose) {
std::cout << "Hit for URL: " << url
<< " (prefix = " << prefixes[i] << ")"
<< std::endl;
}
} else {
++misses;
weighted_misses += weight;
if (verbose) {
std::cout << "Miss for URL: " << url
<< " (prefix = " << prefixes[i] << ")"
<< std::endl;
}
}
}
}
// Print out the results for this test.
std::cout << "URLs checked: " << url_count
<< ", prefix compares: " << prefix_count
<< ", hits: " << hits
<< ", misses: " << misses;
if (use_weights) {
std::cout << ", weighted hits: " << weighted_hits
<< ", weighted misses: " << weighted_misses;
}
std::cout << std::endl;
}
} // namespace
// This test can take several minutes to perform its calculations, so it should
// be disabled until you need to run it.
TEST(SafeBrowsingBloomFilter, FalsePositives) {
std::vector<SBPrefix> prefix_list;
FilePath data_dir = GetFullDataPath();
ASSERT_TRUE(ReadDatabase(data_dir, &prefix_list));
int start = BloomFilter::kBloomFilterSizeRatio;
if (CommandLine::ForCurrentProcess()->HasSwitch(kFilterStart)) {
start = StringToInt(
CommandLine::ForCurrentProcess()->GetSwitchValue(kFilterStart));
}
int steps = 1;
if (CommandLine::ForCurrentProcess()->HasSwitch(kFilterSteps)) {
steps = StringToInt(
CommandLine::ForCurrentProcess()->GetSwitchValue(kFilterSteps));
}
int stop = start + steps;
for (int multiplier = start; multiplier < stop; ++multiplier)
CalculateBloomFilterFalsePositives(multiplier, data_dir, prefix_list);
}
// Computes the time required for performing a number of look ups in a bloom
// filter. This is useful for measuring the performance of new hash functions.
TEST(SafeBrowsingBloomFilter, HashTime) {
// Read the data from the database.
std::vector<SBPrefix> prefix_list;
FilePath data_dir = GetFullDataPath();
ASSERT_TRUE(ReadDatabase(data_dir, &prefix_list));
int num_checks = kNumHashChecks;
if (CommandLine::ForCurrentProcess()->HasSwitch(kFilterNumChecks)) {
num_checks = StringToInt(
CommandLine::ForCurrentProcess()->GetSwitchValue(kFilterNumChecks));
}
// Populate the bloom filter and measure the time.
BloomFilter* bloom_filter = NULL;
Time populate_before = Time::Now();
BuildBloomFilter(BloomFilter::kBloomFilterSizeRatio,
prefix_list, &bloom_filter);
TimeDelta populate = Time::Now() - populate_before;
// Check a large number of random prefixes against the filter.
int hits = 0;
Time check_before = Time::Now();
for (int i = 0; i < num_checks; ++i) {
uint32 prefix = static_cast<uint32>(base::RandUint64());
if (bloom_filter->Exists(prefix))
++hits;
}
TimeDelta check = Time::Now() - check_before;
int64 time_per_insert = populate.InMicroseconds() /
static_cast<int>(prefix_list.size());
int64 time_per_check = check.InMicroseconds() / num_checks;
std::cout << "Time results for checks: " << num_checks
<< ", prefixes: " << prefix_list.size()
<< ", populate time (ms): " << populate.InMilliseconds()
<< ", check time (ms): " << check.InMilliseconds()
<< ", hits: " << hits
<< ", per-populate (us): " << time_per_insert
<< ", per-check (us): " << time_per_check
<< std::endl;
}
<|endoftext|> |
<commit_before>/*
Copyright 2002-2013 CEA LIST
This file is part of LIMA.
LIMA 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.
LIMA 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 LIMA. If not, see <http://www.gnu.org/licenses/>
*/
/***************************************************************************
* Copyright (C) 2004-2012 by CEA LIST *
* *
***************************************************************************/
#include "MorphoSyntacticData.h"
#include "MorphoSyntacticDataUtils.h"
#include "common/MediaticData/mediaticData.h"
#include "common/Data/strwstrtools.h"
#include <algorithm>
using namespace std;
using namespace Lima::Common::MediaticData;
namespace Lima
{
namespace LinguisticProcessing
{
namespace LinguisticAnalysisStructure
{
bool LinguisticElement::operator==(const LinguisticElement& le) const
{
return ((properties==le.properties) &&
(inflectedForm==le.inflectedForm) &&
(lemma==le.lemma) &&
(normalizedForm==le.normalizedForm) &&
(type==le.type));
}
bool LinguisticElement::operator<(const LinguisticElement& le) const
{
if (inflectedForm!=le.inflectedForm) return inflectedForm<le.inflectedForm;
if (lemma!=le.lemma) return lemma<le.lemma;
if (normalizedForm!=le.normalizedForm) return normalizedForm<le.normalizedForm;
if (properties!=le.properties) return properties<le.properties;
return type<le.type;
}
MorphoSyntacticData::MorphoSyntacticData()
{}
MorphoSyntacticData::~MorphoSyntacticData()
{}
bool MorphoSyntacticData::hasUniqueMicro(const Common::PropertyCode::PropertyAccessor& microAccessor,const std::list<LinguisticCode>& microFilter)
{
LinguisticCode micro(0);
for (const_iterator it=begin();
it!=end();
it++)
{
LinguisticCode tmp=microAccessor.readValue(it->properties);
if (micro!=static_cast<LinguisticCode>(0))
{
if (micro!=tmp)
{
return false;
}
}
else
{
micro=tmp;
}
bool found=false;
for (list<LinguisticCode>::const_iterator filterItr=microFilter.begin();
filterItr!=microFilter.end();
filterItr++)
{
if (tmp==*filterItr)
{
found=true;
break;
}
}
if (!found)
{
return false;
}
}
// if micro is 0, then there was no micros, return false
return micro!=static_cast<LinguisticCode>(0);
}
uint64_t MorphoSyntacticData::countValues(const Common::PropertyCode::PropertyAccessor& propertyAccessor)
{
set<LinguisticCode> values;
allValues(propertyAccessor,values);
return values.size();
}
void MorphoSyntacticData::allValues(const Common::PropertyCode::PropertyAccessor& propertyAccessor,std::set<LinguisticCode>& result) const
{
for (const_iterator it=begin();
it!=end();
it++)
{
if (!propertyAccessor.empty(it->properties))
{
result.insert(propertyAccessor.readValue(it->properties));
}
}
}
void MorphoSyntacticData::outputXml(std::ostream& xmlStream,const Common::PropertyCode::PropertyCodeManager& pcm,const FsaStringsPool& sp) const
{
xmlStream << " <data>" << std::endl;
if (!empty())
{
// trie pour avoir les donn�s group�s par strings
MorphoSyntacticData tmp(*this);
sort(tmp.begin(),tmp.end(),ltString());
MorphoSyntacticType type(NO_MORPHOSYNTACTICTYPE);
StringsPoolIndex form(0);
StringsPoolIndex lemma(0);
StringsPoolIndex norm(0);
string currentType;
bool firstEntry=true;
for (const_iterator it=tmp.begin();
it!=tmp.end();
it++)
{
if (it->type != type)
{
// Changement type
if (!firstEntry)
{
xmlStream << " </form>" << std::endl;
xmlStream << " </" << currentType << ">" << std::endl;
}
type=it->type;
switch ( type )
{
case SIMPLE_WORD :
currentType = "simple_word";
break;
case IDIOMATIC_EXPRESSION :
currentType = "idiomatic_expression";
break;
case UNKNOWN_WORD :
currentType = "unknown_word";
break;
case ABBREV_ALTERNATIVE :
currentType = "abbrev_alternative";
break;
case HYPHEN_ALTERNATIVE :
currentType = "hyphen_alternative";
break;
case CONCATENATED_ALTERNATIVE :
currentType = "concatenated_alternative";
break;
case CAPITALFIRST_WORD :
currentType = "capitalfirst_word";
break;
case AGGLUTINATED_WORD:
currentType = "agglutinated_word";
break;
case DESAGGLUTINATED_WORD :
currentType = "desagglutinated_word";
break;
case SPECIFIC_ENTITY :
currentType = "specific_entity";
break;
case HYPERWORD_ALTERNATIVE:
currentType = "hyperwordstemmer_alternative";
break;
case CHINESE_SEGMENTER:
currentType = "chinese_segmenter";
break;
default :
currentType = "UNKNOWN_MORPHOSYNTACTIC_TYPE";
break;
}
xmlStream << " <" << currentType << ">" << std::endl;
}
if ((it->inflectedForm != form) || (it->lemma != lemma) || (it->normalizedForm != norm))
{
if (!firstEntry)
{
xmlStream << " </form>" << std::endl;
}
form=it->inflectedForm;
lemma=it->lemma;
norm=it->normalizedForm;
xmlStream << " <form infl=\"" << Common::Misc::transcodeToXmlEntities(sp[form]) << "\" ";
xmlStream << "lemma=\"" << Common::Misc::transcodeToXmlEntities(sp[lemma]) << "\" ";
xmlStream << "norm=\"" << Common::Misc::transcodeToXmlEntities(sp[norm]) << "\">" << std::endl;
}
const std::map<std::string,Common::PropertyCode::PropertyManager>& managers=pcm.getPropertyManagers();
xmlStream << " <property>" << std::endl;
for (std::map<std::string,Common::PropertyCode::PropertyManager>::const_iterator propItr=managers.begin();
propItr!=managers.end();
propItr++)
{
if (!propItr->second.getPropertyAccessor().empty(it->properties))
{
xmlStream << " <p prop=\"" << propItr->first << "\" val=\"" << propItr->second.getPropertySymbolicValue(it->properties) << "\"/>" << std::endl;
}
}
xmlStream << " </property>" << std::endl;
firstEntry=false;
}
xmlStream << " </form>" << std::endl;
xmlStream << " </" << currentType << ">" << std::endl;
}
xmlStream << " </data>" << std::endl;
}
std::set<StringsPoolIndex> MorphoSyntacticData::allInflectedForms() const
{
set<StringsPoolIndex> forms;
for (const_iterator it=begin();
it!=end();
it++)
{
forms.insert(it->inflectedForm);
}
return forms;
}
std::set<StringsPoolIndex> MorphoSyntacticData::allLemma() const
{
set<StringsPoolIndex> lemma;
for (const_iterator it=begin();
it!=end();
it++)
{
lemma.insert(it->lemma);
}
return lemma;
}
std::set<StringsPoolIndex> MorphoSyntacticData::allNormalizedForms() const
{
set<StringsPoolIndex> norms;
for (const_iterator it=begin();
it!=end();
it++)
{
norms.insert(it->normalizedForm);
}
return norms;
}
LinguisticCode MorphoSyntacticData::firstValue(const Common::PropertyCode::PropertyAccessor& propertyAccessor) const
{
for (const_iterator it=begin();
it!=end();
it++)
{
if (!propertyAccessor.empty(it->properties))
{
return propertyAccessor.readValue(it->properties);
}
}
return static_cast<LinguisticCode>(0);
}
} // LinguisticAnalysisStructure
} // LinguisticProcessing
} // Lima
<commit_msg>add ENCHANT_LIBRARIES for spell checking<commit_after>/*
Copyright 2002-2013 CEA LIST
This file is part of LIMA.
LIMA 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.
LIMA 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 LIMA. If not, see <http://www.gnu.org/licenses/>
*/
/***************************************************************************
* Copyright (C) 2004-2012 by CEA LIST *
* *
***************************************************************************/
#include "MorphoSyntacticData.h"
#include "MorphoSyntacticDataUtils.h"
#include "common/MediaticData/mediaticData.h"
#include "common/Data/strwstrtools.h"
#include <algorithm>
using namespace std;
using namespace Lima::Common::MediaticData;
namespace Lima
{
namespace LinguisticProcessing
{
namespace LinguisticAnalysisStructure
{
bool LinguisticElement::operator==(const LinguisticElement& le) const
{
return ((properties==le.properties) &&
(inflectedForm==le.inflectedForm) &&
(lemma==le.lemma) &&
(normalizedForm==le.normalizedForm) &&
(type==le.type));
}
bool LinguisticElement::operator<(const LinguisticElement& le) const
{
if (inflectedForm!=le.inflectedForm) return inflectedForm<le.inflectedForm;
if (lemma!=le.lemma) return lemma<le.lemma;
if (normalizedForm!=le.normalizedForm) return normalizedForm<le.normalizedForm;
if (properties!=le.properties) return properties<le.properties;
return type<le.type;
}
MorphoSyntacticData::MorphoSyntacticData()
{}
MorphoSyntacticData::~MorphoSyntacticData()
{}
bool MorphoSyntacticData::hasUniqueMicro(const Common::PropertyCode::PropertyAccessor& microAccessor,const std::list<LinguisticCode>& microFilter)
{
LinguisticCode micro(0);
for (const_iterator it=begin();
it!=end();
it++)
{
LinguisticCode tmp=microAccessor.readValue(it->properties);
if (micro!=static_cast<LinguisticCode>(0))
{
if (micro!=tmp)
{
return false;
}
}
else
{
micro=tmp;
}
bool found=false;
for (list<LinguisticCode>::const_iterator filterItr=microFilter.begin();
filterItr!=microFilter.end();
filterItr++)
{
if (tmp==*filterItr)
{
found=true;
break;
}
}
if (!found)
{
return false;
}
}
// if micro is 0, then there was no micros, return false
return micro!=static_cast<LinguisticCode>(0);
}
uint64_t MorphoSyntacticData::countValues(const Common::PropertyCode::PropertyAccessor& propertyAccessor)
{
set<LinguisticCode> values;
allValues(propertyAccessor,values);
return values.size();
}
void MorphoSyntacticData::allValues(const Common::PropertyCode::PropertyAccessor& propertyAccessor,std::set<LinguisticCode>& result) const
{
for (const_iterator it=begin();
it!=end();
it++)
{
if (!propertyAccessor.empty(it->properties))
{
result.insert(propertyAccessor.readValue(it->properties));
}
}
}
void MorphoSyntacticData::outputXml(std::ostream& xmlStream,const Common::PropertyCode::PropertyCodeManager& pcm,const FsaStringsPool& sp) const
{
xmlStream << " <data>" << std::endl;
if (!empty())
{
// trie pour avoir les donn�s group�s par strings
MorphoSyntacticData tmp(*this);
sort(tmp.begin(),tmp.end(),ltString());
MorphoSyntacticType type(NO_MORPHOSYNTACTICTYPE);
StringsPoolIndex form(0);
StringsPoolIndex lemma(0);
StringsPoolIndex norm(0);
string currentType;
bool firstEntry=true;
for (const_iterator it=tmp.begin();
it!=tmp.end();
it++)
{
if (it->type != type)
{
// Changement type
if (!firstEntry)
{
xmlStream << " </form>" << std::endl;
xmlStream << " </" << currentType << ">" << std::endl;
}
type=it->type;
switch ( type )
{
case SIMPLE_WORD :
currentType = "simple_word";
break;
case IDIOMATIC_EXPRESSION :
currentType = "idiomatic_expression";
break;
case UNKNOWN_WORD :
currentType = "unknown_word";
break;
case ABBREV_ALTERNATIVE :
currentType = "abbrev_alternative";
break;
case HYPHEN_ALTERNATIVE :
currentType = "hyphen_alternative";
break;
case CONCATENATED_ALTERNATIVE :
currentType = "concatenated_alternative";
break;
case SPELLING_ALTERNATIVE :
currentType = "spelling_alternative";
break;
case CAPITALFIRST_WORD :
currentType = "capitalfirst_word";
break;
case AGGLUTINATED_WORD:
currentType = "agglutinated_word";
break;
case DESAGGLUTINATED_WORD :
currentType = "desagglutinated_word";
break;
case SPECIFIC_ENTITY :
currentType = "specific_entity";
break;
case HYPERWORD_ALTERNATIVE:
currentType = "hyperwordstemmer_alternative";
break;
case CHINESE_SEGMENTER:
currentType = "chinese_segmenter";
break;
default :
currentType = "UNKNOWN_MORPHOSYNTACTIC_TYPE";
break;
}
xmlStream << " <" << currentType << ">" << std::endl;
}
if ((it->inflectedForm != form) || (it->lemma != lemma) || (it->normalizedForm != norm))
{
if (!firstEntry)
{
xmlStream << " </form>" << std::endl;
}
form=it->inflectedForm;
lemma=it->lemma;
norm=it->normalizedForm;
xmlStream << " <form infl=\"" << Common::Misc::transcodeToXmlEntities(sp[form]) << "\" ";
xmlStream << "lemma=\"" << Common::Misc::transcodeToXmlEntities(sp[lemma]) << "\" ";
xmlStream << "norm=\"" << Common::Misc::transcodeToXmlEntities(sp[norm]) << "\">" << std::endl;
}
const std::map<std::string,Common::PropertyCode::PropertyManager>& managers=pcm.getPropertyManagers();
xmlStream << " <property>" << std::endl;
for (std::map<std::string,Common::PropertyCode::PropertyManager>::const_iterator propItr=managers.begin();
propItr!=managers.end();
propItr++)
{
if (!propItr->second.getPropertyAccessor().empty(it->properties))
{
xmlStream << " <p prop=\"" << propItr->first << "\" val=\"" << propItr->second.getPropertySymbolicValue(it->properties) << "\"/>" << std::endl;
}
}
xmlStream << " </property>" << std::endl;
firstEntry=false;
}
xmlStream << " </form>" << std::endl;
xmlStream << " </" << currentType << ">" << std::endl;
}
xmlStream << " </data>" << std::endl;
}
std::set<StringsPoolIndex> MorphoSyntacticData::allInflectedForms() const
{
set<StringsPoolIndex> forms;
for (const_iterator it=begin();
it!=end();
it++)
{
forms.insert(it->inflectedForm);
}
return forms;
}
std::set<StringsPoolIndex> MorphoSyntacticData::allLemma() const
{
set<StringsPoolIndex> lemma;
for (const_iterator it=begin();
it!=end();
it++)
{
lemma.insert(it->lemma);
}
return lemma;
}
std::set<StringsPoolIndex> MorphoSyntacticData::allNormalizedForms() const
{
set<StringsPoolIndex> norms;
for (const_iterator it=begin();
it!=end();
it++)
{
norms.insert(it->normalizedForm);
}
return norms;
}
LinguisticCode MorphoSyntacticData::firstValue(const Common::PropertyCode::PropertyAccessor& propertyAccessor) const
{
for (const_iterator it=begin();
it!=end();
it++)
{
if (!propertyAccessor.empty(it->properties))
{
return propertyAccessor.readValue(it->properties);
}
}
return static_cast<LinguisticCode>(0);
}
} // LinguisticAnalysisStructure
} // LinguisticProcessing
} // Lima
<|endoftext|> |
<commit_before>//=================================================================================================
/*!
// \file src/mathtest/lapack/OperationTest.cpp
// \brief Source file for the LAPACK operation test
//
// Copyright (C) 2013 Klaus Iglberger - All Rights Reserved
//
// This file is part of the Blaze library. You can redistribute it and/or modify it under
// the terms of the New (Revised) BSD License. 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 names of the Blaze development group 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.
*/
//=================================================================================================
//*************************************************************************************************
// Includes
//*************************************************************************************************
#include <cstdlib>
#include <iostream>
#include <blaze/util/Complex.h>
#include <blazetest/mathtest/lapack/OperationTest.h>
namespace blazetest {
namespace mathtest {
namespace lapack {
//=================================================================================================
//
// CONSTRUCTORS
//
//=================================================================================================
//*************************************************************************************************
/*!\brief Constructor for the OperationTest class test.
//
// \exception std::runtime_error Operation error detected.
*/
OperationTest::OperationTest()
{
/*
testGeqrf< float >();
testGeqrf< double >();
testGeqrf< blaze::complex<float> >();
testGeqrf< blaze::complex<double> >();
testGetrf< float >();
testGetrf< double >();
testGetrf< blaze::complex<float> >();
testGetrf< blaze::complex<double> >();
testSytrf< float >();
testSytrf< double >();
testSytrf< blaze::complex<float> >();
testSytrf< blaze::complex<double> >();
testHetrf< blaze::complex<float> >();
testHetrf< blaze::complex<double> >();
testPotrf< float >();
testPotrf< double >();
testPotrf< blaze::complex<float> >();
testPotrf< blaze::complex<double> >();
testGetri< float >();
testGetri< double >();
testGetri< blaze::complex<float> >();
testGetri< blaze::complex<double> >();
testSytri< float >();
testSytri< double >();
testSytri< blaze::complex<float> >();
testSytri< blaze::complex<double> >();
*/
//testHetri< blaze::complex<float> >();
testHetri< blaze::complex<double> >();
/*
testPotri< float >();
testPotri< double >();
testPotri< blaze::complex<float> >();
testPotri< blaze::complex<double> >();
testTrtri< float >();
testTrtri< double >();
testTrtri< blaze::complex<float> >();
testTrtri< blaze::complex<double> >();
testGesv< float >();
testGesv< double >();
testGesv< blaze::complex<float> >();
testGesv< blaze::complex<double> >();
*/
}
//*************************************************************************************************
} // namespace lapack
} // namespace mathtest
} // namespace blazetest
//=================================================================================================
//
// MAIN FUNCTION
//
//=================================================================================================
//*************************************************************************************************
int main()
{
std::cout << " Running LAPACK operation test..." << std::endl;
try
{
RUN_LAPACK_OPERATION_TEST;
}
catch( std::exception& ex ) {
std::cerr << "\n\n ERROR DETECTED during LAPACK operation test:\n"
<< ex.what() << "\n";
return EXIT_FAILURE;
}
return EXIT_SUCCESS;
}
//*************************************************************************************************
<commit_msg>Fix the operation test for the LAPACK wrapper functions<commit_after>//=================================================================================================
/*!
// \file src/mathtest/lapack/OperationTest.cpp
// \brief Source file for the LAPACK operation test
//
// Copyright (C) 2013 Klaus Iglberger - All Rights Reserved
//
// This file is part of the Blaze library. You can redistribute it and/or modify it under
// the terms of the New (Revised) BSD License. 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 names of the Blaze development group 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.
*/
//=================================================================================================
//*************************************************************************************************
// Includes
//*************************************************************************************************
#include <cstdlib>
#include <iostream>
#include <blaze/util/Complex.h>
#include <blazetest/mathtest/lapack/OperationTest.h>
namespace blazetest {
namespace mathtest {
namespace lapack {
//=================================================================================================
//
// CONSTRUCTORS
//
//=================================================================================================
//*************************************************************************************************
/*!\brief Constructor for the OperationTest class test.
//
// \exception std::runtime_error Operation error detected.
*/
OperationTest::OperationTest()
{
testGeqrf< float >();
testGeqrf< double >();
testGeqrf< blaze::complex<float> >();
testGeqrf< blaze::complex<double> >();
testGetrf< float >();
testGetrf< double >();
testGetrf< blaze::complex<float> >();
testGetrf< blaze::complex<double> >();
testSytrf< float >();
testSytrf< double >();
testSytrf< blaze::complex<float> >();
testSytrf< blaze::complex<double> >();
testHetrf< blaze::complex<float> >();
testHetrf< blaze::complex<double> >();
testPotrf< float >();
testPotrf< double >();
testPotrf< blaze::complex<float> >();
testPotrf< blaze::complex<double> >();
testGetri< float >();
testGetri< double >();
testGetri< blaze::complex<float> >();
testGetri< blaze::complex<double> >();
testSytri< float >();
testSytri< double >();
testSytri< blaze::complex<float> >();
testSytri< blaze::complex<double> >();
testHetri< blaze::complex<float> >();
testHetri< blaze::complex<double> >();
testPotri< float >();
testPotri< double >();
testPotri< blaze::complex<float> >();
testPotri< blaze::complex<double> >();
testTrtri< float >();
testTrtri< double >();
testTrtri< blaze::complex<float> >();
testTrtri< blaze::complex<double> >();
testGesv< float >();
testGesv< double >();
testGesv< blaze::complex<float> >();
testGesv< blaze::complex<double> >();
}
//*************************************************************************************************
} // namespace lapack
} // namespace mathtest
} // namespace blazetest
//=================================================================================================
//
// MAIN FUNCTION
//
//=================================================================================================
//*************************************************************************************************
int main()
{
std::cout << " Running LAPACK operation test..." << std::endl;
try
{
RUN_LAPACK_OPERATION_TEST;
}
catch( std::exception& ex ) {
std::cerr << "\n\n ERROR DETECTED during LAPACK operation test:\n"
<< ex.what() << "\n";
return EXIT_FAILURE;
}
return EXIT_SUCCESS;
}
//*************************************************************************************************
<|endoftext|> |
<commit_before>#include "Adafruit_MCP23008.h"
// This is a library for the MCP23008 i2c port expander
// These displays use I2C to communicate, 2 pins are required to
// interface
// Adafruit invests time and resources providing this open source code,
// please support Adafruit and open-source hardware by purchasing
// products from Adafruit!
// Written by Limor Fried/Ladyada for Adafruit Industries.
// BSD license, all text above must be included in any redistribution
////////////////////////////////////////////////////////////////////////////////
// RTC_DS1307 implementation
void Adafruit_MCP23008::begin(uint8_t addr) {
if (addr > 7) {
addr = 7;
}
i2caddr = addr;
Wire.setSpeed(CLOCK_SPEED_100KHZ);
Wire.stretchClock(true);
Wire.begin();
delayMicroseconds(2);
// set defaults!
Wire.beginTransmission(MCP23008_ADDRESS | i2caddr);
delayMicroseconds(2);
Wire.write((byte)MCP23008_IODIR);
delayMicroseconds(2);
Wire.write((byte)0xFF); // all inputs
delayMicroseconds(2);
Wire.write((byte)0x00);
delayMicroseconds(2);
Wire.write((byte)0x00);
delayMicroseconds(2);
Wire.write((byte)0x00);
delayMicroseconds(2);
Wire.write((byte)0x00);
delayMicroseconds(2);
Wire.write((byte)0x00);
delayMicroseconds(2);
Wire.write((byte)0x00);
delayMicroseconds(2);
Wire.write((byte)0x00);
delayMicroseconds(2);
Wire.write((byte)0x00);
delayMicroseconds(2);
Wire.write((byte)0x00);
delayMicroseconds(2);
Wire.endTransmission();
delayMicroseconds(2);
}
void Adafruit_MCP23008::begin(void) {
begin(0);
}
void Adafruit_MCP23008::pinMode(uint8_t p, uint8_t d) {
uint8_t iodir;
// only 8 bits!
if (p > 7)
return;
iodir = read8(MCP23008_IODIR);
// set the pin and direction
if (d == INPUT) {
iodir |= 1 << p;
} else {
iodir &= ~(1 << p);
}
// write the new IODIR
write8(MCP23008_IODIR, iodir);
}
uint8_t Adafruit_MCP23008::readGPIO(void) {
// read the current GPIO input
return read8(MCP23008_GPIO);
}
void Adafruit_MCP23008::writeGPIO(uint8_t gpio) {
write8(MCP23008_GPIO, gpio);
}
void Adafruit_MCP23008::digitalWrite(uint8_t p, uint8_t d) {
uint8_t gpio;
// only 8 bits!
if (p > 7)
return;
// read the current GPIO output latches
gpio = readGPIO();
// set the pin and direction
if (d == HIGH) {
gpio |= 1 << p;
} else {
gpio &= ~(1 << p);
}
// write the new GPIO
writeGPIO(gpio);
}
void Adafruit_MCP23008::pullUp(uint8_t p, uint8_t d) {
uint8_t gppu;
// only 8 bits!
if (p > 7)
return;
gppu = read8(MCP23008_GPPU);
// set the pin and direction
if (d == HIGH) {
gppu |= 1 << p;
} else {
gppu &= ~(1 << p);
}
// write the new GPIO
write8(MCP23008_GPPU, gppu);
}
uint8_t Adafruit_MCP23008::digitalRead(uint8_t p) {
// only 8 bits!
if (p > 7)
return 0;
// read the current GPIO
return (readGPIO() >> p) & 0x1;
}
uint8_t Adafruit_MCP23008::read8(uint8_t addr) {
Wire.beginTransmission(MCP23008_ADDRESS | i2caddr);
delayMicroseconds(2);
Wire.write((byte)addr);
delayMicroseconds(2);
Wire.endTransmission();
delayMicroseconds(2);
Wire.requestFrom(MCP23008_ADDRESS | i2caddr, 1);
delayMicroseconds(2);
return Wire.read();
}
void Adafruit_MCP23008::write8(uint8_t addr, uint8_t data) {
Wire.beginTransmission(MCP23008_ADDRESS | i2caddr);
delayMicroseconds(2);
Wire.write((byte)addr);
delayMicroseconds(2);
Wire.write((byte)data);
delayMicroseconds(2);
Wire.endTransmission();
delayMicroseconds(2);
}
<commit_msg>modified end of transmission delay<commit_after>#include "Adafruit_MCP23008.h"
// This is a library for the MCP23008 i2c port expander
// These displays use I2C to communicate, 2 pins are required to
// interface
// Adafruit invests time and resources providing this open source code,
// please support Adafruit and open-source hardware by purchasing
// products from Adafruit!
// Written by Limor Fried/Ladyada for Adafruit Industries.
// BSD license, all text above must be included in any redistribution
////////////////////////////////////////////////////////////////////////////////
// RTC_DS1307 implementation
void Adafruit_MCP23008::begin(uint8_t addr) {
if (addr > 7) {
addr = 7;
}
i2caddr = addr;
//Wire.setSpeed(CLOCK_SPEED_100KHZ);
//Wire.stretchClock(true);
Wire.begin();
delayMicroseconds(2);
// set defaults!
Wire.beginTransmission(MCP23008_ADDRESS | i2caddr);
delayMicroseconds(2);
Wire.write((byte)MCP23008_IODIR);
delayMicroseconds(2);
Wire.write((byte)0xFF); // all inputs
delayMicroseconds(2);
Wire.write((byte)0x00);
delayMicroseconds(2);
Wire.write((byte)0x00);
delayMicroseconds(2);
Wire.write((byte)0x00);
delayMicroseconds(2);
Wire.write((byte)0x00);
delayMicroseconds(2);
Wire.write((byte)0x00);
delayMicroseconds(2);
Wire.write((byte)0x00);
delayMicroseconds(2);
Wire.write((byte)0x00);
delayMicroseconds(2);
Wire.write((byte)0x00);
delayMicroseconds(2);
Wire.write((byte)0x00);
delayMicroseconds(2);
Wire.endTransmission();
delayMicroseconds(5);
}
void Adafruit_MCP23008::begin(void) {
begin(0);
}
void Adafruit_MCP23008::pinMode(uint8_t p, uint8_t d) {
uint8_t iodir;
// only 8 bits!
if (p > 7)
return;
iodir = read8(MCP23008_IODIR);
// set the pin and direction
if (d == INPUT) {
iodir |= 1 << p;
} else {
iodir &= ~(1 << p);
}
// write the new IODIR
write8(MCP23008_IODIR, iodir);
}
uint8_t Adafruit_MCP23008::readGPIO(void) {
// read the current GPIO input
return read8(MCP23008_GPIO);
}
void Adafruit_MCP23008::writeGPIO(uint8_t gpio) {
write8(MCP23008_GPIO, gpio);
}
void Adafruit_MCP23008::digitalWrite(uint8_t p, uint8_t d) {
uint8_t gpio;
// only 8 bits!
if (p > 7)
return;
// read the current GPIO output latches
gpio = readGPIO();
// set the pin and direction
if (d == HIGH) {
gpio |= 1 << p;
} else {
gpio &= ~(1 << p);
}
// write the new GPIO
writeGPIO(gpio);
}
void Adafruit_MCP23008::pullUp(uint8_t p, uint8_t d) {
uint8_t gppu;
// only 8 bits!
if (p > 7)
return;
gppu = read8(MCP23008_GPPU);
// set the pin and direction
if (d == HIGH) {
gppu |= 1 << p;
} else {
gppu &= ~(1 << p);
}
// write the new GPIO
write8(MCP23008_GPPU, gppu);
}
uint8_t Adafruit_MCP23008::digitalRead(uint8_t p) {
// only 8 bits!
if (p > 7)
return 0;
// read the current GPIO
return (readGPIO() >> p) & 0x1;
}
uint8_t Adafruit_MCP23008::read8(uint8_t addr) {
Wire.beginTransmission(MCP23008_ADDRESS | i2caddr);
delayMicroseconds(2);
Wire.write((byte)addr);
delayMicroseconds(2);
Wire.endTransmission();
delayMicroseconds(5);
Wire.requestFrom(MCP23008_ADDRESS | i2caddr, 1);
delayMicroseconds(2);
return Wire.read();
}
void Adafruit_MCP23008::write8(uint8_t addr, uint8_t data) {
Wire.beginTransmission(MCP23008_ADDRESS | i2caddr);
delayMicroseconds(2);
Wire.write((byte)addr);
delayMicroseconds(2);
Wire.write((byte)data);
delayMicroseconds(2);
Wire.endTransmission();
delayMicroseconds(5);
}
<|endoftext|> |
<commit_before>#include <algorithm>
#include <cmath>
#include "gain_schedule.h"
#include "MPU6050.h"
namespace control {
vector_t<state_size> StateEstimator::update(const vector_t<state_size>& x,
const vector_t<input_size>& u) const
{
return A * x + B * u;
}
vector_t<output_size> LQRController::update(const vector_t<state_size>& x) const
{
return C * x;
}
vector_t<output_size> PIController::update(const vector_t<output_size>& x,
const vector_t<output_size>& e) const
{
return Kp * x + Ki * e;
}
bool rt_controller_t::operator<(const rt_controller_t& rhs) const
{
return rate < rhs.rate;
}
GainSchedule::GainSchedule() : state_{{}}, pi_control_enabled_{false}
{
}
float GainSchedule::rate() const
{
return rate_;
}
bool GainSchedule::set_sample(Sample& s)
{
s_ = &s;
return set_rate(s.encoder.rear_wheel_rate);
}
void GainSchedule::set_state(const vector_t<state_size>& state)
{
state_ = state;
}
bool GainSchedule::set_rate(float rate)
{
bool valid = true;
rate_ = rate;
r.rate = rate;
auto it = std::upper_bound(schedule_.begin(), schedule_.end(), r);
if (it == schedule_.begin() || it == schedule_.end()) {
valid = false;
if (it == schedule_.begin()) {
s_->estimate.theta_R_dot_upper = it->rate;
s_->estimate.theta_R_dot_lower = NAN;
} else {
s_->estimate.theta_R_dot_upper = NAN;
s_->estimate.theta_R_dot_lower = (--it)->rate;
}
} else {
valid = true;
s_->estimate.theta_R_dot_upper = it->rate;
ss_upper_ = const_cast<controller_t*>(&(it->controller));
s_->estimate.theta_R_dot_lower = (--it)->rate;
ss_lower_ = const_cast<controller_t*>(&(it->controller));
alpha_ = (rate - s_->estimate.theta_R_dot_lower) /
(s_->estimate.theta_R_dot_upper - s_->estimate.theta_R_dot_lower);
}
return valid;
}
void GainSchedule::state_estimate(float torque_prev)
{
if (state_estimate_time_ == s_->loop_count)
return;
state_estimate_time_ = s_->loop_count;
vector_t<input_size> input {{torque_prev, s_->encoder.steer,
hardware::MPU6050::phi_dot(*s_)}};
auto state_lower = ss_lower_->estimator.update(state_, input);
auto state_upper = ss_upper_->estimator.update(state_, input);
state_ = alpha_ * (state_upper - state_lower) + state_lower;
s_->estimate.phi = state_(0, 0);
s_->estimate.delta = state_(1, 0);
s_->estimate.phi_dot = state_(2, 0);
s_->estimate.delta_dot = state_(3, 0);
}
float GainSchedule::lqr_output() const
{
const float t0 = ss_lower_->lqr.update(state_)(0, 0);
const float t1 = ss_upper_->lqr.update(state_)(0, 0);
return alpha_ * (t1 - t0) + t0;
}
float GainSchedule::pi_output() const
{
vector_t<output_size> x {{s_->yaw_rate_pi.x}};
vector_t<output_size> e {{s_->yaw_rate_pi.e}};
const float t0 = ss_lower_->pi.update(x, e)(0, 0);
const float t1 = ss_upper_->pi.update(x, e)(0, 0);
return alpha_ * (t1 - t0) + t0;
}
float GainSchedule::compute_updated_torque(float torque_prev)
{
state_estimate(torque_prev);
return lqr_output() + pi_output();
}
} // namespace control
<commit_msg>Always update state estimate when called.<commit_after>#include <algorithm>
#include <cmath>
#include "gain_schedule.h"
#include "MPU6050.h"
namespace control {
vector_t<state_size> StateEstimator::update(const vector_t<state_size>& x,
const vector_t<input_size>& u) const
{
return A * x + B * u;
}
vector_t<output_size> LQRController::update(const vector_t<state_size>& x) const
{
return C * x;
}
vector_t<output_size> PIController::update(const vector_t<output_size>& x,
const vector_t<output_size>& e) const
{
return Kp * x + Ki * e;
}
bool rt_controller_t::operator<(const rt_controller_t& rhs) const
{
return rate < rhs.rate;
}
GainSchedule::GainSchedule() : state_{{}}, pi_control_enabled_{false}
{
}
float GainSchedule::rate() const
{
return rate_;
}
bool GainSchedule::set_sample(Sample& s)
{
s_ = &s;
return set_rate(s.encoder.rear_wheel_rate);
}
void GainSchedule::set_state(const vector_t<state_size>& state)
{
state_ = state;
}
bool GainSchedule::set_rate(float rate)
{
bool valid = true;
rate_ = rate;
r.rate = rate;
auto it = std::upper_bound(schedule_.begin(), schedule_.end(), r);
if (it == schedule_.begin() || it == schedule_.end()) {
valid = false;
if (it == schedule_.begin()) {
s_->estimate.theta_R_dot_upper = it->rate;
s_->estimate.theta_R_dot_lower = NAN;
} else {
s_->estimate.theta_R_dot_upper = NAN;
s_->estimate.theta_R_dot_lower = (--it)->rate;
}
} else {
valid = true;
s_->estimate.theta_R_dot_upper = it->rate;
ss_upper_ = const_cast<controller_t*>(&(it->controller));
s_->estimate.theta_R_dot_lower = (--it)->rate;
ss_lower_ = const_cast<controller_t*>(&(it->controller));
alpha_ = (rate - s_->estimate.theta_R_dot_lower) /
(s_->estimate.theta_R_dot_upper - s_->estimate.theta_R_dot_lower);
}
return valid;
}
void GainSchedule::state_estimate(float torque_prev)
{
state_estimate_time_ = s_->loop_count;
vector_t<input_size> input {{torque_prev, s_->encoder.steer,
hardware::MPU6050::phi_dot(*s_)}};
auto state_lower = ss_lower_->estimator.update(state_, input);
auto state_upper = ss_upper_->estimator.update(state_, input);
state_ = alpha_ * (state_upper - state_lower) + state_lower;
s_->estimate.phi = state_(0, 0);
s_->estimate.delta = state_(1, 0);
s_->estimate.phi_dot = state_(2, 0);
s_->estimate.delta_dot = state_(3, 0);
}
float GainSchedule::lqr_output() const
{
const float t0 = ss_lower_->lqr.update(state_)(0, 0);
const float t1 = ss_upper_->lqr.update(state_)(0, 0);
return alpha_ * (t1 - t0) + t0;
}
float GainSchedule::pi_output() const
{
vector_t<output_size> x {{s_->yaw_rate_pi.x}};
vector_t<output_size> e {{s_->yaw_rate_pi.e}};
const float t0 = ss_lower_->pi.update(x, e)(0, 0);
const float t1 = ss_upper_->pi.update(x, e)(0, 0);
return alpha_ * (t1 - t0) + t0;
}
float GainSchedule::compute_updated_torque(float torque_prev)
{
state_estimate(torque_prev);
return lqr_output() + pi_output();
}
} // namespace control
<|endoftext|> |
<commit_before>/**
* @file uart.cpp
*
* @brief Contains uart access functionality
*
* Example usage:
* @code
*
* Uart uart0(&UBRR0, &UCSR0A, &UCSR0B, &UCSR0C, &UDR0);
* uart0.Init(9600);
*
* @endcode
*/
#include <stdint.h>
#include <avr/io.h>
#include <avr/interrupt.h>
#include "uart.h"
#include "util/ringbuffer.h"
/**
* @brief Used to access uart0
*
* On atmega2561:<b>
* Pin2: RXD0 <b>
* Pin3: TXD0
*/
Uart uart0(&UBRR0, &UCSR0A, &UCSR0B, &UCSR0C, &UDR0);
/**
* @brief Used to access uart1
*
* On atmega2561:<b>
* Pin27: RXD0 <b>
* Pin28: TXD0
*/
Uart uart1(&UBRR1, &UCSR1A, &UCSR1B, &UCSR1C, &UDR1);
/**
* @brief Calculates the clock scale needed to run uart at the specified baud rate.
*
* @param baudrate Typical values include 1200, 2400, 4800, 9600, 14400, 19200, 38400, 57600, 128000, 256000.
* If not specified 9600 is used.
*/
uint16_t Uart::BaudScale(uint16_t baudrate)
{
return (((F_CPU / (baudrate * 16UL))) - 1);
}
/**
* @brief Initializes uart with specified baud rate.
*
* @param ubrr
* @param ucsra
* @param ucsrb
* @param ucsrc
* @param udr
*
* Example usage:
* @code
*
* Uart uart0(&UBRR0, &UCSR0A, &UCSR0B, &UCSR0C, &UDR0);
* Uart uart1(&UBRR0, &UCSR0A, &UCSR0B, &UCSR0C, &UDR0);
*
* @endcode
*/
Uart::Uart(volatile uint16_t *ubrr, volatile uint8_t *ucsra, volatile uint8_t *ucsrb, volatile uint8_t *ucsrc, volatile uint8_t *udr)
{
_ubrr = ubrr;
_ucsra = ucsra;
_ucsrb = ucsrb;
_ucsrc = ucsrc;
_udr = udr;
}
/**
* @brief Initializes uart with specified baud rate.
*
* @param baudrate Typical values include 1200, 2400, 4800, 9600, 14400, 19200, 38400, 57600, 128000, 256000.
* If not specified 9600 is used.
*
* Example usage:
* @code
*
* Uart uart0(&UBRR0, &UCSR0A, &UCSR0B, &UCSR0C, &UDR0);
* uart0.Init(9600);
*
* @endcode
*/
void Uart::Init(uint16_t baudrate)
{
// initializing uart to specified baud rate
*_ubrr = BaudScale(baudrate);
// setting 8 data bits, 1 stop bit, no parity
*_ucsrc = ((0 << USBS0) | (1 << UCSZ00) | (1 << UCSZ01));
// enabling receiver and transmitter
*_ucsrb = ((1 << RXEN0) | (1 << TXEN0));
// enabling uart interrupts
*_ucsrb |= ((1 << RXCIE0) | (1 << TXCIE0));
}
/**
* @brief Pushes byte to rx buffer. If buffer is full, nothing happens.
*
* @param byte Byte to push to buffer.
*/
void _PushRx(Uart *uart, char byte)
{
uart->_rx_buffer.Push(byte);
}
ISR(USART0_RX_vect)
{
char rxbyte;
// echo rx to tx
rxbyte = UDR0;
UDR0 = rxbyte;
// pushing byte to rxbuff
_PushRx(&uart0, rxbyte);
}
<commit_msg>Added loopback isr and tested for uart1<commit_after>/**
* @file uart.cpp
*
* @brief Contains uart access functionality
*
* Example usage:
* @code
*
* Uart uart0(&UBRR0, &UCSR0A, &UCSR0B, &UCSR0C, &UDR0);
* uart0.Init(9600);
*
* @endcode
*/
#include <stdint.h>
#include <avr/io.h>
#include <avr/interrupt.h>
#include "uart.h"
#include "util/ringbuffer.h"
/**
* @brief Used to access uart0
*
* On atmega2561:<b>
* Pin2: RXD0 <b>
* Pin3: TXD0
*/
Uart uart0(&UBRR0, &UCSR0A, &UCSR0B, &UCSR0C, &UDR0);
/**
* @brief Used to access uart1
*
* On atmega2561:<b>
* Pin27: RXD0 <b>
* Pin28: TXD0
*/
Uart uart1(&UBRR1, &UCSR1A, &UCSR1B, &UCSR1C, &UDR1);
/**
* @brief Calculates the clock scale needed to run uart at the specified baud rate.
*
* @param baudrate Typical values include 1200, 2400, 4800, 9600, 14400, 19200, 38400, 57600, 128000, 256000.
* If not specified 9600 is used.
*/
uint16_t Uart::BaudScale(uint16_t baudrate)
{
return (((F_CPU / (baudrate * 16UL))) - 1);
}
/**
* @brief Initializes uart with specified baud rate.
*
* @param ubrr
* @param ucsra
* @param ucsrb
* @param ucsrc
* @param udr
*
* Example usage:
* @code
*
* Uart uart0(&UBRR0, &UCSR0A, &UCSR0B, &UCSR0C, &UDR0);
* Uart uart1(&UBRR0, &UCSR0A, &UCSR0B, &UCSR0C, &UDR0);
*
* @endcode
*/
Uart::Uart(volatile uint16_t *ubrr, volatile uint8_t *ucsra, volatile uint8_t *ucsrb, volatile uint8_t *ucsrc, volatile uint8_t *udr)
{
_ubrr = ubrr;
_ucsra = ucsra;
_ucsrb = ucsrb;
_ucsrc = ucsrc;
_udr = udr;
}
/**
* @brief Initializes uart with specified baud rate.
*
* @param baudrate Typical values include 1200, 2400, 4800, 9600, 14400, 19200, 38400, 57600, 128000, 256000.
* If not specified 9600 is used.
*
* Example usage:
* @code
*
* Uart uart0(&UBRR0, &UCSR0A, &UCSR0B, &UCSR0C, &UDR0);
* uart0.Init(9600);
*
* @endcode
*/
void Uart::Init(uint16_t baudrate)
{
// initializing uart to specified baud rate
*_ubrr = BaudScale(baudrate);
// setting 8 data bits, 1 stop bit, no parity
*_ucsrc = ((0 << USBS0) | (1 << UCSZ00) | (1 << UCSZ01));
// enabling receiver and transmitter
*_ucsrb = ((1 << RXEN0) | (1 << TXEN0));
// enabling uart interrupts
*_ucsrb |= ((1 << RXCIE0) | (1 << TXCIE0));
}
/**
* @brief Pushes byte to rx buffer. If buffer is full, nothing happens.
*
* @param byte Byte to push to buffer.
*/
void _PushRx(Uart *uart, char byte)
{
uart->_rx_buffer.Push(byte);
}
ISR(USART0_RX_vect)
{
char rxbyte;
// echo rx to tx
rxbyte = UDR0;
UDR0 = rxbyte;
// pushing byte to rxbuff
_PushRx(&uart0, rxbyte);
}
ISR(USART1_RX_vect)
{
char rxbyte;
// echo rx to tx
rxbyte = UDR1;
UDR1 = rxbyte;
// pushing byte to rxbuff
_PushRx(&uart1, rxbyte);
}
<|endoftext|> |
<commit_before>//
// Aspia Project
// Copyright (C) 2020 Dmitry Chapyshev <dmitry@aspia.ru>
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <https://www.gnu.org/licenses/>.
//
#include "base/audio/audio_output_win.h"
#include "base/logging.h"
#include "base/audio/win/audio_util_win.h"
#include "base/audio/win/scoped_mmcss_registration.h"
#include "base/threading/simple_thread.h"
#include "base/win/scoped_com_initializer.h"
namespace base {
namespace {
const char* sessionStateToString(AudioSessionState state)
{
switch (state)
{
case AudioSessionStateActive:
return "Active";
case AudioSessionStateInactive:
return "Inactive";
case AudioSessionStateExpired:
return "Expired";
default:
return "Invalid";
}
}
} // namespace
AudioOutputWin::AudioOutputWin(const NeedMoreDataCB& need_more_data_cb)
: AudioOutput(need_more_data_cb)
{
// Create the event which the audio engine will signal each time a buffer becomes ready to be
// processed by the client.
audio_samples_event_.reset(CreateEventW(nullptr, false, false, nullptr));
DCHECK(audio_samples_event_.isValid());
// Event to be set in Stop() when rendering/capturing shall stop.
stop_event_.reset(CreateEventW(nullptr, false, false, nullptr));
DCHECK(stop_event_.isValid());
// Event to be set when it has been detected that an active device has been invalidated or the
// stream format has changed.
restart_event_.reset(CreateEventW(nullptr, false, false, nullptr));
DCHECK(restart_event_.isValid());
is_initialized_ = init();
}
AudioOutputWin::~AudioOutputWin()
{
stop();
}
bool AudioOutputWin::start()
{
if (!is_initialized_)
return false;
if (is_restarting_)
{
DCHECK(audio_thread_);
}
if (!fillRenderEndpointBufferWithSilence(audio_client_.Get(), audio_render_client_.Get()))
{
LOG(LS_WARNING) << "Failed to prepare output endpoint with silence";
}
num_frames_written_ = endpoint_buffer_size_frames_;
if (!audio_thread_)
{
audio_thread_ = std::make_unique<SimpleThread>();
audio_thread_->start(std::bind(&AudioOutputWin::threadRun, this));
if (!audio_thread_->isRunning())
{
stopThread();
LOG(LS_ERROR) << "Failed to start audio thread";
return false;
}
}
HRESULT hr = audio_client_->Start();
if (FAILED(hr))
{
stopThread();
LOG(LS_ERROR) << "IAudioClient::Start failed: " << SystemError(hr).toString();
return false;
}
is_active_ = true;
return true;
}
bool AudioOutputWin::stop()
{
if (!is_initialized_)
return true;
if (!is_active_)
{
DLOG(LS_WARNING) << "No output stream is active";
releaseCOMObjects();
is_initialized_ = false;
return true;
}
// Stop audio streaming.
HRESULT hr = audio_client_->Stop();
if (FAILED(hr))
{
LOG(LS_ERROR) << "IAudioClient::Stop failed: " << SystemError(hr).toString();
}
// Stop and destroy the audio thread but only when a restart attempt is not ongoing.
if (!is_restarting_)
stopThread();
hr = audio_client_->Reset();
if (FAILED(hr))
{
LOG(LS_ERROR) << "IAudioClient::Reset failed: " << SystemError(hr).toString();
}
// Extra safety check to ensure that the buffers are cleared. If the buffers are not cleared
// correctly, the next call to start() would fail with AUDCLNT_E_BUFFER_ERROR at
// IAudioRenderClient::GetBuffer().
UINT32 num_queued_frames = 0;
audio_client_->GetCurrentPadding(&num_queued_frames);
DCHECK_EQ(0u, num_queued_frames);
// Release all allocated COM interfaces to allow for a restart without intermediate destruction.
releaseCOMObjects();
return true;
}
void AudioOutputWin::threadRun()
{
if (!isMMCSSSupported())
{
LOG(LS_ERROR) << "MMCSS is not supported";
return;
}
ScopedMMCSSRegistration mmcss_registration(L"Pro Audio");
win::ScopedCOMInitializer com_initializer(win::ScopedCOMInitializer::kMTA);
DCHECK(mmcss_registration.isSucceeded());
DCHECK(com_initializer.isSucceeded());
DCHECK(stop_event_.isValid());
DCHECK(audio_samples_event_.isValid());
bool streaming = true;
bool error = false;
HANDLE wait_array[] = { stop_event_.get(), restart_event_.get(), audio_samples_event_.get() };
// Keep streaming audio until the stop event or the stream-switch event
// is signaled. An error event can also break the main thread loop.
while (streaming && !error)
{
// Wait for a close-down event, stream-switch event or a new render event.
DWORD wait_result = WaitForMultipleObjects(
std::size(wait_array), wait_array, false, INFINITE);
switch (wait_result)
{
case WAIT_OBJECT_0 + 0:
// |stop_event_| has been set.
streaming = false;
break;
case WAIT_OBJECT_0 + 1:
// |restart_event_| has been set.
error = !handleRestartEvent();
break;
case WAIT_OBJECT_0 + 2:
// |audio_samples_event_| has been set.
error = !handleDataRequest();
break;
default:
error = true;
break;
}
}
if (streaming && error)
{
LOG(LS_ERROR) << "WASAPI streaming failed";
// Stop audio streaming since something has gone wrong in our main thread loop. Note that,
// we are still in a "started" state, hence a stop() call is required to join the thread
// properly.
HRESULT hr = audio_client_->Stop();
if (FAILED(hr))
{
LOG(LS_ERROR) << "IAudioClient::Stop failed: " << SystemError(hr).toString();
}
}
}
bool AudioOutputWin::init()
{
Microsoft::WRL::ComPtr<IMMDevice> device(createDevice());
if (!device.Get())
return false;
Microsoft::WRL::ComPtr<IAudioClient> audio_client = createClient(device.Get());
if (!audio_client.Get())
return false;
// Define the output WAVEFORMATEXTENSIBLE format in |format_|.
WAVEFORMATEXTENSIBLE format_extensible;
memset(&format_extensible, 0, sizeof(format_extensible));
WAVEFORMATEX& format = format_extensible.Format;
format.wFormatTag = WAVE_FORMAT_EXTENSIBLE;
format.nChannels = kChannels;
format.nSamplesPerSec = kSampleRate;
format.wBitsPerSample = kBitsPerSample;
format.nBlockAlign = (format.wBitsPerSample / 8) * format.nChannels;
format.nAvgBytesPerSec = format.nSamplesPerSec * format.nBlockAlign;
format.cbSize = sizeof(WAVEFORMATEXTENSIBLE) - sizeof(WAVEFORMATEX);
// Add the parts which are unique for the WAVE_FORMAT_EXTENSIBLE structure.
format_extensible.Samples.wValidBitsPerSample = kBitsPerSample;
format_extensible.dwChannelMask = KSAUDIO_SPEAKER_STEREO;
format_extensible.SubFormat = KSDATAFORMAT_SUBTYPE_PCM;
if (!isFormatSupported(audio_client.Get(), AUDCLNT_SHAREMODE_SHARED, &format_extensible))
return false;
// Initialize the audio stream between the client and the device in shared mode using
// event-driven buffer handling. Also, using 0 as requested buffer size results in a default
// (minimum) endpoint buffer size.
const REFERENCE_TIME requested_buffer_size = 0;
if (!sharedModeInitialize(audio_client.Get(), &format_extensible, audio_samples_event_,
requested_buffer_size, true, &endpoint_buffer_size_frames_))
{
return false;
}
// Create an IAudioRenderClient for an initialized IAudioClient. The IAudioRenderClient
// interface enables us to write output data to a rendering endpoint buffer.
Microsoft::WRL::ComPtr<IAudioRenderClient> audio_render_client =
createRenderClient(audio_client.Get());
if (!audio_render_client.Get())
return false;
// Create an AudioSessionControl interface given the initialized client. The IAudioControl
// interface enables a client to configure the control parameters for an audio session and to
// monitor events in the session.
Microsoft::WRL::ComPtr<IAudioSessionControl> audio_session_control =
createAudioSessionControl(audio_client.Get());
if (!audio_session_control.Get())
return false;
// The Sndvol program displays volume and mute controls for sessions that are in the active and
// inactive states.
AudioSessionState state;
if (FAILED(audio_session_control->GetState(&state)))
return false;
LOG(LS_INFO) << "Audio session state: " << sessionStateToString(state);
// Register the client to receive notifications of session events, including changes in the
// stream state.
if (FAILED(audio_session_control->RegisterAudioSessionNotification(this)))
{
LOG(LS_ERROR) << "IAudioSessionControl::RegisterAudioSessionNotification failed";
return false;
}
// Store valid COM interfaces.
audio_client_ = audio_client;
audio_render_client_ = audio_render_client;
audio_session_control_ = audio_session_control;
return true;
}
bool AudioOutputWin::handleDataRequest()
{
// Get the padding value which indicates the amount of valid unread data that the endpoint
// buffer currently contains.
UINT32 num_unread_frames = 0;
HRESULT hr = audio_client_->GetCurrentPadding(&num_unread_frames);
if (hr == AUDCLNT_E_DEVICE_INVALIDATED)
{
// Avoid breaking the thread loop implicitly by returning false and return true instead for
// AUDCLNT_E_DEVICE_INVALIDATED even it is a valid error message. We will use notifications
// about device changes instead to stop data callbacks and attempt to restart streaming.
DLOG(LS_ERROR) << "AUDCLNT_E_DEVICE_INVALIDATED";
return true;
}
if (FAILED(hr))
{
LOG(LS_ERROR) << "IAudioClient::GetCurrentPadding failed: " << SystemError(hr).toString();
return false;
}
// Contains how much new data we can write to the buffer without the risk of overwriting
// previously written data that the audio engine has not yet read from the buffer. I.e., it is
// the maximum buffer size we can request when calling IAudioRenderClient::GetBuffer().
UINT32 num_requested_frames = endpoint_buffer_size_frames_ - num_unread_frames;
if (num_requested_frames == 0)
{
DLOG(LS_WARNING) << "Audio thread is signaled but no new audio samples are needed";
return true;
}
// Request all available space in the rendering endpoint buffer into which the client can later
// write an audio packet.
uint8_t* audio_data;
hr = audio_render_client_->GetBuffer(num_requested_frames, &audio_data);
if (FAILED(hr))
{
LOG(LS_ERROR) << "IAudioRenderClient::GetBuffer failed: " << SystemError(hr).toString();
return false;
}
// Get audio data and write it to the allocated buffer in |audio_data|. The playout latency is
// not updated for each callback.
onDataRequest(reinterpret_cast<int16_t*>(audio_data), num_requested_frames * kChannels);
// Release the buffer space acquired in IAudioRenderClient::GetBuffer.
hr = audio_render_client_->ReleaseBuffer(num_requested_frames, 0);
if (FAILED(hr))
{
LOG(LS_ERROR) << "IAudioRenderClient::ReleaseBuffer failed: "
<< SystemError(hr).toString();
return false;
}
num_frames_written_ += num_requested_frames;
return true;
}
bool AudioOutputWin::handleRestartEvent()
{
DCHECK(audio_thread_);
DCHECK(is_restarting_);
if (!is_initialized_ || !is_active_)
return true;
if (!stop())
return false;
if (!init())
return false;
if (!start())
return false;
return true;
}
void AudioOutputWin::stopThread()
{
DCHECK(!is_restarting_);
if (audio_thread_)
{
if (audio_thread_->isRunning())
{
SetEvent(stop_event_);
audio_thread_->stop();
}
audio_thread_.reset();
// Ensure that we don't quit the main thread loop immediately next time start() is called.
ResetEvent(stop_event_);
ResetEvent(restart_event_);
}
}
void AudioOutputWin::releaseCOMObjects()
{
if (audio_client_)
audio_client_.Reset();
if (audio_session_control_.Get())
audio_session_control_.Reset();
if (audio_render_client_.Get())
audio_render_client_.Reset();
}
ULONG AudioOutputWin::AddRef()
{
ULONG new_ref = InterlockedIncrement(&ref_count_);
return new_ref;
}
ULONG AudioOutputWin::Release()
{
ULONG new_ref = InterlockedDecrement(&ref_count_);
return new_ref;
}
HRESULT AudioOutputWin::QueryInterface(REFIID iid, void** object)
{
if (object == nullptr)
return E_POINTER;
if (iid == IID_IUnknown || iid == __uuidof(IAudioSessionEvents))
{
*object = static_cast<IAudioSessionEvents*>(this);
return S_OK;
};
*object = nullptr;
return E_NOINTERFACE;
}
HRESULT AudioOutputWin::OnStateChanged(AudioSessionState new_state)
{
return S_OK;
}
HRESULT AudioOutputWin::OnSessionDisconnected(AudioSessionDisconnectReason disconnect_reason)
{
if (is_restarting_)
{
DLOG(LS_WARNING) << "Ignoring since restart is already active";
return S_OK;
}
// Internal test method which can be used in tests to emulate a restart signal. It simply sets
// the same event which is normally triggered by session and device notifications. Hence, the
// emulated restart sequence covers most parts of a real sequence expect the actual device
// switch.
if (disconnect_reason == DisconnectReasonDeviceRemoval ||
disconnect_reason == DisconnectReasonFormatChanged)
{
is_restarting_ = true;
SetEvent(restart_event_);
}
return S_OK;
}
HRESULT AudioOutputWin::OnDisplayNameChanged(LPCWSTR new_display_name, LPCGUID event_context)
{
return S_OK;
}
HRESULT AudioOutputWin::OnIconPathChanged(LPCWSTR new_icon_path, LPCGUID event_context)
{
return S_OK;
}
HRESULT AudioOutputWin::OnSimpleVolumeChanged(
float new_simple_volume, BOOL new_mute, LPCGUID event_context)
{
return S_OK;
}
HRESULT AudioOutputWin::OnChannelVolumeChanged(
DWORD channel_count, float new_channel_volumes[], DWORD changed_channel, LPCGUID event_context)
{
return S_OK;
}
HRESULT AudioOutputWin::OnGroupingParamChanged(LPCGUID new_grouping_param, LPCGUID event_context)
{
return S_OK;
}
} // namespace base
<commit_msg>Set priority for audio thread.<commit_after>//
// Aspia Project
// Copyright (C) 2020 Dmitry Chapyshev <dmitry@aspia.ru>
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <https://www.gnu.org/licenses/>.
//
#include "base/audio/audio_output_win.h"
#include "base/logging.h"
#include "base/audio/win/audio_util_win.h"
#include "base/audio/win/scoped_mmcss_registration.h"
#include "base/threading/simple_thread.h"
#include "base/win/scoped_com_initializer.h"
namespace base {
namespace {
const char* sessionStateToString(AudioSessionState state)
{
switch (state)
{
case AudioSessionStateActive:
return "Active";
case AudioSessionStateInactive:
return "Inactive";
case AudioSessionStateExpired:
return "Expired";
default:
return "Invalid";
}
}
} // namespace
AudioOutputWin::AudioOutputWin(const NeedMoreDataCB& need_more_data_cb)
: AudioOutput(need_more_data_cb)
{
// Create the event which the audio engine will signal each time a buffer becomes ready to be
// processed by the client.
audio_samples_event_.reset(CreateEventW(nullptr, false, false, nullptr));
DCHECK(audio_samples_event_.isValid());
// Event to be set in Stop() when rendering/capturing shall stop.
stop_event_.reset(CreateEventW(nullptr, false, false, nullptr));
DCHECK(stop_event_.isValid());
// Event to be set when it has been detected that an active device has been invalidated or the
// stream format has changed.
restart_event_.reset(CreateEventW(nullptr, false, false, nullptr));
DCHECK(restart_event_.isValid());
is_initialized_ = init();
}
AudioOutputWin::~AudioOutputWin()
{
stop();
}
bool AudioOutputWin::start()
{
if (!is_initialized_)
return false;
if (is_restarting_)
{
DCHECK(audio_thread_);
}
if (!fillRenderEndpointBufferWithSilence(audio_client_.Get(), audio_render_client_.Get()))
{
LOG(LS_WARNING) << "Failed to prepare output endpoint with silence";
}
num_frames_written_ = endpoint_buffer_size_frames_;
if (!audio_thread_)
{
audio_thread_ = std::make_unique<SimpleThread>();
audio_thread_->start(std::bind(&AudioOutputWin::threadRun, this));
if (!audio_thread_->isRunning())
{
stopThread();
LOG(LS_ERROR) << "Failed to start audio thread";
return false;
}
}
HRESULT hr = audio_client_->Start();
if (FAILED(hr))
{
stopThread();
LOG(LS_ERROR) << "IAudioClient::Start failed: " << SystemError(hr).toString();
return false;
}
is_active_ = true;
return true;
}
bool AudioOutputWin::stop()
{
if (!is_initialized_)
return true;
if (!is_active_)
{
DLOG(LS_WARNING) << "No output stream is active";
releaseCOMObjects();
is_initialized_ = false;
return true;
}
// Stop audio streaming.
HRESULT hr = audio_client_->Stop();
if (FAILED(hr))
{
LOG(LS_ERROR) << "IAudioClient::Stop failed: " << SystemError(hr).toString();
}
// Stop and destroy the audio thread but only when a restart attempt is not ongoing.
if (!is_restarting_)
stopThread();
hr = audio_client_->Reset();
if (FAILED(hr))
{
LOG(LS_ERROR) << "IAudioClient::Reset failed: " << SystemError(hr).toString();
}
// Extra safety check to ensure that the buffers are cleared. If the buffers are not cleared
// correctly, the next call to start() would fail with AUDCLNT_E_BUFFER_ERROR at
// IAudioRenderClient::GetBuffer().
UINT32 num_queued_frames = 0;
audio_client_->GetCurrentPadding(&num_queued_frames);
DCHECK_EQ(0u, num_queued_frames);
// Release all allocated COM interfaces to allow for a restart without intermediate destruction.
releaseCOMObjects();
return true;
}
void AudioOutputWin::threadRun()
{
if (!isMMCSSSupported())
{
LOG(LS_ERROR) << "MMCSS is not supported";
return;
}
SetThreadPriority(GetCurrentThread(), THREAD_PRIORITY_TIME_CRITICAL);
ScopedMMCSSRegistration mmcss_registration(L"Pro Audio");
win::ScopedCOMInitializer com_initializer(win::ScopedCOMInitializer::kMTA);
DCHECK(mmcss_registration.isSucceeded());
DCHECK(com_initializer.isSucceeded());
DCHECK(stop_event_.isValid());
DCHECK(audio_samples_event_.isValid());
bool streaming = true;
bool error = false;
HANDLE wait_array[] = { stop_event_.get(), restart_event_.get(), audio_samples_event_.get() };
// Keep streaming audio until the stop event or the stream-switch event
// is signaled. An error event can also break the main thread loop.
while (streaming && !error)
{
// Wait for a close-down event, stream-switch event or a new render event.
DWORD wait_result = WaitForMultipleObjects(
std::size(wait_array), wait_array, false, INFINITE);
switch (wait_result)
{
case WAIT_OBJECT_0 + 0:
// |stop_event_| has been set.
streaming = false;
break;
case WAIT_OBJECT_0 + 1:
// |restart_event_| has been set.
error = !handleRestartEvent();
break;
case WAIT_OBJECT_0 + 2:
// |audio_samples_event_| has been set.
error = !handleDataRequest();
break;
default:
error = true;
break;
}
}
if (streaming && error)
{
LOG(LS_ERROR) << "WASAPI streaming failed";
// Stop audio streaming since something has gone wrong in our main thread loop. Note that,
// we are still in a "started" state, hence a stop() call is required to join the thread
// properly.
HRESULT hr = audio_client_->Stop();
if (FAILED(hr))
{
LOG(LS_ERROR) << "IAudioClient::Stop failed: " << SystemError(hr).toString();
}
}
}
bool AudioOutputWin::init()
{
Microsoft::WRL::ComPtr<IMMDevice> device(createDevice());
if (!device.Get())
return false;
Microsoft::WRL::ComPtr<IAudioClient> audio_client = createClient(device.Get());
if (!audio_client.Get())
return false;
// Define the output WAVEFORMATEXTENSIBLE format in |format_|.
WAVEFORMATEXTENSIBLE format_extensible;
memset(&format_extensible, 0, sizeof(format_extensible));
WAVEFORMATEX& format = format_extensible.Format;
format.wFormatTag = WAVE_FORMAT_EXTENSIBLE;
format.nChannels = kChannels;
format.nSamplesPerSec = kSampleRate;
format.wBitsPerSample = kBitsPerSample;
format.nBlockAlign = (format.wBitsPerSample / 8) * format.nChannels;
format.nAvgBytesPerSec = format.nSamplesPerSec * format.nBlockAlign;
format.cbSize = sizeof(WAVEFORMATEXTENSIBLE) - sizeof(WAVEFORMATEX);
// Add the parts which are unique for the WAVE_FORMAT_EXTENSIBLE structure.
format_extensible.Samples.wValidBitsPerSample = kBitsPerSample;
format_extensible.dwChannelMask = KSAUDIO_SPEAKER_STEREO;
format_extensible.SubFormat = KSDATAFORMAT_SUBTYPE_PCM;
if (!isFormatSupported(audio_client.Get(), AUDCLNT_SHAREMODE_SHARED, &format_extensible))
return false;
// Initialize the audio stream between the client and the device in shared mode using
// event-driven buffer handling. Also, using 0 as requested buffer size results in a default
// (minimum) endpoint buffer size.
const REFERENCE_TIME requested_buffer_size = 0;
if (!sharedModeInitialize(audio_client.Get(), &format_extensible, audio_samples_event_,
requested_buffer_size, true, &endpoint_buffer_size_frames_))
{
return false;
}
// Create an IAudioRenderClient for an initialized IAudioClient. The IAudioRenderClient
// interface enables us to write output data to a rendering endpoint buffer.
Microsoft::WRL::ComPtr<IAudioRenderClient> audio_render_client =
createRenderClient(audio_client.Get());
if (!audio_render_client.Get())
return false;
// Create an AudioSessionControl interface given the initialized client. The IAudioControl
// interface enables a client to configure the control parameters for an audio session and to
// monitor events in the session.
Microsoft::WRL::ComPtr<IAudioSessionControl> audio_session_control =
createAudioSessionControl(audio_client.Get());
if (!audio_session_control.Get())
return false;
// The Sndvol program displays volume and mute controls for sessions that are in the active and
// inactive states.
AudioSessionState state;
if (FAILED(audio_session_control->GetState(&state)))
return false;
LOG(LS_INFO) << "Audio session state: " << sessionStateToString(state);
// Register the client to receive notifications of session events, including changes in the
// stream state.
if (FAILED(audio_session_control->RegisterAudioSessionNotification(this)))
{
LOG(LS_ERROR) << "IAudioSessionControl::RegisterAudioSessionNotification failed";
return false;
}
// Store valid COM interfaces.
audio_client_ = audio_client;
audio_render_client_ = audio_render_client;
audio_session_control_ = audio_session_control;
return true;
}
bool AudioOutputWin::handleDataRequest()
{
// Get the padding value which indicates the amount of valid unread data that the endpoint
// buffer currently contains.
UINT32 num_unread_frames = 0;
HRESULT hr = audio_client_->GetCurrentPadding(&num_unread_frames);
if (hr == AUDCLNT_E_DEVICE_INVALIDATED)
{
// Avoid breaking the thread loop implicitly by returning false and return true instead for
// AUDCLNT_E_DEVICE_INVALIDATED even it is a valid error message. We will use notifications
// about device changes instead to stop data callbacks and attempt to restart streaming.
DLOG(LS_ERROR) << "AUDCLNT_E_DEVICE_INVALIDATED";
return true;
}
if (FAILED(hr))
{
LOG(LS_ERROR) << "IAudioClient::GetCurrentPadding failed: " << SystemError(hr).toString();
return false;
}
// Contains how much new data we can write to the buffer without the risk of overwriting
// previously written data that the audio engine has not yet read from the buffer. I.e., it is
// the maximum buffer size we can request when calling IAudioRenderClient::GetBuffer().
UINT32 num_requested_frames = endpoint_buffer_size_frames_ - num_unread_frames;
if (num_requested_frames == 0)
{
DLOG(LS_WARNING) << "Audio thread is signaled but no new audio samples are needed";
return true;
}
// Request all available space in the rendering endpoint buffer into which the client can later
// write an audio packet.
uint8_t* audio_data;
hr = audio_render_client_->GetBuffer(num_requested_frames, &audio_data);
if (FAILED(hr))
{
LOG(LS_ERROR) << "IAudioRenderClient::GetBuffer failed: " << SystemError(hr).toString();
return false;
}
// Get audio data and write it to the allocated buffer in |audio_data|. The playout latency is
// not updated for each callback.
onDataRequest(reinterpret_cast<int16_t*>(audio_data), num_requested_frames * kChannels);
// Release the buffer space acquired in IAudioRenderClient::GetBuffer.
hr = audio_render_client_->ReleaseBuffer(num_requested_frames, 0);
if (FAILED(hr))
{
LOG(LS_ERROR) << "IAudioRenderClient::ReleaseBuffer failed: "
<< SystemError(hr).toString();
return false;
}
num_frames_written_ += num_requested_frames;
return true;
}
bool AudioOutputWin::handleRestartEvent()
{
DCHECK(audio_thread_);
DCHECK(is_restarting_);
if (!is_initialized_ || !is_active_)
return true;
if (!stop())
return false;
if (!init())
return false;
if (!start())
return false;
return true;
}
void AudioOutputWin::stopThread()
{
DCHECK(!is_restarting_);
if (audio_thread_)
{
if (audio_thread_->isRunning())
{
SetEvent(stop_event_);
audio_thread_->stop();
}
audio_thread_.reset();
// Ensure that we don't quit the main thread loop immediately next time start() is called.
ResetEvent(stop_event_);
ResetEvent(restart_event_);
}
}
void AudioOutputWin::releaseCOMObjects()
{
if (audio_client_)
audio_client_.Reset();
if (audio_session_control_.Get())
audio_session_control_.Reset();
if (audio_render_client_.Get())
audio_render_client_.Reset();
}
ULONG AudioOutputWin::AddRef()
{
ULONG new_ref = InterlockedIncrement(&ref_count_);
return new_ref;
}
ULONG AudioOutputWin::Release()
{
ULONG new_ref = InterlockedDecrement(&ref_count_);
return new_ref;
}
HRESULT AudioOutputWin::QueryInterface(REFIID iid, void** object)
{
if (object == nullptr)
return E_POINTER;
if (iid == IID_IUnknown || iid == __uuidof(IAudioSessionEvents))
{
*object = static_cast<IAudioSessionEvents*>(this);
return S_OK;
};
*object = nullptr;
return E_NOINTERFACE;
}
HRESULT AudioOutputWin::OnStateChanged(AudioSessionState new_state)
{
return S_OK;
}
HRESULT AudioOutputWin::OnSessionDisconnected(AudioSessionDisconnectReason disconnect_reason)
{
if (is_restarting_)
{
DLOG(LS_WARNING) << "Ignoring since restart is already active";
return S_OK;
}
// Internal test method which can be used in tests to emulate a restart signal. It simply sets
// the same event which is normally triggered by session and device notifications. Hence, the
// emulated restart sequence covers most parts of a real sequence expect the actual device
// switch.
if (disconnect_reason == DisconnectReasonDeviceRemoval ||
disconnect_reason == DisconnectReasonFormatChanged)
{
is_restarting_ = true;
SetEvent(restart_event_);
}
return S_OK;
}
HRESULT AudioOutputWin::OnDisplayNameChanged(LPCWSTR new_display_name, LPCGUID event_context)
{
return S_OK;
}
HRESULT AudioOutputWin::OnIconPathChanged(LPCWSTR new_icon_path, LPCGUID event_context)
{
return S_OK;
}
HRESULT AudioOutputWin::OnSimpleVolumeChanged(
float new_simple_volume, BOOL new_mute, LPCGUID event_context)
{
return S_OK;
}
HRESULT AudioOutputWin::OnChannelVolumeChanged(
DWORD channel_count, float new_channel_volumes[], DWORD changed_channel, LPCGUID event_context)
{
return S_OK;
}
HRESULT AudioOutputWin::OnGroupingParamChanged(LPCGUID new_grouping_param, LPCGUID event_context)
{
return S_OK;
}
} // namespace base
<|endoftext|> |
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: property.cxx,v $
*
* $Revision: 1.17 $
*
* last change: $Author: kz $ $Date: 2007-05-10 09:59:17 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_forms.hxx"
#ifndef FRM_STRINGS_HXX
#include "frm_strings.hxx"
#endif
#ifndef _FRM_PROPERTY_HXX_
#include "property.hxx"
#endif
#ifndef _FRM_PROPERTY_HRC_
#include "property.hrc"
#endif
#ifndef _CPPUHELPER_QUERYINTERFACE_HXX_
#include <cppuhelper/queryinterface.hxx>
#endif
#ifndef _TOOLS_DEBUG_HXX
#include <tools/debug.hxx>
#endif
#ifndef _COM_SUN_STAR_BEANS_PROPERTYATTRIBUTE_HPP_
#include <com/sun/star/beans/PropertyAttribute.hpp>
#endif
#include <algorithm>
//... namespace frm .......................................................
namespace frm
{
//.........................................................................
//==================================================================
//= PropertyInfoService
//==================================================================
PropertyInfoService::PropertyMap PropertyInfoService::s_AllKnownProperties;
//------------------------------------------------------------------
sal_Int32 PropertyInfoService::getPropertyId(const ::rtl::OUString& _rName)
{
initialize();
PropertyAssignment aCompareName(_rName, -1);
::std::pair<PropertyMapIterator,PropertyMapIterator> aPair = equal_range(
s_AllKnownProperties.begin(),
s_AllKnownProperties.end(),
aCompareName,
PropertyAssignmentNameCompareLess());
sal_Int32 nHandle = -1;
if (aPair.first != aPair.second)
{ // we found something _and_ we have an identity
nHandle = aPair.first->nHandle;
}
return nHandle;
}
//------------------------------------------------------------------
sal_Int32 ConcreteInfoService::getPreferedPropertyId(const ::rtl::OUString& _rName)
{
return PropertyInfoService::getPropertyId(_rName);
}
//------------------------------------------------------------------
#define ADD_PROP_ASSIGNMENT(varname) \
s_AllKnownProperties.push_back(PropertyAssignment(PROPERTY_##varname, PROPERTY_ID_##varname))
//..................................................................
void PropertyInfoService::initialize()
{
if (!s_AllKnownProperties.empty())
return;
s_AllKnownProperties.reserve(220);
ADD_PROP_ASSIGNMENT(NAME);
ADD_PROP_ASSIGNMENT(TAG);
ADD_PROP_ASSIGNMENT(TABINDEX);
ADD_PROP_ASSIGNMENT(CLASSID);
ADD_PROP_ASSIGNMENT(ALIGN);
ADD_PROP_ASSIGNMENT(FETCHSIZE);
ADD_PROP_ASSIGNMENT(VALUE);
ADD_PROP_ASSIGNMENT(VALUEMIN);
ADD_PROP_ASSIGNMENT(VALUEMAX);
ADD_PROP_ASSIGNMENT(VALUESTEP);
ADD_PROP_ASSIGNMENT(TEXT);
ADD_PROP_ASSIGNMENT(LABEL);
ADD_PROP_ASSIGNMENT(NAVIGATION);
ADD_PROP_ASSIGNMENT(CYCLE);
ADD_PROP_ASSIGNMENT(CONTROLSOURCE);
ADD_PROP_ASSIGNMENT(ENABLED);
ADD_PROP_ASSIGNMENT(SPIN);
ADD_PROP_ASSIGNMENT(READONLY);
ADD_PROP_ASSIGNMENT(FILTER);
ADD_PROP_ASSIGNMENT(WIDTH);
ADD_PROP_ASSIGNMENT(SEARCHABLE);
ADD_PROP_ASSIGNMENT(MULTILINE);
ADD_PROP_ASSIGNMENT(TARGET_URL);
ADD_PROP_ASSIGNMENT(DEFAULTCONTROL);
ADD_PROP_ASSIGNMENT(MAXTEXTLEN);
ADD_PROP_ASSIGNMENT(SIZE);
ADD_PROP_ASSIGNMENT(DATE);
ADD_PROP_ASSIGNMENT(TIME);
ADD_PROP_ASSIGNMENT(STATE);
ADD_PROP_ASSIGNMENT(TRISTATE);
ADD_PROP_ASSIGNMENT(HIDDEN_VALUE);
ADD_PROP_ASSIGNMENT(TARGET_FRAME);
ADD_PROP_ASSIGNMENT(BUTTONTYPE);
ADD_PROP_ASSIGNMENT(STRINGITEMLIST);
ADD_PROP_ASSIGNMENT(DEFAULT_TEXT);
ADD_PROP_ASSIGNMENT(DEFAULTCHECKED);
ADD_PROP_ASSIGNMENT(DEFAULT_DATE);
ADD_PROP_ASSIGNMENT(DEFAULT_TIME);
ADD_PROP_ASSIGNMENT(DEFAULT_VALUE);
ADD_PROP_ASSIGNMENT(FORMATKEY);
ADD_PROP_ASSIGNMENT(FORMATSSUPPLIER);
ADD_PROP_ASSIGNMENT(SUBMIT_ACTION);
ADD_PROP_ASSIGNMENT(SUBMIT_TARGET);
ADD_PROP_ASSIGNMENT(SUBMIT_METHOD);
ADD_PROP_ASSIGNMENT(SUBMIT_ENCODING);
ADD_PROP_ASSIGNMENT(IMAGE_URL);
ADD_PROP_ASSIGNMENT(EMPTY_IS_NULL);
ADD_PROP_ASSIGNMENT(LISTSOURCETYPE);
ADD_PROP_ASSIGNMENT(LISTSOURCE);
ADD_PROP_ASSIGNMENT(SELECT_SEQ);
ADD_PROP_ASSIGNMENT(VALUE_SEQ);
ADD_PROP_ASSIGNMENT(DEFAULT_SELECT_SEQ);
ADD_PROP_ASSIGNMENT(MULTISELECTION);
ADD_PROP_ASSIGNMENT(DECIMAL_ACCURACY);
ADD_PROP_ASSIGNMENT(EDITMASK);
ADD_PROP_ASSIGNMENT(ISREADONLY);
ADD_PROP_ASSIGNMENT(FIELDTYPE);
ADD_PROP_ASSIGNMENT(DECIMALS);
ADD_PROP_ASSIGNMENT(REFVALUE);
ADD_PROP_ASSIGNMENT(STRICTFORMAT);
ADD_PROP_ASSIGNMENT(DATASOURCE);
ADD_PROP_ASSIGNMENT(ALLOWADDITIONS);
ADD_PROP_ASSIGNMENT(ALLOWEDITS);
ADD_PROP_ASSIGNMENT(ALLOWDELETIONS);
ADD_PROP_ASSIGNMENT(MASTERFIELDS);
ADD_PROP_ASSIGNMENT(ISPASSTHROUGH);
ADD_PROP_ASSIGNMENT(QUERY);
ADD_PROP_ASSIGNMENT(LITERALMASK);
ADD_PROP_ASSIGNMENT(SHOWTHOUSANDSEP);
ADD_PROP_ASSIGNMENT(CURRENCYSYMBOL);
ADD_PROP_ASSIGNMENT(DATEFORMAT);
ADD_PROP_ASSIGNMENT(DATEMIN);
ADD_PROP_ASSIGNMENT(DATEMAX);
ADD_PROP_ASSIGNMENT(DATE_SHOW_CENTURY);
ADD_PROP_ASSIGNMENT(TIMEFORMAT);
ADD_PROP_ASSIGNMENT(TIMEMIN);
ADD_PROP_ASSIGNMENT(TIMEMAX);
ADD_PROP_ASSIGNMENT(LINECOUNT);
ADD_PROP_ASSIGNMENT(BOUNDCOLUMN);
ADD_PROP_ASSIGNMENT(HASNAVIGATION);
ADD_PROP_ASSIGNMENT(FONT);
ADD_PROP_ASSIGNMENT(BACKGROUNDCOLOR);
ADD_PROP_ASSIGNMENT(FILLCOLOR);
ADD_PROP_ASSIGNMENT(TEXTCOLOR);
ADD_PROP_ASSIGNMENT(LINECOLOR);
ADD_PROP_ASSIGNMENT(BORDER);
ADD_PROP_ASSIGNMENT(DROPDOWN);
ADD_PROP_ASSIGNMENT(HSCROLL);
ADD_PROP_ASSIGNMENT(VSCROLL);
ADD_PROP_ASSIGNMENT(TABSTOP);
ADD_PROP_ASSIGNMENT(AUTOCOMPLETE);
ADD_PROP_ASSIGNMENT(HARDLINEBREAKS);
ADD_PROP_ASSIGNMENT(PRINTABLE);
ADD_PROP_ASSIGNMENT(ECHO_CHAR);
ADD_PROP_ASSIGNMENT(ROWHEIGHT);
ADD_PROP_ASSIGNMENT(HELPTEXT);
ADD_PROP_ASSIGNMENT(FONT_NAME);
ADD_PROP_ASSIGNMENT(FONT_STYLENAME);
ADD_PROP_ASSIGNMENT(FONT_FAMILY);
ADD_PROP_ASSIGNMENT(FONT_CHARSET);
ADD_PROP_ASSIGNMENT(FONT_HEIGHT);
ADD_PROP_ASSIGNMENT(FONT_WEIGHT);
ADD_PROP_ASSIGNMENT(FONT_SLANT);
ADD_PROP_ASSIGNMENT(FONT_UNDERLINE);
ADD_PROP_ASSIGNMENT(FONT_WORDLINEMODE);
ADD_PROP_ASSIGNMENT(FONT_STRIKEOUT);
ADD_PROP_ASSIGNMENT(TEXTLINECOLOR);
ADD_PROP_ASSIGNMENT(FONTEMPHASISMARK);
ADD_PROP_ASSIGNMENT(FONTRELIEF);
ADD_PROP_ASSIGNMENT(HELPURL);
ADD_PROP_ASSIGNMENT(RECORDMARKER);
ADD_PROP_ASSIGNMENT(BOUNDFIELD);
ADD_PROP_ASSIGNMENT(TREATASNUMERIC);
ADD_PROP_ASSIGNMENT(EFFECTIVE_VALUE);
ADD_PROP_ASSIGNMENT(EFFECTIVE_DEFAULT);
ADD_PROP_ASSIGNMENT(EFFECTIVE_MIN);
ADD_PROP_ASSIGNMENT(EFFECTIVE_MAX);
ADD_PROP_ASSIGNMENT(HIDDEN);
ADD_PROP_ASSIGNMENT(FILTERPROPOSAL);
ADD_PROP_ASSIGNMENT(FIELDSOURCE);
ADD_PROP_ASSIGNMENT(TABLENAME);
ADD_PROP_ASSIGNMENT(CONTROLLABEL);
ADD_PROP_ASSIGNMENT(CURRSYM_POSITION);
ADD_PROP_ASSIGNMENT(CURSORCOLOR);
ADD_PROP_ASSIGNMENT(ALWAYSSHOWCURSOR);
ADD_PROP_ASSIGNMENT(DISPLAYSYNCHRON);
ADD_PROP_ASSIGNMENT(ISMODIFIED);
ADD_PROP_ASSIGNMENT(ISNEW);
ADD_PROP_ASSIGNMENT(PRIVILEGES);
ADD_PROP_ASSIGNMENT(DETAILFIELDS);
ADD_PROP_ASSIGNMENT(COMMAND);
ADD_PROP_ASSIGNMENT(COMMANDTYPE);
ADD_PROP_ASSIGNMENT(RESULTSET_CONCURRENCY);
ADD_PROP_ASSIGNMENT(INSERTONLY);
ADD_PROP_ASSIGNMENT(RESULTSET_TYPE);
ADD_PROP_ASSIGNMENT(ESCAPE_PROCESSING);
ADD_PROP_ASSIGNMENT(APPLYFILTER);
ADD_PROP_ASSIGNMENT(ISNULLABLE);
ADD_PROP_ASSIGNMENT(ACTIVECOMMAND);
ADD_PROP_ASSIGNMENT(ISCURRENCY);
ADD_PROP_ASSIGNMENT(URL);
ADD_PROP_ASSIGNMENT(TITLE);
ADD_PROP_ASSIGNMENT(ACTIVE_CONNECTION);
ADD_PROP_ASSIGNMENT(SCALE);
ADD_PROP_ASSIGNMENT(SORT);
ADD_PROP_ASSIGNMENT(PERSISTENCE_MAXTEXTLENGTH);
ADD_PROP_ASSIGNMENT(SCROLL_VALUE);
ADD_PROP_ASSIGNMENT(SPIN_VALUE);
ADD_PROP_ASSIGNMENT(DEFAULT_SCROLL_VALUE);
ADD_PROP_ASSIGNMENT(DEFAULT_SPIN_VALUE);
// now sort the array by name
std::sort(
s_AllKnownProperties.begin(),
s_AllKnownProperties.end(),
PropertyAssignmentNameCompareLess()
);
}
//.........................................................................
}
//... namespace frm .......................................................
<commit_msg>INTEGRATION: CWS changefileheader (1.17.78); FILE MERGED 2008/04/01 15:16:37 thb 1.17.78.3: #i85898# Stripping all external header guards 2008/04/01 12:30:29 thb 1.17.78.2: #i85898# Stripping all external header guards 2008/03/31 13:11:40 rt 1.17.78.1: #i87441# Change license header to LPGL v3.<commit_after>/*************************************************************************
*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* Copyright 2008 by Sun Microsystems, Inc.
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: property.cxx,v $
* $Revision: 1.18 $
*
* This file is part of OpenOffice.org.
*
* OpenOffice.org is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License version 3
* only, as published by the Free Software Foundation.
*
* OpenOffice.org is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License version 3 for more details
* (a copy is included in the LICENSE file that accompanied this code).
*
* You should have received a copy of the GNU Lesser General Public License
* version 3 along with OpenOffice.org. If not, see
* <http://www.openoffice.org/license.html>
* for a copy of the LGPLv3 License.
*
************************************************************************/
// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_forms.hxx"
#include "frm_strings.hxx"
#include "property.hxx"
#ifndef _FRM_PROPERTY_HRC_
#include "property.hrc"
#endif
#include <cppuhelper/queryinterface.hxx>
#include <tools/debug.hxx>
#include <com/sun/star/beans/PropertyAttribute.hpp>
#include <algorithm>
//... namespace frm .......................................................
namespace frm
{
//.........................................................................
//==================================================================
//= PropertyInfoService
//==================================================================
PropertyInfoService::PropertyMap PropertyInfoService::s_AllKnownProperties;
//------------------------------------------------------------------
sal_Int32 PropertyInfoService::getPropertyId(const ::rtl::OUString& _rName)
{
initialize();
PropertyAssignment aCompareName(_rName, -1);
::std::pair<PropertyMapIterator,PropertyMapIterator> aPair = equal_range(
s_AllKnownProperties.begin(),
s_AllKnownProperties.end(),
aCompareName,
PropertyAssignmentNameCompareLess());
sal_Int32 nHandle = -1;
if (aPair.first != aPair.second)
{ // we found something _and_ we have an identity
nHandle = aPair.first->nHandle;
}
return nHandle;
}
//------------------------------------------------------------------
sal_Int32 ConcreteInfoService::getPreferedPropertyId(const ::rtl::OUString& _rName)
{
return PropertyInfoService::getPropertyId(_rName);
}
//------------------------------------------------------------------
#define ADD_PROP_ASSIGNMENT(varname) \
s_AllKnownProperties.push_back(PropertyAssignment(PROPERTY_##varname, PROPERTY_ID_##varname))
//..................................................................
void PropertyInfoService::initialize()
{
if (!s_AllKnownProperties.empty())
return;
s_AllKnownProperties.reserve(220);
ADD_PROP_ASSIGNMENT(NAME);
ADD_PROP_ASSIGNMENT(TAG);
ADD_PROP_ASSIGNMENT(TABINDEX);
ADD_PROP_ASSIGNMENT(CLASSID);
ADD_PROP_ASSIGNMENT(ALIGN);
ADD_PROP_ASSIGNMENT(FETCHSIZE);
ADD_PROP_ASSIGNMENT(VALUE);
ADD_PROP_ASSIGNMENT(VALUEMIN);
ADD_PROP_ASSIGNMENT(VALUEMAX);
ADD_PROP_ASSIGNMENT(VALUESTEP);
ADD_PROP_ASSIGNMENT(TEXT);
ADD_PROP_ASSIGNMENT(LABEL);
ADD_PROP_ASSIGNMENT(NAVIGATION);
ADD_PROP_ASSIGNMENT(CYCLE);
ADD_PROP_ASSIGNMENT(CONTROLSOURCE);
ADD_PROP_ASSIGNMENT(ENABLED);
ADD_PROP_ASSIGNMENT(SPIN);
ADD_PROP_ASSIGNMENT(READONLY);
ADD_PROP_ASSIGNMENT(FILTER);
ADD_PROP_ASSIGNMENT(WIDTH);
ADD_PROP_ASSIGNMENT(SEARCHABLE);
ADD_PROP_ASSIGNMENT(MULTILINE);
ADD_PROP_ASSIGNMENT(TARGET_URL);
ADD_PROP_ASSIGNMENT(DEFAULTCONTROL);
ADD_PROP_ASSIGNMENT(MAXTEXTLEN);
ADD_PROP_ASSIGNMENT(SIZE);
ADD_PROP_ASSIGNMENT(DATE);
ADD_PROP_ASSIGNMENT(TIME);
ADD_PROP_ASSIGNMENT(STATE);
ADD_PROP_ASSIGNMENT(TRISTATE);
ADD_PROP_ASSIGNMENT(HIDDEN_VALUE);
ADD_PROP_ASSIGNMENT(TARGET_FRAME);
ADD_PROP_ASSIGNMENT(BUTTONTYPE);
ADD_PROP_ASSIGNMENT(STRINGITEMLIST);
ADD_PROP_ASSIGNMENT(DEFAULT_TEXT);
ADD_PROP_ASSIGNMENT(DEFAULTCHECKED);
ADD_PROP_ASSIGNMENT(DEFAULT_DATE);
ADD_PROP_ASSIGNMENT(DEFAULT_TIME);
ADD_PROP_ASSIGNMENT(DEFAULT_VALUE);
ADD_PROP_ASSIGNMENT(FORMATKEY);
ADD_PROP_ASSIGNMENT(FORMATSSUPPLIER);
ADD_PROP_ASSIGNMENT(SUBMIT_ACTION);
ADD_PROP_ASSIGNMENT(SUBMIT_TARGET);
ADD_PROP_ASSIGNMENT(SUBMIT_METHOD);
ADD_PROP_ASSIGNMENT(SUBMIT_ENCODING);
ADD_PROP_ASSIGNMENT(IMAGE_URL);
ADD_PROP_ASSIGNMENT(EMPTY_IS_NULL);
ADD_PROP_ASSIGNMENT(LISTSOURCETYPE);
ADD_PROP_ASSIGNMENT(LISTSOURCE);
ADD_PROP_ASSIGNMENT(SELECT_SEQ);
ADD_PROP_ASSIGNMENT(VALUE_SEQ);
ADD_PROP_ASSIGNMENT(DEFAULT_SELECT_SEQ);
ADD_PROP_ASSIGNMENT(MULTISELECTION);
ADD_PROP_ASSIGNMENT(DECIMAL_ACCURACY);
ADD_PROP_ASSIGNMENT(EDITMASK);
ADD_PROP_ASSIGNMENT(ISREADONLY);
ADD_PROP_ASSIGNMENT(FIELDTYPE);
ADD_PROP_ASSIGNMENT(DECIMALS);
ADD_PROP_ASSIGNMENT(REFVALUE);
ADD_PROP_ASSIGNMENT(STRICTFORMAT);
ADD_PROP_ASSIGNMENT(DATASOURCE);
ADD_PROP_ASSIGNMENT(ALLOWADDITIONS);
ADD_PROP_ASSIGNMENT(ALLOWEDITS);
ADD_PROP_ASSIGNMENT(ALLOWDELETIONS);
ADD_PROP_ASSIGNMENT(MASTERFIELDS);
ADD_PROP_ASSIGNMENT(ISPASSTHROUGH);
ADD_PROP_ASSIGNMENT(QUERY);
ADD_PROP_ASSIGNMENT(LITERALMASK);
ADD_PROP_ASSIGNMENT(SHOWTHOUSANDSEP);
ADD_PROP_ASSIGNMENT(CURRENCYSYMBOL);
ADD_PROP_ASSIGNMENT(DATEFORMAT);
ADD_PROP_ASSIGNMENT(DATEMIN);
ADD_PROP_ASSIGNMENT(DATEMAX);
ADD_PROP_ASSIGNMENT(DATE_SHOW_CENTURY);
ADD_PROP_ASSIGNMENT(TIMEFORMAT);
ADD_PROP_ASSIGNMENT(TIMEMIN);
ADD_PROP_ASSIGNMENT(TIMEMAX);
ADD_PROP_ASSIGNMENT(LINECOUNT);
ADD_PROP_ASSIGNMENT(BOUNDCOLUMN);
ADD_PROP_ASSIGNMENT(HASNAVIGATION);
ADD_PROP_ASSIGNMENT(FONT);
ADD_PROP_ASSIGNMENT(BACKGROUNDCOLOR);
ADD_PROP_ASSIGNMENT(FILLCOLOR);
ADD_PROP_ASSIGNMENT(TEXTCOLOR);
ADD_PROP_ASSIGNMENT(LINECOLOR);
ADD_PROP_ASSIGNMENT(BORDER);
ADD_PROP_ASSIGNMENT(DROPDOWN);
ADD_PROP_ASSIGNMENT(HSCROLL);
ADD_PROP_ASSIGNMENT(VSCROLL);
ADD_PROP_ASSIGNMENT(TABSTOP);
ADD_PROP_ASSIGNMENT(AUTOCOMPLETE);
ADD_PROP_ASSIGNMENT(HARDLINEBREAKS);
ADD_PROP_ASSIGNMENT(PRINTABLE);
ADD_PROP_ASSIGNMENT(ECHO_CHAR);
ADD_PROP_ASSIGNMENT(ROWHEIGHT);
ADD_PROP_ASSIGNMENT(HELPTEXT);
ADD_PROP_ASSIGNMENT(FONT_NAME);
ADD_PROP_ASSIGNMENT(FONT_STYLENAME);
ADD_PROP_ASSIGNMENT(FONT_FAMILY);
ADD_PROP_ASSIGNMENT(FONT_CHARSET);
ADD_PROP_ASSIGNMENT(FONT_HEIGHT);
ADD_PROP_ASSIGNMENT(FONT_WEIGHT);
ADD_PROP_ASSIGNMENT(FONT_SLANT);
ADD_PROP_ASSIGNMENT(FONT_UNDERLINE);
ADD_PROP_ASSIGNMENT(FONT_WORDLINEMODE);
ADD_PROP_ASSIGNMENT(FONT_STRIKEOUT);
ADD_PROP_ASSIGNMENT(TEXTLINECOLOR);
ADD_PROP_ASSIGNMENT(FONTEMPHASISMARK);
ADD_PROP_ASSIGNMENT(FONTRELIEF);
ADD_PROP_ASSIGNMENT(HELPURL);
ADD_PROP_ASSIGNMENT(RECORDMARKER);
ADD_PROP_ASSIGNMENT(BOUNDFIELD);
ADD_PROP_ASSIGNMENT(TREATASNUMERIC);
ADD_PROP_ASSIGNMENT(EFFECTIVE_VALUE);
ADD_PROP_ASSIGNMENT(EFFECTIVE_DEFAULT);
ADD_PROP_ASSIGNMENT(EFFECTIVE_MIN);
ADD_PROP_ASSIGNMENT(EFFECTIVE_MAX);
ADD_PROP_ASSIGNMENT(HIDDEN);
ADD_PROP_ASSIGNMENT(FILTERPROPOSAL);
ADD_PROP_ASSIGNMENT(FIELDSOURCE);
ADD_PROP_ASSIGNMENT(TABLENAME);
ADD_PROP_ASSIGNMENT(CONTROLLABEL);
ADD_PROP_ASSIGNMENT(CURRSYM_POSITION);
ADD_PROP_ASSIGNMENT(CURSORCOLOR);
ADD_PROP_ASSIGNMENT(ALWAYSSHOWCURSOR);
ADD_PROP_ASSIGNMENT(DISPLAYSYNCHRON);
ADD_PROP_ASSIGNMENT(ISMODIFIED);
ADD_PROP_ASSIGNMENT(ISNEW);
ADD_PROP_ASSIGNMENT(PRIVILEGES);
ADD_PROP_ASSIGNMENT(DETAILFIELDS);
ADD_PROP_ASSIGNMENT(COMMAND);
ADD_PROP_ASSIGNMENT(COMMANDTYPE);
ADD_PROP_ASSIGNMENT(RESULTSET_CONCURRENCY);
ADD_PROP_ASSIGNMENT(INSERTONLY);
ADD_PROP_ASSIGNMENT(RESULTSET_TYPE);
ADD_PROP_ASSIGNMENT(ESCAPE_PROCESSING);
ADD_PROP_ASSIGNMENT(APPLYFILTER);
ADD_PROP_ASSIGNMENT(ISNULLABLE);
ADD_PROP_ASSIGNMENT(ACTIVECOMMAND);
ADD_PROP_ASSIGNMENT(ISCURRENCY);
ADD_PROP_ASSIGNMENT(URL);
ADD_PROP_ASSIGNMENT(TITLE);
ADD_PROP_ASSIGNMENT(ACTIVE_CONNECTION);
ADD_PROP_ASSIGNMENT(SCALE);
ADD_PROP_ASSIGNMENT(SORT);
ADD_PROP_ASSIGNMENT(PERSISTENCE_MAXTEXTLENGTH);
ADD_PROP_ASSIGNMENT(SCROLL_VALUE);
ADD_PROP_ASSIGNMENT(SPIN_VALUE);
ADD_PROP_ASSIGNMENT(DEFAULT_SCROLL_VALUE);
ADD_PROP_ASSIGNMENT(DEFAULT_SPIN_VALUE);
// now sort the array by name
std::sort(
s_AllKnownProperties.begin(),
s_AllKnownProperties.end(),
PropertyAssignmentNameCompareLess()
);
}
//.........................................................................
}
//... namespace frm .......................................................
<|endoftext|> |
<commit_before>/*
* Modularity.cpp
*
* Created on: 10.12.2012
* Author: cls
*/
#include "Modularity.h"
namespace EnsembleClustering {
Modularity::Modularity() : QualityMeasure() {
}
Modularity::~Modularity() {
// TODO Auto-generated destructor stub
}
double Modularity::getQuality(const Clustering& zeta, Graph& G) {
assert (G.numberOfNodes() <= zeta.numberOfNodes());
DEBUG("m = " << G.numberOfEdges());
DEBUG("l = " << G.numberOfSelfLoops());
Coverage coverage;
double cov = coverage.getQuality(zeta, G); // deprecated: intraEdgeWeightSum / totalEdgeWeight;
DEBUG("coverage = " << cov);
double expCov; // term $\frac{ \sum_{C \in \zeta}( \sum_{v \in C} \omega(v) )^2 }{4( \sum_{e \in E} \omega(e) )^2 }$
double modularity; // mod = coverage - expected coverage
double totalEdgeWeight = G.totalEdgeWeight(); // add edge weight
DEBUG("total edge weight: " << totalEdgeWeight)
if (totalEdgeWeight == 0.0) {
ERROR("G: m=" << G.numberOfEdges() << "n=" << G.numberOfNodes());
throw std::invalid_argument("Modularity is undefined for graphs without edges (including self-loops).");
}
IndexMap<cluster, double> incidentWeightSum(zeta.upperBound(), 0.0); //!< cluster -> sum of the weights of incident edges for all nodes
// compute volume of each cluster
G.forNodes([&](node v){
// add to cluster weight
cluster c = zeta[v];
assert (zeta.lowerBound() <= c);
assert (c < zeta.upperBound());
incidentWeightSum[c] += G.weightedDegree(v) + G.weight(v,v); // account for self-loops a second time
});
// compute sum of squared cluster volumes and divide by squared graph volume
// double totalIncidentWeight = 0.0; //!< term $\sum_{C \in \zeta}( \sum_{v \in C} \omega(v) )^2 $
expCov = 0.0;
// double divisor = 4 * totalEdgeWeight * totalEdgeWeight;
// assert (divisor != 0); // do not divide by 0
#pragma omp parallel for reduction(+:expCov)
for (cluster c = zeta.lowerBound(); c < zeta.upperBound(); ++c) {
expCov += ((incidentWeightSum[c] / totalEdgeWeight) * (incidentWeightSum[c] / totalEdgeWeight )) / 4; // squared
}
DEBUG("expected coverage: " << expCov);
DEBUG("expected coverage: " << expCov);
// assert ranges of coverage
assert(cov <= 1.0);
assert(cov >= 0.0);
assert(expCov <= 1.0);
assert(expCov >= 0.0);
modularity = cov - expCov;
assert(! std::isnan(modularity)); // do not return NaN
// do not return anything not in the range of modularity values
assert(modularity >= -0.5);
assert(modularity <= 1);
return modularity;
}
} /* namespace EnsembleClustering */
<commit_msg>debug statements in modularity<commit_after>/*
* Modularity.cpp
*
* Created on: 10.12.2012
* Author: cls
*/
#include "Modularity.h"
namespace EnsembleClustering {
Modularity::Modularity() : QualityMeasure() {
}
Modularity::~Modularity() {
// TODO Auto-generated destructor stub
}
double Modularity::getQuality(const Clustering& zeta, Graph& G) {
assert (G.numberOfNodes() <= zeta.numberOfNodes());
DEBUG("m = " << G.numberOfEdges());
DEBUG("l = " << G.numberOfSelfLoops());
Coverage coverage;
double cov = coverage.getQuality(zeta, G); // deprecated: intraEdgeWeightSum / totalEdgeWeight;
DEBUG("coverage = " << cov);
double expCov; // term $\frac{ \sum_{C \in \zeta}( \sum_{v \in C} \omega(v) )^2 }{4( \sum_{e \in E} \omega(e) )^2 }$
double modularity; // mod = coverage - expected coverage
double totalEdgeWeight = G.totalEdgeWeight(); // add edge weight
DEBUG("total edge weight: " << totalEdgeWeight)
if (totalEdgeWeight == 0.0) {
ERROR("G: m=" << G.numberOfEdges() << "n=" << G.numberOfNodes());
throw std::invalid_argument("Modularity is undefined for graphs without edges (including self-loops).");
}
IndexMap<cluster, double> incidentWeightSum(zeta.upperBound(), 0.0); //!< cluster -> sum of the weights of incident edges for all nodes
// compute volume of each cluster
G.forNodes([&](node v){
// add to cluster weight
cluster c = zeta[v];
assert (zeta.lowerBound() <= c);
assert (c < zeta.upperBound());
incidentWeightSum[c] += G.weightedDegree(v) + G.weight(v,v); // account for self-loops a second time
});
// compute sum of squared cluster volumes and divide by squared graph volume
// double totalIncidentWeight = 0.0; //!< term $\sum_{C \in \zeta}( \sum_{v \in C} \omega(v) )^2 $
expCov = 0.0;
// double divisor = 4 * totalEdgeWeight * totalEdgeWeight;
// assert (divisor != 0); // do not divide by 0
#pragma omp parallel for reduction(+:expCov)
for (cluster c = zeta.lowerBound(); c < zeta.upperBound(); ++c) {
expCov += ((incidentWeightSum[c] / totalEdgeWeight) * (incidentWeightSum[c] / totalEdgeWeight )) / 4; // squared
}
DEBUG("expected coverage: " << expCov);
// assert ranges of coverage
assert(cov <= 1.0);
assert(cov >= 0.0);
assert(expCov <= 1.0);
assert(expCov >= 0.0);
modularity = cov - expCov;
DEBUG("modularity = " << modularity)
assert(! std::isnan(modularity)); // do not return NaN
// do not return anything not in the range of modularity values
assert(modularity >= -0.5);
assert(modularity <= 1);
return modularity;
}
} /* namespace EnsembleClustering */
<|endoftext|> |
<commit_before>//===----------------------------------------------------------------------===//
//
// PelotonDB
//
// abstract_backend.h
//
// Identification: src/backend/storage/backend_file.cpp
//
// Copyright (c) 2015, Carnegie Mellon University Database Group
//
//===----------------------------------------------------------------------===//
#include "backend/storage/backend_file.h"
#include "backend/logging/log_manager.h"
#include <fcntl.h>
#include <sys/mman.h>
#include <fstream>
#include <unistd.h>
namespace peloton {
namespace storage {
BackendFile::BackendFile() {
if (EnableBackFileType()) {
// create a big file
std::ofstream backend_file(file_name, std::ios::binary | std::ios::out);
backend_file.seekp(file_size - 1);
backend_file.write("", 1);
// do mmap
fd = open(file_name.c_str(), O_RDWR, 0);
backend_space = (char *) mmap(nullptr, file_size, PROT_READ | PROT_WRITE,
MAP_FILE | MAP_SHARED, fd, 0);
close(fd);
assert(backend_space != nullptr);
// create vmem pool
vmp = vmem_create_in_region(backend_space, file_size);
assert(vmp != nullptr);
}
}
BackendFile::~BackendFile() {
if (vmp != nullptr) {
vmem_delete(vmp);
}
if (backend_space != nullptr) {
munmap(backend_space, file_size);
//remove(file_name.c_str());
}
}
void *BackendFile::Allocate(size_t size) {
if (backend_space != nullptr) {
return vmem_malloc(vmp, size);;
} else {
return ::operator new(size);
}
}
void BackendFile::Free(void *ptr) {
if (backend_space != nullptr) {
vmem_free(vmp, ptr);
} else {
::operator delete(ptr);
}
}
void BackendFile::Sync(void *ptr) {
if (backend_space != nullptr) {
size_t ptr_size = vmem_malloc_usable_size(vmp, ptr);
if (ptr_size != 0) {
msync(ptr, ptr_size, MS_SYNC);
}
}
}
} // End storage namespace
} // End peloton namespace
<commit_msg>Backend file should finish creating file before map it.<commit_after>//===----------------------------------------------------------------------===//
//
// PelotonDB
//
// abstract_backend.h
//
// Identification: src/backend/storage/backend_file.cpp
//
// Copyright (c) 2015, Carnegie Mellon University Database Group
//
//===----------------------------------------------------------------------===//
#include "backend/storage/backend_file.h"
#include "backend/logging/log_manager.h"
#include <fcntl.h>
#include <sys/mman.h>
#include <fstream>
#include <unistd.h>
namespace peloton {
namespace storage {
BackendFile::BackendFile() {
if (EnableBackFileType()) {
// create a big file
std::ofstream backend_file(file_name, std::ios::binary | std::ios::out);
backend_file.seekp(file_size - 1);
backend_file.write("", 1);
backend_file.close();
// do mmap
fd = open(file_name.c_str(), O_RDWR, 0);
backend_space = (char *) mmap(nullptr, file_size, PROT_READ | PROT_WRITE,
MAP_FILE | MAP_SHARED, fd, 0);
close(fd);
assert(backend_space != nullptr);
// create vmem pool
vmp = vmem_create_in_region(backend_space, file_size);
assert(vmp != nullptr);
}
}
BackendFile::~BackendFile() {
if (vmp != nullptr) {
vmem_delete(vmp);
}
if (backend_space != nullptr) {
munmap(backend_space, file_size);
//remove(file_name.c_str());
}
}
void *BackendFile::Allocate(size_t size) {
if (backend_space != nullptr) {
return vmem_malloc(vmp, size);;
} else {
return ::operator new(size);
}
}
void BackendFile::Free(void *ptr) {
if (backend_space != nullptr) {
vmem_free(vmp, ptr);
} else {
::operator delete(ptr);
}
}
void BackendFile::Sync(void *ptr) {
if (backend_space != nullptr) {
size_t ptr_size = vmem_malloc_usable_size(vmp, ptr);
if (ptr_size != 0) {
msync(ptr, ptr_size, MS_SYNC);
}
}
}
} // End storage namespace
} // End peloton namespace
<|endoftext|> |
<commit_before>/* This file is part of the Palabos library.
*
* Copyright (C) 2011-2015 FlowKit Sarl
* Route d'Oron 2
* 1010 Lausanne, Switzerland
* E-mail contact: contact@flowkit.com
*
* The most recent release of Palabos can be downloaded at
* <http://www.palabos.org/>
*
* The library Palabos 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.
*
* The 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 Affero 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/>.
*/
#ifndef TRT_DYNAMICS_HH
#define TRT_DYNAMICS_HH
#include "complexDynamics/trtDynamics.h"
#include "latticeBoltzmann/dynamicsTemplates.h"
#include "latticeBoltzmann/momentTemplates.h"
#include "core/latticeStatistics.h"
#include <algorithm>
#include <limits>
namespace plb {
/* *************** Class TRTdynamics *********************************************** */
template<typename T, template<typename U> class Descriptor>
const T TRTdynamics<T,Descriptor>::sMinus = 1.1;
template<typename T, template<typename U> class Descriptor>
int TRTdynamics<T,Descriptor>::id =
meta::registerOneParamDynamics<T,Descriptor,TRTdynamics<T,Descriptor> >("TRT");
/** \param omega_ relaxation parameter, related to the dynamic viscosity
*/
template<typename T, template<typename U> class Descriptor>
TRTdynamics<T,Descriptor>::TRTdynamics(T omega_ )
: IsoThermalBulkDynamics<T,Descriptor>(omega_)
{ }
template<typename T, template<typename U> class Descriptor>
TRTdynamics<T,Descriptor>* TRTdynamics<T,Descriptor>::clone() const {
return new TRTdynamics<T,Descriptor>(*this);
}
template<typename T, template<typename U> class Descriptor>
int TRTdynamics<T,Descriptor>::getId() const {
return id;
}
template<typename T, template<typename U> class Descriptor>
void TRTdynamics<T,Descriptor>::collide (
Cell<T,Descriptor>& cell, BlockStatistics& statistics )
{
const T sPlus = this->getOmega();
Array<T,Descriptor<T>::q> eq;
// In the following, we number the plus/minus variables from 1 to (Q-1)/2.
// So we allocate the index-zero memory location, and waste some memory
// for convenience.
Array<T,Descriptor<T>::q/2+1> eq_plus, eq_minus, f_plus, f_minus;
Array<T,3> j;
T rhoBar;
momentTemplates<T,Descriptor>::get_rhoBar_j(cell, rhoBar, j);
T jSqr = normSqr(j);
T invRho = Descriptor<T>::invRho(rhoBar);
dynamicsTemplates<T,Descriptor>::bgk_ma2_equilibria(rhoBar, invRho, j, jSqr, eq);
for (plint i=1; i<=Descriptor<T>::q/2; ++i) {
eq_plus[i] = 0.5*(eq[i] + eq[i+Descriptor<T>::q/2]);
eq_minus[i] = 0.5*(eq[i] - eq[i+Descriptor<T>::q/2]);
f_plus[i] = 0.5*(cell[i] + cell[i+Descriptor<T>::q/2]);
f_minus[i] = 0.5*(cell[i] - cell[i+Descriptor<T>::q/2]);
}
cell[0] += -sPlus*cell[0] + sPlus*eq[0];
for (plint i=1; i<=Descriptor<T>::q/2; ++i) {
cell[i] += -sPlus*(f_plus[i]-eq_plus[i]) - sMinus*(f_minus[i]-eq_minus[i]);
cell[i+Descriptor<T>::q/2] += -sPlus*(f_plus[i]-eq_plus[i]) + sMinus*(f_minus[i]-eq_minus[i]);
}
if (cell.takesStatistics()) {
gatherStatistics(statistics, rhoBar, jSqr * invRho * invRho );
}
}
template<typename T, template<typename U> class Descriptor>
void TRTdynamics<T,Descriptor>::collideExternal (
Cell<T,Descriptor>& cell, T rhoBar, Array<T,Descriptor<T>::d> const& j,
T thetaBar, BlockStatistics& statistics )
{
const T sPlus = this->getOmega();
Array<T,Descriptor<T>::q> eq;
// In the following, we number the plus/minus variables from 1 to (Q-1)/2.
// So we allocate the index-zero memory location, and waste some memory
// for convenience.
Array<T,Descriptor<T>::q/2+1> eq_plus, eq_minus, f_plus, f_minus;
T jSqr = normSqr(j);
T invRho = Descriptor<T>::invRho(rhoBar);
dynamicsTemplates<T,Descriptor>::bgk_ma2_equilibria(rhoBar, invRho, j, jSqr, eq);
for (plint i=1; i<=Descriptor<T>::q/2; ++i) {
eq_plus[i] = 0.5*(eq[i] + eq[i+Descriptor<T>::q/2]);
eq_minus[i] = 0.5*(eq[i] - eq[i+Descriptor<T>::q/2]);
f_plus[i] = 0.5*(cell[i] + cell[i+Descriptor<T>::q/2]);
f_minus[i] = 0.5*(cell[i] - cell[i+Descriptor<T>::q/2]);
}
cell[0] += -sPlus*cell[0] + sPlus*eq[0];
for (plint i=1; i<=Descriptor<T>::q/2; ++i) {
cell[i] += -sPlus*(f_plus[i]-eq_plus[i]) - sMinus*(f_minus[i]-eq_minus[i]);
cell[i+Descriptor<T>::q/2] += -sPlus*(f_plus[i]-eq_plus[i]) + sMinus*(f_minus[i]-eq_minus[i]);
}
if (cell.takesStatistics()) {
gatherStatistics(statistics, rhoBar, jSqr * Descriptor<T>::invRho(rhoBar) * Descriptor<T>::invRho(rhoBar) );
}
}
template<typename T, template<typename U> class Descriptor>
T TRTdynamics<T,Descriptor>::computeEquilibrium(plint iPop, T rhoBar, Array<T,Descriptor<T>::d> const& j,
T jSqr, T thetaBar) const
{
T invRho = Descriptor<T>::invRho(rhoBar);
return dynamicsTemplates<T,Descriptor>::bgk_ma2_equilibrium(iPop, rhoBar, invRho, j, jSqr);
}
/* *************** Class IncTRTdynamics *********************************************** */
template<typename T, template<typename U> class Descriptor>
const T IncTRTdynamics<T,Descriptor>::sMinus = 1.1;
template<typename T, template<typename U> class Descriptor>
int IncTRTdynamics<T,Descriptor>::id =
meta::registerOneParamDynamics<T,Descriptor,IncTRTdynamics<T,Descriptor> >("IncTRT");
/** \param omega_ relaxation parameter, related to the dynamic viscosity
*/
template<typename T, template<typename U> class Descriptor>
IncTRTdynamics<T,Descriptor>::IncTRTdynamics(T omega_ )
: IsoThermalBulkDynamics<T,Descriptor>(omega_)
{ }
template<typename T, template<typename U> class Descriptor>
IncTRTdynamics<T,Descriptor>* IncTRTdynamics<T,Descriptor>::clone() const {
return new IncTRTdynamics<T,Descriptor>(*this);
}
template<typename T, template<typename U> class Descriptor>
int IncTRTdynamics<T,Descriptor>::getId() const {
return id;
}
template<typename T, template<typename U> class Descriptor>
void IncTRTdynamics<T,Descriptor>::collide (
Cell<T,Descriptor>& cell, BlockStatistics& statistics )
{
const T sPlus = this->getOmega();
Array<T,Descriptor<T>::q> eq;
// In the following, we number the plus/minus variables from 1 to (Q-1)/2.
// So we allocate the index-zero memory location, and waste some memory
// for convenience.
Array<T,Descriptor<T>::q/2+1> eq_plus, eq_minus, f_plus, f_minus;
Array<T,3> j;
T rhoBar;
momentTemplates<T,Descriptor>::get_rhoBar_j(cell, rhoBar, j);
T jSqr = normSqr(j);
T invRho0 = 1.;
dynamicsTemplates<T,Descriptor>::bgk_ma2_equilibria(rhoBar, invRho0, j, jSqr, eq);
for (plint i=1; i<=Descriptor<T>::q/2; ++i) {
eq_plus[i] = 0.5*(eq[i] + eq[i+Descriptor<T>::q/2]);
eq_minus[i] = 0.5*(eq[i] - eq[i+Descriptor<T>::q/2]);
f_plus[i] = 0.5*(cell[i] + cell[i+Descriptor<T>::q/2]);
f_minus[i] = 0.5*(cell[i] - cell[i+Descriptor<T>::q/2]);
}
cell[0] += -sPlus*cell[0] + sPlus*eq[0];
for (plint i=1; i<=Descriptor<T>::q/2; ++i) {
cell[i] += -sPlus*(f_plus[i]-eq_plus[i]) - sMinus*(f_minus[i]-eq_minus[i]);
cell[i+Descriptor<T>::q/2] += -sPlus*(f_plus[i]-eq_plus[i]) + sMinus*(f_minus[i]-eq_minus[i]);
}
if (cell.takesStatistics()) {
gatherStatistics(statistics, rhoBar, jSqr);
}
}
template<typename T, template<typename U> class Descriptor>
void IncTRTdynamics<T,Descriptor>::collideExternal (
Cell<T,Descriptor>& cell, T rhoBar, Array<T,Descriptor<T>::d> const& j,
T thetaBar, BlockStatistics& statistics )
{
const T sPlus = this->getOmega();
Array<T,Descriptor<T>::q> eq;
// In the following, we number the plus/minus variables from 1 to (Q-1)/2.
// So we allocate the index-zero memory location, and waste some memory
// for convenience.
Array<T,Descriptor<T>::q/2+1> eq_plus, eq_minus, f_plus, f_minus;
T jSqr = normSqr(j);
T invRho0 = 1.;
dynamicsTemplates<T,Descriptor>::bgk_ma2_equilibria(rhoBar, invRho0, j, jSqr, eq);
for (plint i=1; i<=Descriptor<T>::q/2; ++i) {
eq_plus[i] = 0.5*(eq[i] + eq[i+Descriptor<T>::q/2]);
eq_minus[i] = 0.5*(eq[i] - eq[i+Descriptor<T>::q/2]);
f_plus[i] = 0.5*(cell[i] + cell[i+Descriptor<T>::q/2]);
f_minus[i] = 0.5*(cell[i] - cell[i+Descriptor<T>::q/2]);
}
cell[0] += -sPlus*cell[0] + sPlus*eq[0];
for (plint i=1; i<=Descriptor<T>::q/2; ++i) {
cell[i] += -sPlus*(f_plus[i]-eq_plus[i]) - sMinus*(f_minus[i]-eq_minus[i]);
cell[i+Descriptor<T>::q/2] += -sPlus*(f_plus[i]-eq_plus[i]) + sMinus*(f_minus[i]-eq_minus[i]);
}
if (cell.takesStatistics()) {
gatherStatistics(statistics, rhoBar, jSqr);
}
}
template<typename T, template<typename U> class Descriptor>
T IncTRTdynamics<T,Descriptor>::computeEquilibrium(plint iPop, T rhoBar, Array<T,Descriptor<T>::d> const& j,
T jSqr, T thetaBar) const
{
return dynamicsTemplates<T,Descriptor>::bgk_ma2_equilibrium(iPop, rhoBar, (T)1, j, jSqr);
}
template<typename T, template<typename U> class Descriptor>
bool IncTRTdynamics<T,Descriptor>::velIsJ() const {
return true;
}
template<typename T, template<typename U> class Descriptor>
void IncTRTdynamics<T,Descriptor>::computeVelocity( Cell<T,Descriptor> const& cell,
Array<T,Descriptor<T>::d>& u ) const
{
T dummyRhoBar;
this->computeRhoBarJ(cell, dummyRhoBar, u);
}
}
#endif // TRT_DYNAMICS_HH
<commit_msg>fixing bug in TRTDynamics: code was limited to 3D simulation only<commit_after>/* This file is part of the Palabos library.
*
* Copyright (C) 2011-2015 FlowKit Sarl
* Route d'Oron 2
* 1010 Lausanne, Switzerland
* E-mail contact: contact@flowkit.com
*
* The most recent release of Palabos can be downloaded at
* <http://www.palabos.org/>
*
* The library Palabos 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.
*
* The 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 Affero 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/>.
*/
#ifndef TRT_DYNAMICS_HH
#define TRT_DYNAMICS_HH
#include "complexDynamics/trtDynamics.h"
#include "latticeBoltzmann/dynamicsTemplates.h"
#include "latticeBoltzmann/momentTemplates.h"
#include "core/latticeStatistics.h"
#include <algorithm>
#include <limits>
namespace plb {
/* *************** Class TRTdynamics *********************************************** */
template<typename T, template<typename U> class Descriptor>
const T TRTdynamics<T,Descriptor>::sMinus = 1.1;
template<typename T, template<typename U> class Descriptor>
int TRTdynamics<T,Descriptor>::id =
meta::registerOneParamDynamics<T,Descriptor,TRTdynamics<T,Descriptor> >("TRT");
/** \param omega_ relaxation parameter, related to the dynamic viscosity
*/
template<typename T, template<typename U> class Descriptor>
TRTdynamics<T,Descriptor>::TRTdynamics(T omega_ )
: IsoThermalBulkDynamics<T,Descriptor>(omega_)
{ }
template<typename T, template<typename U> class Descriptor>
TRTdynamics<T,Descriptor>* TRTdynamics<T,Descriptor>::clone() const {
return new TRTdynamics<T,Descriptor>(*this);
}
template<typename T, template<typename U> class Descriptor>
int TRTdynamics<T,Descriptor>::getId() const {
return id;
}
template<typename T, template<typename U> class Descriptor>
void TRTdynamics<T,Descriptor>::collide (
Cell<T,Descriptor>& cell, BlockStatistics& statistics )
{
const T sPlus = this->getOmega();
Array<T,Descriptor<T>::q> eq;
// In the following, we number the plus/minus variables from 1 to (Q-1)/2.
// So we allocate the index-zero memory location, and waste some memory
// for convenience.
Array<T,Descriptor<T>::q/2+1> eq_plus, eq_minus, f_plus, f_minus;
Array<T,Descriptor<T>::d> j;
T rhoBar;
momentTemplates<T,Descriptor>::get_rhoBar_j(cell, rhoBar, j);
T jSqr = normSqr(j);
T invRho = Descriptor<T>::invRho(rhoBar);
dynamicsTemplates<T,Descriptor>::bgk_ma2_equilibria(rhoBar, invRho, j, jSqr, eq);
for (plint i=1; i<=Descriptor<T>::q/2; ++i) {
eq_plus[i] = 0.5*(eq[i] + eq[i+Descriptor<T>::q/2]);
eq_minus[i] = 0.5*(eq[i] - eq[i+Descriptor<T>::q/2]);
f_plus[i] = 0.5*(cell[i] + cell[i+Descriptor<T>::q/2]);
f_minus[i] = 0.5*(cell[i] - cell[i+Descriptor<T>::q/2]);
}
cell[0] += -sPlus*cell[0] + sPlus*eq[0];
for (plint i=1; i<=Descriptor<T>::q/2; ++i) {
cell[i] += -sPlus*(f_plus[i]-eq_plus[i]) - sMinus*(f_minus[i]-eq_minus[i]);
cell[i+Descriptor<T>::q/2] += -sPlus*(f_plus[i]-eq_plus[i]) + sMinus*(f_minus[i]-eq_minus[i]);
}
if (cell.takesStatistics()) {
gatherStatistics(statistics, rhoBar, jSqr * invRho * invRho );
}
}
template<typename T, template<typename U> class Descriptor>
void TRTdynamics<T,Descriptor>::collideExternal (
Cell<T,Descriptor>& cell, T rhoBar, Array<T,Descriptor<T>::d> const& j,
T thetaBar, BlockStatistics& statistics )
{
const T sPlus = this->getOmega();
Array<T,Descriptor<T>::q> eq;
// In the following, we number the plus/minus variables from 1 to (Q-1)/2.
// So we allocate the index-zero memory location, and waste some memory
// for convenience.
Array<T,Descriptor<T>::q/2+1> eq_plus, eq_minus, f_plus, f_minus;
T jSqr = normSqr(j);
T invRho = Descriptor<T>::invRho(rhoBar);
dynamicsTemplates<T,Descriptor>::bgk_ma2_equilibria(rhoBar, invRho, j, jSqr, eq);
for (plint i=1; i<=Descriptor<T>::q/2; ++i) {
eq_plus[i] = 0.5*(eq[i] + eq[i+Descriptor<T>::q/2]);
eq_minus[i] = 0.5*(eq[i] - eq[i+Descriptor<T>::q/2]);
f_plus[i] = 0.5*(cell[i] + cell[i+Descriptor<T>::q/2]);
f_minus[i] = 0.5*(cell[i] - cell[i+Descriptor<T>::q/2]);
}
cell[0] += -sPlus*cell[0] + sPlus*eq[0];
for (plint i=1; i<=Descriptor<T>::q/2; ++i) {
cell[i] += -sPlus*(f_plus[i]-eq_plus[i]) - sMinus*(f_minus[i]-eq_minus[i]);
cell[i+Descriptor<T>::q/2] += -sPlus*(f_plus[i]-eq_plus[i]) + sMinus*(f_minus[i]-eq_minus[i]);
}
if (cell.takesStatistics()) {
gatherStatistics(statistics, rhoBar, jSqr * Descriptor<T>::invRho(rhoBar) * Descriptor<T>::invRho(rhoBar) );
}
}
template<typename T, template<typename U> class Descriptor>
T TRTdynamics<T,Descriptor>::computeEquilibrium(plint iPop, T rhoBar, Array<T,Descriptor<T>::d> const& j,
T jSqr, T thetaBar) const
{
T invRho = Descriptor<T>::invRho(rhoBar);
return dynamicsTemplates<T,Descriptor>::bgk_ma2_equilibrium(iPop, rhoBar, invRho, j, jSqr);
}
/* *************** Class IncTRTdynamics *********************************************** */
template<typename T, template<typename U> class Descriptor>
const T IncTRTdynamics<T,Descriptor>::sMinus = 1.1;
template<typename T, template<typename U> class Descriptor>
int IncTRTdynamics<T,Descriptor>::id =
meta::registerOneParamDynamics<T,Descriptor,IncTRTdynamics<T,Descriptor> >("IncTRT");
/** \param omega_ relaxation parameter, related to the dynamic viscosity
*/
template<typename T, template<typename U> class Descriptor>
IncTRTdynamics<T,Descriptor>::IncTRTdynamics(T omega_ )
: IsoThermalBulkDynamics<T,Descriptor>(omega_)
{ }
template<typename T, template<typename U> class Descriptor>
IncTRTdynamics<T,Descriptor>* IncTRTdynamics<T,Descriptor>::clone() const {
return new IncTRTdynamics<T,Descriptor>(*this);
}
template<typename T, template<typename U> class Descriptor>
int IncTRTdynamics<T,Descriptor>::getId() const {
return id;
}
template<typename T, template<typename U> class Descriptor>
void IncTRTdynamics<T,Descriptor>::collide (
Cell<T,Descriptor>& cell, BlockStatistics& statistics )
{
const T sPlus = this->getOmega();
Array<T,Descriptor<T>::q> eq;
// In the following, we number the plus/minus variables from 1 to (Q-1)/2.
// So we allocate the index-zero memory location, and waste some memory
// for convenience.
Array<T,Descriptor<T>::q/2+1> eq_plus, eq_minus, f_plus, f_minus;
Array<T,3> j;
T rhoBar;
momentTemplates<T,Descriptor>::get_rhoBar_j(cell, rhoBar, j);
T jSqr = normSqr(j);
T invRho0 = 1.;
dynamicsTemplates<T,Descriptor>::bgk_ma2_equilibria(rhoBar, invRho0, j, jSqr, eq);
for (plint i=1; i<=Descriptor<T>::q/2; ++i) {
eq_plus[i] = 0.5*(eq[i] + eq[i+Descriptor<T>::q/2]);
eq_minus[i] = 0.5*(eq[i] - eq[i+Descriptor<T>::q/2]);
f_plus[i] = 0.5*(cell[i] + cell[i+Descriptor<T>::q/2]);
f_minus[i] = 0.5*(cell[i] - cell[i+Descriptor<T>::q/2]);
}
cell[0] += -sPlus*cell[0] + sPlus*eq[0];
for (plint i=1; i<=Descriptor<T>::q/2; ++i) {
cell[i] += -sPlus*(f_plus[i]-eq_plus[i]) - sMinus*(f_minus[i]-eq_minus[i]);
cell[i+Descriptor<T>::q/2] += -sPlus*(f_plus[i]-eq_plus[i]) + sMinus*(f_minus[i]-eq_minus[i]);
}
if (cell.takesStatistics()) {
gatherStatistics(statistics, rhoBar, jSqr);
}
}
template<typename T, template<typename U> class Descriptor>
void IncTRTdynamics<T,Descriptor>::collideExternal (
Cell<T,Descriptor>& cell, T rhoBar, Array<T,Descriptor<T>::d> const& j,
T thetaBar, BlockStatistics& statistics )
{
const T sPlus = this->getOmega();
Array<T,Descriptor<T>::q> eq;
// In the following, we number the plus/minus variables from 1 to (Q-1)/2.
// So we allocate the index-zero memory location, and waste some memory
// for convenience.
Array<T,Descriptor<T>::q/2+1> eq_plus, eq_minus, f_plus, f_minus;
T jSqr = normSqr(j);
T invRho0 = 1.;
dynamicsTemplates<T,Descriptor>::bgk_ma2_equilibria(rhoBar, invRho0, j, jSqr, eq);
for (plint i=1; i<=Descriptor<T>::q/2; ++i) {
eq_plus[i] = 0.5*(eq[i] + eq[i+Descriptor<T>::q/2]);
eq_minus[i] = 0.5*(eq[i] - eq[i+Descriptor<T>::q/2]);
f_plus[i] = 0.5*(cell[i] + cell[i+Descriptor<T>::q/2]);
f_minus[i] = 0.5*(cell[i] - cell[i+Descriptor<T>::q/2]);
}
cell[0] += -sPlus*cell[0] + sPlus*eq[0];
for (plint i=1; i<=Descriptor<T>::q/2; ++i) {
cell[i] += -sPlus*(f_plus[i]-eq_plus[i]) - sMinus*(f_minus[i]-eq_minus[i]);
cell[i+Descriptor<T>::q/2] += -sPlus*(f_plus[i]-eq_plus[i]) + sMinus*(f_minus[i]-eq_minus[i]);
}
if (cell.takesStatistics()) {
gatherStatistics(statistics, rhoBar, jSqr);
}
}
template<typename T, template<typename U> class Descriptor>
T IncTRTdynamics<T,Descriptor>::computeEquilibrium(plint iPop, T rhoBar, Array<T,Descriptor<T>::d> const& j,
T jSqr, T thetaBar) const
{
return dynamicsTemplates<T,Descriptor>::bgk_ma2_equilibrium(iPop, rhoBar, (T)1, j, jSqr);
}
template<typename T, template<typename U> class Descriptor>
bool IncTRTdynamics<T,Descriptor>::velIsJ() const {
return true;
}
template<typename T, template<typename U> class Descriptor>
void IncTRTdynamics<T,Descriptor>::computeVelocity( Cell<T,Descriptor> const& cell,
Array<T,Descriptor<T>::d>& u ) const
{
T dummyRhoBar;
this->computeRhoBarJ(cell, dummyRhoBar, u);
}
}
#endif // TRT_DYNAMICS_HH
<|endoftext|> |
<commit_before>/***************************************************************
*
* Copyright (C) 1990-2011, Condor Team, Computer Sciences Department,
* University of Wisconsin-Madison, WI.
*
* 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 "condor_common.h"
#include "generic_query.h"
#include "condor_attributes.h"
#include "condor_classad.h"
#include "MyString.h"
static char *new_strdup (const char *);
GenericQuery::
GenericQuery ()
{
// initialize category counts
integerThreshold = 0;
stringThreshold = 0;
floatThreshold = 0;
// initialize pointers
integerConstraints = 0;
floatConstraints = 0;
stringConstraints = 0;
floatKeywordList = NULL;
integerKeywordList = NULL;
stringKeywordList = NULL;
}
GenericQuery::
GenericQuery (const GenericQuery &gq)
{
// initialize category counts
integerThreshold = 0;
stringThreshold = 0;
floatThreshold = 0;
// initialize pointers
integerConstraints = 0;
floatConstraints = 0;
stringConstraints = 0;
floatKeywordList = NULL;
integerKeywordList = NULL;
stringKeywordList = NULL;
copyQueryObject(gq);
}
GenericQuery::
~GenericQuery ()
{
clearQueryObject ();
// release memory
if (stringConstraints) delete [] stringConstraints;
if (floatConstraints) delete [] floatConstraints;
if (integerConstraints)delete [] integerConstraints;
}
int GenericQuery::
setNumIntegerCats (const int numCats)
{
integerThreshold = (numCats > 0) ? numCats : 0;
if (integerThreshold)
{
integerConstraints = new SimpleList<int> [integerThreshold];
if (!integerConstraints)
return Q_MEMORY_ERROR;
return Q_OK;
}
return Q_INVALID_CATEGORY;
}
int GenericQuery::
setNumStringCats (const int numCats)
{
stringThreshold = (numCats > 0) ? numCats : 0;
if (stringThreshold)
{
stringConstraints = new List<char> [stringThreshold];
if (!stringConstraints)
return Q_MEMORY_ERROR;
return Q_OK;
}
return Q_INVALID_CATEGORY;
}
int GenericQuery::
setNumFloatCats (const int numCats)
{
floatThreshold = (numCats > 0) ? numCats : 0;
if (floatThreshold)
{
floatConstraints = new SimpleList<float> [floatThreshold];
if (!floatConstraints)
return Q_MEMORY_ERROR;
return Q_OK;
}
return Q_INVALID_CATEGORY;
}
// add an integer constraint
int GenericQuery::
addInteger (const int cat, int value)
{
if (cat >= 0 && cat < integerThreshold)
{
if (!integerConstraints [cat].Append (value))
return Q_MEMORY_ERROR;
return Q_OK;
}
return Q_INVALID_CATEGORY;
}
int GenericQuery::
addFloat (const int cat, float value)
{
if (cat >= 0 && cat < floatThreshold)
{
if (!floatConstraints [cat].Append (value))
return Q_MEMORY_ERROR;
return Q_OK;
}
return Q_INVALID_CATEGORY;
}
int GenericQuery::
addString (const int cat, const char *value)
{
char *x;
if (cat >= 0 && cat < stringThreshold)
{
x = new_strdup (value);
if (!x) return Q_MEMORY_ERROR;
stringConstraints [cat].Append (x);
return Q_OK;
}
return Q_INVALID_CATEGORY;
}
int GenericQuery::
addCustomOR (const char *value)
{
char *x = new_strdup (value);
if (!x) return Q_MEMORY_ERROR;
customORConstraints.Append (x);
return Q_OK;
}
int GenericQuery::
addCustomAND (const char *value)
{
char *x = new_strdup (value);
if (!x) return Q_MEMORY_ERROR;
customANDConstraints.Append (x);
return Q_OK;
}
// clear functions
int GenericQuery::
clearInteger (const int cat)
{
if (cat >= 0 && cat < integerThreshold)
{
clearIntegerCategory (integerConstraints [cat]);
return Q_OK;
}
else
return Q_INVALID_CATEGORY;
}
int GenericQuery::
clearString (const int cat)
{
if (cat >= 0 && cat < stringThreshold)
{
clearStringCategory (stringConstraints [cat]);
return Q_OK;
}
else
return Q_INVALID_CATEGORY;
}
int GenericQuery::
clearFloat (const int cat)
{
if (cat >= 0 && cat < floatThreshold)
{
clearFloatCategory (floatConstraints [cat]);
return Q_OK;
}
else
return Q_INVALID_CATEGORY;
}
int GenericQuery::
clearCustomOR ()
{
clearStringCategory (customORConstraints);
return Q_OK;
}
int GenericQuery::
clearCustomAND ()
{
clearStringCategory (customANDConstraints);
return Q_OK;
}
// set keyword lists
void GenericQuery::
setIntegerKwList (char **value)
{
integerKeywordList = value;
}
void GenericQuery::
setStringKwList (char **value)
{
stringKeywordList = value;
}
void GenericQuery::
setFloatKwList (char **value)
{
floatKeywordList = value;
}
// make query
int GenericQuery::
makeQuery (MyString &req)
{
int i, value;
char *item;
float fvalue;
req = "";
// construct query requirement expression
bool firstCategory = true;
// add string constraints
for (i = 0; i < stringThreshold; i++)
{
stringConstraints [i].Rewind ();
if (!stringConstraints [i].AtEnd ())
{
bool firstTime = true;
req += firstCategory ? "(" : " && (";
while ((item = stringConstraints [i].Next ()))
{
req.formatstr_cat ("%s(%s == \"%s\")",
firstTime ? " " : " || ",
stringKeywordList [i], item);
firstTime = false;
firstCategory = false;
}
req += " )";
}
}
// add integer constraints
for (i = 0; i < integerThreshold; i++)
{
integerConstraints [i].Rewind ();
if (!integerConstraints [i].AtEnd ())
{
bool firstTime = true;
req += firstCategory ? "(" : " && (";
while (integerConstraints [i].Next (value))
{
req.formatstr_cat ("%s(%s == %d)",
firstTime ? " " : " || ",
integerKeywordList [i], value);
firstTime = false;
firstCategory = false;
}
req += " )";
}
}
// add float constraints
for (i = 0; i < floatThreshold; i++)
{
floatConstraints [i].Rewind ();
if (!floatConstraints [i].AtEnd ())
{
bool firstTime = true;
req += firstCategory ? "(" : " && (";
while (floatConstraints [i].Next (fvalue))
{
req.formatstr_cat ("%s(%s == %f)",
firstTime ? " " : " || ",
floatKeywordList [i], fvalue);
firstTime = false;
firstCategory = false;
}
req += " )";
}
}
// add custom AND constraints
customANDConstraints.Rewind ();
if (!customANDConstraints.AtEnd ())
{
bool firstTime = true;
req += firstCategory ? "(" : " && (";
while ((item = customANDConstraints.Next ()))
{
req.formatstr_cat ("%s(%s)", firstTime ? " " : " && ", item);
firstTime = false;
firstCategory = false;
}
req += " )";
}
// add custom OR constraints
customORConstraints.Rewind ();
if (!customORConstraints.AtEnd ())
{
bool firstTime = true;
req += firstCategory ? "(" : " && (";
while ((item = customORConstraints.Next ()))
{
req.formatstr_cat ("%s(%s)", firstTime ? " " : " || ", item);
firstTime = false;
firstCategory = false;
}
req += " )";
}
return Q_OK;
}
int GenericQuery::
makeQuery (ExprTree *&tree)
{
MyString req;
int status = makeQuery(req);
if (status != Q_OK) return status;
// If there are no constraints, then we match everything.
if (req.empty()) req = "TRUE";
// parse constraints and insert into query ad
if (ParseClassAdRvalExpr (req.Value(), tree) > 0) return Q_PARSE_ERROR;
return Q_OK;
}
// helper functions --- clear
void GenericQuery::
clearQueryObject (void)
{
int i;
for (i = 0; i < stringThreshold; i++)
if (stringConstraints) clearStringCategory (stringConstraints[i]);
for (i = 0; i < integerThreshold; i++)
if (integerConstraints) clearIntegerCategory (integerConstraints[i]);
for (i = 0; i < floatThreshold; i++)
if (integerConstraints) clearFloatCategory (floatConstraints[i]);
clearStringCategory (customANDConstraints);
clearStringCategory (customORConstraints);
}
void GenericQuery::
clearStringCategory (List<char> &str_category)
{
char *x;
str_category.Rewind ();
while ((x = str_category.Next ()))
{
delete [] x;
str_category.DeleteCurrent ();
}
}
void GenericQuery::
clearIntegerCategory (SimpleList<int> &int_category)
{
int item;
int_category.Rewind ();
while (int_category.Next (item))
int_category.DeleteCurrent ();
}
void GenericQuery::
clearFloatCategory (SimpleList<float> &float_category)
{
float item;
float_category.Rewind ();
while (float_category.Next (item))
float_category.DeleteCurrent ();
}
// helper functions --- copy
void GenericQuery::
copyQueryObject (const GenericQuery &from)
{
int i;
// copy string constraints
for (i = 0; i < from.stringThreshold; i++)
copyStringCategory (stringConstraints[i], from.stringConstraints[i]);
// copy integer constraints
for (i = 0; i < from.integerThreshold; i++)
copyIntegerCategory (integerConstraints[i],from.integerConstraints[i]);
// copy custom constraints
copyStringCategory (customANDConstraints, const_cast<List<char> &>(from.customANDConstraints));
copyStringCategory (customORConstraints, const_cast<List<char> &>(from.customORConstraints));
// copy misc fields
stringThreshold = from.stringThreshold;
integerThreshold = from.integerThreshold;
floatThreshold = from.floatThreshold;
integerKeywordList = from.integerKeywordList;
stringKeywordList = from.stringKeywordList;
floatKeywordList = from.floatKeywordList;
floatConstraints = from.floatConstraints;
integerConstraints = from.integerConstraints;
stringConstraints = from.stringConstraints;
}
void GenericQuery::
copyStringCategory (List<char> &to, List<char> &from)
{
char *item;
clearStringCategory (to);
from.Rewind ();
while ((item = from.Next ()))
to.Append (new_strdup (item));
}
void GenericQuery::
copyIntegerCategory (SimpleList<int> &to, SimpleList<int> &from)
{
int item;
clearIntegerCategory (to);
while (from.Next (item))
to.Append (item);
}
void GenericQuery::
copyFloatCategory (SimpleList<float> &to, SimpleList<float> &from)
{
float item;
clearFloatCategory (to);
while (from.Next (item))
to.Append (item);
}
// strdup() which uses new
static char *new_strdup (const char *str)
{
char *x = new char [strlen (str) + 1];
if (!x) return 0;
strcpy (x, str);
return x;
}
<commit_msg>More coverity appeasement #6992<commit_after>/***************************************************************
*
* Copyright (C) 1990-2011, Condor Team, Computer Sciences Department,
* University of Wisconsin-Madison, WI.
*
* 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 "condor_common.h"
#include "generic_query.h"
#include "condor_attributes.h"
#include "condor_classad.h"
#include "MyString.h"
static char *new_strdup (const char *);
GenericQuery::
GenericQuery ()
{
// initialize category counts
integerThreshold = 0;
stringThreshold = 0;
floatThreshold = 0;
// initialize pointers
integerConstraints = 0;
floatConstraints = 0;
stringConstraints = 0;
floatKeywordList = NULL;
integerKeywordList = NULL;
stringKeywordList = NULL;
}
GenericQuery::
GenericQuery (const GenericQuery &gq)
{
// initialize category counts
integerThreshold = 0;
stringThreshold = 0;
floatThreshold = 0;
// initialize pointers
integerConstraints = 0;
floatConstraints = 0;
stringConstraints = 0;
floatKeywordList = NULL;
integerKeywordList = NULL;
stringKeywordList = NULL;
copyQueryObject(gq);
}
GenericQuery::
~GenericQuery ()
{
clearQueryObject ();
// release memory
if (stringConstraints) delete [] stringConstraints;
if (floatConstraints) delete [] floatConstraints;
if (integerConstraints)delete [] integerConstraints;
}
int GenericQuery::
setNumIntegerCats (const int numCats)
{
integerThreshold = (numCats > 0) ? numCats : 0;
if (integerThreshold)
{
integerConstraints = new SimpleList<int> [integerThreshold];
if (!integerConstraints)
return Q_MEMORY_ERROR;
return Q_OK;
}
return Q_INVALID_CATEGORY;
}
int GenericQuery::
setNumStringCats (const int numCats)
{
stringThreshold = (numCats > 0) ? numCats : 0;
if (stringThreshold)
{
stringConstraints = new List<char> [stringThreshold];
if (!stringConstraints)
return Q_MEMORY_ERROR;
return Q_OK;
}
return Q_INVALID_CATEGORY;
}
int GenericQuery::
setNumFloatCats (const int numCats)
{
floatThreshold = (numCats > 0) ? numCats : 0;
if (floatThreshold)
{
floatConstraints = new SimpleList<float> [floatThreshold];
if (!floatConstraints)
return Q_MEMORY_ERROR;
return Q_OK;
}
return Q_INVALID_CATEGORY;
}
// add an integer constraint
int GenericQuery::
addInteger (const int cat, int value)
{
if (cat >= 0 && cat < integerThreshold)
{
if (!integerConstraints [cat].Append (value))
return Q_MEMORY_ERROR;
return Q_OK;
}
return Q_INVALID_CATEGORY;
}
int GenericQuery::
addFloat (const int cat, float value)
{
if (cat >= 0 && cat < floatThreshold)
{
if (!floatConstraints [cat].Append (value))
return Q_MEMORY_ERROR;
return Q_OK;
}
return Q_INVALID_CATEGORY;
}
int GenericQuery::
addString (const int cat, const char *value)
{
char *x;
if (cat >= 0 && cat < stringThreshold)
{
x = new_strdup (value);
if (!x) return Q_MEMORY_ERROR;
stringConstraints [cat].Append (x);
return Q_OK;
}
return Q_INVALID_CATEGORY;
}
int GenericQuery::
addCustomOR (const char *value)
{
char *x = new_strdup (value);
if (!x) return Q_MEMORY_ERROR;
customORConstraints.Append (x);
return Q_OK;
}
int GenericQuery::
addCustomAND (const char *value)
{
char *x = new_strdup (value);
if (!x) return Q_MEMORY_ERROR;
customANDConstraints.Append (x);
return Q_OK;
}
// clear functions
int GenericQuery::
clearInteger (const int cat)
{
if (cat >= 0 && cat < integerThreshold)
{
clearIntegerCategory (integerConstraints [cat]);
return Q_OK;
}
else
return Q_INVALID_CATEGORY;
}
int GenericQuery::
clearString (const int cat)
{
if (cat >= 0 && cat < stringThreshold)
{
clearStringCategory (stringConstraints [cat]);
return Q_OK;
}
else
return Q_INVALID_CATEGORY;
}
int GenericQuery::
clearFloat (const int cat)
{
if (cat >= 0 && cat < floatThreshold)
{
clearFloatCategory (floatConstraints [cat]);
return Q_OK;
}
else
return Q_INVALID_CATEGORY;
}
int GenericQuery::
clearCustomOR ()
{
clearStringCategory (customORConstraints);
return Q_OK;
}
int GenericQuery::
clearCustomAND ()
{
clearStringCategory (customANDConstraints);
return Q_OK;
}
// set keyword lists
void GenericQuery::
setIntegerKwList (char **value)
{
integerKeywordList = value;
}
void GenericQuery::
setStringKwList (char **value)
{
stringKeywordList = value;
}
void GenericQuery::
setFloatKwList (char **value)
{
floatKeywordList = value;
}
// make query
int GenericQuery::
makeQuery (MyString &req)
{
int i, value;
char *item;
float fvalue;
req = "";
// construct query requirement expression
bool firstCategory = true;
// add string constraints
for (i = 0; i < stringThreshold; i++)
{
stringConstraints [i].Rewind ();
if (!stringConstraints [i].AtEnd ())
{
bool firstTime = true;
req += firstCategory ? "(" : " && (";
while ((item = stringConstraints [i].Next ()))
{
req.formatstr_cat ("%s(%s == \"%s\")",
firstTime ? " " : " || ",
stringKeywordList [i], item);
firstTime = false;
firstCategory = false;
}
req += " )";
}
}
// add integer constraints
for (i = 0; i < integerThreshold; i++)
{
integerConstraints [i].Rewind ();
if (!integerConstraints [i].AtEnd ())
{
bool firstTime = true;
req += firstCategory ? "(" : " && (";
while (integerConstraints [i].Next (value))
{
req.formatstr_cat ("%s(%s == %d)",
firstTime ? " " : " || ",
integerKeywordList [i], value);
firstTime = false;
firstCategory = false;
}
req += " )";
}
}
// add float constraints
for (i = 0; i < floatThreshold; i++)
{
floatConstraints [i].Rewind ();
if (!floatConstraints [i].AtEnd ())
{
bool firstTime = true;
req += firstCategory ? "(" : " && (";
while (floatConstraints [i].Next (fvalue))
{
req.formatstr_cat ("%s(%s == %f)",
firstTime ? " " : " || ",
floatKeywordList [i], fvalue);
firstTime = false;
firstCategory = false;
}
req += " )";
}
}
// add custom AND constraints
customANDConstraints.Rewind ();
if (!customANDConstraints.AtEnd ())
{
bool firstTime = true;
req += firstCategory ? "(" : " && (";
while ((item = customANDConstraints.Next ()))
{
req.formatstr_cat ("%s(%s)", firstTime ? " " : " && ", item);
firstTime = false;
firstCategory = false;
}
req += " )";
}
// add custom OR constraints
customORConstraints.Rewind ();
if (!customORConstraints.AtEnd ())
{
bool firstTime = true;
req += firstCategory ? "(" : " && (";
while ((item = customORConstraints.Next ()))
{
req.formatstr_cat ("%s(%s)", firstTime ? " " : " || ", item);
firstTime = false;
firstCategory = false;
}
req += " )";
}
return Q_OK;
}
int GenericQuery::
makeQuery (ExprTree *&tree)
{
MyString req;
int status = makeQuery(req);
if (status != Q_OK) return status;
// If there are no constraints, then we match everything.
if (req.empty()) req = "TRUE";
// parse constraints and insert into query ad
if (ParseClassAdRvalExpr (req.Value(), tree) > 0) return Q_PARSE_ERROR;
return Q_OK;
}
// helper functions --- clear
void GenericQuery::
clearQueryObject (void)
{
int i;
for (i = 0; i < stringThreshold; i++)
if (stringConstraints) clearStringCategory (stringConstraints[i]);
for (i = 0; i < integerThreshold; i++)
if (integerConstraints) clearIntegerCategory (integerConstraints[i]);
for (i = 0; i < floatThreshold; i++)
if (integerConstraints) clearFloatCategory (floatConstraints[i]);
clearStringCategory (customANDConstraints);
clearStringCategory (customORConstraints);
}
void GenericQuery::
clearStringCategory (List<char> &str_category)
{
char *x;
str_category.Rewind ();
while ((x = str_category.Next ()))
{
delete [] x;
str_category.DeleteCurrent ();
}
}
void GenericQuery::
clearIntegerCategory (SimpleList<int> &int_category)
{
int item;
int_category.Rewind ();
while (int_category.Next (item))
int_category.DeleteCurrent ();
}
void GenericQuery::
clearFloatCategory (SimpleList<float> &float_category)
{
float item;
float_category.Rewind ();
while (float_category.Next (item))
float_category.DeleteCurrent ();
}
// helper functions --- copy
void GenericQuery::
copyQueryObject (const GenericQuery &from)
{
int i;
// copy string constraints
for (i = 0; i < from.stringThreshold; i++)
if (stringConstraints) copyStringCategory (stringConstraints[i], from.stringConstraints[i]);
// copy integer constraints
for (i = 0; i < from.integerThreshold; i++)
if (integerConstraints) copyIntegerCategory (integerConstraints[i],from.integerConstraints[i]);
// copy custom constraints
copyStringCategory (customANDConstraints, const_cast<List<char> &>(from.customANDConstraints));
copyStringCategory (customORConstraints, const_cast<List<char> &>(from.customORConstraints));
// copy misc fields
stringThreshold = from.stringThreshold;
integerThreshold = from.integerThreshold;
floatThreshold = from.floatThreshold;
integerKeywordList = from.integerKeywordList;
stringKeywordList = from.stringKeywordList;
floatKeywordList = from.floatKeywordList;
floatConstraints = from.floatConstraints;
integerConstraints = from.integerConstraints;
stringConstraints = from.stringConstraints;
}
void GenericQuery::
copyStringCategory (List<char> &to, List<char> &from)
{
char *item;
clearStringCategory (to);
from.Rewind ();
while ((item = from.Next ()))
to.Append (new_strdup (item));
}
void GenericQuery::
copyIntegerCategory (SimpleList<int> &to, SimpleList<int> &from)
{
int item;
clearIntegerCategory (to);
while (from.Next (item))
to.Append (item);
}
void GenericQuery::
copyFloatCategory (SimpleList<float> &to, SimpleList<float> &from)
{
float item;
clearFloatCategory (to);
while (from.Next (item))
to.Append (item);
}
// strdup() which uses new
static char *new_strdup (const char *str)
{
char *x = new char [strlen (str) + 1];
if (!x) return 0;
strcpy (x, str);
return x;
}
<|endoftext|> |
<commit_before>/*
* PoolingGenConn.cpp
*
* Created on: Apr 25, 2011
* Author: peteschultz
*/
#include "PoolingGenConn.hpp"
namespace PV {
PoolingGenConn::PoolingGenConn(const char * name, HyPerCol * hc,
HyPerLayer * pre, HyPerLayer * post, HyPerLayer * pre2, HyPerLayer * post2,
const char * filename, InitWeights *weightInit) {
initialize_base();
initialize(name, hc, pre, post, pre2, post2, filename, weightInit);
} // end of PoolingGenConn::PoolingGenConn(const char *, HyPerCol *,
// HyPerLayer *, HyPerLayer *, HyPerLayer *, HyPerLayer *, int, const char *)
int PoolingGenConn::initialize_base() {
pre2 = NULL;
post2 = NULL;
return PV_SUCCESS;
}
int PoolingGenConn::initialize(const char * name, HyPerCol * hc,
HyPerLayer * pre, HyPerLayer * post, HyPerLayer * pre2, HyPerLayer * post2,
const char * filename, InitWeights *weightInit) {
int status;
PVParams * params = hc->parameters();
status = GenerativeConn::initialize(name, hc, pre, post, filename, weightInit);
if( status == PV_SUCCESS && checkLayersCompatible(pre, pre2) && checkLayersCompatible(post, post2) ) {
this->pre2 = pre2;
this->post2 = post2;
}
else {
status = PV_FAILURE;
}
if( status == PV_SUCCESS ) {
slownessFlag = params->value(name, "slownessFlag", 0.0/*default is false*/);
}
if( slownessFlag ) {
status = getSlownessLayer(&slownessPre, "slownessPre");
status = getSlownessLayer(&slownessPost, "slownessPost")==PV_SUCCESS ? status : PV_FAILURE;
}
if( slownessFlag && status == PV_SUCCESS ) {
status = checkLayersCompatible(pre, slownessPre) ? status : PV_FAILURE;
status = checkLayersCompatible(post, slownessPost) ? status : PV_FAILURE;
}
if( status != PV_SUCCESS ) {
abort();
}
return status;
} // end of PoolingGenConn::initialize(const char *, HyPerCol *,
// HyPerLayer *, HyPerLayer *, HyPerLayer *, HyPerLayer *, int, const char *, InitWeights *)
bool PoolingGenConn::checkLayersCompatible(HyPerLayer * layer1, HyPerLayer * layer2) {
int nx1 = layer1->getLayerLoc()->nx;
int nx2 = layer2->getLayerLoc()->nx;
int ny1 = layer1->getLayerLoc()->ny;
int ny2 = layer2->getLayerLoc()->ny;
int nf1 = layer1->getLayerLoc()->nf;
int nf2 = layer2->getLayerLoc()->nf;
int nb1 = layer1->getLayerLoc()->nb;
int nb2 = layer2->getLayerLoc()->nb;
bool result = nx1==nx2 && ny1==ny2 && nf1==nf2 && nb1==nb2;
if( !result ) {
const char * name1 = layer1->getName();
const char * name2 = layer2->getName();
fprintf(stderr, "Group \"%s\": Layers \"%s\" and \"%s\" do not have compatible sizes\n", name, name1, name2);
int len1 = (int) strlen(name1);
int len2 = (int) strlen(name2);
int len = len1 >= len2 ? len1 : len2;
fprintf(stderr, "Layer \"%*s\": nx=%d, ny=%d, nf=%d, nb=%d\n", len, name1, nx1, ny1, nf1, nb1);
fprintf(stderr, "Layer \"%*s\": nx=%d, ny=%d, nf=%d, nb=%d\n", len, name2, nx2, ny2, nf2, nb2);
}
return result;
} // end of PoolingGenConn::PoolingGenConn(HyPerLayer *, HyPerLayer *)
int PoolingGenConn::getSlownessLayer(HyPerLayer ** l, const char * paramname) {
int status = PV_SUCCESS;
assert(slownessFlag);
const char * slownessLayerName = parent->parameters()->stringValue(name, paramname, false);
if( slownessLayerName == NULL ) {
status = PV_FAILURE;
fprintf(stderr, "PoolingGenConn \"%s\": if slownessFlag is set, parameter \"%s\" must be set\n", name, paramname);
}
if( status == PV_SUCCESS ) {
*l = parent->getLayerFromName(slownessLayerName);
if( *l == NULL ) {
status = PV_FAILURE;
fprintf(stderr, "PoolingGenConn \"%s\": %s layer \"%s\" was not found\n", name, paramname, slownessLayerName);
}
}
return status;
}
int PoolingGenConn::updateWeights(int axonID) {
int nPre = preSynapticLayer()->getNumNeurons();
int nx = preSynapticLayer()->getLayerLoc()->nx;
int ny = preSynapticLayer()->getLayerLoc()->ny;
int nf = preSynapticLayer()->getLayerLoc()->nf;
int pad = preSynapticLayer()->getLayerLoc()->nb;
for(int kPre=0; kPre<nPre;kPre++) {
int kExt = kIndexExtended(kPre, nx, ny, nf, pad);
size_t offset = getAPostOffset(kPre, axonID);
pvdata_t preact = preSynapticLayer()->getCLayer()->activity->data[kExt];
pvdata_t preact2 = getPre2()->getCLayer()->activity->data[kExt];
PVPatch * weights = getWeights(kPre,axonID);
int nyp = weights->ny;
int nk = weights->nx * nfp;
pvdata_t * postactRef = &(postSynapticLayer()->getCLayer()->activity->data[offset]);
pvdata_t * postact2Ref = &(getPost2()->getCLayer()->activity->data[offset]);
int sya = getPostNonextStrides()->sy;
pvdata_t * wtpatch = get_wData(axonID, kExt); // weights->data;
int syw = syp;
for( int y=0; y<nyp; y++ ) {
int lineoffsetw = weights->offset;
int lineoffseta = 0;
for( int k=0; k<nk; k++ ) {
float w = wtpatch[lineoffsetw + k] + relaxation*(preact*postactRef[lineoffseta + k]+preact2*postact2Ref[lineoffseta + k]);
wtpatch[lineoffsetw + k] = w;
}
lineoffsetw += syw;
lineoffseta += sya;
}
}
if( slownessFlag ) {
for(int kPre=0; kPre<nPre;kPre++) {
int kExt = kIndexExtended(kPre, nx, ny, nf, pad);
size_t offset = getAPostOffset(kPre, axonID);
pvdata_t preact = slownessPre->getCLayer()->activity->data[kExt];
PVPatch * weights = getWeights(kPre,axonID);
int nyp = weights->ny;
int nk = weights->nx * nfp;
pvdata_t * postactRef = &(slownessPost->getCLayer()->activity->data[offset]);
int sya = getPostNonextStrides()->sy;
pvdata_t * wtpatch = get_wData(axonID, kExt); // weights->data;
int syw = syp;
for( int y=0; y<nyp; y++ ) {
int lineoffsetw = 0;
int lineoffseta = 0;
for( int k=0; k<nk; k++ ) {
float w = wtpatch[lineoffsetw + k] - relaxation*(preact*postactRef[lineoffseta + k]);
wtpatch[lineoffsetw + k] = w;
}
lineoffsetw += syw;
lineoffseta += sya;
}
}
}
if( nonnegConstraintFlag ) {
for(int kPatch=0; kPatch<getNumDataPatches();kPatch++) {
// PVPatch * weights = this->getKernelPatch(axonID, kPatch);
pvdata_t * wtpatch = get_wDataHead(axonID, kPatch); // weights->data;
int nk = nxp * nfp;
int syw = nxp*nfp;
for( int y=0; y < nyp; y++ ) {
int lineoffsetw = 0;
for( int k=0; k<nk; k++ ) {
pvdata_t w = wtpatch[lineoffsetw + k];
if( w<0 ) {
wtpatch[lineoffsetw + k] = 0;
}
}
lineoffsetw += syw;
}
}
}
// normalizeWeights now called in KernelConn::updateState
lastUpdateTime = parent->simulationTime();
return PV_SUCCESS;
}
} // end namespace PV
<commit_msg>Bugfix for PoolingGenConn<commit_after>/*
* PoolingGenConn.cpp
*
* Created on: Apr 25, 2011
* Author: peteschultz
*/
#include "PoolingGenConn.hpp"
namespace PV {
PoolingGenConn::PoolingGenConn(const char * name, HyPerCol * hc,
HyPerLayer * pre, HyPerLayer * post, HyPerLayer * pre2, HyPerLayer * post2,
const char * filename, InitWeights *weightInit) {
initialize_base();
initialize(name, hc, pre, post, pre2, post2, filename, weightInit);
} // end of PoolingGenConn::PoolingGenConn(const char *, HyPerCol *,
// HyPerLayer *, HyPerLayer *, HyPerLayer *, HyPerLayer *, int, const char *)
int PoolingGenConn::initialize_base() {
pre2 = NULL;
post2 = NULL;
return PV_SUCCESS;
}
int PoolingGenConn::initialize(const char * name, HyPerCol * hc,
HyPerLayer * pre, HyPerLayer * post, HyPerLayer * pre2, HyPerLayer * post2,
const char * filename, InitWeights *weightInit) {
int status;
PVParams * params = hc->parameters();
status = GenerativeConn::initialize(name, hc, pre, post, filename, weightInit);
if( status == PV_SUCCESS && checkLayersCompatible(pre, pre2) && checkLayersCompatible(post, post2) ) {
this->pre2 = pre2;
this->post2 = post2;
}
else {
status = PV_FAILURE;
}
if( status == PV_SUCCESS ) {
slownessFlag = params->value(name, "slownessFlag", 0.0/*default is false*/);
}
if( slownessFlag ) {
status = getSlownessLayer(&slownessPre, "slownessPre");
status = getSlownessLayer(&slownessPost, "slownessPost")==PV_SUCCESS ? status : PV_FAILURE;
}
if( slownessFlag && status == PV_SUCCESS ) {
status = checkLayersCompatible(pre, slownessPre) ? status : PV_FAILURE;
status = checkLayersCompatible(post, slownessPost) ? status : PV_FAILURE;
}
if( status != PV_SUCCESS ) {
abort();
}
return status;
} // end of PoolingGenConn::initialize(const char *, HyPerCol *,
// HyPerLayer *, HyPerLayer *, HyPerLayer *, HyPerLayer *, int, const char *, InitWeights *)
bool PoolingGenConn::checkLayersCompatible(HyPerLayer * layer1, HyPerLayer * layer2) {
int nx1 = layer1->getLayerLoc()->nx;
int nx2 = layer2->getLayerLoc()->nx;
int ny1 = layer1->getLayerLoc()->ny;
int ny2 = layer2->getLayerLoc()->ny;
int nf1 = layer1->getLayerLoc()->nf;
int nf2 = layer2->getLayerLoc()->nf;
int nb1 = layer1->getLayerLoc()->nb;
int nb2 = layer2->getLayerLoc()->nb;
bool result = nx1==nx2 && ny1==ny2 && nf1==nf2 && nb1==nb2;
if( !result ) {
const char * name1 = layer1->getName();
const char * name2 = layer2->getName();
fprintf(stderr, "Group \"%s\": Layers \"%s\" and \"%s\" do not have compatible sizes\n", name, name1, name2);
int len1 = (int) strlen(name1);
int len2 = (int) strlen(name2);
int len = len1 >= len2 ? len1 : len2;
fprintf(stderr, "Layer \"%*s\": nx=%d, ny=%d, nf=%d, nb=%d\n", len, name1, nx1, ny1, nf1, nb1);
fprintf(stderr, "Layer \"%*s\": nx=%d, ny=%d, nf=%d, nb=%d\n", len, name2, nx2, ny2, nf2, nb2);
}
return result;
} // end of PoolingGenConn::PoolingGenConn(HyPerLayer *, HyPerLayer *)
int PoolingGenConn::getSlownessLayer(HyPerLayer ** l, const char * paramname) {
int status = PV_SUCCESS;
assert(slownessFlag);
const char * slownessLayerName = parent->parameters()->stringValue(name, paramname, false);
if( slownessLayerName == NULL ) {
status = PV_FAILURE;
fprintf(stderr, "PoolingGenConn \"%s\": if slownessFlag is set, parameter \"%s\" must be set\n", name, paramname);
}
if( status == PV_SUCCESS ) {
*l = parent->getLayerFromName(slownessLayerName);
if( *l == NULL ) {
status = PV_FAILURE;
fprintf(stderr, "PoolingGenConn \"%s\": %s layer \"%s\" was not found\n", name, paramname, slownessLayerName);
}
}
return status;
}
int PoolingGenConn::updateWeights(int axonID) {
int nPre = preSynapticLayer()->getNumNeurons();
int nx = preSynapticLayer()->getLayerLoc()->nx;
int ny = preSynapticLayer()->getLayerLoc()->ny;
int nf = preSynapticLayer()->getLayerLoc()->nf;
int pad = preSynapticLayer()->getLayerLoc()->nb;
for(int kPre=0; kPre<nPre;kPre++) {
int kExt = kIndexExtended(kPre, nx, ny, nf, pad);
size_t offset = getAPostOffset(kPre, axonID);
pvdata_t preact = preSynapticLayer()->getCLayer()->activity->data[kExt];
pvdata_t preact2 = getPre2()->getCLayer()->activity->data[kExt];
PVPatch * weights = getWeights(kPre,axonID);
int nyp = weights->ny;
int nk = weights->nx * nfp;
pvdata_t * postactRef = &(postSynapticLayer()->getCLayer()->activity->data[offset]);
pvdata_t * postact2Ref = &(getPost2()->getCLayer()->activity->data[offset]);
int sya = getPostNonextStrides()->sy;
pvdata_t * wtpatch = get_wData(axonID, kExt); // weights->data;
int syw = syp;
int lineoffsetw = weights->offset;
int lineoffseta = 0;
for( int y=0; y<nyp; y++ ) {
for( int k=0; k<nk; k++ ) {
float w = wtpatch[lineoffsetw + k] + relaxation*(preact*postactRef[lineoffseta + k]+preact2*postact2Ref[lineoffseta + k]);
wtpatch[lineoffsetw + k] = w;
}
lineoffsetw += syw;
lineoffseta += sya;
}
}
if( slownessFlag ) {
for(int kPre=0; kPre<nPre;kPre++) {
int kExt = kIndexExtended(kPre, nx, ny, nf, pad);
size_t offset = getAPostOffset(kPre, axonID);
pvdata_t preact = slownessPre->getCLayer()->activity->data[kExt];
PVPatch * weights = getWeights(kPre,axonID);
int nyp = weights->ny;
int nk = weights->nx * nfp;
pvdata_t * postactRef = &(slownessPost->getCLayer()->activity->data[offset]);
int sya = getPostNonextStrides()->sy;
pvdata_t * wtpatch = get_wData(axonID, kExt); // weights->data;
int syw = syp;
for( int y=0; y<nyp; y++ ) {
int lineoffsetw = 0;
int lineoffseta = 0;
for( int k=0; k<nk; k++ ) {
float w = wtpatch[lineoffsetw + k] - relaxation*(preact*postactRef[lineoffseta + k]);
wtpatch[lineoffsetw + k] = w;
}
lineoffsetw += syw;
lineoffseta += sya;
}
}
}
if( nonnegConstraintFlag ) {
for(int kPatch=0; kPatch<getNumDataPatches();kPatch++) {
// PVPatch * weights = this->getKernelPatch(axonID, kPatch);
pvdata_t * wtpatch = get_wDataHead(axonID, kPatch); // weights->data;
int nk = nxp * nfp;
int syw = nxp*nfp;
for( int y=0; y < nyp; y++ ) {
int lineoffsetw = 0;
for( int k=0; k<nk; k++ ) {
pvdata_t w = wtpatch[lineoffsetw + k];
if( w<0 ) {
wtpatch[lineoffsetw + k] = 0;
}
}
lineoffsetw += syw;
}
}
}
// normalizeWeights now called in KernelConn::updateState
lastUpdateTime = parent->simulationTime();
return PV_SUCCESS;
}
} // end namespace PV
<|endoftext|> |
<commit_before>/****************************************************************************
**
** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies).
** All rights reserved.
** Contact: Nokia Corporation (qt-info@nokia.com)
**
** This file is part of the Qt Mobility Components.
**
** $QT_BEGIN_LICENSE:LGPL$
** 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.
**
** GNU General Public License Usage
** Alternatively, this file may be used under the terms of the GNU General
** Public License version 3.0 as published by the Free Software Foundation
** and appearing in the file LICENSE.GPL included in the packaging of this
** file. Please review the following information to ensure the GNU General
** Public License version 3.0 requirements will be met:
** http://www.gnu.org/copyleft/gpl.html.
**
** 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.
**
**
**
**
**
** $QT_END_LICENSE$
**
****************************************************************************/
#include "qcontactmanager.h"
#include "qcontactmanager_p.h"
#include "qcontactmanagerengine.h"
#include "qcontactmanagerenginefactory.h"
#include "qcontactmanagerenginev2wrapper_p.h"
#include "qcontact_p.h"
#include "qcontactaction.h"
#include "qcontactactiondescriptor.h"
#ifdef QT_SIMULATOR
#include "qcontactsimulatorbackend_p.h"
#endif
#include <QSharedData>
#include <QtPlugin>
#include <QPluginLoader>
#include <QDebug>
#include <QDir>
#include <QFile>
#include <QApplication>
#if defined(Q_OS_SYMBIAN)
# include <f32file.h>
#endif
#include "qcontactmemorybackend_p.h"
#include "qcontactinvalidbackend_p.h"
#include "qmobilitypluginsearch.h"
QTM_BEGIN_NAMESPACE
/* Shared QContactManager stuff here, default engine stuff below */
QHash<QString, QContactManagerEngineFactory*> QContactManagerData::m_engines;
QSet<QContactManager*> QContactManagerData::m_aliveEngines;
QList<QContactActionManagerPlugin*> QContactManagerData::m_actionManagers;
bool QContactManagerData::m_discoveredStatic;
QStringList QContactManagerData::m_pluginPaths;
static void qContactsCleanEngines()
{
// This is complicated by needing to remove any engines before we unload factories
foreach(QContactManager* manager, QContactManagerData::m_aliveEngines) {
// We don't delete the managers here, we just kill their engines
// and replace it with an invalid engine (for safety :/)
QContactManagerData* d = QContactManagerData::managerData(manager);
delete d->m_engine;
d->m_engine = new QContactInvalidEngine();
}
QList<QContactManagerEngineFactory*> factories = QContactManagerData::m_engines.values();
for (int i=0; i < factories.count(); i++) {
delete factories.at(i);
}
QContactManagerData::m_engines.clear();
QContactManagerData::m_actionManagers.clear();
QContactManagerData::m_aliveEngines.clear();
}
static int parameterValue(const QMap<QString, QString>& parameters, const char* key, int defaultValue)
{
if (parameters.contains(QString::fromAscii(key))) {
bool ok;
int version = parameters.value(QString::fromAscii(key)).toInt(&ok);
if (ok)
return version;
}
return defaultValue;
}
void QContactManagerData::createEngine(const QString& managerName, const QMap<QString, QString>& parameters)
{
m_engine = 0;
QString builtManagerName = managerName.isEmpty() ? QContactManager::availableManagers().value(0) : managerName;
if (builtManagerName == QLatin1String("memory")) {
QContactManagerEngine* engine = QContactMemoryEngine::createMemoryEngine(parameters);
m_engine = new QContactManagerEngineV2Wrapper(engine);
m_signalSource = engine;
#ifdef QT_SIMULATOR
} else if (builtManagerName == QLatin1String("simulator")) {
QContactManagerEngine* engine = QContactSimulatorEngine::createSimulatorEngine(parameters);
m_engine = new QContactManagerEngineV2Wrapper(engine);
m_signalSource = engine;
#endif
} else {
int implementationVersion = parameterValue(parameters, QTCONTACTS_IMPLEMENTATION_VERSION_NAME, -1);
bool found = false;
bool loadedDynamic = false;
/* First check static factories */
loadStaticFactories();
/* See if we got a fast hit */
QList<QContactManagerEngineFactory*> factories = m_engines.values(builtManagerName);
m_lastError = QContactManager::NoError;
while(!found) {
foreach (QContactManagerEngineFactory* f, factories) {
QList<int> versions = f->supportedImplementationVersions();
if (implementationVersion == -1 ||//no given implementation version required
versions.isEmpty() || //the manager engine factory does not report any version
versions.contains(implementationVersion)) {
QContactManagerEngine* engine = f->engine(parameters, &m_lastError);
// if it's a V2, use it
m_engine = qobject_cast<QContactManagerEngineV2*>(engine);
if (!m_engine && engine) {
// Nope, v1, so wrap it
m_engine = new QContactManagerEngineV2Wrapper(engine);
m_signalSource = engine;
} else {
m_signalSource = m_engine; // use the v2 engine directly
}
found = true;
break;
}
}
// Break if found or if this is the second time through
if (loadedDynamic || found)
break;
// otherwise load dynamic factories and reloop
loadFactories();
factories = m_engines.values(builtManagerName);
loadedDynamic = true;
}
// XXX remove this
// the engine factory could lie to us, so check the real implementation version
if (m_engine && (implementationVersion != -1 && m_engine->managerVersion() != implementationVersion)) {
m_lastError = QContactManager::VersionMismatchError;
m_signalSource = m_engine = 0;
}
if (!m_engine) {
if (m_lastError == QContactManager::NoError)
m_lastError = QContactManager::DoesNotExistError;
m_signalSource = m_engine = new QContactInvalidEngine();
}
}
}
void QContactManagerData::loadStaticFactories()
{
if (!m_discoveredStatic) {
#if !defined QT_NO_DEBUG
const bool showDebug = qgetenv("QT_DEBUG_PLUGINS").toInt() > 0;
#endif
m_discoveredStatic = true;
/* Clean stuff up at the end */
qAddPostRoutine(qContactsCleanEngines);
/* Loop over all the static plugins */
QObjectList staticPlugins = QPluginLoader::staticInstances();
for (int i=0; i < staticPlugins.count(); i++ ){
QContactManagerEngineFactory *f = qobject_cast<QContactManagerEngineFactory*>(staticPlugins.at(i));
if (f) {
QString name = f->managerName();
#if !defined QT_NO_DEBUG
if (showDebug)
qDebug() << "Static: found an engine plugin" << f << "with name" << name;
#endif
if (name != QLatin1String("memory") && name != QLatin1String("invalid") && !name.isEmpty()) {
// we also need to ensure that we haven't already loaded this factory.
if (m_engines.keys().contains(name)) {
qWarning() << "Static contacts plugin" << name << "has the same name as a currently loaded plugin; ignored";
} else {
m_engines.insertMulti(name, f);
}
} else {
qWarning() << "Static contacts plugin with reserved name" << name << "ignored";
}
}
}
}
}
/* Plugin loader */
void QContactManagerData::loadFactories()
{
#if !defined QT_NO_DEBUG
const bool showDebug = qgetenv("QT_DEBUG_PLUGINS").toInt() > 0;
#endif
// Always do this..
loadStaticFactories();
// But only load dynamic plugins when the paths change
QStringList paths = QCoreApplication::libraryPaths();
#ifdef QTM_PLUGIN_PATH
paths << QLatin1String(QTM_PLUGIN_PATH);
#endif
if (paths != m_pluginPaths) {
m_pluginPaths = paths;
QStringList plugins = mobilityPlugins(QLatin1String("contacts"));
/* Now discover the dynamic plugins */
for (int i=0; i < plugins.count(); i++) {
QPluginLoader qpl(plugins.at(i));
#if !defined QT_NO_DEBUG
if (showDebug)
qDebug() << "Loading plugin" << plugins.at(i);
#endif
QContactManagerEngineFactory *f = qobject_cast<QContactManagerEngineFactory*>(qpl.instance());
QContactActionManagerPlugin *m = qobject_cast<QContactActionManagerPlugin*>(qpl.instance());
if (f) {
QString name = f->managerName();
#if !defined QT_NO_DEBUG
if (showDebug)
qDebug() << "Dynamic: found a contact engine plugin" << f << "with name" << name;
#endif
if (name != QLatin1String("memory") && name != QLatin1String("invalid") && !name.isEmpty()) {
// we also need to ensure that we haven't already loaded this factory.
if (m_engines.keys().contains(name)) {
qWarning() << "Contacts plugin" << plugins.at(i) << "has the same name as currently loaded plugin" << name << "; ignored";
} else {
m_engines.insertMulti(name, f);
}
} else {
qWarning() << "Contacts plugin" << plugins.at(i) << "with reserved name" << name << "ignored";
}
}
if (m) {
m_actionManagers.append(m);
}
/* Debugging */
#if !defined QT_NO_DEBUG
if (showDebug && !f && !m) {
qDebug() << "Unknown plugin:" << qpl.errorString();
if (qpl.instance()) {
qDebug() << "[qobject:" << qpl.instance() << "]";
}
}
#endif
}
QStringList engineNames;
foreach (QContactManagerEngineFactory* f, m_engines.values()) {
QStringList versions;
foreach (int v, f->supportedImplementationVersions()) {
versions << QString::fromAscii("%1").arg(v);
}
engineNames << QString::fromAscii("%1[%2]").arg(f->managerName()).arg(versions.join(QString::fromAscii(",")));
}
#if !defined QT_NO_DEBUG
if (showDebug) {
qDebug() << "Found engines:" << engineNames;
qDebug() << "Found action engines:" << m_actionManagers;
}
#endif
}
}
// Observer stuff
void QContactManagerData::registerObserver(QContactManager* manager, QContactObserver* observer)
{
if (!manager)
return;
QContactManagerData* d = QContactManagerData::get(manager);
d->m_observerForContact.insert(observer->contactLocalId(), observer);
// If this is the first observer, connect to the engine too
if (d->m_observerForContact.size() == 1) {
// This takes advantage of the manager connectNotify code
QObject::connect(manager, SIGNAL(contactsChanged(QList<QContactLocalId>)),
manager, SLOT(_q_contactsUpdated(QList<QContactLocalId>)));
QObject::connect(manager, SIGNAL(contactsRemoved(QList<QContactLocalId>)),
manager, SLOT(_q_contactsDeleted(QList<QContactLocalId>)));
}
}
void QContactManagerData::unregisterObserver(QContactManager* manager, QContactObserver* observer)
{
Q_ASSERT(manager);
QContactManagerData* d = QContactManagerData::get(manager);
QContactLocalId key = d->m_observerForContact.key(observer);
if (key != 0) {
d->m_observerForContact.remove(key, observer);
// If there are now no more observers, disconnect from the engine
if (d->m_observerForContact.size() == 0) {
// This takes advantage of the manager disconnectNotify code
QObject::disconnect(manager, SIGNAL(contactsChanged(QList<QContactLocalId>)),
manager, SLOT(_q_contactsUpdated(QList<QContactLocalId>)));
QObject::disconnect(manager, SIGNAL(contactsRemoved(QList<QContactLocalId>)),
manager, SLOT(_q_contactsDeleted(QList<QContactLocalId>)));
}
}
}
void QContactManagerData::_q_contactsUpdated(const QList<QContactLocalId>& ids)
{
foreach (QContactLocalId id, ids) {
QList<QContactObserver*> observers = m_observerForContact.values(id);
foreach (QContactObserver* observer, observers) {
QMetaObject::invokeMethod(observer, "contactChanged");
}
}
}
void QContactManagerData::_q_contactsDeleted(const QList<QContactLocalId>& ids)
{
foreach (QContactLocalId id, ids) {
QList<QContactObserver*> observers = m_observerForContact.values(id);
foreach (QContactObserver* observer, observers) {
QMetaObject::invokeMethod(observer, "contactRemoved");
}
}
}
// trampolines for private classes
QContactManagerData* QContactManagerData::get(const QContactManager* manager)
{
return manager->d;
}
QContactManagerEngineV2* QContactManagerData::engine(const QContactManager* manager)
{
if (manager)
return manager->d->m_engine;
return 0;
}
QTM_END_NAMESPACE
<commit_msg>Fixing double delete segfault in qContactsCleanEngines<commit_after>/****************************************************************************
**
** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies).
** All rights reserved.
** Contact: Nokia Corporation (qt-info@nokia.com)
**
** This file is part of the Qt Mobility Components.
**
** $QT_BEGIN_LICENSE:LGPL$
** 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.
**
** GNU General Public License Usage
** Alternatively, this file may be used under the terms of the GNU General
** Public License version 3.0 as published by the Free Software Foundation
** and appearing in the file LICENSE.GPL included in the packaging of this
** file. Please review the following information to ensure the GNU General
** Public License version 3.0 requirements will be met:
** http://www.gnu.org/copyleft/gpl.html.
**
** 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.
**
**
**
**
**
** $QT_END_LICENSE$
**
****************************************************************************/
#include "qcontactmanager.h"
#include "qcontactmanager_p.h"
#include "qcontactmanagerengine.h"
#include "qcontactmanagerenginefactory.h"
#include "qcontactmanagerenginev2wrapper_p.h"
#include "qcontact_p.h"
#include "qcontactaction.h"
#include "qcontactactiondescriptor.h"
#ifdef QT_SIMULATOR
#include "qcontactsimulatorbackend_p.h"
#endif
#include <QSharedData>
#include <QtPlugin>
#include <QPluginLoader>
#include <QWeakPointer>
#include <QDebug>
#include <QDir>
#include <QFile>
#include <QApplication>
#if defined(Q_OS_SYMBIAN)
# include <f32file.h>
#endif
#include "qcontactmemorybackend_p.h"
#include "qcontactinvalidbackend_p.h"
#include "qmobilitypluginsearch.h"
QTM_BEGIN_NAMESPACE
/* Shared QContactManager stuff here, default engine stuff below */
QHash<QString, QContactManagerEngineFactory*> QContactManagerData::m_engines;
QSet<QContactManager*> QContactManagerData::m_aliveEngines;
QList<QContactActionManagerPlugin*> QContactManagerData::m_actionManagers;
bool QContactManagerData::m_discoveredStatic;
QStringList QContactManagerData::m_pluginPaths;
static void qContactsCleanEngines()
{
// This is complicated by needing to remove any engines before we unload factories
// guard pointers as one engine could be parent of another manager and cause doubledelete
QList<QWeakPointer<QContactManager> > aliveManagers;
foreach(QContactManager* manager, QContactManagerData::m_aliveEngines) {
aliveManagers << QWeakPointer<QContactManager>(manager);
}
foreach(QWeakPointer<QContactManager> manager, aliveManagers) {
if (not manager) {
// deleting engine of one manager, could cause deleting next manager in list (aggregation case)
continue;
}
// We don't delete the managers here, we just kill their engines
// and replace it with an invalid engine (for safety :/)
QContactManagerData* d = QContactManagerData::managerData(manager.data());
delete d->m_engine;
d->m_engine = new QContactInvalidEngine();
}
QList<QContactManagerEngineFactory*> factories = QContactManagerData::m_engines.values();
for (int i=0; i < factories.count(); i++) {
delete factories.at(i);
}
QContactManagerData::m_engines.clear();
QContactManagerData::m_actionManagers.clear();
QContactManagerData::m_aliveEngines.clear();
}
static int parameterValue(const QMap<QString, QString>& parameters, const char* key, int defaultValue)
{
if (parameters.contains(QString::fromAscii(key))) {
bool ok;
int version = parameters.value(QString::fromAscii(key)).toInt(&ok);
if (ok)
return version;
}
return defaultValue;
}
void QContactManagerData::createEngine(const QString& managerName, const QMap<QString, QString>& parameters)
{
m_engine = 0;
QString builtManagerName = managerName.isEmpty() ? QContactManager::availableManagers().value(0) : managerName;
if (builtManagerName == QLatin1String("memory")) {
QContactManagerEngine* engine = QContactMemoryEngine::createMemoryEngine(parameters);
m_engine = new QContactManagerEngineV2Wrapper(engine);
m_signalSource = engine;
#ifdef QT_SIMULATOR
} else if (builtManagerName == QLatin1String("simulator")) {
QContactManagerEngine* engine = QContactSimulatorEngine::createSimulatorEngine(parameters);
m_engine = new QContactManagerEngineV2Wrapper(engine);
m_signalSource = engine;
#endif
} else {
int implementationVersion = parameterValue(parameters, QTCONTACTS_IMPLEMENTATION_VERSION_NAME, -1);
bool found = false;
bool loadedDynamic = false;
/* First check static factories */
loadStaticFactories();
/* See if we got a fast hit */
QList<QContactManagerEngineFactory*> factories = m_engines.values(builtManagerName);
m_lastError = QContactManager::NoError;
while(!found) {
foreach (QContactManagerEngineFactory* f, factories) {
QList<int> versions = f->supportedImplementationVersions();
if (implementationVersion == -1 ||//no given implementation version required
versions.isEmpty() || //the manager engine factory does not report any version
versions.contains(implementationVersion)) {
QContactManagerEngine* engine = f->engine(parameters, &m_lastError);
// if it's a V2, use it
m_engine = qobject_cast<QContactManagerEngineV2*>(engine);
if (!m_engine && engine) {
// Nope, v1, so wrap it
m_engine = new QContactManagerEngineV2Wrapper(engine);
m_signalSource = engine;
} else {
m_signalSource = m_engine; // use the v2 engine directly
}
found = true;
break;
}
}
// Break if found or if this is the second time through
if (loadedDynamic || found)
break;
// otherwise load dynamic factories and reloop
loadFactories();
factories = m_engines.values(builtManagerName);
loadedDynamic = true;
}
// XXX remove this
// the engine factory could lie to us, so check the real implementation version
if (m_engine && (implementationVersion != -1 && m_engine->managerVersion() != implementationVersion)) {
m_lastError = QContactManager::VersionMismatchError;
m_signalSource = m_engine = 0;
}
if (!m_engine) {
if (m_lastError == QContactManager::NoError)
m_lastError = QContactManager::DoesNotExistError;
m_signalSource = m_engine = new QContactInvalidEngine();
}
}
}
void QContactManagerData::loadStaticFactories()
{
if (!m_discoveredStatic) {
#if !defined QT_NO_DEBUG
const bool showDebug = qgetenv("QT_DEBUG_PLUGINS").toInt() > 0;
#endif
m_discoveredStatic = true;
/* Clean stuff up at the end */
qAddPostRoutine(qContactsCleanEngines);
/* Loop over all the static plugins */
QObjectList staticPlugins = QPluginLoader::staticInstances();
for (int i=0; i < staticPlugins.count(); i++ ){
QContactManagerEngineFactory *f = qobject_cast<QContactManagerEngineFactory*>(staticPlugins.at(i));
if (f) {
QString name = f->managerName();
#if !defined QT_NO_DEBUG
if (showDebug)
qDebug() << "Static: found an engine plugin" << f << "with name" << name;
#endif
if (name != QLatin1String("memory") && name != QLatin1String("invalid") && !name.isEmpty()) {
// we also need to ensure that we haven't already loaded this factory.
if (m_engines.keys().contains(name)) {
qWarning() << "Static contacts plugin" << name << "has the same name as a currently loaded plugin; ignored";
} else {
m_engines.insertMulti(name, f);
}
} else {
qWarning() << "Static contacts plugin with reserved name" << name << "ignored";
}
}
}
}
}
/* Plugin loader */
void QContactManagerData::loadFactories()
{
#if !defined QT_NO_DEBUG
const bool showDebug = qgetenv("QT_DEBUG_PLUGINS").toInt() > 0;
#endif
// Always do this..
loadStaticFactories();
// But only load dynamic plugins when the paths change
QStringList paths = QCoreApplication::libraryPaths();
#ifdef QTM_PLUGIN_PATH
paths << QLatin1String(QTM_PLUGIN_PATH);
#endif
if (paths != m_pluginPaths) {
m_pluginPaths = paths;
QStringList plugins = mobilityPlugins(QLatin1String("contacts"));
/* Now discover the dynamic plugins */
for (int i=0; i < plugins.count(); i++) {
QPluginLoader qpl(plugins.at(i));
#if !defined QT_NO_DEBUG
if (showDebug)
qDebug() << "Loading plugin" << plugins.at(i);
#endif
QContactManagerEngineFactory *f = qobject_cast<QContactManagerEngineFactory*>(qpl.instance());
QContactActionManagerPlugin *m = qobject_cast<QContactActionManagerPlugin*>(qpl.instance());
if (f) {
QString name = f->managerName();
#if !defined QT_NO_DEBUG
if (showDebug)
qDebug() << "Dynamic: found a contact engine plugin" << f << "with name" << name;
#endif
if (name != QLatin1String("memory") && name != QLatin1String("invalid") && !name.isEmpty()) {
// we also need to ensure that we haven't already loaded this factory.
if (m_engines.keys().contains(name)) {
qWarning() << "Contacts plugin" << plugins.at(i) << "has the same name as currently loaded plugin" << name << "; ignored";
} else {
m_engines.insertMulti(name, f);
}
} else {
qWarning() << "Contacts plugin" << plugins.at(i) << "with reserved name" << name << "ignored";
}
}
if (m) {
m_actionManagers.append(m);
}
/* Debugging */
#if !defined QT_NO_DEBUG
if (showDebug && !f && !m) {
qDebug() << "Unknown plugin:" << qpl.errorString();
if (qpl.instance()) {
qDebug() << "[qobject:" << qpl.instance() << "]";
}
}
#endif
}
QStringList engineNames;
foreach (QContactManagerEngineFactory* f, m_engines.values()) {
QStringList versions;
foreach (int v, f->supportedImplementationVersions()) {
versions << QString::fromAscii("%1").arg(v);
}
engineNames << QString::fromAscii("%1[%2]").arg(f->managerName()).arg(versions.join(QString::fromAscii(",")));
}
#if !defined QT_NO_DEBUG
if (showDebug) {
qDebug() << "Found engines:" << engineNames;
qDebug() << "Found action engines:" << m_actionManagers;
}
#endif
}
}
// Observer stuff
void QContactManagerData::registerObserver(QContactManager* manager, QContactObserver* observer)
{
if (!manager)
return;
QContactManagerData* d = QContactManagerData::get(manager);
d->m_observerForContact.insert(observer->contactLocalId(), observer);
// If this is the first observer, connect to the engine too
if (d->m_observerForContact.size() == 1) {
// This takes advantage of the manager connectNotify code
QObject::connect(manager, SIGNAL(contactsChanged(QList<QContactLocalId>)),
manager, SLOT(_q_contactsUpdated(QList<QContactLocalId>)));
QObject::connect(manager, SIGNAL(contactsRemoved(QList<QContactLocalId>)),
manager, SLOT(_q_contactsDeleted(QList<QContactLocalId>)));
}
}
void QContactManagerData::unregisterObserver(QContactManager* manager, QContactObserver* observer)
{
Q_ASSERT(manager);
QContactManagerData* d = QContactManagerData::get(manager);
QContactLocalId key = d->m_observerForContact.key(observer);
if (key != 0) {
d->m_observerForContact.remove(key, observer);
// If there are now no more observers, disconnect from the engine
if (d->m_observerForContact.size() == 0) {
// This takes advantage of the manager disconnectNotify code
QObject::disconnect(manager, SIGNAL(contactsChanged(QList<QContactLocalId>)),
manager, SLOT(_q_contactsUpdated(QList<QContactLocalId>)));
QObject::disconnect(manager, SIGNAL(contactsRemoved(QList<QContactLocalId>)),
manager, SLOT(_q_contactsDeleted(QList<QContactLocalId>)));
}
}
}
void QContactManagerData::_q_contactsUpdated(const QList<QContactLocalId>& ids)
{
foreach (QContactLocalId id, ids) {
QList<QContactObserver*> observers = m_observerForContact.values(id);
foreach (QContactObserver* observer, observers) {
QMetaObject::invokeMethod(observer, "contactChanged");
}
}
}
void QContactManagerData::_q_contactsDeleted(const QList<QContactLocalId>& ids)
{
foreach (QContactLocalId id, ids) {
QList<QContactObserver*> observers = m_observerForContact.values(id);
foreach (QContactObserver* observer, observers) {
QMetaObject::invokeMethod(observer, "contactRemoved");
}
}
}
// trampolines for private classes
QContactManagerData* QContactManagerData::get(const QContactManager* manager)
{
return manager->d;
}
QContactManagerEngineV2* QContactManagerData::engine(const QContactManager* manager)
{
if (manager)
return manager->d->m_engine;
return 0;
}
QTM_END_NAMESPACE
<|endoftext|> |
<commit_before>/*
* ConnectedComponents.cpp
*
* Created on: Dec 16, 2013
* Author: cls
*/
#include "ConnectedComponents.h"
#include <set>
namespace NetworKit {
ConnectedComponents::ConnectedComponents() {
}
ConnectedComponents::~ConnectedComponents() {
}
void ConnectedComponents::run(const Graph& G) {
// calculate connected components by label propagation
count z = G.numberOfNodes();
this->component = std::vector<node>(z, none);
G.parallelForNodes([&](node v){
component[v] = v;
});
bool change = false;
do {
DEBUG("next iteration");
change = false;
G.parallelForNodes([&](node u) {
G.forNeighborsOf(u, [&](node v) {
if (component[v] < component[u]) {
component[u] = component[v];
change = true;
}
});
// minimum neighboring label assigned
});
} while (change);
}
std::vector<index> ConnectedComponents::getComponentData() {
return this->component;
}
std::map<index, count> ConnectedComponents::getComponentSizes() {
std::map<index, count> componentSize;
for (node u = 0; u < component.size(); ++u) {
if (component[u] != none) {
componentSize[component[u]] += 1;
}
}
return componentSize;
}
std::vector<node> ConnectedComponents::getComponent(index label) {
std::vector<node> nodesOfComponent;
for (node u = 0; u < component.size(); ++u) {
if (this->component[u] == label) {
nodesOfComponent.push_back(u);
}
}
return nodesOfComponent;
}
count ConnectedComponents::numberOfComponents() {
count nc = 0;
std::set<index> componentLabels;
for (index i = 0; i < component.size(); ++i) {
index c = component[i];
if ((componentLabels.find(c) == componentLabels.end()) && (c != none)) { // label not encountered yet
componentLabels.insert(c);
nc++;
}
}
return nc;
}
count ConnectedComponents::componentOfNode(node u) {
assert (component[u] != none);
return component[u];
}
}
<commit_msg>better load balancing for ConnectedComponents<commit_after>/*
* ConnectedComponents.cpp
*
* Created on: Dec 16, 2013
* Author: cls
*/
#include "ConnectedComponents.h"
#include <set>
namespace NetworKit {
ConnectedComponents::ConnectedComponents() {
}
ConnectedComponents::~ConnectedComponents() {
}
void ConnectedComponents::run(const Graph& G) {
// calculate connected components by label propagation
count z = G.numberOfNodes();
this->component = std::vector<node>(z, none);
G.parallelForNodes([&](node v){
component[v] = v;
});
bool change = false;
do {
DEBUG("next iteration");
change = false;
G.balancedParallelForNodes([&](node u) {
G.forNeighborsOf(u, [&](node v) {
if (component[v] < component[u]) {
component[u] = component[v];
change = true;
}
});
// minimum neighboring label assigned
});
} while (change);
}
std::vector<index> ConnectedComponents::getComponentData() {
return this->component;
}
std::map<index, count> ConnectedComponents::getComponentSizes() {
std::map<index, count> componentSize;
for (node u = 0; u < component.size(); ++u) {
if (component[u] != none) {
componentSize[component[u]] += 1;
}
}
return componentSize;
}
std::vector<node> ConnectedComponents::getComponent(index label) {
std::vector<node> nodesOfComponent;
for (node u = 0; u < component.size(); ++u) {
if (this->component[u] == label) {
nodesOfComponent.push_back(u);
}
}
return nodesOfComponent;
}
count ConnectedComponents::numberOfComponents() {
count nc = 0;
std::set<index> componentLabels;
for (index i = 0; i < component.size(); ++i) {
index c = component[i];
if ((componentLabels.find(c) == componentLabels.end()) && (c != none)) { // label not encountered yet
componentLabels.insert(c);
nc++;
}
}
return nc;
}
count ConnectedComponents::componentOfNode(node u) {
assert (component[u] != none);
return component[u];
}
}
<|endoftext|> |
<commit_before>/* bzflag
* Copyright (c) 1993 - 2009 Tim Riker
*
* This package is free software; you can redistribute it and/or
* modify it under the terms of the license found in the file
* named COPYING that should have accompanied this file.
*
* THIS PACKAGE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR
* IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
*/
#include "common.h"
/* interface header */
#include "bzfio.h"
/* system implementation headers */
#include <iostream>
#include <vector>
#include <string>
#include <stdarg.h>
#include <time.h>
#ifdef HAVE_UNISTD_H
# include <unistd.h>
#endif
#ifdef __BEOS__
# include <OS.h>
#endif
#if !defined(_WIN32)
# include <sys/time.h>
# include <sys/types.h>
#else /* !defined(_WIN32) */
# include <mmsystem.h>
#endif
/** global used to control logging level across all applications */
int debugLevel = 0;
static bool doMicros = false;
static bool doTimestamp = false;
static int callProcDepth = 0;
//============================================================================//
//============================================================================//
struct LoggingProcPair {
LoggingProcPair(LoggingProc p, void* d)
: proc(p)
, data(d)
{}
bool operator==(const LoggingProcPair& lpp) const {
return (proc == lpp.proc) && (data == lpp.data);
}
LoggingProc proc;
void* data;
};
typedef std::vector<LoggingProcPair> LoggingProcVec;
static LoggingProcVec loggingProcs;
bool registerLoggingProc(LoggingProc proc, void* data)
{
if (proc == NULL) {
return false;
}
LoggingProcPair lpp(proc, data);
for (size_t i = 0; i < loggingProcs.size(); i++) {
if (lpp == loggingProcs[i]) {
return false; // already registered
}
}
loggingProcs.push_back(lpp);
return true;
}
bool unregisterLoggingProc(LoggingProc proc, void* data)
{
if (callProcDepth != 0) {
logDebugMessage(0, "error: unregisterLoggingProc() used in a LoggingProc");
return false;
}
LoggingProcPair lpp(proc, data);
for (size_t i = 0; i < loggingProcs.size(); i++) {
if (lpp == loggingProcs[i]) {
loggingProcs.erase(loggingProcs.begin() + i);
return true;
}
}
return false;
}
static void callProcs(int level, const std::string& msg)
{
callProcDepth++;
for (size_t i = 0; i < loggingProcs.size(); i++) {
const LoggingProcPair& lpp = loggingProcs[i];
lpp.proc(level, msg, lpp.data);
}
callProcDepth--;
}
//============================================================================//
//============================================================================//
void setDebugTimestamp(bool enable, bool micros)
{
#ifdef _WIN32
micros = false;
#endif
doTimestamp = enable;
doMicros = micros;
}
static const int tsBufferSize = 26;
static char *timestamp(char *buf, bool micros)
{
struct tm *tm;
if (micros) {
#if !defined(_WIN32)
struct timeval tv;
gettimeofday(&tv, NULL);
tm = localtime((const time_t *)&tv.tv_sec);
snprintf(buf, tsBufferSize, "%04d-%02d-%02d %02d:%02d:%02ld.%06ld: ",
tm->tm_year+1900, tm->tm_mon+1, tm->tm_mday,
tm->tm_hour, tm->tm_min, (long)tm->tm_sec, (long)tv.tv_usec);
#endif
} else {
time_t tt;
time(&tt);
tm = localtime(&tt);
snprintf(buf, tsBufferSize, "%04d-%02d-%02d %02d:%02d:%02d: ",
tm->tm_year+1900, tm->tm_mon+1, tm->tm_mday,
tm->tm_hour, tm->tm_min, tm->tm_sec);
}
return buf;
}
//============================================================================//
//============================================================================//
static void realLogDebugMessage(int level, const char* text)
{
if ((debugLevel >= level) || (level == 0)) {
#if defined(_MSC_VER)
if (doTimestamp) {
char tsbuf[tsBufferSize] = { 0 };
W32_DEBUG_TRACE(timestamp(tsbuf, false));
}
W32_DEBUG_TRACE(text);
#else
if (doTimestamp) {
char tsbuf[tsBufferSize] = { 0 };
std::cout << timestamp(tsbuf, doMicros);
}
std::cout << text;
fflush(stdout);
#endif
callProcs(level, text);
}
}
void logDebugMessageArgs(int level, const char* fmt, va_list ap)
{
char buffer[8192] = { 0 };
if (!fmt) {
return;
}
vsnprintf(buffer, sizeof(buffer), fmt, ap);
realLogDebugMessage(level, buffer);
}
void logDebugMessage(int level, const char* fmt, ...)
{
va_list ap;
va_start(ap, fmt);
logDebugMessageArgs(level, fmt, ap);
va_end(ap);
}
void logDebugMessage(int level, const std::string &text)
{
if (text.empty()) {
return;
}
realLogDebugMessage(level, text.c_str());
}
//============================================================================//
//============================================================================//
// Local Variables: ***
// mode: C++ ***
// tab-width: 8 ***
// c-basic-offset: 2 ***
// indent-tabs-mode: t ***
// End: ***
// ex: shiftwidth=2 tabstop=8
<commit_msg>bzfs: Fix timestamp buffer size so -ts micros output fits<commit_after>/* bzflag
* Copyright (c) 1993 - 2009 Tim Riker
*
* This package is free software; you can redistribute it and/or
* modify it under the terms of the license found in the file
* named COPYING that should have accompanied this file.
*
* THIS PACKAGE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR
* IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
*/
#include "common.h"
/* interface header */
#include "bzfio.h"
/* system implementation headers */
#include <iostream>
#include <vector>
#include <string>
#include <stdarg.h>
#include <time.h>
#ifdef HAVE_UNISTD_H
# include <unistd.h>
#endif
#ifdef __BEOS__
# include <OS.h>
#endif
#if !defined(_WIN32)
# include <sys/time.h>
# include <sys/types.h>
#else /* !defined(_WIN32) */
# include <mmsystem.h>
#endif
/** global used to control logging level across all applications */
int debugLevel = 0;
static bool doMicros = false;
static bool doTimestamp = false;
static int callProcDepth = 0;
//============================================================================//
//============================================================================//
struct LoggingProcPair {
LoggingProcPair(LoggingProc p, void* d)
: proc(p)
, data(d)
{}
bool operator==(const LoggingProcPair& lpp) const {
return (proc == lpp.proc) && (data == lpp.data);
}
LoggingProc proc;
void* data;
};
typedef std::vector<LoggingProcPair> LoggingProcVec;
static LoggingProcVec loggingProcs;
bool registerLoggingProc(LoggingProc proc, void* data)
{
if (proc == NULL) {
return false;
}
LoggingProcPair lpp(proc, data);
for (size_t i = 0; i < loggingProcs.size(); i++) {
if (lpp == loggingProcs[i]) {
return false; // already registered
}
}
loggingProcs.push_back(lpp);
return true;
}
bool unregisterLoggingProc(LoggingProc proc, void* data)
{
if (callProcDepth != 0) {
logDebugMessage(0, "error: unregisterLoggingProc() used in a LoggingProc");
return false;
}
LoggingProcPair lpp(proc, data);
for (size_t i = 0; i < loggingProcs.size(); i++) {
if (lpp == loggingProcs[i]) {
loggingProcs.erase(loggingProcs.begin() + i);
return true;
}
}
return false;
}
static void callProcs(int level, const std::string& msg)
{
callProcDepth++;
for (size_t i = 0; i < loggingProcs.size(); i++) {
const LoggingProcPair& lpp = loggingProcs[i];
lpp.proc(level, msg, lpp.data);
}
callProcDepth--;
}
//============================================================================//
//============================================================================//
void setDebugTimestamp(bool enable, bool micros)
{
#ifdef _WIN32
micros = false;
#endif
doTimestamp = enable;
doMicros = micros;
}
static const int tsBufferSize = 29;
static char *timestamp(char *buf, bool micros)
{
struct tm *tm;
if (micros) {
#if !defined(_WIN32)
struct timeval tv;
gettimeofday(&tv, NULL);
tm = localtime((const time_t *)&tv.tv_sec);
snprintf(buf, tsBufferSize, "%04d-%02d-%02d %02d:%02d:%02ld.%06ld: ",
tm->tm_year+1900, tm->tm_mon+1, tm->tm_mday,
tm->tm_hour, tm->tm_min, (long)tm->tm_sec, (long)tv.tv_usec);
#endif
} else {
time_t tt;
time(&tt);
tm = localtime(&tt);
snprintf(buf, tsBufferSize, "%04d-%02d-%02d %02d:%02d:%02d: ",
tm->tm_year+1900, tm->tm_mon+1, tm->tm_mday,
tm->tm_hour, tm->tm_min, tm->tm_sec);
}
return buf;
}
//============================================================================//
//============================================================================//
static void realLogDebugMessage(int level, const char* text)
{
if ((debugLevel >= level) || (level == 0)) {
#if defined(_MSC_VER)
if (doTimestamp) {
char tsbuf[tsBufferSize] = { 0 };
W32_DEBUG_TRACE(timestamp(tsbuf, false));
}
W32_DEBUG_TRACE(text);
#else
if (doTimestamp) {
char tsbuf[tsBufferSize] = { 0 };
std::cout << timestamp(tsbuf, doMicros);
}
std::cout << text;
fflush(stdout);
#endif
callProcs(level, text);
}
}
void logDebugMessageArgs(int level, const char* fmt, va_list ap)
{
char buffer[8192] = { 0 };
if (!fmt) {
return;
}
vsnprintf(buffer, sizeof(buffer), fmt, ap);
realLogDebugMessage(level, buffer);
}
void logDebugMessage(int level, const char* fmt, ...)
{
va_list ap;
va_start(ap, fmt);
logDebugMessageArgs(level, fmt, ap);
va_end(ap);
}
void logDebugMessage(int level, const std::string &text)
{
if (text.empty()) {
return;
}
realLogDebugMessage(level, text.c_str());
}
//============================================================================//
//============================================================================//
// Local Variables: ***
// mode: C++ ***
// tab-width: 8 ***
// c-basic-offset: 2 ***
// indent-tabs-mode: t ***
// End: ***
// ex: shiftwidth=2 tabstop=8
<|endoftext|> |
<commit_before>/*!
* \author ddubois
* \date 28-Apr-18.
*/
#ifndef NOVA_RENDERER_FRAMEBUFFER_MANAGER_H
#define NOVA_RENDERER_FRAMEBUFFER_MANAGER_H
#include <cstdint>
#include <glm/glm.hpp>
#include <vector>
#include <vulkan/vulkan.h>
#include "../../util/utils.hpp"
namespace nova::renderer {
class vulkan_render_engine;
NOVA_EXCEPTION(swapchain_creation_failed);
NOVA_EXCEPTION(present_failed);
/*!
* \brief Deals with the swapchain, yo
*
* Methods to get he next swapchain image and whatnot are found here
*
* You can even get the framebuffer constructed from the current swapchain. Wow!
*/
class swapchain_manager {
public:
swapchain_manager(uint32_t num_swapchain_images,
vulkan_render_engine& render_engine,
glm::ivec2 window_dimensions,
const std::vector<VkPresentModeKHR>& present_modes);
void present_current_image(VkSemaphore wait_semaphores) const;
/*!
* \brief Acquires the next image in the swapchain, signalling the provided semaphore when the image is ready
* to be rendered to
*
* \param image_acquire_semaphore The semaphore to signal when the image is ready to be rendered to
*/
void acquire_next_swapchain_image(VkSemaphore image_acquire_semaphore);
void set_current_layout(VkImageLayout new_layout);
VkFramebuffer get_current_framebuffer();
VkFence get_current_frame_fence();
VkImage get_current_image();
VkImageLayout get_current_layout();
[[nodiscard]] VkExtent2D get_swapchain_extent() const;
[[nodiscard]] VkFormat get_swapchain_format() const;
// I've had a lot of bugs with RAII so here's an explicit cleanup method
void deinit();
[[nodiscard]] uint32_t get_current_index() const;
[[nodiscard]] uint32_t get_num_images() const;
private:
vulkan_render_engine& render_engine;
VkSwapchainKHR swapchain{};
VkExtent2D swapchain_extent;
VkPresentModeKHR present_mode;
VkFormat swapchain_format;
std::vector<VkFramebuffer> framebuffers;
std::vector<VkImageView> swapchain_image_views;
std::vector<VkImage> swapchain_images;
std::vector<VkImageLayout> swapchain_image_layouts;
std::vector<VkFence> fences;
uint32_t num_swapchain_images;
uint32_t cur_swapchain_index = 0;
static VkSurfaceFormatKHR choose_surface_format(const std::vector<VkSurfaceFormatKHR>& formats);
static VkPresentModeKHR choose_present_mode(const std::vector<VkPresentModeKHR>& modes);
static VkExtent2D choose_surface_extent(const VkSurfaceCapabilitiesKHR& caps, const glm::ivec2& window_dimensions);
void transition_swapchain_images_into_correct_layout(const std::vector<VkImage>& images) const;
};
} // namespace nova::renderer
#endif // NOVA_RENDERER_FRAMEBUFFER_MANAGER_H<commit_msg>Real format<commit_after>/*!
* \author ddubois
* \date 28-Apr-18.
*/
#ifndef NOVA_RENDERER_FRAMEBUFFER_MANAGER_H
#define NOVA_RENDERER_FRAMEBUFFER_MANAGER_H
#include <cstdint>
#include <glm/glm.hpp>
#include <vector>
#include <vulkan/vulkan.h>
#include "../../util/utils.hpp"
namespace nova::renderer {
class vulkan_render_engine;
NOVA_EXCEPTION(swapchain_creation_failed);
NOVA_EXCEPTION(present_failed);
/*!
* \brief Deals with the swapchain, yo
*
* Methods to get he next swapchain image and whatnot are found here
*
* You can even get the framebuffer constructed from the current swapchain. Wow!
*/
class swapchain_manager {
public:
swapchain_manager(uint32_t num_swapchain_images,
vulkan_render_engine& render_engine,
glm::ivec2 window_dimensions,
const std::vector<VkPresentModeKHR>& present_modes);
void present_current_image(VkSemaphore wait_semaphores) const;
/*!
* \brief Acquires the next image in the swapchain, signalling the provided semaphore when the image is ready
* to be rendered to
*
* \param image_acquire_semaphore The semaphore to signal when the image is ready to be rendered to
*/
void acquire_next_swapchain_image(VkSemaphore image_acquire_semaphore);
void set_current_layout(VkImageLayout new_layout);
VkFramebuffer get_current_framebuffer();
VkFence get_current_frame_fence();
VkImage get_current_image();
VkImageLayout get_current_layout();
[[nodiscard]] VkExtent2D get_swapchain_extent() const;
[[nodiscard]] VkFormat get_swapchain_format() const;
// I've had a lot of bugs with RAII so here's an explicit cleanup method
void deinit();
[[nodiscard]] uint32_t get_current_index() const;
[[nodiscard]] uint32_t get_num_images() const;
private:
vulkan_render_engine& render_engine;
VkSwapchainKHR swapchain{};
VkExtent2D swapchain_extent;
VkPresentModeKHR present_mode;
VkFormat swapchain_format;
std::vector<VkFramebuffer> framebuffers;
std::vector<VkImageView> swapchain_image_views;
std::vector<VkImage> swapchain_images;
std::vector<VkImageLayout> swapchain_image_layouts;
std::vector<VkFence> fences;
uint32_t num_swapchain_images;
uint32_t cur_swapchain_index = 0;
static VkSurfaceFormatKHR choose_surface_format(const std::vector<VkSurfaceFormatKHR>& formats);
static VkPresentModeKHR choose_present_mode(const std::vector<VkPresentModeKHR>& modes);
static VkExtent2D choose_surface_extent(const VkSurfaceCapabilitiesKHR& caps, const glm::ivec2& window_dimensions);
void transition_swapchain_images_into_correct_layout(const std::vector<VkImage>& images) const;
};
} // namespace nova::renderer
#endif // NOVA_RENDERER_FRAMEBUFFER_MANAGER_H<|endoftext|> |
<commit_before>/****************************************************************/
/* DO NOT MODIFY THIS HEADER */
/* MOOSE - Multiphysics Object Oriented Simulation Environment */
/* */
/* (c) 2010 Battelle Energy Alliance, LLC */
/* ALL RIGHTS RESERVED */
/* */
/* Prepared by Battelle Energy Alliance, LLC */
/* Under Contract No. DE-AC07-05ID14517 */
/* With the U. S. Department of Energy */
/* */
/* See COPYRIGHT for full restrictions */
/****************************************************************/
#include "ConstantIC.h"
#include "libmesh/point.h"
template<>
InputParameters validParams<ConstantIC>()
{
InputParameters params = validParams<InitialCondition>();
params.set<Real>("value") = 0.0;
return params;
}
ConstantIC::ConstantIC(const std::string & name, InputParameters parameters) :
InitialCondition(name, parameters),
_value(getParam<Real>("value"))
{
}
Real
ConstantIC::value(const Point & /*p*/)
{
return _value;
}
<commit_msg>Fixing ConstantIC's input parameters (refs #2300)<commit_after>/****************************************************************/
/* DO NOT MODIFY THIS HEADER */
/* MOOSE - Multiphysics Object Oriented Simulation Environment */
/* */
/* (c) 2010 Battelle Energy Alliance, LLC */
/* ALL RIGHTS RESERVED */
/* */
/* Prepared by Battelle Energy Alliance, LLC */
/* Under Contract No. DE-AC07-05ID14517 */
/* With the U. S. Department of Energy */
/* */
/* See COPYRIGHT for full restrictions */
/****************************************************************/
#include "ConstantIC.h"
#include "libmesh/point.h"
template<>
InputParameters validParams<ConstantIC>()
{
InputParameters params = validParams<InitialCondition>();
params.addRequiredParam<Real>("value", "The value to be set in IC");
return params;
}
ConstantIC::ConstantIC(const std::string & name, InputParameters parameters) :
InitialCondition(name, parameters),
_value(getParam<Real>("value"))
{
}
Real
ConstantIC::value(const Point & /*p*/)
{
return _value;
}
<|endoftext|> |
<commit_before>/*
* SessionOptions.cpp
*
* Copyright (C) 2009-12 by RStudio, Inc.
*
* Unless you have received this program directly from RStudio pursuant
* to the terms of a commercial license agreement with RStudio, then
* this program is licensed to you under the terms of version 3 of the
* GNU Affero General Public License. This program is distributed WITHOUT
* ANY EXPRESS OR IMPLIED WARRANTY, INCLUDING THOSE OF NON-INFRINGEMENT,
* MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. Please refer to the
* AGPL (http://www.gnu.org/licenses/agpl-3.0.txt) for more details.
*
*/
#include <session/SessionOptions.hpp>
#include <boost/foreach.hpp>
#include <core/FilePath.hpp>
#include <core/ProgramStatus.hpp>
#include <core/ProgramOptions.hpp>
#include <core/SafeConvert.hpp>
#include <core/system/System.hpp>
#include <core/system/Environment.hpp>
#include <core/Error.hpp>
#include <core/Log.hpp>
#include <session/SessionConstants.hpp>
using namespace core ;
namespace session {
namespace {
const char* const kDefaultPostbackPath = "bin/postback/rpostback";
void resolvePath(const FilePath& resourcePath, std::string* pPath)
{
if (!pPath->empty())
*pPath = resourcePath.complete(*pPath).absolutePath();
}
#ifdef __APPLE__
void resolvePostbackPath(const FilePath& resourcePath, std::string* pPath)
{
// On OSX we keep the postback scripts over in the MacOS directory
// rather than in the Resources directory -- make this adjustment
// when the default postback path has been passed
if (*pPath == kDefaultPostbackPath)
{
FilePath path = resourcePath.parent().complete("MacOS/postback/rpostback");
*pPath = path.absolutePath();
}
else
{
resolvePath(resourcePath, pPath);
}
}
#else
void resolvePostbackPath(const FilePath& resourcePath, std::string* pPath)
{
resolvePath(resourcePath, pPath);
}
#endif
}
Options& options()
{
static Options instance ;
return instance ;
}
core::ProgramStatus Options::read(int argc, char * const argv[])
{
using namespace boost::program_options ;
// compute the resource path
FilePath resourcePath;
Error error = core::system::installPath("..", argc, argv, &resourcePath);
if (error)
{
LOG_ERROR_MESSAGE("Unable to determine install path: "+error.summary());
return ProgramStatus::exitFailure();
}
// detect running in OSX bundle and tweak resource path
#ifdef __APPLE__
if (resourcePath.complete("Info.plist").exists())
resourcePath = resourcePath.complete("Resources");
#endif
// detect running in x64 directory and tweak resource path
#ifdef _WIN32
if (resourcePath.complete("x64").exists())
resourcePath = resourcePath.parent();
#endif
// verify installation flag
options_description verify("verify");
verify.add_options()
(kVerifyInstallationSessionOption,
value<bool>(&verifyInstallation_)->default_value(false),
"verify the current installation");
// program - name and execution
options_description program("program");
program.add_options()
(kProgramModeSessionOption,
value<std::string>(&programMode_)->default_value("server"),
"program mode (desktop or server");
// agreement
options_description agreement("agreement");
agreement.add_options()
("agreement-file",
value<std::string>(&agreementFilePath_)->default_value(""),
"agreement file");
// docs url
options_description docs("docs");
docs.add_options()
("docs-url",
value<std::string>(&docsURL_)->default_value(""),
"custom docs url");
// www options
options_description www("www") ;
www.add_options()
("www-local-path",
value<std::string>(&wwwLocalPath_)->default_value("www"),
"www local path")
("www-port",
value<std::string>(&wwwPort_)->default_value("8787"),
"port to listen on");
// session options
options_description session("session") ;
session.add_options()
("session-timeout-minutes",
value<int>(&timeoutMinutes_)->default_value(120),
"session timeout (minutes)" )
("session-preflight-script",
value<std::string>(&preflightScript_)->default_value(""),
"session preflight script")
("session-create-public-folder",
value<bool>(&createPublicFolder_)->default_value(false),
"automatically create public folder")
("session-rprofile-on-resume-default",
value<bool>(&rProfileOnResumeDefault_)->default_value(false),
"default user setting for running Rprofile on resume");
// r options
bool rShellEscape; // no longer works but don't want to break any
// config files which formerly used it
// TODO: eliminate this option entirely
options_description r("r") ;
r.add_options()
("r-core-source",
value<std::string>(&coreRSourcePath_)->default_value("R"),
"Core R source path")
("r-modules-source",
value<std::string>(&modulesRSourcePath_)->default_value("R/modules"),
"Modules R source path")
("r-session-packages",
value<std::string>(&sessionPackagesPath_)->default_value("R/library"),
"R packages path")
("r-libs-user",
value<std::string>(&rLibsUser_)->default_value("~/R/library"),
"R user library path")
("r-cran-repos",
value<std::string>(&rCRANRepos_)->default_value(""),
"Default CRAN repository")
("r-auto-reload-source",
value<bool>(&autoReloadSource_)->default_value(false),
"Reload R source if it changes during the session")
("r-compatible-graphics-engine-version",
value<int>(&rCompatibleGraphicsEngineVersion_)->default_value(10),
"Maximum graphics engine version we are compatible with")
("r-resources-path",
value<std::string>(&rResourcesPath_)->default_value("resources"),
"Directory containing external resources")
("r-shell-escape",
value<bool>(&rShellEscape)->default_value(false),
"Support shell escape (deprecated, no longer works)")
("r-home-dir-override",
value<std::string>(&rHomeDirOverride_)->default_value(""),
"Override for R_HOME (used for debug configurations)")
("r-doc-dir-override",
value<std::string>(&rDocDirOverride_)->default_value(""),
"Override for R_DOC_DIR (used for debug configurations)");
// limits options
options_description limits("limits");
limits.add_options()
("limit-file-upload-size-mb",
value<int>(&limitFileUploadSizeMb_)->default_value(0),
"limit of file upload size")
("limit-cpu-time-minutes",
value<int>(&limitCpuTimeMinutes_)->default_value(0),
"limit on time of top level computations")
("limit-xfs-disk-quota",
value<bool>(&limitXfsDiskQuota_)->default_value(false),
"limit xfs disk quota");
// external options
options_description external("external");
external.add_options()
("external-rpostback-path",
value<std::string>(&rpostbackPath_)->default_value(kDefaultPostbackPath),
"Path to rpostback executable")
("external-consoleio-path",
value<std::string>(&consoleIoPath_)->default_value("bin/consoleio.exe"),
"Path to consoleio executable")
("external-gnudiff-path",
value<std::string>(&gnudiffPath_)->default_value("bin/gnudiff"),
"Path to gnudiff utilities (windows-only)")
("external-gnugrep-path",
value<std::string>(&gnugrepPath_)->default_value("bin/gnugrep"),
"Path to gnugrep utilities (windows-only)")
("external-msysssh-path",
value<std::string>(&msysSshPath_)->default_value("bin/msys_ssh"),
"Path to msys_ssh utilities (windows-only)")
("external-sumatra-path",
value<std::string>(&sumatraPath_)->default_value("bin/sumatra"),
"Path to SumatraPDF (windows-only)")
("external-hunspell-dictionaries-path",
value<std::string>(&hunspellDictionariesPath_)->default_value("resources/dictionaries"),
"Path to hunspell dictionaries")
("external-mathjax-path",
value<std::string>(&mathjaxPath_)->default_value("resources/mathjax"),
"Path to mathjax library");
// user options (default user identity to current username)
std::string currentUsername = core::system::username();
options_description user("user") ;
user.add_options()
(kUserIdentitySessionOption "," kUserIdentitySessionOptionShort,
value<std::string>(&userIdentity_)->default_value(currentUsername),
"user identity" );
// define program options
FilePath defaultConfigPath("/etc/rstudio/rsession.conf");
std::string configFile = defaultConfigPath.exists() ?
defaultConfigPath.absolutePath() : "";
core::program_options::OptionsDescription optionsDesc("rsession",
configFile);
optionsDesc.commandLine.add(verify);
optionsDesc.commandLine.add(program);
optionsDesc.commandLine.add(agreement);
optionsDesc.commandLine.add(docs);
optionsDesc.commandLine.add(www);
optionsDesc.commandLine.add(session);
optionsDesc.commandLine.add(r);
optionsDesc.commandLine.add(limits);
optionsDesc.commandLine.add(external);
optionsDesc.commandLine.add(user);
// define groups included in config-file processing
optionsDesc.configFile.add(program);
optionsDesc.configFile.add(agreement);
optionsDesc.configFile.add(docs);
optionsDesc.configFile.add(www);
optionsDesc.configFile.add(session);
optionsDesc.configFile.add(r);
optionsDesc.configFile.add(limits);
optionsDesc.configFile.add(external);
optionsDesc.configFile.add(user);
// read configuration
ProgramStatus status = core::program_options::read(optionsDesc, argc,argv);
if (status.exit())
return status;
// make sure the program mode is valid
if (programMode_ != kSessionProgramModeDesktop &&
programMode_ != kSessionProgramModeServer)
{
LOG_ERROR_MESSAGE("invalid program mode: " + programMode_);
return ProgramStatus::exitFailure();
}
// compute program identity
programIdentity_ = "rsession-" + userIdentity_;
// provide special home path in temp directory if we are verifying
if (verifyInstallation_)
{
// we create a special home directory in server mode (since the
// user we are running under might not have a home directory)
if (programMode_ == kSessionProgramModeServer)
{
verifyInstallationHomeDir_ = "/tmp/rstudio-verify-installation";
Error error = FilePath(verifyInstallationHomeDir_).ensureDirectory();
if (error)
{
LOG_ERROR(error);
return ProgramStatus::exitFailure();
}
core::system::setenv("R_USER", verifyInstallationHomeDir_);
}
}
// compute user home path
FilePath userHomePath = core::system::userHomePath("R_USER|HOME");
userHomePath_ = userHomePath.absolutePath();
// compute user scratch path
std::string scratchPathName;
if (programMode_ == kSessionProgramModeDesktop)
scratchPathName = "RStudio-Desktop";
else
scratchPathName = "RStudio";
userScratchPath_ = core::system::userSettingsPath(
userHomePath,
scratchPathName).absolutePath();
// session timeout seconds is always -1 in desktop mode
if (programMode_ == kSessionProgramModeDesktop)
timeoutMinutes_ = 0;
// convert relative paths by completing from the app resource path
resolvePath(resourcePath, &rResourcesPath_);
resolvePath(resourcePath, &agreementFilePath_);
resolvePath(resourcePath, &wwwLocalPath_);
resolvePath(resourcePath, &coreRSourcePath_);
resolvePath(resourcePath, &modulesRSourcePath_);
resolvePath(resourcePath, &sessionPackagesPath_);
resolvePostbackPath(resourcePath, &rpostbackPath_);
#ifdef _WIN32
resolvePath(resourcePath, &consoleIoPath_);
resolvePath(resourcePath, &gnudiffPath_);
resolvePath(resourcePath, &gnugrepPath_);
resolvePath(resourcePath, &msysSshPath_);
resolvePath(resourcePath, &sumatraPath_);
#endif
resolvePath(resourcePath, &hunspellDictionariesPath_);
resolvePath(resourcePath, &mathjaxPath_);
// shared secret with parent
secret_ = core::system::getenv("RS_SHARED_SECRET");
/* SECURITY: Need RS_SHARED_SECRET to be available to
rpostback. However, we really ought to communicate
it in a more secure manner than this, at least on
Windows where even within the same user session some
processes can have different priviliges (integrity
levels) than others. For example, using a named pipe
with proper SACL to retrieve the shared secret, where
the name of the pipe is in an environment variable. */
//core::system::unsetenv("RS_SHARED_SECRET");
// initial working dir override
initialWorkingDirOverride_ = core::system::getenv("RS_INITIAL_WD");
core::system::unsetenv("RS_INITIAL_WD");
// initial environment file override
initialEnvironmentFileOverride_ = core::system::getenv("RS_INITIAL_ENV");
core::system::unsetenv("RS_INITIAL_ENV");
// initial project
initialProjectPath_ = core::system::getenv("RS_INITIAL_PROJECT");
core::system::unsetenv("RS_INITIAL_PROJECT");
// limit rpc client uid
limitRpcClientUid_ = -1;
std::string limitUid = core::system::getenv(kRStudioLimitRpcClientUid);
if (!limitUid.empty())
{
limitRpcClientUid_ = core::safe_convert::stringTo<int>(limitUid, -1);
core::system::unsetenv(kRStudioLimitRpcClientUid);
}
// return status
return status;
}
} // namespace session
<commit_msg>allow session timeout to be supressed via an environment variable<commit_after>/*
* SessionOptions.cpp
*
* Copyright (C) 2009-12 by RStudio, Inc.
*
* Unless you have received this program directly from RStudio pursuant
* to the terms of a commercial license agreement with RStudio, then
* this program is licensed to you under the terms of version 3 of the
* GNU Affero General Public License. This program is distributed WITHOUT
* ANY EXPRESS OR IMPLIED WARRANTY, INCLUDING THOSE OF NON-INFRINGEMENT,
* MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. Please refer to the
* AGPL (http://www.gnu.org/licenses/agpl-3.0.txt) for more details.
*
*/
#include <session/SessionOptions.hpp>
#include <boost/foreach.hpp>
#include <core/FilePath.hpp>
#include <core/ProgramStatus.hpp>
#include <core/ProgramOptions.hpp>
#include <core/SafeConvert.hpp>
#include <core/system/System.hpp>
#include <core/system/Environment.hpp>
#include <core/Error.hpp>
#include <core/Log.hpp>
#include <session/SessionConstants.hpp>
using namespace core ;
namespace session {
namespace {
const char* const kDefaultPostbackPath = "bin/postback/rpostback";
void resolvePath(const FilePath& resourcePath, std::string* pPath)
{
if (!pPath->empty())
*pPath = resourcePath.complete(*pPath).absolutePath();
}
#ifdef __APPLE__
void resolvePostbackPath(const FilePath& resourcePath, std::string* pPath)
{
// On OSX we keep the postback scripts over in the MacOS directory
// rather than in the Resources directory -- make this adjustment
// when the default postback path has been passed
if (*pPath == kDefaultPostbackPath)
{
FilePath path = resourcePath.parent().complete("MacOS/postback/rpostback");
*pPath = path.absolutePath();
}
else
{
resolvePath(resourcePath, pPath);
}
}
#else
void resolvePostbackPath(const FilePath& resourcePath, std::string* pPath)
{
resolvePath(resourcePath, pPath);
}
#endif
}
Options& options()
{
static Options instance ;
return instance ;
}
core::ProgramStatus Options::read(int argc, char * const argv[])
{
using namespace boost::program_options ;
// compute the resource path
FilePath resourcePath;
Error error = core::system::installPath("..", argc, argv, &resourcePath);
if (error)
{
LOG_ERROR_MESSAGE("Unable to determine install path: "+error.summary());
return ProgramStatus::exitFailure();
}
// detect running in OSX bundle and tweak resource path
#ifdef __APPLE__
if (resourcePath.complete("Info.plist").exists())
resourcePath = resourcePath.complete("Resources");
#endif
// detect running in x64 directory and tweak resource path
#ifdef _WIN32
if (resourcePath.complete("x64").exists())
resourcePath = resourcePath.parent();
#endif
// verify installation flag
options_description verify("verify");
verify.add_options()
(kVerifyInstallationSessionOption,
value<bool>(&verifyInstallation_)->default_value(false),
"verify the current installation");
// program - name and execution
options_description program("program");
program.add_options()
(kProgramModeSessionOption,
value<std::string>(&programMode_)->default_value("server"),
"program mode (desktop or server");
// agreement
options_description agreement("agreement");
agreement.add_options()
("agreement-file",
value<std::string>(&agreementFilePath_)->default_value(""),
"agreement file");
// docs url
options_description docs("docs");
docs.add_options()
("docs-url",
value<std::string>(&docsURL_)->default_value(""),
"custom docs url");
// www options
options_description www("www") ;
www.add_options()
("www-local-path",
value<std::string>(&wwwLocalPath_)->default_value("www"),
"www local path")
("www-port",
value<std::string>(&wwwPort_)->default_value("8787"),
"port to listen on");
// session options
options_description session("session") ;
session.add_options()
("session-timeout-minutes",
value<int>(&timeoutMinutes_)->default_value(120),
"session timeout (minutes)" )
("session-preflight-script",
value<std::string>(&preflightScript_)->default_value(""),
"session preflight script")
("session-create-public-folder",
value<bool>(&createPublicFolder_)->default_value(false),
"automatically create public folder")
("session-rprofile-on-resume-default",
value<bool>(&rProfileOnResumeDefault_)->default_value(false),
"default user setting for running Rprofile on resume");
// r options
bool rShellEscape; // no longer works but don't want to break any
// config files which formerly used it
// TODO: eliminate this option entirely
options_description r("r") ;
r.add_options()
("r-core-source",
value<std::string>(&coreRSourcePath_)->default_value("R"),
"Core R source path")
("r-modules-source",
value<std::string>(&modulesRSourcePath_)->default_value("R/modules"),
"Modules R source path")
("r-session-packages",
value<std::string>(&sessionPackagesPath_)->default_value("R/library"),
"R packages path")
("r-libs-user",
value<std::string>(&rLibsUser_)->default_value("~/R/library"),
"R user library path")
("r-cran-repos",
value<std::string>(&rCRANRepos_)->default_value(""),
"Default CRAN repository")
("r-auto-reload-source",
value<bool>(&autoReloadSource_)->default_value(false),
"Reload R source if it changes during the session")
("r-compatible-graphics-engine-version",
value<int>(&rCompatibleGraphicsEngineVersion_)->default_value(10),
"Maximum graphics engine version we are compatible with")
("r-resources-path",
value<std::string>(&rResourcesPath_)->default_value("resources"),
"Directory containing external resources")
("r-shell-escape",
value<bool>(&rShellEscape)->default_value(false),
"Support shell escape (deprecated, no longer works)")
("r-home-dir-override",
value<std::string>(&rHomeDirOverride_)->default_value(""),
"Override for R_HOME (used for debug configurations)")
("r-doc-dir-override",
value<std::string>(&rDocDirOverride_)->default_value(""),
"Override for R_DOC_DIR (used for debug configurations)");
// limits options
options_description limits("limits");
limits.add_options()
("limit-file-upload-size-mb",
value<int>(&limitFileUploadSizeMb_)->default_value(0),
"limit of file upload size")
("limit-cpu-time-minutes",
value<int>(&limitCpuTimeMinutes_)->default_value(0),
"limit on time of top level computations")
("limit-xfs-disk-quota",
value<bool>(&limitXfsDiskQuota_)->default_value(false),
"limit xfs disk quota");
// external options
options_description external("external");
external.add_options()
("external-rpostback-path",
value<std::string>(&rpostbackPath_)->default_value(kDefaultPostbackPath),
"Path to rpostback executable")
("external-consoleio-path",
value<std::string>(&consoleIoPath_)->default_value("bin/consoleio.exe"),
"Path to consoleio executable")
("external-gnudiff-path",
value<std::string>(&gnudiffPath_)->default_value("bin/gnudiff"),
"Path to gnudiff utilities (windows-only)")
("external-gnugrep-path",
value<std::string>(&gnugrepPath_)->default_value("bin/gnugrep"),
"Path to gnugrep utilities (windows-only)")
("external-msysssh-path",
value<std::string>(&msysSshPath_)->default_value("bin/msys_ssh"),
"Path to msys_ssh utilities (windows-only)")
("external-sumatra-path",
value<std::string>(&sumatraPath_)->default_value("bin/sumatra"),
"Path to SumatraPDF (windows-only)")
("external-hunspell-dictionaries-path",
value<std::string>(&hunspellDictionariesPath_)->default_value("resources/dictionaries"),
"Path to hunspell dictionaries")
("external-mathjax-path",
value<std::string>(&mathjaxPath_)->default_value("resources/mathjax"),
"Path to mathjax library");
// user options (default user identity to current username)
std::string currentUsername = core::system::username();
options_description user("user") ;
user.add_options()
(kUserIdentitySessionOption "," kUserIdentitySessionOptionShort,
value<std::string>(&userIdentity_)->default_value(currentUsername),
"user identity" );
// define program options
FilePath defaultConfigPath("/etc/rstudio/rsession.conf");
std::string configFile = defaultConfigPath.exists() ?
defaultConfigPath.absolutePath() : "";
core::program_options::OptionsDescription optionsDesc("rsession",
configFile);
optionsDesc.commandLine.add(verify);
optionsDesc.commandLine.add(program);
optionsDesc.commandLine.add(agreement);
optionsDesc.commandLine.add(docs);
optionsDesc.commandLine.add(www);
optionsDesc.commandLine.add(session);
optionsDesc.commandLine.add(r);
optionsDesc.commandLine.add(limits);
optionsDesc.commandLine.add(external);
optionsDesc.commandLine.add(user);
// define groups included in config-file processing
optionsDesc.configFile.add(program);
optionsDesc.configFile.add(agreement);
optionsDesc.configFile.add(docs);
optionsDesc.configFile.add(www);
optionsDesc.configFile.add(session);
optionsDesc.configFile.add(r);
optionsDesc.configFile.add(limits);
optionsDesc.configFile.add(external);
optionsDesc.configFile.add(user);
// read configuration
ProgramStatus status = core::program_options::read(optionsDesc, argc,argv);
if (status.exit())
return status;
// make sure the program mode is valid
if (programMode_ != kSessionProgramModeDesktop &&
programMode_ != kSessionProgramModeServer)
{
LOG_ERROR_MESSAGE("invalid program mode: " + programMode_);
return ProgramStatus::exitFailure();
}
// compute program identity
programIdentity_ = "rsession-" + userIdentity_;
// provide special home path in temp directory if we are verifying
if (verifyInstallation_)
{
// we create a special home directory in server mode (since the
// user we are running under might not have a home directory)
if (programMode_ == kSessionProgramModeServer)
{
verifyInstallationHomeDir_ = "/tmp/rstudio-verify-installation";
Error error = FilePath(verifyInstallationHomeDir_).ensureDirectory();
if (error)
{
LOG_ERROR(error);
return ProgramStatus::exitFailure();
}
core::system::setenv("R_USER", verifyInstallationHomeDir_);
}
}
// compute user home path
FilePath userHomePath = core::system::userHomePath("R_USER|HOME");
userHomePath_ = userHomePath.absolutePath();
// compute user scratch path
std::string scratchPathName;
if (programMode_ == kSessionProgramModeDesktop)
scratchPathName = "RStudio-Desktop";
else
scratchPathName = "RStudio";
userScratchPath_ = core::system::userSettingsPath(
userHomePath,
scratchPathName).absolutePath();
// session timeout seconds is always -1 in desktop mode
if (programMode_ == kSessionProgramModeDesktop)
timeoutMinutes_ = 0;
// allow session timeout to be supressed via environment variable
if (!core::system::getenv("RSTUDIO_NO_SESSION_TIMEOUT").empty())
timeoutMinutes_ = 0;
// convert relative paths by completing from the app resource path
resolvePath(resourcePath, &rResourcesPath_);
resolvePath(resourcePath, &agreementFilePath_);
resolvePath(resourcePath, &wwwLocalPath_);
resolvePath(resourcePath, &coreRSourcePath_);
resolvePath(resourcePath, &modulesRSourcePath_);
resolvePath(resourcePath, &sessionPackagesPath_);
resolvePostbackPath(resourcePath, &rpostbackPath_);
#ifdef _WIN32
resolvePath(resourcePath, &consoleIoPath_);
resolvePath(resourcePath, &gnudiffPath_);
resolvePath(resourcePath, &gnugrepPath_);
resolvePath(resourcePath, &msysSshPath_);
resolvePath(resourcePath, &sumatraPath_);
#endif
resolvePath(resourcePath, &hunspellDictionariesPath_);
resolvePath(resourcePath, &mathjaxPath_);
// shared secret with parent
secret_ = core::system::getenv("RS_SHARED_SECRET");
/* SECURITY: Need RS_SHARED_SECRET to be available to
rpostback. However, we really ought to communicate
it in a more secure manner than this, at least on
Windows where even within the same user session some
processes can have different priviliges (integrity
levels) than others. For example, using a named pipe
with proper SACL to retrieve the shared secret, where
the name of the pipe is in an environment variable. */
//core::system::unsetenv("RS_SHARED_SECRET");
// initial working dir override
initialWorkingDirOverride_ = core::system::getenv("RS_INITIAL_WD");
core::system::unsetenv("RS_INITIAL_WD");
// initial environment file override
initialEnvironmentFileOverride_ = core::system::getenv("RS_INITIAL_ENV");
core::system::unsetenv("RS_INITIAL_ENV");
// initial project
initialProjectPath_ = core::system::getenv("RS_INITIAL_PROJECT");
core::system::unsetenv("RS_INITIAL_PROJECT");
// limit rpc client uid
limitRpcClientUid_ = -1;
std::string limitUid = core::system::getenv(kRStudioLimitRpcClientUid);
if (!limitUid.empty())
{
limitRpcClientUid_ = core::safe_convert::stringTo<int>(limitUid, -1);
core::system::unsetenv(kRStudioLimitRpcClientUid);
}
// return status
return status;
}
} // namespace session
<|endoftext|> |
<commit_before>/**
* @file device_properties.hpp
*
* @brief Classes for holding CUDA device properties and
* CUDA compute capability values.
*
*/
#pragma once
#ifndef CUDA_API_WRAPPERS_DEVICE_PROPERTIES_HPP_
#define CUDA_API_WRAPPERS_DEVICE_PROPERTIES_HPP_
#include <cuda/api/types.hpp>
#include <cuda/api/constants.hpp>
#include <cuda/api/pci_id.hpp>
#include <cuda_runtime_api.h>
namespace cuda {
namespace device {
/**
* A numeric designator of an architectural generation of CUDA devices
*
* @note See @url https://en.wikipedia.org/wiki/Volta_(microarchitecture)
* and previous architectures' pages via "previous" links.
* Also see @ref compute_capability_t .
*/
struct compute_architecture_t {
/**
* A @ref compute_capability_t has a "major" and a "minor" number,
* with "major" indicating the architecture; so this struct only
* has a "major" numner
*/
unsigned major;
static const char* name(unsigned major_compute_capability_version);
unsigned max_warp_schedulings_per_processor_cycle() const;
unsigned max_resident_warps_per_processor() const;
unsigned max_in_flight_threads_per_processor() const;
/**
* @note On some architectures, the shared memory / L1 balance is configurable,
* so you might not get the maxima here without making this configuration
* setting
*/
memory::shared::size_t max_shared_memory_per_block() const;
const char* name() const { return name(major); }
bool is_valid() const noexcept
{
return (major > 0) and (major < 9999); // Picked this up from the CUDA code somwhere
}
};
inline bool operator ==(const compute_architecture_t& lhs, const compute_architecture_t& rhs) noexcept
{
return lhs.major == rhs.major;
}
inline bool operator !=(const compute_architecture_t& lhs, const compute_architecture_t& rhs) noexcept
{
return lhs.major != rhs.major;
}
inline bool operator <(const compute_architecture_t& lhs, const compute_architecture_t& rhs) noexcept
{
return lhs.major < rhs.major;
}
inline bool operator <=(const compute_architecture_t& lhs, const compute_architecture_t& rhs) noexcept
{
return lhs.major < rhs.major;
}
inline bool operator >(const compute_architecture_t& lhs, const compute_architecture_t& rhs) noexcept
{
return lhs.major > rhs.major;
}
inline bool operator >=(const compute_architecture_t& lhs, const compute_architecture_t& rhs) noexcept
{
return lhs.major > rhs.major;
}
// TODO: Consider making this a non-POD struct,
// with a proper ctor checking validity, an operator converting to pair etc;
// however, that would require including at least std::utility, if not other
// stuff (e.g. for an std::hash specialization)
// TODO: If we constrained this to versions we know about, we could make the
// methods noexcept
/**
* A numeric designator of the computational capabilities of a CUDA device
*
* @note See @url https://en.wikipedia.org/wiki/CUDA#Version_features_and_specifications
* for a specification of capabilities by CC values
*/
struct compute_capability_t {
compute_architecture_t architecture;
unsigned minor_;
unsigned as_combined_number() const noexcept { return major() * 10 + minor_; }
unsigned max_warp_schedulings_per_processor_cycle() const;
unsigned max_resident_warps_per_processor() const;
unsigned max_in_flight_threads_per_processor() const;
/**
* @note On some architectures, the shared memory / L1 balance is configurable,
* so you might not get the maxima here without making this configuration
* setting
*/
memory::shared::size_t max_shared_memory_per_block() const;
unsigned major() const { return architecture.major; }
// We don't really need this method, but it allows for the same access pattern as for the
// major number, i.e. major() and minor(). Alternatively, we could have
// used a proxy
unsigned minor() const { return minor_; }
bool is_valid() const
{
return (major() > 0) and (major() < 9999) and (minor_ > 0) and (minor_ < 9999);
// Picked this up from the CUDA code somwhere
}
static compute_capability_t from_combined_number(unsigned combined)
{
return { combined / 10, combined % 10 };
}
};
inline bool operator ==(const compute_capability_t& lhs, const compute_capability_t& rhs) noexcept
{
return lhs.major() == rhs.major() and lhs.minor_ == rhs.minor_;
}
inline bool operator !=(const compute_capability_t& lhs, const compute_capability_t& rhs) noexcept
{
return lhs.major() != rhs.major() or lhs.minor_ != rhs.minor_;
}
inline bool operator <(const compute_capability_t& lhs, const compute_capability_t& rhs) noexcept
{
return lhs.major() < rhs.major() or (lhs.major() == rhs.major() and lhs.minor_ < rhs.minor_);
}
inline bool operator <=(const compute_capability_t& lhs, const compute_capability_t& rhs) noexcept
{
return lhs.major() < rhs.major() or (lhs.major() == rhs.major() and lhs.minor_ <= rhs.minor_);
}
inline bool operator >(const compute_capability_t& lhs, const compute_capability_t& rhs) noexcept
{
return lhs.major() > rhs.major() or (lhs.major() == rhs.major() and lhs.minor_ > rhs.minor_);
}
inline bool operator >=(const compute_capability_t& lhs, const compute_capability_t& rhs) noexcept
{
return lhs.major() > rhs.major() or (lhs.major() == rhs.major() and lhs.minor_ >= rhs.minor_);
}
inline compute_capability_t make_compute_capability(unsigned combined) noexcept
{
return compute_capability_t::from_combined_number(combined);
}
inline compute_capability_t make_compute_capability(unsigned major, unsigned minor) noexcept
{
return { major, minor };
}
/**
* @brief A structure holding a collection various properties of a device
*
* @note Somewhat annoyingly, CUDA devices have attributes, properties and flags.
* Attributes have integral number values; properties have all sorts of values,
* including arrays and limited-length strings (see
* @ref cuda::device::properties_t), and flags are either binary or
* small-finite-domain type fitting into an overall flagss value (see
* @ref cuda::device_t::flags_t). Flags and properties are obtained all at once,
* attributes are more one-at-a-time.
*
*/
struct properties_t : public cudaDeviceProp {
properties_t() = default;
properties_t(const cudaDeviceProp& cdp) noexcept : cudaDeviceProp(cdp) { };
properties_t(cudaDeviceProp&& cdp) noexcept : cudaDeviceProp(cdp) { };
bool usable_for_compute() const noexcept
{
return computeMode != cudaComputeModeProhibited;
}
compute_capability_t compute_capability() const { return { (unsigned) major, (unsigned) minor }; }
compute_architecture_t compute_architecture() const noexcept { return { (unsigned) major }; };
pci_location_t pci_id() const noexcept { return { pciDomainID, pciBusID, pciDeviceID }; }
unsigned long long max_in_flight_threads_on_device() const
{
return compute_capability().max_in_flight_threads_per_processor() * multiProcessorCount;
}
grid_block_dimension_t max_threads_per_block() const noexcept { return maxThreadsPerBlock; }
grid_block_dimension_t max_warps_per_block() const noexcept { return maxThreadsPerBlock / warp_size; }
size_t max_shared_memory_per_block() const noexcept { return sharedMemPerBlock; }
size_t global_memory_size() const noexcept { return totalGlobalMem; }
bool can_map_host_memory() const noexcept { return canMapHostMemory != 0; }
};
} // namespace device
} // namespace cuda
#endif // CUDA_API_WRAPPERS_DEVICE_PROPERTIES_HPP_
<commit_msg>Trying to avoid a GNU C Library warning about the use of identifier named `major` and `minor`.<commit_after>/**
* @file device_properties.hpp
*
* @brief Classes for holding CUDA device properties and
* CUDA compute capability values.
*
*/
#pragma once
#ifndef CUDA_API_WRAPPERS_DEVICE_PROPERTIES_HPP_
#define CUDA_API_WRAPPERS_DEVICE_PROPERTIES_HPP_
#include <cuda/api/types.hpp>
#include <cuda/api/constants.hpp>
#include <cuda/api/pci_id.hpp>
#include <cuda_runtime_api.h>
// The following un-definitions avoid warnings about
// the use of `major` and `minor` in certain versions
// of the GNU C library
#ifdef major
#undef major
#endif
#ifdef minor
#undef minor
#endif
namespace cuda {
namespace device {
/**
* A numeric designator of an architectural generation of CUDA devices
*
* @note See @url https://en.wikipedia.org/wiki/Volta_(microarchitecture)
* and previous architectures' pages via "previous" links.
* Also see @ref compute_capability_t .
*/
struct compute_architecture_t {
/**
* A @ref compute_capability_t has a "major" and a "minor" number,
* with "major" indicating the architecture; so this struct only
* has a "major" numner
*/
unsigned major;
static const char* name(unsigned major_compute_capability_version);
unsigned max_warp_schedulings_per_processor_cycle() const;
unsigned max_resident_warps_per_processor() const;
unsigned max_in_flight_threads_per_processor() const;
/**
* @note On some architectures, the shared memory / L1 balance is configurable,
* so you might not get the maxima here without making this configuration
* setting
*/
memory::shared::size_t max_shared_memory_per_block() const;
const char* name() const { return name(major); }
bool is_valid() const noexcept
{
return (major > 0) and (major < 9999); // Picked this up from the CUDA code somwhere
}
};
inline bool operator ==(const compute_architecture_t& lhs, const compute_architecture_t& rhs) noexcept
{
return lhs.major == rhs.major;
}
inline bool operator !=(const compute_architecture_t& lhs, const compute_architecture_t& rhs) noexcept
{
return lhs.major != rhs.major;
}
inline bool operator <(const compute_architecture_t& lhs, const compute_architecture_t& rhs) noexcept
{
return lhs.major < rhs.major;
}
inline bool operator <=(const compute_architecture_t& lhs, const compute_architecture_t& rhs) noexcept
{
return lhs.major < rhs.major;
}
inline bool operator >(const compute_architecture_t& lhs, const compute_architecture_t& rhs) noexcept
{
return lhs.major > rhs.major;
}
inline bool operator >=(const compute_architecture_t& lhs, const compute_architecture_t& rhs) noexcept
{
return lhs.major > rhs.major;
}
// TODO: Consider making this a non-POD struct,
// with a proper ctor checking validity, an operator converting to pair etc;
// however, that would require including at least std::utility, if not other
// stuff (e.g. for an std::hash specialization)
// TODO: If we constrained this to versions we know about, we could make the
// methods noexcept
/**
* A numeric designator of the computational capabilities of a CUDA device
*
* @note See @url https://en.wikipedia.org/wiki/CUDA#Version_features_and_specifications
* for a specification of capabilities by CC values
*/
struct compute_capability_t {
compute_architecture_t architecture;
unsigned minor_;
unsigned as_combined_number() const noexcept { return major() * 10 + minor_; }
unsigned max_warp_schedulings_per_processor_cycle() const;
unsigned max_resident_warps_per_processor() const;
unsigned max_in_flight_threads_per_processor() const;
/**
* @note On some architectures, the shared memory / L1 balance is configurable,
* so you might not get the maxima here without making this configuration
* setting
*/
memory::shared::size_t max_shared_memory_per_block() const;
unsigned major() const { return architecture.major; }
// We don't really need this method, but it allows for the same access pattern as for the
// major number, i.e. major() and minor(). Alternatively, we could have
// used a proxy
unsigned minor() const { return minor_; }
bool is_valid() const
{
return (major() > 0) and (major() < 9999) and (minor_ > 0) and (minor_ < 9999);
// Picked this up from the CUDA code somwhere
}
static compute_capability_t from_combined_number(unsigned combined)
{
return { combined / 10, combined % 10 };
}
};
inline bool operator ==(const compute_capability_t& lhs, const compute_capability_t& rhs) noexcept
{
return lhs.major() == rhs.major() and lhs.minor_ == rhs.minor_;
}
inline bool operator !=(const compute_capability_t& lhs, const compute_capability_t& rhs) noexcept
{
return lhs.major() != rhs.major() or lhs.minor_ != rhs.minor_;
}
inline bool operator <(const compute_capability_t& lhs, const compute_capability_t& rhs) noexcept
{
return lhs.major() < rhs.major() or (lhs.major() == rhs.major() and lhs.minor_ < rhs.minor_);
}
inline bool operator <=(const compute_capability_t& lhs, const compute_capability_t& rhs) noexcept
{
return lhs.major() < rhs.major() or (lhs.major() == rhs.major() and lhs.minor_ <= rhs.minor_);
}
inline bool operator >(const compute_capability_t& lhs, const compute_capability_t& rhs) noexcept
{
return lhs.major() > rhs.major() or (lhs.major() == rhs.major() and lhs.minor_ > rhs.minor_);
}
inline bool operator >=(const compute_capability_t& lhs, const compute_capability_t& rhs) noexcept
{
return lhs.major() > rhs.major() or (lhs.major() == rhs.major() and lhs.minor_ >= rhs.minor_);
}
inline compute_capability_t make_compute_capability(unsigned combined) noexcept
{
return compute_capability_t::from_combined_number(combined);
}
inline compute_capability_t make_compute_capability(unsigned major, unsigned minor) noexcept
{
return { major, minor };
}
/**
* @brief A structure holding a collection various properties of a device
*
* @note Somewhat annoyingly, CUDA devices have attributes, properties and flags.
* Attributes have integral number values; properties have all sorts of values,
* including arrays and limited-length strings (see
* @ref cuda::device::properties_t), and flags are either binary or
* small-finite-domain type fitting into an overall flagss value (see
* @ref cuda::device_t::flags_t). Flags and properties are obtained all at once,
* attributes are more one-at-a-time.
*
*/
struct properties_t : public cudaDeviceProp {
properties_t() = default;
properties_t(const cudaDeviceProp& cdp) noexcept : cudaDeviceProp(cdp) { };
properties_t(cudaDeviceProp&& cdp) noexcept : cudaDeviceProp(cdp) { };
bool usable_for_compute() const noexcept
{
return computeMode != cudaComputeModeProhibited;
}
compute_capability_t compute_capability() const { return { (unsigned) major, (unsigned) minor }; }
compute_architecture_t compute_architecture() const noexcept { return { (unsigned) major }; };
pci_location_t pci_id() const noexcept { return { pciDomainID, pciBusID, pciDeviceID }; }
unsigned long long max_in_flight_threads_on_device() const
{
return compute_capability().max_in_flight_threads_per_processor() * multiProcessorCount;
}
grid_block_dimension_t max_threads_per_block() const noexcept { return maxThreadsPerBlock; }
grid_block_dimension_t max_warps_per_block() const noexcept { return maxThreadsPerBlock / warp_size; }
size_t max_shared_memory_per_block() const noexcept { return sharedMemPerBlock; }
size_t global_memory_size() const noexcept { return totalGlobalMem; }
bool can_map_host_memory() const noexcept { return canMapHostMemory != 0; }
};
} // namespace device
} // namespace cuda
#endif // CUDA_API_WRAPPERS_DEVICE_PROPERTIES_HPP_
<|endoftext|> |
<commit_before>/*
L3G4200D implementation based on code by:
* http://bildr.org/2011/06/l3g4200d-arduino/
* http://www.pieter-jan.com/node/7
* https://github.com/sparkfun/Tri-Axis_Gyro_Breakout-L3G4200D
*/
#include "GY50.hpp"
#include "../../../utilities/Utilities.hpp"
namespace
{
const uint8_t kGyroAddress = 105;
const auto kMeasurementInterval = 100;
const float kGyroSensitivity = 0.07f;
const int kGyroThreshold = 12; // Smaller changes are to be ignored
} // namespace
using namespace smartcarlib::utils;
using namespace smartcarlib::constants::gy50;
GY50::GY50(int offset, unsigned long samplingInterval, Runtime& runtime)
: kOffset{ offset }
, kSamplingInterval{ samplingInterval }
, mRuntime(runtime)
, mPreviousSample{ 0 }
, mAttached{ false }
, mAngularDisplacement{ 0 }
{
}
int GY50::getHeading()
{
// Get the reading from (-180,180) to [0, 360) scale
auto normalizedReading = static_cast<int>(mAngularDisplacement) % 360;
return normalizedReading < 0 ? normalizedReading + 360 : normalizedReading;
}
void GY50::update()
{
unsigned long currentTime = mRuntime.currentTimeMillis();
unsigned long interval = currentTime - mPreviousSample;
if (interval <= kSamplingInterval)
{
return; // Not the time to read yet
}
int drift = kOffset - getAngularVelocity();
if (getAbsolute(drift) > kGyroThreshold)
{
float gyroRate = drift * kGyroSensitivity;
mAngularDisplacement += gyroRate / (1000.0 / interval);
}
mPreviousSample = currentTime;
}
void GY50::attach()
{
if (mAttached)
{
return;
}
static const uint8_t controlRegister1 = 0x20;
static const uint8_t controlRegister2 = 0x21;
static const uint8_t controlRegister3 = 0x22;
static const uint8_t controlRegister4 = 0x23;
static const uint8_t controlRegister5 = 0x24;
mRuntime.i2cInit();
// Enable z and turn off power down
writeL3G4200DRegister(controlRegister1, 0b00001100);
// If you'd like to adjust/use the HPF, you can edit the line below to configure CTRL_REG2
writeL3G4200DRegister(controlRegister2, 0b00000000);
// Configure CTRL_REG3 to generate data ready interrupt on INT2
// No interrupts used on INT1, if you'd like to configure INT1
// or INT2 otherwise, consult the datasheet
writeL3G4200DRegister(controlRegister3, 0b00001000);
// CTRL_REG4 controls the full-scale range, among other things
writeL3G4200DRegister(controlRegister4, 0b00110000);
// CTRL_REG5 controls high-pass filtering of outputs, use it if you'd like
writeL3G4200DRegister(controlRegister5, 0b00000000);
mAttached = true;
}
int GY50::getOffset(int measurements)
{
if (measurements <= 0)
{
return kError;
}
long sum = 0;
for (auto i = 0; i < measurements; i++)
{
sum += getAngularVelocity();
mRuntime.delayMillis(kMeasurementInterval);
}
return sum / measurements;
}
int GY50::getAngularVelocity()
{
attach();
static const uint8_t zAxisFirstByteRegister = 0x2D;
static const uint8_t zAxisSecondByteRegister = 0x2C;
auto firstByte = readL3G4200DRegister(zAxisFirstByteRegister);
// Serial.println("Bytes:");
// Serial.println(firstByte, BIN);
auto secondByte = readL3G4200DRegister(zAxisSecondByteRegister);
return static_cast<int16_t>((firstByte << 8) | secondByte);
}
int GY50::readL3G4200DRegister(uint8_t registerAddress)
{
mRuntime.i2cBeginTransmission(kGyroAddress);
mRuntime.i2cWrite(registerAddress);
mRuntime.i2cEndTransmission();
mRuntime.i2cRequestFrom(kGyroAddress, 1);
return mRuntime.i2cAvailable() ? mRuntime.i2cRead() : 0;
}
void GY50::writeL3G4200DRegister(uint8_t registerAddress, uint8_t value)
{
mRuntime.i2cBeginTransmission(kGyroAddress);
mRuntime.i2cWrite(registerAddress);
mRuntime.i2cWrite(value);
mRuntime.i2cEndTransmission();
}
<commit_msg>Remove unnecessary comments<commit_after>/*
L3G4200D implementation based on code by:
* http://bildr.org/2011/06/l3g4200d-arduino/
* http://www.pieter-jan.com/node/7
* https://github.com/sparkfun/Tri-Axis_Gyro_Breakout-L3G4200D
*/
#include "GY50.hpp"
#include "../../../utilities/Utilities.hpp"
namespace
{
const uint8_t kGyroAddress = 105;
const auto kMeasurementInterval = 100;
const float kGyroSensitivity = 0.07f;
const int kGyroThreshold = 12; // Smaller changes are to be ignored
} // namespace
using namespace smartcarlib::utils;
using namespace smartcarlib::constants::gy50;
GY50::GY50(int offset, unsigned long samplingInterval, Runtime& runtime)
: kOffset{ offset }
, kSamplingInterval{ samplingInterval }
, mRuntime(runtime)
, mPreviousSample{ 0 }
, mAttached{ false }
, mAngularDisplacement{ 0 }
{
}
int GY50::getHeading()
{
// Get the reading from (-180,180) to [0, 360) scale
auto normalizedReading = static_cast<int>(mAngularDisplacement) % 360;
return normalizedReading < 0 ? normalizedReading + 360 : normalizedReading;
}
void GY50::update()
{
unsigned long currentTime = mRuntime.currentTimeMillis();
unsigned long interval = currentTime - mPreviousSample;
if (interval <= kSamplingInterval)
{
return; // Not the time to read yet
}
int drift = kOffset - getAngularVelocity();
if (getAbsolute(drift) > kGyroThreshold)
{
float gyroRate = drift * kGyroSensitivity;
mAngularDisplacement += gyroRate / (1000.0 / interval);
}
mPreviousSample = currentTime;
}
void GY50::attach()
{
if (mAttached)
{
return;
}
static const uint8_t controlRegister1 = 0x20;
static const uint8_t controlRegister2 = 0x21;
static const uint8_t controlRegister3 = 0x22;
static const uint8_t controlRegister4 = 0x23;
static const uint8_t controlRegister5 = 0x24;
mRuntime.i2cInit();
// Enable z and turn off power down
writeL3G4200DRegister(controlRegister1, 0b00001100);
// If you'd like to adjust/use the HPF, you can edit the line below to configure CTRL_REG2
writeL3G4200DRegister(controlRegister2, 0b00000000);
// Configure CTRL_REG3 to generate data ready interrupt on INT2
// No interrupts used on INT1, if you'd like to configure INT1
// or INT2 otherwise, consult the datasheet
writeL3G4200DRegister(controlRegister3, 0b00001000);
// CTRL_REG4 controls the full-scale range, among other things
writeL3G4200DRegister(controlRegister4, 0b00110000);
// CTRL_REG5 controls high-pass filtering of outputs, use it if you'd like
writeL3G4200DRegister(controlRegister5, 0b00000000);
mAttached = true;
}
int GY50::getOffset(int measurements)
{
if (measurements <= 0)
{
return kError;
}
long sum = 0;
for (auto i = 0; i < measurements; i++)
{
sum += getAngularVelocity();
mRuntime.delayMillis(kMeasurementInterval);
}
return sum / measurements;
}
int GY50::getAngularVelocity()
{
attach();
static const uint8_t zAxisFirstByteRegister = 0x2D;
static const uint8_t zAxisSecondByteRegister = 0x2C;
auto firstByte = readL3G4200DRegister(zAxisFirstByteRegister);
auto secondByte = readL3G4200DRegister(zAxisSecondByteRegister);
return static_cast<int16_t>((firstByte << 8) | secondByte);
}
int GY50::readL3G4200DRegister(uint8_t registerAddress)
{
mRuntime.i2cBeginTransmission(kGyroAddress);
mRuntime.i2cWrite(registerAddress);
mRuntime.i2cEndTransmission();
mRuntime.i2cRequestFrom(kGyroAddress, 1);
return mRuntime.i2cAvailable() ? mRuntime.i2cRead() : 0;
}
void GY50::writeL3G4200DRegister(uint8_t registerAddress, uint8_t value)
{
mRuntime.i2cBeginTransmission(kGyroAddress);
mRuntime.i2cWrite(registerAddress);
mRuntime.i2cWrite(value);
mRuntime.i2cEndTransmission();
}
<|endoftext|> |
<commit_before>/*************************************************************************
* UrBackup - Client/Server backup system
* Copyright (C) 2011 Martin Raiber
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
**************************************************************************/
#ifndef CLIENT_ONLY
#include "server_writer.h"
#include "../Interface/Mutex.h"
#include "../Interface/Condition.h"
#include "../Interface/Server.h"
#include "../fsimageplugin/IVHDFile.h"
#include "../fsimageplugin/IFSImageFactory.h"
#include "../stringtools.h"
#include "os_functions.h"
#include "server_log.h"
#include "server_cleanup.h"
extern IFSImageFactory *image_fak;
const size_t free_space_lim=1000*1024*1024; //1000MB
const uint64 filebuf_lim=1000*1024*1024; //1000MB
ServerVHDWriter::ServerVHDWriter(IVHDFile *pVHD, unsigned int blocksize, unsigned int nbufs, int pClientid)
{
filebuffer=true;
clientid=pClientid;
vhd=pVHD;
bufmgr=new CBufMgr2(nbufs, blocksize);
if(filebuffer)
{
filebuf=new CFileBufMgr(500, false);
filebuf_writer=new ServerFileBufferWriter(this, blocksize);
filebuf_writer_ticket=Server->getThreadPool()->execute(filebuf_writer);
currfile=filebuf->getBuffer();
currfile_size=0;
}
mutex=Server->createMutex();
vhd_mutex=Server->createMutex();
cond=Server->createCondition();
exit=false;
exit_now=false;
has_error=false;
written=free_space_lim;
}
ServerVHDWriter::~ServerVHDWriter(void)
{
delete bufmgr;
if(filebuffer)
{
delete filebuf_writer;
delete filebuf;
}
Server->destroy(mutex);
Server->destroy(vhd_mutex);
Server->destroy(cond);
}
void ServerVHDWriter::operator()(void)
{
{
while(!exit_now)
{
BufferVHDItem item;
bool has_item=false;
bool do_exit;
{
IScopedLock lock(mutex);
do_exit=exit;
if(tqueue.empty() && exit==false)
cond->wait(&lock);
if(!tqueue.empty())
{
item=tqueue.front();
tqueue.pop();
has_item=true;
}
}
if(has_item)
{
if(!has_error)
{
if(!filebuffer)
{
writeVHD(item.pos, item.buf, item.bsize);
}
else
{
FileBufferVHDItem fbi;
fbi.pos=item.pos;
fbi.bsize=item.bsize;
writeRetry(currfile, (char*)&fbi, sizeof(FileBufferVHDItem));
currfile_size+=sizeof(FileBufferVHDItem);
writeRetry(currfile, item.buf, item.bsize);
currfile_size+=item.bsize;
if(currfile_size>filebuf_lim)
{
filebuf_writer->writeBuffer(currfile);
currfile=filebuf->getBuffer();
currfile_size=0;
}
}
}
bufmgr->releaseBuffer(item.buf);
}
else if(do_exit)
{
break;
}
if(!filebuffer && written>=free_space_lim/2)
{
written=0;
checkFreeSpaceAndCleanup();
}
}
}
if(filebuf)
{
filebuf_writer->writeBuffer(currfile);
if(!exit_now)
filebuf_writer->doExit();
else
filebuf_writer->doExitNow();
Server->getThreadPool()->waitFor(filebuf_writer_ticket);
}
image_fak->destroyVHDFile(vhd);
}
void ServerVHDWriter::checkFreeSpaceAndCleanup(void)
{
std::wstring p;
{
IScopedLock lock(vhd_mutex);
p=ExtractFilePath(vhd->getFilename());
}
int64 fs=os_free_space(os_file_prefix()+p);
if(fs!=-1 && fs <= free_space_lim )
{
Server->Log("Not enough free space. Waiting for cleanup...");
if(!cleanupSpace())
{
Server->Log("Not enough free space.", LL_WARNING);
}
}
}
void ServerVHDWriter::writeVHD(uint64 pos, char *buf, unsigned int bsize)
{
IScopedLock lock(vhd_mutex);
vhd->Seek(pos);
bool b=vhd->Write(buf, bsize);
written+=bsize;
if(!b)
{
std::wstring p=ExtractFilePath(vhd->getFilename());
int64 fs=os_free_space(os_file_prefix()+p);
if(fs!=-1 && fs <= free_space_lim )
{
Server->Log("Not enough free space. Waiting for cleanup...");
if(cleanupSpace())
{
if(!vhd->Write(buf, bsize))
{
ServerLogger::Log(clientid, "FATAL: Writing failed after cleanup", LL_ERROR);
has_error=true;
}
}
else
{
has_error=true;
Server->Log("FATAL: NOT ENOUGH free space. Cleanup failed.", LL_ERROR);
}
}
else
{
has_error=true;
ServerLogger::Log(clientid, "FATAL: Error writing to VHD-File.", LL_ERROR);
}
}
}
char *ServerVHDWriter::getBuffer(void)
{
return bufmgr->getBuffer();
}
void ServerVHDWriter::writeBuffer(uint64 pos, char *buf, unsigned int bsize)
{
IScopedLock lock(mutex);
BufferVHDItem item;
item.pos=pos;
item.buf=buf;
item.bsize=bsize;
tqueue.push(item);
cond->notify_all();
}
void ServerVHDWriter::freeBuffer(char *buf)
{
bufmgr->releaseBuffer(buf);
}
void ServerVHDWriter::doExit(void)
{
IScopedLock lock(mutex);
exit=true;
finish=true;
cond->notify_all();
}
void ServerVHDWriter::doExitNow(void)
{
IScopedLock lock(mutex);
exit=true;
exit_now=true;
finish=true;
cond->notify_all();
}
void ServerVHDWriter::doFinish(void)
{
IScopedLock lock(mutex);
finish=true;
cond->notify_all();
}
size_t ServerVHDWriter::getQueueSize(void)
{
IScopedLock lock(mutex);
return tqueue.size();
}
bool ServerVHDWriter::hasError(void)
{
return has_error;
}
IMutex * ServerVHDWriter::getVHDMutex(void)
{
return vhd_mutex;
}
IVHDFile* ServerVHDWriter::getVHD(void)
{
return vhd;
}
bool ServerVHDWriter::cleanupSpace(void)
{
ServerLogger::Log(clientid, "Not enough free space. Cleaning up.", LL_INFO);
ServerCleanupThread cleanup;
if(!cleanup.do_cleanup(free_space_lim) )
{
ServerLogger::Log(clientid, "Could not free space for image. NOT ENOUGH FREE SPACE.", LL_ERROR);
return false;
}
return true;
}
void ServerVHDWriter::freeFile(IFile *buf)
{
filebuf->releaseBuffer(buf);
}
void ServerVHDWriter::writeRetry(IFile *f, char *buf, unsigned int bsize)
{
unsigned int off=0;
unsigned int r;
while( (r=f->Write(buf+off, bsize-off))!=bsize-off)
{
off+=r;
Server->Log("Error writing to file \""+f->getFilename()+"\". Retrying", LL_WARNING);
Server->wait(10000);
}
}
ServerFileBufferWriter::ServerFileBufferWriter(ServerVHDWriter *pParent, unsigned int pBlocksize) : parent(pParent), blocksize(pBlocksize)
{
mutex=Server->createMutex();
cond=Server->createCondition();
exit=false;
exit_now=false;
written=free_space_lim;
}
ServerFileBufferWriter::~ServerFileBufferWriter(void)
{
while(!fb_queue.empty())
{
parent->freeFile(fb_queue.front());
fb_queue.pop();
}
Server->destroy(mutex);
Server->destroy(cond);
}
void ServerFileBufferWriter::operator()(void)
{
char *blockbuf=new char[blocksize];
unsigned int blockbuf_size=blocksize;
while(!exit_now)
{
IFile* tmp;
bool has_item=false;
{
IScopedLock lock(mutex);
while(fb_queue.empty() && exit==false)
{
cond->wait(&lock);
}
if(!fb_queue.empty())
{
has_item=true;
tmp=fb_queue.front();
fb_queue.pop();
}
}
if(has_item)
{
tmp->Seek(0);
uint64 tpos=0;
uint64 tsize=tmp->Size();
while(tpos<tsize)
{
if(!parent->hasError())
{
FileBufferVHDItem item;
if(tmp->Read((char*)&item, sizeof(FileBufferVHDItem))!=sizeof(FileBufferVHDItem))
{
Server->Log("Error reading FileBufferVHDItem", LL_ERROR);
}
tpos+=sizeof(FileBufferVHDItem);
unsigned int tw=item.bsize;
if(tpos+tw>tsize)
{
Server->Log("Size field is wrong", LL_ERROR);
}
if(tw>blockbuf_size)
{
delete []blockbuf;
blockbuf=new char[tw];
blockbuf_size=tw;
}
if(tmp->Read(blockbuf, tw)!=tw)
{
Server->Log("Error reading from tmp.f", LL_ERROR);
}
parent->writeVHD(item.pos, blockbuf, tw);
written+=tw;
tpos+=item.bsize;
if( written>=free_space_lim/2)
{
written=0;
parent->checkFreeSpaceAndCleanup();
}
}
else
{
break;
}
}
parent->freeFile(tmp);
}
else if(exit)
{
break;
}
}
delete []blockbuf;
}
void ServerFileBufferWriter::doExit(void)
{
exit=true;
cond->notify_all();
}
void ServerFileBufferWriter::doExitNow(void)
{
exit_now=true;
exit=true;
cond->notify_all();
}
void ServerFileBufferWriter::writeBuffer(IFile *buf)
{
IScopedLock lock(mutex);
fb_queue.push(buf);
cond->notify_all();
}
#endif //CLIENT_ONLY<commit_msg>Sped up imaging<commit_after>/*************************************************************************
* UrBackup - Client/Server backup system
* Copyright (C) 2011 Martin Raiber
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
**************************************************************************/
#ifndef CLIENT_ONLY
#include "server_writer.h"
#include "../Interface/Mutex.h"
#include "../Interface/Condition.h"
#include "../Interface/Server.h"
#include "../fsimageplugin/IVHDFile.h"
#include "../fsimageplugin/IFSImageFactory.h"
#include "../stringtools.h"
#include "os_functions.h"
#include "server_log.h"
#include "server_cleanup.h"
extern IFSImageFactory *image_fak;
const size_t free_space_lim=1000*1024*1024; //1000MB
const uint64 filebuf_lim=1000*1024*1024; //1000MB
ServerVHDWriter::ServerVHDWriter(IVHDFile *pVHD, unsigned int blocksize, unsigned int nbufs, int pClientid)
{
filebuffer=true;
clientid=pClientid;
vhd=pVHD;
if(filebuffer)
{
bufmgr=new CBufMgr2(nbufs, sizeof(FileBufferVHDItem)+blocksize);
}
else
{
bufmgr=new CBufMgr2(nbufs, blocksize);
}
if(filebuffer)
{
filebuf=new CFileBufMgr(500, false);
filebuf_writer=new ServerFileBufferWriter(this, blocksize);
filebuf_writer_ticket=Server->getThreadPool()->execute(filebuf_writer);
currfile=filebuf->getBuffer();
currfile_size=0;
}
mutex=Server->createMutex();
vhd_mutex=Server->createMutex();
cond=Server->createCondition();
exit=false;
exit_now=false;
has_error=false;
written=free_space_lim;
}
ServerVHDWriter::~ServerVHDWriter(void)
{
delete bufmgr;
if(filebuffer)
{
delete filebuf_writer;
delete filebuf;
}
Server->destroy(mutex);
Server->destroy(vhd_mutex);
Server->destroy(cond);
}
void ServerVHDWriter::operator()(void)
{
{
while(!exit_now)
{
BufferVHDItem item;
bool has_item=false;
bool do_exit;
{
IScopedLock lock(mutex);
do_exit=exit;
if(tqueue.empty() && exit==false)
cond->wait(&lock);
if(!tqueue.empty())
{
item=tqueue.front();
tqueue.pop();
has_item=true;
}
}
if(has_item)
{
if(!has_error)
{
if(!filebuffer)
{
writeVHD(item.pos, item.buf, item.bsize);
}
else
{
FileBufferVHDItem *fbi=(FileBufferVHDItem*)(item.buf-sizeof(FileBufferVHDItem));
fbi->pos=item.pos;
fbi->bsize=item.bsize;
writeRetry(currfile, (char*)fbi, sizeof(FileBufferVHDItem)+item.bsize);
currfile_size+=item.bsize+sizeof(FileBufferVHDItem);
if(currfile_size>filebuf_lim)
{
filebuf_writer->writeBuffer(currfile);
currfile=filebuf->getBuffer();
currfile_size=0;
}
}
}
freeBuffer(item.buf);
}
else if(do_exit)
{
break;
}
if(!filebuffer && written>=free_space_lim/2)
{
written=0;
checkFreeSpaceAndCleanup();
}
}
}
if(filebuf)
{
filebuf_writer->writeBuffer(currfile);
if(!exit_now)
filebuf_writer->doExit();
else
filebuf_writer->doExitNow();
Server->getThreadPool()->waitFor(filebuf_writer_ticket);
}
image_fak->destroyVHDFile(vhd);
}
void ServerVHDWriter::checkFreeSpaceAndCleanup(void)
{
std::wstring p;
{
IScopedLock lock(vhd_mutex);
p=ExtractFilePath(vhd->getFilename());
}
int64 fs=os_free_space(os_file_prefix()+p);
if(fs!=-1 && fs <= free_space_lim )
{
Server->Log("Not enough free space. Waiting for cleanup...");
if(!cleanupSpace())
{
Server->Log("Not enough free space.", LL_WARNING);
}
}
}
void ServerVHDWriter::writeVHD(uint64 pos, char *buf, unsigned int bsize)
{
IScopedLock lock(vhd_mutex);
vhd->Seek(pos);
bool b=vhd->Write(buf, bsize);
written+=bsize;
if(!b)
{
std::wstring p=ExtractFilePath(vhd->getFilename());
int64 fs=os_free_space(os_file_prefix()+p);
if(fs!=-1 && fs <= free_space_lim )
{
Server->Log("Not enough free space. Waiting for cleanup...");
if(cleanupSpace())
{
if(!vhd->Write(buf, bsize))
{
ServerLogger::Log(clientid, "FATAL: Writing failed after cleanup", LL_ERROR);
has_error=true;
}
}
else
{
has_error=true;
Server->Log("FATAL: NOT ENOUGH free space. Cleanup failed.", LL_ERROR);
}
}
else
{
has_error=true;
ServerLogger::Log(clientid, "FATAL: Error writing to VHD-File.", LL_ERROR);
}
}
}
char *ServerVHDWriter::getBuffer(void)
{
if(filebuffer)
return bufmgr->getBuffer()+sizeof(FileBufferVHDItem);
else
return bufmgr->getBuffer();
}
void ServerVHDWriter::writeBuffer(uint64 pos, char *buf, unsigned int bsize)
{
IScopedLock lock(mutex);
BufferVHDItem item;
item.pos=pos;
item.buf=buf;
item.bsize=bsize;
tqueue.push(item);
cond->notify_all();
}
void ServerVHDWriter::freeBuffer(char *buf)
{
if(filebuffer)
bufmgr->releaseBuffer(buf-sizeof(FileBufferVHDItem));
else
bufmgr->releaseBuffer(buf);
}
void ServerVHDWriter::doExit(void)
{
IScopedLock lock(mutex);
exit=true;
finish=true;
cond->notify_all();
}
void ServerVHDWriter::doExitNow(void)
{
IScopedLock lock(mutex);
exit=true;
exit_now=true;
finish=true;
cond->notify_all();
}
void ServerVHDWriter::doFinish(void)
{
IScopedLock lock(mutex);
finish=true;
cond->notify_all();
}
size_t ServerVHDWriter::getQueueSize(void)
{
IScopedLock lock(mutex);
return tqueue.size();
}
bool ServerVHDWriter::hasError(void)
{
return has_error;
}
IMutex * ServerVHDWriter::getVHDMutex(void)
{
return vhd_mutex;
}
IVHDFile* ServerVHDWriter::getVHD(void)
{
return vhd;
}
bool ServerVHDWriter::cleanupSpace(void)
{
ServerLogger::Log(clientid, "Not enough free space. Cleaning up.", LL_INFO);
ServerCleanupThread cleanup;
if(!cleanup.do_cleanup(free_space_lim) )
{
ServerLogger::Log(clientid, "Could not free space for image. NOT ENOUGH FREE SPACE.", LL_ERROR);
return false;
}
return true;
}
void ServerVHDWriter::freeFile(IFile *buf)
{
filebuf->releaseBuffer(buf);
}
void ServerVHDWriter::writeRetry(IFile *f, char *buf, unsigned int bsize)
{
unsigned int off=0;
while( off<bsize )
{
unsigned int r=f->Write(buf+off, bsize-off);
off+=r;
if(off<bsize)
{
Server->Log("Error writing to file \""+f->getFilename()+"\". Retrying", LL_WARNING);
Server->wait(10000);
}
}
}
//-------------FilebufferWriter-----------------
ServerFileBufferWriter::ServerFileBufferWriter(ServerVHDWriter *pParent, unsigned int pBlocksize) : parent(pParent), blocksize(pBlocksize)
{
mutex=Server->createMutex();
cond=Server->createCondition();
exit=false;
exit_now=false;
written=free_space_lim;
}
ServerFileBufferWriter::~ServerFileBufferWriter(void)
{
while(!fb_queue.empty())
{
parent->freeFile(fb_queue.front());
fb_queue.pop();
}
Server->destroy(mutex);
Server->destroy(cond);
}
void ServerFileBufferWriter::operator()(void)
{
char *blockbuf=new char[blocksize+sizeof(FileBufferVHDItem)];
unsigned int blockbuf_size=blocksize+sizeof(FileBufferVHDItem);
while(!exit_now)
{
IFile* tmp;
bool has_item=false;
{
IScopedLock lock(mutex);
while(fb_queue.empty() && exit==false)
{
cond->wait(&lock);
}
if(!fb_queue.empty())
{
has_item=true;
tmp=fb_queue.front();
fb_queue.pop();
}
}
if(has_item)
{
tmp->Seek(0);
uint64 tpos=0;
uint64 tsize=tmp->Size();
while(tpos<tsize)
{
if(!parent->hasError())
{
unsigned int tw=blockbuf_size;
bool old_method=false;
if(tw<sizeof(FileBufferVHDItem) || tmp->Read(blockbuf, tw)!=tw)
{
old_method=true;
}
else
{
FileBufferVHDItem *item=(FileBufferVHDItem*)blockbuf;
if(tw==item->bsize+sizeof(FileBufferVHDItem) )
{
parent->writeVHD(item->pos, blockbuf+sizeof(FileBufferVHDItem), item->bsize);
written+=item->bsize;
tpos+=item->bsize+sizeof(FileBufferVHDItem);
}
else
{
old_method=true;
}
}
if(old_method==true)
{
tmp->Seek(tpos);
FileBufferVHDItem item;
if(tmp->Read((char*)&item, sizeof(FileBufferVHDItem))!=sizeof(FileBufferVHDItem))
{
Server->Log("Error reading FileBufferVHDItem", LL_ERROR);
}
tpos+=sizeof(FileBufferVHDItem);
unsigned int tw=item.bsize;
if(tpos+tw>tsize)
{
Server->Log("Size field is wrong", LL_ERROR);
}
if(tw>blockbuf_size)
{
delete []blockbuf;
blockbuf=new char[tw+sizeof(FileBufferVHDItem)];
blockbuf_size=tw+sizeof(FileBufferVHDItem);
}
if(tmp->Read(blockbuf, tw)!=tw)
{
Server->Log("Error reading from tmp.f", LL_ERROR);
}
parent->writeVHD(item.pos, blockbuf, tw);
written+=tw;
tpos+=item.bsize;
}
if( written>=free_space_lim/2)
{
written=0;
parent->checkFreeSpaceAndCleanup();
}
}
else
{
break;
}
}
parent->freeFile(tmp);
}
else if(exit)
{
break;
}
}
delete []blockbuf;
}
void ServerFileBufferWriter::doExit(void)
{
exit=true;
cond->notify_all();
}
void ServerFileBufferWriter::doExitNow(void)
{
exit_now=true;
exit=true;
cond->notify_all();
}
void ServerFileBufferWriter::writeBuffer(IFile *buf)
{
IScopedLock lock(mutex);
fb_queue.push(buf);
cond->notify_all();
}
#endif //CLIENT_ONLY<|endoftext|> |
<commit_before>// -*- C++ -*-
// The MIT License (MIT)
//
// Copyright (c) 2021 Alexander Samoilov
//
// 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 "PoissonProblem.hpp"
#include "ChebyshevDifferentiate.hpp"
PoissonProblem::PoissonProblem(size_t M, size_t N,
double x_min, double x_max,
double y_min, double y_max,
bool verbose)
: verbose_(verbose),
M_(M), N_(N),
x_grid_(M + 1),
y_grid_(N + 1),
ome_ (M + 1, N + 1),
psi_ (M + 1, N + 1),
border_(M, N)
{
double xa = 0.5*(x_min-x_max);
double xb = 0.5*(x_min+x_max);
double ya = 0.5*(y_min-y_max);
double yb = 0.5*(y_min+y_max);
for (size_t i = 0; i <= M_; ++i) {
x_grid_[i] = xa*std::cos(M_PI*i/(double)M_)+xb;
}
for (size_t i = 0; i <= N_; ++i) {
y_grid_[i] = ya*std::cos(M_PI*i/(double)N_)+yb;
}
if (verbose_) {
std::cout << "x_grid: [" << x_grid_ << "]\n";
std::cout << "y_grid: [" << y_grid_ << "]\n";
}
// zero boundary conditions
border_.left_ = RowVectorXd::Zero(M_ + 1);
border_.down_ = RowVectorXd::Zero(N_ + 1);
border_.right_ = RowVectorXd::Zero(M_ + 1);
border_.up_ = RowVectorXd::Zero(N_ + 1);
// fill right hand function
for (size_t i = 0; i <= M_; ++i) {
for (size_t j = 0; j <= N_; ++j) {
ome_(i, j) = 32.*M_PI*M_PI * std::sin(4.*M_PI*x_grid_[i])
* std::sin(4.*M_PI*y_grid_[j]);
}
}
}
void PoissonProblem::generate_matrix(size_t n, Eigen::Ref<RowMatrixXd> ma)
{
// TODO use MatrixXd::Identity(rows,cols)
for (size_t i=0; i<=n; ++i) {
for (size_t j=0; j<=n; ++j) {
ma(i, j) = detail::id(i, j);
}
}
laplacian(n, ma, ma);
}
void PoissonProblem::homogeneous_boundary(size_t n,
Eigen::Ref<RowMatrixXd> in,
Eigen::Ref<RowMatrixXd> out)
{
for (size_t i=0; i<=n; i++) {
double evens = 0.0, odds = 0.0;
for (size_t j=1; j<=n-2; j+=2) {
odds -= in(i, j);
evens -= in(i, j+1);
}
if (out != in) {
for (size_t j=0; j<=n-2; j++) {
out(i, j) = in(i, j);
}
}
out(i, n-1) = odds;
out(i, n) = evens-in(i, 0);
/*
out(i, 0) = out(i, 1) = 0.0;
*/
}
}
void PoissonProblem::laplacian(size_t n,
Eigen::Ref<RowMatrixXd> in,
Eigen::Ref<RowMatrixXd> out)
{
homogeneous_boundary(n, in, out);
for (size_t i = 0; i <= n; ++i) {
}
}
<commit_msg>implemented laplacian in spectral space.<commit_after>// -*- C++ -*-
// The MIT License (MIT)
//
// Copyright (c) 2021 Alexander Samoilov
//
// 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 "PoissonProblem.hpp"
#include "ChebyshevDifferentiate.hpp"
PoissonProblem::PoissonProblem(size_t M, size_t N,
double x_min, double x_max,
double y_min, double y_max,
bool verbose)
: verbose_(verbose),
M_(M), N_(N),
x_grid_(M + 1),
y_grid_(N + 1),
ome_ (M + 1, N + 1),
psi_ (M + 1, N + 1),
border_(M, N)
{
double xa = 0.5*(x_min-x_max);
double xb = 0.5*(x_min+x_max);
double ya = 0.5*(y_min-y_max);
double yb = 0.5*(y_min+y_max);
for (size_t i = 0; i <= M_; ++i) {
x_grid_[i] = xa*std::cos(M_PI*i/(double)M_)+xb;
}
for (size_t i = 0; i <= N_; ++i) {
y_grid_[i] = ya*std::cos(M_PI*i/(double)N_)+yb;
}
if (verbose_) {
std::cout << "x_grid: [" << x_grid_ << "]\n";
std::cout << "y_grid: [" << y_grid_ << "]\n";
}
// zero boundary conditions
border_.left_ = RowVectorXd::Zero(M_ + 1);
border_.down_ = RowVectorXd::Zero(N_ + 1);
border_.right_ = RowVectorXd::Zero(M_ + 1);
border_.up_ = RowVectorXd::Zero(N_ + 1);
// fill right hand function
for (size_t i = 0; i <= M_; ++i) {
for (size_t j = 0; j <= N_; ++j) {
ome_(i, j) = 32.*M_PI*M_PI * std::sin(4.*M_PI*x_grid_[i])
* std::sin(4.*M_PI*y_grid_[j]);
}
}
}
void PoissonProblem::generate_matrix(size_t n, Eigen::Ref<RowMatrixXd> ma)
{
// TODO use MatrixXd::Identity(rows,cols)
for (size_t i=0; i<=n; ++i) {
for (size_t j=0; j<=n; ++j) {
ma(i, j) = detail::id(i, j);
}
}
laplacian(n, ma, ma);
}
void PoissonProblem::homogeneous_boundary(size_t n,
Eigen::Ref<RowMatrixXd> in,
Eigen::Ref<RowMatrixXd> out)
{
for (size_t i=0; i<=n; i++) {
double evens = 0.0, odds = 0.0;
for (size_t j=1; j<=n-2; j+=2) {
odds -= in(i, j);
evens -= in(i, j+1);
}
if (out != in) {
for (size_t j=0; j<=n-2; j++) {
out(i, j) = in(i, j);
}
}
out(i, n-1) = odds;
out(i, n) = evens-in(i, 0);
/*
out(i, 0) = out(i, 1) = 0.0;
*/
}
}
void PoissonProblem::laplacian(size_t n,
Eigen::Ref<RowMatrixXd> in,
Eigen::Ref<RowMatrixXd> out)
{
homogeneous_boundary(n, in, out);
for (size_t i = 0; i <= n; ++i) {
spectral_differentiate(n, out.row(i), out.row(i));
spectral_differentiate(n, out.row(i), out.row(i));
}
}
<|endoftext|> |
<commit_before>// Copyright (c) 2006-2008 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/extensions/extensions_service.h"
#include "base/file_util.h"
#include "base/values.h"
#include "base/string_util.h"
#include "base/thread.h"
#include "chrome/browser/browser_process.h"
#include "chrome/common/json_value_serializer.h"
// ExtensionsService
const FilePath::CharType* ExtensionsService::kInstallDirectoryName =
FILE_PATH_LITERAL("Extensions");
ExtensionsService::ExtensionsService(const FilePath& profile_directory)
: message_loop_(MessageLoop::current()),
backend_(new ExtensionsServiceBackend),
install_directory_(profile_directory.Append(kInstallDirectoryName)) {
}
ExtensionsService::~ExtensionsService() {
for (ExtensionList::iterator iter = extensions_.begin();
iter != extensions_.end(); ++iter) {
delete *iter;
}
}
bool ExtensionsService::Init() {
// TODO(aa): This message loop should probably come from a backend
// interface, similar to how the message loop for the frontend comes
// from the frontend interface.
g_browser_process->file_thread()->message_loop()->PostTask(FROM_HERE,
NewRunnableMethod(backend_.get(),
&ExtensionsServiceBackend::LoadExtensionsFromDirectory,
install_directory_,
scoped_refptr<ExtensionsServiceFrontendInterface>(this)));
// TODO(aa): Load extensions from other registered directories.
return true;
}
MessageLoop* ExtensionsService::GetMessageLoop() {
return message_loop_;
}
void ExtensionsService::OnExtensionsLoadedFromDirectory(
ExtensionList* new_extensions) {
extensions_.insert(extensions_.end(), new_extensions->begin(),
new_extensions->end());
delete new_extensions;
// TODO(aa): Notify extensions are loaded.
}
void ExtensionsService::OnExtensionLoadError(const std::string& error) {
// TODO(aa): Print the error message out somewhere better. I think we are
// going to need some sort of 'extension inspector'.
LOG(WARNING) << error;
}
// ExtensionsServicesBackend
bool ExtensionsServiceBackend::LoadExtensionsFromDirectory(
const FilePath& path,
scoped_refptr<ExtensionsServiceFrontendInterface> frontend) {
// Find all child directories in the install directory and load their
// manifests. Post errors and results to the frontend.
scoped_ptr<ExtensionList> extensions(new ExtensionList);
file_util::FileEnumerator enumerator(path.ToWStringHack(),
false, // not recursive
file_util::FileEnumerator::DIRECTORIES);
for (std::wstring child_path = enumerator.Next(); !child_path.empty();
child_path = enumerator.Next()) {
FilePath manifest_path = FilePath::FromWStringHack(child_path).Append(
Extension::kManifestFilename);
if (!file_util::PathExists(manifest_path)) {
ReportExtensionLoadError(frontend.get(), child_path,
Extension::kInvalidManifestError);
continue;
}
JSONFileValueSerializer serializer(manifest_path.ToWStringHack());
Value* root = NULL;
std::string error;
if (!serializer.Deserialize(&root, &error)) {
ReportExtensionLoadError(frontend.get(), child_path, error);
continue;
}
scoped_ptr<Value> scoped_root(root);
if (!root->IsType(Value::TYPE_DICTIONARY)) {
ReportExtensionLoadError(frontend.get(), child_path,
Extension::kInvalidManifestError);
continue;
}
scoped_ptr<Extension> extension(new Extension());
if (!extension->InitFromValue(*static_cast<DictionaryValue*>(root),
&error)) {
ReportExtensionLoadError(frontend.get(), child_path, error);
continue;
}
extensions->push_back(extension.release());
delete root;
}
ReportExtensionsLoaded(frontend.get(), extensions.release());
return true;
}
void ExtensionsServiceBackend::ReportExtensionLoadError(
ExtensionsServiceFrontendInterface *frontend, const std::wstring& path,
const std::string &error) {
std::string message = StringPrintf("Could not load extension from '%s'. %s",
WideToASCII(path).c_str(), error.c_str());
frontend->GetMessageLoop()->PostTask(FROM_HERE, NewRunnableMethod(
frontend, &ExtensionsServiceFrontendInterface::OnExtensionLoadError,
message));
}
void ExtensionsServiceBackend::ReportExtensionsLoaded(
ExtensionsServiceFrontendInterface *frontend, ExtensionList* extensions) {
frontend->GetMessageLoop()->PostTask(FROM_HERE, NewRunnableMethod(
frontend,
&ExtensionsServiceFrontendInterface::OnExtensionsLoadedFromDirectory,
extensions));
}
<commit_msg>bad merge, no need to delete a scoped_ptr<commit_after>// Copyright (c) 2006-2008 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/extensions/extensions_service.h"
#include "base/file_util.h"
#include "base/values.h"
#include "base/string_util.h"
#include "base/thread.h"
#include "chrome/browser/browser_process.h"
#include "chrome/common/json_value_serializer.h"
// ExtensionsService
const FilePath::CharType* ExtensionsService::kInstallDirectoryName =
FILE_PATH_LITERAL("Extensions");
ExtensionsService::ExtensionsService(const FilePath& profile_directory)
: message_loop_(MessageLoop::current()),
backend_(new ExtensionsServiceBackend),
install_directory_(profile_directory.Append(kInstallDirectoryName)) {
}
ExtensionsService::~ExtensionsService() {
for (ExtensionList::iterator iter = extensions_.begin();
iter != extensions_.end(); ++iter) {
delete *iter;
}
}
bool ExtensionsService::Init() {
// TODO(aa): This message loop should probably come from a backend
// interface, similar to how the message loop for the frontend comes
// from the frontend interface.
g_browser_process->file_thread()->message_loop()->PostTask(FROM_HERE,
NewRunnableMethod(backend_.get(),
&ExtensionsServiceBackend::LoadExtensionsFromDirectory,
install_directory_,
scoped_refptr<ExtensionsServiceFrontendInterface>(this)));
// TODO(aa): Load extensions from other registered directories.
return true;
}
MessageLoop* ExtensionsService::GetMessageLoop() {
return message_loop_;
}
void ExtensionsService::OnExtensionsLoadedFromDirectory(
ExtensionList* new_extensions) {
extensions_.insert(extensions_.end(), new_extensions->begin(),
new_extensions->end());
delete new_extensions;
// TODO(aa): Notify extensions are loaded.
}
void ExtensionsService::OnExtensionLoadError(const std::string& error) {
// TODO(aa): Print the error message out somewhere better. I think we are
// going to need some sort of 'extension inspector'.
LOG(WARNING) << error;
}
// ExtensionsServicesBackend
bool ExtensionsServiceBackend::LoadExtensionsFromDirectory(
const FilePath& path,
scoped_refptr<ExtensionsServiceFrontendInterface> frontend) {
// Find all child directories in the install directory and load their
// manifests. Post errors and results to the frontend.
scoped_ptr<ExtensionList> extensions(new ExtensionList);
file_util::FileEnumerator enumerator(path.ToWStringHack(),
false, // not recursive
file_util::FileEnumerator::DIRECTORIES);
for (std::wstring child_path = enumerator.Next(); !child_path.empty();
child_path = enumerator.Next()) {
FilePath manifest_path = FilePath::FromWStringHack(child_path).Append(
Extension::kManifestFilename);
if (!file_util::PathExists(manifest_path)) {
ReportExtensionLoadError(frontend.get(), child_path,
Extension::kInvalidManifestError);
continue;
}
JSONFileValueSerializer serializer(manifest_path.ToWStringHack());
Value* root = NULL;
std::string error;
if (!serializer.Deserialize(&root, &error)) {
ReportExtensionLoadError(frontend.get(), child_path, error);
continue;
}
scoped_ptr<Value> scoped_root(root);
if (!root->IsType(Value::TYPE_DICTIONARY)) {
ReportExtensionLoadError(frontend.get(), child_path,
Extension::kInvalidManifestError);
continue;
}
scoped_ptr<Extension> extension(new Extension());
if (!extension->InitFromValue(*static_cast<DictionaryValue*>(root),
&error)) {
ReportExtensionLoadError(frontend.get(), child_path, error);
continue;
}
extensions->push_back(extension.release());
}
ReportExtensionsLoaded(frontend.get(), extensions.release());
return true;
}
void ExtensionsServiceBackend::ReportExtensionLoadError(
ExtensionsServiceFrontendInterface *frontend, const std::wstring& path,
const std::string &error) {
std::string message = StringPrintf("Could not load extension from '%s'. %s",
WideToASCII(path).c_str(), error.c_str());
frontend->GetMessageLoop()->PostTask(FROM_HERE, NewRunnableMethod(
frontend, &ExtensionsServiceFrontendInterface::OnExtensionLoadError,
message));
}
void ExtensionsServiceBackend::ReportExtensionsLoaded(
ExtensionsServiceFrontendInterface *frontend, ExtensionList* extensions) {
frontend->GetMessageLoop()->PostTask(FROM_HERE, NewRunnableMethod(
frontend,
&ExtensionsServiceFrontendInterface::OnExtensionsLoadedFromDirectory,
extensions));
}
<|endoftext|> |
<commit_before>/********************************************************************************
** The MIT License (MIT)
**
** Copyright (c) 2013 Sascha Ludwig Häusler
**
** 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 "AbstractModel.h"
#include "AbstractModel_p.h"
namespace PublicServerSystem
{
namespace Web
{
namespace Model
{
AbstractModel::AbstractModel(QObject *parent) :
AbstractModel(new AbstractModelPrivate, parent)
{
}
AbstractModel::AbstractModel(arangodb::Document *doc, QObject *parent) :
AbstractModel(doc, new AbstractModelPrivate, parent)
{
}
AbstractModel::AbstractModel(const AbstractModel &mo) :
AbstractModel(new AbstractModelPrivate, mo.parent())
{
Q_D(AbstractModel);
d->doc = mo.d_ptr->doc;
}
AbstractModel::~AbstractModel()
{
if (! d_ptr->hasDocumentDestroyed) delete d_ptr->doc;
delete d_ptr;
}
void AbstractModel::save()
{
Q_D(AbstractModel);
if ( d->doc->save() ) {
d->doc->waitForResult();
}
}
void AbstractModel::saveAndDelete()
{
Q_D(AbstractModel);
d->hasDocumentDestroyed = true;
QObject::connect( d->doc, &arangodb::Document::destroyed,
this, &AbstractModel::deleteLater
);
d->doc->save();
d->doc->deleteAfterFinished();
}
QString AbstractModel::dbCollectionKey() const
{
Q_D(const AbstractModel);
return d->doc->key();
}
AbstractModel::AbstractModel(arangodb::Document *doc, AbstractModelPrivate *ptr, QObject *parent) :
AbstractModel(ptr, parent)
{
Q_D(AbstractModel);
d->doc = doc;
}
AbstractModel::AbstractModel(AbstractModelPrivate *ptr, QObject *parent) :
QObject(parent),
d_ptr(ptr)
{
}
QVariant AbstractModel::get(const QString &name) const
{
Q_D(const AbstractModel);
return d->doc->get(name);
}
void AbstractModel::set(const QString &name, QVariant val)
{
Q_D(AbstractModel);
d->doc->set(name, val);
}
Form::AbstractFormField *AbstractModel::field(const QString &referencingPropertyName, const QMetaObject &fieldClassObj, const QString &description)
{
Q_D(AbstractModel);
Form::AbstractFormField * thisField;
// If the field has already been created
if (d->fields.contains(referencingPropertyName)) {
thisField = d->fields.value(referencingPropertyName);
}
else {
thisField = qobject_cast<Form::AbstractFormField *>(fieldClassObj.newInstance(
Q_ARG(QString, referencingPropertyName),
Q_ARG(QString, description),
Q_ARG(QObject *, 0)
));
d->fields.insert(referencingPropertyName, thisField);
}
// Get current value for the field
thisField->setValue(d->doc->get(referencingPropertyName));
return thisField;
}
}
}
}
<commit_msg>Objects are only saved if they haven't been created<commit_after>/********************************************************************************
** The MIT License (MIT)
**
** Copyright (c) 2013 Sascha Ludwig Häusler
**
** 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 "AbstractModel.h"
#include "AbstractModel_p.h"
namespace PublicServerSystem
{
namespace Web
{
namespace Model
{
AbstractModel::AbstractModel(QObject *parent) :
AbstractModel(new AbstractModelPrivate, parent)
{
}
AbstractModel::AbstractModel(arangodb::Document *doc, QObject *parent) :
AbstractModel(doc, new AbstractModelPrivate, parent)
{
}
AbstractModel::AbstractModel(const AbstractModel &mo) :
AbstractModel(new AbstractModelPrivate, mo.parent())
{
Q_D(AbstractModel);
d->doc = mo.d_ptr->doc;
}
AbstractModel::~AbstractModel()
{
if (! d_ptr->hasDocumentDestroyed) delete d_ptr->doc;
delete d_ptr;
}
void AbstractModel::save()
{
Q_D(AbstractModel);
if ( d->doc->isCreated() ) {
d->doc->update();
d->doc->waitForResult();
}
else if ( d->doc->save() ) {
d->doc->waitForResult();
}
}
void AbstractModel::saveAndDelete()
{
Q_D(AbstractModel);
d->hasDocumentDestroyed = true;
QObject::connect( d->doc, &arangodb::Document::destroyed,
this, &AbstractModel::deleteLater
);
d->doc->save();
d->doc->deleteAfterFinished();
}
QString AbstractModel::dbCollectionKey() const
{
Q_D(const AbstractModel);
return d->doc->key();
}
AbstractModel::AbstractModel(arangodb::Document *doc, AbstractModelPrivate *ptr, QObject *parent) :
AbstractModel(ptr, parent)
{
Q_D(AbstractModel);
d->doc = doc;
}
AbstractModel::AbstractModel(AbstractModelPrivate *ptr, QObject *parent) :
QObject(parent),
d_ptr(ptr)
{
}
QVariant AbstractModel::get(const QString &name) const
{
Q_D(const AbstractModel);
return d->doc->get(name);
}
void AbstractModel::set(const QString &name, QVariant val)
{
Q_D(AbstractModel);
d->doc->set(name, val);
}
Form::AbstractFormField *AbstractModel::field(const QString &referencingPropertyName, const QMetaObject &fieldClassObj, const QString &description)
{
Q_D(AbstractModel);
Form::AbstractFormField * thisField;
// If the field has already been created
if (d->fields.contains(referencingPropertyName)) {
thisField = d->fields.value(referencingPropertyName);
}
else {
thisField = qobject_cast<Form::AbstractFormField *>(fieldClassObj.newInstance(
Q_ARG(QString, referencingPropertyName),
Q_ARG(QString, description),
Q_ARG(QObject *, 0)
));
d->fields.insert(referencingPropertyName, thisField);
}
// Get current value for the field
thisField->setValue(d->doc->get(referencingPropertyName));
return thisField;
}
}
}
}
<|endoftext|> |
<commit_before>#include "Halide.h"
#include <cstdlib>
#include <chrono>
#include <iomanip>
#include <fstream>
#include <iostream>
#include <fstream>
#include <string>
#include <time.h>
#include "configure.h"
#include "fused_resnet_block_generator_tiramisu.o.h"
#include <tiramisu/utils.h>
using namespace std;
bool compareFiles(const std::string &p1, const std::string &p2)
{
std::ifstream f1(p1, std::ifstream::binary | std::ifstream::ate);
std::ifstream f2(p2, std::ifstream::binary | std::ifstream::ate);
if (f1.fail() || f2.fail())
{
return false; //File problem
}
if (f1.tellg() != f2.tellg())
{
return false; //Size mismatch
}
//Seek back to beginning and use std::equal to compare contents
f1.seekg(0, std::ifstream::beg);
f2.seekg(0, std::ifstream::beg);
return std::equal(std::istreambuf_iterator<char>(f1.rdbuf()),
std::istreambuf_iterator<char>(),
std::istreambuf_iterator<char>(f2.rdbuf()));
}
int main(int, char **)
{
Halide::Buffer<int> parameters(2);
Halide::Buffer<double> input(N, N, 3, BATCH_SIZE);
Halide::Buffer<double> filter1(3, 3, 3, 64);
Halide::Buffer<double> filter2(3, 3, 64, 64);
Halide::Buffer<double> padd1(N + 2, N + 2, 3, BATCH_SIZE);
Halide::Buffer<double> conv1(N, N, 64, BATCH_SIZE);
Halide::Buffer<double> padd2(N + 2, N + 2, 64, BATCH_SIZE);
Halide::Buffer<double> conv2(N, N, 64, BATCH_SIZE);
Halide::Buffer<double> bn1(N, N, 64, BATCH_SIZE);
Halide::Buffer<double> bn2(N, N, 64, BATCH_SIZE);
Halide::Buffer<double> mean(N, N, 64, BATCH_SIZE);
Halide::Buffer<double> variance(N, N, 64, BATCH_SIZE);
std::vector<std::chrono::duration<double, std::milli>> duration_vector;
srand(1);
for (int n = 0; n < BATCH_SIZE; ++n)
for (int z = 0; z < 3; ++z)
for (int y = 0; y < N; ++y)
for (int x = 0; x < N; ++x)
input(x, y, z, n) = rand() % 1000;
for (int x = 0; x < 3; ++x)
for (int y = 0; y < 3; ++y)
for (int z = 0; z < 3; ++z)
for (int q = 0; q < 64; ++q)
filter1(x, y, z, q) = 1;
for (int x = 0; x < 3; ++x)
for (int y = 0; y < 3; ++y)
for (int z = 0; z < 64; ++z)
for (int q = 0; q < 64; ++q)
filter2(x, y, z, q) = 1;
std::cout << "\t\tBuffers initialized" << std::endl;
// Initialize parameters[]
parameters(0) = N;
parameters(1) = BATCH_SIZE;
for (int i = 0; i < NB_TESTS; i++)
{
auto start1 = std::chrono::high_resolution_clock::now();
fused_resnet_block(parameters.raw_buffer(), filter1.raw_buffer(),
filter2.raw_buffer(), input.raw_buffer(), padd1.raw_buffer(),
conv1.raw_buffer(), mean.raw_buffer(), variance.raw_buffer(),
bn1.raw_buffer(), padd2.raw_buffer(), conv2.raw_buffer(), bn2.raw_buffer());
auto end1 = std::chrono::high_resolution_clock::now();
std::chrono::duration<double, std::milli> duration = end1 - start1;
duration_vector.push_back(duration);
}
std::cout << "\t\tTiramisu convolution duration"
<< ": " << median(duration_vector) << "; " << std::endl;
std::ofstream resultfile;
resultfile.open("tiramisu_result.txt");
for (int n = 0; n < BATCH_SIZE; ++n)
for (int z = 0; z < 64; ++z)
for (int y = 0; y < N; ++y)
for (int x = 0; x < N; ++x)
resultfile << fixed << setprecision(2) << (float)((int)(bn2(x, y, z, n) * 1000) / 1000.0);
resultfile.close();
std::cout << "\t\t Result"
<< ":\n\n";
FILE *fp1, *fp2;
char line1[5], line2[5];
float file_count = 0, corr = 0;
fp1 = fopen("tiramisu_result.txt", "r");
fp2 = fopen("mkldnn_result.txt", "r");
while (!feof(fp1))
{
fgets(line1, sizeof(line1), fp1);
fgets(line2, sizeof(line2), fp2);
file_count += 1;
if (strcmp(line1, line2) == 0)
corr += 1;
}
fclose(fp1);
fclose(fp2);
printf("\t\t Percentage of correctness %f \n\n", corr / file_count * 100);
return 0;
}
<commit_msg>Correctness test modifed<commit_after>#include "Halide.h"
#include <cstdlib>
#include <chrono>
#include <iomanip>
#include <fstream>
#include <iostream>
#include <fstream>
#include <string>
#include <time.h>
#include "configure.h"
#include "fused_resnet_block_generator_tiramisu.o.h"
#include <tiramisu/utils.h>
using namespace std;
bool compareFiles(const std::string &p1, const std::string &p2)
{
std::ifstream f1(p1, std::ifstream::binary | std::ifstream::ate);
std::ifstream f2(p2, std::ifstream::binary | std::ifstream::ate);
if (f1.fail() || f2.fail())
{
return false; //File problem
}
if (f1.tellg() != f2.tellg())
{
return false; //Size mismatch
}
//Seek back to beginning and use std::equal to compare contents
f1.seekg(0, std::ifstream::beg);
f2.seekg(0, std::ifstream::beg);
return std::equal(std::istreambuf_iterator<char>(f1.rdbuf()),
std::istreambuf_iterator<char>(),
std::istreambuf_iterator<char>(f2.rdbuf()));
}
int main(int, char **)
{
Halide::Buffer<int> parameters(2);
Halide::Buffer<double> input(N, N, 3, BATCH_SIZE);
Halide::Buffer<double> filter1(3, 3, 3, 64);
Halide::Buffer<double> filter2(3, 3, 64, 64);
Halide::Buffer<double> padd1(N + 2, N + 2, 3, BATCH_SIZE);
Halide::Buffer<double> conv1(N, N, 64, BATCH_SIZE);
Halide::Buffer<double> padd2(N + 2, N + 2, 64, BATCH_SIZE);
Halide::Buffer<double> conv2(N, N, 64, BATCH_SIZE);
Halide::Buffer<double> bn1(N, N, 64, BATCH_SIZE);
Halide::Buffer<double> bn2(N, N, 64, BATCH_SIZE);
Halide::Buffer<double> mean(N, N, 64, BATCH_SIZE);
Halide::Buffer<double> variance(N, N, 64, BATCH_SIZE);
std::vector<std::chrono::duration<double, std::milli>> duration_vector;
srand(1);
for (int n = 0; n < BATCH_SIZE; ++n)
for (int z = 0; z < 3; ++z)
for (int y = 0; y < N; ++y)
for (int x = 0; x < N; ++x)
input(x, y, z, n) = rand() % 1000;
for (int x = 0; x < 3; ++x)
for (int y = 0; y < 3; ++y)
for (int z = 0; z < 3; ++z)
for (int q = 0; q < 64; ++q)
filter1(x, y, z, q) = 1;
for (int x = 0; x < 3; ++x)
for (int y = 0; y < 3; ++y)
for (int z = 0; z < 64; ++z)
for (int q = 0; q < 64; ++q)
filter2(x, y, z, q) = 1;
std::cout << "\t\tBuffers initialized" << std::endl;
// Initialize parameters[]
parameters(0) = N;
parameters(1) = BATCH_SIZE;
for (int i = 0; i < NB_TESTS; i++)
{
auto start1 = std::chrono::high_resolution_clock::now();
fused_resnet_block(parameters.raw_buffer(), filter1.raw_buffer(),
filter2.raw_buffer(), input.raw_buffer(), padd1.raw_buffer(),
conv1.raw_buffer(), mean.raw_buffer(), variance.raw_buffer(),
bn1.raw_buffer(), padd2.raw_buffer(), conv2.raw_buffer(), bn2.raw_buffer());
auto end1 = std::chrono::high_resolution_clock::now();
std::chrono::duration<double, std::milli> duration = end1 - start1;
duration_vector.push_back(duration);
}
std::cout << "\t\tTiramisu convolution duration"
<< ": " << median(duration_vector) << "; " << std::endl;
std::ofstream resultfile;
resultfile.open("tiramisu_result.txt");
for (int n = 0; n < BATCH_SIZE; ++n)
for (int z = 0; z < 64; ++z)
for (int y = 0; y < N; ++y)
for (int x = 0; x < N; ++x)
{
resultfile << fixed << setprecision(2) << (float)((int)(bn2(x, y, z, n) * 1000) / 1000.0);
resultfile << "\n";
}
resultfile.close();
std::cout << "\t\t Result"
<< ":\n\n";
std::ifstream infile1("tiramisu_result.txt"), infile2("mkldnn_result.txt");
std::string line1, line2;
float file_count = 0, corr = 0, f1, f2;
while (std::getline(infile1, line1))
{
std::getline(infile2, line2);
file_count += 1;
f1 = std::stof(line1);
f2 = std::stof(line2);
if (f1 - f2 <= 0.01)
corr += 1;
}
printf("\t\t Percentage of correctness %f \n\n", corr / file_count * 100);
return 0;
}
<|endoftext|> |
<commit_before>#include <aleph/math/SymmetricMatrix.hh>
#include <aleph/persistenceDiagrams/Norms.hh>
#include <aleph/persistenceDiagrams/PersistenceDiagram.hh>
#include <aleph/persistentHomology/Calculation.hh>
#include <aleph/topology/Simplex.hh>
#include <aleph/topology/SimplicialComplex.hh>
#include <aleph/topology/filtrations/Data.hh>
#include <aleph/topology/io/BipartiteAdjacencyMatrix.hh>
#include <algorithm>
#include <chrono>
#include <iostream>
#include <limits>
#include <random>
#include <stdexcept>
#include <unordered_map>
#include <vector>
#include <getopt.h>
// These declarations should remain global because we have to refer to
// them in utility functions that are living outside of `main()`.
using DataType = double;
using VertexType = unsigned short;
using Simplex = aleph::topology::Simplex<DataType, VertexType>;
using SimplicialComplex = aleph::topology::SimplicialComplex<Simplex>;
using PersistenceDiagram = aleph::PersistenceDiagram<DataType>;
using Point = typename PersistenceDiagram::Point;
PersistenceDiagram merge( const PersistenceDiagram& D, const PersistenceDiagram& E )
{
PersistenceDiagram F;
if( D.dimension() != F.dimension() )
throw std::runtime_error( "Persistence diagram dimensions have to agree" );
for( auto&& diagram : { D, E } )
for( auto&& p : diagram )
F.add( p.x(), p.y() );
return F;
}
template
<
class Engine, // random engine to use for weight generation (e.g. std::default_random_engine)
class Distribution // distribution to use for weight generation (e.g. std::uniform_real_distribution)
>
SimplicialComplex makeRandomStratifiedGraph(
const std::vector<unsigned>& strata,
Engine& engine,
Distribution& distribution
)
{
auto n = strata.size();
if( n <= 1 )
throw std::runtime_error( "Invalid number of strata" );
std::vector<Simplex> simplices;
// Create vertices ---------------------------------------------------
//
// The `strata` vector contains the size of each stratum, so we just
// have to add the correct number of vertices here.
VertexType index = VertexType(0);
for( auto&& stratum : strata )
{
for( unsigned i = 0; i < stratum; i++ )
simplices.push_back( Simplex( index++ ) );
}
// Create edges ------------------------------------------------------
//
// Every stratum is connected to every other stratum, but there are no
// connections *within* a given stratum.
VertexType offset = VertexType(0);
for( decltype(n) i = 0; i < n - 1; i++ )
{
// All vertices in the next stratum start with this offset to their
// indices. It depends on the sum of all vertices in *all* previous
// strata.
offset += strata[i];
for( unsigned j = 0; j < strata[i]; j++ )
{
for( unsigned k = 0; k < strata[i+1]; k++ )
{
simplices.push_back(
Simplex(
{
VertexType( offset - strata[i] + j ),
VertexType( offset + k )
},
distribution( engine )
)
);
}
}
}
return SimplicialComplex( simplices.begin(), simplices.end() );
}
SimplicialComplex applyFiltration( const SimplicialComplex& K,
const std::string& strategy,
bool reverse = false )
{
auto L = K;
if( strategy == "standard" )
{
if( reverse )
{
L.sort(
aleph::topology::filtrations::Data<Simplex, std::greater<DataType> >()
);
}
else
{
L.sort(
aleph::topology::filtrations::Data<Simplex, std::less<DataType> >()
);
}
}
else if( strategy == "absolute" )
{
if( reverse )
{
auto functor = [] ( const Simplex& s, const Simplex& t )
{
auto w1 = s.data();
auto w2 = t.data();
if( std::abs( w1 ) > std::abs( w2 ) )
return true;
else if( std::abs( w1 ) == std::abs( w2 ) )
{
// This amounts to saying that w1 is positive and w2 is
// negative.
if( w1 > w2 )
return true;
else
{
if( s.dimension() < t.dimension() )
return true;
// Absolute value is equal, signed value is equal, and the
// dimension is equal. We thus have to fall back to merely
// using the lexicographical order.
else
return s < t;
}
}
return false;
};
L.sort( functor );
}
else
{
auto functor = [] ( const Simplex& s, const Simplex& t )
{
auto w1 = s.data();
auto w2 = t.data();
if( std::abs( w1 ) < std::abs( w2 ) )
return true;
else if( std::abs( w1 ) == std::abs( w2 ) )
{
// This amounts to saying that w1 is negative and w2 is
// positive.
if( w1 < w2 )
return true;
else
{
if( s.dimension() < t.dimension() )
return true;
// Absolute value is equal, signed value is equal, and the
// dimension is equal. We thus have to fall back to merely
// using the lexicographical order.
else
return s < t;
}
}
return false;
};
L.sort( functor );
}
}
return L;
}
SimplicialComplex assignVertexWeights( const SimplicialComplex& K,
const std::string& strategy,
bool reverse = false )
{
DataType minData = std::numeric_limits<DataType>::max();
DataType maxData = std::numeric_limits<DataType>::lowest();
for( auto&& s : K )
{
if( s.dimension() != 1 )
continue;
minData = std::min( minData, s.data() );
maxData = std::max( maxData, s.data() );
}
// Setting up the weights --------------------------------------------
//
// This function assumes that the simplicial complex is already in
// filtration ordering with respect to its weights. Hence, we only
// have to take the *first* weight that we encounter (when using a
// global vertex weight assignment) or the *extremal* value, which
// is either a minimum or a maximum depending on the direction.
std::unordered_map<VertexType, DataType> weight;
for( auto&& s : K )
{
if( s.dimension() != 1 )
continue;
auto u = s[0];
auto v = s[1];
DataType w = DataType(); // weight to assign; depends on filtration
// Assign the global minimum or maximum. This is rather wasteful
// because the values do not change, but at least the code makes
// it clear that all updates are done in the same place.
if( strategy == "global" )
w = reverse ? maxData : minData;
else if( strategy == "local" )
w = s.data();
else
throw std::runtime_error( "Unknown update strategy '" + strategy + "'" );
// This only performs the update *once*.
weight.insert( {u,w} );
weight.insert( {v,w} );
}
// Assign the weights ------------------------------------------------
//
// Having set up the map of weights, we now only need to traverse it
// in order to assign weights afterwards.
auto L = K;
for( auto it = L.begin(); it != L.end(); ++it )
{
if( it->dimension() == 0 )
{
auto s = *it; // simplex
auto v = s[0]; // vertex
s.setData( weight.at(v) );
auto result = L.replace( it, s );
if( !result )
throw std::runtime_error( "Unable to replace simplex in simplicial complex" );
}
}
return L;
}
template <class Reader> std::vector<SimplicialComplex> loadSimplicialComplexes( int argc, char** argv )
{
Reader reader;
std::vector<SimplicialComplex> simplicialComplexes;
simplicialComplexes.reserve( static_cast<std::size_t>( argc - optind ) );
for( int i = optind; i < argc; i++ )
{
auto filename = std::string( argv[i] );
std::cerr << "* Processing " << filename << "...";
SimplicialComplex K;
reader( filename, K );
std::cerr << "finished\n";
simplicialComplexes.emplace_back( K );
}
return simplicialComplexes;
}
int main( int argc, char** argv )
{
bool bipartite = false;
bool normalize = false;
bool reverse = false;
bool verbose = false;
bool calculateDiagrams = false;
// The default filtration sorts simplices by their weights. Negative
// weights are treated as being less relevant than positive ones.
std::string filtration = "standard";
// Defines how the minimum value for the vertices is to be set. Valid
// options include:
//
// - global (uses the global extremal value)
// - local (uses the local extremal value over all neighbours)
std::string weights = "global";
{
static option commandLineOptions[] =
{
{ "bipartite" , no_argument, nullptr, 'b' },
{ "normalize" , no_argument, nullptr, 'n' },
{ "persistence-diagrams", no_argument, nullptr, 'p' },
{ "reverse" , no_argument, nullptr, 'r' },
{ "verbose" , no_argument, nullptr, 'v' },
{ "filtration" , required_argument, nullptr, 'f' },
{ "weights" , required_argument, nullptr, 'w' },
{ nullptr , 0 , nullptr, 0 }
};
int option = 0;
while( ( option = getopt_long( argc, argv, "bnprtvf:w:", commandLineOptions, nullptr ) ) != -1 )
{
switch( option )
{
case 'b':
bipartite = true;
break;
case 'f':
filtration = optarg;
break;
case 'n':
normalize = true;
break;
case 'p':
calculateDiagrams = true;
break;
case 'r':
reverse = true;
break;
case 'v':
verbose = true;
break;
case 'w':
weights = optarg;
break;
default:
break;
}
}
// Check filtration validity ---------------------------------------
if( filtration != "absolute"
&& filtration != "standard" )
{
std::cerr << "* Invalid filtration value '" << filtration << "', so falling back to standard one\n";
filtration = "standard";
}
// Check validity of weight strategy -------------------------------
if( weights != "global"
&& weights != "local" )
{
std::cerr << "* Invalid weight strategy value '" << weights << "', so falling back to global one\n";
weights = "global";
}
}
// Be verbose about parameters ---------------------------------------
if( bipartite )
std::cerr << "* Mode: reading bipartite adjacency matrices\n";
else
std::cerr << "* Mode: reading edge lists\n";
std::cerr << "* Filtration: " << filtration
<< " (" << ( reverse ? "" : "not " ) << "reversed" << ")\n"
<< "* Vertex weight assignment strategy: " << weights << "\n";
if( verbose )
std::cerr << "* Verbose output\n";
// 1. Read simplicial complexes --------------------------------------
std::vector<SimplicialComplex> simplicialComplexes;
simplicialComplexes.reserve( static_cast<unsigned>( argc - optind - 1 ) );
std::vector<DataType> minData;
std::vector<DataType> maxData;
minData.reserve( simplicialComplexes.size() );
maxData.reserve( simplicialComplexes.size() );
if( argc - optind >= 1 )
{
if( bipartite )
{
using Reader = aleph::topology::io::BipartiteAdjacencyMatrixReader;
simplicialComplexes
= loadSimplicialComplexes<Reader>( argc, argv );
}
}
else
{
std::default_random_engine engine;
engine.seed(
static_cast<unsigned>(
std::chrono::system_clock::now().time_since_epoch().count()
)
);
DataType minWeight = DataType(-1);
DataType maxWeight = DataType( 1);
std::uniform_real_distribution<DataType> distribution(
minWeight,
std::nextafter( maxWeight, std::numeric_limits<DataType>::max() )
);
for( unsigned i = 0; i < 1e5; i++ )
{
auto K
= makeRandomStratifiedGraph( {2,3}, // FIXME: {2,3,1} for the complete network
engine,
distribution
);
simplicialComplexes.emplace_back( K );
}
}
// Determine minimum and maximum values for each complex -------------
for( auto&& K : simplicialComplexes )
{
DataType minData_ = std::numeric_limits<DataType>::max();
DataType maxData_ = std::numeric_limits<DataType>::lowest();
// *Always* determine minimum and maximum weights so that we may
// report them later on. They are only used for normalization in
// the persistence diagram calculation step.
for( auto&& s : K )
{
minData_ = std::min( minData_, s.data() );
maxData_ = std::max( maxData_, s.data() );
}
minData.push_back( minData_ );
maxData.push_back( maxData_ );
}
// Establish filtration order ----------------------------------------
for( auto&& K : simplicialComplexes )
{
K = applyFiltration( K, filtration, reverse );
K = assignVertexWeights( K, weights, reverse );
K = applyFiltration( K, filtration, reverse );
}
// 2. Calculate persistent homology ----------------------------------
for( std::size_t i = 0; i < simplicialComplexes.size(); i++ )
{
// The persistence diagram that will be used in the subsequent
// analysis. This does not necessarily have to stem from data,
// but can be calculated from a suitable transformation.
PersistenceDiagram D;
auto&& K = simplicialComplexes[i];
auto diagrams = aleph::calculatePersistenceDiagrams( K );
D = diagrams.back(); // Use the *last* diagram of the filtration so that
// we get features in the highest dimension.
D.removeDiagonal();
D.removeUnpaired();
if( normalize )
{
// Ensures that all weights are in [0:1] for the corresponding
// diagram. This enables the comparison of time-varying graphs
// or different instances.
std::transform( D.begin(), D.end(), D.begin(),
[&i, &minData, &maxData] ( const Point& p )
{
auto x = p.x();
auto y = p.y();
if( minData[i] != maxData[i] )
{
x = (x - minData[i]) / (maxData[i] - minData[i]);
y = (y - minData[i]) / (maxData[i] - minData[i]);
}
return Point( x,y );
}
);
}
// Determine mode of operation -------------------------------------
//
// Several modes of operation exist for this program. They can be
// set using the flags specified above. At present, the following
// operations are possible:
//
// - Calculate persistence diagrams
// - Calculate 2-norm of the persistence diagrams
if( calculateDiagrams )
std::cout << D << "\n\n";
else
std::cout << i << "\t" << aleph::pNorm( D ) << "\n";
}
}
<commit_msg>Added (untested) support for reading edge lists<commit_after>#include <aleph/math/SymmetricMatrix.hh>
#include <aleph/persistenceDiagrams/Norms.hh>
#include <aleph/persistenceDiagrams/PersistenceDiagram.hh>
#include <aleph/persistentHomology/Calculation.hh>
#include <aleph/topology/Simplex.hh>
#include <aleph/topology/SimplicialComplex.hh>
#include <aleph/topology/filtrations/Data.hh>
#include <aleph/topology/io/BipartiteAdjacencyMatrix.hh>
#include <aleph/topology/io/EdgeLists.hh>
#include <algorithm>
#include <chrono>
#include <iostream>
#include <limits>
#include <random>
#include <stdexcept>
#include <unordered_map>
#include <vector>
#include <getopt.h>
// These declarations should remain global because we have to refer to
// them in utility functions that are living outside of `main()`.
using DataType = double;
using VertexType = unsigned short;
using Simplex = aleph::topology::Simplex<DataType, VertexType>;
using SimplicialComplex = aleph::topology::SimplicialComplex<Simplex>;
using PersistenceDiagram = aleph::PersistenceDiagram<DataType>;
using Point = typename PersistenceDiagram::Point;
PersistenceDiagram merge( const PersistenceDiagram& D, const PersistenceDiagram& E )
{
PersistenceDiagram F;
if( D.dimension() != F.dimension() )
throw std::runtime_error( "Persistence diagram dimensions have to agree" );
for( auto&& diagram : { D, E } )
for( auto&& p : diagram )
F.add( p.x(), p.y() );
return F;
}
template
<
class Engine, // random engine to use for weight generation (e.g. std::default_random_engine)
class Distribution // distribution to use for weight generation (e.g. std::uniform_real_distribution)
>
SimplicialComplex makeRandomStratifiedGraph(
const std::vector<unsigned>& strata,
Engine& engine,
Distribution& distribution
)
{
auto n = strata.size();
if( n <= 1 )
throw std::runtime_error( "Invalid number of strata" );
std::vector<Simplex> simplices;
// Create vertices ---------------------------------------------------
//
// The `strata` vector contains the size of each stratum, so we just
// have to add the correct number of vertices here.
VertexType index = VertexType(0);
for( auto&& stratum : strata )
{
for( unsigned i = 0; i < stratum; i++ )
simplices.push_back( Simplex( index++ ) );
}
// Create edges ------------------------------------------------------
//
// Every stratum is connected to every other stratum, but there are no
// connections *within* a given stratum.
VertexType offset = VertexType(0);
for( decltype(n) i = 0; i < n - 1; i++ )
{
// All vertices in the next stratum start with this offset to their
// indices. It depends on the sum of all vertices in *all* previous
// strata.
offset += strata[i];
for( unsigned j = 0; j < strata[i]; j++ )
{
for( unsigned k = 0; k < strata[i+1]; k++ )
{
simplices.push_back(
Simplex(
{
VertexType( offset - strata[i] + j ),
VertexType( offset + k )
},
distribution( engine )
)
);
}
}
}
return SimplicialComplex( simplices.begin(), simplices.end() );
}
SimplicialComplex applyFiltration( const SimplicialComplex& K,
const std::string& strategy,
bool reverse = false )
{
auto L = K;
if( strategy == "standard" )
{
if( reverse )
{
L.sort(
aleph::topology::filtrations::Data<Simplex, std::greater<DataType> >()
);
}
else
{
L.sort(
aleph::topology::filtrations::Data<Simplex, std::less<DataType> >()
);
}
}
else if( strategy == "absolute" )
{
if( reverse )
{
auto functor = [] ( const Simplex& s, const Simplex& t )
{
auto w1 = s.data();
auto w2 = t.data();
if( std::abs( w1 ) > std::abs( w2 ) )
return true;
else if( std::abs( w1 ) == std::abs( w2 ) )
{
// This amounts to saying that w1 is positive and w2 is
// negative.
if( w1 > w2 )
return true;
else
{
if( s.dimension() < t.dimension() )
return true;
// Absolute value is equal, signed value is equal, and the
// dimension is equal. We thus have to fall back to merely
// using the lexicographical order.
else
return s < t;
}
}
return false;
};
L.sort( functor );
}
else
{
auto functor = [] ( const Simplex& s, const Simplex& t )
{
auto w1 = s.data();
auto w2 = t.data();
if( std::abs( w1 ) < std::abs( w2 ) )
return true;
else if( std::abs( w1 ) == std::abs( w2 ) )
{
// This amounts to saying that w1 is negative and w2 is
// positive.
if( w1 < w2 )
return true;
else
{
if( s.dimension() < t.dimension() )
return true;
// Absolute value is equal, signed value is equal, and the
// dimension is equal. We thus have to fall back to merely
// using the lexicographical order.
else
return s < t;
}
}
return false;
};
L.sort( functor );
}
}
return L;
}
SimplicialComplex assignVertexWeights( const SimplicialComplex& K,
const std::string& strategy,
bool reverse = false )
{
DataType minData = std::numeric_limits<DataType>::max();
DataType maxData = std::numeric_limits<DataType>::lowest();
for( auto&& s : K )
{
if( s.dimension() != 1 )
continue;
minData = std::min( minData, s.data() );
maxData = std::max( maxData, s.data() );
}
// Setting up the weights --------------------------------------------
//
// This function assumes that the simplicial complex is already in
// filtration ordering with respect to its weights. Hence, we only
// have to take the *first* weight that we encounter (when using a
// global vertex weight assignment) or the *extremal* value, which
// is either a minimum or a maximum depending on the direction.
std::unordered_map<VertexType, DataType> weight;
for( auto&& s : K )
{
if( s.dimension() != 1 )
continue;
auto u = s[0];
auto v = s[1];
DataType w = DataType(); // weight to assign; depends on filtration
// Assign the global minimum or maximum. This is rather wasteful
// because the values do not change, but at least the code makes
// it clear that all updates are done in the same place.
if( strategy == "global" )
w = reverse ? maxData : minData;
else if( strategy == "local" )
w = s.data();
else
throw std::runtime_error( "Unknown update strategy '" + strategy + "'" );
// This only performs the update *once*.
weight.insert( {u,w} );
weight.insert( {v,w} );
}
// Assign the weights ------------------------------------------------
//
// Having set up the map of weights, we now only need to traverse it
// in order to assign weights afterwards.
auto L = K;
for( auto it = L.begin(); it != L.end(); ++it )
{
if( it->dimension() == 0 )
{
auto s = *it; // simplex
auto v = s[0]; // vertex
s.setData( weight.at(v) );
auto result = L.replace( it, s );
if( !result )
throw std::runtime_error( "Unable to replace simplex in simplicial complex" );
}
}
return L;
}
template <class Reader> std::vector<SimplicialComplex> loadSimplicialComplexes( int argc, char** argv )
{
Reader reader;
std::vector<SimplicialComplex> simplicialComplexes;
simplicialComplexes.reserve( static_cast<std::size_t>( argc - optind ) );
for( int i = optind; i < argc; i++ )
{
auto filename = std::string( argv[i] );
std::cerr << "* Processing " << filename << "...";
SimplicialComplex K;
reader( filename, K );
std::cerr << "finished\n";
simplicialComplexes.emplace_back( K );
}
return simplicialComplexes;
}
int main( int argc, char** argv )
{
bool bipartite = false;
bool normalize = false;
bool reverse = false;
bool verbose = false;
bool calculateDiagrams = false;
// The default filtration sorts simplices by their weights. Negative
// weights are treated as being less relevant than positive ones.
std::string filtration = "standard";
// Defines how the minimum value for the vertices is to be set. Valid
// options include:
//
// - global (uses the global extremal value)
// - local (uses the local extremal value over all neighbours)
std::string weights = "global";
{
static option commandLineOptions[] =
{
{ "bipartite" , no_argument, nullptr, 'b' },
{ "normalize" , no_argument, nullptr, 'n' },
{ "persistence-diagrams", no_argument, nullptr, 'p' },
{ "reverse" , no_argument, nullptr, 'r' },
{ "verbose" , no_argument, nullptr, 'v' },
{ "filtration" , required_argument, nullptr, 'f' },
{ "weights" , required_argument, nullptr, 'w' },
{ nullptr , 0 , nullptr, 0 }
};
int option = 0;
while( ( option = getopt_long( argc, argv, "bnprtvf:w:", commandLineOptions, nullptr ) ) != -1 )
{
switch( option )
{
case 'b':
bipartite = true;
break;
case 'f':
filtration = optarg;
break;
case 'n':
normalize = true;
break;
case 'p':
calculateDiagrams = true;
break;
case 'r':
reverse = true;
break;
case 'v':
verbose = true;
break;
case 'w':
weights = optarg;
break;
default:
break;
}
}
// Check filtration validity ---------------------------------------
if( filtration != "absolute"
&& filtration != "standard" )
{
std::cerr << "* Invalid filtration value '" << filtration << "', so falling back to standard one\n";
filtration = "standard";
}
// Check validity of weight strategy -------------------------------
if( weights != "global"
&& weights != "local" )
{
std::cerr << "* Invalid weight strategy value '" << weights << "', so falling back to global one\n";
weights = "global";
}
}
// Be verbose about parameters ---------------------------------------
if( bipartite )
std::cerr << "* Mode: reading bipartite adjacency matrices\n";
else
std::cerr << "* Mode: reading edge lists\n";
std::cerr << "* Filtration: " << filtration
<< " (" << ( reverse ? "" : "not " ) << "reversed" << ")\n"
<< "* Vertex weight assignment strategy: " << weights << "\n";
if( verbose )
std::cerr << "* Verbose output\n";
// 1. Read simplicial complexes --------------------------------------
std::vector<SimplicialComplex> simplicialComplexes;
simplicialComplexes.reserve( static_cast<unsigned>( argc - optind - 1 ) );
std::vector<DataType> minData;
std::vector<DataType> maxData;
minData.reserve( simplicialComplexes.size() );
maxData.reserve( simplicialComplexes.size() );
if( argc - optind >= 1 )
{
if( bipartite )
{
using Reader = aleph::topology::io::BipartiteAdjacencyMatrixReader;
simplicialComplexes
= loadSimplicialComplexes<Reader>( argc, argv );
}
else
{
using Reader = aleph::topology::io::EdgeListReader;
simplicialComplexes
= loadSimplicialComplexes<Reader>( argc, argv );
}
}
else
{
std::default_random_engine engine;
engine.seed(
static_cast<unsigned>(
std::chrono::system_clock::now().time_since_epoch().count()
)
);
DataType minWeight = DataType(-1);
DataType maxWeight = DataType( 1);
std::uniform_real_distribution<DataType> distribution(
minWeight,
std::nextafter( maxWeight, std::numeric_limits<DataType>::max() )
);
for( unsigned i = 0; i < 1e5; i++ )
{
auto K
= makeRandomStratifiedGraph( {2,3}, // FIXME: {2,3,1} for the complete network
engine,
distribution
);
simplicialComplexes.emplace_back( K );
}
}
// Determine minimum and maximum values for each complex -------------
for( auto&& K : simplicialComplexes )
{
DataType minData_ = std::numeric_limits<DataType>::max();
DataType maxData_ = std::numeric_limits<DataType>::lowest();
// *Always* determine minimum and maximum weights so that we may
// report them later on. They are only used for normalization in
// the persistence diagram calculation step.
for( auto&& s : K )
{
minData_ = std::min( minData_, s.data() );
maxData_ = std::max( maxData_, s.data() );
}
minData.push_back( minData_ );
maxData.push_back( maxData_ );
}
// Establish filtration order ----------------------------------------
for( auto&& K : simplicialComplexes )
{
K = applyFiltration( K, filtration, reverse );
K = assignVertexWeights( K, weights, reverse );
K = applyFiltration( K, filtration, reverse );
}
// 2. Calculate persistent homology ----------------------------------
for( std::size_t i = 0; i < simplicialComplexes.size(); i++ )
{
// The persistence diagram that will be used in the subsequent
// analysis. This does not necessarily have to stem from data,
// but can be calculated from a suitable transformation.
PersistenceDiagram D;
auto&& K = simplicialComplexes[i];
auto diagrams = aleph::calculatePersistenceDiagrams( K );
D = diagrams.back(); // Use the *last* diagram of the filtration so that
// we get features in the highest dimension.
D.removeDiagonal();
D.removeUnpaired();
if( normalize )
{
// Ensures that all weights are in [0:1] for the corresponding
// diagram. This enables the comparison of time-varying graphs
// or different instances.
std::transform( D.begin(), D.end(), D.begin(),
[&i, &minData, &maxData] ( const Point& p )
{
auto x = p.x();
auto y = p.y();
if( minData[i] != maxData[i] )
{
x = (x - minData[i]) / (maxData[i] - minData[i]);
y = (y - minData[i]) / (maxData[i] - minData[i]);
}
return Point( x,y );
}
);
}
// Determine mode of operation -------------------------------------
//
// Several modes of operation exist for this program. They can be
// set using the flags specified above. At present, the following
// operations are possible:
//
// - Calculate persistence diagrams
// - Calculate 2-norm of the persistence diagrams
if( calculateDiagrams )
std::cout << D << "\n\n";
else
std::cout << i << "\t" << aleph::pNorm( D ) << "\n";
}
}
<|endoftext|> |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.