text stringlengths 54 60.6k |
|---|
<commit_before>#include "logging.h"
#include "common/config.h"
#include "spdlog/sinks/null_sink.h"
#include "3rd_party/ExceptionWithCallStack.h"
#include <time.h>
#include <stdlib.h>
#ifdef __unix__
#include <signal.h>
#endif
std::shared_ptr<spdlog::logger> stderrLogger(
const std::string& name,
const std::string& pattern,
const std::vector<std::string>& files,
bool quiet) {
std::vector<spdlog::sink_ptr> sinks;
auto stderr_sink = spdlog::sinks::stderr_sink_mt::instance();
if(!quiet)
sinks.push_back(stderr_sink);
for(auto&& file : files) {
auto file_sink
= std::make_shared<spdlog::sinks::simple_file_sink_st>(file, true);
sinks.push_back(file_sink);
}
auto logger
= std::make_shared<spdlog::logger>(name, begin(sinks), end(sinks));
spdlog::register_logger(logger);
logger->set_pattern(pattern);
return logger;
}
bool setLoggingLevel(spdlog::logger& logger, std::string const level) {
if(level == "trace")
logger.set_level(spdlog::level::trace);
else if(level == "debug")
logger.set_level(spdlog::level::debug);
else if(level == "info")
logger.set_level(spdlog::level::info);
else if(level == "warn")
logger.set_level(spdlog::level::warn);
else if(level == "err" || level == "error")
logger.set_level(spdlog::level::err);
else if(level == "critical")
logger.set_level(spdlog::level::critical);
else if(level == "off")
logger.set_level(spdlog::level::off);
else {
logger.warn("Unknown log level '{}' for logger '{}'",
level.c_str(),
logger.name().c_str());
return false;
}
return true;
}
#ifdef __unix__
static struct sigaction prev_segfault_sigaction;
void segfault_sigaction(int signal, siginfo_t *si, void *arg)
{
sigaction(signal, &prev_segfault_sigaction, NULL); // revert signal handler
marian::logCallStack(/*skipLevels=*/1);
raise(signal); // re-raise so we terminate mostly as usual
}
#endif
void createLoggers(const marian::Config* options) {
std::vector<std::string> generalLogs;
std::vector<std::string> validLogs;
if(options && options->has("log")) {
generalLogs.push_back(options->get<std::string>("log"));
#ifndef _WIN32 // can't open the same file twice in Windows for some reason
validLogs.push_back(options->get<std::string>("log"));
#endif
}
if(options && options->has("valid-log")) {
validLogs.push_back(options->get<std::string>("valid-log"));
}
bool quiet = options && options->get<bool>("quiet");
Logger general{
stderrLogger("general", "[%Y-%m-%d %T] %v", generalLogs, quiet)};
Logger valid{
stderrLogger("valid", "[%Y-%m-%d %T] [valid] %v", validLogs, quiet)};
if(options && options->has("log-level")) {
std::string loglevel = options->get<std::string>("log-level");
if(!setLoggingLevel(*general, loglevel))
return;
setLoggingLevel(*valid, loglevel);
}
if (options && options->has("log-time-zone")) {
std::string timezone = options->get<std::string>("log-time-zone");
if (timezone != "") {
#ifdef _WIN32
#define setenv(var, val, over) SetEnvironmentVariableA(var, val) // ignoring over flag
#endif
setenv("TZ", timezone.c_str(), true);
tzset();
}
}
#ifdef __unix__
// catch segfaults
struct sigaction sa;
memset(&sa, 0, sizeof(sa));
sigemptyset(&sa.sa_mask);
sa.sa_sigaction = segfault_sigaction;
sa.sa_flags = SA_SIGINFO | SA_RESETHAND;
sigaction(SIGSEGV, &sa, &prev_segfault_sigaction);
// test it
*((int*)0) = 13; // cause a crash
#endif
}
namespace marian {
void logCallStack(size_t skipLevels)
{
auto callStack = ::Microsoft::MSR::CNTK::DebugUtil::GetCallStack(skipLevels + 1, /*makeFunctionNamesStandOut=*/true);
checkedLog("general", "critical", "Call stack:\n{}", callStack);
}
}
<commit_msg>call-stack logging now seems to work for both ABORT and segfault<commit_after>#include "logging.h"
#include "common/config.h"
#include "spdlog/sinks/null_sink.h"
#include "3rd_party/ExceptionWithCallStack.h"
#include <time.h>
#include <stdlib.h>
#ifdef __unix__
#include <signal.h>
#endif
#ifdef _MSC_VER
#define noinline __declspec(noinline)
#else
#define noinline __attribute__((noinline))
#endif
std::shared_ptr<spdlog::logger> stderrLogger(
const std::string& name,
const std::string& pattern,
const std::vector<std::string>& files,
bool quiet) {
std::vector<spdlog::sink_ptr> sinks;
auto stderr_sink = spdlog::sinks::stderr_sink_mt::instance();
if(!quiet)
sinks.push_back(stderr_sink);
for(auto&& file : files) {
auto file_sink
= std::make_shared<spdlog::sinks::simple_file_sink_st>(file, true);
sinks.push_back(file_sink);
}
auto logger
= std::make_shared<spdlog::logger>(name, begin(sinks), end(sinks));
spdlog::register_logger(logger);
logger->set_pattern(pattern);
return logger;
}
bool setLoggingLevel(spdlog::logger& logger, std::string const level) {
if(level == "trace")
logger.set_level(spdlog::level::trace);
else if(level == "debug")
logger.set_level(spdlog::level::debug);
else if(level == "info")
logger.set_level(spdlog::level::info);
else if(level == "warn")
logger.set_level(spdlog::level::warn);
else if(level == "err" || level == "error")
logger.set_level(spdlog::level::err);
else if(level == "critical")
logger.set_level(spdlog::level::critical);
else if(level == "off")
logger.set_level(spdlog::level::off);
else {
logger.warn("Unknown log level '{}' for logger '{}'",
level.c_str(),
logger.name().c_str());
return false;
}
return true;
}
#ifdef __unix__
static struct sigaction prev_segfault_sigaction;
void noinline segfault_sigaction(int signal, siginfo_t *si, void *arg)
{
sigaction(signal, &prev_segfault_sigaction, NULL); // revert signal handler
marian::logCallStack(/*skipLevels=*/2); // skip segfault_sigaction() and one level up in the kernel
raise(signal); // re-raise so we terminate mostly as usual
}
#endif
void createLoggers(const marian::Config* options) {
std::vector<std::string> generalLogs;
std::vector<std::string> validLogs;
if(options && options->has("log")) {
generalLogs.push_back(options->get<std::string>("log"));
#ifndef _WIN32 // can't open the same file twice in Windows for some reason
validLogs.push_back(options->get<std::string>("log"));
#endif
}
if(options && options->has("valid-log")) {
validLogs.push_back(options->get<std::string>("valid-log"));
}
bool quiet = options && options->get<bool>("quiet");
Logger general{
stderrLogger("general", "[%Y-%m-%d %T] %v", generalLogs, quiet)};
Logger valid{
stderrLogger("valid", "[%Y-%m-%d %T] [valid] %v", validLogs, quiet)};
if(options && options->has("log-level")) {
std::string loglevel = options->get<std::string>("log-level");
if(!setLoggingLevel(*general, loglevel))
return;
setLoggingLevel(*valid, loglevel);
}
if (options && options->has("log-time-zone")) {
std::string timezone = options->get<std::string>("log-time-zone");
if (timezone != "") {
#ifdef _WIN32
#define setenv(var, val, over) SetEnvironmentVariableA(var, val) // ignoring over flag
#endif
setenv("TZ", timezone.c_str(), true);
tzset();
}
}
#ifdef __unix__
// catch segfaults
struct sigaction sa;
memset(&sa, 0, sizeof(sa));
sigemptyset(&sa.sa_mask);
sa.sa_sigaction = segfault_sigaction;
sa.sa_flags = SA_SIGINFO | SA_RESETHAND;
sigaction(SIGSEGV, &sa, &prev_segfault_sigaction);
#endif
}
namespace marian {
void noinline logCallStack(size_t skipLevels)
{
auto callStack = ::Microsoft::MSR::CNTK::DebugUtil::GetCallStack(skipLevels + 2, /*makeFunctionNamesStandOut=*/true);
checkedLog("general", "critical", "Call stack:{}", callStack);
}
}
<|endoftext|> |
<commit_before>/***************************************************************************
* Copyright (C) 2006 by Till Adam <adam@kde.org> *
* *
* This program is free software; you can redistribute it and/or modify *
* it under the terms of the GNU Library General Public License as *
* published by the Free Software Foundation; either version 2 of the *
* License, or (at your option) any later version. *
* *
* This program is distributed in the hope that it will be useful, *
* but WITHOUT ANY WARRANTY; without even the implied warranty of *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
* GNU General Public License for more details. *
* *
* You should have received a copy of the GNU Library 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 "../libs/xdgbasedirs_p.h"
#include "akonadi.h"
#include "akonadiconnection.h"
#include "serveradaptor.h"
#include "cachecleaner.h"
#include "intervalcheck.h"
#include "storage/datastore.h"
#include "notificationmanager.h"
#include "resourcemanager.h"
#include "tracer.h"
#include "xesammanager.h"
#include "nepomukmanager.h"
#include <QtCore/QCoreApplication>
#include <QtCore/QDir>
#include <QtCore/QProcess>
#include <QtCore/QSettings>
#include <QtCore/QTimer>
#include <config-akonadi.h>
#ifdef HAVE_UNISTD_H
# include <unistd.h>
#endif
#include <stdlib.h>
using namespace Akonadi;
static AkonadiServer *s_instance = 0;
AkonadiServer::AkonadiServer( QObject* parent )
: QLocalServer( parent )
, mCacheCleaner( 0 )
, mIntervalChecker( 0 )
, mDatabaseProcess( 0 )
, mAlreadyShutdown( false )
{
QSettings settings( XdgBaseDirs::akonadiServerConfigFile(), QSettings::IniFormat );
if ( settings.value( QLatin1String("General/Driver"), QLatin1String( "QMYSQL" ) ).toString() == QLatin1String( "QMYSQL" )
&& settings.value( QLatin1String( "QMYSQL/StartServer" ), true ).toBool() )
startDatabaseProcess();
s_instance = this;
const QString connectionSettingsFile = XdgBaseDirs::akonadiConnectionConfigFile(
XdgBaseDirs::WriteOnly );
QSettings connectionSettings( connectionSettingsFile, QSettings::IniFormat );
#ifdef Q_OS_WIN
QString namedPipe = settings.value( QLatin1String( "Connection/NamedPipe" ), QLatin1String( "Akonadi" ) ).toString();
if ( !listen( namedPipe ) )
qFatal( "Unable to listen on Named Pipe %s", namedPipe.toLocal8Bit().data() );
connectionSettings.setValue( QLatin1String( "Data/Method" ), QLatin1String( "NamedPipe" ) );
connectionSettings.setValue( QLatin1String( "Data/NamedPipe" ), namedPipe );
#else
const QString defaultSocketDir = XdgBaseDirs::saveDir( "data", QLatin1String( "akonadi" ) );
QString socketDir = settings.value( QLatin1String( "Connection/SocketDirectory" ), defaultSocketDir ).toString();
if ( socketDir[0] != QLatin1Char( '/' ) ) {
QDir::home().mkdir( socketDir );
socketDir = QDir::homePath() + QLatin1Char( '/' ) + socketDir;
}
const QString socketFile = socketDir + QLatin1String( "/akonadiserver.socket" );
unlink( socketFile.toUtf8().constData() );
if ( !listen( socketFile ) )
qFatal("Unable to listen on Unix socket '%s'", socketFile.toLocal8Bit().data() );
connectionSettings.setValue( QLatin1String( "Data/Method" ), QLatin1String( "UnixPath" ) );
connectionSettings.setValue( QLatin1String( "Data/UnixPath" ), socketFile );
#endif
// initialize the database
DataStore *db = DataStore::self();
if ( !db->database().isOpen() )
qFatal("Unable to open database.");
if ( !db->init() )
qFatal("Unable to initialize database.");
NotificationManager::self();
Tracer::self();
ResourceManager::self();
if ( settings.value( QLatin1String( "Cache/EnableCleaner" ), true ).toBool() ) {
mCacheCleaner = new CacheCleaner( this );
mCacheCleaner->start( QThread::IdlePriority );
}
mIntervalChecker = new IntervalCheck( this );
mIntervalChecker->start( QThread::IdlePriority );
mSearchManager = new DummySearchManager;
new ServerAdaptor( this );
QDBusConnection::sessionBus().registerObject( QLatin1String( "/Server" ), this );
const QByteArray dbusAddress = qgetenv( "DBUS_SESSION_BUS_ADDRESS" );
if ( !dbusAddress.isEmpty() ) {
connectionSettings.setValue( QLatin1String( "DBUS/Address" ), QLatin1String( dbusAddress ) );
}
}
AkonadiServer::~AkonadiServer()
{
}
void AkonadiServer::quit()
{
if ( mAlreadyShutdown )
return;
mAlreadyShutdown = true;
if ( mCacheCleaner )
QMetaObject::invokeMethod( mCacheCleaner, "quit", Qt::QueuedConnection );
if ( mIntervalChecker )
QMetaObject::invokeMethod( mIntervalChecker, "quit", Qt::QueuedConnection );
QCoreApplication::instance()->processEvents();
if ( mCacheCleaner )
mCacheCleaner->wait();
if ( mIntervalChecker )
mIntervalChecker->wait();
delete mSearchManager;
mSearchManager = 0;
for ( int i = 0; i < mConnections.count(); ++i ) {
if ( mConnections[ i ] ) {
mConnections[ i ]->quit();
mConnections[ i ]->wait();
}
}
DataStore::self()->close();
// execute the deleteLater() calls for the threads so they free their db connections
// and the following db termination will work
QCoreApplication::instance()->processEvents();
if ( mDatabaseProcess )
stopDatabaseProcess();
QSettings settings( XdgBaseDirs::akonadiServerConfigFile(), QSettings::IniFormat );
const QString connectionSettingsFile = XdgBaseDirs::akonadiConnectionConfigFile( XdgBaseDirs::WriteOnly );
#ifndef Q_OS_WIN
QSettings connectionSettings( connectionSettingsFile, QSettings::IniFormat );
const QString defaultSocketDir = XdgBaseDirs::saveDir( "data", QLatin1String( "akonadi" ) );
const QString socketDir = settings.value( QLatin1String( "Connection/SocketDirectory" ), defaultSocketDir ).toString();
if ( !QDir::home().remove( socketDir + QLatin1String( "/akonadiserver.socket" ) ) )
qWarning("Failed to remove Unix socket");
#endif
if ( !QDir::home().remove( connectionSettingsFile ) )
qWarning("Failed to remove runtime connection config file");
QTimer::singleShot( 0, this, SLOT( doQuit() ) );
}
void AkonadiServer::doQuit()
{
QCoreApplication::exit();
}
void AkonadiServer::incomingConnection( quintptr socketDescriptor )
{
QPointer<AkonadiConnection> thread = new AkonadiConnection( socketDescriptor, this );
connect( thread, SIGNAL( finished() ), thread, SLOT( deleteLater() ) );
mConnections.append( thread );
thread->start();
}
AkonadiServer * AkonadiServer::instance()
{
if ( !s_instance )
s_instance = new AkonadiServer();
return s_instance;
}
void AkonadiServer::startDatabaseProcess()
{
#ifdef MYSQLD_EXECUTABLE
const QString mysqldPath = QLatin1String( MYSQLD_EXECUTABLE );
#else
const QString mysqldPath;
Q_ASSERT_X( false, "AkonadiServer::startDatabaseProcess()",
"mysqld was not found during compile time, you need to start a MySQL server yourself first and configure Akonadi accordingly" );
#endif
// create the database directories if they don't exists
const QString dataDir = XdgBaseDirs::saveDir( "data", QLatin1String( "akonadi/db_data" ) );
const QString akDir = XdgBaseDirs::saveDir( "data", QLatin1String( "akonadi/" ) );
const QString miscDir = XdgBaseDirs::saveDir( "data", QLatin1String( "akonadi/db_misc" ) );
// generate config file
const QString globalConfig = XdgBaseDirs::findResourceFile( "config", QLatin1String( "akonadi/mysql-global.conf" ) );
const QString localConfig = XdgBaseDirs::findResourceFile( "config", QLatin1String( "akonadi/mysql-local.conf" ) );
const QString actualConfig = XdgBaseDirs::saveDir( "data", QLatin1String( "akonadi" ) ) + QLatin1String("/mysql.conf");
if ( globalConfig.isEmpty() )
qFatal("Where is my MySQL config file??");
QFile globalFile( globalConfig );
QFile actualFile( actualConfig );
if ( globalFile.open( QFile::ReadOnly ) && actualFile.open( QFile::WriteOnly ) ) {
actualFile.write( globalFile.readAll() );
if ( !localConfig.isEmpty() ) {
QFile localFile( localConfig );
if ( localFile.open( QFile::ReadOnly ) ) {
actualFile.write( localFile.readAll() );
localFile.close();
}
}
actualFile.close();
globalFile.close();
} else {
qFatal("What did you do to my MySQL config file??");
}
if ( dataDir.isEmpty() )
qFatal("Akonadi server was not able not create database data directory");
if ( akDir.isEmpty() )
qFatal("Akonadi server was not able not create database log directory");
if ( miscDir.isEmpty() )
qFatal("Akonadi server was not able not create database misc directory");
// synthesize the mysqld command
QStringList arguments;
arguments << QString::fromLatin1( "--defaults-file=%1/mysql.conf" ).arg( akDir );
arguments << QString::fromLatin1( "--datadir=%1/" ).arg( dataDir );
arguments << QString::fromLatin1( "--socket=%1/mysql.socket" ).arg( miscDir );
mDatabaseProcess = new QProcess( this );
mDatabaseProcess->start( mysqldPath, arguments );
if ( !mDatabaseProcess->waitForStarted() )
qFatal( "Could not start database server '%s'", qPrintable( mysqldPath ) );
{
QSqlDatabase db = QSqlDatabase::addDatabase( QLatin1String( "QMYSQL" ), QLatin1String( "initConnection" ) );
db.setConnectOptions( QString::fromLatin1( "UNIX_SOCKET=%1/mysql.socket" ).arg( miscDir ) );
bool opened = false;
for ( int i = 0; i < 120; ++i ) {
opened = db.open();
if ( opened )
break;
if ( mDatabaseProcess->waitForFinished( 500 ) )
qFatal( "Database server exited unexpectedly, exit code %d", mDatabaseProcess->exitCode() );
}
if ( opened ) {
QSqlQuery query( db );
if ( !query.exec( QLatin1String( "USE DATABASE akonadi" ) ) )
query.exec( QLatin1String( "CREATE DATABASE akonadi" ) );
db.close();
}
}
QSqlDatabase::removeDatabase( QLatin1String( "initConnection" ) );
}
void AkonadiServer::stopDatabaseProcess()
{
mDatabaseProcess->terminate();
mDatabaseProcess->waitForFinished();
}
#include "akonadi.moc"
<commit_msg>integrate message verbosity from 1.0 branch<commit_after>/***************************************************************************
* Copyright (C) 2006 by Till Adam <adam@kde.org> *
* *
* This program is free software; you can redistribute it and/or modify *
* it under the terms of the GNU Library General Public License as *
* published by the Free Software Foundation; either version 2 of the *
* License, or (at your option) any later version. *
* *
* This program is distributed in the hope that it will be useful, *
* but WITHOUT ANY WARRANTY; without even the implied warranty of *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
* GNU General Public License for more details. *
* *
* You should have received a copy of the GNU Library 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 "../libs/xdgbasedirs_p.h"
#include "akonadi.h"
#include "akonadiconnection.h"
#include "serveradaptor.h"
#include "cachecleaner.h"
#include "intervalcheck.h"
#include "storage/datastore.h"
#include "notificationmanager.h"
#include "resourcemanager.h"
#include "tracer.h"
#include "xesammanager.h"
#include "nepomukmanager.h"
#include <QtCore/QCoreApplication>
#include <QtCore/QDir>
#include <QtCore/QProcess>
#include <QtCore/QSettings>
#include <QtCore/QTimer>
#include <config-akonadi.h>
#ifdef HAVE_UNISTD_H
# include <unistd.h>
#endif
#include <stdlib.h>
using namespace Akonadi;
static AkonadiServer *s_instance = 0;
AkonadiServer::AkonadiServer( QObject* parent )
: QLocalServer( parent )
, mCacheCleaner( 0 )
, mIntervalChecker( 0 )
, mDatabaseProcess( 0 )
, mAlreadyShutdown( false )
{
QSettings settings( XdgBaseDirs::akonadiServerConfigFile(), QSettings::IniFormat );
if ( settings.value( QLatin1String("General/Driver"), QLatin1String( "QMYSQL" ) ).toString() == QLatin1String( "QMYSQL" )
&& settings.value( QLatin1String( "QMYSQL/StartServer" ), true ).toBool() )
startDatabaseProcess();
s_instance = this;
const QString connectionSettingsFile = XdgBaseDirs::akonadiConnectionConfigFile(
XdgBaseDirs::WriteOnly );
QSettings connectionSettings( connectionSettingsFile, QSettings::IniFormat );
#ifdef Q_OS_WIN
QString namedPipe = settings.value( QLatin1String( "Connection/NamedPipe" ), QLatin1String( "Akonadi" ) ).toString();
if ( !listen( namedPipe ) )
qFatal( "Unable to listen on Named Pipe %s", namedPipe.toLocal8Bit().data() );
connectionSettings.setValue( QLatin1String( "Data/Method" ), QLatin1String( "NamedPipe" ) );
connectionSettings.setValue( QLatin1String( "Data/NamedPipe" ), namedPipe );
#else
const QString defaultSocketDir = XdgBaseDirs::saveDir( "data", QLatin1String( "akonadi" ) );
QString socketDir = settings.value( QLatin1String( "Connection/SocketDirectory" ), defaultSocketDir ).toString();
if ( socketDir[0] != QLatin1Char( '/' ) ) {
QDir::home().mkdir( socketDir );
socketDir = QDir::homePath() + QLatin1Char( '/' ) + socketDir;
}
const QString socketFile = socketDir + QLatin1String( "/akonadiserver.socket" );
unlink( socketFile.toUtf8().constData() );
if ( !listen( socketFile ) )
qFatal("Unable to listen on Unix socket '%s'", socketFile.toLocal8Bit().data() );
connectionSettings.setValue( QLatin1String( "Data/Method" ), QLatin1String( "UnixPath" ) );
connectionSettings.setValue( QLatin1String( "Data/UnixPath" ), socketFile );
#endif
// initialize the database
DataStore *db = DataStore::self();
if ( !db->database().isOpen() )
qFatal("Unable to open database: '%s'", qPrintable(db->database().lastError().text()));
if ( !db->init() )
qFatal("Unable to initialize database.");
NotificationManager::self();
Tracer::self();
ResourceManager::self();
if ( settings.value( QLatin1String( "Cache/EnableCleaner" ), true ).toBool() ) {
mCacheCleaner = new CacheCleaner( this );
mCacheCleaner->start( QThread::IdlePriority );
}
mIntervalChecker = new IntervalCheck( this );
mIntervalChecker->start( QThread::IdlePriority );
mSearchManager = new DummySearchManager;
new ServerAdaptor( this );
QDBusConnection::sessionBus().registerObject( QLatin1String( "/Server" ), this );
const QByteArray dbusAddress = qgetenv( "DBUS_SESSION_BUS_ADDRESS" );
if ( !dbusAddress.isEmpty() ) {
connectionSettings.setValue( QLatin1String( "DBUS/Address" ), QLatin1String( dbusAddress ) );
}
}
AkonadiServer::~AkonadiServer()
{
}
void AkonadiServer::quit()
{
if ( mAlreadyShutdown )
return;
mAlreadyShutdown = true;
if ( mCacheCleaner )
QMetaObject::invokeMethod( mCacheCleaner, "quit", Qt::QueuedConnection );
if ( mIntervalChecker )
QMetaObject::invokeMethod( mIntervalChecker, "quit", Qt::QueuedConnection );
QCoreApplication::instance()->processEvents();
if ( mCacheCleaner )
mCacheCleaner->wait();
if ( mIntervalChecker )
mIntervalChecker->wait();
delete mSearchManager;
mSearchManager = 0;
for ( int i = 0; i < mConnections.count(); ++i ) {
if ( mConnections[ i ] ) {
mConnections[ i ]->quit();
mConnections[ i ]->wait();
}
}
DataStore::self()->close();
// execute the deleteLater() calls for the threads so they free their db connections
// and the following db termination will work
QCoreApplication::instance()->processEvents();
if ( mDatabaseProcess )
stopDatabaseProcess();
QSettings settings( XdgBaseDirs::akonadiServerConfigFile(), QSettings::IniFormat );
const QString connectionSettingsFile = XdgBaseDirs::akonadiConnectionConfigFile( XdgBaseDirs::WriteOnly );
#ifndef Q_OS_WIN
QSettings connectionSettings( connectionSettingsFile, QSettings::IniFormat );
const QString defaultSocketDir = XdgBaseDirs::saveDir( "data", QLatin1String( "akonadi" ) );
const QString socketDir = settings.value( QLatin1String( "Connection/SocketDirectory" ), defaultSocketDir ).toString();
if ( !QDir::home().remove( socketDir + QLatin1String( "/akonadiserver.socket" ) ) )
qWarning("Failed to remove Unix socket");
#endif
if ( !QDir::home().remove( connectionSettingsFile ) )
qWarning("Failed to remove runtime connection config file");
QTimer::singleShot( 0, this, SLOT( doQuit() ) );
}
void AkonadiServer::doQuit()
{
QCoreApplication::exit();
}
void AkonadiServer::incomingConnection( quintptr socketDescriptor )
{
QPointer<AkonadiConnection> thread = new AkonadiConnection( socketDescriptor, this );
connect( thread, SIGNAL( finished() ), thread, SLOT( deleteLater() ) );
mConnections.append( thread );
thread->start();
}
AkonadiServer * AkonadiServer::instance()
{
if ( !s_instance )
s_instance = new AkonadiServer();
return s_instance;
}
void AkonadiServer::startDatabaseProcess()
{
#ifdef MYSQLD_EXECUTABLE
const QString mysqldPath = QLatin1String( MYSQLD_EXECUTABLE );
#else
const QString mysqldPath;
Q_ASSERT_X( false, "AkonadiServer::startDatabaseProcess()",
"mysqld was not found during compile time, you need to start a MySQL server yourself first and configure Akonadi accordingly" );
#endif
// create the database directories if they don't exists
const QString dataDir = XdgBaseDirs::saveDir( "data", QLatin1String( "akonadi/db_data" ) );
const QString akDir = XdgBaseDirs::saveDir( "data", QLatin1String( "akonadi/" ) );
const QString miscDir = XdgBaseDirs::saveDir( "data", QLatin1String( "akonadi/db_misc" ) );
// generate config file
const QString globalConfig = XdgBaseDirs::findResourceFile( "config", QLatin1String( "akonadi/mysql-global.conf" ) );
const QString localConfig = XdgBaseDirs::findResourceFile( "config", QLatin1String( "akonadi/mysql-local.conf" ) );
const QString actualConfig = XdgBaseDirs::saveDir( "data", QLatin1String( "akonadi" ) ) + QLatin1String("/mysql.conf");
if ( globalConfig.isEmpty() )
qFatal("Where is my MySQL config file??");
QFile globalFile( globalConfig );
QFile actualFile( actualConfig );
if ( globalFile.open( QFile::ReadOnly ) && actualFile.open( QFile::WriteOnly ) ) {
actualFile.write( globalFile.readAll() );
if ( !localConfig.isEmpty() ) {
QFile localFile( localConfig );
if ( localFile.open( QFile::ReadOnly ) ) {
actualFile.write( localFile.readAll() );
localFile.close();
}
}
actualFile.close();
globalFile.close();
} else {
qFatal("What did you do to my MySQL config file??");
}
if ( dataDir.isEmpty() )
qFatal("Akonadi server was not able not create database data directory");
if ( akDir.isEmpty() )
qFatal("Akonadi server was not able not create database log directory");
if ( miscDir.isEmpty() )
qFatal("Akonadi server was not able not create database misc directory");
// synthesize the mysqld command
QStringList arguments;
arguments << QString::fromLatin1( "--defaults-file=%1/mysql.conf" ).arg( akDir );
arguments << QString::fromLatin1( "--datadir=%1/" ).arg( dataDir );
arguments << QString::fromLatin1( "--socket=%1/mysql.socket" ).arg( miscDir );
mDatabaseProcess = new QProcess( this );
mDatabaseProcess->start( mysqldPath, arguments );
if ( !mDatabaseProcess->waitForStarted() )
qFatal( "Could not start database server '%s': '%s'", qPrintable( mysqldPath ), qPrintable( mDatabaseProcess->errorString()) );
{
QSqlDatabase db = QSqlDatabase::addDatabase( QLatin1String( "QMYSQL" ), QLatin1String( "initConnection" ) );
db.setConnectOptions( QString::fromLatin1( "UNIX_SOCKET=%1/mysql.socket" ).arg( miscDir ) );
bool opened = false;
for ( int i = 0; i < 120; ++i ) {
opened = db.open();
if ( opened )
break;
if ( mDatabaseProcess->waitForFinished( 500 ) ) {
qDebug( "Database stdout: '%s'", mDatabaseProcess->readAllStandardOutput().constData() );
qFatal( "Database server exited unexpectedly, exit code %d,\n process error: '%s'\n DB error: '%s'",
mDatabaseProcess->exitCode(),
qPrintable( mDatabaseProcess->errorString() ),
mDatabaseProcess->readAllStandardError().constData() );
}
}
if ( opened ) {
QSqlQuery query( db );
if ( !query.exec( QLatin1String( "USE DATABASE akonadi" ) ) )
query.exec( QLatin1String( "CREATE DATABASE akonadi" ) );
db.close();
}
}
QSqlDatabase::removeDatabase( QLatin1String( "initConnection" ) );
}
void AkonadiServer::stopDatabaseProcess()
{
mDatabaseProcess->terminate();
mDatabaseProcess->waitForFinished();
}
#include "akonadi.moc"
<|endoftext|> |
<commit_before>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*************************************************************************
*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* Copyright 2000, 2010 Oracle and/or its affiliates.
*
* OpenOffice.org - a multi-platform office productivity suite
*
* This file is part of OpenOffice.org.
*
* OpenOffice.org is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License version 3
* only, as published by the Free Software Foundation.
*
* OpenOffice.org is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License version 3 for more details
* (a copy is included in the LICENSE file that accompanied this code).
*
* You should have received a copy of the GNU Lesser General Public License
* version 3 along with OpenOffice.org. If not, see
* <http://www.openoffice.org/license.html>
* for a copy of the LGPLv3 License.
*
************************************************************************/
// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_svl.hxx"
#define _SVARRAY_CXX
#define _SVSTDARR_ULONGS
#define _SVSTDARR_sal_uInt16S
#define _SVSTDARR_STRINGS
#define _SVSTDARR_STRINGSDTOR
#define _SVSTDARR_STRINGSSORT
#define _SVSTDARR_STRINGSSORTDTOR
#define _SVSTDARR_STRINGSISORT
#define _SVSTDARR_STRINGSISORTDTOR
#define _SVSTDARR_sal_uInt16SSORT
#define _SVSTDARR_BYTESTRINGS
#define _SVSTDARR_BYTESTRINGSDTOR
#define _SVSTDARR_BYTESTRINGSSORT
#define _SVSTDARR_BYTESTRINGSSORTDTOR
#define _SVSTDARR_BYTESTRINGSISORT
#define _SVSTDARR_BYTESTRINGSISORTDTOR
#define _SVSTDARR_XUB_STRLEN
#define _SVSTDARR_XUB_STRLENSORT
#include <svl/svstdarr.hxx>
#include <tools/string.hxx>
#include <tools/debug.hxx>
SV_IMPL_VARARR(SvPtrarr,VoidPtr)
sal_uInt16 SvPtrarr::GetPos( const VoidPtr& aElement ) const
{ sal_uInt16 n;
for( n=0; n < nA && *(GetData()+n) != aElement; ) n++;
return ( n >= nA ? USHRT_MAX : n );
}
SV_IMPL_VARARR( SvULongs, sal_uLong )
SV_IMPL_VARARR( SvUShorts, sal_uInt16 )
SV_IMPL_PTRARR( SvStrings, StringPtr )
SV_IMPL_PTRARR( SvStringsDtor, StringPtr )
SV_IMPL_OP_PTRARR_SORT( SvStringsSort, StringPtr )
SV_IMPL_OP_PTRARR_SORT( SvStringsSortDtor, StringPtr )
SV_IMPL_PTRARR( SvByteStrings, ByteStringPtr )
SV_IMPL_PTRARR( SvByteStringsDtor, ByteStringPtr )
SV_IMPL_OP_PTRARR_SORT( SvByteStringsSort, ByteStringPtr )
SV_IMPL_OP_PTRARR_SORT( SvByteStringsSortDtor, ByteStringPtr )
// ---------------- strings -------------------------------------
// Array mit anderer Seek-Methode!
_SV_IMPL_SORTAR_ALG( SvStringsISort, StringPtr )
void SvStringsISort::DeleteAndDestroy( sal_uInt16 nP, sal_uInt16 nL )
{
if( nL )
{
DBG_ASSERT( nP < nA && nP + nL <= nA, "ERR_VAR_DEL" );
for( sal_uInt16 n=nP; n < nP + nL; n++ )
delete *((StringPtr*)pData+n);
SvPtrarr::Remove( nP, nL );
}
}
sal_Bool SvStringsISort::Seek_Entry( const StringPtr aE, sal_uInt16* pP ) const
{
register sal_uInt16 nO = SvStringsISort_SAR::Count(),
nM,
nU = 0;
if( nO > 0 )
{
nO--;
while( nU <= nO )
{
nM = nU + ( nO - nU ) / 2;
StringCompare eCmp = (*((StringPtr*)pData + nM))->
CompareIgnoreCaseToAscii( *(aE) );
if( COMPARE_EQUAL == eCmp )
{
if( pP ) *pP = nM;
return sal_True;
}
else if( COMPARE_LESS == eCmp )
nU = nM + 1;
else if( nM == 0 )
{
if( pP ) *pP = nU;
return sal_False;
}
else
nO = nM - 1;
}
}
if( pP ) *pP = nU;
return sal_False;
}
// ---------------- strings -------------------------------------
// Array mit anderer Seek-Methode!
_SV_IMPL_SORTAR_ALG( SvStringsISortDtor, StringPtr )
void SvStringsISortDtor::DeleteAndDestroy( sal_uInt16 nP, sal_uInt16 nL )
{
if( nL )
{
DBG_ASSERT( nP < nA && nP + nL <= nA, "ERR_VAR_DEL" );
for( sal_uInt16 n=nP; n < nP + nL; n++ )
delete *((StringPtr*)pData+n);
SvPtrarr::Remove( nP, nL );
}
}
sal_Bool SvStringsISortDtor::Seek_Entry( const StringPtr aE, sal_uInt16* pP ) const
{
register sal_uInt16 nO = SvStringsISortDtor_SAR::Count(),
nM,
nU = 0;
if( nO > 0 )
{
nO--;
while( nU <= nO )
{
nM = nU + ( nO - nU ) / 2;
StringCompare eCmp = (*((StringPtr*)pData + nM))->
CompareIgnoreCaseToAscii( *(aE) );
if( COMPARE_EQUAL == eCmp )
{
if( pP ) *pP = nM;
return sal_True;
}
else if( COMPARE_LESS == eCmp )
nU = nM + 1;
else if( nM == 0 )
{
if( pP ) *pP = nU;
return sal_False;
}
else
nO = nM - 1;
}
}
if( pP ) *pP = nU;
return sal_False;
}
// ---------------- Ushorts -------------------------------------
/* SortArray fuer UShorts */
sal_Bool SvUShortsSort::Seek_Entry( const sal_uInt16 aE, sal_uInt16* pP ) const
{
register sal_uInt16 nO = SvUShorts::Count(),
nM,
nU = 0;
if( nO > 0 )
{
nO--;
while( nU <= nO )
{
nM = nU + ( nO - nU ) / 2;
if( *(pData + nM) == aE )
{
if( pP ) *pP = nM;
return sal_True;
}
else if( *(pData + nM) < aE )
nU = nM + 1;
else if( nM == 0 )
{
if( pP ) *pP = nU;
return sal_False;
}
else
nO = nM - 1;
}
}
if( pP ) *pP = nU;
return sal_False;
}
void SvUShortsSort::Insert( const SvUShortsSort * pI, sal_uInt16 nS, sal_uInt16 nE )
{
if( USHRT_MAX == nE )
nE = pI->Count();
sal_uInt16 nP;
const sal_uInt16 * pIArr = pI->GetData();
for( ; nS < nE; ++nS )
{
if( ! Seek_Entry( *(pIArr+nS), &nP) )
SvUShorts::Insert( *(pIArr+nS), nP );
if( ++nP >= Count() )
{
SvUShorts::Insert( pI, nP, nS+1, nE );
nS = nE;
}
}
}
sal_Bool SvUShortsSort::Insert( const sal_uInt16 aE )
{
sal_uInt16 nP;
sal_Bool bExist = Seek_Entry( aE, &nP );
if( !bExist )
SvUShorts::Insert( aE, nP );
return !bExist;
}
sal_Bool SvUShortsSort::Insert( const sal_uInt16 aE, sal_uInt16& rP )
{
sal_Bool bExist = Seek_Entry( aE, &rP );
if( !bExist )
SvUShorts::Insert( aE, rP );
return !bExist;
}
void SvUShortsSort::Insert( const sal_uInt16* pE, sal_uInt16 nL)
{
sal_uInt16 nP;
for( sal_uInt16 n = 0; n < nL; ++n )
if( ! Seek_Entry( *(pE+n), &nP ))
SvUShorts::Insert( *(pE+n), nP );
}
// remove ab Pos
void SvUShortsSort::RemoveAt( const sal_uInt16 nP, sal_uInt16 nL )
{
if( nL )
SvUShorts::Remove( nP, nL);
}
// remove ab dem Eintrag
void SvUShortsSort::Remove( const sal_uInt16 aE, sal_uInt16 nL )
{
sal_uInt16 nP;
if( nL && Seek_Entry( aE, &nP ) )
SvUShorts::Remove( nP, nL);
}
// ---------------- bytestrings -------------------------------------
// Array mit anderer Seek-Methode!
_SV_IMPL_SORTAR_ALG( SvByteStringsISort, ByteStringPtr )
void SvByteStringsISort::DeleteAndDestroy( sal_uInt16 nP, sal_uInt16 nL )
{
if( nL )
{
DBG_ASSERT( nP < nA && nP + nL <= nA, "ERR_VAR_DEL" );
for( sal_uInt16 n=nP; n < nP + nL; n++ )
delete *((ByteStringPtr*)pData+n);
SvPtrarr::Remove( nP, nL );
}
}
sal_Bool SvByteStringsISort::Seek_Entry( const ByteStringPtr aE, sal_uInt16* pP ) const
{
register sal_uInt16 nO = SvByteStringsISort_SAR::Count(),
nM,
nU = 0;
if( nO > 0 )
{
nO--;
while( nU <= nO )
{
nM = nU + ( nO - nU ) / 2;
StringCompare eCmp = (*((ByteStringPtr*)pData + nM))->
CompareIgnoreCaseToAscii( *(aE) );
if( COMPARE_EQUAL == eCmp )
{
if( pP ) *pP = nM;
return sal_True;
}
else if( COMPARE_LESS == eCmp )
nU = nM + 1;
else if( nM == 0 )
{
if( pP ) *pP = nU;
return sal_False;
}
else
nO = nM - 1;
}
}
if( pP ) *pP = nU;
return sal_False;
}
// Array mit anderer Seek-Methode!
_SV_IMPL_SORTAR_ALG( SvByteStringsISortDtor, ByteStringPtr )
void SvByteStringsISortDtor::DeleteAndDestroy( sal_uInt16 nP, sal_uInt16 nL )
{
if( nL )
{
DBG_ASSERT( nP < nA && nP + nL <= nA, "ERR_VAR_DEL" );
for( sal_uInt16 n=nP; n < nP + nL; n++ )
delete *((ByteStringPtr*)pData+n);
SvPtrarr::Remove( nP, nL );
}
}
sal_Bool SvByteStringsISortDtor::Seek_Entry( const ByteStringPtr aE, sal_uInt16* pP ) const
{
register sal_uInt16 nO = SvByteStringsISortDtor_SAR::Count(),
nM,
nU = 0;
if( nO > 0 )
{
nO--;
while( nU <= nO )
{
nM = nU + ( nO - nU ) / 2;
StringCompare eCmp = (*((ByteStringPtr*)pData + nM))->
CompareIgnoreCaseToAscii( *(aE) );
if( COMPARE_EQUAL == eCmp )
{
if( pP ) *pP = nM;
return sal_True;
}
else if( COMPARE_LESS == eCmp )
nU = nM + 1;
else if( nM == 0 )
{
if( pP ) *pP = nU;
return sal_False;
}
else
nO = nM - 1;
}
}
if( pP ) *pP = nU;
return sal_False;
}
/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
<commit_msg>Remove last trace of SvXub_StrLensSort. LGPLv3+/MPL.<commit_after>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*************************************************************************
*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* Copyright 2000, 2010 Oracle and/or its affiliates.
*
* OpenOffice.org - a multi-platform office productivity suite
*
* This file is part of OpenOffice.org.
*
* OpenOffice.org is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License version 3
* only, as published by the Free Software Foundation.
*
* OpenOffice.org is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License version 3 for more details
* (a copy is included in the LICENSE file that accompanied this code).
*
* You should have received a copy of the GNU Lesser General Public License
* version 3 along with OpenOffice.org. If not, see
* <http://www.openoffice.org/license.html>
* for a copy of the LGPLv3 License.
*
************************************************************************/
// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_svl.hxx"
#define _SVARRAY_CXX
#define _SVSTDARR_ULONGS
#define _SVSTDARR_sal_uInt16S
#define _SVSTDARR_STRINGS
#define _SVSTDARR_STRINGSDTOR
#define _SVSTDARR_STRINGSSORT
#define _SVSTDARR_STRINGSSORTDTOR
#define _SVSTDARR_STRINGSISORT
#define _SVSTDARR_STRINGSISORTDTOR
#define _SVSTDARR_sal_uInt16SSORT
#define _SVSTDARR_BYTESTRINGS
#define _SVSTDARR_BYTESTRINGSDTOR
#define _SVSTDARR_BYTESTRINGSSORT
#define _SVSTDARR_BYTESTRINGSSORTDTOR
#define _SVSTDARR_BYTESTRINGSISORT
#define _SVSTDARR_BYTESTRINGSISORTDTOR
#define _SVSTDARR_XUB_STRLEN
#include <svl/svstdarr.hxx>
#include <tools/string.hxx>
#include <tools/debug.hxx>
SV_IMPL_VARARR(SvPtrarr,VoidPtr)
sal_uInt16 SvPtrarr::GetPos( const VoidPtr& aElement ) const
{ sal_uInt16 n;
for( n=0; n < nA && *(GetData()+n) != aElement; ) n++;
return ( n >= nA ? USHRT_MAX : n );
}
SV_IMPL_VARARR( SvULongs, sal_uLong )
SV_IMPL_VARARR( SvUShorts, sal_uInt16 )
SV_IMPL_PTRARR( SvStrings, StringPtr )
SV_IMPL_PTRARR( SvStringsDtor, StringPtr )
SV_IMPL_OP_PTRARR_SORT( SvStringsSort, StringPtr )
SV_IMPL_OP_PTRARR_SORT( SvStringsSortDtor, StringPtr )
SV_IMPL_PTRARR( SvByteStrings, ByteStringPtr )
SV_IMPL_PTRARR( SvByteStringsDtor, ByteStringPtr )
SV_IMPL_OP_PTRARR_SORT( SvByteStringsSort, ByteStringPtr )
SV_IMPL_OP_PTRARR_SORT( SvByteStringsSortDtor, ByteStringPtr )
// ---------------- strings -------------------------------------
// Array mit anderer Seek-Methode!
_SV_IMPL_SORTAR_ALG( SvStringsISort, StringPtr )
void SvStringsISort::DeleteAndDestroy( sal_uInt16 nP, sal_uInt16 nL )
{
if( nL )
{
DBG_ASSERT( nP < nA && nP + nL <= nA, "ERR_VAR_DEL" );
for( sal_uInt16 n=nP; n < nP + nL; n++ )
delete *((StringPtr*)pData+n);
SvPtrarr::Remove( nP, nL );
}
}
sal_Bool SvStringsISort::Seek_Entry( const StringPtr aE, sal_uInt16* pP ) const
{
register sal_uInt16 nO = SvStringsISort_SAR::Count(),
nM,
nU = 0;
if( nO > 0 )
{
nO--;
while( nU <= nO )
{
nM = nU + ( nO - nU ) / 2;
StringCompare eCmp = (*((StringPtr*)pData + nM))->
CompareIgnoreCaseToAscii( *(aE) );
if( COMPARE_EQUAL == eCmp )
{
if( pP ) *pP = nM;
return sal_True;
}
else if( COMPARE_LESS == eCmp )
nU = nM + 1;
else if( nM == 0 )
{
if( pP ) *pP = nU;
return sal_False;
}
else
nO = nM - 1;
}
}
if( pP ) *pP = nU;
return sal_False;
}
// ---------------- strings -------------------------------------
// Array mit anderer Seek-Methode!
_SV_IMPL_SORTAR_ALG( SvStringsISortDtor, StringPtr )
void SvStringsISortDtor::DeleteAndDestroy( sal_uInt16 nP, sal_uInt16 nL )
{
if( nL )
{
DBG_ASSERT( nP < nA && nP + nL <= nA, "ERR_VAR_DEL" );
for( sal_uInt16 n=nP; n < nP + nL; n++ )
delete *((StringPtr*)pData+n);
SvPtrarr::Remove( nP, nL );
}
}
sal_Bool SvStringsISortDtor::Seek_Entry( const StringPtr aE, sal_uInt16* pP ) const
{
register sal_uInt16 nO = SvStringsISortDtor_SAR::Count(),
nM,
nU = 0;
if( nO > 0 )
{
nO--;
while( nU <= nO )
{
nM = nU + ( nO - nU ) / 2;
StringCompare eCmp = (*((StringPtr*)pData + nM))->
CompareIgnoreCaseToAscii( *(aE) );
if( COMPARE_EQUAL == eCmp )
{
if( pP ) *pP = nM;
return sal_True;
}
else if( COMPARE_LESS == eCmp )
nU = nM + 1;
else if( nM == 0 )
{
if( pP ) *pP = nU;
return sal_False;
}
else
nO = nM - 1;
}
}
if( pP ) *pP = nU;
return sal_False;
}
// ---------------- Ushorts -------------------------------------
/* SortArray fuer UShorts */
sal_Bool SvUShortsSort::Seek_Entry( const sal_uInt16 aE, sal_uInt16* pP ) const
{
register sal_uInt16 nO = SvUShorts::Count(),
nM,
nU = 0;
if( nO > 0 )
{
nO--;
while( nU <= nO )
{
nM = nU + ( nO - nU ) / 2;
if( *(pData + nM) == aE )
{
if( pP ) *pP = nM;
return sal_True;
}
else if( *(pData + nM) < aE )
nU = nM + 1;
else if( nM == 0 )
{
if( pP ) *pP = nU;
return sal_False;
}
else
nO = nM - 1;
}
}
if( pP ) *pP = nU;
return sal_False;
}
void SvUShortsSort::Insert( const SvUShortsSort * pI, sal_uInt16 nS, sal_uInt16 nE )
{
if( USHRT_MAX == nE )
nE = pI->Count();
sal_uInt16 nP;
const sal_uInt16 * pIArr = pI->GetData();
for( ; nS < nE; ++nS )
{
if( ! Seek_Entry( *(pIArr+nS), &nP) )
SvUShorts::Insert( *(pIArr+nS), nP );
if( ++nP >= Count() )
{
SvUShorts::Insert( pI, nP, nS+1, nE );
nS = nE;
}
}
}
sal_Bool SvUShortsSort::Insert( const sal_uInt16 aE )
{
sal_uInt16 nP;
sal_Bool bExist = Seek_Entry( aE, &nP );
if( !bExist )
SvUShorts::Insert( aE, nP );
return !bExist;
}
sal_Bool SvUShortsSort::Insert( const sal_uInt16 aE, sal_uInt16& rP )
{
sal_Bool bExist = Seek_Entry( aE, &rP );
if( !bExist )
SvUShorts::Insert( aE, rP );
return !bExist;
}
void SvUShortsSort::Insert( const sal_uInt16* pE, sal_uInt16 nL)
{
sal_uInt16 nP;
for( sal_uInt16 n = 0; n < nL; ++n )
if( ! Seek_Entry( *(pE+n), &nP ))
SvUShorts::Insert( *(pE+n), nP );
}
// remove ab Pos
void SvUShortsSort::RemoveAt( const sal_uInt16 nP, sal_uInt16 nL )
{
if( nL )
SvUShorts::Remove( nP, nL);
}
// remove ab dem Eintrag
void SvUShortsSort::Remove( const sal_uInt16 aE, sal_uInt16 nL )
{
sal_uInt16 nP;
if( nL && Seek_Entry( aE, &nP ) )
SvUShorts::Remove( nP, nL);
}
// ---------------- bytestrings -------------------------------------
// Array mit anderer Seek-Methode!
_SV_IMPL_SORTAR_ALG( SvByteStringsISort, ByteStringPtr )
void SvByteStringsISort::DeleteAndDestroy( sal_uInt16 nP, sal_uInt16 nL )
{
if( nL )
{
DBG_ASSERT( nP < nA && nP + nL <= nA, "ERR_VAR_DEL" );
for( sal_uInt16 n=nP; n < nP + nL; n++ )
delete *((ByteStringPtr*)pData+n);
SvPtrarr::Remove( nP, nL );
}
}
sal_Bool SvByteStringsISort::Seek_Entry( const ByteStringPtr aE, sal_uInt16* pP ) const
{
register sal_uInt16 nO = SvByteStringsISort_SAR::Count(),
nM,
nU = 0;
if( nO > 0 )
{
nO--;
while( nU <= nO )
{
nM = nU + ( nO - nU ) / 2;
StringCompare eCmp = (*((ByteStringPtr*)pData + nM))->
CompareIgnoreCaseToAscii( *(aE) );
if( COMPARE_EQUAL == eCmp )
{
if( pP ) *pP = nM;
return sal_True;
}
else if( COMPARE_LESS == eCmp )
nU = nM + 1;
else if( nM == 0 )
{
if( pP ) *pP = nU;
return sal_False;
}
else
nO = nM - 1;
}
}
if( pP ) *pP = nU;
return sal_False;
}
// Array mit anderer Seek-Methode!
_SV_IMPL_SORTAR_ALG( SvByteStringsISortDtor, ByteStringPtr )
void SvByteStringsISortDtor::DeleteAndDestroy( sal_uInt16 nP, sal_uInt16 nL )
{
if( nL )
{
DBG_ASSERT( nP < nA && nP + nL <= nA, "ERR_VAR_DEL" );
for( sal_uInt16 n=nP; n < nP + nL; n++ )
delete *((ByteStringPtr*)pData+n);
SvPtrarr::Remove( nP, nL );
}
}
sal_Bool SvByteStringsISortDtor::Seek_Entry( const ByteStringPtr aE, sal_uInt16* pP ) const
{
register sal_uInt16 nO = SvByteStringsISortDtor_SAR::Count(),
nM,
nU = 0;
if( nO > 0 )
{
nO--;
while( nU <= nO )
{
nM = nU + ( nO - nU ) / 2;
StringCompare eCmp = (*((ByteStringPtr*)pData + nM))->
CompareIgnoreCaseToAscii( *(aE) );
if( COMPARE_EQUAL == eCmp )
{
if( pP ) *pP = nM;
return sal_True;
}
else if( COMPARE_LESS == eCmp )
nU = nM + 1;
else if( nM == 0 )
{
if( pP ) *pP = nU;
return sal_False;
}
else
nO = nM - 1;
}
}
if( pP ) *pP = nU;
return sal_False;
}
/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
<|endoftext|> |
<commit_before>/*
This file implements the classes defined in Match.h:
Match, Capability, and Client
A Match object contains all of the information a startd needs
about a given match, such as the capability, the client of this
match, etc. The capability in the match is just a pointer to a
Capability object. The client is also just a pointer to a Client
object. The startd maintains two Match objects in the "rip", the
per-resource information structure. One for the current match,
and one for the possibly preempting match that is pending.
A Capability object contains the capability string, and some
functions to manipulate and compare against this string. The
constructor generates a new capability with the following form:
<ip:port>#random_integer
A Client object contains all the info about a given client of a
startd. In particular, the client name (a.k.a. "user"), the
address ("<www.xxx.yyy.zzz:pppp>" formed ip/port), and the
hostname.
Written 9/29/97 by Derek Wright <wright@cs.wisc.edu>
*/
#include "startd.h"
static char *_FileName_ = __FILE__;
///////////////////////////////////////////////////////////////////////////
// Match
///////////////////////////////////////////////////////////////////////////
Match::Match()
{
m_client = new Client;
m_cap = new Capability;
m_ad = NULL;
m_rank = -1;
m_oldrank = -1;
m_universe = -1;
m_agentstream = NULL;
m_match_tid = -1;
m_claim_tid = -1;
m_aliveint = -1;
}
Match::~Match()
{
// Cancel any timers associated with this match
this->cancel_match_timer();
this->cancel_claim_timer();
// Free up memory that's been allocated
if( m_ad ) {
delete( m_ad );
}
delete( m_cap );
if( m_client ) {
delete( m_client );
}
// We don't want to delete m_agentstream, since DaemonCore
// will delete it for us.
// delete( m_agentstream );
}
// Vacate the current match
void
Match::vacate()
{
assert( m_cap );
// warn the client of this match that it's being vacated
if( m_client && m_client->addr() ) {
m_client->vacate( m_cap->capab() );
}
// send RELEASE_CLAIM and capability to accountant
if( accountant_host ) {
ReliSock sock;
sock.timeout( 30 );
if( sock.connect( accountant_host, ACCOUNTANT_PORT ) < 0 ) {
dprintf(D_ALWAYS, "Couldn't connect to accountant\n");
} else {
if( !sock.put( RELEASE_CLAIM ) ) {
dprintf(D_ALWAYS, "Can't send RELEASE_CLAIM command\n");
} else if( !sock.put( m_cap->capab() ) ) {
dprintf(D_ALWAYS, "Can't send capability to accountant\n");
} else if( !sock.eom() ) {
dprintf(D_ALWAYS, "Can't send EOM to accountant\n");
}
sock.close();
}
}
}
void
Match::start_match_timer()
{
m_match_tid =
daemonCore->Register_Timer( match_timeout, 0,
(TimerHandler)match_timed_out,
"match_timed_out" );
if( m_match_tid == -1 ) {
EXCEPT( "Couldn't register timer (out of memory)." );
}
if( ! daemonCore->Register_DataPtr( (void*) this ) ) {
EXCEPT( "Couldn't register data pointer for match_timed_out handler" );
}
dprintf( D_FULLDEBUG, "Started match timer for %d seconds.\n",
match_timeout );
}
void
Match::cancel_match_timer()
{
if( m_match_tid != -1 ) {
daemonCore->Cancel_Timer( m_match_tid );
m_match_tid = -1;
dprintf( D_FULLDEBUG, "Canceled match timer.\n" );
}
}
void
Match::start_claim_timer()
{
if( m_aliveint < 0 ) {
dprintf( D_ALWAYS,
"Warning: starting claim timer before alive interval set.\n" );
m_aliveint = 300;
}
m_claim_tid =
daemonCore->Register_Timer( (3 * m_aliveint), 0,
(TimerHandler)claim_timed_out,
"claim_timed_out" );
if( m_claim_tid == -1 ) {
EXCEPT( "Couldn't register timer (out of memory)." );
}
if( ! daemonCore->Register_DataPtr( (void*) this ) ) {
EXCEPT( "Couldn't register data pointer." );
}
dprintf( D_FULLDEBUG, "Started claim timer w/ %d second alive interval.\n",
m_aliveint );
}
void
Match::cancel_claim_timer()
{
if( m_claim_tid != -1 ) {
daemonCore->Cancel_Timer( m_claim_tid );
m_claim_tid = -1;
dprintf( D_FULLDEBUG, "Canceled claim timer.\n" );
}
}
void
Match::alive()
{
// Process a keep alive command
daemonCore->Reset_Timer( m_claim_tid, (3 * m_aliveint), 0 );
}
// The claim timed out, so we should delete our m_client object, since
// it is pointing to a dead daemon.
void
Match::claim_timed_out()
{
if( m_client ) {
delete m_client;
m_client = NULL;
}
}
// Set our ad to the given pointer
void
Match::setad(ClassAd *ad)
{
if( m_ad ) {
delete( m_ad );
}
m_ad = ad;
}
void
Match::deletead(void)
{
if( m_ad ) {
delete( m_ad );
m_ad = NULL;
}
}
void
Match::setagentstream(Stream* stream)
{
if( m_agentstream ) {
delete( m_agentstream );
}
m_agentstream = stream;
}
///////////////////////////////////////////////////////////////////////////
// Client
///////////////////////////////////////////////////////////////////////////
Client::Client()
{
c_name = NULL;
c_addr = NULL;
c_host = NULL;
}
Client::~Client()
{
free( c_name );
free( c_addr );
free( c_host );
}
void
Client::setname(char* name)
{
if( c_name ) {
free( c_name);
}
if( name ) {
c_name = strdup( name );
} else {
c_name = NULL;
}
}
void
Client::setaddr(char* addr)
{
if( c_addr ) {
free( c_addr);
}
if( addr ) {
c_addr = strdup( addr );
} else {
c_addr = NULL;
}
}
void
Client::sethost(char* host)
{
if( c_host ) {
free( c_host);
}
if( host ) {
c_host = strdup( host );
} else {
c_host = NULL;
}
}
void
Client::vacate(char* cap)
{
ReliSock sock;
sock.timeout( 30 );
if( ! (c_addr || c_host || c_name ) ) {
// Client not really set, nothing to do.
return;
}
dprintf(D_FULLDEBUG, "Entered vacate_client %s %s...\n", c_addr, c_host);
if( sock.connect( c_addr, 0 ) < 0 ) {
dprintf(D_ALWAYS, "Can't connect to schedd (%s)\n", c_addr);
} else {
if( !sock.put( RELEASE_CLAIM ) ) {
dprintf(D_ALWAYS, "Can't send RELEASE_CLAIM command to client\n");
} else if( !sock.put( cap ) ) {
dprintf(D_ALWAYS, "Can't send capability to client\n");
} else if( !sock.eom() ) {
dprintf(D_ALWAYS, "Can't send EOM to client\n");
}
sock.close();
}
}
///////////////////////////////////////////////////////////////////////////
// Capability
///////////////////////////////////////////////////////////////////////////
char*
new_capability_string()
{
char cap[256];
cap[0] = '\0';
char tmp[128];
sprintf( tmp, "%d\0", get_random_int() );
strcpy( cap, daemonCore->InfoCommandSinfulString() );
strcat( cap, "#" );
strcat( cap, tmp );
return strdup( cap );
}
Capability::Capability()
{
c_capab = new_capability_string();
}
Capability::~Capability()
{
free( c_capab );
}
int
Capability::matches(char* capab)
{
return( strcmp(capab, c_capab) == 0 );
}
void
Capability::setcapab(char* capab)
{
if( c_capab ) {
free( c_capab );
}
if( capab ) {
c_capab = strdup( capab );
} else {
c_capab = NULL;
}
}
<commit_msg>Since the Match class has a "claim_timed_out" member function, when we register the DC timer handler for claim_timed_out, we need to use ::claim_timed_out to specify we want the regular claim_timed_out function, not the Match member.<commit_after>/*
This file implements the classes defined in Match.h:
Match, Capability, and Client
A Match object contains all of the information a startd needs
about a given match, such as the capability, the client of this
match, etc. The capability in the match is just a pointer to a
Capability object. The client is also just a pointer to a Client
object. The startd maintains two Match objects in the "rip", the
per-resource information structure. One for the current match,
and one for the possibly preempting match that is pending.
A Capability object contains the capability string, and some
functions to manipulate and compare against this string. The
constructor generates a new capability with the following form:
<ip:port>#random_integer
A Client object contains all the info about a given client of a
startd. In particular, the client name (a.k.a. "user"), the
address ("<www.xxx.yyy.zzz:pppp>" formed ip/port), and the
hostname.
Written 9/29/97 by Derek Wright <wright@cs.wisc.edu>
*/
#include "startd.h"
static char *_FileName_ = __FILE__;
///////////////////////////////////////////////////////////////////////////
// Match
///////////////////////////////////////////////////////////////////////////
Match::Match()
{
m_client = new Client;
m_cap = new Capability;
m_ad = NULL;
m_rank = -1;
m_oldrank = -1;
m_universe = -1;
m_agentstream = NULL;
m_match_tid = -1;
m_claim_tid = -1;
m_aliveint = -1;
}
Match::~Match()
{
// Cancel any timers associated with this match
this->cancel_match_timer();
this->cancel_claim_timer();
// Free up memory that's been allocated
if( m_ad ) {
delete( m_ad );
}
delete( m_cap );
if( m_client ) {
delete( m_client );
}
// We don't want to delete m_agentstream, since DaemonCore
// will delete it for us.
// delete( m_agentstream );
}
// Vacate the current match
void
Match::vacate()
{
assert( m_cap );
// warn the client of this match that it's being vacated
if( m_client && m_client->addr() ) {
m_client->vacate( m_cap->capab() );
}
// send RELEASE_CLAIM and capability to accountant
if( accountant_host ) {
ReliSock sock;
sock.timeout( 30 );
if( sock.connect( accountant_host, ACCOUNTANT_PORT ) < 0 ) {
dprintf(D_ALWAYS, "Couldn't connect to accountant\n");
} else {
if( !sock.put( RELEASE_CLAIM ) ) {
dprintf(D_ALWAYS, "Can't send RELEASE_CLAIM command\n");
} else if( !sock.put( m_cap->capab() ) ) {
dprintf(D_ALWAYS, "Can't send capability to accountant\n");
} else if( !sock.eom() ) {
dprintf(D_ALWAYS, "Can't send EOM to accountant\n");
}
sock.close();
}
}
}
void
Match::start_match_timer()
{
m_match_tid =
daemonCore->Register_Timer( match_timeout, 0,
(TimerHandler)match_timed_out,
"match_timed_out" );
if( m_match_tid == -1 ) {
EXCEPT( "Couldn't register timer (out of memory)." );
}
if( ! daemonCore->Register_DataPtr( (void*) this ) ) {
EXCEPT( "Couldn't register data pointer for match_timed_out handler" );
}
dprintf( D_FULLDEBUG, "Started match timer for %d seconds.\n",
match_timeout );
}
void
Match::cancel_match_timer()
{
if( m_match_tid != -1 ) {
daemonCore->Cancel_Timer( m_match_tid );
m_match_tid = -1;
dprintf( D_FULLDEBUG, "Canceled match timer.\n" );
}
}
void
Match::start_claim_timer()
{
if( m_aliveint < 0 ) {
dprintf( D_ALWAYS,
"Warning: starting claim timer before alive interval set.\n" );
m_aliveint = 300;
}
m_claim_tid =
daemonCore->Register_Timer( (3 * m_aliveint), 0,
(TimerHandler) ::claim_timed_out,
"claim_timed_out" );
if( m_claim_tid == -1 ) {
EXCEPT( "Couldn't register timer (out of memory)." );
}
if( ! daemonCore->Register_DataPtr( (void*) this ) ) {
EXCEPT( "Couldn't register data pointer." );
}
dprintf( D_FULLDEBUG, "Started claim timer w/ %d second alive interval.\n",
m_aliveint );
}
void
Match::cancel_claim_timer()
{
if( m_claim_tid != -1 ) {
daemonCore->Cancel_Timer( m_claim_tid );
m_claim_tid = -1;
dprintf( D_FULLDEBUG, "Canceled claim timer.\n" );
}
}
void
Match::alive()
{
// Process a keep alive command
daemonCore->Reset_Timer( m_claim_tid, (3 * m_aliveint), 0 );
}
// The claim timed out, so we should delete our m_client object, since
// it is pointing to a dead daemon.
void
Match::claim_timed_out()
{
if( m_client ) {
delete m_client;
m_client = NULL;
}
}
// Set our ad to the given pointer
void
Match::setad(ClassAd *ad)
{
if( m_ad ) {
delete( m_ad );
}
m_ad = ad;
}
void
Match::deletead(void)
{
if( m_ad ) {
delete( m_ad );
m_ad = NULL;
}
}
void
Match::setagentstream(Stream* stream)
{
if( m_agentstream ) {
delete( m_agentstream );
}
m_agentstream = stream;
}
///////////////////////////////////////////////////////////////////////////
// Client
///////////////////////////////////////////////////////////////////////////
Client::Client()
{
c_name = NULL;
c_addr = NULL;
c_host = NULL;
}
Client::~Client()
{
free( c_name );
free( c_addr );
free( c_host );
}
void
Client::setname(char* name)
{
if( c_name ) {
free( c_name);
}
if( name ) {
c_name = strdup( name );
} else {
c_name = NULL;
}
}
void
Client::setaddr(char* addr)
{
if( c_addr ) {
free( c_addr);
}
if( addr ) {
c_addr = strdup( addr );
} else {
c_addr = NULL;
}
}
void
Client::sethost(char* host)
{
if( c_host ) {
free( c_host);
}
if( host ) {
c_host = strdup( host );
} else {
c_host = NULL;
}
}
void
Client::vacate(char* cap)
{
ReliSock sock;
sock.timeout( 30 );
if( ! (c_addr || c_host || c_name ) ) {
// Client not really set, nothing to do.
return;
}
dprintf(D_FULLDEBUG, "Entered vacate_client %s %s...\n", c_addr, c_host);
if( sock.connect( c_addr, 0 ) < 0 ) {
dprintf(D_ALWAYS, "Can't connect to schedd (%s)\n", c_addr);
} else {
if( !sock.put( RELEASE_CLAIM ) ) {
dprintf(D_ALWAYS, "Can't send RELEASE_CLAIM command to client\n");
} else if( !sock.put( cap ) ) {
dprintf(D_ALWAYS, "Can't send capability to client\n");
} else if( !sock.eom() ) {
dprintf(D_ALWAYS, "Can't send EOM to client\n");
}
sock.close();
}
}
///////////////////////////////////////////////////////////////////////////
// Capability
///////////////////////////////////////////////////////////////////////////
char*
new_capability_string()
{
char cap[256];
cap[0] = '\0';
char tmp[128];
sprintf( tmp, "%d\0", get_random_int() );
strcpy( cap, daemonCore->InfoCommandSinfulString() );
strcat( cap, "#" );
strcat( cap, tmp );
return strdup( cap );
}
Capability::Capability()
{
c_capab = new_capability_string();
}
Capability::~Capability()
{
free( c_capab );
}
int
Capability::matches(char* capab)
{
return( strcmp(capab, c_capab) == 0 );
}
void
Capability::setcapab(char* capab)
{
if( c_capab ) {
free( c_capab );
}
if( capab ) {
c_capab = strdup( capab );
} else {
c_capab = NULL;
}
}
<|endoftext|> |
<commit_before>//===- PassRegistry.cpp - Pass Registration Implementation ----------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file implements the PassRegistry, with which passes are registered on
// initialization, and supports the PassManager in dependency resolution.
//
//===----------------------------------------------------------------------===//
#include "llvm/PassRegistry.h"
#include "llvm/ADT/DenseMap.h"
#include "llvm/ADT/SmallPtrSet.h"
#include "llvm/ADT/StringMap.h"
#include "llvm/IR/Function.h"
#include "llvm/PassSupport.h"
#include "llvm/Support/Compiler.h"
#include "llvm/Support/ManagedStatic.h"
#include "llvm/Support/Mutex.h"
#include "llvm/Support/RWMutex.h"
#include <vector>
using namespace llvm;
// FIXME: We use ManagedStatic to erase the pass registrar on shutdown.
// Unfortunately, passes are registered with static ctors, and having
// llvm_shutdown clear this map prevents successful resurrection after
// llvm_shutdown is run. Ideally we should find a solution so that we don't
// leak the map, AND can still resurrect after shutdown.
static ManagedStatic<PassRegistry> PassRegistryObj;
PassRegistry *PassRegistry::getPassRegistry() {
return &*PassRegistryObj;
}
static ManagedStatic<sys::SmartRWMutex<true> > Lock;
//===----------------------------------------------------------------------===//
// PassRegistryImpl
//
namespace {
struct PassRegistryImpl {
/// PassInfoMap - Keep track of the PassInfo object for each registered pass.
typedef DenseMap<const void*, const PassInfo*> MapType;
MapType PassInfoMap;
typedef StringMap<const PassInfo*> StringMapType;
StringMapType PassInfoStringMap;
/// AnalysisGroupInfo - Keep track of information for each analysis group.
struct AnalysisGroupInfo {
SmallPtrSet<const PassInfo *, 8> Implementations;
};
DenseMap<const PassInfo*, AnalysisGroupInfo> AnalysisGroupInfoMap;
std::vector<std::unique_ptr<const PassInfo>> ToFree;
std::vector<PassRegistrationListener*> Listeners;
};
} // end anonymous namespace
void *PassRegistry::getImpl() const {
if (!pImpl)
pImpl = new PassRegistryImpl();
return pImpl;
}
//===----------------------------------------------------------------------===//
// Accessors
//
PassRegistry::~PassRegistry() {
sys::SmartScopedWriter<true> Guard(*Lock);
PassRegistryImpl *Impl = static_cast<PassRegistryImpl*>(pImpl);
delete Impl;
pImpl = nullptr;
}
const PassInfo *PassRegistry::getPassInfo(const void *TI) const {
sys::SmartScopedReader<true> Guard(*Lock);
PassRegistryImpl *Impl = static_cast<PassRegistryImpl*>(getImpl());
PassRegistryImpl::MapType::const_iterator I = Impl->PassInfoMap.find(TI);
return I != Impl->PassInfoMap.end() ? I->second : nullptr;
}
const PassInfo *PassRegistry::getPassInfo(StringRef Arg) const {
sys::SmartScopedReader<true> Guard(*Lock);
PassRegistryImpl *Impl = static_cast<PassRegistryImpl*>(getImpl());
PassRegistryImpl::StringMapType::const_iterator
I = Impl->PassInfoStringMap.find(Arg);
return I != Impl->PassInfoStringMap.end() ? I->second : nullptr;
}
//===----------------------------------------------------------------------===//
// Pass Registration mechanism
//
void PassRegistry::registerPass(const PassInfo &PI, bool ShouldFree) {
sys::SmartScopedWriter<true> Guard(*Lock);
PassRegistryImpl *Impl = static_cast<PassRegistryImpl*>(getImpl());
bool Inserted =
Impl->PassInfoMap.insert(std::make_pair(PI.getTypeInfo(),&PI)).second;
assert(Inserted && "Pass registered multiple times!");
(void)Inserted;
Impl->PassInfoStringMap[PI.getPassArgument()] = &PI;
// Notify any listeners.
for (std::vector<PassRegistrationListener*>::iterator
I = Impl->Listeners.begin(), E = Impl->Listeners.end(); I != E; ++I)
(*I)->passRegistered(&PI);
if (ShouldFree) Impl->ToFree.push_back(std::unique_ptr<const PassInfo>(&PI));
}
void PassRegistry::unregisterPass(const PassInfo &PI) {
sys::SmartScopedWriter<true> Guard(*Lock);
PassRegistryImpl *Impl = static_cast<PassRegistryImpl*>(getImpl());
PassRegistryImpl::MapType::iterator I =
Impl->PassInfoMap.find(PI.getTypeInfo());
assert(I != Impl->PassInfoMap.end() && "Pass registered but not in map!");
// Remove pass from the map.
Impl->PassInfoMap.erase(I);
Impl->PassInfoStringMap.erase(PI.getPassArgument());
}
void PassRegistry::enumerateWith(PassRegistrationListener *L) {
sys::SmartScopedReader<true> Guard(*Lock);
PassRegistryImpl *Impl = static_cast<PassRegistryImpl*>(getImpl());
for (PassRegistryImpl::MapType::const_iterator I = Impl->PassInfoMap.begin(),
E = Impl->PassInfoMap.end(); I != E; ++I)
L->passEnumerate(I->second);
}
/// Analysis Group Mechanisms.
void PassRegistry::registerAnalysisGroup(const void *InterfaceID,
const void *PassID,
PassInfo& Registeree,
bool isDefault,
bool ShouldFree) {
PassInfo *InterfaceInfo = const_cast<PassInfo*>(getPassInfo(InterfaceID));
if (!InterfaceInfo) {
// First reference to Interface, register it now.
registerPass(Registeree);
InterfaceInfo = &Registeree;
}
assert(Registeree.isAnalysisGroup() &&
"Trying to join an analysis group that is a normal pass!");
if (PassID) {
PassInfo *ImplementationInfo = const_cast<PassInfo*>(getPassInfo(PassID));
assert(ImplementationInfo &&
"Must register pass before adding to AnalysisGroup!");
sys::SmartScopedWriter<true> Guard(*Lock);
// Make sure we keep track of the fact that the implementation implements
// the interface.
ImplementationInfo->addInterfaceImplemented(InterfaceInfo);
PassRegistryImpl *Impl = static_cast<PassRegistryImpl*>(getImpl());
PassRegistryImpl::AnalysisGroupInfo &AGI =
Impl->AnalysisGroupInfoMap[InterfaceInfo];
assert(AGI.Implementations.count(ImplementationInfo) == 0 &&
"Cannot add a pass to the same analysis group more than once!");
AGI.Implementations.insert(ImplementationInfo);
if (isDefault) {
assert(InterfaceInfo->getNormalCtor() == nullptr &&
"Default implementation for analysis group already specified!");
assert(ImplementationInfo->getNormalCtor() &&
"Cannot specify pass as default if it does not have a default ctor");
InterfaceInfo->setNormalCtor(ImplementationInfo->getNormalCtor());
InterfaceInfo->setTargetMachineCtor(
ImplementationInfo->getTargetMachineCtor());
}
}
PassRegistryImpl *Impl = static_cast<PassRegistryImpl*>(getImpl());
if (ShouldFree)
Impl->ToFree.push_back(std::unique_ptr<const PassInfo>(&Registeree));
}
void PassRegistry::addRegistrationListener(PassRegistrationListener *L) {
sys::SmartScopedWriter<true> Guard(*Lock);
PassRegistryImpl *Impl = static_cast<PassRegistryImpl*>(getImpl());
Impl->Listeners.push_back(L);
}
void PassRegistry::removeRegistrationListener(PassRegistrationListener *L) {
sys::SmartScopedWriter<true> Guard(*Lock);
// NOTE: This is necessary, because removeRegistrationListener() can be called
// as part of the llvm_shutdown sequence. Since we have no control over the
// order of that sequence, we need to gracefully handle the case where the
// PassRegistry is destructed before the object that triggers this call.
if (!pImpl) return;
PassRegistryImpl *Impl = static_cast<PassRegistryImpl*>(getImpl());
std::vector<PassRegistrationListener*>::iterator I =
std::find(Impl->Listeners.begin(), Impl->Listeners.end(), L);
assert(I != Impl->Listeners.end() &&
"PassRegistrationListener not registered!");
Impl->Listeners.erase(I);
}
<commit_msg>Don't acquire the mutex during the destructor of PassRegistry.<commit_after>//===- PassRegistry.cpp - Pass Registration Implementation ----------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file implements the PassRegistry, with which passes are registered on
// initialization, and supports the PassManager in dependency resolution.
//
//===----------------------------------------------------------------------===//
#include "llvm/PassRegistry.h"
#include "llvm/ADT/DenseMap.h"
#include "llvm/ADT/SmallPtrSet.h"
#include "llvm/ADT/StringMap.h"
#include "llvm/IR/Function.h"
#include "llvm/PassSupport.h"
#include "llvm/Support/Compiler.h"
#include "llvm/Support/ManagedStatic.h"
#include "llvm/Support/Mutex.h"
#include "llvm/Support/RWMutex.h"
#include <vector>
using namespace llvm;
// FIXME: We use ManagedStatic to erase the pass registrar on shutdown.
// Unfortunately, passes are registered with static ctors, and having
// llvm_shutdown clear this map prevents successful resurrection after
// llvm_shutdown is run. Ideally we should find a solution so that we don't
// leak the map, AND can still resurrect after shutdown.
static ManagedStatic<PassRegistry> PassRegistryObj;
PassRegistry *PassRegistry::getPassRegistry() {
return &*PassRegistryObj;
}
static ManagedStatic<sys::SmartRWMutex<true> > Lock;
//===----------------------------------------------------------------------===//
// PassRegistryImpl
//
namespace {
struct PassRegistryImpl {
/// PassInfoMap - Keep track of the PassInfo object for each registered pass.
typedef DenseMap<const void*, const PassInfo*> MapType;
MapType PassInfoMap;
typedef StringMap<const PassInfo*> StringMapType;
StringMapType PassInfoStringMap;
/// AnalysisGroupInfo - Keep track of information for each analysis group.
struct AnalysisGroupInfo {
SmallPtrSet<const PassInfo *, 8> Implementations;
};
DenseMap<const PassInfo*, AnalysisGroupInfo> AnalysisGroupInfoMap;
std::vector<std::unique_ptr<const PassInfo>> ToFree;
std::vector<PassRegistrationListener*> Listeners;
};
} // end anonymous namespace
void *PassRegistry::getImpl() const {
if (!pImpl)
pImpl = new PassRegistryImpl();
return pImpl;
}
//===----------------------------------------------------------------------===//
// Accessors
//
PassRegistry::~PassRegistry() {
// Don't acquire the mutex here. This is destroyed during static execution of
// static destructors, after llvm_shutdown() has been called, so all instances
// of all ManagedStatics (including the Mutex), will have been destroyed as
// well.
PassRegistryImpl *Impl = static_cast<PassRegistryImpl*>(pImpl);
delete Impl;
pImpl = nullptr;
}
const PassInfo *PassRegistry::getPassInfo(const void *TI) const {
sys::SmartScopedReader<true> Guard(*Lock);
PassRegistryImpl *Impl = static_cast<PassRegistryImpl*>(getImpl());
PassRegistryImpl::MapType::const_iterator I = Impl->PassInfoMap.find(TI);
return I != Impl->PassInfoMap.end() ? I->second : nullptr;
}
const PassInfo *PassRegistry::getPassInfo(StringRef Arg) const {
sys::SmartScopedReader<true> Guard(*Lock);
PassRegistryImpl *Impl = static_cast<PassRegistryImpl*>(getImpl());
PassRegistryImpl::StringMapType::const_iterator
I = Impl->PassInfoStringMap.find(Arg);
return I != Impl->PassInfoStringMap.end() ? I->second : nullptr;
}
//===----------------------------------------------------------------------===//
// Pass Registration mechanism
//
void PassRegistry::registerPass(const PassInfo &PI, bool ShouldFree) {
sys::SmartScopedWriter<true> Guard(*Lock);
PassRegistryImpl *Impl = static_cast<PassRegistryImpl*>(getImpl());
bool Inserted =
Impl->PassInfoMap.insert(std::make_pair(PI.getTypeInfo(),&PI)).second;
assert(Inserted && "Pass registered multiple times!");
(void)Inserted;
Impl->PassInfoStringMap[PI.getPassArgument()] = &PI;
// Notify any listeners.
for (std::vector<PassRegistrationListener*>::iterator
I = Impl->Listeners.begin(), E = Impl->Listeners.end(); I != E; ++I)
(*I)->passRegistered(&PI);
if (ShouldFree) Impl->ToFree.push_back(std::unique_ptr<const PassInfo>(&PI));
}
void PassRegistry::unregisterPass(const PassInfo &PI) {
sys::SmartScopedWriter<true> Guard(*Lock);
PassRegistryImpl *Impl = static_cast<PassRegistryImpl*>(getImpl());
PassRegistryImpl::MapType::iterator I =
Impl->PassInfoMap.find(PI.getTypeInfo());
assert(I != Impl->PassInfoMap.end() && "Pass registered but not in map!");
// Remove pass from the map.
Impl->PassInfoMap.erase(I);
Impl->PassInfoStringMap.erase(PI.getPassArgument());
}
void PassRegistry::enumerateWith(PassRegistrationListener *L) {
sys::SmartScopedReader<true> Guard(*Lock);
PassRegistryImpl *Impl = static_cast<PassRegistryImpl*>(getImpl());
for (PassRegistryImpl::MapType::const_iterator I = Impl->PassInfoMap.begin(),
E = Impl->PassInfoMap.end(); I != E; ++I)
L->passEnumerate(I->second);
}
/// Analysis Group Mechanisms.
void PassRegistry::registerAnalysisGroup(const void *InterfaceID,
const void *PassID,
PassInfo& Registeree,
bool isDefault,
bool ShouldFree) {
PassInfo *InterfaceInfo = const_cast<PassInfo*>(getPassInfo(InterfaceID));
if (!InterfaceInfo) {
// First reference to Interface, register it now.
registerPass(Registeree);
InterfaceInfo = &Registeree;
}
assert(Registeree.isAnalysisGroup() &&
"Trying to join an analysis group that is a normal pass!");
if (PassID) {
PassInfo *ImplementationInfo = const_cast<PassInfo*>(getPassInfo(PassID));
assert(ImplementationInfo &&
"Must register pass before adding to AnalysisGroup!");
sys::SmartScopedWriter<true> Guard(*Lock);
// Make sure we keep track of the fact that the implementation implements
// the interface.
ImplementationInfo->addInterfaceImplemented(InterfaceInfo);
PassRegistryImpl *Impl = static_cast<PassRegistryImpl*>(getImpl());
PassRegistryImpl::AnalysisGroupInfo &AGI =
Impl->AnalysisGroupInfoMap[InterfaceInfo];
assert(AGI.Implementations.count(ImplementationInfo) == 0 &&
"Cannot add a pass to the same analysis group more than once!");
AGI.Implementations.insert(ImplementationInfo);
if (isDefault) {
assert(InterfaceInfo->getNormalCtor() == nullptr &&
"Default implementation for analysis group already specified!");
assert(ImplementationInfo->getNormalCtor() &&
"Cannot specify pass as default if it does not have a default ctor");
InterfaceInfo->setNormalCtor(ImplementationInfo->getNormalCtor());
InterfaceInfo->setTargetMachineCtor(
ImplementationInfo->getTargetMachineCtor());
}
}
PassRegistryImpl *Impl = static_cast<PassRegistryImpl*>(getImpl());
if (ShouldFree)
Impl->ToFree.push_back(std::unique_ptr<const PassInfo>(&Registeree));
}
void PassRegistry::addRegistrationListener(PassRegistrationListener *L) {
sys::SmartScopedWriter<true> Guard(*Lock);
PassRegistryImpl *Impl = static_cast<PassRegistryImpl*>(getImpl());
Impl->Listeners.push_back(L);
}
void PassRegistry::removeRegistrationListener(PassRegistrationListener *L) {
sys::SmartScopedWriter<true> Guard(*Lock);
// NOTE: This is necessary, because removeRegistrationListener() can be called
// as part of the llvm_shutdown sequence. Since we have no control over the
// order of that sequence, we need to gracefully handle the case where the
// PassRegistry is destructed before the object that triggers this call.
if (!pImpl) return;
PassRegistryImpl *Impl = static_cast<PassRegistryImpl*>(getImpl());
std::vector<PassRegistrationListener*>::iterator I =
std::find(Impl->Listeners.begin(), Impl->Listeners.end(), L);
assert(I != Impl->Listeners.end() &&
"PassRegistrationListener not registered!");
Impl->Listeners.erase(I);
}
<|endoftext|> |
<commit_before><commit_msg>Force position type size_t instead of long<commit_after><|endoftext|> |
<commit_before>// MMOVE.C -- implementation of MMOVE class
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>
#include <ugens.h>
#include <mixerr.h>
#include <rt.h>
#include <rtdefs.h>
#include <assert.h>
#include <common.h>
#include "MMOVE.h"
//#define debug
#ifdef SIG_DEBUG
#define DBG(stmt) { stmt; }
#else
#define DBG(stmt)
#endif
extern "C" int get_path_params(double *rhos, double *thetas, int *cartesian, double *mdiff);
// Defined in ../MOVE/common.C
extern double SINARRAY[1025], COSARRAY[1025], ATANARRAY[1025];
static const double radpt = 162.99746617261; /* converts rads to 1024-element array ptr */
static const double radpt2 = 325.9493234522;
inline double SIN(double x) { return SINARRAY[(int)(wrap(x) * radpt + 0.5)]; }
inline double COS(double x) { return COSARRAY[(int)(wrap(x) * radpt + 0.5)]; }
inline double ATAN(double x) { return ATANARRAY[(int)((x) * radpt2) + 512]; }
static const double LocationUnset = -999999.999999;
/* ------------------------------------------------------------ makeMOVE --- */
Instrument *makeMMOVE()
{
MMOVE *inst;
inst = new MMOVE(); // The class is called MOVE, but the inst is MMOVE
inst->set_bus_config("MMOVE");
return inst;
}
#ifndef EMBEDDED
extern Instrument *makeRVB(); // From RVB.C
/* ------------------------------------------------------------ rtprofile --- */
void rtprofile()
{
RT_INTRO("MMOVE", makeMMOVE);
RT_INTRO("RVB", makeRVB);
}
#endif
// Move methods
MMOVE::MMOVE()
{
R_old = -100000.0;
T_old = 0.0;
m_updateCount = 0;
m_updateSamps = RTBUFSAMPS;
setup_trigfuns();
rholoc = new double[ARRAYSIZE];
thetaloc = new double[ARRAYSIZE];
for (int n = 0; n < 2; n++)
for (int o = 0; o < 13; o++)
oldOutlocs[n][o] = LocationUnset; // to force update
}
MMOVE::~MMOVE()
{
delete [] thetaloc;
delete [] rholoc;
}
#define MINBUFFERSIZE 64
int MMOVE::localInit(double *p, int n_args)
{
if (n_args < 6)
return die(name(), "Wrong number of args.");
m_dist = p[4];
m_inchan = n_args > 5 ? (int)p[5] : AVERAGE_CHANS;
// copy global params into instrument
if (get_path_params(&rholoc[0], &thetaloc[0], &m_cartflag, &mindiff) < 0)
return die(name(), "get_path_params failed.");
// treat mindiff as update rate in seconds
if (mindiff > 0.0) {
m_updateSamps = (int) (SR * mindiff + 0.5);
if (m_updateSamps <= RTBUFSAMPS) {
if (m_updateSamps < MINBUFFERSIZE)
m_updateSamps = MINBUFFERSIZE;
setBufferSize(m_updateSamps);
#ifdef debug
printf("buffer size reset to %d samples\n", getBufferSize());
#endif
}
// if update rate is larger than RTBUFSAMPS samples, set buffer size
// to be some integer fraction of the desired update count, then
// reset update count to be multiple of this.
else {
int divisor = 2;
int newBufferLen;
while ((newBufferLen = m_updateSamps / divisor) > RTBUFSAMPS)
divisor++;
setBufferSize(newBufferLen);
m_updateSamps = newBufferLen * divisor;
#ifdef debug
printf("buffer size reset to %d samples\n", getBufferSize());
#endif
}
#ifdef debug
printf("updating every %d samps\n", m_updateSamps);
#endif
}
// tables for positional lookup
tableset(SR, m_dur, ARRAYSIZE, tabr);
tableset(SR, m_dur, ARRAYSIZE, tabt);
return 0;
}
int MMOVE::finishInit(double *ringdur)
{
*ringdur = (float)m_tapsize / SR; // max possible room delay
tapcount = updatePosition(0);
return 0;
}
void MMOVE::get_tap(int currentSamp, int chan, int path, int len)
{
Vector *vec = &m_vectors[chan][path];
const double outloc = (double) vec->outloc;
const double oldOutloc = oldOutlocs[chan][path];
const double delta = (oldOutloc == LocationUnset) ? 0.0 : outloc - oldOutloc;
oldOutlocs[chan][path] = outloc;
const double incr = 1.0 + delta / len;
const int tap = currentSamp % m_tapsize;
register double *tapdel = m_tapDelay;
register double *Sig = vec->Sig;
register double outTap = (double) tap - outloc;
if (outTap < 0.0)
outTap += m_tapsize;
int out = 0;
while (out < len)
{
if (outTap >= (double) m_tapsize)
outTap -= m_tapsize;
int iouttap = (int) outTap;
int outTapPlusOne = int(outTap + 1.0);
if (outTapPlusOne >= m_tapsize)
outTapPlusOne -= m_tapsize;
double frac = outTap - (double)iouttap;
Sig[out++] = tapdel[iouttap] + frac * (tapdel[outTapPlusOne] - tapdel[iouttap]);
outTap += incr;
}
}
// This gets called every internal buffer's worth of samples. The actual
// update of source angles and delays only happens if we are due for an update
// (based on the update count) and there has been a change of position
int MMOVE::updatePosition(int currentSamp)
{
double R = tablei(currentSamp, rholoc, tabr);
double T = tablei(currentSamp, thetaloc, tabt);
int maxtap = tapcount;
m_updateCount -= getBufferSize();
if (m_updateCount <= 0 && (R != R_old || T != T_old)) {
#ifdef debug
printf("updatePosition[%d]:\t\tR: %f T: %f\n", currentSamp, R, T);
#endif
if (roomtrig(R , T, m_dist, m_cartflag)) {
return (-1);
}
// set taps, return max samp
maxtap = tap_set(m_binaural);
int resetFlag = (currentSamp == 0);
airfil_set(resetFlag);
if (m_binaural)
earfil_set(resetFlag);
else
mike_set();
R_old = R;
T_old = T;
m_updateCount = m_updateSamps; // reset counter
}
return maxtap; // return new maximum delay in samples
}
<commit_msg>Optimized MMOVE inner loops.<commit_after>// MMOVE.C -- implementation of MMOVE class
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>
#include <ugens.h>
#include <mixerr.h>
#include <rt.h>
#include <rtdefs.h>
#include <assert.h>
#include <common.h>
#include "MMOVE.h"
//#define debug
#ifdef SIG_DEBUG
#define DBG(stmt) { stmt; }
#else
#define DBG(stmt)
#endif
extern "C" int get_path_params(double *rhos, double *thetas, int *cartesian, double *mdiff);
// Defined in ../MOVE/common.C
extern double SINARRAY[1025], COSARRAY[1025], ATANARRAY[1025];
static const double radpt = 162.99746617261; /* converts rads to 1024-element array ptr */
static const double radpt2 = 325.9493234522;
inline double SIN(double x) { return SINARRAY[(int)(wrap(x) * radpt + 0.5)]; }
inline double COS(double x) { return COSARRAY[(int)(wrap(x) * radpt + 0.5)]; }
inline double ATAN(double x) { return ATANARRAY[(int)((x) * radpt2) + 512]; }
static const double LocationUnset = -999999.999999;
/* ------------------------------------------------------------ makeMOVE --- */
Instrument *makeMMOVE()
{
MMOVE *inst;
inst = new MMOVE(); // The class is called MOVE, but the inst is MMOVE
inst->set_bus_config("MMOVE");
return inst;
}
#ifndef EMBEDDED
extern Instrument *makeRVB(); // From RVB.C
/* ------------------------------------------------------------ rtprofile --- */
void rtprofile()
{
RT_INTRO("MMOVE", makeMMOVE);
RT_INTRO("RVB", makeRVB);
}
#endif
// Move methods
MMOVE::MMOVE()
{
R_old = -100000.0;
T_old = 0.0;
m_updateCount = 0;
m_updateSamps = RTBUFSAMPS;
setup_trigfuns();
rholoc = new double[ARRAYSIZE];
thetaloc = new double[ARRAYSIZE];
for (int n = 0; n < 2; n++)
for (int o = 0; o < 13; o++)
oldOutlocs[n][o] = LocationUnset; // to force update
}
MMOVE::~MMOVE()
{
delete [] thetaloc;
delete [] rholoc;
}
#define MINBUFFERSIZE 64
int MMOVE::localInit(double *p, int n_args)
{
if (n_args < 6)
return die(name(), "Wrong number of args.");
m_dist = p[4];
m_inchan = n_args > 5 ? (int)p[5] : AVERAGE_CHANS;
// copy global params into instrument
if (get_path_params(&rholoc[0], &thetaloc[0], &m_cartflag, &mindiff) < 0)
return die(name(), "get_path_params failed.");
// treat mindiff as update rate in seconds
if (mindiff > 0.0) {
m_updateSamps = (int) (SR * mindiff + 0.5);
if (m_updateSamps <= RTBUFSAMPS) {
if (m_updateSamps < MINBUFFERSIZE)
m_updateSamps = MINBUFFERSIZE;
setBufferSize(m_updateSamps);
#ifdef debug
printf("buffer size reset to %d samples\n", getBufferSize());
#endif
}
// if update rate is larger than RTBUFSAMPS samples, set buffer size
// to be some integer fraction of the desired update count, then
// reset update count to be multiple of this.
else {
int divisor = 2;
int newBufferLen;
while ((newBufferLen = m_updateSamps / divisor) > RTBUFSAMPS)
divisor++;
setBufferSize(newBufferLen);
m_updateSamps = newBufferLen * divisor;
#ifdef debug
printf("buffer size reset to %d samples\n", getBufferSize());
#endif
}
#ifdef debug
printf("updating every %d samps\n", m_updateSamps);
#endif
}
// tables for positional lookup
tableset(SR, m_dur, ARRAYSIZE, tabr);
tableset(SR, m_dur, ARRAYSIZE, tabt);
return 0;
}
int MMOVE::finishInit(double *ringdur)
{
*ringdur = (float)m_tapsize / SR; // max possible room delay
tapcount = updatePosition(0);
return 0;
}
void MMOVE::get_tap(int currentSamp, int chan, int path, int len)
{
Vector *vec = &m_vectors[chan][path];
const double outloc = (double) vec->outloc;
const double oldOutloc = oldOutlocs[chan][path];
const double delta = (oldOutloc == LocationUnset) ? 0.0 : outloc - oldOutloc;
oldOutlocs[chan][path] = outloc;
const double incr = 1.0 + delta / len;
const int tap = currentSamp % m_tapsize;
register double *tapdel = m_tapDelay;
register double *Sig = vec->Sig;
register double outTap = (double) tap - outloc;
if (outTap < 0.0)
outTap += m_tapsize;
int out = 0;
int len1 = (m_tapsize - (outTap + 1.0)) / incr; // boundary point before needing to wrap
int count = 0;
int sampsNeeded = len;
while (sampsNeeded > 0 && count++ < len1) {
const int iOuttap = (int) outTap;
const double frac = outTap - (double)iOuttap;
Sig[out++] = tapdel[iOuttap] + frac * (tapdel[iOuttap+1] - tapdel[iOuttap]);
outTap += incr;
--sampsNeeded;
}
while (sampsNeeded > 0 && outTap < (double) m_tapsize) {
const int iOuttap = (int) outTap;
const double frac = outTap - (double)iOuttap;
int outTapPlusOne = int(outTap + 1.0);
if (outTapPlusOne >= m_tapsize)
outTapPlusOne -= m_tapsize;
Sig[out++] = tapdel[iOuttap] + frac * (tapdel[outTapPlusOne] - tapdel[iOuttap]);
outTap += incr;
--sampsNeeded;
}
outTap -= m_tapsize;
while (sampsNeeded > 0) {
const int iOuttap = (int) outTap;
const double frac = outTap - (double)iOuttap;
Sig[out++] = tapdel[iOuttap] + frac * (tapdel[iOuttap+1] - tapdel[iOuttap]);
outTap += incr;
--sampsNeeded;
}
}
// This gets called every internal buffer's worth of samples. The actual
// update of source angles and delays only happens if we are due for an update
// (based on the update count) and there has been a change of position
int MMOVE::updatePosition(int currentSamp)
{
double R = tablei(currentSamp, rholoc, tabr);
double T = tablei(currentSamp, thetaloc, tabt);
int maxtap = tapcount;
m_updateCount -= getBufferSize();
if (m_updateCount <= 0 && (R != R_old || T != T_old)) {
#ifdef debug
printf("updatePosition[%d]:\t\tR: %f T: %f\n", currentSamp, R, T);
#endif
if (roomtrig(R , T, m_dist, m_cartflag)) {
return (-1);
}
// set taps, return max samp
maxtap = tap_set(m_binaural);
int resetFlag = (currentSamp == 0);
airfil_set(resetFlag);
if (m_binaural)
earfil_set(resetFlag);
else
mike_set();
R_old = R;
T_old = T;
m_updateCount = m_updateSamps; // reset counter
}
return maxtap; // return new maximum delay in samples
}
<|endoftext|> |
<commit_before>/*
* kinetic-cpp-client
* Copyright (C) 2014 Seagate Technology.
*
* 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 <memory>
#include "gtest/gtest.h"
#include "integration_test.h"
namespace kinetic {
using std::shared_ptr;
using std::make_shared;
using std::vector;
using com::seagate::kinetic::client::proto::Message_Algorithm_CRC32;
using com::seagate::kinetic::client::proto::Message_Algorithm_SHA1;
TEST_F(IntegrationTest, BlockingSmoketest) {
ASSERT_TRUE(blocking_connection_->NoOp().ok());
auto record1 = make_shared<KineticRecord>(make_shared<string>("value1"),
make_shared<string>("v1"), make_shared<string>("t1"), Message_Algorithm_CRC32);
KineticStatus kineticStatus = blocking_connection_->Put("key1", "",WriteMode::IGNORE_VERSION, *record1);
ASSERT_TRUE(kineticStatus.ok());
auto record2 = make_shared<KineticRecord>(make_shared<string>("value2"),
make_shared<string>("v2"), make_shared<string>("t2"), Message_Algorithm_SHA1);
ASSERT_TRUE(blocking_connection_->Put(make_shared<string>("key2"), make_shared<string>(""),
WriteMode::IGNORE_VERSION, record2).ok());
auto record3 = make_shared<KineticRecord>(make_shared<string>("value3"),
make_shared<string>("v3"), make_shared<string>("t3"), Message_Algorithm_CRC32);
ASSERT_TRUE(blocking_connection_->Put(make_shared<string>("key3"), make_shared<string>(""),
WriteMode::IGNORE_VERSION, record3).ok());
KeyRangeIterator it = blocking_connection_->IterateKeyRange("key1", true, "key3", false, 1);
ASSERT_EQ("key1", *it);
++it;
ASSERT_EQ("key2", *it);
++it;
ASSERT_EQ(KeyRangeEnd(), it);
std::unique_ptr<KineticRecord> result_record;
ASSERT_TRUE(blocking_connection_->Get("key2", result_record).ok());
EXPECT_EQ("value2", *(result_record->value()));
EXPECT_EQ("v2", *(result_record->version()));
EXPECT_EQ("t2", *(result_record->tag()));
EXPECT_EQ(Message_Algorithm_SHA1, result_record->algorithm());
unique_ptr<string> result_key(nullptr);
ASSERT_TRUE(blocking_connection_->GetNext("key1", result_key, result_record).ok());
EXPECT_EQ("key2", *result_key);
EXPECT_EQ("value2", *(result_record->value()));
EXPECT_EQ("v2", *(result_record->version()));
EXPECT_EQ("t2", *(result_record->tag()));
EXPECT_EQ(Message_Algorithm_SHA1, result_record->algorithm());
ASSERT_TRUE(blocking_connection_->GetPrevious("key3", result_key, result_record).ok());
EXPECT_EQ("key2", *result_key);
EXPECT_EQ("value2", *(result_record->value()));
EXPECT_EQ("v2", *(result_record->version()));
EXPECT_EQ("t2", *(result_record->tag()));
EXPECT_EQ(Message_Algorithm_SHA1, result_record->algorithm());
unique_ptr<string> result_version(nullptr);
ASSERT_TRUE(blocking_connection_->GetVersion("key3", result_version).ok());
EXPECT_EQ("v3", *result_version);
unique_ptr<vector<string>> actual_keys(new vector<string>);
vector<string> expected_keys = {"key2", "key3"};
KineticStatus status =
blocking_connection_->GetKeyRange("key1", false, "key3", true, false, 2, actual_keys);
ASSERT_TRUE(status.ok());
EXPECT_EQ(expected_keys, *actual_keys);
ASSERT_TRUE(blocking_connection_->Delete("key1", "",WriteMode::IGNORE_VERSION).ok());
ASSERT_EQ(blocking_connection_->Get("key1", result_record).statusCode(), StatusCode::REMOTE_NOT_FOUND);
ASSERT_TRUE(blocking_connection_->InstantSecureErase("").ok());
ASSERT_EQ(blocking_connection_->Get("key3", result_record).statusCode(), StatusCode::REMOTE_NOT_FOUND);
blocking_connection_->SetClientClusterVersion(33);
ASSERT_EQ(blocking_connection_->Get("key1", result_record).statusCode(),
StatusCode::REMOTE_CLUSTER_VERSION_MISMATCH);
}
} // namespace kinetic
<commit_msg>Fixed whitespace issue<commit_after>/*
* kinetic-cpp-client
* Copyright (C) 2014 Seagate Technology.
*
* 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 <memory>
#include "gtest/gtest.h"
#include "integration_test.h"
namespace kinetic {
using std::shared_ptr;
using std::make_shared;
using std::vector;
using com::seagate::kinetic::client::proto::Message_Algorithm_CRC32;
using com::seagate::kinetic::client::proto::Message_Algorithm_SHA1;
TEST_F(IntegrationTest, BlockingSmoketest) {
ASSERT_TRUE(blocking_connection_->NoOp().ok());
auto record1 = make_shared<KineticRecord>(make_shared<string>("value1"),
make_shared<string>("v1"), make_shared<string>("t1"), Message_Algorithm_CRC32);
KineticStatus kineticStatus = blocking_connection_->Put("key1", "", WriteMode::IGNORE_VERSION, *record1);
ASSERT_TRUE(kineticStatus.ok());
auto record2 = make_shared<KineticRecord>(make_shared<string>("value2"),
make_shared<string>("v2"), make_shared<string>("t2"), Message_Algorithm_SHA1);
ASSERT_TRUE(blocking_connection_->Put(make_shared<string>("key2"), make_shared<string>(""),
WriteMode::IGNORE_VERSION, record2).ok());
auto record3 = make_shared<KineticRecord>(make_shared<string>("value3"),
make_shared<string>("v3"), make_shared<string>("t3"), Message_Algorithm_CRC32);
ASSERT_TRUE(blocking_connection_->Put(make_shared<string>("key3"), make_shared<string>(""),
WriteMode::IGNORE_VERSION, record3).ok());
KeyRangeIterator it = blocking_connection_->IterateKeyRange("key1", true, "key3", false, 1);
ASSERT_EQ("key1", *it);
++it;
ASSERT_EQ("key2", *it);
++it;
ASSERT_EQ(KeyRangeEnd(), it);
std::unique_ptr<KineticRecord> result_record;
ASSERT_TRUE(blocking_connection_->Get("key2", result_record).ok());
EXPECT_EQ("value2", *(result_record->value()));
EXPECT_EQ("v2", *(result_record->version()));
EXPECT_EQ("t2", *(result_record->tag()));
EXPECT_EQ(Message_Algorithm_SHA1, result_record->algorithm());
unique_ptr<string> result_key(nullptr);
ASSERT_TRUE(blocking_connection_->GetNext("key1", result_key, result_record).ok());
EXPECT_EQ("key2", *result_key);
EXPECT_EQ("value2", *(result_record->value()));
EXPECT_EQ("v2", *(result_record->version()));
EXPECT_EQ("t2", *(result_record->tag()));
EXPECT_EQ(Message_Algorithm_SHA1, result_record->algorithm());
ASSERT_TRUE(blocking_connection_->GetPrevious("key3", result_key, result_record).ok());
EXPECT_EQ("key2", *result_key);
EXPECT_EQ("value2", *(result_record->value()));
EXPECT_EQ("v2", *(result_record->version()));
EXPECT_EQ("t2", *(result_record->tag()));
EXPECT_EQ(Message_Algorithm_SHA1, result_record->algorithm());
unique_ptr<string> result_version(nullptr);
ASSERT_TRUE(blocking_connection_->GetVersion("key3", result_version).ok());
EXPECT_EQ("v3", *result_version);
unique_ptr<vector<string>> actual_keys(new vector<string>);
vector<string> expected_keys = {"key2", "key3"};
KineticStatus status =
blocking_connection_->GetKeyRange("key1", false, "key3", true, false, 2, actual_keys);
ASSERT_TRUE(status.ok());
EXPECT_EQ(expected_keys, *actual_keys);
ASSERT_TRUE(blocking_connection_->Delete("key1", "", WriteMode::IGNORE_VERSION).ok());
ASSERT_EQ(blocking_connection_->Get("key1", result_record).statusCode(), StatusCode::REMOTE_NOT_FOUND);
ASSERT_TRUE(blocking_connection_->InstantSecureErase("").ok());
ASSERT_EQ(blocking_connection_->Get("key3", result_record).statusCode(), StatusCode::REMOTE_NOT_FOUND);
blocking_connection_->SetClientClusterVersion(33);
ASSERT_EQ(blocking_connection_->Get("key1", result_record).statusCode(),
StatusCode::REMOTE_CLUSTER_VERSION_MISMATCH);
}
} // namespace kinetic
<|endoftext|> |
<commit_before>
#include "types.h"
namespace csfm {
class DepthmapEstimator {
public:
void AddView(const double *pK,
const double *pR,
const double *pt,
const unsigned char *pimage,
int width,
int height) {
cv::Matx33d K(pK);
cv::Matx33d R(pR);
cv::Matx31d t(pt);
Ks_.emplace_back(K);
Rs_.emplace_back(R);
ts_.emplace_back(t);
cv::Matx34d Rt;
cv::hconcat(R, t, Rt);
Ps_.emplace_back(K * Rt);
images_.emplace_back(cv::Mat(height, width, CV_8U, (void *)pimage));
}
void Compute() {
cv::Mat best_depth(images_[0].rows, images_[0].cols, CV_32F, 0.0f);
cv::Mat best_score(images_[0].rows, images_[0].cols, CV_32F, -1.0f);
int num_depth_tests = 10;
float min_depth = 1;
float max_depth = 10;
for (int i = 0; i < best_depth.rows; ++i) {
for (int j = 0; j < best_depth.cols; ++j) {
for (int d = 0; d < num_depth_tests; ++d) {
float depth = min_depth + d * (max_depth - min_depth) / (num_depth_tests - 1);
float score = ComputePlaneScore(i, j, depth);
if (score > best_score.at<float>(i, j)) {
best_score.at<float>(i, j) = score;
best_depth.at<float>(i, j) = depth;
}
}
return;
}
}
}
float ComputePlaneScore(int i, int j, float depth) {
float best_score = -1.0f;
for (int other = 1; other < images_.size(); ++other) {
float score = ComputePlaneImageScore(i, j, depth, other);
if (score > best_score) {
best_score = score;
}
}
return best_score;
}
float ComputePlaneImageScore(int i, int j, float depth, int other) {
cv::Matx33d H = PlaneInducedHomography(Ks_[0], Rs_[0], ts_[0],
Ks_[other], Rs_[other], ts_[other],
cv::Matx31d(0, 0, -1 / depth));
return 0;
}
cv::Matx33d PlaneInducedHomography(const cv::Matx33d K1,
const cv::Matx33d R1,
const cv::Matx31d t1,
const cv::Matx33d K2,
const cv::Matx33d R2,
const cv::Matx31d t2,
const cv::Matx31d v) {
cv::Matx33d R2R1 = R2 * R1.t();
return K2 * (R2R1 + (R2R1 * t1 - t2) * v.t()) * K1.inv();
}
private:
std::vector<cv::Mat> images_;
std::vector<cv::Matx33d> Ks_;
std::vector<cv::Matx33d> Rs_;
std::vector<cv::Matx31d> ts_;
std::vector<cv::Matx34d> Ps_;
};
class DepthmapEstimatorWrapper {
public:
void AddView(PyObject *K,
PyObject *R,
PyObject *t,
PyObject *image) {
PyArrayContiguousView<double> K_view((PyArrayObject *)K);
PyArrayContiguousView<double> R_view((PyArrayObject *)R);
PyArrayContiguousView<double> t_view((PyArrayObject *)t);
PyArrayContiguousView<unsigned char> image_view((PyArrayObject *)image);
de_.AddView(K_view.data(), R_view.data(), t_view.data(),
image_view.data(), image_view.shape(1), image_view.shape(0));
}
void Compute() {
de_.Compute();
}
private:
DepthmapEstimator de_;
};
}
<commit_msg>Remove unused projection matrices.<commit_after>
#include "types.h"
namespace csfm {
class DepthmapEstimator {
public:
void AddView(const double *pK,
const double *pR,
const double *pt,
const unsigned char *pimage,
int width,
int height) {
cv::Matx33d K(pK);
cv::Matx33d R(pR);
cv::Matx31d t(pt);
Ks_.emplace_back(K);
Rs_.emplace_back(R);
ts_.emplace_back(t);
images_.emplace_back(cv::Mat(height, width, CV_8U, (void *)pimage));
}
void Compute() {
cv::Mat best_depth(images_[0].rows, images_[0].cols, CV_32F, 0.0f);
cv::Mat best_score(images_[0].rows, images_[0].cols, CV_32F, -1.0f);
int num_depth_tests = 10;
float min_depth = 1;
float max_depth = 10;
for (int i = 0; i < best_depth.rows; ++i) {
std::cout << "i " << i << "\n";
for (int j = 0; j < best_depth.cols; ++j) {
for (int d = 0; d < num_depth_tests; ++d) {
float depth = min_depth + d * (max_depth - min_depth) / (num_depth_tests - 1);
float score = ComputePlaneScore(i, j, depth);
if (score > best_score.at<float>(i, j)) {
best_score.at<float>(i, j) = score;
best_depth.at<float>(i, j) = depth;
}
}
}
}
}
float ComputePlaneScore(int i, int j, float depth) {
float best_score = -1.0f;
for (int other = 1; other < images_.size(); ++other) {
float score = ComputePlaneImageScore(i, j, depth, other);
if (score > best_score) {
best_score = score;
}
}
return best_score;
}
float ComputePlaneImageScore(int i, int j, float depth, int other) {
cv::Matx33d H = PlaneInducedHomography(Ks_[0], Rs_[0], ts_[0],
Ks_[other], Rs_[other], ts_[other],
cv::Matx31d(0, 0, -1 / depth));
return 0;
}
cv::Matx33d PlaneInducedHomography(const cv::Matx33d K1,
const cv::Matx33d R1,
const cv::Matx31d t1,
const cv::Matx33d K2,
const cv::Matx33d R2,
const cv::Matx31d t2,
const cv::Matx31d v) {
cv::Matx33d R2R1 = R2 * R1.t();
return K2 * (R2R1 + (R2R1 * t1 - t2) * v.t()) * K1.inv();
}
private:
std::vector<cv::Mat> images_;
std::vector<cv::Matx33d> Ks_;
std::vector<cv::Matx33d> Rs_;
std::vector<cv::Matx31d> ts_;
};
class DepthmapEstimatorWrapper {
public:
void AddView(PyObject *K,
PyObject *R,
PyObject *t,
PyObject *image) {
PyArrayContiguousView<double> K_view((PyArrayObject *)K);
PyArrayContiguousView<double> R_view((PyArrayObject *)R);
PyArrayContiguousView<double> t_view((PyArrayObject *)t);
PyArrayContiguousView<unsigned char> image_view((PyArrayObject *)image);
de_.AddView(K_view.data(), R_view.data(), t_view.data(),
image_view.data(), image_view.shape(1), image_view.shape(0));
}
void Compute() {
de_.Compute();
}
private:
DepthmapEstimator de_;
};
}
<|endoftext|> |
<commit_before>/** @file
@brief Implementation
@date 2016
@author
Sensics, Inc.
<http://sensics.com/osvr>
*/
// Copyright 2016 Sensics, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// Internal Includes
#include "DriverLoader.h"
#include "FindDriver.h"
#include "GetProvider.h"
#include "ViveServerDriverHost.h"
// Library/third-party includes
#include <openvr_driver.h>
#include <osvr/Util/PlatformConfig.h>
// Standard includes
#include <chrono>
#include <fstream>
#include <iostream>
#include <thread>
namespace osvr {
namespace vive {} // namespace vive
} // namespace osvr
int main() {
auto driverLocation = osvr::vive::findDriver();
if (driverLocation.found) {
std::cout << "Found the Vive driver at " << driverLocation.driverFile
<< std::endl;
} else {
std::cout << "Could not find the native SteamVR Vive driver, exiting!"
<< std::endl;
return 1;
}
auto vive = osvr::vive::DriverLoader::make(driverLocation.driverRoot,
driverLocation.driverFile);
if (!*vive) {
std::cout << "Could not open driver." << std::endl;
return 1;
}
auto configDirs = osvr::vive::findConfigDirs(driverLocation);
#if 0
{
std::ofstream os("test.txt");
os << configDirs.rootConfigDir << "---\n\n\n---" << configDirs.driverConfigDir << std::flush;
os.close();
}
return 0;
#endif
std::cout << "*** Config dir is:\n"
<< configDirs.driverConfigDir << std::endl;
if (vive->isHMDPresent(configDirs.rootConfigDir)) {
std::cout << "*** Vive is connected." << std::endl;
std::unique_ptr<vr::ViveServerDriverHost> serverDriverHost(
new vr::ViveServerDriverHost);
auto serverDeviceProvider =
osvr::vive::getProvider<vr::IServerTrackedDeviceProvider>(
std::move(vive), nullptr, serverDriverHost.get(),
configDirs.driverConfigDir);
/// Power the system up.
serverDeviceProvider->LeaveStandby();
auto numDevices = serverDeviceProvider->GetTrackedDeviceCount();
std::cout << "*** Got " << numDevices << " tracked devices"
<< std::endl;
std::cout << "*** Entering dummy mainloop" << std::endl;
for (int i = 0; i < 3000; ++i) {
serverDeviceProvider->RunFrame();
std::this_thread::sleep_for(std::chrono::milliseconds(1));
}
std::cout << "*** Done with dummy mainloop" << std::endl;
/// Warn of shutdown moments before it will occur (at end of scope)
serverDriverHost->setExiting();
}
return 0;
}
<commit_msg>Iterate through the devices<commit_after>/** @file
@brief Implementation
@date 2016
@author
Sensics, Inc.
<http://sensics.com/osvr>
*/
// Copyright 2016 Sensics, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// Internal Includes
#include "DriverLoader.h"
#include "FindDriver.h"
#include "GetProvider.h"
#include "ViveServerDriverHost.h"
// Library/third-party includes
#include <openvr_driver.h>
#include <osvr/Util/PlatformConfig.h>
// Standard includes
#include <chrono>
#include <fstream>
#include <iostream>
#include <thread>
namespace osvr {
namespace vive {} // namespace vive
} // namespace osvr
int main() {
auto driverLocation = osvr::vive::findDriver();
if (driverLocation.found) {
std::cout << "Found the Vive driver at " << driverLocation.driverFile
<< std::endl;
} else {
std::cout << "Could not find the native SteamVR Vive driver, exiting!"
<< std::endl;
return 1;
}
auto vive = osvr::vive::DriverLoader::make(driverLocation.driverRoot,
driverLocation.driverFile);
if (!*vive) {
std::cout << "Could not open driver." << std::endl;
return 1;
}
auto configDirs = osvr::vive::findConfigDirs(driverLocation);
#if 0
{
std::ofstream os("test.txt");
os << configDirs.rootConfigDir << "---\n\n\n---" << configDirs.driverConfigDir << std::flush;
os.close();
}
return 0;
#endif
std::cout << "*** Config dir is:\n"
<< configDirs.driverConfigDir << std::endl;
if (vive->isHMDPresent(configDirs.rootConfigDir)) {
std::cout << "*** Vive is connected." << std::endl;
std::unique_ptr<vr::ViveServerDriverHost> serverDriverHost(
new vr::ViveServerDriverHost);
auto serverDeviceProvider =
osvr::vive::getProvider<vr::IServerTrackedDeviceProvider>(
std::move(vive), nullptr, serverDriverHost.get(),
configDirs.driverConfigDir);
/// Power the system up.
serverDeviceProvider->LeaveStandby();
auto numDevices = serverDeviceProvider->GetTrackedDeviceCount();
std::cout << "*** Got " << numDevices << " tracked devices"
<< std::endl;
for (int i = 0; i < numDevices; ++i) {
auto dev = serverDeviceProvider->GetTrackedDeviceDriver(
i, vr::ITrackedDeviceServerDriver_Version);
std::cout << "Device " << i << std::endl;
auto disp = osvr::vive::getComponent<vr::IVRDisplayComponent>(dev);
if (disp) {
std::cout << "-- and it's a display, too!" << std::endl;
}
}
std::cout << "*** Entering dummy mainloop" << std::endl;
for (int i = 0; i < 3000; ++i) {
serverDeviceProvider->RunFrame();
std::this_thread::sleep_for(std::chrono::milliseconds(1));
}
std::cout << "*** Done with dummy mainloop" << std::endl;
/// Warn of shutdown moments before it will occur (at end of scope)
serverDriverHost->setExiting();
}
return 0;
}
<|endoftext|> |
<commit_before>/*************************************************************************
*
* $RCSfile: unomtabl.cxx,v $
*
* $Revision: 1.4 $
*
* last change: $Author: cl $ $Date: 2000-11-12 15:51:48 $
*
* The Contents of this file are made available subject to the terms of
* either of the following licenses
*
* - GNU Lesser General Public License Version 2.1
* - Sun Industry Standards Source License Version 1.1
*
* Sun Microsystems Inc., October, 2000
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2000 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
*
* Sun Industry Standards Source License Version 1.1
* =================================================
* The contents of this file are subject to the Sun Industry Standards
* Source License Version 1.1 (the "License"); You may not use this file
* except in compliance with the License. You may obtain a copy of the
* License at http://www.openoffice.org/license.html.
*
* Software provided under this License is provided on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
* WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
* MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
* See the License for the specific provisions governing your rights and
* obligations concerning the Software.
*
* The Initial Developer of the Original Code is: Sun Microsystems, Inc.
*
* Copyright: 2000 by Sun Microsystems, Inc.
*
* All Rights Reserved.
*
* Contributor(s): _______________________________________
*
*
************************************************************************/
#ifndef _COM_SUN_STAR_LANG_XSERVICEINFO_HPP_
#include <com/sun/star/lang/XServiceInfo.hpp>
#endif
#ifndef _COM_SUN_STAR_CONTAINER_XNAMECONTAINER_HPP_
#include <com/sun/star/container/XNameContainer.hpp>
#endif
#ifndef _COM_SUN_STAR_DRAWING_POINTSEQUENCE_HPP_
#include <com/sun/star/drawing/PointSequence.hpp>
#endif
#include <cppuhelper/implbase2.hxx>
#ifndef _SFXITEMPOOL_HXX
#include <svtools/itempool.hxx>
#endif
#ifndef _SFXITEMSET_HXX //autogen
#include <svtools/itemset.hxx>
#endif
#ifndef _SVX_XLNEDIT_HXX //autogen
#include <xlnedit.hxx>
#endif
#ifndef _SVX_XLNSTIT_HXX
#include <xlnstit.hxx>
#endif
#include "svdmodel.hxx"
#include "xdef.hxx"
#include "xflhtit.hxx"
#ifndef _LIST_HXX
#include<tools/list.hxx>
#endif
using namespace ::com::sun::star;
using namespace ::rtl;
using namespace ::cppu;
DECLARE_LIST( ItemSetArray_Impl, SfxItemSet* )
class SvxUnoMarkerTable : public WeakImplHelper2< container::XNameContainer, lang::XServiceInfo >
{
private:
SdrModel* mpModel;
SfxItemPool* mpPool;
ItemSetArray_Impl aItemSetArray;
void CreateName( OUString& rStrName );
public:
SvxUnoMarkerTable( SdrModel* pModel ) throw();
virtual ~SvxUnoMarkerTable() throw();
// XServiceInfo
virtual OUString SAL_CALL getImplementationName( ) throw( uno::RuntimeException );
virtual sal_Bool SAL_CALL supportsService( const OUString& ServiceName ) throw( uno::RuntimeException);
virtual uno::Sequence< OUString > SAL_CALL getSupportedServiceNames( ) throw( uno::RuntimeException);
static OUString getImplementationName_Static() throw()
{
return OUString(RTL_CONSTASCII_USTRINGPARAM("com.sun.star.drawing.SvxUnoMarkerTable"));
}
static uno::Sequence< OUString > getSupportedServiceNames_Static(void) throw();
// XNameContainer
virtual void SAL_CALL insertByName( const OUString& aName, const uno::Any& aElement ) throw( lang::IllegalArgumentException, container::ElementExistException, lang::WrappedTargetException, uno::RuntimeException);
virtual void SAL_CALL removeByName( const OUString& Name ) throw( container::NoSuchElementException, lang::WrappedTargetException, uno::RuntimeException);
// XNameReplace
virtual void SAL_CALL replaceByName( const OUString& aName, const uno::Any& aElement ) throw( lang::IllegalArgumentException, container::NoSuchElementException, lang::WrappedTargetException, uno::RuntimeException);
// XNameAccess
virtual uno::Any SAL_CALL getByName( const OUString& aName ) throw( container::NoSuchElementException, lang::WrappedTargetException, uno::RuntimeException);
virtual uno::Sequence< OUString > SAL_CALL getElementNames( ) throw( uno::RuntimeException);
virtual sal_Bool SAL_CALL hasByName( const OUString& aName ) throw( uno::RuntimeException);
// XElementAccess
virtual uno::Type SAL_CALL getElementType( ) throw( uno::RuntimeException);
virtual sal_Bool SAL_CALL hasElements( ) throw( uno::RuntimeException);
};
SvxUnoMarkerTable::SvxUnoMarkerTable( SdrModel* pModel ) throw()
: mpModel( pModel ),
mpPool( pModel ? &pModel->GetItemPool() : (SfxItemPool*)NULL )
{
}
SvxUnoMarkerTable::~SvxUnoMarkerTable() throw()
{
for( int i = 0; i<aItemSetArray.Count(); i++ )
delete (SfxItemSet*)aItemSetArray.GetObject( i );
}
sal_Bool SAL_CALL SvxUnoMarkerTable::supportsService( const OUString& ServiceName ) throw(uno::RuntimeException)
{
uno::Sequence< OUString > aSNL( getSupportedServiceNames() );
const OUString * pArray = aSNL.getConstArray();
for( INT32 i = 0; i < aSNL.getLength(); i++ )
if( pArray[i] == ServiceName )
return TRUE;
return FALSE;
}
OUString SAL_CALL SvxUnoMarkerTable::getImplementationName() throw( uno::RuntimeException )
{
return OUString( RTL_CONSTASCII_USTRINGPARAM("SvxUnoMarkerTable") );
}
uno::Sequence< OUString > SAL_CALL SvxUnoMarkerTable::getSupportedServiceNames( )
throw( uno::RuntimeException )
{
return getSupportedServiceNames_Static();
}
uno::Sequence< OUString > SvxUnoMarkerTable::getSupportedServiceNames_Static(void) throw()
{
uno::Sequence< OUString > aSNS( 1 );
aSNS.getArray()[0] = OUString( RTL_CONSTASCII_USTRINGPARAM("com.sun.star.drawing.MarkerTable" ));
return aSNS;
}
// XNameContainer
void SAL_CALL SvxUnoMarkerTable::insertByName( const OUString& aName, const uno::Any& aElement )
throw( lang::IllegalArgumentException, container::ElementExistException, lang::WrappedTargetException, uno::RuntimeException )
{
if( hasByName( aName ) )
throw container::ElementExistException();
SfxItemSet* mpInSet = new SfxItemSet( *mpPool, XATTR_LINESTART, XATTR_LINEEND );
aItemSetArray.Insert( mpInSet );//, aItemSetArray.Count() );
XLineEndItem aEndMarker;
aEndMarker.SetName( String( aName ) );
aEndMarker.PutValue( aElement );
mpInSet->Put( aEndMarker, XATTR_LINEEND );
XLineStartItem aStartMarker;
aStartMarker.SetName( String( aName ) );
aStartMarker.PutValue( aElement );
mpInSet->Put( aStartMarker, XATTR_LINESTART );
}
void SAL_CALL SvxUnoMarkerTable::removeByName( const OUString& Name )
throw( container::NoSuchElementException, lang::WrappedTargetException, uno::RuntimeException)
{
}
// XNameReplace
void SAL_CALL SvxUnoMarkerTable::replaceByName( const OUString& aName, const uno::Any& aElement )
throw( lang::IllegalArgumentException, container::NoSuchElementException, lang::WrappedTargetException, uno::RuntimeException )
{
}
// XNameAccess
uno::Any SAL_CALL SvxUnoMarkerTable::getByName( const OUString& aName )
throw( container::NoSuchElementException, lang::WrappedTargetException, uno::RuntimeException)
{
if( mpPool )
{
const String aSearchName( aName );
USHORT nCount = mpPool->GetItemCount( XATTR_LINEEND );
const XLineEndItem *pEndItem;
for( USHORT nSurrogate = 0; nSurrogate < nCount; nSurrogate++ )
{
pEndItem = (XLineEndItem*)mpPool->GetItem( XATTR_LINEEND, nSurrogate );
if( pEndItem && ( pEndItem->GetName() == aSearchName ) )
{
uno::Any aAny;
pEndItem->QueryValue( aAny );
return aAny;
}
}
const XLineStartItem *pStartItem;
nCount = mpPool->GetItemCount( XATTR_LINESTART );
for( nSurrogate = 0; nSurrogate < nCount; nSurrogate++ )
{
pStartItem = (XLineStartItem*)mpPool->GetItem( XATTR_LINESTART, nSurrogate );
if( pStartItem && ( pStartItem->GetName() == aSearchName ) )
{
uno::Any aAny;
pStartItem->QueryValue( aAny );
return aAny;
}
}
}
throw container::NoSuchElementException();
}
uno::Sequence< OUString > SAL_CALL SvxUnoMarkerTable::getElementNames( )
throw( uno::RuntimeException )
{
const USHORT nEndCount = mpPool ? mpPool->GetItemCount( XATTR_LINEEND ) : 0;
const USHORT nStartCount = mpPool ? mpPool->GetItemCount( XATTR_LINESTART ) : 0;
uno::Sequence< OUString > aSeq( nEndCount+nStartCount );
OUString* pStrings = aSeq.getArray();
XLineEndItem *pEndItem;
for( USHORT nSurrogate = 0; nSurrogate < nEndCount; nSurrogate++ )
{
pEndItem = (XLineEndItem*)mpPool->GetItem( XATTR_LINEEND, nSurrogate);
if( pEndItem )
{
if( pEndItem->GetName().Len() == 0 )
pEndItem->SetName( pEndItem->CreateStandardName( mpPool, XATTR_LINEEND ) );
pStrings[nSurrogate] = pEndItem->GetName();
DBG_ASSERT( pStrings[nSurrogate].getLength(), "XLineEndItem in pool should have a name !");
}
}
XLineStartItem *pStartItem;
for( nSurrogate = 0; nSurrogate < nStartCount; nSurrogate++ )
{
pStartItem = (XLineStartItem*)mpPool->GetItem( XATTR_LINESTART, nSurrogate);
if( pStartItem )
{
if( pStartItem->GetName().Len() == 0 )
pStartItem->SetName( pStartItem->CreateStandardName( mpPool, XATTR_LINESTART ) );
pStrings[nSurrogate+nEndCount] = pStartItem->GetName();
DBG_ASSERT( pStrings[nSurrogate].getLength(), "XLineStartItem in pool should have a name !");
}
}
return aSeq;
}
sal_Bool SAL_CALL SvxUnoMarkerTable::hasByName( const OUString& aName )
throw( uno::RuntimeException )
{
const String aSearchName( aName );
const USHORT nStartCount = mpPool ? mpPool->GetItemCount( XATTR_LINESTART ) : 0;
const USHORT nEndCount = mpPool ? mpPool->GetItemCount( XATTR_LINEEND ) : 0;
const XLineEndItem *pEndItem;
const XLineStartItem *pStartItem;
for( USHORT nSurrogate = 0; nSurrogate < nStartCount; nSurrogate++ )
{
pStartItem = (XLineStartItem*)mpPool->GetItem( XATTR_LINESTART, nSurrogate);
if( pStartItem && pStartItem->GetName() == aSearchName )
return sal_True;
}
for( nSurrogate = 0; nSurrogate < nEndCount; nSurrogate++ )
{
pEndItem = (XLineEndItem*)mpPool->GetItem( XATTR_LINEEND, nSurrogate);
if( pEndItem && pEndItem->GetName() == aSearchName )
return sal_True;
}
return sal_False;
}
void SvxUnoMarkerTable::CreateName( OUString& rStrName )
{
const USHORT nStartCount = mpPool ? mpPool->GetItemCount(XATTR_LINESTART) : 0;
const USHORT nEndCount = mpPool ? mpPool->GetItemCount(XATTR_LINEEND) : 0;
const USHORT nCount = nStartCount > nEndCount ? nStartCount : nEndCount;
sal_Bool bFound = sal_True;
for( sal_Int32 nPostfix = 1; nPostfix<= nCount && bFound; nPostfix++ )
{
rStrName = OUString::createFromAscii( "Standard " );
rStrName += OUString::valueOf( nPostfix );
bFound = hasByName( rStrName );
}
}
// XElementAccess
uno::Type SAL_CALL SvxUnoMarkerTable::getElementType( )
throw( uno::RuntimeException )
{
return ::getCppuType((const drawing::PointSequence*)0);
}
sal_Bool SAL_CALL SvxUnoMarkerTable::hasElements( )
throw( uno::RuntimeException )
{
return mpPool && mpPool->GetItemCount(XATTR_LINEEND) != 0;
}
/**
* Create a hatchtable
*/
uno::Reference< uno::XInterface > SAL_CALL SvxUnoMarkerTable_createInstance( SdrModel* pModel )
{
return *new SvxUnoMarkerTable(pModel);
}
<commit_msg>fixed an assertions<commit_after>/*************************************************************************
*
* $RCSfile: unomtabl.cxx,v $
*
* $Revision: 1.5 $
*
* last change: $Author: cl $ $Date: 2001-01-16 20:17:25 $
*
* The Contents of this file are made available subject to the terms of
* either of the following licenses
*
* - GNU Lesser General Public License Version 2.1
* - Sun Industry Standards Source License Version 1.1
*
* Sun Microsystems Inc., October, 2000
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2000 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
*
* Sun Industry Standards Source License Version 1.1
* =================================================
* The contents of this file are subject to the Sun Industry Standards
* Source License Version 1.1 (the "License"); You may not use this file
* except in compliance with the License. You may obtain a copy of the
* License at http://www.openoffice.org/license.html.
*
* Software provided under this License is provided on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
* WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
* MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
* See the License for the specific provisions governing your rights and
* obligations concerning the Software.
*
* The Initial Developer of the Original Code is: Sun Microsystems, Inc.
*
* Copyright: 2000 by Sun Microsystems, Inc.
*
* All Rights Reserved.
*
* Contributor(s): _______________________________________
*
*
************************************************************************/
#ifndef _COM_SUN_STAR_LANG_XSERVICEINFO_HPP_
#include <com/sun/star/lang/XServiceInfo.hpp>
#endif
#ifndef _COM_SUN_STAR_CONTAINER_XNAMECONTAINER_HPP_
#include <com/sun/star/container/XNameContainer.hpp>
#endif
#ifndef _COM_SUN_STAR_DRAWING_POINTSEQUENCE_HPP_
#include <com/sun/star/drawing/PointSequence.hpp>
#endif
#include <cppuhelper/implbase2.hxx>
#ifndef _SFXITEMPOOL_HXX
#include <svtools/itempool.hxx>
#endif
#ifndef _SFXITEMSET_HXX //autogen
#include <svtools/itemset.hxx>
#endif
#ifndef _SVX_XLNEDIT_HXX //autogen
#include <xlnedit.hxx>
#endif
#ifndef _SVX_XLNSTIT_HXX
#include <xlnstit.hxx>
#endif
#include "svdmodel.hxx"
#include "xdef.hxx"
#include "xflhtit.hxx"
#ifndef _LIST_HXX
#include<tools/list.hxx>
#endif
using namespace ::com::sun::star;
using namespace ::rtl;
using namespace ::cppu;
DECLARE_LIST( ItemSetArray_Impl, SfxItemSet* )
class SvxUnoMarkerTable : public WeakImplHelper2< container::XNameContainer, lang::XServiceInfo >
{
private:
SdrModel* mpModel;
SfxItemPool* mpPool;
ItemSetArray_Impl aItemSetArray;
void CreateName( OUString& rStrName );
public:
SvxUnoMarkerTable( SdrModel* pModel ) throw();
virtual ~SvxUnoMarkerTable() throw();
// XServiceInfo
virtual OUString SAL_CALL getImplementationName( ) throw( uno::RuntimeException );
virtual sal_Bool SAL_CALL supportsService( const OUString& ServiceName ) throw( uno::RuntimeException);
virtual uno::Sequence< OUString > SAL_CALL getSupportedServiceNames( ) throw( uno::RuntimeException);
static OUString getImplementationName_Static() throw()
{
return OUString(RTL_CONSTASCII_USTRINGPARAM("com.sun.star.drawing.SvxUnoMarkerTable"));
}
static uno::Sequence< OUString > getSupportedServiceNames_Static(void) throw();
// XNameContainer
virtual void SAL_CALL insertByName( const OUString& aName, const uno::Any& aElement ) throw( lang::IllegalArgumentException, container::ElementExistException, lang::WrappedTargetException, uno::RuntimeException);
virtual void SAL_CALL removeByName( const OUString& Name ) throw( container::NoSuchElementException, lang::WrappedTargetException, uno::RuntimeException);
// XNameReplace
virtual void SAL_CALL replaceByName( const OUString& aName, const uno::Any& aElement ) throw( lang::IllegalArgumentException, container::NoSuchElementException, lang::WrappedTargetException, uno::RuntimeException);
// XNameAccess
virtual uno::Any SAL_CALL getByName( const OUString& aName ) throw( container::NoSuchElementException, lang::WrappedTargetException, uno::RuntimeException);
virtual uno::Sequence< OUString > SAL_CALL getElementNames( ) throw( uno::RuntimeException);
virtual sal_Bool SAL_CALL hasByName( const OUString& aName ) throw( uno::RuntimeException);
// XElementAccess
virtual uno::Type SAL_CALL getElementType( ) throw( uno::RuntimeException);
virtual sal_Bool SAL_CALL hasElements( ) throw( uno::RuntimeException);
};
SvxUnoMarkerTable::SvxUnoMarkerTable( SdrModel* pModel ) throw()
: mpModel( pModel ),
mpPool( pModel ? &pModel->GetItemPool() : (SfxItemPool*)NULL )
{
}
SvxUnoMarkerTable::~SvxUnoMarkerTable() throw()
{
for( int i = 0; i<aItemSetArray.Count(); i++ )
delete (SfxItemSet*)aItemSetArray.GetObject( i );
}
sal_Bool SAL_CALL SvxUnoMarkerTable::supportsService( const OUString& ServiceName ) throw(uno::RuntimeException)
{
uno::Sequence< OUString > aSNL( getSupportedServiceNames() );
const OUString * pArray = aSNL.getConstArray();
for( INT32 i = 0; i < aSNL.getLength(); i++ )
if( pArray[i] == ServiceName )
return TRUE;
return FALSE;
}
OUString SAL_CALL SvxUnoMarkerTable::getImplementationName() throw( uno::RuntimeException )
{
return OUString( RTL_CONSTASCII_USTRINGPARAM("SvxUnoMarkerTable") );
}
uno::Sequence< OUString > SAL_CALL SvxUnoMarkerTable::getSupportedServiceNames( )
throw( uno::RuntimeException )
{
return getSupportedServiceNames_Static();
}
uno::Sequence< OUString > SvxUnoMarkerTable::getSupportedServiceNames_Static(void) throw()
{
uno::Sequence< OUString > aSNS( 1 );
aSNS.getArray()[0] = OUString( RTL_CONSTASCII_USTRINGPARAM("com.sun.star.drawing.MarkerTable" ));
return aSNS;
}
// XNameContainer
void SAL_CALL SvxUnoMarkerTable::insertByName( const OUString& aName, const uno::Any& aElement )
throw( lang::IllegalArgumentException, container::ElementExistException, lang::WrappedTargetException, uno::RuntimeException )
{
if( hasByName( aName ) )
throw container::ElementExistException();
SfxItemSet* mpInSet = new SfxItemSet( *mpPool, XATTR_LINESTART, XATTR_LINEEND );
aItemSetArray.Insert( mpInSet );//, aItemSetArray.Count() );
XLineEndItem aEndMarker;
aEndMarker.SetName( String( aName ) );
aEndMarker.PutValue( aElement );
mpInSet->Put( aEndMarker, XATTR_LINEEND );
XLineStartItem aStartMarker;
aStartMarker.SetName( String( aName ) );
aStartMarker.PutValue( aElement );
mpInSet->Put( aStartMarker, XATTR_LINESTART );
}
void SAL_CALL SvxUnoMarkerTable::removeByName( const OUString& Name )
throw( container::NoSuchElementException, lang::WrappedTargetException, uno::RuntimeException)
{
}
// XNameReplace
void SAL_CALL SvxUnoMarkerTable::replaceByName( const OUString& aName, const uno::Any& aElement )
throw( lang::IllegalArgumentException, container::NoSuchElementException, lang::WrappedTargetException, uno::RuntimeException )
{
}
// XNameAccess
uno::Any SAL_CALL SvxUnoMarkerTable::getByName( const OUString& aName )
throw( container::NoSuchElementException, lang::WrappedTargetException, uno::RuntimeException)
{
if( mpPool )
{
const String aSearchName( aName );
USHORT nCount = mpPool->GetItemCount( XATTR_LINEEND );
const XLineEndItem *pEndItem;
for( USHORT nSurrogate = 0; nSurrogate < nCount; nSurrogate++ )
{
pEndItem = (XLineEndItem*)mpPool->GetItem( XATTR_LINEEND, nSurrogate );
if( pEndItem && ( pEndItem->GetName() == aSearchName ) )
{
uno::Any aAny;
pEndItem->QueryValue( aAny );
return aAny;
}
}
const XLineStartItem *pStartItem;
nCount = mpPool->GetItemCount( XATTR_LINESTART );
for( nSurrogate = 0; nSurrogate < nCount; nSurrogate++ )
{
pStartItem = (XLineStartItem*)mpPool->GetItem( XATTR_LINESTART, nSurrogate );
if( pStartItem && ( pStartItem->GetName() == aSearchName ) )
{
uno::Any aAny;
pStartItem->QueryValue( aAny );
return aAny;
}
}
}
throw container::NoSuchElementException();
}
uno::Sequence< OUString > SAL_CALL SvxUnoMarkerTable::getElementNames( )
throw( uno::RuntimeException )
{
const USHORT nEndCount = mpPool ? mpPool->GetItemCount( XATTR_LINEEND ) : 0;
const USHORT nStartCount = mpPool ? mpPool->GetItemCount( XATTR_LINESTART ) : 0;
uno::Sequence< OUString > aSeq( nEndCount+nStartCount );
OUString* pStrings = aSeq.getArray();
XLineEndItem *pEndItem;
for( USHORT nSurrogate = 0; nSurrogate < nEndCount; nSurrogate++ )
{
pEndItem = (XLineEndItem*)mpPool->GetItem( XATTR_LINEEND, nSurrogate);
if( pEndItem )
{
if( pEndItem->GetName().Len() == 0 )
pEndItem->SetName( pEndItem->CreateStandardName( mpPool, XATTR_LINEEND ) );
pStrings[nSurrogate] = pEndItem->GetName();
DBG_ASSERT( pStrings[nSurrogate].getLength(), "XLineEndItem in pool should have a name !");
}
}
XLineStartItem *pStartItem;
for( nSurrogate = 0; nSurrogate < nStartCount; nSurrogate++ )
{
pStartItem = (XLineStartItem*)mpPool->GetItem( XATTR_LINESTART, nSurrogate);
if( pStartItem )
{
if( pStartItem->GetName().Len() == 0 )
pStartItem->SetName( pStartItem->CreateStandardName( mpPool, XATTR_LINESTART ) );
pStrings[nSurrogate+nEndCount] = pStartItem->GetName();
DBG_ASSERT( pStrings[nSurrogate+nEndCount].getLength(), "XLineStartItem in pool should have a name !");
}
}
return aSeq;
}
sal_Bool SAL_CALL SvxUnoMarkerTable::hasByName( const OUString& aName )
throw( uno::RuntimeException )
{
const String aSearchName( aName );
const USHORT nStartCount = mpPool ? mpPool->GetItemCount( XATTR_LINESTART ) : 0;
const USHORT nEndCount = mpPool ? mpPool->GetItemCount( XATTR_LINEEND ) : 0;
const XLineEndItem *pEndItem;
const XLineStartItem *pStartItem;
for( USHORT nSurrogate = 0; nSurrogate < nStartCount; nSurrogate++ )
{
pStartItem = (XLineStartItem*)mpPool->GetItem( XATTR_LINESTART, nSurrogate);
if( pStartItem && pStartItem->GetName() == aSearchName )
return sal_True;
}
for( nSurrogate = 0; nSurrogate < nEndCount; nSurrogate++ )
{
pEndItem = (XLineEndItem*)mpPool->GetItem( XATTR_LINEEND, nSurrogate);
if( pEndItem && pEndItem->GetName() == aSearchName )
return sal_True;
}
return sal_False;
}
void SvxUnoMarkerTable::CreateName( OUString& rStrName )
{
const USHORT nStartCount = mpPool ? mpPool->GetItemCount(XATTR_LINESTART) : 0;
const USHORT nEndCount = mpPool ? mpPool->GetItemCount(XATTR_LINEEND) : 0;
const USHORT nCount = nStartCount > nEndCount ? nStartCount : nEndCount;
sal_Bool bFound = sal_True;
for( sal_Int32 nPostfix = 1; nPostfix<= nCount && bFound; nPostfix++ )
{
rStrName = OUString::createFromAscii( "Standard " );
rStrName += OUString::valueOf( nPostfix );
bFound = hasByName( rStrName );
}
}
// XElementAccess
uno::Type SAL_CALL SvxUnoMarkerTable::getElementType( )
throw( uno::RuntimeException )
{
return ::getCppuType((const drawing::PointSequence*)0);
}
sal_Bool SAL_CALL SvxUnoMarkerTable::hasElements( )
throw( uno::RuntimeException )
{
return mpPool && mpPool->GetItemCount(XATTR_LINEEND) != 0;
}
/**
* Create a hatchtable
*/
uno::Reference< uno::XInterface > SAL_CALL SvxUnoMarkerTable_createInstance( SdrModel* pModel )
{
return *new SvxUnoMarkerTable(pModel);
}
<|endoftext|> |
<commit_before>#include "MessageHandler.h"
#include <iostream>
#include <sstream>
#include <random>
#include <fstream>
#include "WAMPServer.h"
#include "Directory.h"
using namespace std;
using namespace boost::filesystem;
WAMPServer::WAMPServer()
: basedir(""), debug(false) {
}
void WAMPServer::on_message(websocketpp::connection_hdl hdl, message_ptr msg) {
if(debug) {
cout << "Message received " << msg->get_payload() << endl;
}
handler.receiveMessage(clients.right.at(hdl),msg->get_payload());
/*
try {
wserver.send(hdl, msg->get_payload(), msg->get_opcode());
} catch (const websocketpp::lib::error_code& e) {
std::cout << " failed because: " << e
<< "(" << e.message() << ")" << std::endl;
}
*/
}
void WAMPServer::setDebug(bool enable) {
debug = enable;
}
void WAMPServer::on_http(websocketpp::connection_hdl hdl) {
server::connection_ptr con = wserver.get_con_from_hdl(hdl);
try {
path request;
if(basedir == "")
{
throw 0;
}
request = canonical(basedir.string()+con->get_resource()); //will throw exception if file not exists!
if (request.string().compare(0, basedir.string().length(), basedir.string()) != 0)
{
throw 0;
}
if(!is_regular_file(request))
{
if(is_directory(request))
{
request += "/index.html";
}
}
cout << request << endl;
ifstream t(request.string());
if(!t.is_open())
{
throw 0;
}
con->set_status(websocketpp::http::status_code::ok);
std::string str;
t.seekg(0, std::ios::end);
str.reserve(t.tellg());
t.seekg(0, std::ios::beg);
str.assign((std::istreambuf_iterator<char>(t)), std::istreambuf_iterator<char>());
con->set_body(str);
string mime = "text/plain";
string extension = request.extension().string();
if(extension == ".htm" || extension == ".html") {
mime = "text/html";
}
else if(extension == ".svg") {
mime = "image/svg+xml";
}
else if(extension == ".js") {
mime = "application/javascript";
}
con->replace_header("Content-Type",mime);
t.close();
}
catch(...){
con->set_body("Request could not be handled");
con->set_status(websocketpp::http::status_code::not_found);
}
}
void WAMPServer::setBaseDir(std::string dir) {
basedir = canonical(dir); //will throw exception if file not exists!
}
bool WAMPServer::validate(connection_hdl hdl) {
server::connection_ptr con = wserver.get_con_from_hdl(hdl);
//std::cout << "Cache-Control: " << con->get_request_header("Cache-Control") << std::endl;
const std::vector<std::string> & subp_requests = con->get_requested_subprotocols();
std::vector<std::string>::const_iterator it;
for (it = subp_requests.begin(); it != subp_requests.end(); ++it) {
std::cout << "Requested: " << *it << std::endl;
}
if (subp_requests.size() > 0) {
con->select_subprotocol(subp_requests[0]);
}
return true;
}
string WAMPServer::generateRandomString()
{
stringstream ss;
string chars(
"abcdefghijklmnopqrstuvwxyz"
"ABCDEFGHIJKLMNOPQRSTUVWXYZ"
"1234567890");
random_device rng;
uniform_int_distribution<> index_dist(0, chars.size() - 1);
for(int i = 0; i < 16; ++i) {
ss << chars[index_dist(rng)];
}
return ss.str();
}
void WAMPServer::on_open(connection_hdl hdl) {
connections.insert(hdl);
try {
string sessionId = generateRandomString();
stringstream ss;
clients.insert(boost::bimap< std::string, connection_hdl >::value_type(sessionId,hdl));
ss << "[0, \"" << sessionId << "\", 1, \"wamp_cpp/0.0.0.1\"]";
wserver.send(hdl, ss.str(), websocketpp::frame::opcode::text);
Directory::getInstance().connectionEstablished(sessionId);
} catch (const websocketpp::lib::error_code& e) {
std::cout << "Open connection failed because: " << e
<< " (" << e.message() << ")" << std::endl;
}
}
void WAMPServer::on_close(connection_hdl hdl) {
connections.erase(hdl);
}
void WAMPServer::send(std::string client, std::string msg)
{
if(debug) {
cout << "Send message " << msg << endl;
}
try {
auto hdl = clients.left.at(client);
if(!hdl.lock().get())
{
cout << "Session to " << client << " finished" << endl;
clients.left.erase(client);
return;
}
wserver.send(hdl, msg, websocketpp::frame::opcode::text);
} catch (const websocketpp::lib::error_code& e) {
std::cout << "Send failed because: " << e
<< " (" << e.message() << ")" << std::endl;
} catch(std::out_of_range e) {
// does not matter -> don't send anything
}
}
void WAMPServer::start()
{
serverThread = std::thread(&WAMPServer::thread,this);
}
void WAMPServer::stop()
{
wserver.stop();
serverThread.join();
}
void WAMPServer::thread()
{
handler.registerSend(bind(&WAMPServer::send,this,::_1,::_2));
try {
// Set logging settings
//wserver.set_access_channels(websocketpp::log::alevel::all);
wserver.clear_access_channels(websocketpp::log::alevel::all);
// Initialize ASIO
wserver.init_asio();
// Register our message handler
wserver.set_message_handler(bind(&WAMPServer::on_message,this,::_1,::_2));
wserver.set_validate_handler(bind(&WAMPServer::validate,this,::_1));
wserver.set_open_handler(bind(&WAMPServer::on_open,this,::_1));
wserver.set_close_handler(bind(&WAMPServer::on_close,this,::_1));
wserver.set_http_handler(bind(&WAMPServer::on_http,this,::_1));
// Listen on port
wserver.listen(boost::asio::ip::tcp::v4(), 9002);
// Start the server accept loop
wserver.start_accept();
// Start the ASIO io_service run loop
wserver.run();
} catch (const std::exception & e) {
std::cerr << "WAMPServer error " << e.what() << std::endl;
} catch (websocketpp::lib::error_code e) {
std::cerr << "WAMPServer error " << e.message() << std::endl;
} catch (...) {
std::cerr << "WAMPServer error unknown exception" << std::endl;
}
}
<commit_msg>Clean Up<commit_after>#include "MessageHandler.h"
#include <iostream>
#include <sstream>
#include <random>
#include <fstream>
#include "WAMPServer.h"
#include "Directory.h"
using namespace std;
using namespace boost::filesystem;
WAMPServer::WAMPServer()
: basedir(""), debug(false) {
}
void WAMPServer::on_message(websocketpp::connection_hdl hdl, message_ptr msg) {
if(debug) {
cout << "Message received " << msg->get_payload() << endl;
}
handler.receiveMessage(clients.right.at(hdl),msg->get_payload());
}
void WAMPServer::setDebug(bool enable) {
debug = enable;
}
void WAMPServer::on_http(websocketpp::connection_hdl hdl) {
server::connection_ptr con = wserver.get_con_from_hdl(hdl);
try {
path request;
if(basedir == "")
{
throw 0;
}
string resource = con->get_resource();
size_t found = resource.find_first_of("?#");
request = canonical(basedir.string()+resource.substr(0,found)); //will throw exception if file not exists!
if (request.string().compare(0, basedir.string().length(), basedir.string()) != 0)
{
throw 0;
}
if(!is_regular_file(request))
{
if(is_directory(request))
{
request += "/index.html";
}
}
cout << request << endl;
ifstream t(request.string());
if(!t.is_open())
{
throw 0;
}
con->set_status(websocketpp::http::status_code::ok);
std::string str;
t.seekg(0, std::ios::end);
str.reserve(t.tellg());
t.seekg(0, std::ios::beg);
str.assign((std::istreambuf_iterator<char>(t)), std::istreambuf_iterator<char>());
con->set_body(str);
string mime = "text/plain";
string extension = request.extension().string();
if(extension == ".htm" || extension == ".html") {
mime = "text/html";
}
else if(extension == ".svg") {
mime = "image/svg+xml";
}
else if(extension == ".js") {
mime = "application/javascript";
}
con->replace_header("Content-Type",mime);
t.close();
}
catch(...){
con->set_body("Request could not be handled");
con->set_status(websocketpp::http::status_code::not_found);
}
}
void WAMPServer::setBaseDir(std::string dir) {
basedir = canonical(dir); //will throw exception if file not exists!
}
bool WAMPServer::validate(connection_hdl hdl) {
server::connection_ptr con = wserver.get_con_from_hdl(hdl);
//std::cout << "Cache-Control: " << con->get_request_header("Cache-Control") << std::endl;
const std::vector<std::string> & subp_requests = con->get_requested_subprotocols();
std::vector<std::string>::const_iterator it;
for (it = subp_requests.begin(); it != subp_requests.end(); ++it) {
std::cout << "Requested: " << *it << std::endl;
}
if (subp_requests.size() > 0) {
con->select_subprotocol(subp_requests[0]);
}
return true;
}
string WAMPServer::generateRandomString()
{
stringstream ss;
string chars(
"abcdefghijklmnopqrstuvwxyz"
"ABCDEFGHIJKLMNOPQRSTUVWXYZ"
"1234567890");
random_device rng;
uniform_int_distribution<> index_dist(0, chars.size() - 1);
for(int i = 0; i < 16; ++i) {
ss << chars[index_dist(rng)];
}
return ss.str();
}
void WAMPServer::on_open(connection_hdl hdl) {
connections.insert(hdl);
try {
string sessionId = generateRandomString();
stringstream ss;
clients.insert(boost::bimap< std::string, connection_hdl >::value_type(sessionId,hdl));
ss << "[0, \"" << sessionId << "\", 1, \"wamp_cpp/0.0.0.1\"]";
wserver.send(hdl, ss.str(), websocketpp::frame::opcode::text);
Directory::getInstance().connectionEstablished(sessionId);
} catch (const websocketpp::lib::error_code& e) {
std::cout << "Open connection failed because: " << e
<< " (" << e.message() << ")" << std::endl;
}
}
void WAMPServer::on_close(connection_hdl hdl) {
connections.erase(hdl);
}
void WAMPServer::send(std::string client, std::string msg)
{
if(debug) {
cout << "Send message " << msg << endl;
}
try {
auto hdl = clients.left.at(client);
if(!hdl.lock().get())
{
cout << "Session to " << client << " finished" << endl;
clients.left.erase(client);
return;
}
wserver.send(hdl, msg, websocketpp::frame::opcode::text);
} catch (const websocketpp::lib::error_code& e) {
std::cout << "Send failed because: " << e
<< " (" << e.message() << ")" << std::endl;
} catch(std::out_of_range e) {
// does not matter -> don't send anything
}
}
void WAMPServer::start()
{
serverThread = std::thread(&WAMPServer::thread,this);
}
void WAMPServer::stop()
{
wserver.stop();
serverThread.join();
}
void WAMPServer::thread()
{
handler.registerSend(bind(&WAMPServer::send,this,::_1,::_2));
try {
// Set logging settings
//wserver.set_access_channels(websocketpp::log::alevel::all);
wserver.clear_access_channels(websocketpp::log::alevel::all);
// Initialize ASIO
wserver.init_asio();
// Register our message handler
wserver.set_message_handler(bind(&WAMPServer::on_message,this,::_1,::_2));
wserver.set_validate_handler(bind(&WAMPServer::validate,this,::_1));
wserver.set_open_handler(bind(&WAMPServer::on_open,this,::_1));
wserver.set_close_handler(bind(&WAMPServer::on_close,this,::_1));
wserver.set_http_handler(bind(&WAMPServer::on_http,this,::_1));
// Listen on port
wserver.listen(boost::asio::ip::tcp::v4(), 9002);
// Start the server accept loop
wserver.start_accept();
// Start the ASIO io_service run loop
wserver.run();
} catch (const std::exception & e) {
std::cerr << "WAMPServer error " << e.what() << std::endl;
} catch (websocketpp::lib::error_code e) {
std::cerr << "WAMPServer error " << e.message() << std::endl;
} catch (...) {
std::cerr << "WAMPServer error unknown exception" << std::endl;
}
}
<|endoftext|> |
<commit_before>/*
* Copyright 2013 Google Inc.
*
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*/
#include "SkRectShaderImageFilter.h"
#include "SkBitmap.h"
#include "SkCanvas.h"
#include "SkDevice.h"
#include "SkFlattenableBuffers.h"
#include "SkShader.h"
SkRectShaderImageFilter* SkRectShaderImageFilter::Create(SkShader* s, const SkRect& rect) {
SkASSERT(s);
return SkNEW_ARGS(SkRectShaderImageFilter, (s, rect));
}
SkRectShaderImageFilter::SkRectShaderImageFilter(SkShader* s, const SkRect& rect)
: INHERITED(NULL)
, fShader(s)
, fRect(rect) {
SkASSERT(s);
s->ref();
}
SkRectShaderImageFilter::SkRectShaderImageFilter(SkFlattenableReadBuffer& buffer)
: INHERITED(buffer) {
fShader = buffer.readFlattenableT<SkShader>();
buffer.readRect(&fRect);
}
void SkRectShaderImageFilter::flatten(SkFlattenableWriteBuffer& buffer) const {
this->INHERITED::flatten(buffer);
buffer.writeFlattenable(fShader);
buffer.writeRect(fRect);
}
SkRectShaderImageFilter::~SkRectShaderImageFilter() {
SkSafeUnref(fShader);
}
bool SkRectShaderImageFilter::onFilterImage(Proxy* proxy,
const SkBitmap& source,
const SkMatrix& matrix,
SkBitmap* result,
SkIPoint* loc) {
SkAutoTUnref<SkDevice> device(proxy->createDevice(SkScalarCeilToInt(fRect.width()),
SkScalarCeilToInt(fRect.height())));
SkCanvas canvas(device.get());
SkPaint paint;
paint.setShader(fShader);
canvas.drawRect(fRect, paint);
*result = device.get()->accessBitmap(false);
return true;
}
<commit_msg>Sanitizing source files in Skia_Periodic_House_Keeping<commit_after>/*
* Copyright 2013 Google Inc.
*
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*/
#include "SkRectShaderImageFilter.h"
#include "SkBitmap.h"
#include "SkCanvas.h"
#include "SkDevice.h"
#include "SkFlattenableBuffers.h"
#include "SkShader.h"
SkRectShaderImageFilter* SkRectShaderImageFilter::Create(SkShader* s, const SkRect& rect) {
SkASSERT(s);
return SkNEW_ARGS(SkRectShaderImageFilter, (s, rect));
}
SkRectShaderImageFilter::SkRectShaderImageFilter(SkShader* s, const SkRect& rect)
: INHERITED(NULL)
, fShader(s)
, fRect(rect) {
SkASSERT(s);
s->ref();
}
SkRectShaderImageFilter::SkRectShaderImageFilter(SkFlattenableReadBuffer& buffer)
: INHERITED(buffer) {
fShader = buffer.readFlattenableT<SkShader>();
buffer.readRect(&fRect);
}
void SkRectShaderImageFilter::flatten(SkFlattenableWriteBuffer& buffer) const {
this->INHERITED::flatten(buffer);
buffer.writeFlattenable(fShader);
buffer.writeRect(fRect);
}
SkRectShaderImageFilter::~SkRectShaderImageFilter() {
SkSafeUnref(fShader);
}
bool SkRectShaderImageFilter::onFilterImage(Proxy* proxy,
const SkBitmap& source,
const SkMatrix& matrix,
SkBitmap* result,
SkIPoint* loc) {
SkAutoTUnref<SkDevice> device(proxy->createDevice(SkScalarCeilToInt(fRect.width()),
SkScalarCeilToInt(fRect.height())));
SkCanvas canvas(device.get());
SkPaint paint;
paint.setShader(fShader);
canvas.drawRect(fRect, paint);
*result = device.get()->accessBitmap(false);
return true;
}
<|endoftext|> |
<commit_before>/*************************************************************************
*
* $RCSfile: docbasic.cxx,v $
*
* $Revision: 1.7 $
*
* last change: $Author: rt $ $Date: 2004-06-16 09:35:21 $
*
* The Contents of this file are made available subject to the terms of
* either of the following licenses
*
* - GNU Lesser General Public License Version 2.1
* - Sun Industry Standards Source License Version 1.1
*
* Sun Microsystems Inc., October, 2000
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2000 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
*
* Sun Industry Standards Source License Version 1.1
* =================================================
* The contents of this file are subject to the Sun Industry Standards
* Source License Version 1.1 (the "License"); You may not use this file
* except in compliance with the License. You may obtain a copy of the
* License at http://www.openoffice.org/license.html.
*
* Software provided under this License is provided on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
* WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
* MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
* See the License for the specific provisions governing your rights and
* obligations concerning the Software.
*
* The Initial Developer of the Original Code is: Sun Microsystems, Inc.
*
* Copyright: 2000 by Sun Microsystems, Inc.
*
* All Rights Reserved.
*
* Contributor(s): _______________________________________
*
*
************************************************************************/
#pragma hdrstop
#ifndef _HINTIDS_HXX
#include <hintids.hxx>
#endif
#ifndef _RTL_USTRING_HXX //autogen
#include <rtl/ustring.hxx>
#endif
#ifndef _IMAP_HXX //autogen
#include <svtools/imap.hxx>
#endif
#ifndef _GOODIES_IMAPOBJ_HXX
#include <svtools/imapobj.hxx>
#endif
#ifndef _SBXCLASS_HXX
#include <svtools/sbx.hxx>
#endif
#ifndef _SBXCORE_HXX
#include <svtools/sbxcore.hxx>
#endif
#ifndef __SBX_SBXVALUE
#include <svtools/sbxvar.hxx>
#endif
#ifndef _FRMFMT_HXX //autogen
#include <frmfmt.hxx>
#endif
#ifndef _FMTINFMT_HXX //autogen
#include <fmtinfmt.hxx>
#endif
#ifndef _FMTURL_HXX //autogen
#include <fmturl.hxx>
#endif
#ifndef _FRMATR_HXX
#include <frmatr.hxx>
#endif
#ifndef _DOCARY_HXX
#include <docary.hxx>
#endif
#ifndef _DOC_HXX
#include <doc.hxx>
#endif
#ifndef _DOCSH_HXX
#include <docsh.hxx>
#endif
#ifndef _SWEVENT_HXX
#include <swevent.hxx>
#endif
using namespace ::com::sun::star::uno;
using namespace ::rtl;
Sequence<Any> *lcl_docbasic_convertArgs( SbxArray& rArgs )
{
Sequence<Any> *pRet = 0;
#if 0
switch( nEvent )
{
case SW_EVENT_FRM_KEYINPUT_ALPHA:
case SW_EVENT_FRM_KEYINPUT_NOALPHA:
case SW_EVENT_FRM_MOVE:
case SW_EVENT_FRM_RESIZE:
}
#endif
USHORT nCount = rArgs.Count();
if( nCount > 1 )
{
nCount--;
pRet = new Sequence<Any>( nCount );
Any *pUnoArgs = pRet->getArray();
for( USHORT i=0; i<nCount; i++ )
{
SbxVariable *pVar = rArgs.Get( i+1 );
switch( pVar->GetType() )
{
case SbxSTRING:
pUnoArgs[i] <<= OUString( pVar->GetString() );
break;
case SbxCHAR:
pUnoArgs[i] <<= (sal_Int16)pVar->GetChar() ;
break;
case SbxUSHORT:
pUnoArgs[i] <<= (sal_Int16)pVar->GetUShort();
break;
case SbxLONG:
pUnoArgs[i] <<= (sal_Int32)pVar->GetLong();
break;
default:
pUnoArgs[i].setValue(0, ::getVoidCppuType());
break;
}
}
}
return pRet;
}
BOOL SwDoc::ExecMacro( const SvxMacro& rMacro, String* pRet, SbxArray* pArgs )
{
ErrCode eErr = 0;
switch( rMacro.GetScriptType() )
{
case STARBASIC:
{
SbxBaseRef aRef;
SbxValue* pRetValue = new SbxValue;
aRef = pRetValue;
eErr = pDocShell->CallBasic( rMacro.GetMacName(),
rMacro.GetLibName(),
0, pArgs, pRet ? pRetValue : 0 );
if( pRet && SbxNULL < pRetValue->GetType() &&
SbxVOID != pRetValue->GetType() )
// gueltiger Wert, also setzen
*pRet = pRetValue->GetString();
}
break;
case JAVASCRIPT:
// ignore JavaScript calls
break;
case EXTENDED_STYPE:
{
Sequence<Any> *pUnoArgs = 0;
if( pArgs )
{
// better to rename the local function to lcl_translateBasic2Uno and
// a much shorter routine can be found in sfx2/source/doc/objmisc.cxx
pUnoArgs = lcl_docbasic_convertArgs( *pArgs );
}
if (!pUnoArgs)
{
pUnoArgs = new Sequence< Any > (0);
}
// TODO - return value is not handled
Any aRet;
Sequence< sal_Int16 > aOutArgsIndex;
Sequence< Any > aOutArgs;
OSL_TRACE( "SwDoc::ExecMacro URL is %s", ByteString( rMacro.GetMacName(),
RTL_TEXTENCODING_UTF8).GetBuffer() );
eErr = pDocShell->CallXScript(
rMacro.GetMacName(), *pUnoArgs, aRet, aOutArgsIndex, aOutArgs);
//*pRet = pRetValue->GetString();
// use the AnyConverter to return a String if appropriate?
// need to call something like lcl_translateUno2Basic
// pArgs = lcl_translateUno2Basic( pUnoArgs );
delete pUnoArgs;
break;
}
}
return 0 == eErr;
}
USHORT SwDoc::CallEvent( USHORT nEvent, const SwCallMouseEvent& rCallEvent,
BOOL bCheckPtr, SbxArray* pArgs, const Link* pCallBack )
{
if( !pDocShell ) // ohne DocShell geht das nicht!
return 0;
USHORT nRet = 0;
const SvxMacroTableDtor* pTbl = 0;
switch( rCallEvent.eType )
{
case EVENT_OBJECT_INETATTR:
if( bCheckPtr )
{
const SfxPoolItem* pItem;
USHORT n, nMaxItems = GetAttrPool().GetItemCount( RES_TXTATR_INETFMT );
for( n = 0; n < nMaxItems; ++n )
if( 0 != (pItem = GetAttrPool().GetItem( RES_TXTATR_INETFMT, n ) )
&& rCallEvent.PTR.pINetAttr == pItem )
{
bCheckPtr = FALSE; // als Flag missbrauchen
break;
}
}
if( !bCheckPtr )
pTbl = rCallEvent.PTR.pINetAttr->GetMacroTbl();
break;
case EVENT_OBJECT_URLITEM:
case EVENT_OBJECT_IMAGE:
{
const SwFrmFmtPtr pFmt = (SwFrmFmtPtr)rCallEvent.PTR.pFmt;
if( bCheckPtr )
{
USHORT nPos = GetSpzFrmFmts()->GetPos( pFmt );
if( USHRT_MAX != nPos )
bCheckPtr = FALSE; // als Flag missbrauchen
}
if( !bCheckPtr )
pTbl = &pFmt->GetMacro().GetMacroTable();
}
break;
case EVENT_OBJECT_IMAGEMAP:
{
const IMapObject* pIMapObj = rCallEvent.PTR.IMAP.pIMapObj;
if( bCheckPtr )
{
const SwFrmFmtPtr pFmt = (SwFrmFmtPtr)rCallEvent.PTR.IMAP.pFmt;
USHORT nPos = GetSpzFrmFmts()->GetPos( pFmt );
const ImageMap* pIMap;
if( USHRT_MAX != nPos &&
0 != (pIMap = pFmt->GetURL().GetMap()) )
{
for( nPos = pIMap->GetIMapObjectCount(); nPos; )
if( pIMapObj == pIMap->GetIMapObject( --nPos ))
{
bCheckPtr = FALSE; // als Flag missbrauchen
break;
}
}
}
if( !bCheckPtr )
pTbl = &pIMapObj->GetMacroTable();
}
break;
default:
break;
}
if( pTbl )
{
nRet = 0x1;
if( pTbl->IsKeyValid( nEvent ) )
{
const SvxMacro& rMacro = *pTbl->Get( nEvent );
if( STARBASIC == rMacro.GetScriptType() )
{
nRet += 0 == pDocShell->CallBasic( rMacro.GetMacName(),
rMacro.GetLibName(), 0, pArgs ) ? 1 : 0;
}
else if( EXTENDED_STYPE == rMacro.GetScriptType() )
{
Sequence<Any> *pUnoArgs = 0;
if( pArgs )
{
pUnoArgs = lcl_docbasic_convertArgs( *pArgs );
}
if (!pUnoArgs)
{
pUnoArgs = new Sequence <Any> (0);
}
Any aRet;
Sequence< sal_Int16 > aOutArgsIndex;
Sequence< Any > aOutArgs;
OSL_TRACE( "SwDoc::CallEvent URL is %s", ByteString(
rMacro.GetMacName(), RTL_TEXTENCODING_UTF8).GetBuffer() );
nRet += 0 == pDocShell->CallXScript(
rMacro.GetMacName(), *pUnoArgs,aRet, aOutArgsIndex, aOutArgs);
//*pRet = pRetValue->GetString();
// use the AnyConverter to return a String if appropriate?
// need to call something like lcl_translateUno2Basic
// pArgs = lcl_translateUno2Basic( pUnoArgs );
delete pUnoArgs;
}
// JavaScript calls are ignored
}
}
return nRet;
}
<commit_msg>INTEGRATION: CWS tune05 (1.7.8); FILE MERGED 2004/06/24 10:20:54 cmc 1.7.8.1: #i30554# make lcl_foos static to emphasis their lclness<commit_after>/*************************************************************************
*
* $RCSfile: docbasic.cxx,v $
*
* $Revision: 1.8 $
*
* last change: $Author: obo $ $Date: 2004-08-12 12:15:21 $
*
* The Contents of this file are made available subject to the terms of
* either of the following licenses
*
* - GNU Lesser General Public License Version 2.1
* - Sun Industry Standards Source License Version 1.1
*
* Sun Microsystems Inc., October, 2000
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2000 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
*
* Sun Industry Standards Source License Version 1.1
* =================================================
* The contents of this file are subject to the Sun Industry Standards
* Source License Version 1.1 (the "License"); You may not use this file
* except in compliance with the License. You may obtain a copy of the
* License at http://www.openoffice.org/license.html.
*
* Software provided under this License is provided on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
* WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
* MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
* See the License for the specific provisions governing your rights and
* obligations concerning the Software.
*
* The Initial Developer of the Original Code is: Sun Microsystems, Inc.
*
* Copyright: 2000 by Sun Microsystems, Inc.
*
* All Rights Reserved.
*
* Contributor(s): _______________________________________
*
*
************************************************************************/
#pragma hdrstop
#ifndef _HINTIDS_HXX
#include <hintids.hxx>
#endif
#ifndef _RTL_USTRING_HXX //autogen
#include <rtl/ustring.hxx>
#endif
#ifndef _IMAP_HXX //autogen
#include <svtools/imap.hxx>
#endif
#ifndef _GOODIES_IMAPOBJ_HXX
#include <svtools/imapobj.hxx>
#endif
#ifndef _SBXCLASS_HXX
#include <svtools/sbx.hxx>
#endif
#ifndef _SBXCORE_HXX
#include <svtools/sbxcore.hxx>
#endif
#ifndef __SBX_SBXVALUE
#include <svtools/sbxvar.hxx>
#endif
#ifndef _FRMFMT_HXX //autogen
#include <frmfmt.hxx>
#endif
#ifndef _FMTINFMT_HXX //autogen
#include <fmtinfmt.hxx>
#endif
#ifndef _FMTURL_HXX //autogen
#include <fmturl.hxx>
#endif
#ifndef _FRMATR_HXX
#include <frmatr.hxx>
#endif
#ifndef _DOCARY_HXX
#include <docary.hxx>
#endif
#ifndef _DOC_HXX
#include <doc.hxx>
#endif
#ifndef _DOCSH_HXX
#include <docsh.hxx>
#endif
#ifndef _SWEVENT_HXX
#include <swevent.hxx>
#endif
using namespace ::com::sun::star::uno;
using namespace ::rtl;
static Sequence<Any> *lcl_docbasic_convertArgs( SbxArray& rArgs )
{
Sequence<Any> *pRet = 0;
#if 0
switch( nEvent )
{
case SW_EVENT_FRM_KEYINPUT_ALPHA:
case SW_EVENT_FRM_KEYINPUT_NOALPHA:
case SW_EVENT_FRM_MOVE:
case SW_EVENT_FRM_RESIZE:
}
#endif
USHORT nCount = rArgs.Count();
if( nCount > 1 )
{
nCount--;
pRet = new Sequence<Any>( nCount );
Any *pUnoArgs = pRet->getArray();
for( USHORT i=0; i<nCount; i++ )
{
SbxVariable *pVar = rArgs.Get( i+1 );
switch( pVar->GetType() )
{
case SbxSTRING:
pUnoArgs[i] <<= OUString( pVar->GetString() );
break;
case SbxCHAR:
pUnoArgs[i] <<= (sal_Int16)pVar->GetChar() ;
break;
case SbxUSHORT:
pUnoArgs[i] <<= (sal_Int16)pVar->GetUShort();
break;
case SbxLONG:
pUnoArgs[i] <<= (sal_Int32)pVar->GetLong();
break;
default:
pUnoArgs[i].setValue(0, ::getVoidCppuType());
break;
}
}
}
return pRet;
}
BOOL SwDoc::ExecMacro( const SvxMacro& rMacro, String* pRet, SbxArray* pArgs )
{
ErrCode eErr = 0;
switch( rMacro.GetScriptType() )
{
case STARBASIC:
{
SbxBaseRef aRef;
SbxValue* pRetValue = new SbxValue;
aRef = pRetValue;
eErr = pDocShell->CallBasic( rMacro.GetMacName(),
rMacro.GetLibName(),
0, pArgs, pRet ? pRetValue : 0 );
if( pRet && SbxNULL < pRetValue->GetType() &&
SbxVOID != pRetValue->GetType() )
// gueltiger Wert, also setzen
*pRet = pRetValue->GetString();
}
break;
case JAVASCRIPT:
// ignore JavaScript calls
break;
case EXTENDED_STYPE:
{
Sequence<Any> *pUnoArgs = 0;
if( pArgs )
{
// better to rename the local function to lcl_translateBasic2Uno and
// a much shorter routine can be found in sfx2/source/doc/objmisc.cxx
pUnoArgs = lcl_docbasic_convertArgs( *pArgs );
}
if (!pUnoArgs)
{
pUnoArgs = new Sequence< Any > (0);
}
// TODO - return value is not handled
Any aRet;
Sequence< sal_Int16 > aOutArgsIndex;
Sequence< Any > aOutArgs;
OSL_TRACE( "SwDoc::ExecMacro URL is %s", ByteString( rMacro.GetMacName(),
RTL_TEXTENCODING_UTF8).GetBuffer() );
eErr = pDocShell->CallXScript(
rMacro.GetMacName(), *pUnoArgs, aRet, aOutArgsIndex, aOutArgs);
//*pRet = pRetValue->GetString();
// use the AnyConverter to return a String if appropriate?
// need to call something like lcl_translateUno2Basic
// pArgs = lcl_translateUno2Basic( pUnoArgs );
delete pUnoArgs;
break;
}
}
return 0 == eErr;
}
USHORT SwDoc::CallEvent( USHORT nEvent, const SwCallMouseEvent& rCallEvent,
BOOL bCheckPtr, SbxArray* pArgs, const Link* pCallBack )
{
if( !pDocShell ) // ohne DocShell geht das nicht!
return 0;
USHORT nRet = 0;
const SvxMacroTableDtor* pTbl = 0;
switch( rCallEvent.eType )
{
case EVENT_OBJECT_INETATTR:
if( bCheckPtr )
{
const SfxPoolItem* pItem;
USHORT n, nMaxItems = GetAttrPool().GetItemCount( RES_TXTATR_INETFMT );
for( n = 0; n < nMaxItems; ++n )
if( 0 != (pItem = GetAttrPool().GetItem( RES_TXTATR_INETFMT, n ) )
&& rCallEvent.PTR.pINetAttr == pItem )
{
bCheckPtr = FALSE; // als Flag missbrauchen
break;
}
}
if( !bCheckPtr )
pTbl = rCallEvent.PTR.pINetAttr->GetMacroTbl();
break;
case EVENT_OBJECT_URLITEM:
case EVENT_OBJECT_IMAGE:
{
const SwFrmFmtPtr pFmt = (SwFrmFmtPtr)rCallEvent.PTR.pFmt;
if( bCheckPtr )
{
USHORT nPos = GetSpzFrmFmts()->GetPos( pFmt );
if( USHRT_MAX != nPos )
bCheckPtr = FALSE; // als Flag missbrauchen
}
if( !bCheckPtr )
pTbl = &pFmt->GetMacro().GetMacroTable();
}
break;
case EVENT_OBJECT_IMAGEMAP:
{
const IMapObject* pIMapObj = rCallEvent.PTR.IMAP.pIMapObj;
if( bCheckPtr )
{
const SwFrmFmtPtr pFmt = (SwFrmFmtPtr)rCallEvent.PTR.IMAP.pFmt;
USHORT nPos = GetSpzFrmFmts()->GetPos( pFmt );
const ImageMap* pIMap;
if( USHRT_MAX != nPos &&
0 != (pIMap = pFmt->GetURL().GetMap()) )
{
for( nPos = pIMap->GetIMapObjectCount(); nPos; )
if( pIMapObj == pIMap->GetIMapObject( --nPos ))
{
bCheckPtr = FALSE; // als Flag missbrauchen
break;
}
}
}
if( !bCheckPtr )
pTbl = &pIMapObj->GetMacroTable();
}
break;
default:
break;
}
if( pTbl )
{
nRet = 0x1;
if( pTbl->IsKeyValid( nEvent ) )
{
const SvxMacro& rMacro = *pTbl->Get( nEvent );
if( STARBASIC == rMacro.GetScriptType() )
{
nRet += 0 == pDocShell->CallBasic( rMacro.GetMacName(),
rMacro.GetLibName(), 0, pArgs ) ? 1 : 0;
}
else if( EXTENDED_STYPE == rMacro.GetScriptType() )
{
Sequence<Any> *pUnoArgs = 0;
if( pArgs )
{
pUnoArgs = lcl_docbasic_convertArgs( *pArgs );
}
if (!pUnoArgs)
{
pUnoArgs = new Sequence <Any> (0);
}
Any aRet;
Sequence< sal_Int16 > aOutArgsIndex;
Sequence< Any > aOutArgs;
OSL_TRACE( "SwDoc::CallEvent URL is %s", ByteString(
rMacro.GetMacName(), RTL_TEXTENCODING_UTF8).GetBuffer() );
nRet += 0 == pDocShell->CallXScript(
rMacro.GetMacName(), *pUnoArgs,aRet, aOutArgsIndex, aOutArgs);
//*pRet = pRetValue->GetString();
// use the AnyConverter to return a String if appropriate?
// need to call something like lcl_translateUno2Basic
// pArgs = lcl_translateUno2Basic( pUnoArgs );
delete pUnoArgs;
}
// JavaScript calls are ignored
}
}
return nRet;
}
<|endoftext|> |
<commit_before>/*************************************************************************
*
* $RCSfile: committer.cxx,v $
*
* $Revision: 1.14 $
*
* last change: $Author: hr $ $Date: 2003-03-19 16:18:30 $
*
* The Contents of this file are made available subject to the terms of
* either of the following licenses
*
* - GNU Lesser General Public License Version 2.1
* - Sun Industry Standards Source License Version 1.1
*
* Sun Microsystems Inc., October, 2000
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2000 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
*
* Sun Industry Standards Source License Version 1.1
* =================================================
* The contents of this file are subject to the Sun Industry Standards
* Source License Version 1.1 (the "License"); You may not use this file
* except in compliance with the License. You may obtain a copy of the
* License at http://www.openoffice.org/license.html.
*
* Software provided under this License is provided on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
* WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
* MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
* See the License for the specific provisions governing your rights and
* obligations concerning the Software.
*
* The Initial Developer of the Original Code is: Sun Microsystems, Inc.
*
* Copyright: 2000 by Sun Microsystems, Inc.
*
* All Rights Reserved.
*
* Contributor(s): _______________________________________
*
*
************************************************************************/
#include <stdio.h>
#include "committer.hxx"
#ifndef CONFIGMGR_API_TREEIMPLOBJECTS_HXX_
#include "apitreeimplobj.hxx"
#endif
#ifndef CONFIGMGR_ROOTTREE_HXX_
#include "roottree.hxx"
#endif
#ifndef CONFIGMGR_API_PROVIDERIMPL2_HXX_
#include "confproviderimpl2.hxx"
#endif
#ifndef CONFIGMGR_UPDATEACCESSOR_HXX
#include "updateaccessor.hxx"
#endif
#ifndef CONFIGMGR_TREEACCESSOR_HXX
#include "treeaccessor.hxx"
#endif
#ifndef CONFIGMGR_TREECHANGELIST_HXX
#include "treechangelist.hxx"
#endif
namespace configmgr
{
//-----------------------------------------------------------------------------
namespace configapi
{
//-----------------------------------------------------------------------------
using configuration::Tree;
using configuration::CommitHelper;
//-----------------------------------------------------------------------------
namespace
{
//-------------------------------------------------------------------------
struct NotifyDisabler
{
ApiRootTreeImpl& m_rTree;
bool m_bOldState;
NotifyDisabler(ApiRootTreeImpl& rTree)
: m_rTree(rTree)
, m_bOldState(rTree .enableNotification(false) )
{
}
~NotifyDisabler()
{
m_rTree.enableNotification(m_bOldState);
}
};
//-------------------------------------------------------------------------
}
//-----------------------------------------------------------------------------
// class Committer
//-----------------------------------------------------------------------------
Committer::Committer(ApiRootTreeImpl& rTree)
: m_rTree(rTree)
{}
//-----------------------------------------------------------------------------
ITreeManager* Committer::getUpdateProvider()
{
return &m_rTree.getApiTree().getProvider().getProviderImpl();
}
//-----------------------------------------------------------------------------
void Committer::commit()
{
ApiTreeImpl& rApiTree = m_rTree.getApiTree();
OSL_PRECOND(!m_rTree.getLocation().isRoot(),"INTERNAL ERROR: Empty location used.");
OSL_PRECOND(m_rTree.getOptions().isValid(),"INTERNAL ERROR: Invalid Options used.");
if (!m_rTree.getOptions().isValid()) return;
RequestOptions aOptions = m_rTree.getOptions()->getRequestOptions();
ITreeManager* pUpdateProvider = getUpdateProvider();
OSL_ASSERT(pUpdateProvider);
memory::Segment * pCacheSegment = pUpdateProvider->getDataSegment(m_rTree.getLocation(),aOptions);
OSL_ASSERT(rApiTree.getSourceData() == pCacheSegment);
memory::UpdateAccessor aUpdateAccessor(pCacheSegment);
osl::ClearableMutexGuard aLocalGuard(rApiTree.getDataLock());
Tree aTree( aUpdateAccessor.accessor(), rApiTree.getTree());
if (!aTree.hasChanges()) return;
TreeChangeList aChangeList(aOptions,
aTree.getRootPath(),
aTree.getAttributes(aTree.getRootNode()));
aTree.unbind();
// now do the commit
CommitHelper aHelper(rApiTree.getTree());
if (aHelper.prepareCommit(aUpdateAccessor.accessor(),aChangeList))
try
{
pUpdateProvider->updateTree(aUpdateAccessor,aChangeList);
aHelper.finishCommit(aUpdateAccessor.accessor(),aChangeList);
aLocalGuard.clear(); // done locally
data::Accessor aNotifyAccessor = aUpdateAccessor.downgrade(); // keep a read lock for notification
NotifyDisabler aDisableNotify(m_rTree); // do not notify self
pUpdateProvider->saveAndNotifyUpdate(aNotifyAccessor,aChangeList);
}
catch(...)
{
// should be a special clean-up routine, but for now we just need a consistent state
try
{
// aHelper.finishCommit(aChangeList);
aHelper.failedCommit(aUpdateAccessor.accessor(),aChangeList);
}
catch(configuration::Exception&)
{
OSL_ENSURE(false, "Cleanup really should not throw");
}
throw;
}
}
//-----------------------------------------------------------------------------
}
}
<commit_msg>INTEGRATION: CWS ooo19126 (1.14.194); FILE MERGED 2005/09/05 17:03:33 rt 1.14.194.1: #i54170# Change license header: remove SISSL<commit_after>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: committer.cxx,v $
*
* $Revision: 1.15 $
*
* last change: $Author: rt $ $Date: 2005-09-08 03:10:42 $
*
* 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
*
************************************************************************/
#include <stdio.h>
#include "committer.hxx"
#ifndef CONFIGMGR_API_TREEIMPLOBJECTS_HXX_
#include "apitreeimplobj.hxx"
#endif
#ifndef CONFIGMGR_ROOTTREE_HXX_
#include "roottree.hxx"
#endif
#ifndef CONFIGMGR_API_PROVIDERIMPL2_HXX_
#include "confproviderimpl2.hxx"
#endif
#ifndef CONFIGMGR_UPDATEACCESSOR_HXX
#include "updateaccessor.hxx"
#endif
#ifndef CONFIGMGR_TREEACCESSOR_HXX
#include "treeaccessor.hxx"
#endif
#ifndef CONFIGMGR_TREECHANGELIST_HXX
#include "treechangelist.hxx"
#endif
namespace configmgr
{
//-----------------------------------------------------------------------------
namespace configapi
{
//-----------------------------------------------------------------------------
using configuration::Tree;
using configuration::CommitHelper;
//-----------------------------------------------------------------------------
namespace
{
//-------------------------------------------------------------------------
struct NotifyDisabler
{
ApiRootTreeImpl& m_rTree;
bool m_bOldState;
NotifyDisabler(ApiRootTreeImpl& rTree)
: m_rTree(rTree)
, m_bOldState(rTree .enableNotification(false) )
{
}
~NotifyDisabler()
{
m_rTree.enableNotification(m_bOldState);
}
};
//-------------------------------------------------------------------------
}
//-----------------------------------------------------------------------------
// class Committer
//-----------------------------------------------------------------------------
Committer::Committer(ApiRootTreeImpl& rTree)
: m_rTree(rTree)
{}
//-----------------------------------------------------------------------------
ITreeManager* Committer::getUpdateProvider()
{
return &m_rTree.getApiTree().getProvider().getProviderImpl();
}
//-----------------------------------------------------------------------------
void Committer::commit()
{
ApiTreeImpl& rApiTree = m_rTree.getApiTree();
OSL_PRECOND(!m_rTree.getLocation().isRoot(),"INTERNAL ERROR: Empty location used.");
OSL_PRECOND(m_rTree.getOptions().isValid(),"INTERNAL ERROR: Invalid Options used.");
if (!m_rTree.getOptions().isValid()) return;
RequestOptions aOptions = m_rTree.getOptions()->getRequestOptions();
ITreeManager* pUpdateProvider = getUpdateProvider();
OSL_ASSERT(pUpdateProvider);
memory::Segment * pCacheSegment = pUpdateProvider->getDataSegment(m_rTree.getLocation(),aOptions);
OSL_ASSERT(rApiTree.getSourceData() == pCacheSegment);
memory::UpdateAccessor aUpdateAccessor(pCacheSegment);
osl::ClearableMutexGuard aLocalGuard(rApiTree.getDataLock());
Tree aTree( aUpdateAccessor.accessor(), rApiTree.getTree());
if (!aTree.hasChanges()) return;
TreeChangeList aChangeList(aOptions,
aTree.getRootPath(),
aTree.getAttributes(aTree.getRootNode()));
aTree.unbind();
// now do the commit
CommitHelper aHelper(rApiTree.getTree());
if (aHelper.prepareCommit(aUpdateAccessor.accessor(),aChangeList))
try
{
pUpdateProvider->updateTree(aUpdateAccessor,aChangeList);
aHelper.finishCommit(aUpdateAccessor.accessor(),aChangeList);
aLocalGuard.clear(); // done locally
data::Accessor aNotifyAccessor = aUpdateAccessor.downgrade(); // keep a read lock for notification
NotifyDisabler aDisableNotify(m_rTree); // do not notify self
pUpdateProvider->saveAndNotifyUpdate(aNotifyAccessor,aChangeList);
}
catch(...)
{
// should be a special clean-up routine, but for now we just need a consistent state
try
{
// aHelper.finishCommit(aChangeList);
aHelper.failedCommit(aUpdateAccessor.accessor(),aChangeList);
}
catch(configuration::Exception&)
{
OSL_ENSURE(false, "Cleanup really should not throw");
}
throw;
}
}
//-----------------------------------------------------------------------------
}
}
<|endoftext|> |
<commit_before><commit_msg>coverity#704924 Unchecked dynamic_cast<commit_after><|endoftext|> |
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: xmlstrings.cxx,v $
*
* $Revision: 1.8 $
*
* last change: $Author: hr $ $Date: 2006-04-19 14:02:10 $
*
* 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
*
************************************************************************/
#include "xmlstrings.hxx"
//.........................................................................
namespace configmgr
{
//.........................................................................
namespace xml
{
//----------------------------------------------------------------------------
// For now: Include the fixed OOR prefix into (most) attribute names
#define OOR_PREFIX_ "oor:"
// ... but not into (most) tag names
#define OOR_TAG_PREFIX_
// ... but into root tag names
#define OOR_ROOTTAG_PREFIX_ OOR_PREFIX_
//----------------------------------------------------------------------------
// extern declaration for strings used in the XML format
// namespace prefixes
IMPLEMENT_CONSTASCII_USTRING(NS_PREFIX_OOR, "oor");
IMPLEMENT_CONSTASCII_USTRING(NS_PREFIX_XS, "xs");
// namespace urls
IMPLEMENT_CONSTASCII_USTRING(NS_URI_OOR,"http://openoffice.org/2001/registry");
IMPLEMENT_CONSTASCII_USTRING(NS_URI_XS, "http://www.w3.org/2001/XMLSchema");
// tag names
IMPLEMENT_CONSTASCII_USTRING(TAG_SCHEMA, OOR_ROOTTAG_PREFIX_"component-schema");
IMPLEMENT_CONSTASCII_USTRING(TAG_LAYER, OOR_ROOTTAG_PREFIX_"component-data");
IMPLEMENT_CONSTASCII_USTRING(DEPRECATED_TAG_LAYER, OOR_ROOTTAG_PREFIX_"node");
IMPLEMENT_CONSTASCII_USTRING(TAG_COMPONENT, OOR_TAG_PREFIX_"component");
IMPLEMENT_CONSTASCII_USTRING(TAG_TEMPLATES, OOR_TAG_PREFIX_"templates");
IMPLEMENT_CONSTASCII_USTRING(TAG_NODE, OOR_TAG_PREFIX_"node");
IMPLEMENT_CONSTASCII_USTRING(TAG_GROUP, OOR_TAG_PREFIX_"group");
IMPLEMENT_CONSTASCII_USTRING(TAG_SET, OOR_TAG_PREFIX_"set");
IMPLEMENT_CONSTASCII_USTRING(TAG_PROP, OOR_TAG_PREFIX_"prop");
IMPLEMENT_CONSTASCII_USTRING(TAG_VALUE, OOR_TAG_PREFIX_"value");
IMPLEMENT_CONSTASCII_USTRING(TAG_IMPORT, OOR_TAG_PREFIX_"import");
IMPLEMENT_CONSTASCII_USTRING(TAG_INSTANCE, OOR_TAG_PREFIX_"node-ref");
IMPLEMENT_CONSTASCII_USTRING(TAG_ITEMTYPE, OOR_TAG_PREFIX_"item");
IMPLEMENT_CONSTASCII_USTRING(TAG_USES, OOR_TAG_PREFIX_"uses");
// attribute names
IMPLEMENT_CONSTASCII_USTRING(ATTR_NAME, OOR_PREFIX_"name");
IMPLEMENT_CONSTASCII_USTRING(ATTR_CONTEXT, OOR_PREFIX_"context");
IMPLEMENT_CONSTASCII_USTRING(ATTR_PACKAGE, OOR_PREFIX_"package");
IMPLEMENT_CONSTASCII_USTRING(ATTR_COMPONENT,OOR_PREFIX_"component");
IMPLEMENT_CONSTASCII_USTRING(ATTR_ITEMTYPE, OOR_PREFIX_"node-type");
IMPLEMENT_CONSTASCII_USTRING(ATTR_ITEMTYPECOMPONENT,OOR_PREFIX_"component");
IMPLEMENT_CONSTASCII_USTRING(ATTR_VALUETYPE, OOR_PREFIX_"type");
IMPLEMENT_CONSTASCII_USTRING(ATTR_VALUESEPARATOR, OOR_PREFIX_"separator");
IMPLEMENT_CONSTASCII_USTRING(ATTR_FLAG_EXTENSIBLE, OOR_PREFIX_"extensible");
IMPLEMENT_CONSTASCII_USTRING(ATTR_FLAG_FINALIZED, OOR_PREFIX_"finalized");
IMPLEMENT_CONSTASCII_USTRING(ATTR_FLAG_READONLY, OOR_PREFIX_"readonly");
IMPLEMENT_CONSTASCII_USTRING(ATTR_FLAG_MANDATORY, OOR_PREFIX_"mandatory");
IMPLEMENT_CONSTASCII_USTRING(ATTR_FLAG_NULLABLE, OOR_PREFIX_"nillable");
IMPLEMENT_CONSTASCII_USTRING(ATTR_FLAG_LOCALIZED, OOR_PREFIX_"localized");
IMPLEMENT_CONSTASCII_USTRING(ATTR_OPERATION, OOR_PREFIX_"op");
// attributes defined elsewhere
IMPLEMENT_CONSTASCII_USTRING(EXT_ATTR_LANGUAGE, "xml:lang");
IMPLEMENT_CONSTASCII_USTRING(EXT_ATTR_NULL, "xsi:nil");
// attribute contents
// boolean constants
IMPLEMENT_CONSTASCII_USTRING(ATTR_VALUE_TRUE, "true");
IMPLEMENT_CONSTASCII_USTRING(ATTR_VALUE_FALSE, "false");
// simple types names
IMPLEMENT_CONSTASCII_USTRING(VALUETYPE_BOOLEAN, "boolean");
IMPLEMENT_CONSTASCII_USTRING(VALUETYPE_SHORT, "short");
IMPLEMENT_CONSTASCII_USTRING(VALUETYPE_INT, "int");
IMPLEMENT_CONSTASCII_USTRING(VALUETYPE_LONG, "long");
IMPLEMENT_CONSTASCII_USTRING(VALUETYPE_DOUBLE, "double");
IMPLEMENT_CONSTASCII_USTRING(VALUETYPE_STRING, "string");
// Type: Sequence<bytes>
IMPLEMENT_CONSTASCII_USTRING(VALUETYPE_BINARY, "hexBinary");
// Universal type: Any
IMPLEMENT_CONSTASCII_USTRING(VALUETYPE_ANY, "any");
// modifier suffix for list types
IMPLEMENT_CONSTASCII_USTRING(VALUETYPE_LIST_SUFFIX, "-list");
// States for update actions
IMPLEMENT_CONSTASCII_USTRING(OPERATION_MODIFY, "modify");
IMPLEMENT_CONSTASCII_USTRING(OPERATION_REPLACE, "replace");
IMPLEMENT_CONSTASCII_USTRING(OPERATION_FUSE, "fuse");
IMPLEMENT_CONSTASCII_USTRING(OPERATION_REMOVE, "remove");
// the default separator for strings
IMPLEMENT_CONSTASCII_USTRING(SEPARATOR_WHITESPACE, " ");
// Needed for building attribute lists
IMPLEMENT_CONSTASCII_USTRING(XML_ATTRTYPE_CDATA, "CDATA");
} // namespace xml
} // namespace configmgr
<commit_msg>INTEGRATION: CWS pchfix02 (1.8.28); FILE MERGED 2006/09/01 17:20:54 kaib 1.8.28.1: #i68856# Added header markers and pch files<commit_after>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: xmlstrings.cxx,v $
*
* $Revision: 1.9 $
*
* last change: $Author: obo $ $Date: 2006-09-16 15:36:38 $
*
* 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_configmgr.hxx"
#include "xmlstrings.hxx"
//.........................................................................
namespace configmgr
{
//.........................................................................
namespace xml
{
//----------------------------------------------------------------------------
// For now: Include the fixed OOR prefix into (most) attribute names
#define OOR_PREFIX_ "oor:"
// ... but not into (most) tag names
#define OOR_TAG_PREFIX_
// ... but into root tag names
#define OOR_ROOTTAG_PREFIX_ OOR_PREFIX_
//----------------------------------------------------------------------------
// extern declaration for strings used in the XML format
// namespace prefixes
IMPLEMENT_CONSTASCII_USTRING(NS_PREFIX_OOR, "oor");
IMPLEMENT_CONSTASCII_USTRING(NS_PREFIX_XS, "xs");
// namespace urls
IMPLEMENT_CONSTASCII_USTRING(NS_URI_OOR,"http://openoffice.org/2001/registry");
IMPLEMENT_CONSTASCII_USTRING(NS_URI_XS, "http://www.w3.org/2001/XMLSchema");
// tag names
IMPLEMENT_CONSTASCII_USTRING(TAG_SCHEMA, OOR_ROOTTAG_PREFIX_"component-schema");
IMPLEMENT_CONSTASCII_USTRING(TAG_LAYER, OOR_ROOTTAG_PREFIX_"component-data");
IMPLEMENT_CONSTASCII_USTRING(DEPRECATED_TAG_LAYER, OOR_ROOTTAG_PREFIX_"node");
IMPLEMENT_CONSTASCII_USTRING(TAG_COMPONENT, OOR_TAG_PREFIX_"component");
IMPLEMENT_CONSTASCII_USTRING(TAG_TEMPLATES, OOR_TAG_PREFIX_"templates");
IMPLEMENT_CONSTASCII_USTRING(TAG_NODE, OOR_TAG_PREFIX_"node");
IMPLEMENT_CONSTASCII_USTRING(TAG_GROUP, OOR_TAG_PREFIX_"group");
IMPLEMENT_CONSTASCII_USTRING(TAG_SET, OOR_TAG_PREFIX_"set");
IMPLEMENT_CONSTASCII_USTRING(TAG_PROP, OOR_TAG_PREFIX_"prop");
IMPLEMENT_CONSTASCII_USTRING(TAG_VALUE, OOR_TAG_PREFIX_"value");
IMPLEMENT_CONSTASCII_USTRING(TAG_IMPORT, OOR_TAG_PREFIX_"import");
IMPLEMENT_CONSTASCII_USTRING(TAG_INSTANCE, OOR_TAG_PREFIX_"node-ref");
IMPLEMENT_CONSTASCII_USTRING(TAG_ITEMTYPE, OOR_TAG_PREFIX_"item");
IMPLEMENT_CONSTASCII_USTRING(TAG_USES, OOR_TAG_PREFIX_"uses");
// attribute names
IMPLEMENT_CONSTASCII_USTRING(ATTR_NAME, OOR_PREFIX_"name");
IMPLEMENT_CONSTASCII_USTRING(ATTR_CONTEXT, OOR_PREFIX_"context");
IMPLEMENT_CONSTASCII_USTRING(ATTR_PACKAGE, OOR_PREFIX_"package");
IMPLEMENT_CONSTASCII_USTRING(ATTR_COMPONENT,OOR_PREFIX_"component");
IMPLEMENT_CONSTASCII_USTRING(ATTR_ITEMTYPE, OOR_PREFIX_"node-type");
IMPLEMENT_CONSTASCII_USTRING(ATTR_ITEMTYPECOMPONENT,OOR_PREFIX_"component");
IMPLEMENT_CONSTASCII_USTRING(ATTR_VALUETYPE, OOR_PREFIX_"type");
IMPLEMENT_CONSTASCII_USTRING(ATTR_VALUESEPARATOR, OOR_PREFIX_"separator");
IMPLEMENT_CONSTASCII_USTRING(ATTR_FLAG_EXTENSIBLE, OOR_PREFIX_"extensible");
IMPLEMENT_CONSTASCII_USTRING(ATTR_FLAG_FINALIZED, OOR_PREFIX_"finalized");
IMPLEMENT_CONSTASCII_USTRING(ATTR_FLAG_READONLY, OOR_PREFIX_"readonly");
IMPLEMENT_CONSTASCII_USTRING(ATTR_FLAG_MANDATORY, OOR_PREFIX_"mandatory");
IMPLEMENT_CONSTASCII_USTRING(ATTR_FLAG_NULLABLE, OOR_PREFIX_"nillable");
IMPLEMENT_CONSTASCII_USTRING(ATTR_FLAG_LOCALIZED, OOR_PREFIX_"localized");
IMPLEMENT_CONSTASCII_USTRING(ATTR_OPERATION, OOR_PREFIX_"op");
// attributes defined elsewhere
IMPLEMENT_CONSTASCII_USTRING(EXT_ATTR_LANGUAGE, "xml:lang");
IMPLEMENT_CONSTASCII_USTRING(EXT_ATTR_NULL, "xsi:nil");
// attribute contents
// boolean constants
IMPLEMENT_CONSTASCII_USTRING(ATTR_VALUE_TRUE, "true");
IMPLEMENT_CONSTASCII_USTRING(ATTR_VALUE_FALSE, "false");
// simple types names
IMPLEMENT_CONSTASCII_USTRING(VALUETYPE_BOOLEAN, "boolean");
IMPLEMENT_CONSTASCII_USTRING(VALUETYPE_SHORT, "short");
IMPLEMENT_CONSTASCII_USTRING(VALUETYPE_INT, "int");
IMPLEMENT_CONSTASCII_USTRING(VALUETYPE_LONG, "long");
IMPLEMENT_CONSTASCII_USTRING(VALUETYPE_DOUBLE, "double");
IMPLEMENT_CONSTASCII_USTRING(VALUETYPE_STRING, "string");
// Type: Sequence<bytes>
IMPLEMENT_CONSTASCII_USTRING(VALUETYPE_BINARY, "hexBinary");
// Universal type: Any
IMPLEMENT_CONSTASCII_USTRING(VALUETYPE_ANY, "any");
// modifier suffix for list types
IMPLEMENT_CONSTASCII_USTRING(VALUETYPE_LIST_SUFFIX, "-list");
// States for update actions
IMPLEMENT_CONSTASCII_USTRING(OPERATION_MODIFY, "modify");
IMPLEMENT_CONSTASCII_USTRING(OPERATION_REPLACE, "replace");
IMPLEMENT_CONSTASCII_USTRING(OPERATION_FUSE, "fuse");
IMPLEMENT_CONSTASCII_USTRING(OPERATION_REMOVE, "remove");
// the default separator for strings
IMPLEMENT_CONSTASCII_USTRING(SEPARATOR_WHITESPACE, " ");
// Needed for building attribute lists
IMPLEMENT_CONSTASCII_USTRING(XML_ATTRTYPE_CDATA, "CDATA");
} // namespace xml
} // namespace configmgr
<|endoftext|> |
<commit_before>//
// ElevationData.cpp
// G3MiOSSDK
//
// Created by Diego Gomez Deck on 2/17/13.
//
//
#include "ElevationData.hpp"
#include "Vector2I.hpp"
#include "FloatBufferBuilderFromGeodetic.hpp"
#include "FloatBufferBuilderFromColor.hpp"
#include "DirectMesh.hpp"
#include "GLConstants.hpp"
#include "BilinearInterpolator.hpp"
ElevationData::ElevationData(const Sector& sector,
const Vector2I& extent) :
_sector(sector),
_width(extent._x),
_height(extent._y),
_resolution(sector._deltaLatitude.div(extent._y),
sector._deltaLongitude.div(extent._x)),
_interpolator(NULL)
{
}
ElevationData::~ElevationData() {
if (_interpolator != NULL) {
delete _interpolator;
}
}
double ElevationData::getElevationAt(const Vector2I& position) const {
return getElevationAt(position._x, position._y);
}
const Vector2I ElevationData::getExtent() const {
return Vector2I(_width, _height);
}
Mesh* ElevationData::createMesh(const Planet* planet,
float verticalExaggeration,
const Geodetic3D& positionOffset,
float pointSize,
const Sector& sector,
const Vector2I& resolution) const {
const Vector3D minMaxAverageElevations = getMinMaxAverageElevations();
const double minElevation = minMaxAverageElevations._x;
const double maxElevation = minMaxAverageElevations._y;
const double deltaElevation = maxElevation - minElevation;
const double averageElevation = minMaxAverageElevations._z;
ILogger::instance()->logInfo("Elevations: average=%f, min=%f max=%f delta=%f",
averageElevation, minElevation, maxElevation, deltaElevation);
// FloatBufferBuilderFromGeodetic vertices(CenterStrategy::firstVertex(),
// ellipsoid,
// Vector3D::zero);
// FloatBufferBuilderFromGeodetic vertices(CenterStrategy::givenCenter(),
// planet,
// sector._center);
FloatBufferBuilderFromGeodetic vertices = FloatBufferBuilderFromGeodetic::builderWithGivenCenter(planet, sector._center);
FloatBufferBuilderFromColor colors;
const Geodetic2D positionOffset2D = positionOffset.asGeodetic2D();
const int width = resolution._x;
const int height = resolution._y;
for (int x = 0; x < width; x++) {
const double u = (double) x / (width - 1);
for (int y = 0; y < height; y++) {
const double v = 1.0 - ( (double) y / (height - 1) );
const Geodetic2D position = sector.getInnerPoint(u, v);
const double elevation = getElevationAt(position);
if ( ISNAN(elevation) ) {
continue;
}
const float alpha = (float) ((elevation - minElevation) / deltaElevation);
const float r = alpha;
const float g = alpha;
const float b = alpha;
colors.add(r, g, b, 1);
vertices.add(position.add(positionOffset2D),
positionOffset._height + (elevation * verticalExaggeration));
}
}
// for (int x = 0; x < _width; x++) {
// const double u = (double) x / (_width - 1);
//
// for (int y = 0; y < _height; y++) {
// const double v = 1.0 - ( (double) y / (_height - 1) );
// const Geodetic2D position = _sector.getInnerPoint(u, v);
// if (!sector.contains(position)) {
// continue;
// }
//
// const double elevation = getElevationAt(x, y);
// if (mu->isNan(elevation)) {
// continue;
// }
//
// vertices.add(position.add(positionOffset2D),
// positionOffset._height + (elevation * verticalExaggeration));
//
//
// const float alpha = (float) ((elevation - minElevation) / deltaElevation);
// const float r = alpha;
// const float g = alpha;
// const float b = alpha;
// colors.add(r, g, b, 1);
// }
// }
const float lineWidth = 1;
Color* flatColor = NULL;
return new DirectMesh(GLPrimitive::points(),
//GLPrimitive::lineStrip(),
true,
vertices.getCenter(),
vertices.create(),
lineWidth,
pointSize,
flatColor,
colors.create(),
0,
false);
}
Mesh* ElevationData::createMesh(const Planet* planet,
float verticalExaggeration,
const Geodetic3D& positionOffset,
float pointSize) const {
const Vector3D minMaxAverageElevations = getMinMaxAverageElevations();
const double minElevation = minMaxAverageElevations._x;
const double maxElevation = minMaxAverageElevations._y;
const double deltaElevation = maxElevation - minElevation;
const double averageElevation = minMaxAverageElevations._z;
ILogger::instance()->logInfo("Elevations: average=%f, min=%f max=%f delta=%f",
averageElevation, minElevation, maxElevation, deltaElevation);
// FloatBufferBuilderFromGeodetic vertices(CenterStrategy::firstVertex(),
// planet,
// Vector3D::zero);
FloatBufferBuilderFromGeodetic vertices = FloatBufferBuilderFromGeodetic::builderWithFirstVertexAsCenter(planet);
FloatBufferBuilderFromColor colors;
const Geodetic2D positionOffset2D = positionOffset.asGeodetic2D();
for (int x = 0; x < _width; x++) {
const double u = (double) x / (_width - 1);
for (int y = 0; y < _height; y++) {
const double elevation = getElevationAt(x, y);
if (ISNAN(elevation)) {
continue;
}
const float alpha = (float) ((elevation - minElevation) / deltaElevation);
const float r = alpha;
const float g = alpha;
const float b = alpha;
colors.add(r, g, b, 1);
const double v = 1.0 - ( (double) y / (_height - 1) );
const Geodetic2D position = _sector.getInnerPoint(u, v).add(positionOffset2D);
vertices.add(position,
positionOffset._height + (elevation * verticalExaggeration));
}
}
const float lineWidth = 1;
Color* flatColor = NULL;
return new DirectMesh(GLPrimitive::points(),
//GLPrimitive::lineStrip(),
true,
vertices.getCenter(),
vertices.create(),
lineWidth,
pointSize,
flatColor,
colors.create(),
0,
false);
}
Interpolator* ElevationData::getInterpolator() const {
if (_interpolator == NULL) {
_interpolator = new BilinearInterpolator();
}
return _interpolator;
}
double ElevationData::getElevationAt(const Angle& latitude,
const Angle& longitude) const {
const IMathUtils* mu = IMathUtils::instance();
const double nanD = mu->NanD();
int _CHECK; // evaluate if this condition can be rewrited using (uv < 0 || uv > 1)
if (!_sector.contains(latitude, longitude)) {
// ILogger::instance()->logError("Sector %s doesn't contain lat=%s lon=%s",
// _sector.description().c_str(),
// latitude.description().c_str(),
// longitude.description().c_str());
return nanD;
}
const Vector2D uv = _sector.getUVCoordinates(latitude, longitude);
const double u = mu->clamp(uv._x, 0, 1);
const double v = mu->clamp(uv._y, 0, 1);
const double dX = u * (_width - 1);
const double dY = (1.0 - v) * (_height - 1);
const int x = (int) dX;
const int y = (int) dY;
const int nextX = x + 1;
const int nextY = y + 1;
const double alphaY = dY - y;
const double alphaX = dX - x;
double result;
if (x == dX) {
if (y == dY) {
// exact on grid point
result = getElevationAt(x, y);
}
else {
// linear on Y
const double heightY = getElevationAt(x, y);
if (ISNAN(heightY)) {
return nanD;
}
const double heightNextY = getElevationAt(x, nextY);
if (ISNAN(heightNextY)) {
return nanD;
}
result = mu->linearInterpolation(heightNextY, heightY, alphaY);
}
}
else {
if (y == dY) {
// linear on X
const double heightX = getElevationAt(x, y);
if (ISNAN(heightX)) {
return nanD;
}
const double heightNextX = getElevationAt(nextX, y);
if (ISNAN(heightNextX)) {
return nanD;
}
result = mu->linearInterpolation(heightX, heightNextX, alphaX);
}
else {
// bilinear
const double valueNW = getElevationAt(x, y);
if (ISNAN(valueNW)) {
return nanD;
}
const double valueNE = getElevationAt(nextX, y);
if (ISNAN(valueNE)) {
return nanD;
}
const double valueSE = getElevationAt(nextX, nextY);
if (ISNAN(valueSE)) {
return nanD;
}
const double valueSW = getElevationAt(x, nextY);
if (ISNAN(valueSW)) {
return nanD;
}
result = getInterpolator()->interpolation(valueSW,
valueSE,
valueNE,
valueNW,
alphaX,
alphaY);
}
}
return result;
}
<commit_msg>testing ios<commit_after>//
// ElevationData.cpp
// G3MiOSSDK
//
// Created by Diego Gomez Deck on 2/17/13.
//
//
#include "ElevationData.hpp"
#include "Vector2I.hpp"
#include "FloatBufferBuilderFromGeodetic.hpp"
#include "FloatBufferBuilderFromColor.hpp"
#include "DirectMesh.hpp"
#include "GLConstants.hpp"
#include "BilinearInterpolator.hpp"
ElevationData::ElevationData(const Sector& sector,
const Vector2I& extent) :
_sector(sector),
_width(extent._x),
_height(extent._y),
_resolution(sector._deltaLatitude.div(extent._y),
sector._deltaLongitude.div(extent._x)),
_interpolator(NULL)
{
}
ElevationData::~ElevationData() {
if (_interpolator != NULL) {
delete _interpolator;
}
}
double ElevationData::getElevationAt(const Vector2I& position) const {
return getElevationAt(position._x, position._y);
}
const Vector2I ElevationData::getExtent() const {
return Vector2I(_width, _height);
}
Mesh* ElevationData::createMesh(const Planet* planet,
float verticalExaggeration,
const Geodetic3D& positionOffset,
float pointSize,
const Sector& sector,
const Vector2I& resolution) const {
const Vector3D minMaxAverageElevations = getMinMaxAverageElevations();
const double minElevation = minMaxAverageElevations._x;
const double maxElevation = minMaxAverageElevations._y;
const double deltaElevation = maxElevation - minElevation;
const double averageElevation = minMaxAverageElevations._z;
ILogger::instance()->logInfo("Elevations: average=%f, min=%f max=%f delta=%f",
averageElevation, minElevation, maxElevation, deltaElevation);
// FloatBufferBuilderFromGeodetic vertices(CenterStrategy::firstVertex(),
// ellipsoid,
// Vector3D::zero);
// FloatBufferBuilderFromGeodetic vertices(CenterStrategy::givenCenter(),
// planet,
// sector._center);
FloatBufferBuilderFromGeodetic vertices = FloatBufferBuilderFromGeodetic::builderWithGivenCenter(planet, sector._center);
FloatBufferBuilderFromColor colors;
const Geodetic2D positionOffset2D = positionOffset.asGeodetic2D();
const int width = resolution._x;
const int height = resolution._y;
for (int x = 0; x < width; x++) {
const double u = (double) x / (width - 1);
for (int y = 0; y < height; y++) {
const double v = 1.0 - ( (double) y / (height - 1) );
const Geodetic2D position = sector.getInnerPoint(u, v);
const double elevation = getElevationAt(position);
if ( ISNAN(elevation) ) {
continue;
}
const float alpha = (float) ((elevation - minElevation) / deltaElevation);
const float r = alpha;
const float g = alpha;
const float b = alpha;
colors.add(r, g, b, 1);
vertices.add(position.add(positionOffset2D),
positionOffset._height + (elevation * verticalExaggeration));
}
}
// for (int x = 0; x < _width; x++) {
// const double u = (double) x / (_width - 1);
//
// for (int y = 0; y < _height; y++) {
// const double v = 1.0 - ( (double) y / (_height - 1) );
// const Geodetic2D position = _sector.getInnerPoint(u, v);
// if (!sector.contains(position)) {
// continue;
// }
//
// const double elevation = getElevationAt(x, y);
// if (mu->isNan(elevation)) {
// continue;
// }
//
// vertices.add(position.add(positionOffset2D),
// positionOffset._height + (elevation * verticalExaggeration));
//
//
// const float alpha = (float) ((elevation - minElevation) / deltaElevation);
// const float r = alpha;
// const float g = alpha;
// const float b = alpha;
// colors.add(r, g, b, 1);
// }
// }
const float lineWidth = 1;
Color* flatColor = NULL;
return new DirectMesh(GLPrimitive::points(),
//GLPrimitive::lineStrip(),
true,
vertices.getCenter(),
vertices.create(),
lineWidth,
pointSize,
flatColor,
colors.create(),
0,
false);
}
Mesh* ElevationData::createMesh(const Planet* planet,
float verticalExaggeration,
const Geodetic3D& positionOffset,
float pointSize) const {
const Vector3D minMaxAverageElevations = getMinMaxAverageElevations();
const double minElevation = minMaxAverageElevations._x;
const double maxElevation = minMaxAverageElevations._y;
const double deltaElevation = maxElevation - minElevation;
const double averageElevation = minMaxAverageElevations._z;
ILogger::instance()->logInfo("Elevations: average=%f, min=%f max=%f delta=%f",
averageElevation, minElevation, maxElevation, deltaElevation);
// FloatBufferBuilderFromGeodetic vertices(CenterStrategy::firstVertex(),
// planet,
// Vector3D::zero);
FloatBufferBuilderFromGeodetic vertices = FloatBufferBuilderFromGeodetic::builderWithFirstVertexAsCenter(planet);
FloatBufferBuilderFromColor colors;
const Geodetic2D positionOffset2D = positionOffset.asGeodetic2D();
for (int x = 0; x < _width; x++) {
const double u = (double) x / (_width - 1);
for (int y = 0; y < _height; y++) {
const double elevation = getElevationAt(x, y);
if (ISNAN(elevation)) {
continue;
}
const float alpha = (float) ((elevation - minElevation) / deltaElevation);
const float r = alpha;
const float g = alpha;
const float b = alpha;
colors.add(r, g, b, 1);
const double v = 1.0 - ( (double) y / (_height - 1) );
const Geodetic2D position = _sector.getInnerPoint(u, v).add(positionOffset2D);
vertices.add(position,
positionOffset._height + (elevation * verticalExaggeration));
}
}
const float lineWidth = 1;
Color* flatColor = NULL;
return new DirectMesh(GLPrimitive::points(),
//GLPrimitive::lineStrip(),
true,
vertices.getCenter(),
vertices.create(),
lineWidth,
pointSize,
flatColor,
colors.create(),
0,
false);
}
Interpolator* ElevationData::getInterpolator() const {
if (_interpolator == NULL) {
_interpolator = new BilinearInterpolator();
}
return _interpolator;
}
double ElevationData::getElevationAt(const Angle& latitude,
const Angle& longitude) const {
const IMathUtils* mu = IMathUtils::instance();
const double nanD = mu->NanD();
const Vector2D uv = _sector.getUVCoordinates(latitude, longitude);
const double u = uv._x;
const double v = uv._y;
if (u < 0 || u > 1 || v < 0 || v > 1){
if (_sector.contains(latitude, longitude)){
printf("error");
}
return nanD;
}
// int _CHECK; // evaluate if this condition can be rewrited using (uv < 0 || uv > 1)
// if (!_sector.contains(latitude, longitude)) {
// // ILogger::instance()->logError("Sector %s doesn't contain lat=%s lon=%s",
// // _sector.description().c_str(),
// // latitude.description().c_str(),
// // longitude.description().c_str());
// return nanD;
// }
// const double u = mu->clamp(uv._x, 0, 1);
// const double v = mu->clamp(uv._y, 0, 1);
const double dX = u * (_width - 1);
const double dY = (1.0 - v) * (_height - 1);
const int x = (int) dX;
const int y = (int) dY;
const int nextX = x + 1;
const int nextY = y + 1;
const double alphaY = dY - y;
const double alphaX = dX - x;
double result;
if (x == dX) {
if (y == dY) {
// exact on grid point
result = getElevationAt(x, y);
}
else {
// linear on Y
const double heightY = getElevationAt(x, y);
if (ISNAN(heightY)) {
return nanD;
}
const double heightNextY = getElevationAt(x, nextY);
if (ISNAN(heightNextY)) {
return nanD;
}
result = mu->linearInterpolation(heightNextY, heightY, alphaY);
}
}
else {
if (y == dY) {
// linear on X
const double heightX = getElevationAt(x, y);
if (ISNAN(heightX)) {
return nanD;
}
const double heightNextX = getElevationAt(nextX, y);
if (ISNAN(heightNextX)) {
return nanD;
}
result = mu->linearInterpolation(heightX, heightNextX, alphaX);
}
else {
// bilinear
const double valueNW = getElevationAt(x, y);
if (ISNAN(valueNW)) {
return nanD;
}
const double valueNE = getElevationAt(nextX, y);
if (ISNAN(valueNE)) {
return nanD;
}
const double valueSE = getElevationAt(nextX, nextY);
if (ISNAN(valueSE)) {
return nanD;
}
const double valueSW = getElevationAt(x, nextY);
if (ISNAN(valueSW)) {
return nanD;
}
result = getInterpolator()->interpolation(valueSW,
valueSE,
valueNE,
valueNW,
alphaX,
alphaY);
}
}
return result;
}
<|endoftext|> |
<commit_before>#include "DiagonalMass.inl"
#include "Sofa/Components/Common/ObjectFactory.h"
#include "Sofa/Components/Common/Vec3Types.h"
#include "Sofa/Components/Common/RigidTypes.h"
#include "GL/Axis.h"
namespace Sofa
{
namespace Components
{
using namespace Common;
template <>
void DiagonalMass<RigidTypes, RigidMass>::draw()
{
const VecMass& masses = f_mass.getValue();
if (!getContext()->getShowBehaviorModels()) return;
VecCoord& x = *mmodel->getX();
for (unsigned int i=0; i<x.size(); i++)
{
const Quat& orient = x[i].getOrientation();
//orient[3] = -orient[3];
const RigidTypes::Vec3& center = x[i].getCenter();
RigidTypes::Vec3 len;
// The moment of inertia of a box is:
// m->_I(0,0) = M/REAL(12.0) * (ly*ly + lz*lz);
// m->_I(1,1) = M/REAL(12.0) * (lx*lx + lz*lz);
// m->_I(2,2) = M/REAL(12.0) * (lx*lx + ly*ly);
// So to get lx,ly,lz back we need to do
// lx = sqrt(12/M * (m->_I(1,1)+m->_I(2,2)-m->_I(0,0)))
// Note that RigidMass inertiaMatrix is already divided by M
double m00 = masses[i].inertiaMatrix[0][0];
double m11 = masses[i].inertiaMatrix[1][1];
double m22 = masses[i].inertiaMatrix[2][2];
len[0] = sqrt(m11+m22-m00);
len[1] = sqrt(m00+m22-m11);
len[2] = sqrt(m00+m11-m22);
GL::Axis::draw(center, orient, len);
}
}
SOFA_DECL_CLASS(DiagonalMass)
template class DiagonalMass<Vec3dTypes,double>;
template class DiagonalMass<Vec3fTypes,float>;
// specialization for rigid bodies
template <>
double DiagonalMass<RigidTypes,RigidMass>::getPotentialEnergy( const RigidTypes::VecCoord& x )
{
const VecMass& masses = f_mass.getValue();
double e = 0;
// gravity
Vec3d g ( this->getContext()->getLocalGravity() );
Deriv theGravity;
DataTypes::set
( theGravity, g[0], g[1], g[2]);
for (unsigned int i=0; i<masses.size(); i++)
{
e += g*masses[i].mass*x[i].getCenter();
}
return e;
}
template class DiagonalMass<RigidTypes,RigidMass>;
namespace Common // \todo Why this must be inside Common namespace
{
template<class Vec>
void readVec1(Vec& vec, const char* str)
{
vec.clear();
if (str==NULL) return;
const char* str2 = NULL;
for(;;)
{
double v = strtod(str,(char**)&str2);
if (str2==str) break;
str = str2;
vec.push_back((typename Vec::value_type)v);
}
}
template<class DataTypes, class MassType>
void create(DiagonalMass<DataTypes, MassType>*& obj, ObjectDescription* arg)
{
XML::createWithParent< DiagonalMass<DataTypes, MassType>, Core::MechanicalModel<DataTypes> >(obj, arg);
if (obj!=NULL)
{
obj->parseFields( arg->getAttributeMap() );
if (arg->getAttribute("filename"))
{
obj->load(arg->getAttribute("filename"));
}
/*
if (arg->getAttribute("gravity"))
{
double x=0;
double y=0;
double z=0;
sscanf(arg->getAttribute("gravity"),"%lf %lf %lf",&x,&y,&z);
typename DataTypes::Deriv g;
DataTypes::set(g,x,y,z);
obj->setGravity(g);
}
*/
if (arg->getAttribute("mass"))
{
std::vector<MassType> mass;
readVec1(mass,arg->getAttribute("mass"));
obj->clear();
for (unsigned int i=0; i<mass.size(); i++)
obj->addMass(mass[i]);
}
}
}
}
Creator< ObjectFactory, DiagonalMass<Vec3dTypes,double> > DiagonalMass3dClass("DiagonalMass",true);
Creator< ObjectFactory, DiagonalMass<Vec3fTypes,float > > DiagonalMass3fClass("DiagonalMass",true);
Creator< ObjectFactory, DiagonalMass<RigidTypes,RigidMass> > DiagonalMassRigidClass("DiagonalMass",true);
} // namespace Components
} // namespace Sofa
<commit_msg>r588/sofa-dev : removed warnings when loading from XML files<commit_after>#include "DiagonalMass.inl"
#include "Sofa/Components/Common/ObjectFactory.h"
#include "Sofa/Components/Common/Vec3Types.h"
#include "Sofa/Components/Common/RigidTypes.h"
#include "GL/Axis.h"
namespace Sofa
{
namespace Components
{
using namespace Common;
template <>
void DiagonalMass<RigidTypes, RigidMass>::draw()
{
const VecMass& masses = f_mass.getValue();
if (!getContext()->getShowBehaviorModels()) return;
VecCoord& x = *mmodel->getX();
for (unsigned int i=0; i<x.size(); i++)
{
const Quat& orient = x[i].getOrientation();
//orient[3] = -orient[3];
const RigidTypes::Vec3& center = x[i].getCenter();
RigidTypes::Vec3 len;
// The moment of inertia of a box is:
// m->_I(0,0) = M/REAL(12.0) * (ly*ly + lz*lz);
// m->_I(1,1) = M/REAL(12.0) * (lx*lx + lz*lz);
// m->_I(2,2) = M/REAL(12.0) * (lx*lx + ly*ly);
// So to get lx,ly,lz back we need to do
// lx = sqrt(12/M * (m->_I(1,1)+m->_I(2,2)-m->_I(0,0)))
// Note that RigidMass inertiaMatrix is already divided by M
double m00 = masses[i].inertiaMatrix[0][0];
double m11 = masses[i].inertiaMatrix[1][1];
double m22 = masses[i].inertiaMatrix[2][2];
len[0] = sqrt(m11+m22-m00);
len[1] = sqrt(m00+m22-m11);
len[2] = sqrt(m00+m11-m22);
GL::Axis::draw(center, orient, len);
}
}
SOFA_DECL_CLASS(DiagonalMass)
template class DiagonalMass<Vec3dTypes,double>;
template class DiagonalMass<Vec3fTypes,float>;
// specialization for rigid bodies
template <>
double DiagonalMass<RigidTypes,RigidMass>::getPotentialEnergy( const RigidTypes::VecCoord& x )
{
const VecMass& masses = f_mass.getValue();
double e = 0;
// gravity
Vec3d g ( this->getContext()->getLocalGravity() );
Deriv theGravity;
DataTypes::set
( theGravity, g[0], g[1], g[2]);
for (unsigned int i=0; i<masses.size(); i++)
{
e += g*masses[i].mass*x[i].getCenter();
}
return e;
}
template class DiagonalMass<RigidTypes,RigidMass>;
namespace Common // \todo Why this must be inside Common namespace
{
template<class Vec>
void readVec1(Vec& vec, const char* str)
{
vec.clear();
if (str==NULL) return;
const char* str2 = NULL;
for(;;)
{
double v = strtod(str,(char**)&str2);
if (str2==str) break;
str = str2;
vec.push_back((typename Vec::value_type)v);
}
}
template<class DataTypes, class MassType>
void create(DiagonalMass<DataTypes, MassType>*& obj, ObjectDescription* arg)
{
XML::createWithParent< DiagonalMass<DataTypes, MassType>, Core::MechanicalModel<DataTypes> >(obj, arg);
if (obj!=NULL)
{
if (arg->getAttribute("filename"))
{
obj->load(arg->getAttribute("filename"));
arg->removeAttribute("filename");
}
obj->parseFields( arg->getAttributeMap() );
/*
if (arg->getAttribute("gravity"))
{
double x=0;
double y=0;
double z=0;
sscanf(arg->getAttribute("gravity"),"%lf %lf %lf",&x,&y,&z);
typename DataTypes::Deriv g;
DataTypes::set(g,x,y,z);
obj->setGravity(g);
}
*/
if (arg->getAttribute("mass"))
{
std::vector<MassType> mass;
readVec1(mass,arg->getAttribute("mass"));
obj->clear();
for (unsigned int i=0; i<mass.size(); i++)
obj->addMass(mass[i]);
}
}
}
}
Creator< ObjectFactory, DiagonalMass<Vec3dTypes,double> > DiagonalMass3dClass("DiagonalMass",true);
Creator< ObjectFactory, DiagonalMass<Vec3fTypes,float > > DiagonalMass3fClass("DiagonalMass",true);
Creator< ObjectFactory, DiagonalMass<RigidTypes,RigidMass> > DiagonalMassRigidClass("DiagonalMass",true);
} // namespace Components
} // namespace Sofa
<|endoftext|> |
<commit_before>#include "irods_hasher_factory.hpp"
#include "md5Checksum.hpp"
#include "MD5Strategy.hpp"
#include "SHA256Strategy.hpp"
#include <sstream>
#include <boost/unordered_map.hpp>
namespace irods {
namespace {
boost::unordered_map<const std::string, const HashStrategy*>
make_map() {
boost::unordered_map<const std::string, const HashStrategy*> map;
map[ SHA256_NAME ] = new SHA256Strategy();
map[ MD5_NAME ] = new MD5Strategy();
return map;
}
const boost::unordered_map<const std::string, const HashStrategy*> _strategies( make_map() );
};
error
getHasher( const std::string& _name, Hasher& _hasher) {
boost::unordered_map<const std::string, const HashStrategy*>::const_iterator it = _strategies.find( _name );
if ( _strategies.end() == it ) {
std::stringstream msg;
msg << "Unknown hashing scheme [" << _name << "]";
return ERROR( SYS_INVALID_INPUT_PARAM, msg.str() );
}
_hasher.init(it->second);
return SUCCESS();
}
error
get_hash_scheme_from_checksum(
const std::string& _chksum,
std::string& _scheme ) {
if ( _chksum.empty() ) {
return ERROR(
SYS_INVALID_INPUT_PARAM,
"empty chksum string" );
}
for ( boost::unordered_map<const std::string, const HashStrategy*>::const_iterator it = _strategies.begin();
_strategies.end() != it; ++it ) {
if( it->second->isChecksum( _chksum ) ) {
_scheme = it->second->name();
return SUCCESS();
}
}
return ERROR(
SYS_INVALID_INPUT_PARAM,
"hash scheme not found" );
} // get_hasher_scheme_from_checksum
}; // namespace irods
<commit_msg>[#1376] stack-allocated the hash strategies, as they will never be freed<commit_after>#include "irods_hasher_factory.hpp"
#include "md5Checksum.hpp"
#include "MD5Strategy.hpp"
#include "SHA256Strategy.hpp"
#include <sstream>
#include <boost/unordered_map.hpp>
namespace irods {
namespace {
const SHA256Strategy _sha256;
const MD5Strategy _md5;
boost::unordered_map<const std::string, const HashStrategy*>
make_map() {
boost::unordered_map<const std::string, const HashStrategy*> map;
map[ SHA256_NAME ] = &_sha256;
map[ MD5_NAME ] = &_md5;
return map;
}
const boost::unordered_map<const std::string, const HashStrategy*> _strategies( make_map() );
};
error
getHasher( const std::string& _name, Hasher& _hasher) {
boost::unordered_map<const std::string, const HashStrategy*>::const_iterator it = _strategies.find( _name );
if ( _strategies.end() == it ) {
std::stringstream msg;
msg << "Unknown hashing scheme [" << _name << "]";
return ERROR( SYS_INVALID_INPUT_PARAM, msg.str() );
}
_hasher.init(it->second);
return SUCCESS();
}
error
get_hash_scheme_from_checksum(
const std::string& _chksum,
std::string& _scheme ) {
if ( _chksum.empty() ) {
return ERROR(
SYS_INVALID_INPUT_PARAM,
"empty chksum string" );
}
for ( boost::unordered_map<const std::string, const HashStrategy*>::const_iterator it = _strategies.begin();
_strategies.end() != it; ++it ) {
if( it->second->isChecksum( _chksum ) ) {
_scheme = it->second->name();
return SUCCESS();
}
}
return ERROR(
SYS_INVALID_INPUT_PARAM,
"hash scheme not found" );
} // get_hasher_scheme_from_checksum
}; // namespace irods
<|endoftext|> |
<commit_before>/*
Copyright (c) 2008, Arvid Norberg
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in
the documentation and/or other materials provided with the distribution.
* Neither the name of the author nor the names of its
contributors may be used to endorse or promote products derived
from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
*/
#include "libtorrent/session.hpp"
#include "libtorrent/session_settings.hpp"
#include "libtorrent/hasher.hpp"
#include "libtorrent/alert_types.hpp"
#include "libtorrent/bencode.hpp"
#include "libtorrent/thread.hpp"
#include "libtorrent/time.hpp"
#include "libtorrent/file.hpp"
#include <boost/tuple/tuple.hpp>
#include <boost/bind.hpp>
#include "test.hpp"
#include "setup_transfer.hpp"
#include <fstream>
#include <iostream>
using namespace libtorrent;
using boost::tuples::ignore;
void test_transfer()
{
// in case the previous run was terminated
error_code ec;
remove_all("./tmp1_utp", ec);
remove_all("./tmp2_utp", ec);
session ses1(fingerprint("LT", 0, 1, 0, 0), std::make_pair(48885, 49930), "0.0.0.0", 0);
session ses2(fingerprint("LT", 0, 1, 0, 0), std::make_pair(49885, 50930), "0.0.0.0", 0);
session_settings sett;
sett.enable_outgoing_tcp = false;
sett.min_reconnect_time = 1;
sett.announce_to_all_trackers = true;
sett.announce_to_all_tiers = true;
// make sure we announce to both http and udp trackers
sett.prefer_udp_trackers = false;
// for performance testing
// sett.disable_hash_checks = true;
// sett.utp_delayed_ack = 0;
// disable this to use regular size packets over loopback
// sett.utp_dynamic_sock_buf = false;
ses1.set_settings(sett);
ses2.set_settings(sett);
#ifndef TORRENT_DISABLE_ENCRYPTION
pe_settings pes;
pes.out_enc_policy = pe_settings::disabled;
pes.in_enc_policy = pe_settings::disabled;
ses1.set_pe_settings(pes);
ses2.set_pe_settings(pes);
#endif
torrent_handle tor1;
torrent_handle tor2;
create_directory("./tmp1_utp", ec);
std::ofstream file("./tmp1_utp/temporary");
boost::intrusive_ptr<torrent_info> t = ::create_torrent(&file, 16 * 1024, 1000, false);
file.close();
// for performance testing
add_torrent_params atp;
// atp.storage = &disabled_storage_constructor;
// test using piece sizes smaller than 16kB
boost::tie(tor1, tor2, ignore) = setup_transfer(&ses1, &ses2, 0
, true, false, true, "_utp", 8 * 1024, &t, false, &atp);
for (int i = 0; i < 300; ++i)
{
print_alerts(ses1, "ses1", true, true, true);
print_alerts(ses2, "ses2", true, true, true);
torrent_status st1 = tor1.status();
torrent_status st2 = tor2.status();
std::cerr
<< "\033[32m" << int(st1.download_payload_rate / 1000.f) << "kB/s "
<< "\033[33m" << int(st1.upload_payload_rate / 1000.f) << "kB/s "
<< "\033[0m" << int(st1.progress * 100) << "% "
<< st1.num_peers
<< ": "
<< "\033[32m" << int(st2.download_payload_rate / 1000.f) << "kB/s "
<< "\033[31m" << int(st2.upload_payload_rate / 1000.f) << "kB/s "
<< "\033[0m" << int(st2.progress * 100) << "% "
<< st2.num_peers
<< " cc: " << st2.connect_candidates
<< std::endl;
if (st2.is_finished) break;
TEST_CHECK(st1.state == torrent_status::seeding
|| st1.state == torrent_status::checking_files);
TEST_CHECK(st2.state == torrent_status::downloading);
test_sleep(500);
}
TEST_CHECK(tor1.status().is_finished);
TEST_CHECK(tor2.status().is_finished);
}
int test_main()
{
using namespace libtorrent;
test_transfer();
error_code ec;
remove_all("./tmp1_utp", ec);
remove_all("./tmp2_utp", ec);
return 0;
}
<commit_msg>make the utp test pass with full invariant checks enabled<commit_after>/*
Copyright (c) 2008, Arvid Norberg
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in
the documentation and/or other materials provided with the distribution.
* Neither the name of the author nor the names of its
contributors may be used to endorse or promote products derived
from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
*/
#include "libtorrent/session.hpp"
#include "libtorrent/session_settings.hpp"
#include "libtorrent/hasher.hpp"
#include "libtorrent/alert_types.hpp"
#include "libtorrent/bencode.hpp"
#include "libtorrent/thread.hpp"
#include "libtorrent/time.hpp"
#include "libtorrent/file.hpp"
#include <boost/tuple/tuple.hpp>
#include <boost/bind.hpp>
#include "test.hpp"
#include "setup_transfer.hpp"
#include <fstream>
#include <iostream>
using namespace libtorrent;
using boost::tuples::ignore;
void test_transfer()
{
// in case the previous run was terminated
error_code ec;
remove_all("./tmp1_utp", ec);
remove_all("./tmp2_utp", ec);
session ses1(fingerprint("LT", 0, 1, 0, 0), std::make_pair(48885, 49930), "0.0.0.0", 0);
session ses2(fingerprint("LT", 0, 1, 0, 0), std::make_pair(49885, 50930), "0.0.0.0", 0);
session_settings sett;
sett.enable_outgoing_tcp = false;
sett.min_reconnect_time = 1;
sett.announce_to_all_trackers = true;
sett.announce_to_all_tiers = true;
// make sure we announce to both http and udp trackers
sett.prefer_udp_trackers = false;
// for performance testing
// sett.disable_hash_checks = true;
// sett.utp_delayed_ack = 0;
// disable this to use regular size packets over loopback
// sett.utp_dynamic_sock_buf = false;
ses1.set_settings(sett);
ses2.set_settings(sett);
#ifndef TORRENT_DISABLE_ENCRYPTION
pe_settings pes;
pes.out_enc_policy = pe_settings::disabled;
pes.in_enc_policy = pe_settings::disabled;
ses1.set_pe_settings(pes);
ses2.set_pe_settings(pes);
#endif
torrent_handle tor1;
torrent_handle tor2;
create_directory("./tmp1_utp", ec);
std::ofstream file("./tmp1_utp/temporary");
boost::intrusive_ptr<torrent_info> t = ::create_torrent(&file, 512 * 1024, 20, false);
file.close();
// for performance testing
add_torrent_params atp;
// atp.storage = &disabled_storage_constructor;
// test using piece sizes smaller than 16kB
boost::tie(tor1, tor2, ignore) = setup_transfer(&ses1, &ses2, 0
, true, false, true, "_utp", 0, &t, false, &atp);
for (int i = 0; i < 300; ++i)
{
print_alerts(ses1, "ses1", true, true, true);
print_alerts(ses2, "ses2", true, true, true);
torrent_status st1 = tor1.status();
torrent_status st2 = tor2.status();
std::cerr
<< "\033[32m" << int(st1.download_payload_rate / 1000.f) << "kB/s "
<< "\033[33m" << int(st1.upload_payload_rate / 1000.f) << "kB/s "
<< "\033[0m" << int(st1.progress * 100) << "% "
<< st1.num_peers
<< ": "
<< "\033[32m" << int(st2.download_payload_rate / 1000.f) << "kB/s "
<< "\033[31m" << int(st2.upload_payload_rate / 1000.f) << "kB/s "
<< "\033[0m" << int(st2.progress * 100) << "% "
<< st2.num_peers
<< " cc: " << st2.connect_candidates
<< std::endl;
if (st2.is_finished) break;
TEST_CHECK(st1.state == torrent_status::seeding
|| st1.state == torrent_status::checking_files);
TEST_CHECK(st2.state == torrent_status::downloading);
test_sleep(500);
}
TEST_CHECK(tor1.status().is_finished);
TEST_CHECK(tor2.status().is_finished);
}
int test_main()
{
using namespace libtorrent;
test_transfer();
error_code ec;
remove_all("./tmp1_utp", ec);
remove_all("./tmp2_utp", ec);
return 0;
}
<|endoftext|> |
<commit_before>
/* dijkstra.c
Compute shortest paths in weighted graphs using Dijkstra's algorithm
by: Steven Skiena
date: March 6, 2002
*/
/*
Copyright 2003 by Steven S. Skiena; all rights reserved.
Permission is granted for use in non-commerical applications
provided this copyright notice remains intact and unchanged.
This program appears in my book:
"Programming Challenges: The Programming Contest Training Manual"
by Steven Skiena and Miguel Revilla, Springer-Verlag, New York 2003.
See our website www.programming-challenges.com for additional information.
This book can be ordered from Amazon.com at
http://www.amazon.com/exec/obidos/ASIN/0387001638/thealgorithmrepo/
*/
#include <iostream>
#include <map>
#include <string>
#include <utility>
#include <sstream>
#include <cstdio>
#include <cstdlib>
#include "wgraph.h"
using namespace std;
#define MAXINT 100007
int parent[MAXV]; /* discovery relation */
int firstHop[MAXV];
int distanceList[MAXV]; /* distance vertex is from start */
void dijkstra(graph *g, int start) /* WAS prim(g,start) */
{
int i,j; /* counters */
bool intree[MAXV]; /* is the vertex in the tree yet? */
int v; /* current vertex to process */
int w; /* candidate next vertex */
int weight; /* edge weight */
int dist; /* best current distance from start */
for (i=1; i<=g->nvertices; i++) {
intree[i] = false;
distanceList[i] = MAXINT;
parent[i] = -1;
}
distanceList[start] = 0;
v = start;
firstHop[v] = v;
while (intree[v] == false) {
intree[v] = true;
for (i=0; i<g->degree[v]; i++) {
w = g->edges[v][i].v;
weight = g->edges[v][i].weight;
/* CHANGED */ if (distanceList[w] > (distanceList[v]+weight)) {
/* CHANGED */ distanceList[w] = distanceList[v]+weight;
/* CHANGED */ parent[w] = v;
if (firstHop[v] == start)
{
firstHop[w] = w;
}
else
{
firstHop[w] = firstHop[v];
}
}
}
v = 1;
dist = MAXINT;
for (i=1; i<=g->nvertices; i++)
if ((intree[i] == false) && (dist > distanceList[i])) {
dist = distanceList[i];
v = i;
}
}
/*for (i=1; i<=g->nvertices; i++) printf("%d %d\n",i,distanceList[i]);*/
}
void print_route(graph * g, int source, int dest)
{
multimap< int, pair<string, string> >::iterator sourcePos;
sourcePos = g->ip[source].find(firstHop[dest]);
if (sourcePos == g->ip[source].end())
{
cerr << "ddijk: internal error: route not found" << endl;
exit(1);
}
multimap< int, pair<string, string> >::iterator pos;
pos = g->ip[dest].begin();
multimap< int, pair<string, string> >::iterator limit;
limit = g->ip[dest].end();
string sourceIp = sourcePos->second.first;
string firstHopIp = sourcePos->second.second;
for ( ; pos != limit; ++pos)
{
if (pos->second.first != firstHopIp)
{
cout << "ROUTE DEST=" << pos->second.first
<< " DESTTYPE=host DESTMASK=255.255.255.255 NEXTHOP="
<< firstHopIp << " COST=" << distanceList[dest] << " SRC="
<< sourceIp << endl;
}
}
}
int main(int argc, char * argv[])
{
if (argc == 2)
{
string arg(argv[1]);
string firstHost, secondHost;
string firstIp, secondIp;
map<string, int> nameToIndex;
int weight = 0;
graph g;
int i = 0;
int vertexCounter = 1;
int numEdges = 0;
initialize_graph(&g);
cin >> g.nvertices >> numEdges;
for (i = 1; i <= numEdges; ++i)
{
cin >> firstHost >> firstIp >> secondHost >> secondIp >> weight;
map<string,int>::iterator firstPos = nameToIndex.find(firstHost);
if (firstPos == nameToIndex.end())
{
firstPos = nameToIndex.insert(make_pair(firstHost,
vertexCounter)).first;
++vertexCounter;
}
map<string,int>::iterator secondPos = nameToIndex.find(secondHost);
if (secondPos == nameToIndex.end())
{
secondPos = nameToIndex.insert(make_pair(secondHost,
vertexCounter)).first;
++vertexCounter;
}
insert_edge(&g, firstPos->second, secondPos->second, false,
weight);
g.ip[firstPos->second].insert(make_pair(firstPos->second,
make_pair(firstIp,
secondIp)));
g.ip[secondPos->second].insert(make_pair(firstPos->second,
make_pair(secondIp,
firstIp)));
}
map<string,int>::iterator sourcePos = nameToIndex.find(arg);
if (sourcePos == nameToIndex.end())
{
cerr << "Invalid source name in command line" << endl;
return 1;
}
// read_graph(&g,false);
dijkstra(&g,sourcePos->second);
for (i=1; i<=g.nvertices; i++)
{
if (i != sourcePos->second)
{
print_route(&g,sourcePos->second,i);
}
// find_path(source,i,parent);
}
return 0;
}
else
{
cerr << "Incorrect number of arguments" << endl;
return 1;
}
}
<commit_msg>Fixed ip processing bug in distributed dijkstra<commit_after>
/* dijkstra.c
Compute shortest paths in weighted graphs using Dijkstra's algorithm
by: Steven Skiena
date: March 6, 2002
*/
/*
Copyright 2003 by Steven S. Skiena; all rights reserved.
Permission is granted for use in non-commerical applications
provided this copyright notice remains intact and unchanged.
This program appears in my book:
"Programming Challenges: The Programming Contest Training Manual"
by Steven Skiena and Miguel Revilla, Springer-Verlag, New York 2003.
See our website www.programming-challenges.com for additional information.
This book can be ordered from Amazon.com at
http://www.amazon.com/exec/obidos/ASIN/0387001638/thealgorithmrepo/
*/
#include <iostream>
#include <map>
#include <string>
#include <utility>
#include <sstream>
#include <cstdio>
#include <cstdlib>
#include "wgraph.h"
using namespace std;
#define MAXINT 100007
int parent[MAXV]; /* discovery relation */
int firstHop[MAXV];
int distanceList[MAXV]; /* distance vertex is from start */
void dijkstra(graph *g, int start) /* WAS prim(g,start) */
{
int i,j; /* counters */
bool intree[MAXV]; /* is the vertex in the tree yet? */
int v; /* current vertex to process */
int w; /* candidate next vertex */
int weight; /* edge weight */
int dist; /* best current distance from start */
for (i=1; i<=g->nvertices; i++) {
intree[i] = false;
distanceList[i] = MAXINT;
parent[i] = -1;
}
distanceList[start] = 0;
v = start;
firstHop[v] = v;
while (intree[v] == false) {
intree[v] = true;
for (i=0; i<g->degree[v]; i++) {
w = g->edges[v][i].v;
weight = g->edges[v][i].weight;
/* CHANGED */ if (distanceList[w] > (distanceList[v]+weight)) {
/* CHANGED */ distanceList[w] = distanceList[v]+weight;
/* CHANGED */ parent[w] = v;
if (firstHop[v] == start)
{
firstHop[w] = w;
}
else
{
firstHop[w] = firstHop[v];
}
}
}
v = 1;
dist = MAXINT;
for (i=1; i<=g->nvertices; i++)
if ((intree[i] == false) && (dist > distanceList[i])) {
dist = distanceList[i];
v = i;
}
}
/*for (i=1; i<=g->nvertices; i++) printf("%d %d\n",i,distanceList[i]);*/
}
void print_route(graph * g, int source, int dest)
{
multimap< int, pair<string, string> >::iterator sourcePos;
sourcePos = g->ip[source].find(firstHop[dest]);
if (sourcePos == g->ip[source].end())
{
cerr << "ddijk: internal error: route not found" << endl;
exit(1);
}
multimap< int, pair<string, string> >::iterator pos;
pos = g->ip[dest].begin();
multimap< int, pair<string, string> >::iterator limit;
limit = g->ip[dest].end();
string sourceIp = sourcePos->second.first;
string firstHopIp = sourcePos->second.second;
for ( ; pos != limit; ++pos)
{
if (pos->second.first != firstHopIp)
{
cout << "ROUTE DEST=" << pos->second.first
<< " DESTTYPE=host DESTMASK=255.255.255.255 NEXTHOP="
<< firstHopIp << " COST=" << distanceList[dest] << " SRC="
<< sourceIp << endl;
}
}
}
int main(int argc, char * argv[])
{
if (argc == 2)
{
string arg(argv[1]);
string firstHost, secondHost;
string firstIp, secondIp;
map<string, int> nameToIndex;
int weight = 0;
graph g;
int i = 0;
int vertexCounter = 1;
int numEdges = 0;
initialize_graph(&g);
cin >> g.nvertices >> numEdges;
for (i = 1; i <= numEdges; ++i)
{
cin >> firstHost >> firstIp >> secondHost >> secondIp >> weight;
map<string,int>::iterator firstPos = nameToIndex.find(firstHost);
if (firstPos == nameToIndex.end())
{
firstPos = nameToIndex.insert(make_pair(firstHost,
vertexCounter)).first;
++vertexCounter;
}
map<string,int>::iterator secondPos = nameToIndex.find(secondHost);
if (secondPos == nameToIndex.end())
{
secondPos = nameToIndex.insert(make_pair(secondHost,
vertexCounter)).first;
++vertexCounter;
}
insert_edge(&g, firstPos->second, secondPos->second, false,
weight);
g.ip[firstPos->second].insert(make_pair(secondPos->second,
make_pair(firstIp,
secondIp)));
g.ip[secondPos->second].insert(make_pair(firstPos->second,
make_pair(secondIp,
firstIp)));
}
map<string,int>::iterator sourcePos = nameToIndex.find(arg);
if (sourcePos == nameToIndex.end())
{
cerr << "Invalid source name in command line" << endl;
return 1;
}
// read_graph(&g,false);
dijkstra(&g,sourcePos->second);
for (i=1; i<=g.nvertices; i++)
{
if (i != sourcePos->second)
{
print_route(&g,sourcePos->second,i);
}
// find_path(source,i,parent);
}
return 0;
}
else
{
cerr << "Incorrect number of arguments" << endl;
return 1;
}
}
<|endoftext|> |
<commit_before>/**
* \file standard_gaussian.hpp
* \date May 2014
* \author Jan Issac (jan.issac@gmail.com)
* \author Manuel Wuthrich (manuel.wuthrich@gmail.com)
*/
#ifndef FL__DISTRIBUTION__STANDARD_GAUSSIAN_HPP
#define FL__DISTRIBUTION__STANDARD_GAUSSIAN_HPP
#include <Eigen/Dense>
#include <random>
#include <type_traits>
#include <fl/util/random.hpp>
#include <fl/util/traits.hpp>
#include <fl/util/math.hpp>
#include <fl/distribution/interface/sampling.hpp>
#include <fl/distribution/interface/moments.hpp>
#include <fl/exception/exception.hpp>
namespace fl
{
// Forward declaration
template <typename StandardVariate> class StandardGaussian;
/**
* \ingroup distributions
* Traits fo StandardGaussian<StandardVariate>
*/
template <typename StandardVariate>
struct Traits<
StandardGaussian<StandardVariate>
>
{
typedef StandardVariate Variate;
typedef typename Variate::Scalar Scalar;
typedef Eigen::Matrix<Scalar, Variate::SizeAtCompileTime, 1> SecondMoment;
typedef Moments<StandardVariate, SecondMoment> MomentsBase;
};
/**
* \ingroup distributions
*/
template <typename StandardVariate>
class StandardGaussian
: public Sampling<StandardVariate>,
public Traits<StandardGaussian<StandardVariate>>::MomentsBase
{
public:
/** Typdef of \c This for #from_traits(TypeName) helper */
typedef StandardGaussian This;
typedef from_traits(Variate);
typedef from_traits(SecondMoment);
public:
explicit
StandardGaussian(int dim = DimensionOf<StandardVariate>())
: dimension_ (dim),
generator_(fl::seed()),
gaussian_distribution_(0.0, 1.0)
{
}
virtual ~StandardGaussian() { }
virtual StandardVariate sample() const
{
StandardVariate gaussian_sample(dimension(), 1);
for (int i = 0; i < dimension(); i++)
{
gaussian_sample(i, 0) = gaussian_distribution_(generator_);
}
return gaussian_sample;
}
virtual int dimension() const
{
return dimension_;
}
virtual void dimension(int new_dimension)
{
if (dimension_ == new_dimension) return;
if (fl::IsFixed<StandardVariate::SizeAtCompileTime>())
{
fl_throw(
fl::ResizingFixedSizeEntityException(dimension_,
new_dimension,
"Gaussian"));
}
dimension_ = new_dimension;
}
virtual Variate mean() const
{
Variate mu;
mu.setZero(dimension(), 1);
return mu;
}
virtual SecondMoment covariance() const
{
SecondMoment cov;
cov.setIdentity(dimension(), dimension());
return cov;
}
private:
int dimension_;
// mutable std::default_random_engine generator_;
// mutable std::normal_distribution<double> gaussian_distribution_;
mutable fl::mt11213b generator_;
mutable std::normal_distribution<> gaussian_distribution_;
};
/** \cond IMPL_DETAILS */
/**
* Floating point implementation for Scalar types float, double and long double
*/
template <typename Scalar>
class StandardGaussianFloatingPointScalarImpl
: Moments<Scalar, Scalar>
{
static_assert(
std::is_floating_point<Scalar>::value,
"Scalar must be a floating point (float, double, long double)");
public:
StandardGaussianFloatingPointScalarImpl()
: generator_(fl::seed()),
gaussian_distribution_(Scalar(0.), Scalar(1.))
{ }
Scalar sample_impl() const
{
return gaussian_distribution_(generator_);
}
virtual Scalar mean() const
{
return 0.;
}
virtual Scalar covariance() const
{
return 1.;
}
protected:
mutable fl::mt11213b generator_;
mutable std::normal_distribution<Scalar> gaussian_distribution_;
};
/** \endcond */
/**
* Float floating point StandardGaussian specialization
* \ingroup distributions
*/
template <>
class StandardGaussian<float>
: public Sampling<float>,
public StandardGaussianFloatingPointScalarImpl<float>
{
public:
/**
* \copydoc Sampling::sample
*/
virtual float sample() const
{
return this->sample_impl();
}
};
/**
* Double floating point StandardGaussian specialization
* \ingroup distributions
*/
template <>
class StandardGaussian<double>
: public Sampling<double>,
public StandardGaussianFloatingPointScalarImpl<double>
{
public:
/**
* \copydoc Sampling::sample
*/
virtual double sample() const
{
return this->sample_impl();
}
};
/**
* Long double floating point StandardGaussian specialization
* \ingroup distributions
*/
template <>
class StandardGaussian<long double>
: public Sampling<long double>,
public StandardGaussianFloatingPointScalarImpl<long double>
{
public:
/**
* \copydoc Sampling::sample
*/
virtual long double sample() const
{
return this->sample_impl();
}
};
}
#endif
<commit_msg>Less Traits, Small implementation of the standard normal Gaussian<commit_after>/**
* \file standard_gaussian.hpp
* \date May 2014
* \author Jan Issac (jan.issac@gmail.com)
* \author Manuel Wuthrich (manuel.wuthrich@gmail.com)
*/
#ifndef FL__DISTRIBUTION__STANDARD_GAUSSIAN_HPP
#define FL__DISTRIBUTION__STANDARD_GAUSSIAN_HPP
#include <Eigen/Dense>
#include <random>
#include <type_traits>
#include <fl/util/random.hpp>
#include <fl/util/traits.hpp>
#include <fl/util/math.hpp>
#include <fl/distribution/interface/sampling.hpp>
#include <fl/distribution/interface/moments.hpp>
#include <fl/exception/exception.hpp>
namespace fl
{
/**
* \ingroup distributions
*/
template <typename StandardVariate>
class StandardGaussian
: public Sampling<StandardVariate>,
public Moments<StandardVariate>
{
public:
typedef StandardVariate Variate;
typedef typename Moments<StandardVariate>::SecondMoment SecondMoment;
public:
explicit
StandardGaussian(int dim = DimensionOf<StandardVariate>())
: dimension_ (dim),
generator_(fl::seed()),
gaussian_distribution_(0.0, 1.0)
{
}
virtual ~StandardGaussian() { }
virtual StandardVariate sample() const
{
StandardVariate gaussian_sample(dimension(), 1);
for (int i = 0; i < dimension(); i++)
{
gaussian_sample(i, 0) = gaussian_distribution_(generator_);
}
return gaussian_sample;
}
virtual int dimension() const
{
return dimension_;
}
virtual void dimension(int new_dimension)
{
if (dimension_ == new_dimension) return;
if (fl::IsFixed<StandardVariate::SizeAtCompileTime>())
{
fl_throw(
fl::ResizingFixedSizeEntityException(dimension_,
new_dimension,
"Gaussian"));
}
dimension_ = new_dimension;
}
virtual Variate mean() const
{
Variate mu;
mu.setZero(dimension(), 1);
return mu;
}
virtual SecondMoment covariance() const
{
SecondMoment cov;
cov.setIdentity(dimension(), dimension());
return cov;
}
private:
int dimension_;
mutable fl::mt11213b generator_;
mutable std::normal_distribution<> gaussian_distribution_;
};
/**
* Floating point implementation for Scalar types float, double and long double
*/
template <>
class StandardGaussian<Real>
: public Sampling<Real>,
public Moments<Real, Real>
{
public:
StandardGaussian()
: generator_(fl::seed()),
gaussian_distribution_(Real(0.), Real(1.))
{ }
Real sample() const
{
return gaussian_distribution_(generator_);
}
virtual Real mean() const
{
return 0.;
}
virtual Real covariance() const
{
return 1.;
}
protected:
mutable fl::mt11213b generator_;
mutable std::normal_distribution<Real> gaussian_distribution_;
};
}
#endif
<|endoftext|> |
<commit_before>#include "DSL_bless.hpp"
using namespace std;
namespace snarkfront {
////////////////////////////////////////////////////////////////////////////////
// blessing (initialize variables)
//
// 8-bit value from data buffer stream (useful for templates)
void bless(uint8_t& a, DataBufferStream& ss) {
a = ss.getWord<uint8_t>();
}
// 32-bit value from data buffer stream (useful for templates)
void bless(uint32_t& a, DataBufferStream& ss) {
a = ss.getWord<uint32_t>();
}
// 64-bit value from data buffer stream (useful for templates)
void bless(uint64_t& a, DataBufferStream& ss) {
a = ss.getWord<uint64_t>();
}
} // namespace snarkfront
<commit_msg>scope header file paths<commit_after>#include "snarkfront/DSL_bless.hpp"
using namespace std;
namespace snarkfront {
////////////////////////////////////////////////////////////////////////////////
// blessing (initialize variables)
//
// 8-bit value from data buffer stream (useful for templates)
void bless(uint8_t& a, DataBufferStream& ss) {
a = ss.getWord<uint8_t>();
}
// 32-bit value from data buffer stream (useful for templates)
void bless(uint32_t& a, DataBufferStream& ss) {
a = ss.getWord<uint32_t>();
}
// 64-bit value from data buffer stream (useful for templates)
void bless(uint64_t& a, DataBufferStream& ss) {
a = ss.getWord<uint64_t>();
}
} // namespace snarkfront
<|endoftext|> |
<commit_before>#include<stdio.h>
void baseConversion(char *number, int orig, int dest){
}
int main(void){
return 0;
}
<commit_msg>Created and tested binary exponentiation function successfully<commit_after><|endoftext|> |
<commit_before>// Bindings
#include "PyROOT.h"
#include "Adapters.h"
#include "Utility.h"
// ROOT
#include "TInterpreter.h"
#include "TBaseClass.h"
#include "TClass.h"
#include "TClassEdit.h"
#include "TDataType.h"
#include "TDataMember.h"
#include "TMethod.h"
#include "TFunction.h"
#include "TMethodArg.h"
#include "TList.h"
#include "TError.h"
//- helper -------------------------------------------------------------------
namespace PyROOT {
inline std::string UnqualifiedTypeName( const std::string name ) {
return TClassEdit::ShortType(
TClassEdit::CleanType( name.c_str(), 1 ).c_str(), 5 );
}
} // namespace PyROOT
//= TReturnTypeAdapter =======================================================
std::string PyROOT::TReturnTypeAdapter::Name( unsigned int mod ) const
{
// get the name of the return type that is being adapted
std::string name = fName;
if ( ! ( mod & Rflx::QUALIFIED ) )
name = UnqualifiedTypeName( fName );
if ( mod & Rflx::FINAL )
name = Utility::ResolveTypedef( name );
return name;
}
//= TMemberAdapter ===========================================================
PyROOT::TMemberAdapter::TMemberAdapter( TMethod* meth ) : fMember( meth )
{
/* empty */
}
//____________________________________________________________________________
PyROOT::TMemberAdapter::operator TMethod*() const
{
// cast the adapter to a TMethod* being adapted, returns 0 on failure
return dynamic_cast< TMethod* >( const_cast< TDictionary* >( fMember ) );
}
//____________________________________________________________________________
PyROOT::TMemberAdapter::TMemberAdapter( TFunction* func ) : fMember( func )
{
/* empty */
}
//____________________________________________________________________________
PyROOT::TMemberAdapter::operator TFunction*() const
{
// cast the adapter to a TFunction* being adapted, returns 0 on failure
return dynamic_cast< TFunction* >( const_cast< TDictionary* >( fMember ) );
}
//____________________________________________________________________________
PyROOT::TMemberAdapter::TMemberAdapter( TDataMember* mb ) : fMember( mb )
{
/* empty */
}
//____________________________________________________________________________
PyROOT::TMemberAdapter::operator TDataMember*() const
{
// cast the adapter to a TDataMember* being adapted, returns 0 on failure
return dynamic_cast< TDataMember* >( const_cast< TDictionary* >( fMember ) );
}
//____________________________________________________________________________
PyROOT::TMemberAdapter::TMemberAdapter( TMethodArg* ma ) : fMember( ma )
{
/* empty */
}
//____________________________________________________________________________
PyROOT::TMemberAdapter::operator TMethodArg*() const
{
// cast the adapter to a TMethodArg* being adapted, returns 0 on failure
return dynamic_cast< TMethodArg* >( const_cast< TDictionary* >( fMember ) );
}
//____________________________________________________________________________
std::string PyROOT::TMemberAdapter::Name( unsigned int mod ) const
{
// Return name of the type described by fMember
TMethodArg* arg = (TMethodArg*)*this;
if ( arg ) {
std::string name = arg->GetTypeNormalizedName();
if ( mod & Rflx::FINAL )
name = Utility::ResolveTypedef( name );
if ( ! ( mod & Rflx::QUALIFIED ) )
name = UnqualifiedTypeName( name );
return name;
} else if ( mod & Rflx::FINAL )
return Utility::ResolveTypedef( fMember->GetName() );
// CLING WORKAROUND -- TMethod names are fully scoped ...
TMethod* m = (TMethod*)*this;
if (m && m->GetClass()) {
std::string scoped_name = m->GetName();
std::string class_name = m->GetClass()->GetName();
std::string::size_type pos = scoped_name.find(class_name + "::");
if (pos == 0) // only accept found at start
scoped_name = scoped_name.substr(class_name.size() + 2 /* for :: */, std::string::npos);
return scoped_name;
}
// CLING WORKAROUND -- should not be null, but can be due #100389
if ( fMember != 0 )
return fMember->GetName();
return "<unknown>";
}
//____________________________________________________________________________
Bool_t PyROOT::TMemberAdapter::IsConstant() const
{
// test if the adapted member is a const method
return fMember ? (fMember->Property() & kIsConstMethod) : kFALSE;
}
//____________________________________________________________________________
Bool_t PyROOT::TMemberAdapter::IsConstructor() const
{
// test if the adapted member is a const method
return ((TFunction*)fMember) ? (((TFunction*)fMember)->ExtraProperty() & kIsConstructor) : kFALSE;
}
//____________________________________________________________________________
Bool_t PyROOT::TMemberAdapter::IsEnum() const
{
// test if the adapted member is of an enum type
return fMember->Property() & kIsEnum;
}
//____________________________________________________________________________
Bool_t PyROOT::TMemberAdapter::IsPublic() const
{
// test if the adapted member represents an public (data) member
return fMember->Property() & kIsPublic;
}
//____________________________________________________________________________
Bool_t PyROOT::TMemberAdapter::IsStatic() const
{
// test if the adapted member represents a class (data) member
return fMember->Property() & kIsStatic;
}
//____________________________________________________________________________
size_t PyROOT::TMemberAdapter::FunctionParameterSize( Bool_t required ) const
{
// get the total number of parameters that the adapted function/method takes
TFunction* func = (TFunction*)fMember;
if ( ! func )
return 0;
if ( required == true )
return func->GetNargs() - func->GetNargsOpt();
return func->GetNargs();
}
//____________________________________________________________________________
PyROOT::TMemberAdapter PyROOT::TMemberAdapter::FunctionParameterAt( size_t nth ) const
{
// get the type info of the function parameter at position nth
return (TMethodArg*)((TFunction*)fMember)->GetListOfMethodArgs()->At( nth );
}
//____________________________________________________________________________
std::string PyROOT::TMemberAdapter::FunctionParameterNameAt( size_t nth ) const
{
// get the formal name, if available, of the function parameter at position nth
const char* name =
((TMethodArg*)((TFunction*)fMember)->GetListOfMethodArgs()->At( nth ))->GetName();
if ( name )
return name;
return "";
}
//____________________________________________________________________________
std::string PyROOT::TMemberAdapter::FunctionParameterDefaultAt( size_t nth ) const
{
// get the default value, if available, of the function parameter at position nth
TMethodArg* arg = (TMethodArg*)((TFunction*)fMember)->GetListOfMethodArgs()->At( nth );
const char* def = arg->GetDefault();
if ( ! def )
return "";
// special case for strings: "some value" -> ""some value"
if ( strstr( Utility::ResolveTypedef( arg->GetTypeNormalizedName() ).c_str(), "char*" ) ) {
std::string sdef = "\"";
sdef += def;
sdef += "\"";
return sdef;
}
return def;
}
//____________________________________________________________________________
PyROOT::TReturnTypeAdapter PyROOT::TMemberAdapter::ReturnType() const
{
// get the return type of the wrapped function/method
return TReturnTypeAdapter( ((TFunction*)fMember)->GetReturnTypeNormalizedName() );
}
//____________________________________________________________________________
PyROOT::TScopeAdapter PyROOT::TMemberAdapter::DeclaringScope() const
{
// get the declaring scope (class) of the wrapped function/method
TMethod* method = (TMethod*)*this;
if ( method )
return method->GetClass();
// happens for free-standing functions (i.e. global scope)
return std::string( "" );
}
//= TBaseAdapter =============================================================
std::string PyROOT::TBaseAdapter::Name() const
{
// get the name of the base class that is being adapted
return fBase->GetName();
}
//= TScopeAdapter ============================================================
PyROOT::TScopeAdapter::TScopeAdapter( TClass* klass ) : fClass( klass )
{
// wrap a class (scope)
if ( fClass.GetClass() != 0 )
fName = fClass->GetName();
}
//____________________________________________________________________________
PyROOT::TScopeAdapter::TScopeAdapter( const std::string& name ) :
fClass( name.c_str() ), fName( name )
{
/* empty */
}
PyROOT::TScopeAdapter::TScopeAdapter( const TMemberAdapter& mb ) :
fClass( mb.Name( Rflx::SCOPED ).c_str() ),
fName( mb.Name( Rflx::QUALIFIED | Rflx::SCOPED ) )
{
/* empty */
}
//____________________________________________________________________________
PyROOT::TScopeAdapter PyROOT::TScopeAdapter::ByName( const std::string& name, Bool_t quiet )
{
// lookup a scope (class) by name
Int_t oldEIL = gErrorIgnoreLevel;
if ( quiet )
gErrorIgnoreLevel = 3000;
TClassRef klass( name.c_str() );
if (klass.GetClass() && klass->GetListOfAllPublicMethods()->GetSize() == 0) {
// sometimes I/O interferes, leading to zero methods: reload from CINT
ClassInfo_t* cl = gInterpreter->ClassInfo_Factory( name.c_str() );
if ( cl ) {
gInterpreter->SetClassInfo( klass, kTRUE );
gInterpreter->ClassInfo_Delete(cl);
}
}
gErrorIgnoreLevel = oldEIL;
return klass.GetClass();
}
//____________________________________________________________________________
std::string PyROOT::TScopeAdapter::Name( unsigned int mod ) const
{
// Return name of type described by fClass
if ( ! fClass.GetClass() || ! fClass->Property() ) {
// fundamental types have no class, and unknown classes have no property
std::string name = fName;
if ( mod & Rflx::FINAL )
name = Utility::ResolveTypedef( name );
if ( ! ( mod & Rflx::QUALIFIED ) )
name = UnqualifiedTypeName( fName );
return name;
}
std::string name = fClass->GetName();
if ( mod & Rflx::FINAL )
name = Utility::ResolveTypedef( name );
if ( ! (mod & Rflx::SCOPED) ) {
// remove scope from the name
Int_t tpl_open = 0;
for ( std::string::size_type pos = name.size() - 1; 0 < pos; --pos ) {
std::string::value_type c = name[ pos ];
// count '<' and '>' to be able to skip template contents
if ( c == '>' )
++tpl_open;
else if ( c == '<' )
--tpl_open;
else if ( tpl_open == 0 && c == ':' && 0 < pos && name[ pos-1 ] == ':' ) {
// found scope, strip name from it
name = name.substr( pos+1, std::string::npos );
}
}
}
return name;
}
//____________________________________________________________________________
size_t PyROOT::TScopeAdapter::BaseSize() const
{
// get the total number of base classes that this class has
if ( fClass.GetClass() && fClass->GetListOfBases() != 0 )
return fClass->GetListOfBases()->GetSize();
return 0;
}
//____________________________________________________________________________
PyROOT::TBaseAdapter PyROOT::TScopeAdapter::BaseAt( size_t nth ) const
{
// get the nth base of this class
return (TBaseClass*)fClass->GetListOfBases()->At( nth );
}
//____________________________________________________________________________
size_t PyROOT::TScopeAdapter::FunctionMemberSize() const
{
// get the total number of methods that this class has
if ( fClass.GetClass() )
return fClass->GetListOfMethods()->GetSize();
return 0;
}
//____________________________________________________________________________
PyROOT::TMemberAdapter PyROOT::TScopeAdapter::FunctionMemberAt( size_t nth ) const
{
// get the nth method of this class
return (TMethod*)fClass->GetListOfMethods()->At( nth );
}
//____________________________________________________________________________
size_t PyROOT::TScopeAdapter::DataMemberSize() const
{
// get the total number of data members that this class has
if ( fClass.GetClass() )
return fClass->GetListOfDataMembers()->GetSize();
return 0;
}
//____________________________________________________________________________
PyROOT::TMemberAdapter PyROOT::TScopeAdapter::DataMemberAt( size_t nth ) const
{
// get the nth data member of this class
return (TDataMember*)fClass->GetListOfDataMembers()->At( nth );
}
//____________________________________________________________________________
PyROOT::TScopeAdapter::operator Bool_t() const
{
// check the validity of this scope (class)
if ( fName.empty() )
return false;
Bool_t b = kFALSE;
Int_t oldEIL = gErrorIgnoreLevel;
gErrorIgnoreLevel = 3000;
std::string scname = Name( Rflx::SCOPED );
TClass* klass = TClass::GetClass( scname.c_str() );
if ( klass && klass->GetClassInfo() ) // works for normal case w/ dict
b = gInterpreter->ClassInfo_IsValid( klass->GetClassInfo() );
else { // special case for forward declared classes
ClassInfo_t* ci = gInterpreter->ClassInfo_Factory( scname.c_str() );
if ( ci ) {
b = gInterpreter->ClassInfo_IsValid( ci );
gInterpreter->ClassInfo_Delete( ci ); // we own the fresh class info
}
}
gErrorIgnoreLevel = oldEIL;
return b;
}
//____________________________________________________________________________
Bool_t PyROOT::TScopeAdapter::IsComplete() const
{
// verify whether the dictionary of this class is fully available
Bool_t b = kFALSE;
std::string scname = Name( Rflx::SCOPED );
TClass* klass = TClass::GetClass( scname.c_str() );
if ( klass && klass->GetClassInfo() ) // works for normal case w/ dict
b = gInterpreter->ClassInfo_IsLoaded( klass->GetClassInfo() );
else { // special case for forward declared classes
ClassInfo_t* ci = gInterpreter->ClassInfo_Factory( scname.c_str() );
if ( ci ) {
b = gInterpreter->ClassInfo_IsLoaded( ci );
gInterpreter->ClassInfo_Delete( ci ); // we own the fresh class info
}
}
return b;
}
//____________________________________________________________________________
Bool_t PyROOT::TScopeAdapter::IsClass() const
{
// test if this scope represents a class
if ( fClass.GetClass() ) {
// some inverted logic: we don't have a TClass, but a builtin will be recognized, so
// if it is NOT a builtin, it is a class or struct (but may be missing dictionary)
return (fClass->Property() & kIsClass) || ! (fClass->Property() & kIsFundamental);
}
// no class can mean either is no class (i.e. builtin), or no dict but coming in
// through PyCintex/Reflex ... as a workaround, use TDataTypes that has a full
// enumeration of builtin types
return TDataType( Name( Rflx::FINAL | Rflx::SCOPED ).c_str() ).GetType() == kOther_t;
}
//____________________________________________________________________________
Bool_t PyROOT::TScopeAdapter::IsStruct() const
{
// test if this scope represents a struct
if ( fClass.GetClass() ) {
// same logic as for IsClass() above ...
return (fClass->Property() & kIsStruct) || ! (fClass->Property() & kIsFundamental);
}
// same logic as for IsClass() above ...
return TDataType( Name( Rflx::FINAL | Rflx::SCOPED ).c_str() ).GetType() == kOther_t;
}
//____________________________________________________________________________
Bool_t PyROOT::TScopeAdapter::IsNamespace() const
{
// test if this scope represents a namespace
if ( fClass.GetClass() )
return fClass->Property() & kIsNamespace;
return kFALSE;
}
//____________________________________________________________________________
Bool_t PyROOT::TScopeAdapter::IsAbstract() const
{
// test if this scope represents an abstract class
if ( fClass.GetClass() )
return fClass->Property() & kIsAbstract; // assume set only for classes
return kFALSE;
}
<commit_msg>fix for ROOT-5653<commit_after>// Bindings
#include "PyROOT.h"
#include "Adapters.h"
#include "Utility.h"
// ROOT
#include "TInterpreter.h"
#include "TBaseClass.h"
#include "TClass.h"
#include "TClassEdit.h"
#include "TDataType.h"
#include "TDataMember.h"
#include "TMethod.h"
#include "TFunction.h"
#include "TMethodArg.h"
#include "TList.h"
#include "TError.h"
//- helper -------------------------------------------------------------------
namespace PyROOT {
inline std::string UnqualifiedTypeName( const std::string name ) {
return TClassEdit::ShortType(
TClassEdit::CleanType( name.c_str(), 1 ).c_str(), 5 );
}
} // namespace PyROOT
//= TReturnTypeAdapter =======================================================
std::string PyROOT::TReturnTypeAdapter::Name( unsigned int mod ) const
{
// get the name of the return type that is being adapted
std::string name = fName;
if ( ! ( mod & Rflx::QUALIFIED ) )
name = UnqualifiedTypeName( fName );
if ( mod & Rflx::FINAL )
name = Utility::ResolveTypedef( name );
return name;
}
//= TMemberAdapter ===========================================================
PyROOT::TMemberAdapter::TMemberAdapter( TMethod* meth ) : fMember( meth )
{
/* empty */
}
//____________________________________________________________________________
PyROOT::TMemberAdapter::operator TMethod*() const
{
// cast the adapter to a TMethod* being adapted, returns 0 on failure
return dynamic_cast< TMethod* >( const_cast< TDictionary* >( fMember ) );
}
//____________________________________________________________________________
PyROOT::TMemberAdapter::TMemberAdapter( TFunction* func ) : fMember( func )
{
/* empty */
}
//____________________________________________________________________________
PyROOT::TMemberAdapter::operator TFunction*() const
{
// cast the adapter to a TFunction* being adapted, returns 0 on failure
return dynamic_cast< TFunction* >( const_cast< TDictionary* >( fMember ) );
}
//____________________________________________________________________________
PyROOT::TMemberAdapter::TMemberAdapter( TDataMember* mb ) : fMember( mb )
{
/* empty */
}
//____________________________________________________________________________
PyROOT::TMemberAdapter::operator TDataMember*() const
{
// cast the adapter to a TDataMember* being adapted, returns 0 on failure
return dynamic_cast< TDataMember* >( const_cast< TDictionary* >( fMember ) );
}
//____________________________________________________________________________
PyROOT::TMemberAdapter::TMemberAdapter( TMethodArg* ma ) : fMember( ma )
{
/* empty */
}
//____________________________________________________________________________
PyROOT::TMemberAdapter::operator TMethodArg*() const
{
// cast the adapter to a TMethodArg* being adapted, returns 0 on failure
return dynamic_cast< TMethodArg* >( const_cast< TDictionary* >( fMember ) );
}
//____________________________________________________________________________
std::string PyROOT::TMemberAdapter::Name( unsigned int mod ) const
{
// Return name of the type described by fMember
TMethodArg* arg = (TMethodArg*)*this;
if ( arg ) {
std::string name = arg->GetTypeNormalizedName();
if ( mod & Rflx::FINAL )
name = Utility::ResolveTypedef( name );
if ( ! ( mod & Rflx::QUALIFIED ) )
name = UnqualifiedTypeName( name );
return name;
} else if ( mod & Rflx::FINAL )
return Utility::ResolveTypedef( fMember->GetName() );
// CLING WORKAROUND -- TMethod names are fully scoped ...
TMethod* m = (TMethod*)*this;
if (m && m->GetClass()) {
std::string scoped_name = m->GetName();
std::string class_name = m->GetClass()->GetName();
std::string::size_type pos = scoped_name.find(class_name + "::");
if (pos == 0) // only accept found at start
scoped_name = scoped_name.substr(class_name.size() + 2 /* for :: */, std::string::npos);
return scoped_name;
}
// CLING WORKAROUND -- should not be null, but can be due #100389
if ( fMember != 0 )
return fMember->GetName();
return "<unknown>";
}
//____________________________________________________________________________
Bool_t PyROOT::TMemberAdapter::IsConstant() const
{
// test if the adapted member is a const method
return fMember ? (fMember->Property() & kIsConstMethod) : kFALSE;
}
//____________________________________________________________________________
Bool_t PyROOT::TMemberAdapter::IsConstructor() const
{
// test if the adapted member is a const method
return ((TFunction*)fMember) ? (((TFunction*)fMember)->ExtraProperty() & kIsConstructor) : kFALSE;
}
//____________________________________________________________________________
Bool_t PyROOT::TMemberAdapter::IsEnum() const
{
// test if the adapted member is of an enum type
return fMember->Property() & kIsEnum;
}
//____________________________________________________________________________
Bool_t PyROOT::TMemberAdapter::IsPublic() const
{
// test if the adapted member represents an public (data) member
return fMember->Property() & kIsPublic;
}
//____________________________________________________________________________
Bool_t PyROOT::TMemberAdapter::IsStatic() const
{
// test if the adapted member represents a class (data) member
return fMember->Property() & kIsStatic;
}
//____________________________________________________________________________
size_t PyROOT::TMemberAdapter::FunctionParameterSize( Bool_t required ) const
{
// get the total number of parameters that the adapted function/method takes
TFunction* func = (TFunction*)fMember;
if ( ! func )
return 0;
if ( required == true )
return func->GetNargs() - func->GetNargsOpt();
return func->GetNargs();
}
//____________________________________________________________________________
PyROOT::TMemberAdapter PyROOT::TMemberAdapter::FunctionParameterAt( size_t nth ) const
{
// get the type info of the function parameter at position nth
return (TMethodArg*)((TFunction*)fMember)->GetListOfMethodArgs()->At( nth );
}
//____________________________________________________________________________
std::string PyROOT::TMemberAdapter::FunctionParameterNameAt( size_t nth ) const
{
// get the formal name, if available, of the function parameter at position nth
const char* name =
((TMethodArg*)((TFunction*)fMember)->GetListOfMethodArgs()->At( nth ))->GetName();
if ( name )
return name;
return "";
}
//____________________________________________________________________________
std::string PyROOT::TMemberAdapter::FunctionParameterDefaultAt( size_t nth ) const
{
// get the default value, if available, of the function parameter at position nth
TMethodArg* arg = (TMethodArg*)((TFunction*)fMember)->GetListOfMethodArgs()->At( nth );
const char* def = arg->GetDefault();
if ( ! def )
return "";
// special case for strings: "some value" -> ""some value"
if ( strstr( Utility::ResolveTypedef( arg->GetTypeNormalizedName() ).c_str(), "char*" ) ) {
std::string sdef = "\"";
sdef += def;
sdef += "\"";
return sdef;
}
return def;
}
//____________________________________________________________________________
PyROOT::TReturnTypeAdapter PyROOT::TMemberAdapter::ReturnType() const
{
// get the return type of the wrapped function/method
return TReturnTypeAdapter( ((TFunction*)fMember)->GetReturnTypeNormalizedName() );
}
//____________________________________________________________________________
PyROOT::TScopeAdapter PyROOT::TMemberAdapter::DeclaringScope() const
{
// get the declaring scope (class) of the wrapped function/method
TMethod* method = (TMethod*)*this;
if ( method )
return method->GetClass();
// happens for free-standing functions (i.e. global scope)
return std::string( "" );
}
//= TBaseAdapter =============================================================
std::string PyROOT::TBaseAdapter::Name() const
{
// get the name of the base class that is being adapted
return fBase->GetName();
}
//= TScopeAdapter ============================================================
PyROOT::TScopeAdapter::TScopeAdapter( TClass* klass ) : fClass( klass )
{
// wrap a class (scope)
if ( fClass.GetClass() != 0 )
fName = fClass->GetName();
}
//____________________________________________________________________________
PyROOT::TScopeAdapter::TScopeAdapter( const std::string& name ) :
fClass( name.c_str() ), fName( name )
{
/* empty */
}
PyROOT::TScopeAdapter::TScopeAdapter( const TMemberAdapter& mb ) :
fClass( mb.Name( Rflx::SCOPED ).c_str() ),
fName( mb.Name( Rflx::QUALIFIED | Rflx::SCOPED ) )
{
/* empty */
}
//____________________________________________________________________________
PyROOT::TScopeAdapter PyROOT::TScopeAdapter::ByName( const std::string& name, Bool_t quiet )
{
// lookup a scope (class) by name
Int_t oldEIL = gErrorIgnoreLevel;
if ( quiet )
gErrorIgnoreLevel = 3000;
TClassRef klass( name.c_str() );
if (klass.GetClass() && klass->GetListOfAllPublicMethods()->GetSize() == 0) {
// sometimes I/O interferes, leading to zero methods: reload from CINT
ClassInfo_t* cl = gInterpreter->ClassInfo_Factory( name.c_str() );
if ( cl ) {
gInterpreter->SetClassInfo( klass, kTRUE );
gInterpreter->ClassInfo_Delete(cl);
}
}
gErrorIgnoreLevel = oldEIL;
return klass.GetClass();
}
//____________________________________________________________________________
std::string PyROOT::TScopeAdapter::Name( unsigned int mod ) const
{
// Return name of type described by fClass
if ( ! fClass.GetClass() || ! fClass->Property() ) {
// fundamental types have no class, and unknown classes have no property
std::string name = fName;
if ( mod & Rflx::FINAL )
name = Utility::ResolveTypedef( name );
if ( ! ( mod & Rflx::QUALIFIED ) )
name = UnqualifiedTypeName( fName );
return name;
}
std::string name = fClass->GetName();
if ( mod & Rflx::FINAL )
name = Utility::ResolveTypedef( name );
if ( ! (mod & Rflx::SCOPED) ) {
// remove scope from the name
Int_t tpl_open = 0;
for ( std::string::size_type pos = name.size() - 1; 0 < pos; --pos ) {
std::string::value_type c = name[ pos ];
// count '<' and '>' to be able to skip template contents
if ( c == '>' )
++tpl_open;
else if ( c == '<' )
--tpl_open;
else if ( tpl_open == 0 && c == ':' && 0 < pos && name[ pos-1 ] == ':' ) {
// found scope, strip name from it
name = name.substr( pos+1, std::string::npos );
break;
}
}
}
return name;
}
//____________________________________________________________________________
size_t PyROOT::TScopeAdapter::BaseSize() const
{
// get the total number of base classes that this class has
if ( fClass.GetClass() && fClass->GetListOfBases() != 0 )
return fClass->GetListOfBases()->GetSize();
return 0;
}
//____________________________________________________________________________
PyROOT::TBaseAdapter PyROOT::TScopeAdapter::BaseAt( size_t nth ) const
{
// get the nth base of this class
return (TBaseClass*)fClass->GetListOfBases()->At( nth );
}
//____________________________________________________________________________
size_t PyROOT::TScopeAdapter::FunctionMemberSize() const
{
// get the total number of methods that this class has
if ( fClass.GetClass() )
return fClass->GetListOfMethods()->GetSize();
return 0;
}
//____________________________________________________________________________
PyROOT::TMemberAdapter PyROOT::TScopeAdapter::FunctionMemberAt( size_t nth ) const
{
// get the nth method of this class
return (TMethod*)fClass->GetListOfMethods()->At( nth );
}
//____________________________________________________________________________
size_t PyROOT::TScopeAdapter::DataMemberSize() const
{
// get the total number of data members that this class has
if ( fClass.GetClass() )
return fClass->GetListOfDataMembers()->GetSize();
return 0;
}
//____________________________________________________________________________
PyROOT::TMemberAdapter PyROOT::TScopeAdapter::DataMemberAt( size_t nth ) const
{
// get the nth data member of this class
return (TDataMember*)fClass->GetListOfDataMembers()->At( nth );
}
//____________________________________________________________________________
PyROOT::TScopeAdapter::operator Bool_t() const
{
// check the validity of this scope (class)
if ( fName.empty() )
return false;
Bool_t b = kFALSE;
Int_t oldEIL = gErrorIgnoreLevel;
gErrorIgnoreLevel = 3000;
std::string scname = Name( Rflx::SCOPED );
TClass* klass = TClass::GetClass( scname.c_str() );
if ( klass && klass->GetClassInfo() ) // works for normal case w/ dict
b = gInterpreter->ClassInfo_IsValid( klass->GetClassInfo() );
else { // special case for forward declared classes
ClassInfo_t* ci = gInterpreter->ClassInfo_Factory( scname.c_str() );
if ( ci ) {
b = gInterpreter->ClassInfo_IsValid( ci );
gInterpreter->ClassInfo_Delete( ci ); // we own the fresh class info
}
}
gErrorIgnoreLevel = oldEIL;
return b;
}
//____________________________________________________________________________
Bool_t PyROOT::TScopeAdapter::IsComplete() const
{
// verify whether the dictionary of this class is fully available
Bool_t b = kFALSE;
std::string scname = Name( Rflx::SCOPED );
TClass* klass = TClass::GetClass( scname.c_str() );
if ( klass && klass->GetClassInfo() ) // works for normal case w/ dict
b = gInterpreter->ClassInfo_IsLoaded( klass->GetClassInfo() );
else { // special case for forward declared classes
ClassInfo_t* ci = gInterpreter->ClassInfo_Factory( scname.c_str() );
if ( ci ) {
b = gInterpreter->ClassInfo_IsLoaded( ci );
gInterpreter->ClassInfo_Delete( ci ); // we own the fresh class info
}
}
return b;
}
//____________________________________________________________________________
Bool_t PyROOT::TScopeAdapter::IsClass() const
{
// test if this scope represents a class
if ( fClass.GetClass() ) {
// some inverted logic: we don't have a TClass, but a builtin will be recognized, so
// if it is NOT a builtin, it is a class or struct (but may be missing dictionary)
return (fClass->Property() & kIsClass) || ! (fClass->Property() & kIsFundamental);
}
// no class can mean either is no class (i.e. builtin), or no dict but coming in
// through PyCintex/Reflex ... as a workaround, use TDataTypes that has a full
// enumeration of builtin types
return TDataType( Name( Rflx::FINAL | Rflx::SCOPED ).c_str() ).GetType() == kOther_t;
}
//____________________________________________________________________________
Bool_t PyROOT::TScopeAdapter::IsStruct() const
{
// test if this scope represents a struct
if ( fClass.GetClass() ) {
// same logic as for IsClass() above ...
return (fClass->Property() & kIsStruct) || ! (fClass->Property() & kIsFundamental);
}
// same logic as for IsClass() above ...
return TDataType( Name( Rflx::FINAL | Rflx::SCOPED ).c_str() ).GetType() == kOther_t;
}
//____________________________________________________________________________
Bool_t PyROOT::TScopeAdapter::IsNamespace() const
{
// test if this scope represents a namespace
if ( fClass.GetClass() )
return fClass->Property() & kIsNamespace;
return kFALSE;
}
//____________________________________________________________________________
Bool_t PyROOT::TScopeAdapter::IsAbstract() const
{
// test if this scope represents an abstract class
if ( fClass.GetClass() )
return fClass->Property() & kIsAbstract; // assume set only for classes
return kFALSE;
}
<|endoftext|> |
<commit_before>#include "node_helpers.hpp"
namespace cloudcv
{
static char encoding_table[] = {'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H',
'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P',
'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X',
'Y', 'Z', 'a', 'b', 'c', 'd', 'e', 'f',
'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n',
'o', 'p', 'q', 'r', 's', 't', 'u', 'v',
'w', 'x', 'y', 'z', '0', '1', '2', '3',
'4', '5', '6', '7', '8', '9', '+', '/'};
static char *decoding_table = NULL;
static int mod_table[] = {0, 2, 1};
void base64_encode(const std::vector<unsigned char>& data, std::vector<unsigned char>& encoded_data)
{
int input_length = data.size();
int output_length = 4 * ((input_length + 2) / 3);
encoded_data.resize(output_length);
for (int i = 0, j = 0; i < input_length;)
{
uint32_t octet_a = i < input_length ? data[i++] : 0;
uint32_t octet_b = i < input_length ? data[i++] : 0;
uint32_t octet_c = i < input_length ? data[i++] : 0;
uint32_t triple = (octet_a << 0x10) + (octet_b << 0x08) + octet_c;
encoded_data[j++] = encoding_table[(triple >> 3 * 6) & 0x3F];
encoded_data[j++] = encoding_table[(triple >> 2 * 6) & 0x3F];
encoded_data[j++] = encoding_table[(triple >> 1 * 6) & 0x3F];
encoded_data[j++] = encoding_table[(triple >> 0 * 6) & 0x3F];
}
for (int i = 0; i < mod_table[input_length % 3]; i++)
encoded_data[output_length - 1 - i] = '=';
}
/*
unsigned char *base64_decode(const char *data,
size_t input_length,
size_t *output_length) {
if (decoding_table == NULL) build_decoding_table();
if (input_length % 4 != 0) return NULL;
*output_length = input_length / 4 * 3;
if (data[input_length - 1] == '=') (*output_length)--;
if (data[input_length - 2] == '=') (*output_length)--;
unsigned char *decoded_data = malloc(*output_length);
if (decoded_data == NULL) return NULL;
for (int i = 0, j = 0; i < input_length;) {
uint32_t sextet_a = data[i] == '=' ? 0 & i++ : decoding_table[data[i++]];
uint32_t sextet_b = data[i] == '=' ? 0 & i++ : decoding_table[data[i++]];
uint32_t sextet_c = data[i] == '=' ? 0 & i++ : decoding_table[data[i++]];
uint32_t sextet_d = data[i] == '=' ? 0 & i++ : decoding_table[data[i++]];
uint32_t triple = (sextet_a << 3 * 6)
+ (sextet_b << 2 * 6)
+ (sextet_c << 1 * 6)
+ (sextet_d << 0 * 6);
if (j < *output_length) decoded_data[j++] = (triple >> 2 * 8) & 0xFF;
if (j < *output_length) decoded_data[j++] = (triple >> 1 * 8) & 0xFF;
if (j < *output_length) decoded_data[j++] = (triple >> 0 * 8) & 0xFF;
}
return decoded_data;
}
**/
std::string base64encode(cv::Mat& img)
{
std::vector<unsigned char> buf, encoded;
cv::imencode(".png", img, buf);
base64_encode(buf, encoded);
std::ostringstream os;
os << "data:image/png;base64,";
std::copy(encoded.begin(), encoded.end(), std::ostream_iterator<unsigned char>(os));
return os.str();
}
}<commit_msg>Fix compilation error under gcc<commit_after>#include "node_helpers.hpp"
#include <iterator>
namespace cloudcv
{
static char encoding_table[] = {'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H',
'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P',
'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X',
'Y', 'Z', 'a', 'b', 'c', 'd', 'e', 'f',
'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n',
'o', 'p', 'q', 'r', 's', 't', 'u', 'v',
'w', 'x', 'y', 'z', '0', '1', '2', '3',
'4', '5', '6', '7', '8', '9', '+', '/'};
static char *decoding_table = NULL;
static int mod_table[] = {0, 2, 1};
void base64_encode(const std::vector<unsigned char>& data, std::vector<unsigned char>& encoded_data)
{
int input_length = data.size();
int output_length = 4 * ((input_length + 2) / 3);
encoded_data.resize(output_length);
for (int i = 0, j = 0; i < input_length;)
{
uint32_t octet_a = i < input_length ? data[i++] : 0;
uint32_t octet_b = i < input_length ? data[i++] : 0;
uint32_t octet_c = i < input_length ? data[i++] : 0;
uint32_t triple = (octet_a << 0x10) + (octet_b << 0x08) + octet_c;
encoded_data[j++] = encoding_table[(triple >> 3 * 6) & 0x3F];
encoded_data[j++] = encoding_table[(triple >> 2 * 6) & 0x3F];
encoded_data[j++] = encoding_table[(triple >> 1 * 6) & 0x3F];
encoded_data[j++] = encoding_table[(triple >> 0 * 6) & 0x3F];
}
for (int i = 0; i < mod_table[input_length % 3]; i++)
encoded_data[output_length - 1 - i] = '=';
}
/*
unsigned char *base64_decode(const char *data,
size_t input_length,
size_t *output_length) {
if (decoding_table == NULL) build_decoding_table();
if (input_length % 4 != 0) return NULL;
*output_length = input_length / 4 * 3;
if (data[input_length - 1] == '=') (*output_length)--;
if (data[input_length - 2] == '=') (*output_length)--;
unsigned char *decoded_data = malloc(*output_length);
if (decoded_data == NULL) return NULL;
for (int i = 0, j = 0; i < input_length;) {
uint32_t sextet_a = data[i] == '=' ? 0 & i++ : decoding_table[data[i++]];
uint32_t sextet_b = data[i] == '=' ? 0 & i++ : decoding_table[data[i++]];
uint32_t sextet_c = data[i] == '=' ? 0 & i++ : decoding_table[data[i++]];
uint32_t sextet_d = data[i] == '=' ? 0 & i++ : decoding_table[data[i++]];
uint32_t triple = (sextet_a << 3 * 6)
+ (sextet_b << 2 * 6)
+ (sextet_c << 1 * 6)
+ (sextet_d << 0 * 6);
if (j < *output_length) decoded_data[j++] = (triple >> 2 * 8) & 0xFF;
if (j < *output_length) decoded_data[j++] = (triple >> 1 * 8) & 0xFF;
if (j < *output_length) decoded_data[j++] = (triple >> 0 * 8) & 0xFF;
}
return decoded_data;
}
**/
std::string base64encode(cv::Mat& img)
{
std::vector<unsigned char> buf, encoded;
cv::imencode(".png", img, buf);
base64_encode(buf, encoded);
std::ostringstream os;
os << "data:image/png;base64,";
std::copy(encoded.begin(), encoded.end(), std::ostream_iterator<unsigned char>(os));
return os.str();
}
}
<|endoftext|> |
<commit_before>// $Id: readFile.C,v 1.8 2000/10/08 23:26:13 amoll Exp $
#include <BALL/FORMAT/readFile.h>
#include <BALL/COMMON/exception.h>
#include <stdio.h>
using namespace std;
namespace BALL
{
ReadFile::ReadFileError::ReadFileError(const char* file, int line, const ReadFile& rf, const String& message)
: Exception::GeneralException(file, line, "ReadFileError", "")
{
message_ = message;
message_ += "; last read line number = ";
char buf[40];
sprintf(buf, "%i", rf.getLineNumber());
message_ += buf;
message_ += "\n contents of line: \n";
message_ += rf.getLineContens();
Exception::GlobalExceptionHandler globalHandler;
globalHandler.setMessage(message_);
}
Position ReadFile::getLineNumber() const
{
return line_number_;
}
const String& ReadFile::getLineContens() const
{
return line_;
}
ReadFile::ReadFile(const String& file_name)
: line_number_(0),
file_name_(file_name)
{
in.open(file_name_.c_str());
if (!in)
{
throw Exception::FileNotFound(__FILE__, __LINE__, file_name);
}
}
String ReadFile::getToken_(Position& pos, char delimiter) const
{
test_(__FILE__, __LINE__,
pos < line_.size(),
"in getToken_ : pos too large");
while (pos < line_.size() && line_[pos] != delimiter)
{
++pos;
}
++pos;
test_(__FILE__, __LINE__,
pos < line_.size(),
"open token");
String token;
while (line_[pos] != delimiter)
{
test_(__FILE__, __LINE__,
pos < line_.size(),
"open token");
token += line_[pos];
++pos;
}
++pos;
test_(__FILE__, __LINE__,
token.size() > 0,
"token could not be read");
return token;
}
String ReadFile::getToken_(Position& pos) const
{
test_(__FILE__, __LINE__,
pos < line_.size(),
"in getToken_ : pos too large");
while (pos < line_.size() && isspace(line_[pos]))
{
++pos;
}
String token;
while (pos < line_.size() && !isspace(line_[pos]))
{
token += line_[pos];
++pos;
}
++pos;
test_(__FILE__, __LINE__,
token.size() > 0,
"token could not be read");
return token;
}
String ReadFile::getToken_() const
{
Position pos = 0;
while (pos < line_.size() && isspace(line_[pos]))
{
++pos;
}
String token;
while (pos < line_.size() && !isspace(line_[pos]))
{
token += line_[pos];
++pos;
}
test_(__FILE__, __LINE__,
token.size() > 0,
"token could not be read");
return token;
}
String ReadFile::copyString_(Position start, Position end) const
{
if (end == 0)
{
end = line_.size() - 1;
}
test_(__FILE__, __LINE__,
end < line_.size(),
"error in copyString_");
String dest;
for (; start <= end ; ++start)
{
dest += line_[start];
}
return dest;
}
int ReadFile::switch_(const vector<String>& data) const
{
for (Position i = 0; i < data.size(); i++)
{
if (line_ == data[i])
{
return i;
}
}
return (-1);
}
bool ReadFile::startsWith_(const String& text) const
{
return line_.hasPrefix(text);
}
bool ReadFile::search_(const String& text)
{
while (!in.eof())
{
readLine_();
if (startsWith_(text))
{
return true;
}
}
return false;
}
bool ReadFile::search_(const String& text, const String& stop)
{
while (!in.eof())
{
readLine_();
if (has_(stop))
{
return false;
}
if (startsWith_(text))
{
return true;
}
}
return false;
}
void ReadFile::test_(const char* file, int line, bool condition, const String& msg) const
{
if (!condition)
{
throw ReadFileError(file, line, *this, msg);
}
}
void ReadFile::readLine_()
{
char* c = new char[200];
in.getline(c, 200);
line_ = c;
++line_number_;
}
void ReadFile::skipLines_(Size number)
{
for (Position i = 0; i <= number; i++)
{
readLine_();
}
}
bool ReadFile::has_(const String& text) const
{
return line_.hasSubstring(text);
}
void ReadFile::rewind_()
{
in.close();
in.open(file_name_.c_str());
line_number_ = 0;
line_ = "";
}
ReadFile& ReadFile::operator = (const ReadFile& rf)
{
file_name_ = rf.file_name_;
rewind_();
return *this;
}
ReadFile::ReadFile(const ReadFile& rf)
{
file_name_ = rf.file_name_;
rewind_();
}
} //namespace
<commit_msg>fixed: ReadFileError, but still buggy<commit_after>// $Id: readFile.C,v 1.9 2000/10/09 11:46:09 amoll Exp $
#include <BALL/FORMAT/readFile.h>
#include <BALL/COMMON/exception.h>
#include <stdio.h>
using namespace std;
namespace BALL
{
ReadFile::ReadFileError::ReadFileError(const char* file, int line, const ReadFile& rf, const String& message)
: Exception::GeneralException(file, line, "ReadFileError", "")
{
message_ = message;
message_ += "; last read line number = ";
char buf[40];
sprintf(buf, "%i", rf.getLineNumber());
message_ += buf;
message_ += "\n contents of line: \n";
message_ += rf.getLineContens();
Exception::globalHandler.setMessage(message_);
}
Position ReadFile::getLineNumber() const
{
return line_number_;
}
const String& ReadFile::getLineContens() const
{
return line_;
}
ReadFile::ReadFile(const String& file_name)
: line_number_(0),
file_name_(file_name)
{
in.open(file_name_.c_str());
if (!in)
{
throw Exception::FileNotFound(__FILE__, __LINE__, file_name);
}
}
String ReadFile::getToken_(Position& pos, char delimiter) const
{
test_(__FILE__, __LINE__,
pos < line_.size(),
"in getToken_ : pos too large");
while (pos < line_.size() && line_[pos] != delimiter)
{
++pos;
}
++pos;
test_(__FILE__, __LINE__,
pos < line_.size(),
"open token");
String token;
while (line_[pos] != delimiter)
{
test_(__FILE__, __LINE__,
pos < line_.size(),
"open token");
token += line_[pos];
++pos;
}
++pos;
test_(__FILE__, __LINE__,
token.size() > 0,
"token could not be read");
return token;
}
String ReadFile::getToken_(Position& pos) const
{
test_(__FILE__, __LINE__,
pos < line_.size(),
"in getToken_ : pos too large");
while (pos < line_.size() && isspace(line_[pos]))
{
++pos;
}
String token;
while (pos < line_.size() && !isspace(line_[pos]))
{
token += line_[pos];
++pos;
}
++pos;
test_(__FILE__, __LINE__,
token.size() > 0,
"token could not be read");
return token;
}
String ReadFile::getToken_() const
{
Position pos = 0;
while (pos < line_.size() && isspace(line_[pos]))
{
++pos;
}
String token;
while (pos < line_.size() && !isspace(line_[pos]))
{
token += line_[pos];
++pos;
}
test_(__FILE__, __LINE__,
token.size() > 0,
"token could not be read");
return token;
}
String ReadFile::copyString_(Position start, Position end) const
{
if (end == 0)
{
end = line_.size() - 1;
}
test_(__FILE__, __LINE__,
end < line_.size(),
"error in copyString_");
String dest;
for (; start <= end ; ++start)
{
dest += line_[start];
}
return dest;
}
int ReadFile::switch_(const vector<String>& data) const
{
for (Position i = 0; i < data.size(); i++)
{
if (line_ == data[i])
{
return i;
}
}
return (-1);
}
bool ReadFile::startsWith_(const String& text) const
{
return line_.hasPrefix(text);
}
bool ReadFile::search_(const String& text)
{
while (!in.eof())
{
readLine_();
if (startsWith_(text))
{
return true;
}
}
return false;
}
bool ReadFile::search_(const String& text, const String& stop)
{
while (!in.eof())
{
readLine_();
if (has_(stop))
{
return false;
}
if (startsWith_(text))
{
return true;
}
}
return false;
}
void ReadFile::test_(const char* file, int line, bool condition, const String& msg) const
{
if (!condition)
{
throw ReadFileError(file, line, *this, msg);
}
}
void ReadFile::readLine_()
{
char* c = new char[200];
in.getline(c, 200);
line_ = c;
++line_number_;
}
void ReadFile::skipLines_(Size number)
{
for (Position i = 0; i <= number; i++)
{
readLine_();
}
}
bool ReadFile::has_(const String& text) const
{
return line_.hasSubstring(text);
}
void ReadFile::rewind_()
{
in.close();
in.open(file_name_.c_str());
line_number_ = 0;
line_ = "";
}
ReadFile& ReadFile::operator = (const ReadFile& rf)
{
file_name_ = rf.file_name_;
rewind_();
return *this;
}
ReadFile::ReadFile(const ReadFile& rf)
{
file_name_ = rf.file_name_;
rewind_();
}
} //namespace
<|endoftext|> |
<commit_before>/*****************************************************************************
* Project: RooFit *
* Package: RooFitCore *
* File: $Id: RooBinning.cc,v 1.5 2002/09/05 04:33:15 verkerke Exp $
* Authors: *
* WV, Wouter Verkerke, UC Santa Barbara, verkerke@slac.stanford.edu *
* DK, David Kirkby, UC Irvine, dkirkby@uci.edu *
* *
* Copyright (c) 2000-2002, Regents of the University of California *
* and Stanford University. All rights reserved. *
* *
* Redistribution and use in source and binary forms, *
* with or without modification, are permitted according to the terms *
* listed in LICENSE (http://roofit.sourceforge.net/license.txt) *
*****************************************************************************/
// -- CLASS DESCRIPTION [MISC] --
// Class RooBinning is an implements RooAbsBinning in terms of
// an array of boundary values, posing no constraints on the
// choice of binning, thus allowing variable bin sizes. Various
// methods allow the user to add single bin boundaries, mirrored pairs,
// or sets of uniformly spaced boundaries.
#include <iostream.h>
#include "RooFitCore/RooBinning.hh"
#include "RooFitCore/RooDouble.hh"
#include "RooFitCore/RooAbsPdf.hh"
#include "RooFitCore/RooRealVar.hh"
#include "RooFitCore/RooNumber.hh"
ClassImp(RooBinning)
;
RooBinning::RooBinning(Double_t xlo, Double_t xhi) : _array(0), _ownBoundHi(kTRUE), _ownBoundLo(kTRUE)
{
_bIter = binIterator() ;
setRange(xlo,xhi) ;
}
RooBinning::RooBinning(Int_t nbins, Double_t xlo, Double_t xhi) : _array(0), _ownBoundHi(kTRUE), _ownBoundLo(kTRUE)
{
_bIter = binIterator() ;
// Uniform bin size constructor
setRange(xlo,xhi) ;
addUniform(nbins,xlo,xhi) ;
}
RooBinning::RooBinning(Int_t nbins, const Double_t* boundaries) : _array(0), _ownBoundHi(kTRUE), _ownBoundLo(kTRUE)
{
_bIter = binIterator() ;
// Variable bin size constructor
setRange(boundaries[0],boundaries[nbins-1]) ;
while(nbins--) addBoundary(boundaries[nbins]) ;
}
RooBinning::RooBinning(const RooBinning& other) : _array(0)
{
// Copy constructor
_boundaries.Delete() ;
_bIter = binIterator();
other._bIter->Reset() ;
RooDouble* boundary ;
while (boundary=(RooDouble*)other._bIter->Next()) {
addBoundary((Double_t)*boundary) ;
}
_xlo = other._xlo ;
_xhi = other._xhi ;
_ownBoundLo = other._ownBoundLo ;
_ownBoundHi = other._ownBoundHi ;
_nbins = other._nbins ;
}
RooBinning::~RooBinning()
{
// Destructor
delete _bIter ;
if (_array) delete[] _array ;
_boundaries.Delete() ;
}
Bool_t RooBinning::addBoundary(Double_t boundary)
{
// Check if boundary already exists
if (hasBoundary(boundary)) {
// If boundary previously existed as range delimiter,
// convert to regular boundary now
if (boundary==_xlo) _ownBoundLo = kFALSE ;
if (boundary==_xhi) _ownBoundHi = kFALSE ;
return kFALSE ;
}
// Add a new boundary
_boundaries.Add(new RooDouble(boundary)) ;
_boundaries.Sort() ;
updateBinCount() ;
return kTRUE ;
}
void RooBinning::addBoundaryPair(Double_t boundary, Double_t mirrorPoint)
{
// Add mirrored pair of boundaries
addBoundary(boundary) ;
addBoundary(2*mirrorPoint-boundary) ;
}
Bool_t RooBinning::removeBoundary(Double_t boundary)
{
// Remove boundary at given value
_bIter->Reset() ;
RooDouble* b ;
while(b=(RooDouble*)_bIter->Next()) {
if (((Double_t)(*b))==boundary) {
// If boundary is also range delimiter don't delete
if (boundary!= _xlo && boundary != _xhi) {
_boundaries.Remove(b) ;
delete b ;
}
return kFALSE ;
}
}
// Return error status - no boundary found
return kTRUE ;
}
Bool_t RooBinning::hasBoundary(Double_t boundary)
{
// Check if boundary exists at given value
_bIter->Reset() ;
RooDouble* b ;
while(b=(RooDouble*)_bIter->Next()) {
if (((Double_t)(*b))==boundary) {
return kTRUE ;
}
}
return kFALSE ;
}
void RooBinning::addUniform(Int_t nbins, Double_t xlo, Double_t xhi)
{
// Add array of uniform bins
Int_t i ;
Double_t binw = (xhi-xlo)/nbins ;
for (i=0 ; i<=nbins ; i++)
addBoundary(xlo+i*binw) ;
}
Int_t RooBinning::binNumber(Double_t x) const
{
// Determine sequential bin number for given value
Int_t n(0) ;
_bIter->Reset() ;
RooDouble* b ;
while(b=(RooDouble*)_bIter->Next()) {
Double_t val = (Double_t)*b ;
if (x<val) {
return n ;
}
// Only increment counter in valid range
if (val> _xlo && n<_nbins-1) n++ ;
}
return n;
}
TIterator* RooBinning::binIterator() const
{
// Return iterator over sorted boundaries
return _boundaries.MakeIterator() ;
}
Double_t* RooBinning::array() const
{
if (_array) delete[] _array ;
_array = new Double_t[numBoundaries()] ;
_bIter->Reset() ;
RooDouble* boundary ;
Int_t i(0) ;
while(boundary=(RooDouble*)_bIter->Next()) {
Double_t bval = (Double_t)*boundary ;
if (bval>=_xlo && bval <=_xhi) {
_array[i++] = bval ;
}
}
return _array ;
}
void RooBinning::setRange(Double_t xlo, Double_t xhi)
{
if (xlo>xhi) {
cout << "RooUniformBinning::setRange: ERROR low bound > high bound" << endl ;
return ;
}
// Remove previous boundaries
_bIter->Reset() ;
RooDouble* b ;
while(b=(RooDouble*)_bIter->Next()) {
if (((Double_t)*b == _xlo && _ownBoundLo) ||
((Double_t)*b == _xhi && _ownBoundHi)) {
_boundaries.Remove(b) ;
delete b ;
}
}
// Insert boundaries at range delimiter, if necessary
_ownBoundLo = kFALSE ;
_ownBoundHi = kFALSE ;
if (!hasBoundary(xlo)) {
addBoundary(xlo) ;
_ownBoundLo = kTRUE ;
}
if (!hasBoundary(xhi)) {
addBoundary(xhi) ;
_ownBoundHi = kTRUE ;
}
_xlo = xlo ;
_xhi = xhi ;
// Count number of bins with new range
updateBinCount() ;
}
// OK
void RooBinning::updateBinCount()
{
_bIter->Reset() ;
RooDouble* boundary ;
Int_t i(-1) ;
while(boundary=(RooDouble*)_bIter->Next()) {
Double_t bval = (Double_t)*boundary ;
if (bval>=_xlo && bval <=_xhi) {
i++ ;
}
}
_nbins = i ;
}
// not OK
Bool_t RooBinning::binEdges(Int_t bin, Double_t& xlo, Double_t& xhi) const
{
if (bin<0 || bin>= _nbins) {
cout << "RooBinning::binEdges ERROR: bin number must be in range (0," << _nbins << ")" << endl ;
return kTRUE ;
}
// Determine sequential bin number for given value
Int_t n(0) ;
_bIter->Reset() ;
RooDouble* b ;
while(b=(RooDouble*)_bIter->Next()) {
Double_t val = (Double_t)*b ;
if (n==bin && val>=_xlo) {
xlo = val ;
b = (RooDouble*)_bIter->Next() ;
xhi = *b ;
return kFALSE ;
}
// Only increment counter in valid range
if (val>= _xlo && n<_nbins-1) n++ ;
}
return kTRUE ;
}
Double_t RooBinning::binCenter(Int_t bin) const
{
Double_t xlo,xhi ;
if (binEdges(bin,xlo,xhi)) return 0 ;
return (xlo+xhi)/2 ;
}
Double_t RooBinning::binWidth(Int_t bin) const
{
Double_t xlo,xhi ;
if (binEdges(bin,xlo,xhi)) return 0 ;
return (xhi-xlo);
}
Double_t RooBinning::binLow(Int_t bin) const
{
Double_t xlo,xhi ;
if (binEdges(bin,xlo,xhi)) return 0 ;
return xlo ;
}
Double_t RooBinning::binHigh(Int_t bin) const
{
Double_t xlo,xhi ;
if (binEdges(bin,xlo,xhi)) return 0 ;
return xhi ;
}
<commit_msg><commit_after>/*****************************************************************************
* Project: RooFit *
* Package: RooFitCore *
* File: $Id: RooBinning.cc,v 1.6 2002/09/05 22:29:46 verkerke Exp $
* Authors: *
* WV, Wouter Verkerke, UC Santa Barbara, verkerke@slac.stanford.edu *
* DK, David Kirkby, UC Irvine, dkirkby@uci.edu *
* *
* Copyright (c) 2000-2002, Regents of the University of California *
* and Stanford University. All rights reserved. *
* *
* Redistribution and use in source and binary forms, *
* with or without modification, are permitted according to the terms *
* listed in LICENSE (http://roofit.sourceforge.net/license.txt) *
*****************************************************************************/
// -- CLASS DESCRIPTION [MISC] --
// Class RooBinning is an implements RooAbsBinning in terms of
// an array of boundary values, posing no constraints on the
// choice of binning, thus allowing variable bin sizes. Various
// methods allow the user to add single bin boundaries, mirrored pairs,
// or sets of uniformly spaced boundaries.
#include <iostream.h>
#include "RooFitCore/RooBinning.hh"
#include "RooFitCore/RooDouble.hh"
#include "RooFitCore/RooAbsPdf.hh"
#include "RooFitCore/RooRealVar.hh"
#include "RooFitCore/RooNumber.hh"
ClassImp(RooBinning)
;
RooBinning::RooBinning(Double_t xlo, Double_t xhi) : _array(0), _ownBoundHi(kTRUE), _ownBoundLo(kTRUE)
{
_bIter = binIterator() ;
setRange(xlo,xhi) ;
}
RooBinning::RooBinning(Int_t nbins, Double_t xlo, Double_t xhi) : _array(0), _ownBoundHi(kTRUE), _ownBoundLo(kTRUE)
{
_bIter = binIterator() ;
// Uniform bin size constructor
setRange(xlo,xhi) ;
addUniform(nbins,xlo,xhi) ;
}
RooBinning::RooBinning(Int_t nbins, const Double_t* boundaries) : _array(0), _ownBoundHi(kTRUE), _ownBoundLo(kTRUE)
{
_bIter = binIterator() ;
// Variable bin size constructor
setRange(boundaries[0],boundaries[nbins]) ;
while(nbins--) addBoundary(boundaries[nbins]) ;
}
RooBinning::RooBinning(const RooBinning& other) : _array(0)
{
// Copy constructor
_boundaries.Delete() ;
_bIter = binIterator();
other._bIter->Reset() ;
RooDouble* boundary ;
while (boundary=(RooDouble*)other._bIter->Next()) {
addBoundary((Double_t)*boundary) ;
}
_xlo = other._xlo ;
_xhi = other._xhi ;
_ownBoundLo = other._ownBoundLo ;
_ownBoundHi = other._ownBoundHi ;
_nbins = other._nbins ;
}
RooBinning::~RooBinning()
{
// Destructor
delete _bIter ;
if (_array) delete[] _array ;
_boundaries.Delete() ;
}
Bool_t RooBinning::addBoundary(Double_t boundary)
{
// Check if boundary already exists
if (hasBoundary(boundary)) {
// If boundary previously existed as range delimiter,
// convert to regular boundary now
if (boundary==_xlo) _ownBoundLo = kFALSE ;
if (boundary==_xhi) _ownBoundHi = kFALSE ;
return kFALSE ;
}
// Add a new boundary
_boundaries.Add(new RooDouble(boundary)) ;
_boundaries.Sort() ;
updateBinCount() ;
return kTRUE ;
}
void RooBinning::addBoundaryPair(Double_t boundary, Double_t mirrorPoint)
{
// Add mirrored pair of boundaries
addBoundary(boundary) ;
addBoundary(2*mirrorPoint-boundary) ;
}
Bool_t RooBinning::removeBoundary(Double_t boundary)
{
// Remove boundary at given value
_bIter->Reset() ;
RooDouble* b ;
while(b=(RooDouble*)_bIter->Next()) {
if (((Double_t)(*b))==boundary) {
// If boundary is also range delimiter don't delete
if (boundary!= _xlo && boundary != _xhi) {
_boundaries.Remove(b) ;
delete b ;
}
return kFALSE ;
}
}
// Return error status - no boundary found
return kTRUE ;
}
Bool_t RooBinning::hasBoundary(Double_t boundary)
{
// Check if boundary exists at given value
_bIter->Reset() ;
RooDouble* b ;
while(b=(RooDouble*)_bIter->Next()) {
if (((Double_t)(*b))==boundary) {
return kTRUE ;
}
}
return kFALSE ;
}
void RooBinning::addUniform(Int_t nbins, Double_t xlo, Double_t xhi)
{
// Add array of uniform bins
Int_t i ;
Double_t binw = (xhi-xlo)/nbins ;
for (i=0 ; i<=nbins ; i++)
addBoundary(xlo+i*binw) ;
}
Int_t RooBinning::binNumber(Double_t x) const
{
// Determine sequential bin number for given value
Int_t n(0) ;
_bIter->Reset() ;
RooDouble* b ;
while(b=(RooDouble*)_bIter->Next()) {
Double_t val = (Double_t)*b ;
if (x<val) {
return n ;
}
// Only increment counter in valid range
if (val> _xlo && n<_nbins-1) n++ ;
}
return n;
}
TIterator* RooBinning::binIterator() const
{
// Return iterator over sorted boundaries
return _boundaries.MakeIterator() ;
}
Double_t* RooBinning::array() const
{
if (_array) delete[] _array ;
_array = new Double_t[numBoundaries()] ;
_bIter->Reset() ;
RooDouble* boundary ;
Int_t i(0) ;
while(boundary=(RooDouble*)_bIter->Next()) {
Double_t bval = (Double_t)*boundary ;
if (bval>=_xlo && bval <=_xhi) {
_array[i++] = bval ;
}
}
return _array ;
}
void RooBinning::setRange(Double_t xlo, Double_t xhi)
{
if (xlo>xhi) {
cout << "RooUniformBinning::setRange: ERROR low bound > high bound" << endl ;
return ;
}
// Remove previous boundaries
_bIter->Reset() ;
RooDouble* b ;
while(b=(RooDouble*)_bIter->Next()) {
if (((Double_t)*b == _xlo && _ownBoundLo) ||
((Double_t)*b == _xhi && _ownBoundHi)) {
_boundaries.Remove(b) ;
delete b ;
}
}
// Insert boundaries at range delimiter, if necessary
_ownBoundLo = kFALSE ;
_ownBoundHi = kFALSE ;
if (!hasBoundary(xlo)) {
addBoundary(xlo) ;
_ownBoundLo = kTRUE ;
}
if (!hasBoundary(xhi)) {
addBoundary(xhi) ;
_ownBoundHi = kTRUE ;
}
_xlo = xlo ;
_xhi = xhi ;
// Count number of bins with new range
updateBinCount() ;
}
// OK
void RooBinning::updateBinCount()
{
_bIter->Reset() ;
RooDouble* boundary ;
Int_t i(-1) ;
while(boundary=(RooDouble*)_bIter->Next()) {
Double_t bval = (Double_t)*boundary ;
if (bval>=_xlo && bval <=_xhi) {
i++ ;
}
}
_nbins = i ;
}
// not OK
Bool_t RooBinning::binEdges(Int_t bin, Double_t& xlo, Double_t& xhi) const
{
if (bin<0 || bin>= _nbins) {
cout << "RooBinning::binEdges ERROR: bin number must be in range (0," << _nbins << ")" << endl ;
return kTRUE ;
}
// Determine sequential bin number for given value
Int_t n(0) ;
_bIter->Reset() ;
RooDouble* b ;
while(b=(RooDouble*)_bIter->Next()) {
Double_t val = (Double_t)*b ;
if (n==bin && val>=_xlo) {
xlo = val ;
b = (RooDouble*)_bIter->Next() ;
xhi = *b ;
return kFALSE ;
}
// Only increment counter in valid range
if (val>= _xlo && n<_nbins-1) n++ ;
}
return kTRUE ;
}
Double_t RooBinning::binCenter(Int_t bin) const
{
Double_t xlo,xhi ;
if (binEdges(bin,xlo,xhi)) return 0 ;
return (xlo+xhi)/2 ;
}
Double_t RooBinning::binWidth(Int_t bin) const
{
Double_t xlo,xhi ;
if (binEdges(bin,xlo,xhi)) return 0 ;
return (xhi-xlo);
}
Double_t RooBinning::binLow(Int_t bin) const
{
Double_t xlo,xhi ;
if (binEdges(bin,xlo,xhi)) return 0 ;
return xlo ;
}
Double_t RooBinning::binHigh(Int_t bin) const
{
Double_t xlo,xhi ;
if (binEdges(bin,xlo,xhi)) return 0 ;
return xhi ;
}
<|endoftext|> |
<commit_before>/*
* Copyright 2013 Jonathan R. Guthrie
*
* 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 "appendhandler.hpp"
#include "imapmaster.hpp"
ImapHandler *appendHandler(ImapSession *session, INPUT_DATA_STRUCT &input) {
(void) input;
return new AppendHandler(session, session->parseBuffer(), session->store());
}
// Parse stage is 0 if it doesn't have a mailbox name, and 1 if it does. There are no other significant states
IMAP_RESULTS AppendHandler::execute(INPUT_DATA_STRUCT &input) {
IMAP_RESULTS result = IMAP_BAD;
DateTime messageDateTime;
if (m_parseStage < 3) {
if ((2 < (input.dataLen - input.parsingAt)) && (' ' == input.data[input.parsingAt++])) {
if ('(' == input.data[input.parsingAt]) {
++input.parsingAt;
bool flagsOk;
m_mailFlags = m_parseBuffer->readEmailFlags(input, flagsOk);
if (flagsOk && (2 < (input.dataLen - input.parsingAt)) &&
(')' == input.data[input.parsingAt]) && (' ' == input.data[input.parsingAt+1])) {
input.parsingAt += 2;
}
else {
m_session->responseText("Malformed Command");
}
}
else {
m_mailFlags = 0;
}
if ('"' == input.data[input.parsingAt]) {
++input.parsingAt;
// The constructor for DateTime swallows both the leading and trailing
// double quote characters
if (messageDateTime.parse(input.data, input.dataLen, input.parsingAt, DateTime::IMAP) &&
('"' == input.data[input.parsingAt]) &&
(' ' == input.data[input.parsingAt+1])) {
input.parsingAt += 2;
}
else {
m_session->responseText("Malformed Command");
}
}
if ((2 < (input.dataLen - input.parsingAt)) && ('{' == input.data[input.parsingAt])) {
// It's a literal string
input.parsingAt++; // Skip the curly brace
char *close;
// read the number
m_parseBuffer->literalLength(strtoul((char *)&input.data[input.parsingAt], &close, 10));
// check for the close curly brace and end of message and to see if I can fit all that data
// into the buffer
size_t lastChar = (size_t) (close - ((char *)input.data));
if ((NULL == close) || ('}' != close[0]) || (lastChar != (input.dataLen - 1))) {
m_session->responseText("Malformed Command");
}
else {
m_parseStage = 2;
result = IMAP_OK;
}
}
else {
m_session->responseText("Malformed Command");
}
}
else {
m_session->responseText("Malformed Command");
}
}
else {
result = IMAP_OK;
}
if (IMAP_OK == result) {
MailStore::MAIL_STORE_RESULT mlr;
m_tempMailboxName = m_parseBuffer->arguments();
if (MailStore::SUCCESS == (mlr = m_store->lock(m_tempMailboxName))) {
switch (m_store->addMessageToMailbox(m_tempMailboxName, m_session->lineBuffer(), 0, messageDateTime, m_mailFlags, &m_appendingUid)) {
case MailStore::SUCCESS:
m_session->responseText("Ready for the Message Data");
m_parseStage = 3;
result = IMAP_NOTDONE;
break;
case MailStore::CANNOT_COMPLETE_ACTION:
result = IMAP_TRY_AGAIN;
break;
default:
result = IMAP_MBOX_ERROR;
break;
}
}
else {
result = IMAP_MBOX_ERROR;
if (MailStore::CANNOT_COMPLETE_ACTION == mlr) {
result = IMAP_TRY_AGAIN;
}
}
}
return result;
}
IMAP_RESULTS AppendHandler::receiveData(INPUT_DATA_STRUCT &input) {
IMAP_RESULTS result = IMAP_OK;
switch (m_parseStage) {
case 0:
switch (m_parseBuffer->astring(input, false, NULL)) {
case ImapStringGood:
result = execute(input);
break;
case ImapStringBad:
m_session->responseText("Malformed Command");
result = IMAP_BAD;
break;
case ImapStringPending:
result = IMAP_NOTDONE;
m_parseStage = 1;
break;
default:
m_session->responseText("Failed -- internal error");
result = IMAP_NO;
break;
}
break;
case 1:
// It's the mailbox name that's arrived
{
size_t dataUsed = m_parseBuffer->addLiteralToParseBuffer(input);
if (dataUsed <= input.dataLen) {
m_parseStage = 2;
if (2 < (input.dataLen - dataUsed)) {
// Get rid of the CRLF if I have it
input.dataLen -= 2;
input.data[input.dataLen] = '\0'; // Make sure it's terminated so strchr et al work
}
result = execute(input);
}
else {
result = IMAP_IN_LITERAL;
}
}
break;
case 2:
{
result = execute(input);
}
break;
case 3:
{
size_t residue;
// It's the message body that's arrived
size_t len = MIN(m_parseBuffer->literalLength(), input.dataLen);
if (m_parseBuffer->literalLength() > input.dataLen) {
result = IMAP_IN_LITERAL;
residue = input.dataLen - m_parseBuffer->literalLength();
}
else {
residue = 0;
}
m_parseBuffer->literalLength(residue);
std::string mailbox(m_parseBuffer->arguments());
switch (m_store->appendDataToMessage(mailbox, m_appendingUid, input.data, len)) {
case MailStore::SUCCESS:
result = IMAP_MBOX_ERROR;
if (0 == m_parseBuffer->literalLength()) {
m_parseStage = 4;
switch(m_store->doneAppendingDataToMessage(mailbox, m_appendingUid)) {
case MailStore::SUCCESS:
if (MailStore::SUCCESS == m_store->unlock(m_tempMailboxName)) {
result = IMAP_OK;
}
else {
m_store->deleteMessage(mailbox, m_appendingUid);
result = IMAP_MBOX_ERROR;
}
m_appendingUid = 0;
result = IMAP_OK;
break;
case MailStore::CANNOT_COMPLETE_ACTION:
result = IMAP_TRY_AGAIN;
break;
default:
m_store->deleteMessage(mailbox, m_appendingUid);
m_appendingUid = 0;
result = IMAP_MBOX_ERROR;
}
}
break;
case MailStore::CANNOT_COMPLETE_ACTION:
result = IMAP_TRY_AGAIN;
break;
default:
m_store->doneAppendingDataToMessage(mailbox, m_appendingUid);
m_store->deleteMessage(mailbox, m_appendingUid);
m_store->unlock(m_tempMailboxName);
result = IMAP_MBOX_ERROR;
m_appendingUid = 0;
m_parseBuffer->literalLength(0);
break;
}
}
break;
case 4:
// I've got the last of the data, and I'm retrying the done appending code
{
std::string mailbox(m_parseBuffer->arguments());
switch(m_store->doneAppendingDataToMessage(mailbox, m_appendingUid)) {
case MailStore::SUCCESS:
if (MailStore::SUCCESS == m_store->unlock(m_tempMailboxName)) {
result = IMAP_OK;
}
else {
m_store->deleteMessage(mailbox, m_appendingUid);
result = IMAP_MBOX_ERROR;
}
m_appendingUid = 0;
break;
case MailStore::CANNOT_COMPLETE_ACTION:
result = IMAP_TRY_AGAIN;
break;
default:
m_store->deleteMessage(mailbox, m_appendingUid);
m_appendingUid = 0;
result = IMAP_MBOX_ERROR;
}
m_tempMailboxName = "";
}
break;
default:
m_session->responseText("Failed -- internal error");
result = IMAP_NO;
break;
}
return result;
}
<commit_msg>Fix a comment that was incorrect.<commit_after>/*
* Copyright 2013 Jonathan R. Guthrie
*
* 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 "appendhandler.hpp"
#include "imapmaster.hpp"
ImapHandler *appendHandler(ImapSession *session, INPUT_DATA_STRUCT &input) {
(void) input;
return new AppendHandler(session, session->parseBuffer(), session->store());
}
// Parse stage is 0 if it doesn't have a mailbox name, and 1 if it is waiting for one, 2 if the name has arrived, and 3 if it's receiving message data.
IMAP_RESULTS AppendHandler::execute(INPUT_DATA_STRUCT &input) {
IMAP_RESULTS result = IMAP_BAD;
DateTime messageDateTime;
if (m_parseStage < 3) {
if ((2 < (input.dataLen - input.parsingAt)) && (' ' == input.data[input.parsingAt++])) {
if ('(' == input.data[input.parsingAt]) {
++input.parsingAt;
bool flagsOk;
m_mailFlags = m_parseBuffer->readEmailFlags(input, flagsOk);
if (flagsOk && (2 < (input.dataLen - input.parsingAt)) &&
(')' == input.data[input.parsingAt]) && (' ' == input.data[input.parsingAt+1])) {
input.parsingAt += 2;
}
else {
m_session->responseText("Malformed Command");
}
}
else {
m_mailFlags = 0;
}
if ('"' == input.data[input.parsingAt]) {
++input.parsingAt;
// The constructor for DateTime swallows both the leading and trailing
// double quote characters
if (messageDateTime.parse(input.data, input.dataLen, input.parsingAt, DateTime::IMAP) &&
('"' == input.data[input.parsingAt]) &&
(' ' == input.data[input.parsingAt+1])) {
input.parsingAt += 2;
}
else {
m_session->responseText("Malformed Command");
}
}
if ((2 < (input.dataLen - input.parsingAt)) && ('{' == input.data[input.parsingAt])) {
// It's a literal string
input.parsingAt++; // Skip the curly brace
char *close;
// read the number
m_parseBuffer->literalLength(strtoul((char *)&input.data[input.parsingAt], &close, 10));
// check for the close curly brace and end of message and to see if I can fit all that data
// into the buffer
size_t lastChar = (size_t) (close - ((char *)input.data));
if ((NULL == close) || ('}' != close[0]) || (lastChar != (input.dataLen - 1))) {
m_session->responseText("Malformed Command");
}
else {
m_parseStage = 2;
result = IMAP_OK;
}
}
else {
m_session->responseText("Malformed Command");
}
}
else {
m_session->responseText("Malformed Command");
}
}
else {
result = IMAP_OK;
}
if (IMAP_OK == result) {
MailStore::MAIL_STORE_RESULT mlr;
m_tempMailboxName = m_parseBuffer->arguments();
if (MailStore::SUCCESS == (mlr = m_store->lock(m_tempMailboxName))) {
switch (m_store->addMessageToMailbox(m_tempMailboxName, m_session->lineBuffer(), 0, messageDateTime, m_mailFlags, &m_appendingUid)) {
case MailStore::SUCCESS:
m_session->responseText("Ready for the Message Data");
m_parseStage = 3;
result = IMAP_NOTDONE;
break;
case MailStore::CANNOT_COMPLETE_ACTION:
result = IMAP_TRY_AGAIN;
break;
default:
result = IMAP_MBOX_ERROR;
break;
}
}
else {
result = IMAP_MBOX_ERROR;
if (MailStore::CANNOT_COMPLETE_ACTION == mlr) {
result = IMAP_TRY_AGAIN;
}
}
}
return result;
}
IMAP_RESULTS AppendHandler::receiveData(INPUT_DATA_STRUCT &input) {
IMAP_RESULTS result = IMAP_OK;
switch (m_parseStage) {
case 0:
switch (m_parseBuffer->astring(input, false, NULL)) {
case ImapStringGood:
result = execute(input);
break;
case ImapStringBad:
m_session->responseText("Malformed Command");
result = IMAP_BAD;
break;
case ImapStringPending:
result = IMAP_NOTDONE;
m_parseStage = 1;
break;
default:
m_session->responseText("Failed -- internal error");
result = IMAP_NO;
break;
}
break;
case 1:
// It's the mailbox name that's arrived
{
size_t dataUsed = m_parseBuffer->addLiteralToParseBuffer(input);
if (dataUsed <= input.dataLen) {
m_parseStage = 2;
if (2 < (input.dataLen - dataUsed)) {
// Get rid of the CRLF if I have it
input.dataLen -= 2;
input.data[input.dataLen] = '\0'; // Make sure it's terminated so strchr et al work
}
result = execute(input);
}
else {
result = IMAP_IN_LITERAL;
}
}
break;
case 2:
{
result = execute(input);
}
break;
case 3:
{
size_t residue;
// It's the message body that's arrived
size_t len = MIN(m_parseBuffer->literalLength(), input.dataLen);
if (m_parseBuffer->literalLength() > input.dataLen) {
result = IMAP_IN_LITERAL;
residue = input.dataLen - m_parseBuffer->literalLength();
}
else {
residue = 0;
}
m_parseBuffer->literalLength(residue);
std::string mailbox(m_parseBuffer->arguments());
switch (m_store->appendDataToMessage(mailbox, m_appendingUid, input.data, len)) {
case MailStore::SUCCESS:
result = IMAP_MBOX_ERROR;
if (0 == m_parseBuffer->literalLength()) {
m_parseStage = 4;
switch(m_store->doneAppendingDataToMessage(mailbox, m_appendingUid)) {
case MailStore::SUCCESS:
if (MailStore::SUCCESS == m_store->unlock(m_tempMailboxName)) {
result = IMAP_OK;
}
else {
m_store->deleteMessage(mailbox, m_appendingUid);
result = IMAP_MBOX_ERROR;
}
m_appendingUid = 0;
result = IMAP_OK;
break;
case MailStore::CANNOT_COMPLETE_ACTION:
result = IMAP_TRY_AGAIN;
break;
default:
m_store->deleteMessage(mailbox, m_appendingUid);
m_appendingUid = 0;
result = IMAP_MBOX_ERROR;
}
}
break;
case MailStore::CANNOT_COMPLETE_ACTION:
result = IMAP_TRY_AGAIN;
break;
default:
m_store->doneAppendingDataToMessage(mailbox, m_appendingUid);
m_store->deleteMessage(mailbox, m_appendingUid);
m_store->unlock(m_tempMailboxName);
result = IMAP_MBOX_ERROR;
m_appendingUid = 0;
m_parseBuffer->literalLength(0);
break;
}
}
break;
case 4:
// I've got the last of the data, and I'm retrying the done appending code
{
std::string mailbox(m_parseBuffer->arguments());
switch(m_store->doneAppendingDataToMessage(mailbox, m_appendingUid)) {
case MailStore::SUCCESS:
if (MailStore::SUCCESS == m_store->unlock(m_tempMailboxName)) {
result = IMAP_OK;
}
else {
m_store->deleteMessage(mailbox, m_appendingUid);
result = IMAP_MBOX_ERROR;
}
m_appendingUid = 0;
break;
case MailStore::CANNOT_COMPLETE_ACTION:
result = IMAP_TRY_AGAIN;
break;
default:
m_store->deleteMessage(mailbox, m_appendingUid);
m_appendingUid = 0;
result = IMAP_MBOX_ERROR;
}
m_tempMailboxName = "";
}
break;
default:
m_session->responseText("Failed -- internal error");
result = IMAP_NO;
break;
}
return result;
}
<|endoftext|> |
<commit_before>#ifndef rpl_utils_hpp
#define rpl_utils_hpp
#include <string>
namespace utils {
template <typename T>
std::string to_string(const T& t) {
std::string str{ std::to_string(t) };
int offset = 1;
if ( str.find_last_not_of('0') == str.find('.') ) {
offset = 0;
}
str.erase( str.find_last_not_of('0') + offset, std::string::npos);
return str;
}
}
#endif
<commit_msg>utils functions<commit_after>#ifndef rpl_utils_hpp
#define rpl_utils_hpp
#include <string>
#include <cmath>
namespace utils {
template <typename T>
std::string to_string(const T& t) {
std::string str{ std::to_string(t) };
int offset = 1;
if ( str.find_last_not_of('0') == str.find('.') ) {
offset = 0;
}
str.erase( str.find_last_not_of('0') + offset, std::string::npos);
return str;
}
template <typename T>
std::size_t count_digits(const T& n) {
if ( n == 0 ) return 1;
return std::floor( std::log10(n) + 1 );
}
template <typename T>
std::string get_spaces(const T& num) {
return num > 0 ? std::string(num, ' ') : "";
}
template <typename T>
std::string get_idx(const T& idx, const T& max_idx) {
std::size_t num_spaces = count_digits(max_idx) - count_digits(idx);
return get_spaces(num_spaces) + "[" + std::to_string(idx) + "]";
}
}
#endif
<|endoftext|> |
<commit_before>/*
Resembla: Word-based Japanese similar sentence search library
https://github.com/tuem/resembla
Copyright 2017 Takashi Uemura
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
#ifndef __KEYWORD_MATCH_PREPROCESSOR_HPP__
#define __KEYWORD_MATCH_PREPROCESSOR_HPP__
#include <string>
#include <vector>
#include <iostream>
namespace resembla {
template<typename string_type>
class KeywordMatchPreprocessor
{
public:
struct output_type
{
string_type text;
std::vector<string_type> keywords;
};
using output_type = output_type;
KeywordMatchPreprocessor()
/*
KeywordMatchPreprocessor(std::string synonym_path, size_t text_col, size_t features_col,
const std::string feature_key, size_t keyword_delimiter):
text_col(text_col), features_col(features_col),
feature_key(feature_key), keyword_delimiter(keyword_delimiter)
*/
{
// TODO: loadSynonyms(synonym_path);
}
output_type operator()(const string_type& raw_text, bool is_original = false) const
{
if(!is_original){
return {raw_text, {}};
}
std::cerr << "load text: " << cast_string<std::string>(raw_text) << std::endl;
auto columns = split(raw_text, L'\t');//TODO
if(columns.size() > 1){
for(auto f: split(columns[1], L'&')){
auto kv = split(f, L'=');
if(kv.size() == 2 && kv[0] == L"keyword"){
#ifdef DEBUG
for(auto w: split(kv[1], L',')){
std::cerr << "load keyword: text=" << cast_string<std::string>(columns[0]) << ", keyword=" << cast_string<std::string>(w) << std::endl;
}
#endif
return {columns[0], split(kv[1], L',')};
}
}
return {columns[0], {}};
}
return {raw_text, {}};
}
string_type index(const string_type& text) const
{
return text;
}
protected:
// std::vector<std::vector<string_type>> synonyms;
// std::unordered_map<string_type, size_t> synonym_index;
};
}
#endif
<commit_msg>add TODO comment<commit_after>/*
Resembla: Word-based Japanese similar sentence search library
https://github.com/tuem/resembla
Copyright 2017 Takashi Uemura
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
#ifndef __KEYWORD_MATCH_PREPROCESSOR_HPP__
#define __KEYWORD_MATCH_PREPROCESSOR_HPP__
#include <string>
#include <vector>
#include <iostream>
namespace resembla {
template<typename string_type>
class KeywordMatchPreprocessor
{
public:
struct output_type
{
string_type text;
std::vector<string_type> keywords;
};
using output_type = output_type;
KeywordMatchPreprocessor()
{
// TODO: loadSynonyms(synonym_path);
}
output_type operator()(const string_type& raw_text, bool is_original = false) const
{
if(!is_original){
return {raw_text, {}};
}
std::cerr << "load text: " << cast_string<std::string>(raw_text) << std::endl;
auto columns = split(raw_text, L'\t');//TODO
if(columns.size() > 1){
for(auto f: split(columns[1], L'&')){
auto kv = split(f, L'=');
if(kv.size() == 2 && kv[0] == L"keyword"){
#ifdef DEBUG
for(auto w: split(kv[1], L',')){
std::cerr << "load keyword: text=" << cast_string<std::string>(columns[0]) << ", keyword=" << cast_string<std::string>(w) << std::endl;
}
#endif
return {columns[0], split(kv[1], L',')};
}
}
return {columns[0], {}};
}
return {raw_text, {}};
}
string_type index(const string_type& text) const
{
return text;
}
protected:
// TODO: use synonym dictionary to improve keyword matching quality
// std::vector<std::vector<string_type>> synonyms;
// std::unordered_map<string_type, size_t> synonym_index;
};
}
#endif
<|endoftext|> |
<commit_before>/*
* The Apache Software License, Version 1.1
*
*
* Copyright (c) 1999-2002 The Apache Software Foundation. All rights
* reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* 3. The end-user documentation included with the redistribution,
* if any, must include the following acknowledgment:
* "This product includes software developed by the
* Apache Software Foundation (http://www.apache.org/)."
* Alternately, this acknowledgment may appear in the software itself,
* if and wherever such third-party acknowledgments normally appear.
*
* 4. The names "Xalan" and "Apache Software Foundation" must
* not be used to endorse or promote products derived from this
* software without prior written permission. For written
* permission, please contact apache@apache.org.
*
* 5. Products derived from this software may not be called "Apache",
* nor may "Apache" appear in their name, without prior written
* permission of the Apache Software Foundation.
*
* THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR
* ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
* USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
* OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation and was
* originally based on software copyright (c) 1999, International
* Business Machines, Inc., http://www.ibm.com. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
* @author <a href="mailto:david_n_bertoni@lotus.com">David N. Bertoni</a>
*/
#include "XPathEnvSupportDefault.hpp"
#include <algorithm>
#if defined(XALAN_CLASSIC_IOSTREAMS)
#include <iostream.h>
#else
#include <iostream>
#endif
#include <Include/STLHelper.hpp>
#include <PlatformSupport/DOMStringHelper.hpp>
#include <DOMSupport/DOMServices.hpp>
#include "XObject.hpp"
#include "XObjectFactory.hpp"
#include "XPath.hpp"
#include "XPathExecutionContext.hpp"
#if !defined(XALAN_NO_STD_NAMESPACE)
using std::cerr;
using std::endl;
using std::for_each;
#endif
XALAN_CPP_NAMESPACE_BEGIN
XPathEnvSupportDefault::NamespaceFunctionTablesType XPathEnvSupportDefault::s_externalFunctions;
void
XPathEnvSupportDefault::initialize()
{
}
void
XPathEnvSupportDefault::terminate()
{
// Clean up the extension namespaces vector
for_each(s_externalFunctions.begin(),
s_externalFunctions.end(),
NamespaceFunctionTableDeleteFunctor());
NamespaceFunctionTablesType().swap(s_externalFunctions);
}
XPathEnvSupportDefault::XPathEnvSupportDefault() :
XPathEnvSupport(),
m_sourceDocs(),
m_externalFunctions()
{
}
XPathEnvSupportDefault::~XPathEnvSupportDefault()
{
// Clean up the extension namespaces vector
for_each(m_externalFunctions.begin(),
m_externalFunctions.end(),
NamespaceFunctionTableDeleteFunctor());
NamespaceFunctionTablesType().swap(m_externalFunctions);
}
void
XPathEnvSupportDefault::updateFunctionTable(
NamespaceFunctionTablesType& theTable,
const XalanDOMString& theNamespace,
const XalanDOMString& functionName,
const Function* function)
{
// See if there's a table for that namespace...
const NamespaceFunctionTablesType::iterator i =
theTable.find(theNamespace);
if (i == theTable.end())
{
// The namespace was not found. If function is not
// 0, then add a clone of the function.
if (function != 0)
{
theTable[theNamespace][functionName] =
function->clone();
}
}
else
{
// There is already a table for the namespace,
// so look for the function...
const FunctionTableType::iterator j =
(*i).second.find(functionName);
if (j == (*i).second.end())
{
// The function was not found. If function is not
// 0, then add a clone of the function.
if (function != 0)
{
(*i).second[functionName] = function->clone();
}
}
else
{
// Found it, so delete the function...
#if defined(XALAN_CANNOT_DELETE_CONST)
delete (Function*)(*j).second;
#else
delete (*j).second;
#endif
// If function is not 0, then we update
// the entry. Otherwise, we erase it...
if (function != 0)
{
// Update it...
(*j).second = function->clone();
}
else
{
// Erase it...
(*i).second.erase(j);
}
}
}
}
void
XPathEnvSupportDefault::installExternalFunctionGlobal(
const XalanDOMString& theNamespace,
const XalanDOMString& functionName,
const Function& function)
{
updateFunctionTable(s_externalFunctions, theNamespace, functionName, &function);
}
void
XPathEnvSupportDefault::uninstallExternalFunctionGlobal(
const XalanDOMString& theNamespace,
const XalanDOMString& functionName)
{
updateFunctionTable(s_externalFunctions, theNamespace, functionName, 0);
}
void
XPathEnvSupportDefault::installExternalFunctionLocal(
const XalanDOMString& theNamespace,
const XalanDOMString& functionName,
const Function& function)
{
updateFunctionTable(m_externalFunctions, theNamespace, functionName, &function);
}
void
XPathEnvSupportDefault::uninstallExternalFunctionLocal(
const XalanDOMString& theNamespace,
const XalanDOMString& functionName)
{
updateFunctionTable(m_externalFunctions, theNamespace, functionName, 0);
}
void
XPathEnvSupportDefault::reset()
{
m_sourceDocs.clear();
}
XalanDocument*
XPathEnvSupportDefault::parseXML(
const XalanDOMString& /* urlString */,
const XalanDOMString& /* base */)
{
return 0;
}
XalanDocument*
XPathEnvSupportDefault::getSourceDocument(const XalanDOMString& theURI) const
{
const SourceDocsTableType::const_iterator i =
m_sourceDocs.find(theURI);
if (i == m_sourceDocs.end())
{
return 0;
}
else
{
return (*i).second;
}
}
void
XPathEnvSupportDefault::setSourceDocument(
const XalanDOMString& theURI,
XalanDocument* theDocument)
{
m_sourceDocs[theURI] = theDocument;
}
XalanDOMString
XPathEnvSupportDefault::findURIFromDoc(const XalanDocument* owner) const
{
SourceDocsTableType::const_iterator i =
m_sourceDocs.begin();
bool fFound = false;
while(i != m_sourceDocs.end() && fFound == false)
{
if ((*i).second == owner)
{
fFound = true;
}
else
{
++i;
}
}
return fFound == false ? XalanDOMString() : (*i).first;
}
bool
XPathEnvSupportDefault::elementAvailable(
const XalanDOMString& /* theNamespace */,
const XalanDOMString& /* elementName */) const
{
return false;
}
bool
XPathEnvSupportDefault::functionAvailable(
const XalanDOMString& theNamespace,
const XalanDOMString& functionName) const
{
bool theResult = false;
// Any function without a namespace prefix is considered
// to be an intrinsic function.
if (isEmpty(theNamespace) == true)
{
theResult = XPath::isInstalledFunction(functionName);
}
else
{
const Function* const theFunction =
findFunction(
theNamespace,
functionName);
if (theFunction != 0)
{
theResult = true;
}
}
return theResult;
}
const Function*
XPathEnvSupportDefault::findFunction(
const XalanDOMString& theNamespace,
const XalanDOMString& functionName) const
{
// First, look locally...
const Function* theFunction = findFunction(
m_externalFunctions,
theNamespace,
functionName);
if (theFunction == 0)
{
// Not found, so look in the global space...
theFunction = findFunction(
s_externalFunctions,
theNamespace,
functionName);
}
return theFunction;
}
const Function*
XPathEnvSupportDefault::findFunction(
const NamespaceFunctionTablesType& theTable,
const XalanDOMString& theNamespace,
const XalanDOMString& functionName) const
{
const Function* theFunction = 0;
// See if there's a table for that namespace...
const NamespaceFunctionTablesType::const_iterator i =
theTable.find(theNamespace);
if (i != theTable.end())
{
// There is a table for the namespace,
// so look for the function...
const FunctionTableType::const_iterator j =
(*i).second.find(functionName);
if (j != (*i).second.end())
{
// Found the function...
assert((*j).second != 0);
theFunction = (*j).second;
}
}
return theFunction;
}
XObjectPtr
XPathEnvSupportDefault::extFunction(
XPathExecutionContext& executionContext,
const XalanDOMString& theNamespace,
const XalanDOMString& functionName,
XalanNode* context,
const XObjectArgVectorType& argVec,
const LocatorType* locator) const
{
const Function* const theFunction = findFunction(theNamespace, functionName);
if (theFunction != 0)
{
return theFunction->execute(
executionContext,
context,
argVec,
locator);
}
else
{
XalanDOMString theFunctionName;
if(length(theNamespace) > 0)
{
theFunctionName += theNamespace;
theFunctionName += DOMServices::s_XMLNamespaceSeparatorString;
}
theFunctionName += functionName;
if (locator != 0)
{
throw XPathExceptionFunctionNotAvailable(theFunctionName, *locator);
}
else
{
throw XPathExceptionFunctionNotAvailable(theFunctionName);
}
// dummy return value...
return XObjectPtr();
}
}
bool
XPathEnvSupportDefault::problem(
eSource /* where */,
eClassification classification,
const PrefixResolver* /* resolver */,
const XalanNode* /* sourceNode */,
const XalanDOMString& msg,
const XalanDOMChar* uri,
int lineNo,
int charOffset) const
{
cerr << msg;
if (uri != 0)
{
cerr << ",in " << uri;
}
cerr << ", at line number "
<< lineNo
<< " at offset "
<< charOffset
<< endl;
return classification == XPathEnvSupport::eError ? true : false;
}
void
XPathEnvSupportDefault::NamespaceFunctionTableDeleteFunctor::operator()(const NamespaceFunctionTablesInnerType::value_type& thePair) const
{
#if defined(XALAN_CANNOT_DELETE_CONST)
FunctionTableInnerType::const_iterator i = thePair.second.begin();
while(i != thePair.second.end())
{
delete (Function*) (*i).second;
++i;
}
#else
// Clean up the extension namespaces vector
for_each(thePair.second.begin(),
thePair.second.end(),
MapValueDeleteFunctor<FunctionTableInnerType>());
#endif
}
XALAN_CPP_NAMESPACE_END
<commit_msg>Replaced if defined() section with macros.<commit_after>/*
* The Apache Software License, Version 1.1
*
*
* Copyright (c) 1999-2002 The Apache Software Foundation. All rights
* reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* 3. The end-user documentation included with the redistribution,
* if any, must include the following acknowledgment:
* "This product includes software developed by the
* Apache Software Foundation (http://www.apache.org/)."
* Alternately, this acknowledgment may appear in the software itself,
* if and wherever such third-party acknowledgments normally appear.
*
* 4. The names "Xalan" and "Apache Software Foundation" must
* not be used to endorse or promote products derived from this
* software without prior written permission. For written
* permission, please contact apache@apache.org.
*
* 5. Products derived from this software may not be called "Apache",
* nor may "Apache" appear in their name, without prior written
* permission of the Apache Software Foundation.
*
* THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR
* ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
* USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
* OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation and was
* originally based on software copyright (c) 1999, International
* Business Machines, Inc., http://www.ibm.com. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
* @author <a href="mailto:david_n_bertoni@lotus.com">David N. Bertoni</a>
*/
#include "XPathEnvSupportDefault.hpp"
#include <algorithm>
#if defined(XALAN_CLASSIC_IOSTREAMS)
#include <iostream.h>
#else
#include <iostream>
#endif
#include <Include/STLHelper.hpp>
#include <PlatformSupport/DOMStringHelper.hpp>
#include <DOMSupport/DOMServices.hpp>
#include "XObject.hpp"
#include "XObjectFactory.hpp"
#include "XPath.hpp"
#include "XPathExecutionContext.hpp"
XALAN_USING_STD(cerr)
XALAN_USING_STD(endl)
XALAN_CPP_NAMESPACE_BEGIN
XPathEnvSupportDefault::NamespaceFunctionTablesType XPathEnvSupportDefault::s_externalFunctions;
void
XPathEnvSupportDefault::initialize()
{
}
void
XPathEnvSupportDefault::terminate()
{
XALAN_USING_STD(for_each)
// Clean up the extension namespaces vector
for_each(s_externalFunctions.begin(),
s_externalFunctions.end(),
NamespaceFunctionTableDeleteFunctor());
NamespaceFunctionTablesType().swap(s_externalFunctions);
}
XPathEnvSupportDefault::XPathEnvSupportDefault() :
XPathEnvSupport(),
m_sourceDocs(),
m_externalFunctions()
{
}
XPathEnvSupportDefault::~XPathEnvSupportDefault()
{
XALAN_USING_STD(for_each)
// Clean up the extension namespaces vector
for_each(m_externalFunctions.begin(),
m_externalFunctions.end(),
NamespaceFunctionTableDeleteFunctor());
NamespaceFunctionTablesType().swap(m_externalFunctions);
}
void
XPathEnvSupportDefault::updateFunctionTable(
NamespaceFunctionTablesType& theTable,
const XalanDOMString& theNamespace,
const XalanDOMString& functionName,
const Function* function)
{
// See if there's a table for that namespace...
const NamespaceFunctionTablesType::iterator i =
theTable.find(theNamespace);
if (i == theTable.end())
{
// The namespace was not found. If function is not
// 0, then add a clone of the function.
if (function != 0)
{
theTable[theNamespace][functionName] =
function->clone();
}
}
else
{
// There is already a table for the namespace,
// so look for the function...
const FunctionTableType::iterator j =
(*i).second.find(functionName);
if (j == (*i).second.end())
{
// The function was not found. If function is not
// 0, then add a clone of the function.
if (function != 0)
{
(*i).second[functionName] = function->clone();
}
}
else
{
// Found it, so delete the function...
#if defined(XALAN_CANNOT_DELETE_CONST)
delete (Function*)(*j).second;
#else
delete (*j).second;
#endif
// If function is not 0, then we update
// the entry. Otherwise, we erase it...
if (function != 0)
{
// Update it...
(*j).second = function->clone();
}
else
{
// Erase it...
(*i).second.erase(j);
}
}
}
}
void
XPathEnvSupportDefault::installExternalFunctionGlobal(
const XalanDOMString& theNamespace,
const XalanDOMString& functionName,
const Function& function)
{
updateFunctionTable(s_externalFunctions, theNamespace, functionName, &function);
}
void
XPathEnvSupportDefault::uninstallExternalFunctionGlobal(
const XalanDOMString& theNamespace,
const XalanDOMString& functionName)
{
updateFunctionTable(s_externalFunctions, theNamespace, functionName, 0);
}
void
XPathEnvSupportDefault::installExternalFunctionLocal(
const XalanDOMString& theNamespace,
const XalanDOMString& functionName,
const Function& function)
{
updateFunctionTable(m_externalFunctions, theNamespace, functionName, &function);
}
void
XPathEnvSupportDefault::uninstallExternalFunctionLocal(
const XalanDOMString& theNamespace,
const XalanDOMString& functionName)
{
updateFunctionTable(m_externalFunctions, theNamespace, functionName, 0);
}
void
XPathEnvSupportDefault::reset()
{
m_sourceDocs.clear();
}
XalanDocument*
XPathEnvSupportDefault::parseXML(
const XalanDOMString& /* urlString */,
const XalanDOMString& /* base */)
{
return 0;
}
XalanDocument*
XPathEnvSupportDefault::getSourceDocument(const XalanDOMString& theURI) const
{
const SourceDocsTableType::const_iterator i =
m_sourceDocs.find(theURI);
if (i == m_sourceDocs.end())
{
return 0;
}
else
{
return (*i).second;
}
}
void
XPathEnvSupportDefault::setSourceDocument(
const XalanDOMString& theURI,
XalanDocument* theDocument)
{
m_sourceDocs[theURI] = theDocument;
}
XalanDOMString
XPathEnvSupportDefault::findURIFromDoc(const XalanDocument* owner) const
{
SourceDocsTableType::const_iterator i =
m_sourceDocs.begin();
bool fFound = false;
while(i != m_sourceDocs.end() && fFound == false)
{
if ((*i).second == owner)
{
fFound = true;
}
else
{
++i;
}
}
return fFound == false ? XalanDOMString() : (*i).first;
}
bool
XPathEnvSupportDefault::elementAvailable(
const XalanDOMString& /* theNamespace */,
const XalanDOMString& /* elementName */) const
{
return false;
}
bool
XPathEnvSupportDefault::functionAvailable(
const XalanDOMString& theNamespace,
const XalanDOMString& functionName) const
{
bool theResult = false;
// Any function without a namespace prefix is considered
// to be an intrinsic function.
if (isEmpty(theNamespace) == true)
{
theResult = XPath::isInstalledFunction(functionName);
}
else
{
const Function* const theFunction =
findFunction(
theNamespace,
functionName);
if (theFunction != 0)
{
theResult = true;
}
}
return theResult;
}
const Function*
XPathEnvSupportDefault::findFunction(
const XalanDOMString& theNamespace,
const XalanDOMString& functionName) const
{
// First, look locally...
const Function* theFunction = findFunction(
m_externalFunctions,
theNamespace,
functionName);
if (theFunction == 0)
{
// Not found, so look in the global space...
theFunction = findFunction(
s_externalFunctions,
theNamespace,
functionName);
}
return theFunction;
}
const Function*
XPathEnvSupportDefault::findFunction(
const NamespaceFunctionTablesType& theTable,
const XalanDOMString& theNamespace,
const XalanDOMString& functionName) const
{
const Function* theFunction = 0;
// See if there's a table for that namespace...
const NamespaceFunctionTablesType::const_iterator i =
theTable.find(theNamespace);
if (i != theTable.end())
{
// There is a table for the namespace,
// so look for the function...
const FunctionTableType::const_iterator j =
(*i).second.find(functionName);
if (j != (*i).second.end())
{
// Found the function...
assert((*j).second != 0);
theFunction = (*j).second;
}
}
return theFunction;
}
XObjectPtr
XPathEnvSupportDefault::extFunction(
XPathExecutionContext& executionContext,
const XalanDOMString& theNamespace,
const XalanDOMString& functionName,
XalanNode* context,
const XObjectArgVectorType& argVec,
const LocatorType* locator) const
{
const Function* const theFunction = findFunction(theNamespace, functionName);
if (theFunction != 0)
{
return theFunction->execute(
executionContext,
context,
argVec,
locator);
}
else
{
XalanDOMString theFunctionName;
if(length(theNamespace) > 0)
{
theFunctionName += theNamespace;
theFunctionName += DOMServices::s_XMLNamespaceSeparatorString;
}
theFunctionName += functionName;
if (locator != 0)
{
throw XPathExceptionFunctionNotAvailable(theFunctionName, *locator);
}
else
{
throw XPathExceptionFunctionNotAvailable(theFunctionName);
}
// dummy return value...
return XObjectPtr();
}
}
bool
XPathEnvSupportDefault::problem(
eSource /* where */,
eClassification classification,
const PrefixResolver* /* resolver */,
const XalanNode* /* sourceNode */,
const XalanDOMString& msg,
const XalanDOMChar* uri,
int lineNo,
int charOffset) const
{
cerr << msg;
if (uri != 0)
{
cerr << ",in " << uri;
}
cerr << ", at line number "
<< lineNo
<< " at offset "
<< charOffset
<< endl;
return classification == XPathEnvSupport::eError ? true : false;
}
void
XPathEnvSupportDefault::NamespaceFunctionTableDeleteFunctor::operator()(const NamespaceFunctionTablesInnerType::value_type& thePair) const
{
#if defined(XALAN_CANNOT_DELETE_CONST)
FunctionTableInnerType::const_iterator i = thePair.second.begin();
while(i != thePair.second.end())
{
delete (Function*) (*i).second;
++i;
}
#else
XALAN_USING_STD(for_each)
// Clean up the extension namespaces vector
for_each(thePair.second.begin(),
thePair.second.end(),
MapValueDeleteFunctor<FunctionTableInnerType>());
#endif
}
XALAN_CPP_NAMESPACE_END
<|endoftext|> |
<commit_before>// @(#)root/cont:$Name: $:$Id: TExMap.cxx,v 1.1.1.1 2000/05/16 17:00:40 rdm Exp $
// Author: Fons Rademakers 26/05/99
/*************************************************************************
* 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. *
*************************************************************************/
//////////////////////////////////////////////////////////////////////////
// //
// TExMap //
// //
// This class stores a (key,value) pair using an external hash. //
// The (key,value) are Long_t's and therefore can contain object //
// pointers or any longs. The map uses an open addressing hashing //
// method (linear probing). //
// //
//////////////////////////////////////////////////////////////////////////
#include "TExMap.h"
#include "TMath.h"
ClassImp(TExMap)
//______________________________________________________________________________
TExMap::TExMap(Int_t mapSize)
{
// Create a TExMap.
fSize = (Int_t)TMath::NextPrime(mapSize);
fTable = new Assoc_t* [fSize];
memset(fTable, 0, fSize*sizeof(Assoc_t*));
fTally = 0;
}
//______________________________________________________________________________
TExMap::TExMap(const TExMap &map)
{
// Copy constructor.
fSize = map.fSize;
fTally = map.fTally;
fTable = new Assoc_t* [fSize];
memset(fTable, 0, fSize*sizeof(Assoc_t*));
for (Int_t i = 0; i < fSize; i++)
if (map.fTable[i])
fTable[i] = new Assoc_t(map.fTable[i]->fHash, map.fTable[i]->fKey,
map.fTable[i]->fValue);
}
//______________________________________________________________________________
TExMap::~TExMap()
{
// Delete TExMap.
for (Int_t i = 0; i < fSize; i++)
delete fTable[i];
delete [] fTable; fTable = 0;
}
//______________________________________________________________________________
void TExMap::Add(ULong_t hash, Long_t key, Long_t value)
{
// Add an (key,value) pair to the table. The key should be unique.
if (!fTable)
return;
Int_t slot = FindElement(hash, key);
if (fTable[slot] == 0) {
fTable[slot] = new Assoc_t(hash, key, value);
fTally++;
if (HighWaterMark())
Expand(2 * fSize);
} else
Error("Add", "key %ld is not unique", key);
}
//______________________________________________________________________________
Long_t &TExMap::operator()(ULong_t hash, Long_t key)
{
// Return a reference to the value belonging to the key with the
// specified hash value. If the key does not exist it will be added.
static Long_t err;
if (!fTable) {
Error("operator()", "fTable==0, should never happen");
return err;
}
Int_t slot = FindElement(hash, key);
if (fTable[slot] == 0) {
fTable[slot] = new Assoc_t(hash, key, 0);
fTally++;
if (HighWaterMark()) {
Expand(2 * fSize);
slot = FindElement(hash, key);
}
}
return fTable[slot]->fValue;
}
//______________________________________________________________________________
void TExMap::Delete(Option_t *)
{
// Delete all entries stored in the TExMap.
for (int i = 0; i < fSize; i++) {
if (fTable[i]) {
delete fTable[i];
fTable[i] = 0;
}
}
fTally = 0;
}
//______________________________________________________________________________
Long_t TExMap::GetValue(ULong_t hash, Long_t key)
{
// Return the value belonging to specified key and hash value. If key not
// found return 0.
if (!fTable) return 0;
Int_t slot = Int_t(hash % fSize);
for (int n = 0; n < fSize; n++) {
if (!fTable[slot]) return 0;
if (key == fTable[slot]->fKey) return fTable[slot]->fValue;
if (++slot == fSize) slot = 0;
}
if (fTable[slot])
return fTable[slot]->fValue;
return 0;
}
//______________________________________________________________________________
void TExMap::Remove(ULong_t hash, Long_t key)
{
// Remove entry with specified key from the TExMap.
if (!fTable)
return;
Int_t i = FindElement(hash, key);
if (fTable[i] == 0) {
Warning("Remove", "key %ld not found at %d", key, i);
for (int j = 0; j < fSize; j++) {
if (fTable[j] && fTable[j]->fKey == key) {
Error("Remove", "%ld found at %d !!!", key, j);
i = j;
}
}
}
if (fTable[i]) {
delete fTable[i];
fTable[i] = 0;
FixCollisions(i);
fTally--;
}
}
//______________________________________________________________________________
Int_t TExMap::FindElement(ULong_t hash, Long_t key)
{
// Find an entry with specified hash and key in the TExMap.
// Returns the slot of the key or the next empty slot.
if (!fTable) return 0;
Int_t slot = Int_t(hash % fSize);
for (int n = 0; n < fSize; n++) {
if (!fTable[slot]) return slot;
if (key == fTable[slot]->fKey) return slot;
if (++slot == fSize) slot = 0;
}
return slot;
}
//______________________________________________________________________________
void TExMap::FixCollisions(Int_t index)
{
// Rehash the map in case an entry has been removed.
Int_t oldIndex, nextIndex;
Assoc_t *nextObject;
for (oldIndex = index+1; ;oldIndex++) {
if (oldIndex >= fSize)
oldIndex = 0;
nextObject = fTable[oldIndex];
if (nextObject == 0)
break;
nextIndex = FindElement(nextObject->fHash, nextObject->fKey);
if (nextIndex != oldIndex) {
fTable[nextIndex] = nextObject;
fTable[oldIndex] = 0;
}
}
}
//______________________________________________________________________________
void TExMap::Expand(Int_t newSize)
{
// Expand the TExMap.
Assoc_t **oldTable = fTable, *op;
Int_t oldsize = fSize;
newSize = (Int_t)TMath::NextPrime(newSize);
fTable = new Assoc_t* [newSize];
memset(fTable, 0, newSize*sizeof(Assoc_t*));
fSize = newSize;
for (int i = 0; i < oldsize; i++)
if ((op = oldTable[i])) {
Int_t slot = FindElement(op->fHash, op->fKey);
if (fTable[slot] == 0)
fTable[slot] = op;
else
Error("Expand", "slot %d not empty (should never happen)", slot);
}
delete [] oldTable;
}
ClassImp(TExMapIter)
//______________________________________________________________________________
TExMapIter::TExMapIter(const TExMap *map) : fMap(map), fCursor(0)
{
// Create TExMap iterator.
}
//______________________________________________________________________________
Bool_t TExMapIter::Next(ULong_t &hash, Long_t &key, Long_t &value)
{
// Get next entry from TExMap. Returns kFALSE at end of map.
while (fCursor < fMap->fSize && !fMap->fTable[fCursor])
fCursor++;
if (fCursor == fMap->fSize)
return kFALSE;
hash = fMap->fTable[fCursor]->fHash;
key = fMap->fTable[fCursor]->fKey;
value = fMap->fTable[fCursor]->fValue;
return kTRUE;
}
//______________________________________________________________________________
Bool_t TExMapIter::Next(Long_t &key, Long_t &value)
{
// Get next entry from TExMap. Returns kFALSE at end of map.
ULong_t hash;
return Next(hash, key, value);
}
<commit_msg>small fix in TExMapIter::Next().<commit_after>// @(#)root/cont:$Name: $:$Id: TExMap.cxx,v 1.2 2001/05/21 11:18:02 rdm Exp $
// Author: Fons Rademakers 26/05/99
/*************************************************************************
* 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. *
*************************************************************************/
//////////////////////////////////////////////////////////////////////////
// //
// TExMap //
// //
// This class stores a (key,value) pair using an external hash. //
// The (key,value) are Long_t's and therefore can contain object //
// pointers or any longs. The map uses an open addressing hashing //
// method (linear probing). //
// //
//////////////////////////////////////////////////////////////////////////
#include "TExMap.h"
#include "TMath.h"
ClassImp(TExMap)
//______________________________________________________________________________
TExMap::TExMap(Int_t mapSize)
{
// Create a TExMap.
fSize = (Int_t)TMath::NextPrime(mapSize);
fTable = new Assoc_t* [fSize];
memset(fTable, 0, fSize*sizeof(Assoc_t*));
fTally = 0;
}
//______________________________________________________________________________
TExMap::TExMap(const TExMap &map)
{
// Copy constructor.
fSize = map.fSize;
fTally = map.fTally;
fTable = new Assoc_t* [fSize];
memset(fTable, 0, fSize*sizeof(Assoc_t*));
for (Int_t i = 0; i < fSize; i++)
if (map.fTable[i])
fTable[i] = new Assoc_t(map.fTable[i]->fHash, map.fTable[i]->fKey,
map.fTable[i]->fValue);
}
//______________________________________________________________________________
TExMap::~TExMap()
{
// Delete TExMap.
for (Int_t i = 0; i < fSize; i++)
delete fTable[i];
delete [] fTable; fTable = 0;
}
//______________________________________________________________________________
void TExMap::Add(ULong_t hash, Long_t key, Long_t value)
{
// Add an (key,value) pair to the table. The key should be unique.
if (!fTable)
return;
Int_t slot = FindElement(hash, key);
if (fTable[slot] == 0) {
fTable[slot] = new Assoc_t(hash, key, value);
fTally++;
if (HighWaterMark())
Expand(2 * fSize);
} else
Error("Add", "key %ld is not unique", key);
}
//______________________________________________________________________________
Long_t &TExMap::operator()(ULong_t hash, Long_t key)
{
// Return a reference to the value belonging to the key with the
// specified hash value. If the key does not exist it will be added.
static Long_t err;
if (!fTable) {
Error("operator()", "fTable==0, should never happen");
return err;
}
Int_t slot = FindElement(hash, key);
if (fTable[slot] == 0) {
fTable[slot] = new Assoc_t(hash, key, 0);
fTally++;
if (HighWaterMark()) {
Expand(2 * fSize);
slot = FindElement(hash, key);
}
}
return fTable[slot]->fValue;
}
//______________________________________________________________________________
void TExMap::Delete(Option_t *)
{
// Delete all entries stored in the TExMap.
for (int i = 0; i < fSize; i++) {
if (fTable[i]) {
delete fTable[i];
fTable[i] = 0;
}
}
fTally = 0;
}
//______________________________________________________________________________
Long_t TExMap::GetValue(ULong_t hash, Long_t key)
{
// Return the value belonging to specified key and hash value. If key not
// found return 0.
if (!fTable) return 0;
Int_t slot = Int_t(hash % fSize);
for (int n = 0; n < fSize; n++) {
if (!fTable[slot]) return 0;
if (key == fTable[slot]->fKey) return fTable[slot]->fValue;
if (++slot == fSize) slot = 0;
}
if (fTable[slot])
return fTable[slot]->fValue;
return 0;
}
//______________________________________________________________________________
void TExMap::Remove(ULong_t hash, Long_t key)
{
// Remove entry with specified key from the TExMap.
if (!fTable)
return;
Int_t i = FindElement(hash, key);
if (fTable[i] == 0) {
Warning("Remove", "key %ld not found at %d", key, i);
for (int j = 0; j < fSize; j++) {
if (fTable[j] && fTable[j]->fKey == key) {
Error("Remove", "%ld found at %d !!!", key, j);
i = j;
}
}
}
if (fTable[i]) {
delete fTable[i];
fTable[i] = 0;
FixCollisions(i);
fTally--;
}
}
//______________________________________________________________________________
Int_t TExMap::FindElement(ULong_t hash, Long_t key)
{
// Find an entry with specified hash and key in the TExMap.
// Returns the slot of the key or the next empty slot.
if (!fTable) return 0;
Int_t slot = Int_t(hash % fSize);
for (int n = 0; n < fSize; n++) {
if (!fTable[slot]) return slot;
if (key == fTable[slot]->fKey) return slot;
if (++slot == fSize) slot = 0;
}
return slot;
}
//______________________________________________________________________________
void TExMap::FixCollisions(Int_t index)
{
// Rehash the map in case an entry has been removed.
Int_t oldIndex, nextIndex;
Assoc_t *nextObject;
for (oldIndex = index+1; ;oldIndex++) {
if (oldIndex >= fSize)
oldIndex = 0;
nextObject = fTable[oldIndex];
if (nextObject == 0)
break;
nextIndex = FindElement(nextObject->fHash, nextObject->fKey);
if (nextIndex != oldIndex) {
fTable[nextIndex] = nextObject;
fTable[oldIndex] = 0;
}
}
}
//______________________________________________________________________________
void TExMap::Expand(Int_t newSize)
{
// Expand the TExMap.
Assoc_t **oldTable = fTable, *op;
Int_t oldsize = fSize;
newSize = (Int_t)TMath::NextPrime(newSize);
fTable = new Assoc_t* [newSize];
memset(fTable, 0, newSize*sizeof(Assoc_t*));
fSize = newSize;
for (int i = 0; i < oldsize; i++)
if ((op = oldTable[i])) {
Int_t slot = FindElement(op->fHash, op->fKey);
if (fTable[slot] == 0)
fTable[slot] = op;
else
Error("Expand", "slot %d not empty (should never happen)", slot);
}
delete [] oldTable;
}
ClassImp(TExMapIter)
//______________________________________________________________________________
TExMapIter::TExMapIter(const TExMap *map) : fMap(map), fCursor(0)
{
// Create TExMap iterator.
}
//______________________________________________________________________________
Bool_t TExMapIter::Next(ULong_t &hash, Long_t &key, Long_t &value)
{
// Get next entry from TExMap. Returns kFALSE at end of map.
while (fCursor < fMap->fSize && !fMap->fTable[fCursor])
fCursor++;
if (fCursor == fMap->fSize)
return kFALSE;
hash = fMap->fTable[fCursor]->fHash;
key = fMap->fTable[fCursor]->fKey;
value = fMap->fTable[fCursor]->fValue;
fCursor++;
return kTRUE;
}
//______________________________________________________________________________
Bool_t TExMapIter::Next(Long_t &key, Long_t &value)
{
// Get next entry from TExMap. Returns kFALSE at end of map.
ULong_t hash;
return Next(hash, key, value);
}
<|endoftext|> |
<commit_before>/*
* VapourSynth D2V Plugin
*
* Copyright (c) 2012 Derek Buitenhuis
*
* This file is part of d2vsource.
*
* d2vsource 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.
*
* d2vsource 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 d2vsource; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
extern "C" {
#include <stdint.h>
#include <stdlib.h>
}
#include <VapourSynth.h>
#include <VSHelper.h>
#include "d2v.hpp"
#include "d2vsource.hpp"
#include "decode.hpp"
#include "directrender.hpp"
void VS_CC d2vInit(VSMap *in, VSMap *out, void **instanceData, VSNode *node, VSCore *core, const VSAPI *vsapi)
{
d2vData *d = (d2vData *) *instanceData;
vsapi->setVideoInfo(&d->vi, 1, node);
}
const VSFrameRef *VS_CC d2vGetFrame(int n, int activationReason, void **instanceData, void **frameData,
VSFrameContext *frameCtx, VSCore *core, const VSAPI *vsapi)
{
d2vData *d = (d2vData *) *instanceData;
const VSFrameRef *s;
VSFrameRef *f;
VSMap *props;
string msg;
int ret;
int plane;
/* Unreference the previously decoded frame. */
av_frame_unref(d->frame);
ret = decodeframe(n, d->d2v, d->dec, d->frame, msg);
if (ret < 0) {
vsapi->setFilterError(msg.c_str(), frameCtx);
return NULL;
}
/* Grab our direct-rendered frame. */
s = (const VSFrameRef *) d->frame->opaque;
if (!s) {
vsapi->setFilterError("Seek pattern broke d2vsource! Please send a sample.", frameCtx);
return NULL;
}
/* If our width and height are the same, just return it. */
if (d->vi.width == d->aligned_width && d->vi.height == d->aligned_height) {
f = vsapi->copyFrame(s, core);
} else {
f = vsapi->newVideoFrame(d->vi.format, d->vi.width, d->vi.height, NULL, core);
/* Copy into VS's buffers. */
for (plane = 0; plane < d->vi.format->numPlanes; plane++) {
uint8_t *dstp = vsapi->getWritePtr(f, plane);
const uint8_t *srcp = vsapi->getReadPtr(s, plane);
int dst_stride = vsapi->getStride(f, plane);
int src_stride = vsapi->getStride(s, plane);
int width = vsapi->getFrameWidth(f, plane);
int height = vsapi->getFrameHeight(f, plane);
vs_bitblt(dstp, dst_stride, srcp, src_stride, width * d->vi.format->bytesPerSample, height);
}
}
props = vsapi->getFramePropsRW(f);
/*
* The DGIndex manual simply says:
* "The matrix field displays the currently applicable matrix_coefficients value (colorimetry)."
*
* I can only assume this lines up with the tables VS uses correctly.
*/
vsapi->propSetInt(props, "_Matrix", d->d2v->gops[d->d2v->frames[n].gop].matrix, paReplace);
vsapi->propSetInt(props, "_DurationNum", d->d2v->fps_den, paReplace);
vsapi->propSetInt(props, "_DurationDen", d->d2v->fps_num, paReplace);
vsapi->propSetFloat(props, "_AbsoluteTime",
(static_cast<double>(d->d2v->fps_den) * n) / static_cast<double>(d->d2v->fps_num), paReplace);
/*
* YUVRGB_Scale describes the output range.
* _ColorRange describes the input range.
*/
if (d->d2v->yuvrgb_scale == PC)
vsapi->propSetInt(props, "_ColorRange", 1, paReplace);
else if (d->d2v->yuvrgb_scale == TV)
vsapi->propSetInt(props, "_ColorRange", 0, paReplace);
switch (d->frame->pict_type) {
case AV_PICTURE_TYPE_I:
vsapi->propSetData(props, "_PictType", "I", 1, paReplace);
break;
case AV_PICTURE_TYPE_P:
vsapi->propSetData(props, "_PictType", "P", 1, paReplace);
break;
case AV_PICTURE_TYPE_B:
vsapi->propSetData(props, "_PictType", "B", 1, paReplace);
break;
default:
break;
}
int fieldbased;
if (d->d2v->gops[d->d2v->frames[n].gop].flags[d->d2v->frames[n].offset] & FRAME_FLAG_PROGRESSIVE)
fieldbased = 0;
else
fieldbased = 1 + !!(d->d2v->gops[d->d2v->frames[n].gop].flags[d->d2v->frames[n].offset] & FRAME_FLAG_TFF);
vsapi->propSetInt(props, "_FieldBased", fieldbased, paReplace);
vsapi->propSetInt(props, "_ChromaLocation", d->d2v->mpeg_type == 1 ? 1 : 0, paReplace);
return f;
}
void VS_CC d2vFree(void *instanceData, VSCore *core, const VSAPI *vsapi)
{
d2vData *d = (d2vData *) instanceData;
d2vfreep(&d->d2v);
decodefreep(&d->dec);
av_frame_unref(d->frame);
av_freep(&d->frame);
free(d);
}
void VS_CC d2vCreate(const VSMap *in, VSMap *out, void *userData, VSCore *core, const VSAPI *vsapi)
{
d2vData *data;
string msg;
bool no_crop;
bool rff;
int threads;
int err;
/* Need to get thread info before anything to pass to decodeinit(). */
threads = vsapi->propGetInt(in, "threads", 0, &err);
if (err)
threads = 0;
if (threads < 0) {
vsapi->setError(out, "Invalid number of threads.");
return;
}
/* Allocate our private data. */
data = (d2vData *) malloc(sizeof(*data));
if (!data) {
vsapi->setError(out, "Cannot allocate private data.");
return;
}
data->d2v = d2vparse((char *) vsapi->propGetData(in, "input", 0, 0), msg);
if (!data->d2v) {
vsapi->setError(out, msg.c_str());
free(data);
return;
}
data->dec = decodeinit(data->d2v, threads, msg);
if (!data->dec) {
vsapi->setError(out, msg.c_str());
d2vfreep(&data->d2v);
free(data);
return;
}
/*
* Make our private data available to libavcodec, and
* set our custom get/release_buffer funcs.
*/
data->dec->avctx->opaque = (void *) data;
data->dec->avctx->get_buffer2 = VSGetBuffer;
data->vi.numFrames = data->d2v->frames.size();
data->vi.width = data->d2v->width;
data->vi.height = data->d2v->height;
data->vi.fpsNum = data->d2v->fps_num;
data->vi.fpsDen = data->d2v->fps_den;
/* Stash the pointer to our core. */
data->core = core;
data->api = (VSAPI *) vsapi;
/*
* Stash our aligned width and height for use with our
* custom get_buffer, since it could require this.
*/
data->aligned_width = FFALIGN(data->vi.width, 16);
data->aligned_height = FFALIGN(data->vi.height, 32);
data->frame = av_frame_alloc();
if (!data->frame) {
vsapi->setError(out, "Cannot allocate AVFrame.");
d2vfreep(&data->d2v);
decodefreep(&data->dec);
free(data);
return;
}
/*
* Decode 1 frame to find out how the chroma is subampled.
* The first time our custom get_buffer is called, it will
* fill in data->vi.format.
*/
data->format_set = false;
err = decodeframe(0, data->d2v, data->dec, data->frame, msg);
if (err < 0) {
msg.insert(0, "Failed to decode test frame: ");
vsapi->setError(out, msg.c_str());
d2vfreep(&data->d2v);
decodefreep(&data->dec);
av_frame_unref(data->frame);
av_freep(&data->frame);
free(data);
return;
}
/* See if nocrop is enabled, and set the width/height accordingly. */
no_crop = !!vsapi->propGetInt(in, "nocrop", 0, &err);
if (err)
no_crop = false;
if (no_crop) {
data->vi.width = data->aligned_width;
data->vi.height = data->aligned_height;
}
vsapi->createFilter(in, out, "d2vsource", d2vInit, d2vGetFrame, d2vFree, fmUnordered, nfMakeLinear, data, core);
rff = !!vsapi->propGetInt(in, "rff", 0, &err);
if (err)
rff = true;
if (rff) {
VSPlugin *d2vPlugin = vsapi->getPluginById("com.sources.d2vsource", core);
VSPlugin *corePlugin = vsapi->getPluginById("com.vapoursynth.std", core);
VSNodeRef *before = vsapi->propGetNode(out, "clip", 0, NULL);
VSNodeRef *middle;
VSNodeRef *after;
VSMap *args = vsapi->createMap();
VSMap *ret;
const char *error;
vsapi->propSetNode(args, "clip", before, paReplace);
vsapi->freeNode(before);
ret = vsapi->invoke(corePlugin, "Cache", args);
middle = vsapi->propGetNode(ret, "clip", 0, NULL);
vsapi->freeMap(ret);
vsapi->propSetNode(args, "clip", middle, paReplace);
vsapi->propSetData(args, "d2v", vsapi->propGetData(in, "input", 0, NULL),
vsapi->propGetDataSize(in, "input", 0, NULL), paReplace);
vsapi->freeNode(middle);
ret = vsapi->invoke(d2vPlugin, "ApplyRFF", args);
vsapi->freeMap(args);
error = vsapi->getError(ret);
if (error) {
vsapi->setError(out, error);
vsapi->freeMap(ret);
return;
}
after = vsapi->propGetNode(ret, "clip", 0, NULL);
vsapi->propSetNode(out, "clip", after, paReplace);
vsapi->freeNode(after);
vsapi->freeMap(ret);
}
}
<commit_msg>d2vsource: Return an error for unsupported pixel formats<commit_after>/*
* VapourSynth D2V Plugin
*
* Copyright (c) 2012 Derek Buitenhuis
*
* This file is part of d2vsource.
*
* d2vsource 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.
*
* d2vsource 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 d2vsource; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
extern "C" {
#include <stdint.h>
#include <stdlib.h>
}
#include <VapourSynth.h>
#include <VSHelper.h>
#include "d2v.hpp"
#include "d2vsource.hpp"
#include "decode.hpp"
#include "directrender.hpp"
void VS_CC d2vInit(VSMap *in, VSMap *out, void **instanceData, VSNode *node, VSCore *core, const VSAPI *vsapi)
{
d2vData *d = (d2vData *) *instanceData;
vsapi->setVideoInfo(&d->vi, 1, node);
}
const VSFrameRef *VS_CC d2vGetFrame(int n, int activationReason, void **instanceData, void **frameData,
VSFrameContext *frameCtx, VSCore *core, const VSAPI *vsapi)
{
d2vData *d = (d2vData *) *instanceData;
const VSFrameRef *s;
VSFrameRef *f;
VSMap *props;
string msg;
int ret;
int plane;
/* Unreference the previously decoded frame. */
av_frame_unref(d->frame);
ret = decodeframe(n, d->d2v, d->dec, d->frame, msg);
if (ret < 0) {
vsapi->setFilterError(msg.c_str(), frameCtx);
return NULL;
}
/* Grab our direct-rendered frame. */
s = (const VSFrameRef *) d->frame->opaque;
if (!s) {
vsapi->setFilterError("Seek pattern broke d2vsource! Please send a sample.", frameCtx);
return NULL;
}
/* If our width and height are the same, just return it. */
if (d->vi.width == d->aligned_width && d->vi.height == d->aligned_height) {
f = vsapi->copyFrame(s, core);
} else {
f = vsapi->newVideoFrame(d->vi.format, d->vi.width, d->vi.height, NULL, core);
/* Copy into VS's buffers. */
for (plane = 0; plane < d->vi.format->numPlanes; plane++) {
uint8_t *dstp = vsapi->getWritePtr(f, plane);
const uint8_t *srcp = vsapi->getReadPtr(s, plane);
int dst_stride = vsapi->getStride(f, plane);
int src_stride = vsapi->getStride(s, plane);
int width = vsapi->getFrameWidth(f, plane);
int height = vsapi->getFrameHeight(f, plane);
vs_bitblt(dstp, dst_stride, srcp, src_stride, width * d->vi.format->bytesPerSample, height);
}
}
props = vsapi->getFramePropsRW(f);
/*
* The DGIndex manual simply says:
* "The matrix field displays the currently applicable matrix_coefficients value (colorimetry)."
*
* I can only assume this lines up with the tables VS uses correctly.
*/
vsapi->propSetInt(props, "_Matrix", d->d2v->gops[d->d2v->frames[n].gop].matrix, paReplace);
vsapi->propSetInt(props, "_DurationNum", d->d2v->fps_den, paReplace);
vsapi->propSetInt(props, "_DurationDen", d->d2v->fps_num, paReplace);
vsapi->propSetFloat(props, "_AbsoluteTime",
(static_cast<double>(d->d2v->fps_den) * n) / static_cast<double>(d->d2v->fps_num), paReplace);
/*
* YUVRGB_Scale describes the output range.
* _ColorRange describes the input range.
*/
if (d->d2v->yuvrgb_scale == PC)
vsapi->propSetInt(props, "_ColorRange", 1, paReplace);
else if (d->d2v->yuvrgb_scale == TV)
vsapi->propSetInt(props, "_ColorRange", 0, paReplace);
switch (d->frame->pict_type) {
case AV_PICTURE_TYPE_I:
vsapi->propSetData(props, "_PictType", "I", 1, paReplace);
break;
case AV_PICTURE_TYPE_P:
vsapi->propSetData(props, "_PictType", "P", 1, paReplace);
break;
case AV_PICTURE_TYPE_B:
vsapi->propSetData(props, "_PictType", "B", 1, paReplace);
break;
default:
break;
}
int fieldbased;
if (d->d2v->gops[d->d2v->frames[n].gop].flags[d->d2v->frames[n].offset] & FRAME_FLAG_PROGRESSIVE)
fieldbased = 0;
else
fieldbased = 1 + !!(d->d2v->gops[d->d2v->frames[n].gop].flags[d->d2v->frames[n].offset] & FRAME_FLAG_TFF);
vsapi->propSetInt(props, "_FieldBased", fieldbased, paReplace);
vsapi->propSetInt(props, "_ChromaLocation", d->d2v->mpeg_type == 1 ? 1 : 0, paReplace);
return f;
}
void VS_CC d2vFree(void *instanceData, VSCore *core, const VSAPI *vsapi)
{
d2vData *d = (d2vData *) instanceData;
d2vfreep(&d->d2v);
decodefreep(&d->dec);
av_frame_unref(d->frame);
av_freep(&d->frame);
free(d);
}
void VS_CC d2vCreate(const VSMap *in, VSMap *out, void *userData, VSCore *core, const VSAPI *vsapi)
{
d2vData *data;
string msg;
bool no_crop;
bool rff;
int threads;
int err;
/* Need to get thread info before anything to pass to decodeinit(). */
threads = vsapi->propGetInt(in, "threads", 0, &err);
if (err)
threads = 0;
if (threads < 0) {
vsapi->setError(out, "Invalid number of threads.");
return;
}
/* Allocate our private data. */
data = (d2vData *) malloc(sizeof(*data));
if (!data) {
vsapi->setError(out, "Cannot allocate private data.");
return;
}
data->d2v = d2vparse((char *) vsapi->propGetData(in, "input", 0, 0), msg);
if (!data->d2v) {
vsapi->setError(out, msg.c_str());
free(data);
return;
}
data->dec = decodeinit(data->d2v, threads, msg);
if (!data->dec) {
vsapi->setError(out, msg.c_str());
d2vfreep(&data->d2v);
free(data);
return;
}
/*
* Make our private data available to libavcodec, and
* set our custom get/release_buffer funcs.
*/
data->dec->avctx->opaque = (void *) data;
data->dec->avctx->get_buffer2 = VSGetBuffer;
data->vi.numFrames = data->d2v->frames.size();
data->vi.width = data->d2v->width;
data->vi.height = data->d2v->height;
data->vi.fpsNum = data->d2v->fps_num;
data->vi.fpsDen = data->d2v->fps_den;
/* Stash the pointer to our core. */
data->core = core;
data->api = (VSAPI *) vsapi;
/*
* Stash our aligned width and height for use with our
* custom get_buffer, since it could require this.
*/
data->aligned_width = FFALIGN(data->vi.width, 16);
data->aligned_height = FFALIGN(data->vi.height, 32);
data->frame = av_frame_alloc();
if (!data->frame) {
vsapi->setError(out, "Cannot allocate AVFrame.");
d2vfreep(&data->d2v);
decodefreep(&data->dec);
free(data);
return;
}
/*
* Decode 1 frame to find out how the chroma is subampled.
* The first time our custom get_buffer is called, it will
* fill in data->vi.format.
*/
data->format_set = false;
err = decodeframe(0, data->d2v, data->dec, data->frame, msg);
if (err < 0) {
msg.insert(0, "Failed to decode test frame: ");
vsapi->setError(out, msg.c_str());
d2vfreep(&data->d2v);
decodefreep(&data->dec);
av_frame_unref(data->frame);
av_freep(&data->frame);
free(data);
return;
}
if (!data->format_set) {
vsapi->setError(out, "Source: video has unsupported pixel format.");
d2vfreep(&data->d2v);
decodefreep(&data->dec);
av_frame_unref(data->frame);
av_freep(&data->frame);
free(data);
return;
}
/* See if nocrop is enabled, and set the width/height accordingly. */
no_crop = !!vsapi->propGetInt(in, "nocrop", 0, &err);
if (err)
no_crop = false;
if (no_crop) {
data->vi.width = data->aligned_width;
data->vi.height = data->aligned_height;
}
vsapi->createFilter(in, out, "d2vsource", d2vInit, d2vGetFrame, d2vFree, fmUnordered, nfMakeLinear, data, core);
rff = !!vsapi->propGetInt(in, "rff", 0, &err);
if (err)
rff = true;
if (rff) {
VSPlugin *d2vPlugin = vsapi->getPluginById("com.sources.d2vsource", core);
VSPlugin *corePlugin = vsapi->getPluginById("com.vapoursynth.std", core);
VSNodeRef *before = vsapi->propGetNode(out, "clip", 0, NULL);
VSNodeRef *middle;
VSNodeRef *after;
VSMap *args = vsapi->createMap();
VSMap *ret;
const char *error;
vsapi->propSetNode(args, "clip", before, paReplace);
vsapi->freeNode(before);
ret = vsapi->invoke(corePlugin, "Cache", args);
middle = vsapi->propGetNode(ret, "clip", 0, NULL);
vsapi->freeMap(ret);
vsapi->propSetNode(args, "clip", middle, paReplace);
vsapi->propSetData(args, "d2v", vsapi->propGetData(in, "input", 0, NULL),
vsapi->propGetDataSize(in, "input", 0, NULL), paReplace);
vsapi->freeNode(middle);
ret = vsapi->invoke(d2vPlugin, "ApplyRFF", args);
vsapi->freeMap(args);
error = vsapi->getError(ret);
if (error) {
vsapi->setError(out, error);
vsapi->freeMap(ret);
return;
}
after = vsapi->propGetNode(ret, "clip", 0, NULL);
vsapi->propSetNode(out, "clip", after, paReplace);
vsapi->freeNode(after);
vsapi->freeMap(ret);
}
}
<|endoftext|> |
<commit_before>/*
BMPImage class
Copyright (C) 1998 by Olivier Langlois <olanglois@sympatic.ca>
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Library General Public
License as published by the Free Software Foundation; either
version 2 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Library General Public License for more details.
You should have received a copy of the GNU Library General Public
License along with this library; if not, write to the Free
Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
*/
#include <math.h>
#include "cssysdef.h"
#include "cstypes.h"
#include "csgeom/math3d.h"
#include "bmpimage.h"
#include "cssys/csendian.h"
#include "csgfx/rgbpixel.h"
#include "csutil/databuf.h"
IMPLEMENT_IBASE (csBMPImageIO)
IMPLEMENTS_INTERFACE (iImageIO)
IMPLEMENTS_INTERFACE (iPlugIn)
IMPLEMENT_IBASE_END
IMPLEMENT_FACTORY (csBMPImageIO);
EXPORT_CLASS_TABLE (csbmpimg)
EXPORT_CLASS (csBMPImageIO, "crystalspace.graphic.image.io.bmp", "CrystalSpace BMP image format I/O plugin")
EXPORT_CLASS_TABLE_END
#define BMP_MIME "image/bmp"
static iImageIO::FileFormatDescription formatlist[] =
{
{ BMP_MIME, "8 bit, palettized, RGB", CS_IMAGEIO_LOAD|CS_IMAGEIO_SAVE},
{ BMP_MIME, "8 bit, palettized, RLE8", CS_IMAGEIO_LOAD},
{ BMP_MIME, "24 bit, RGB", CS_IMAGEIO_LOAD|CS_IMAGEIO_SAVE}
};
//-----------------------------------------------------------------------------
// Some platforms require strict-alignment, which means that values of
// primitive types must be accessed at memory locations which are multiples
// of the size of those types. For instance, a 'long' can only be accessed
// at a memory location which is a multiple of four. Consequently, the
// following endian-conversion functions first copy the raw data into a
// variable of the proper data type using memcpy() prior to attempting to
// access it as the given type.
//-----------------------------------------------------------------------------
static inline UShort us_endian (const UByte* ptr)
{
UShort n;
memcpy(&n, ptr, sizeof(n));
return convert_endian(n);
}
static inline ULong ul_endian (const UByte* ptr)
{
ULong n;
memcpy(&n, ptr, sizeof(n));
return convert_endian(n);
}
static inline long l_endian (const UByte* ptr)
{
long n;
memcpy(&n, ptr, sizeof(n));
return convert_endian(n);
}
#define BFTYPE(x) us_endian((x) + 0)
#define BFSIZE(x) ul_endian((x) + 2)
#define BFOFFBITS(x) ul_endian((x) + 10)
#define BISIZE(x) ul_endian((x) + 14)
#define BIWIDTH(x) l_endian ((x) + 18)
#define BIHEIGHT(x) l_endian ((x) + 22)
#define BITCOUNT(x) us_endian((x) + 28)
#define BICOMP(x) ul_endian((x) + 30)
#define IMAGESIZE(x) ul_endian((x) + 34)
#define BICLRUSED(x) ul_endian((x) + 46)
#define BICLRIMP(x) ul_endian((x) + 50)
#define BIPALETTE(x) ((x) + 54)
// Type ID
#define BM "BM" // Windows 3.1x, 95, NT, ...
#define BA "BA" // OS/2 Bitmap Array
#define CI "CI" // OS/2 Color Icon
#define CP "CP" // OS/2 Color Pointer
#define IC "IC" // OS/2 Icon
#define PT "PT" // OS/2 Pointer
// Possible values for the header size
#define WinHSize 0x28
#define OS21xHSize 0x0C
#define OS22xHSize 0xF0
// Possible values for the BPP setting
#define Mono 1 // Monochrome bitmap
#define _16Color 4 // 16 color bitmap
#define _256Color 8 // 256 color bitmap
#define HIGHCOLOR 16 // 16bit (high color) bitmap
#define TRUECOLOR24 24 // 24bit (true color) bitmap
#define TRUECOLOR32 32 // 32bit (true color) bitmap
// Compression Types
#ifndef BI_RGB
#define BI_RGB 0 // none
#define BI_RLE8 1 // RLE 8-bit / pixel
#define BI_RLE4 2 // RLE 4-bit / pixel
#define BI_BITFIELDS 3 // Bitfields
#endif
struct bmpHeader
{
UShort pad;
UByte bfTypeLo;
UByte bfTypeHi;
ULong bfSize;
UShort bfRes1;
UShort bfRes2;
ULong bfOffBits;
ULong biSize;
ULong biWidth;
ULong biHeight;
UShort biPlanes;
UShort biBitCount;
ULong biCompression;
ULong biSizeImage;
ULong biXPelsPerMeter;
ULong biYPelsPerMeter;
ULong biClrUsed;
ULong biClrImportant;
};
//---------------------------------------------------------------------------
csBMPImageIO::csBMPImageIO (iBase *pParent)
{
CONSTRUCT_IBASE (pParent);
formats.Push (&formatlist[0]);
formats.Push (&formatlist[1]);
formats.Push (&formatlist[2]);
}
bool csBMPImageIO::Initialize (iSystem *)
{
return true;
}
const csVector& csBMPImageIO::GetDescription ()
{
return formats;
}
iImage *csBMPImageIO::Load (UByte* iBuffer, ULong iSize, int iFormat)
{
ImageBMPFile* i = new ImageBMPFile (iFormat);
if (i && !i->Load (iBuffer, iSize))
{
delete i;
return NULL;
}
return i;
}
void csBMPImageIO::SetDithering (bool)
{
}
iDataBuffer *csBMPImageIO::Save (iImage *Image, iImageIO::FileFormatDescription *)
{
if (!Image || !Image->GetImageData ())
return NULL;
// check if we have a format we support saving
int format = Image->GetFormat ();
bool palette = false;
switch (format & CS_IMGFMT_MASK)
{
case CS_IMGFMT_PALETTED8:
palette = true;
case CS_IMGFMT_TRUECOLOR:
break;
default:
// unknown format
return NULL;
} /* endswitch */
if (palette && !Image->GetPalette ())
return NULL;
// calc size
int w = Image->GetWidth ();
int h = Image->GetHeight ();
size_t len = sizeof (bmpHeader)-2 + w*h*(palette?1:3) + 256*(palette?4:0);
bmpHeader hdr;
hdr.bfTypeLo = 'B';
hdr.bfTypeHi = 'M';
hdr.bfSize = little_endian_long (len);
hdr.bfRes1 = 0;
hdr.bfRes2 = 0;
hdr.bfOffBits = little_endian_long (sizeof (bmpHeader)-2 + 256*(palette?4:0));
hdr.biSize = little_endian_long (40);
hdr.biWidth = little_endian_long (w);
hdr.biHeight = little_endian_long (h);
hdr.biPlanes = little_endian_short (1);
hdr.biBitCount = little_endian_short (palette?8:24);
hdr.biCompression = little_endian_long (0);
hdr.biSizeImage = little_endian_long (0);
hdr.biXPelsPerMeter = little_endian_long (0);
hdr.biYPelsPerMeter = little_endian_long (0);
hdr.biClrUsed = little_endian_long (0);
hdr.biClrImportant = little_endian_long (0);
csDataBuffer *db = new csDataBuffer (len);
unsigned char *p = (unsigned char *)db->GetData ();
memcpy (p, &hdr.bfTypeLo, sizeof (bmpHeader)-2);
p += sizeof (bmpHeader)-2;
if (palette)
{
csRGBpixel *pal = Image->GetPalette ();
for (int i= 0; i < 256; i++)
{
*p++ = pal[i].blue;
*p++ = pal[i].green;
*p++ = pal[i].red;
p++;
}
unsigned char *data = (unsigned char *)Image->GetImageData ();
for (int y=h-1; y >= 0; y--)
for (int x=0; x < w; x++)
*p++ = data[y*w+x];
}
else
{
csRGBpixel *pixel = (csRGBpixel *)Image->GetImageData ();
for (int y=h-1; y >= 0; y--)
for (int x=0; x < w; x++)
{
unsigned char *c = (unsigned char *)&pixel[y*w+x];
*p++ = *(c+2);
*p++ = *(c+1);
*p++ = *c;
}
}
return db;
}
iDataBuffer *csBMPImageIO::Save (iImage *Image, const char *mime)
{
if (!strcasecmp (mime, BMP_MIME))
return Save (Image, (iImageIO::FileFormatDescription *)NULL);
return NULL;
}
bool ImageBMPFile::Load (UByte* iBuffer, ULong iSize)
{
if ((memcmp (iBuffer, BM, 2) == 0) && BISIZE(iBuffer) == WinHSize)
return LoadWindowsBitmap (iBuffer, iSize);
return false;
}
bool ImageBMPFile::LoadWindowsBitmap (UByte* iBuffer, ULong iSize)
{
set_dimensions (BIWIDTH(iBuffer), BIHEIGHT(iBuffer));
const int bmp_size = Width * Height;
UByte *iPtr = iBuffer + BFOFFBITS(iBuffer);
// No alpha for BMP.
Format &= ~CS_IMGFMT_ALPHA;
// The last scanline in BMP corresponds to the top line in the image
int buffer_y = Width * (Height - 1);
bool blip = false;
if (BITCOUNT(iBuffer) == _256Color && BICLRUSED(iBuffer))
{
UByte *buffer = new UByte [bmp_size];
csRGBpixel *palette = new csRGBpixel [256];
csRGBpixel *pwork = palette;
UByte *inpal = BIPALETTE(iBuffer);
int scanlinewidth = 4 * ((Width+3) / 4);
for (int color = 0; color < 256; color++, pwork++)
{
// Whacky BMP palette is in BGR order.
pwork->blue = *inpal++;
pwork->green = *inpal++;
pwork->red = *inpal++;
pwork->alpha = 0;
inpal++; // Skip unused byte.
}
if (BICOMP(iBuffer) == BI_RGB)
{
// Read the pixels from "top" to "bottom"
while (iPtr < iBuffer + iSize && buffer_y >= 0)
{
memcpy (buffer + buffer_y, iPtr, Width);
iPtr += scanlinewidth;
buffer_y -= Width;
} /* endwhile */
}
else if (BICOMP(iBuffer) == BI_RLE8)
{
// Decompress pixel data
UByte rl, rl1, i; // runlength
UByte clridx, clridx1; // colorindex
int buffer_x = 0;
while (iPtr < iBuffer + iSize && buffer_y >= 0)
{
rl = rl1 = *iPtr++;
clridx = clridx1 = *iPtr++;
if (rl == 0)
if (clridx == 0)
{
// new scanline
if (!blip)
{
// if we didnt already jumped to the new line, do it now
buffer_x = 0;
buffer_y -= Width;
}
continue;
}
else if (clridx == 1)
// end of bitmap
break;
else if (clridx == 2)
{
// next 2 bytes mean column- and scanline- offset
buffer_x += *iPtr++;
buffer_y -= (Width * (*iPtr++));
continue;
}
else if (clridx > 2)
rl1 = clridx;
for ( i = 0; i < rl1; i++ )
{
if (!rl) clridx1 = *iPtr++;
buffer [buffer_y + buffer_x] = clridx1;
if (++buffer_x >= Width)
{
buffer_x = 0;
buffer_y -= Width;
blip = true;
}
else
blip = false;
}
// pad in case rl == 0 and clridx in [3..255]
if (rl == 0 && (clridx & 0x01)) iPtr++;
}
}
// Now transform the image data to target format
convert_pal8 (buffer, palette);
return true;
}
else if (!BICLRUSED(iBuffer) && BITCOUNT(iBuffer) == TRUECOLOR24)
{
csRGBpixel *buffer = new csRGBpixel [bmp_size];
while (iPtr < iBuffer + iSize && buffer_y >= 0)
{
csRGBpixel *d = buffer + buffer_y;
for (int x = Width; x; x--)
{
d->blue = *iPtr++;
d->green = *iPtr++;
d->red = *iPtr++;
d++;
} /* endfor */
buffer_y -= Width;
}
// Now transform the image data to target format
convert_rgba (buffer);
return true;
}
return false;
}
<commit_msg>fixed the bug that made indexed bmp images fully transparent<commit_after>/*
BMPImage class
Copyright (C) 1998 by Olivier Langlois <olanglois@sympatic.ca>
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Library General Public
License as published by the Free Software Foundation; either
version 2 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Library General Public License for more details.
You should have received a copy of the GNU Library General Public
License along with this library; if not, write to the Free
Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
*/
#include <math.h>
#include "cssysdef.h"
#include "cstypes.h"
#include "csgeom/math3d.h"
#include "bmpimage.h"
#include "cssys/csendian.h"
#include "csgfx/rgbpixel.h"
#include "csutil/databuf.h"
IMPLEMENT_IBASE (csBMPImageIO)
IMPLEMENTS_INTERFACE (iImageIO)
IMPLEMENTS_INTERFACE (iPlugIn)
IMPLEMENT_IBASE_END
IMPLEMENT_FACTORY (csBMPImageIO);
EXPORT_CLASS_TABLE (csbmpimg)
EXPORT_CLASS (csBMPImageIO, "crystalspace.graphic.image.io.bmp", "CrystalSpace BMP image format I/O plugin")
EXPORT_CLASS_TABLE_END
#define BMP_MIME "image/bmp"
static iImageIO::FileFormatDescription formatlist[] =
{
{ BMP_MIME, "8 bit, palettized, RGB", CS_IMAGEIO_LOAD|CS_IMAGEIO_SAVE},
{ BMP_MIME, "8 bit, palettized, RLE8", CS_IMAGEIO_LOAD},
{ BMP_MIME, "24 bit, RGB", CS_IMAGEIO_LOAD|CS_IMAGEIO_SAVE}
};
//-----------------------------------------------------------------------------
// Some platforms require strict-alignment, which means that values of
// primitive types must be accessed at memory locations which are multiples
// of the size of those types. For instance, a 'long' can only be accessed
// at a memory location which is a multiple of four. Consequently, the
// following endian-conversion functions first copy the raw data into a
// variable of the proper data type using memcpy() prior to attempting to
// access it as the given type.
//-----------------------------------------------------------------------------
static inline UShort us_endian (const UByte* ptr)
{
UShort n;
memcpy(&n, ptr, sizeof(n));
return convert_endian(n);
}
static inline ULong ul_endian (const UByte* ptr)
{
ULong n;
memcpy(&n, ptr, sizeof(n));
return convert_endian(n);
}
static inline long l_endian (const UByte* ptr)
{
long n;
memcpy(&n, ptr, sizeof(n));
return convert_endian(n);
}
#define BFTYPE(x) us_endian((x) + 0)
#define BFSIZE(x) ul_endian((x) + 2)
#define BFOFFBITS(x) ul_endian((x) + 10)
#define BISIZE(x) ul_endian((x) + 14)
#define BIWIDTH(x) l_endian ((x) + 18)
#define BIHEIGHT(x) l_endian ((x) + 22)
#define BITCOUNT(x) us_endian((x) + 28)
#define BICOMP(x) ul_endian((x) + 30)
#define IMAGESIZE(x) ul_endian((x) + 34)
#define BICLRUSED(x) ul_endian((x) + 46)
#define BICLRIMP(x) ul_endian((x) + 50)
#define BIPALETTE(x) ((x) + 54)
// Type ID
#define BM "BM" // Windows 3.1x, 95, NT, ...
#define BA "BA" // OS/2 Bitmap Array
#define CI "CI" // OS/2 Color Icon
#define CP "CP" // OS/2 Color Pointer
#define IC "IC" // OS/2 Icon
#define PT "PT" // OS/2 Pointer
// Possible values for the header size
#define WinHSize 0x28
#define OS21xHSize 0x0C
#define OS22xHSize 0xF0
// Possible values for the BPP setting
#define Mono 1 // Monochrome bitmap
#define _16Color 4 // 16 color bitmap
#define _256Color 8 // 256 color bitmap
#define HIGHCOLOR 16 // 16bit (high color) bitmap
#define TRUECOLOR24 24 // 24bit (true color) bitmap
#define TRUECOLOR32 32 // 32bit (true color) bitmap
// Compression Types
#ifndef BI_RGB
#define BI_RGB 0 // none
#define BI_RLE8 1 // RLE 8-bit / pixel
#define BI_RLE4 2 // RLE 4-bit / pixel
#define BI_BITFIELDS 3 // Bitfields
#endif
struct bmpHeader
{
UShort pad;
UByte bfTypeLo;
UByte bfTypeHi;
ULong bfSize;
UShort bfRes1;
UShort bfRes2;
ULong bfOffBits;
ULong biSize;
ULong biWidth;
ULong biHeight;
UShort biPlanes;
UShort biBitCount;
ULong biCompression;
ULong biSizeImage;
ULong biXPelsPerMeter;
ULong biYPelsPerMeter;
ULong biClrUsed;
ULong biClrImportant;
};
//---------------------------------------------------------------------------
csBMPImageIO::csBMPImageIO (iBase *pParent)
{
CONSTRUCT_IBASE (pParent);
formats.Push (&formatlist[0]);
formats.Push (&formatlist[1]);
formats.Push (&formatlist[2]);
}
bool csBMPImageIO::Initialize (iSystem *)
{
return true;
}
const csVector& csBMPImageIO::GetDescription ()
{
return formats;
}
iImage *csBMPImageIO::Load (UByte* iBuffer, ULong iSize, int iFormat)
{
ImageBMPFile* i = new ImageBMPFile (iFormat);
if (i && !i->Load (iBuffer, iSize))
{
delete i;
return NULL;
}
return i;
}
void csBMPImageIO::SetDithering (bool)
{
}
iDataBuffer *csBMPImageIO::Save (iImage *Image, iImageIO::FileFormatDescription *)
{
if (!Image || !Image->GetImageData ())
return NULL;
// check if we have a format we support saving
int format = Image->GetFormat ();
bool palette = false;
switch (format & CS_IMGFMT_MASK)
{
case CS_IMGFMT_PALETTED8:
palette = true;
case CS_IMGFMT_TRUECOLOR:
break;
default:
// unknown format
return NULL;
} /* endswitch */
if (palette && !Image->GetPalette ())
return NULL;
// calc size
int w = Image->GetWidth ();
int h = Image->GetHeight ();
size_t len = sizeof (bmpHeader)-2 + w*h*(palette?1:3) + 256*(palette?4:0);
bmpHeader hdr;
hdr.bfTypeLo = 'B';
hdr.bfTypeHi = 'M';
hdr.bfSize = little_endian_long (len);
hdr.bfRes1 = 0;
hdr.bfRes2 = 0;
hdr.bfOffBits = little_endian_long (sizeof (bmpHeader)-2 + 256*(palette?4:0));
hdr.biSize = little_endian_long (40);
hdr.biWidth = little_endian_long (w);
hdr.biHeight = little_endian_long (h);
hdr.biPlanes = little_endian_short (1);
hdr.biBitCount = little_endian_short (palette?8:24);
hdr.biCompression = little_endian_long (0);
hdr.biSizeImage = little_endian_long (0);
hdr.biXPelsPerMeter = little_endian_long (0);
hdr.biYPelsPerMeter = little_endian_long (0);
hdr.biClrUsed = little_endian_long (0);
hdr.biClrImportant = little_endian_long (0);
csDataBuffer *db = new csDataBuffer (len);
unsigned char *p = (unsigned char *)db->GetData ();
memcpy (p, &hdr.bfTypeLo, sizeof (bmpHeader)-2);
p += sizeof (bmpHeader)-2;
if (palette)
{
csRGBpixel *pal = Image->GetPalette ();
for (int i= 0; i < 256; i++)
{
*p++ = pal[i].blue;
*p++ = pal[i].green;
*p++ = pal[i].red;
p++;
}
unsigned char *data = (unsigned char *)Image->GetImageData ();
for (int y=h-1; y >= 0; y--)
for (int x=0; x < w; x++)
*p++ = data[y*w+x];
}
else
{
csRGBpixel *pixel = (csRGBpixel *)Image->GetImageData ();
for (int y=h-1; y >= 0; y--)
for (int x=0; x < w; x++)
{
unsigned char *c = (unsigned char *)&pixel[y*w+x];
*p++ = *(c+2);
*p++ = *(c+1);
*p++ = *c;
}
}
return db;
}
iDataBuffer *csBMPImageIO::Save (iImage *Image, const char *mime)
{
if (!strcasecmp (mime, BMP_MIME))
return Save (Image, (iImageIO::FileFormatDescription *)NULL);
return NULL;
}
bool ImageBMPFile::Load (UByte* iBuffer, ULong iSize)
{
if ((memcmp (iBuffer, BM, 2) == 0) && BISIZE(iBuffer) == WinHSize)
return LoadWindowsBitmap (iBuffer, iSize);
return false;
}
bool ImageBMPFile::LoadWindowsBitmap (UByte* iBuffer, ULong iSize)
{
set_dimensions (BIWIDTH(iBuffer), BIHEIGHT(iBuffer));
const int bmp_size = Width * Height;
UByte *iPtr = iBuffer + BFOFFBITS(iBuffer);
// No alpha for BMP.
Format &= ~CS_IMGFMT_ALPHA;
// The last scanline in BMP corresponds to the top line in the image
int buffer_y = Width * (Height - 1);
bool blip = false;
if (BITCOUNT(iBuffer) == _256Color && BICLRUSED(iBuffer))
{
UByte *buffer = new UByte [bmp_size];
csRGBpixel *palette = new csRGBpixel [256];
csRGBpixel *pwork = palette;
UByte *inpal = BIPALETTE(iBuffer);
int scanlinewidth = 4 * ((Width+3) / 4);
for (int color = 0; color < 256; color++, pwork++)
{
// Whacky BMP palette is in BGR order.
pwork->blue = *inpal++;
pwork->green = *inpal++;
pwork->red = *inpal++;
inpal++; // Skip unused byte.
}
if (BICOMP(iBuffer) == BI_RGB)
{
// Read the pixels from "top" to "bottom"
while (iPtr < iBuffer + iSize && buffer_y >= 0)
{
memcpy (buffer + buffer_y, iPtr, Width);
iPtr += scanlinewidth;
buffer_y -= Width;
} /* endwhile */
}
else if (BICOMP(iBuffer) == BI_RLE8)
{
// Decompress pixel data
UByte rl, rl1, i; // runlength
UByte clridx, clridx1; // colorindex
int buffer_x = 0;
while (iPtr < iBuffer + iSize && buffer_y >= 0)
{
rl = rl1 = *iPtr++;
clridx = clridx1 = *iPtr++;
if (rl == 0)
if (clridx == 0)
{
// new scanline
if (!blip)
{
// if we didnt already jumped to the new line, do it now
buffer_x = 0;
buffer_y -= Width;
}
continue;
}
else if (clridx == 1)
// end of bitmap
break;
else if (clridx == 2)
{
// next 2 bytes mean column- and scanline- offset
buffer_x += *iPtr++;
buffer_y -= (Width * (*iPtr++));
continue;
}
else if (clridx > 2)
rl1 = clridx;
for ( i = 0; i < rl1; i++ )
{
if (!rl) clridx1 = *iPtr++;
buffer [buffer_y + buffer_x] = clridx1;
if (++buffer_x >= Width)
{
buffer_x = 0;
buffer_y -= Width;
blip = true;
}
else
blip = false;
}
// pad in case rl == 0 and clridx in [3..255]
if (rl == 0 && (clridx & 0x01)) iPtr++;
}
}
// Now transform the image data to target format
convert_pal8 (buffer, palette);
return true;
}
else if (!BICLRUSED(iBuffer) && BITCOUNT(iBuffer) == TRUECOLOR24)
{
csRGBpixel *buffer = new csRGBpixel [bmp_size];
while (iPtr < iBuffer + iSize && buffer_y >= 0)
{
csRGBpixel *d = buffer + buffer_y;
for (int x = Width; x; x--)
{
d->blue = *iPtr++;
d->green = *iPtr++;
d->red = *iPtr++;
d++;
} /* endfor */
buffer_y -= Width;
}
// Now transform the image data to target format
convert_rgba (buffer);
return true;
}
return false;
}
<|endoftext|> |
<commit_before>/* -*- coding: utf-8; mode: c++; tab-width: 3; indent-tabs-mode: nil -*-
Copyright 2015
Raffaello D. Di Napoli
This file is part of Abaclade.
Abaclade 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.
Abaclade 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 Abaclade. If not, see
<http://www.gnu.org/licenses/>.
--------------------------------------------------------------------------------------------------*/
#include <abaclade.hxx>
#include <abaclade/collections/map.hxx>
#include <abaclade/thread.hxx>
#include <atomic>
#include <mutex>
////////////////////////////////////////////////////////////////////////////////////////////////////
// abc::thread::comm_manager
namespace abc {
class thread::comm_manager : public noncopyable {
public:
//! Constructor.
comm_manager();
//! Destructor.
~comm_manager();
#if ABC_HOST_API_POSIX
/*! Returns the signal number to be used to inject an exception in a thread.
@param return
Signal number.
*/
int exception_injection_signal_number() const {
return mc_iInterruptionSignal;
}
#endif
/*! Returns a pointer to the singleton instance.
@return
Pointer to the only instance of this class.
*/
static comm_manager * instance() {
return sm_pInst;
}
/*! Registers the termination of the program’s abc::app::main() overload.
@param inj
Type of exception that escaped the program’s main(), or exception::injectable::none if main()
returned normally.
*/
void main_thread_terminated(exception::injectable inj);
/*! Registers a new thread as running.
@param pimpl
Pointer to the abc::thread::impl instance running the thread.
*/
void nonmain_thread_started(std::shared_ptr<impl> const & pimpl);
/*! Registers a non-main thread as no longer running.
@param pimpl
Pointer to the abc::thread::impl instance running the thread.
@param bUncaughtException
true if an exception escaped the thread’s function and was only blocked by thread:impl.
*/
void nonmain_thread_terminated(impl * pimpl, bool bUncaughtException);
private:
#if ABC_HOST_API_POSIX
//! Signal number to be used to interrupt threads.
int const mc_iInterruptionSignal;
#endif
/*! Pointer to an incomplete abc::thread::impl instance that’s used to control the main (default)
thread of the process. */
// TODO: instantiate this lazily, only if needed.
std::shared_ptr<impl> m_pimplMainThread;
//! Governs access to m_mappimplThreads.
std::mutex m_mtxThreads;
//! Tracks all threads running in the process except *m_pimplMainThread.
// TODO: make this a set instead of a map.
collections::map<impl *, std::shared_ptr<impl>> m_mappimplThreads;
//! true if the main thread of the process is terminating, or false otherwise.
std::atomic<bool> m_bMainThreadTerminating;
//! Pointer to the singleton instance.
static thread::comm_manager * sm_pInst;
};
} //namespace abc
////////////////////////////////////////////////////////////////////////////////////////////////////
<commit_msg>Remove unnecessary member variable<commit_after>/* -*- coding: utf-8; mode: c++; tab-width: 3; indent-tabs-mode: nil -*-
Copyright 2015
Raffaello D. Di Napoli
This file is part of Abaclade.
Abaclade 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.
Abaclade 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 Abaclade. If not, see
<http://www.gnu.org/licenses/>.
--------------------------------------------------------------------------------------------------*/
#include <abaclade.hxx>
#include <abaclade/collections/map.hxx>
#include <abaclade/thread.hxx>
#include <atomic>
#include <mutex>
////////////////////////////////////////////////////////////////////////////////////////////////////
// abc::thread::comm_manager
namespace abc {
class thread::comm_manager : public noncopyable {
public:
//! Constructor.
comm_manager();
//! Destructor.
~comm_manager();
#if ABC_HOST_API_POSIX
/*! Returns the signal number to be used to inject an exception in a thread.
@param return
Signal number.
*/
int exception_injection_signal_number() const {
return mc_iInterruptionSignal;
}
#endif
/*! Returns a pointer to the singleton instance.
@return
Pointer to the only instance of this class.
*/
static comm_manager * instance() {
return sm_pInst;
}
/*! Registers the termination of the program’s abc::app::main() overload.
@param inj
Type of exception that escaped the program’s main(), or exception::injectable::none if main()
returned normally.
*/
void main_thread_terminated(exception::injectable inj);
/*! Registers a new thread as running.
@param pimpl
Pointer to the abc::thread::impl instance running the thread.
*/
void nonmain_thread_started(std::shared_ptr<impl> const & pimpl);
/*! Registers a non-main thread as no longer running.
@param pimpl
Pointer to the abc::thread::impl instance running the thread.
@param bUncaughtException
true if an exception escaped the thread’s function and was only blocked by thread:impl.
*/
void nonmain_thread_terminated(impl * pimpl, bool bUncaughtException);
private:
#if ABC_HOST_API_POSIX
//! Signal number to be used to interrupt threads.
int const mc_iInterruptionSignal;
#endif
/*! Pointer to an incomplete abc::thread::impl instance that’s used to control the main (default)
thread of the process. */
// TODO: instantiate this lazily, only if needed.
std::shared_ptr<impl> m_pimplMainThread;
//! Governs access to m_mappimplThreads.
std::mutex m_mtxThreads;
//! Tracks all threads running in the process except *m_pimplMainThread.
// TODO: make this a set instead of a map.
collections::map<impl *, std::shared_ptr<impl>> m_mappimplThreads;
//! Pointer to the singleton instance.
static thread::comm_manager * sm_pInst;
};
} //namespace abc
////////////////////////////////////////////////////////////////////////////////////////////////////
<|endoftext|> |
<commit_before>//------------------------------------------------------------------------------
// CLING - the C++ LLVM-based InterpreterG :)
//
// This file is dual-licensed: you can choose to license it under the University
// of Illinois Open Source License or the GNU Lesser General Public License. See
// LICENSE.TXT for details.
//------------------------------------------------------------------------------
// RUN: cat %s | %cling -Xclang -verify | FileCheck %s
//This file checks a call instruction. The called function has arguments with nonnull attribute.
#include <string.h>
char *p = 0;
strcmp("a", p); // expected-warning {{null passed to a callee that requires a non-null argument}}
strcmp(p, "a"); // expected-warning {{null passed to a callee that requires a non-null argument}}
extern "C" int printf(const char* fmt, ...);
.rawInput 1
extern "C" int cannotCallWithNull(int* p = 0);
extern "C" int cannotCallWithNull(int* p) __attribute__((nonnull(1)));
extern "C" int cannotCallWithNull(int* p);
extern "C" int cannotCallWithNull(int* p);
.rawInput 0
extern "C" int cannotCallWithNull(int* p) {
if (!p) // expected-warning {{nonnull parameter 'p' will evaluate to 'true' on first encounter}}
printf("Must not be called with p=0.\n");
return 1;
}
int *q = 0;
cannotCallWithNull(q); // expected-warning {{null passed to a callee that requires a non-null argument}}
//CHECK-NOT: Must not be called with p=0.
cannotCallWithNull(new int(4))
//CHECK: (int) 1
.q
<commit_msg>Remove platform-specific code (fails on Darwin), just use cannotCallWithNull.<commit_after>//------------------------------------------------------------------------------
// CLING - the C++ LLVM-based InterpreterG :)
//
// This file is dual-licensed: you can choose to license it under the University
// of Illinois Open Source License or the GNU Lesser General Public License. See
// LICENSE.TXT for details.
//------------------------------------------------------------------------------
// RUN: cat %s | %cling -Xclang -verify | FileCheck %s
//This file checks a call instruction. The called function has arguments with nonnull attribute.
extern "C" int printf(const char* fmt, ...);
.rawInput 1
extern "C" int cannotCallWithNull(int* p = 0);
extern "C" int cannotCallWithNull(int* p) __attribute__((nonnull(1)));
extern "C" int cannotCallWithNull(int* p);
extern "C" int cannotCallWithNull(int* p);
.rawInput 0
extern "C" int cannotCallWithNull(int* p) {
if (!p) // expected-warning {{nonnull parameter 'p' will evaluate to 'true' on first encounter}}
printf("Must not be called with p=0.\n");
return 1;
}
int *q = 0;
cannotCallWithNull(q); // expected-warning {{null passed to a callee that requires a non-null argument}}
//CHECK-NOT: Must not be called with p=0.
cannotCallWithNull(new int(4))
//CHECK: (int) 1
.q
<|endoftext|> |
<commit_before>/*
* Copyright (C) 2012
* Alessio Sclocco <a.sclocco@vu.nl>
*
* 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 <iostream>
#include <string>
#include <vector>
#include <exception>
#include <fstream>
#include <iomanip>
#include <limits>
#include <cmath>
#include <ctime>
using std::cout;
using std::cerr;
using std::endl;
using std::string;
using std::vector;
using std::exception;
using std::ofstream;
using std::fixed;
using std::setprecision;
using std::numeric_limits;
#include <ArgumentList.hpp>
using isa::utils::ArgumentList;
#include <Observation.hpp>
using AstroData::Observation;
#include <InitializeOpenCL.hpp>
using isa::OpenCL::initializeOpenCL;
#include <CLData.hpp>
using isa::OpenCL::CLData;
#include <utils.hpp>
using isa::utils::same;
#include <Folding.hpp>
using PulsarSearch::Folding;
#include <FoldingCPU.hpp>
using PulsarSearch::folding;
#include <Bins.hpp>
using PulsarSearch::getNrSamplesPerBin;
typedef float dataType;
const string typeName("float");
const unsigned int padding = 32;
// LOFAR
//const unsigned int nrSamplesPerSecond = 200000;
// Apertif
const unsigned int nrSamplesPerSecond = 20000;
// DMs
const unsigned int nrDMs = 256;
// Periods
const unsigned int nrPeriods = 128;
const unsigned int nrBins = 256;
const unsigned int periodStep = 64;
int main(int argc, char *argv[]) {
unsigned int clPlatformID = 0;
unsigned int clDeviceID = 0;
long long unsigned int wrongValues = 0;
Observation< dataType > observation("FoldingTest", typeName);
CLData< dataType > * dedispersedData = new CLData< dataType >("DedispersedData", true);
CLData< dataType > * foldedData = new CLData<dataType >("FoldedData", true);
CLData< unsigned int > * readCounterData = new CLData< unsigned int >("ReadCounterData", true);
CLData< unsigned int > * writeCounterData = new CLData< unsigned int >("WriteCounterData", true);
CLData< unsigned int > * nrSamplesPerBin = new CLData< unsigned int >("NrSamplesPerBin", true);
try {
ArgumentList args(argc, argv);
clPlatformID = args.getSwitchArgument< unsigned int >("-opencl_platform");
clDeviceID = args.getSwitchArgument< unsigned int >("-opencl_device");
} catch ( exception &err ) {
cerr << err.what() << endl;
return 1;
}
// Setup of the observation
observation.setPadding(padding);
observation.setNrSamplesPerSecond(nrSamplesPerSecond);
observation.setNrDMs(nrDMs);
observation.setNrPeriods(nrPeriods);
observation.setFirstPeriod(nrBins);
observation.setPeriodStep(periodStep);
observation.setNrBins(nrBins);
cl::Context * clContext = new cl::Context();
vector< cl::Platform > * clPlatforms = new vector< cl::Platform >();
vector< cl::Device > * clDevices = new vector< cl::Device >();
vector< vector< cl::CommandQueue > > * clQueues = new vector< vector < cl::CommandQueue > >();
initializeOpenCL(clPlatformID, 1, clPlatforms, clContext, clDevices, clQueues);
// Allocate memory
dedispersedData->allocateHostData(observation.getNrSamplesPerSecond() * observation.getNrPaddedDMs());
foldedData->allocateHostData(observation.getNrPaddedDMs() * observation.getNrBins() * observation.getNrPeriods());
foldedData->blankHostData();
readCounterData->allocateHostData(observation.getNrPeriods() * 2 * observation.getNrPaddedBins());
readCounterData->blankHostData();
writeCounterData->allocateHostData(observation.getNrPeriods() * 2 * observation.getNrPaddedBins());
writeCounterData->blankHostData();
vector< unsigned int > * nrSamplesPerBinData = getNrSamplesPerBin(observation);
nrSamplesPerBin->allocateHostData(*nrSamplesPerBinData);
dedispersedData->setCLContext(clContext);
dedispersedData->setCLQueue(&((clQueues->at(clDeviceID)).at(0)));
foldedData->setCLContext(clContext);
foldedData->setCLQueue(&((clQueues->at(clDeviceID)).at(0)));
readCounterData->setCLContext(clContext);
readCounterData->setCLQueue(&((clQueues->at(clDeviceID)).at(0)));
writeCounterData->setCLContext(clContext);
writeCounterData->setCLQueue(&((clQueues->at(clDeviceID)).at(0)));
nrSamplesPerBin->setCLContext(clContext);
nrSamplesPerBin->setCLQueue(&((clQueues->at(clDeviceID)).at(0)));
nrSamplesPerBin->setDeviceReadOnly();
try {
dedispersedData->allocateDeviceData();
foldedData->allocateDeviceData();
foldedData->copyHostToDevice();
readCounterData->allocateDeviceData();
readCounterData->copyHostToDevice();
writeCounterData->allocateDeviceData();
writeCounterData->copyHostToDevice();
nrSamplesPerBin->allocateDeviceData();
nrSamplesPerBin->copyHostToDevice();
} catch ( OpenCLError err ) {
cerr << err.what() << endl;
return 1;
}
srand(time(NULL));
for ( unsigned int sample = 0; sample < observation.getNrSamplesPerSecond(); sample++ ) {
for ( unsigned int DM = 0; DM < observation.getNrDMs(); DM++ ) {
dedispersedData->setHostDataItem((sample * observation.getNrPaddedDMs()) + DM, rand() % 100);
}
}
// Test
try {
// Generate kernel
Folding< dataType > clFold("clFold", typeName);
clFold.bindOpenCL(clContext, &(clDevices->at(clDeviceID)), &((clQueues->at(clDeviceID)).at(0)));
clFold.setObservation(&observation);
clFold.setNrSamplesPerBin(nrSamplesPerBin);
clFold.setNrDMsPerBlock(128);
clFold.setNrPeriodsPerBlock(2);
clFold.setNrBinsPerBlock(1);
clFold.setNrDMsPerThread(2);
clFold.setNrPeriodsPerThread(2);
clFold.setNrBinsPerThread(4);
clFold.generateCode();
dedispersedData->copyHostToDevice();
clFold(0, dedispersedData, foldedData, readCounterData, writeCounterData);
foldedData->copyDeviceToHost();
} catch ( OpenCLError err ) {
cerr << err.what() << endl;
return 1;
}
// Check
CLData< dataType > * CPUFolded = new CLData<dataType >("CPUFolded", true);
CLData< unsigned int > * CPUCounter = new CLData< unsigned int >("CPUCounter", true);
CPUFolded->allocateHostData(observation.getNrBins() * observation.getNrPeriods() * observation.getNrPaddedDMs());
CPUCounter->allocateHostData(observation.getNrPeriods() * 2 * observation.getNrPaddedBins());
CPUCounter->blankHostData();
folding(0, observation, dedispersedData->getHostData(), CPUFolded->getHostData(), CPUCounter->getHostData());
for ( unsigned int bin = 0; bin < observation.getNrBins(); bin++ ) {
long long unsigned int wrongValuesBin = 0;
for ( unsigned int period = 0; period < observation.getNrPeriods(); period++ ) {
for ( unsigned int DM = 0; DM < observation.getNrDMs(); DM++ ) {
const unsigned int dataItem = (bin * observation.getNrPeriods() * observation.getNrPaddedDMs()) + (period * observation.getNrPaddedDMs()) + DM;
if ( !same(CPUFolded->getHostDataItem(dataItem), foldedData->getHostDataItem(dataItem)) ) {
wrongValues++;
wrongValuesBin++;
}
}
}
if ( wrongValuesBin > 0 ) {
cout << "Wrong samples bin " << bin << ": " << wrongValuesBin << " (" << (wrongValuesBin * 100) / (static_cast< long long unsigned int >(observation.getNrDMs()) * observation.getNrPeriods()) << "%)." << endl;
}
}
cout << endl;
cout << "Wrong samples: " << wrongValues << " (" << (wrongValues * 100) / (static_cast< long long unsigned int >(observation.getNrDMs()) * observation.getNrPeriods() * observation.getNrBins()) << "%)." << endl;
cout << endl;
return 0;
}
<commit_msg>Code not modified, just some reordering of the includes.<commit_after>//
// Copyright (C) 2012
// Alessio Sclocco <a.sclocco@vu.nl>
//
// 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 <iostream>
using std::cout;
using std::cerr;
using std::endl;
#include <string>
using std::string;
#include <vector>
using std::vector;
#include <exception>
using std::exception;
#include <iomanip>
using std::fixed;
using std::setprecision;
#include <limits>
using std::numeric_limits;
#include <cmath>
#include <ctime>
#include <ArgumentList.hpp>
using isa::utils::ArgumentList;
#include <Observation.hpp>
using AstroData::Observation;
#include <InitializeOpenCL.hpp>
using isa::OpenCL::initializeOpenCL;
#include <CLData.hpp>
using isa::OpenCL::CLData;
#include <utils.hpp>
using isa::utils::same;
#include <Folding.hpp>
using PulsarSearch::Folding;
#include <FoldingCPU.hpp>
using PulsarSearch::folding;
#include <Bins.hpp>
using PulsarSearch::getNrSamplesPerBin;
typedef float dataType;
const string typeName("float");
const unsigned int padding = 32;
// LOFAR
//const unsigned int nrSamplesPerSecond = 200000;
// Apertif
const unsigned int nrSamplesPerSecond = 20000;
// DMs
const unsigned int nrDMs = 256;
// Periods
const unsigned int nrPeriods = 128;
const unsigned int nrBins = 256;
const unsigned int periodStep = 64;
int main(int argc, char *argv[]) {
unsigned int clPlatformID = 0;
unsigned int clDeviceID = 0;
long long unsigned int wrongValues = 0;
Observation< dataType > observation("FoldingTest", typeName);
CLData< dataType > * dedispersedData = new CLData< dataType >("DedispersedData", true);
CLData< dataType > * foldedData = new CLData<dataType >("FoldedData", true);
CLData< unsigned int > * readCounterData = new CLData< unsigned int >("ReadCounterData", true);
CLData< unsigned int > * writeCounterData = new CLData< unsigned int >("WriteCounterData", true);
CLData< unsigned int > * nrSamplesPerBin = new CLData< unsigned int >("NrSamplesPerBin", true);
try {
ArgumentList args(argc, argv);
clPlatformID = args.getSwitchArgument< unsigned int >("-opencl_platform");
clDeviceID = args.getSwitchArgument< unsigned int >("-opencl_device");
} catch ( exception &err ) {
cerr << err.what() << endl;
return 1;
}
// Setup of the observation
observation.setPadding(padding);
observation.setNrSamplesPerSecond(nrSamplesPerSecond);
observation.setNrDMs(nrDMs);
observation.setNrPeriods(nrPeriods);
observation.setFirstPeriod(nrBins);
observation.setPeriodStep(periodStep);
observation.setNrBins(nrBins);
cl::Context * clContext = new cl::Context();
vector< cl::Platform > * clPlatforms = new vector< cl::Platform >();
vector< cl::Device > * clDevices = new vector< cl::Device >();
vector< vector< cl::CommandQueue > > * clQueues = new vector< vector < cl::CommandQueue > >();
initializeOpenCL(clPlatformID, 1, clPlatforms, clContext, clDevices, clQueues);
// Allocate memory
dedispersedData->allocateHostData(observation.getNrSamplesPerSecond() * observation.getNrPaddedDMs());
foldedData->allocateHostData(observation.getNrPaddedDMs() * observation.getNrBins() * observation.getNrPeriods());
foldedData->blankHostData();
readCounterData->allocateHostData(observation.getNrPeriods() * 2 * observation.getNrPaddedBins());
readCounterData->blankHostData();
writeCounterData->allocateHostData(observation.getNrPeriods() * 2 * observation.getNrPaddedBins());
writeCounterData->blankHostData();
vector< unsigned int > * nrSamplesPerBinData = getNrSamplesPerBin(observation);
nrSamplesPerBin->allocateHostData(*nrSamplesPerBinData);
dedispersedData->setCLContext(clContext);
dedispersedData->setCLQueue(&((clQueues->at(clDeviceID)).at(0)));
foldedData->setCLContext(clContext);
foldedData->setCLQueue(&((clQueues->at(clDeviceID)).at(0)));
readCounterData->setCLContext(clContext);
readCounterData->setCLQueue(&((clQueues->at(clDeviceID)).at(0)));
writeCounterData->setCLContext(clContext);
writeCounterData->setCLQueue(&((clQueues->at(clDeviceID)).at(0)));
nrSamplesPerBin->setCLContext(clContext);
nrSamplesPerBin->setCLQueue(&((clQueues->at(clDeviceID)).at(0)));
nrSamplesPerBin->setDeviceReadOnly();
try {
dedispersedData->allocateDeviceData();
foldedData->allocateDeviceData();
foldedData->copyHostToDevice();
readCounterData->allocateDeviceData();
readCounterData->copyHostToDevice();
writeCounterData->allocateDeviceData();
writeCounterData->copyHostToDevice();
nrSamplesPerBin->allocateDeviceData();
nrSamplesPerBin->copyHostToDevice();
} catch ( OpenCLError err ) {
cerr << err.what() << endl;
return 1;
}
srand(time(NULL));
for ( unsigned int sample = 0; sample < observation.getNrSamplesPerSecond(); sample++ ) {
for ( unsigned int DM = 0; DM < observation.getNrDMs(); DM++ ) {
dedispersedData->setHostDataItem((sample * observation.getNrPaddedDMs()) + DM, rand() % 100);
}
}
// Test
try {
// Generate kernel
Folding< dataType > clFold("clFold", typeName);
clFold.bindOpenCL(clContext, &(clDevices->at(clDeviceID)), &((clQueues->at(clDeviceID)).at(0)));
clFold.setObservation(&observation);
clFold.setNrSamplesPerBin(nrSamplesPerBin);
clFold.setNrDMsPerBlock(128);
clFold.setNrPeriodsPerBlock(2);
clFold.setNrBinsPerBlock(1);
clFold.setNrDMsPerThread(2);
clFold.setNrPeriodsPerThread(2);
clFold.setNrBinsPerThread(4);
clFold.generateCode();
dedispersedData->copyHostToDevice();
clFold(0, dedispersedData, foldedData, readCounterData, writeCounterData);
foldedData->copyDeviceToHost();
} catch ( OpenCLError err ) {
cerr << err.what() << endl;
return 1;
}
// Check
CLData< dataType > * CPUFolded = new CLData<dataType >("CPUFolded", true);
CLData< unsigned int > * CPUCounter = new CLData< unsigned int >("CPUCounter", true);
CPUFolded->allocateHostData(observation.getNrBins() * observation.getNrPeriods() * observation.getNrPaddedDMs());
CPUCounter->allocateHostData(observation.getNrPeriods() * 2 * observation.getNrPaddedBins());
CPUCounter->blankHostData();
folding(0, observation, dedispersedData->getHostData(), CPUFolded->getHostData(), CPUCounter->getHostData());
for ( unsigned int bin = 0; bin < observation.getNrBins(); bin++ ) {
long long unsigned int wrongValuesBin = 0;
for ( unsigned int period = 0; period < observation.getNrPeriods(); period++ ) {
for ( unsigned int DM = 0; DM < observation.getNrDMs(); DM++ ) {
const unsigned int dataItem = (bin * observation.getNrPeriods() * observation.getNrPaddedDMs()) + (period * observation.getNrPaddedDMs()) + DM;
if ( !same(CPUFolded->getHostDataItem(dataItem), foldedData->getHostDataItem(dataItem)) ) {
wrongValues++;
wrongValuesBin++;
}
}
}
if ( wrongValuesBin > 0 ) {
cout << "Wrong samples bin " << bin << ": " << wrongValuesBin << " (" << (wrongValuesBin * 100) / (static_cast< long long unsigned int >(observation.getNrDMs()) * observation.getNrPeriods()) << "%)." << endl;
}
}
cout << endl;
cout << "Wrong samples: " << wrongValues << " (" << (wrongValues * 100) / (static_cast< long long unsigned int >(observation.getNrDMs()) * observation.getNrPeriods() * observation.getNrBins()) << "%)." << endl;
cout << endl;
return 0;
}
<|endoftext|> |
<commit_before>//#include <mcheck.h>
#include <stdlib.h>
#include <stdio.h>
#include "LinkedList.h"
#include "ChessBoard.h"
#include "HumanPlayer.h"
#include "AIPlayer.h"
int main(void) {
ChessBoard board;
LinkedList<Move> regulars, nulls;
ListIterator<Move> iter;
int turn = WHITE;
Move move;
bool found;
// Initialize players
AIPlayer black(BLACK, 4);
HumanPlayer white(WHITE);
// setup board
board.initDefaultSetup();
do {
// show board
board.print();
// query player's choice
if(turn) {
found = black.getMove(board, move);
}
else {
found = white.getMove(board, move);
}
// if player has a move
if(found) {
// get all moves
regulars.clear();
nulls.clear();
board.getMoves(turn, regulars, regulars, nulls);
// execute maintenance moves
iter = nulls.getIterator();
while(*iter) {
board.move((*iter)->value);
iter++;
}
// execute move
board.move(move);
move.print();
}
// opponents turn
turn = TOGGLE_COLOR(turn);
}
while(found);
// who won?
if(turn) {
printf("\n Black wins!\n\n");
}
else {
printf("\n White wins!\n\n");
}
}
<commit_msg>AI player goes to ply 2 only<commit_after>//#include <mcheck.h>
#include <stdlib.h>
#include <stdio.h>
#include "LinkedList.h"
#include "ChessBoard.h"
#include "HumanPlayer.h"
#include "AIPlayer.h"
int main(void) {
ChessBoard board;
LinkedList<Move> regulars, nulls;
ListIterator<Move> iter;
int turn = WHITE;
Move move;
bool found;
// Initialize players
AIPlayer black(BLACK, 2);
HumanPlayer white(WHITE);
// setup board
board.initDefaultSetup();
do {
// show board
board.print();
// query player's choice
if(turn) {
found = black.getMove(board, move);
}
else {
found = white.getMove(board, move);
}
// if player has a move
if(found) {
// get all moves
regulars.clear();
nulls.clear();
board.getMoves(turn, regulars, regulars, nulls);
// execute maintenance moves
iter = nulls.getIterator();
while(*iter) {
board.move((*iter)->value);
iter++;
}
// execute move
board.move(move);
move.print();
}
// opponents turn
turn = TOGGLE_COLOR(turn);
}
while(found);
// who won?
if(turn) {
printf("\n Black wins!\n\n");
}
else {
printf("\n White wins!\n\n");
}
}
<|endoftext|> |
<commit_before>/*
* Copyright (C) 2012
* Alessio Sclocco <a.sclocco@vu.nl>
*
* 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 <iostream>
#include <string>
#include <vector>
#include <exception>
#include <fstream>
#include <iomanip>
#include <limits>
#include <cmath>
#include <ctime>
using std::cout;
using std::cerr;
using std::endl;
using std::string;
using std::vector;
using std::exception;
using std::ofstream;
using std::fixed;
using std::setprecision;
using std::numeric_limits;
#include <ArgumentList.hpp>
#include <Observation.hpp>
#include <InitializeOpenCL.hpp>
#include <CLData.hpp>
#include <utils.hpp>
#include <Folding.hpp>
#include <FoldingCPU.hpp>
using isa::utils::ArgumentList;
using isa::utils::same;
using AstroData::Observation;
using isa::OpenCL::initializeOpenCL;
using isa::OpenCL::CLData;
using PulsarSearch::folding;
using PulsarSearch::Folding;
typedef float dataType;
const string typeName("float");
const unsigned int padding = 32;
// Common parameters
const unsigned int nrBeams = 1;
const unsigned int nrStations = 64;
// LOFAR
/*const float minFreq = 138.965f;
const float channelBandwidth = 0.195f;
const unsigned int nrSamplesPerSecond = 200000;
const unsigned int nrChannels = 32;*/
// Apertif
const float minFreq = 1425.0f;
const float channelBandwidth = 0.2929f;
const unsigned int nrSamplesPerSecond = 20000;
const unsigned int nrChannels = 1024;
// DMs
const unsigned int nrDMs = 256;
// Periods
const unsigned int nrPeriods = 128;
const unsigned int nrBins = 256;
int main(int argc, char *argv[]) {
unsigned int clPlatformID = 0;
unsigned int clDeviceID = 0;
long long unsigned int wrongValues = 0;
Observation< dataType > observation("FoldingTest", typeName);
CLData< dataType > * dedispersedData = new CLData< dataType >("DedispersedData", true);
CLData< dataType > * foldedData = new CLData<dataType >("FoldedData", true);
CLData< unsigned int > * counterData = new CLData< unsigned int >("CounterData", true);
try {
ArgumentList args(argc, argv);
clPlatformID = args.getSwitchArgument< unsigned int >("-opencl_platform");
clDeviceID = args.getSwitchArgument< unsigned int >("-opencl_device");
} catch ( exception &err ) {
cerr << err.what() << endl;
return 1;
}
// Setup of the observation
observation.setPadding(padding);
observation.setNrSamplesPerSecond(nrSamplesPerSecond);
observation.setNrDMs(nrDMs);
observation.setNrPeriods(nrPeriods);
observation.setFirstPeriod(nrBins);
observation.setPeriodStep(nrBins);
observation.setNrBins(nrBins);
cl::Context * clContext = new cl::Context();
vector< cl::Platform > * clPlatforms = new vector< cl::Platform >();
vector< cl::Device > * clDevices = new vector< cl::Device >();
vector< vector< cl::CommandQueue > > * clQueues = new vector< vector < cl::CommandQueue > >();
initializeOpenCL(clPlatformID, 1, clPlatforms, clContext, clDevices, clQueues);
// Allocate memory
dedispersedData->allocateHostData(observation.getNrSamplesPerSecond() * observation.getNrPaddedDMs());
foldedData->allocateHostData(observation.getNrPaddedDMs() * observation.getNrBins() * observation.getNrPeriods());
foldedData->blankHostData();
counterData->allocateHostData(observation.getNrPaddedDMs() * observation.getNrBins() * observation.getNrPeriods());
counterData->blankHostData();
dedispersedData->setCLContext(clContext);
dedispersedData->setCLQueue(&((clQueues->at(clDeviceID)).at(0)));
foldedData->setCLContext(clContext);
foldedData->setCLQueue(&((clQueues->at(clDeviceID)).at(0)));
counterData->setCLContext(clContext);
counterData->setCLQueue(&((clQueues->at(clDeviceID)).at(0)));
try {
dedispersedData->allocateDeviceData();
foldedData->allocateDeviceData();
foldedData->copyHostToDevice();
counterData->allocateDeviceData();
counterData->copyHostToDevice();
} catch ( OpenCLError err ) {
cerr << err.what() << endl;
return 1;
}
srand(time(NULL));
for ( unsigned int sample = 0; sample < observation.getNrSamplesPerSecond(); sample++ ) {
for ( unsigned int DM = 0; DM < observation.getNrDMs(); DM++ ) {
dedispersedData->setHostDataItem((sample * observation.getNrPaddedDMs()) + DM, rand() % 100);
}
}
// Test
try {
// Generate kernel
Folding< dataType > clFold("clFold", typeName);
clFold.bindOpenCL(clContext, &(clDevices->at(clDeviceID)), &((clQueues->at(clDeviceID)).at(0)));
clFold.setObservation(&observation);
clFold.setNrDMsPerBlock(128);
clFold.setNrPeriodsPerBlock(2);
clFold.setNrBinsPerBlock(1);
clFold.setNrDMsPerThread(2);
clFold.setNrPeriodsPerThread(2);
clFold.setNrBinsPerThread(4);
clFold.generateCode();
dedispersedData->copyHostToDevice();
clFold(dedispersedData, foldedData, counterData);
foldedData->copyDeviceToHost();
} catch ( OpenCLError err ) {
cerr << err.what() << endl;
return 1;
}
// Check
CLData< dataType > * CPUFolded = new CLData<dataType >("CPUFolded", true);
CLData< unsigned int > * CPUCounter = new CLData< unsigned int >("CPUCounter", true);
CPUFolded->allocateHostData(observation.getNrBins() * observation.getNrPeriods() * observation.getNrPaddedDMs());
CPUCounter->allocateHostData(observation.getNrBins() * observation.getNrPeriods() * observation.getNrPaddedDMs());
folding(0, observation, dedispersedData->getHostData(), CPUFolded->getHostData(), CPUCounter->getHostData());
for ( unsigned int bin = 0; bin < observation.getNrBins(); bin++ ) {
long long unsigned int wrongValuesBin = 0;
for ( unsigned int period = 0; period < observation.getNrPeriods(); period++ ) {
for ( unsigned int DM = 0; DM < observation.getNrDMs(); DM++ ) {
const unsigned int dataItem = (bin * observation.getNrPeriods() * observation.getNrPaddedDMs()) + (period * observation.getNrPaddedDMs()) + DM;
if ( !same(CPUFolded->getHostDataItem(dataItem), foldedData->getHostDataItem(dataItem)) ) {
wrongValues++;
wrongValuesBin++;
}
}
}
if ( wrongValuesBin > 0 ) {
cout << "Wrong samples bin " << bin << ": " << wrongValuesBin << " (" << (wrongValuesBin * 100) / (static_cast< long long unsigned int >(observation.getNrDMs()) * observation.getNrPeriods()) << "%)." << endl;
}
}
cout << endl;
cout << "Wrong samples: " << wrongValues << " (" << (wrongValues * 100) / (static_cast< long long unsigned int >(observation.getNrDMs()) * observation.getNrPeriods() * observation.getNrBins()) << "%)." << endl;
cout << endl;
return 0;
}
<commit_msg>Using the OpenCL equivalent CPU version in testing.<commit_after>/*
* Copyright (C) 2012
* Alessio Sclocco <a.sclocco@vu.nl>
*
* 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 <iostream>
#include <string>
#include <vector>
#include <exception>
#include <fstream>
#include <iomanip>
#include <limits>
#include <cmath>
#include <ctime>
using std::cout;
using std::cerr;
using std::endl;
using std::string;
using std::vector;
using std::exception;
using std::ofstream;
using std::fixed;
using std::setprecision;
using std::numeric_limits;
#include <ArgumentList.hpp>
#include <Observation.hpp>
#include <InitializeOpenCL.hpp>
#include <CLData.hpp>
#include <utils.hpp>
#include <Folding.hpp>
#include <FoldingCPU.hpp>
using isa::utils::ArgumentList;
using isa::utils::same;
using AstroData::Observation;
using isa::OpenCL::initializeOpenCL;
using isa::OpenCL::CLData;
using PulsarSearch::folding;
using PulsarSearch::Folding;
typedef float dataType;
const string typeName("float");
const unsigned int padding = 32;
// Common parameters
const unsigned int nrBeams = 1;
const unsigned int nrStations = 64;
// LOFAR
/*const float minFreq = 138.965f;
const float channelBandwidth = 0.195f;
const unsigned int nrSamplesPerSecond = 200000;
const unsigned int nrChannels = 32;*/
// Apertif
const float minFreq = 1425.0f;
const float channelBandwidth = 0.2929f;
const unsigned int nrSamplesPerSecond = 20000;
const unsigned int nrChannels = 1024;
// DMs
const unsigned int nrDMs = 256;
// Periods
const unsigned int nrPeriods = 128;
const unsigned int nrBins = 256;
int main(int argc, char *argv[]) {
unsigned int clPlatformID = 0;
unsigned int clDeviceID = 0;
long long unsigned int wrongValues = 0;
Observation< dataType > observation("FoldingTest", typeName);
CLData< dataType > * dedispersedData = new CLData< dataType >("DedispersedData", true);
CLData< dataType > * foldedData = new CLData<dataType >("FoldedData", true);
CLData< unsigned int > * counterData = new CLData< unsigned int >("CounterData", true);
try {
ArgumentList args(argc, argv);
clPlatformID = args.getSwitchArgument< unsigned int >("-opencl_platform");
clDeviceID = args.getSwitchArgument< unsigned int >("-opencl_device");
} catch ( exception &err ) {
cerr << err.what() << endl;
return 1;
}
// Setup of the observation
observation.setPadding(padding);
observation.setNrSamplesPerSecond(nrSamplesPerSecond);
observation.setNrDMs(nrDMs);
observation.setNrPeriods(nrPeriods);
observation.setFirstPeriod(nrBins);
observation.setPeriodStep(nrBins);
observation.setNrBins(nrBins);
cl::Context * clContext = new cl::Context();
vector< cl::Platform > * clPlatforms = new vector< cl::Platform >();
vector< cl::Device > * clDevices = new vector< cl::Device >();
vector< vector< cl::CommandQueue > > * clQueues = new vector< vector < cl::CommandQueue > >();
initializeOpenCL(clPlatformID, 1, clPlatforms, clContext, clDevices, clQueues);
// Allocate memory
dedispersedData->allocateHostData(observation.getNrSamplesPerSecond() * observation.getNrPaddedDMs());
foldedData->allocateHostData(observation.getNrPaddedDMs() * observation.getNrBins() * observation.getNrPeriods());
foldedData->blankHostData();
counterData->allocateHostData(observation.getNrPaddedDMs() * observation.getNrBins() * observation.getNrPeriods());
counterData->blankHostData();
dedispersedData->setCLContext(clContext);
dedispersedData->setCLQueue(&((clQueues->at(clDeviceID)).at(0)));
foldedData->setCLContext(clContext);
foldedData->setCLQueue(&((clQueues->at(clDeviceID)).at(0)));
counterData->setCLContext(clContext);
counterData->setCLQueue(&((clQueues->at(clDeviceID)).at(0)));
try {
dedispersedData->allocateDeviceData();
foldedData->allocateDeviceData();
foldedData->copyHostToDevice();
counterData->allocateDeviceData();
counterData->copyHostToDevice();
} catch ( OpenCLError err ) {
cerr << err.what() << endl;
return 1;
}
srand(time(NULL));
for ( unsigned int sample = 0; sample < observation.getNrSamplesPerSecond(); sample++ ) {
for ( unsigned int DM = 0; DM < observation.getNrDMs(); DM++ ) {
dedispersedData->setHostDataItem((sample * observation.getNrPaddedDMs()) + DM, rand() % 100);
}
}
// Test
try {
// Generate kernel
Folding< dataType > clFold("clFold", typeName);
clFold.bindOpenCL(clContext, &(clDevices->at(clDeviceID)), &((clQueues->at(clDeviceID)).at(0)));
clFold.setObservation(&observation);
clFold.setNrDMsPerBlock(128);
clFold.setNrPeriodsPerBlock(2);
clFold.setNrBinsPerBlock(1);
clFold.setNrDMsPerThread(2);
clFold.setNrPeriodsPerThread(2);
clFold.setNrBinsPerThread(4);
clFold.generateCode();
dedispersedData->copyHostToDevice();
clFold(dedispersedData, foldedData, counterData);
foldedData->copyDeviceToHost();
} catch ( OpenCLError err ) {
cerr << err.what() << endl;
return 1;
}
// Check
CLData< dataType > * CPUFolded = new CLData<dataType >("CPUFolded", true);
CLData< unsigned int > * CPUCounter = new CLData< unsigned int >("CPUCounter", true);
CPUFolded->allocateHostData(observation.getNrBins() * observation.getNrPeriods() * observation.getNrPaddedDMs());
CPUCounter->allocateHostData(observation.getNrBins() * observation.getNrPeriods() * observation.getNrPaddedDMs());
folding(observation, dedispersedData->getHostData(), CPUFolded->getHostData(), CPUCounter->getHostData());
for ( unsigned int bin = 0; bin < observation.getNrBins(); bin++ ) {
long long unsigned int wrongValuesBin = 0;
for ( unsigned int period = 0; period < observation.getNrPeriods(); period++ ) {
for ( unsigned int DM = 0; DM < observation.getNrDMs(); DM++ ) {
const unsigned int dataItem = (bin * observation.getNrPeriods() * observation.getNrPaddedDMs()) + (period * observation.getNrPaddedDMs()) + DM;
if ( !same(CPUFolded->getHostDataItem(dataItem), foldedData->getHostDataItem(dataItem)) ) {
wrongValues++;
wrongValuesBin++;
}
}
}
if ( wrongValuesBin > 0 ) {
cout << "Wrong samples bin " << bin << ": " << wrongValuesBin << " (" << (wrongValuesBin * 100) / (static_cast< long long unsigned int >(observation.getNrDMs()) * observation.getNrPeriods()) << "%)." << endl;
}
}
cout << endl;
cout << "Wrong samples: " << wrongValues << " (" << (wrongValues * 100) / (static_cast< long long unsigned int >(observation.getNrDMs()) * observation.getNrPeriods() * observation.getNrBins()) << "%)." << endl;
cout << endl;
return 0;
}
<|endoftext|> |
<commit_before>/*
This file is part of kdepim.
Copyright (c) 2004 Cornelius Schumacher <schumacher@kde.org>
This program is free software; you can redistribute it and/or modify it
under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful, but
WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
In addition, as a special exception, the copyright holders give
permission to link the code of this program with any edition of
the Qt library by Trolltech AS, Norway (or with modified versions
of Qt that use the same license as Qt), and distribute linked
combinations including the two. You must obey the GNU General
Public License in all respects for all of the code used other than
Qt. If you modify this file, you may extend this exception to
your version of the file, but you are not obligated to do so. If
you do not wish to do so, delete this exception statement from
your version.
*/
#include <interfaces/bodypartformatter.h>
#include <interfaces/bodypart.h>
#include <interfaces/bodyparturlhandler.h>
#include <khtmlparthtmlwriter.h>
#include <libkcal/calendarlocal.h>
#include <libkcal/icalformat.h>
#include <libkcal/attendee.h>
#include <libkcal/incidence.h>
#include <libkcal/incidenceformatter.h>
#include <kpimprefs.h> // for the timezone
#include <kmail/callback.h>
#include <kmail/kmmessage.h>
#include <kglobal.h>
#include <klocale.h>
#include <kstringhandler.h>
#include <kglobalsettings.h>
#include <kiconloader.h>
#include <kdebug.h>
#include <kmessagebox.h>
#include <kstandarddirs.h>
#include <kapplication.h>
#include <ktempfile.h>
#include <qurl.h>
#include <qdir.h>
#include <qtextstream.h>
using namespace KCal;
namespace {
class KMInvitationFormatterHelper : public KCal::InvitationFormatterHelper
{
public:
KMInvitationFormatterHelper( KMail::Interface::BodyPart *bodyPart ) : mBodyPart( bodyPart ) {}
virtual QString generateLinkURL( const QString &id ) { return mBodyPart->makeLink( id ); }
private:
KMail::Interface::BodyPart *mBodyPart;
};
class Formatter : public KMail::Interface::BodyPartFormatter
{
public:
Result format( KMail::Interface::BodyPart *bodyPart,
KMail::HtmlWriter *writer ) const
{
if ( !writer )
// Guard against crashes in createReply()
return Ok;
CalendarLocal cl( KPimPrefs::timezone() );
KMInvitationFormatterHelper helper( bodyPart );
QString html = IncidenceFormatter::formatICalInvitation( bodyPart->asText(), &cl, &helper );
if ( html.isEmpty() ) return AsIcon;
writer->queue( html );
return Ok;
}
};
class UrlHandler : public KMail::Interface::BodyPartURLHandler
{
public:
UrlHandler()
{
kdDebug() << "UrlHandler() (iCalendar)" << endl;
}
Incidence* icalToString( const QString& iCal, ICalFormat& format ) const
{
CalendarLocal calendar;
ScheduleMessage *message =
format.parseScheduleMessage( &calendar, iCal );
if ( !message )
//TODO: Error message?
return 0;
return dynamic_cast<Incidence*>( message->event() );
}
void setStatusOnMyself( Incidence* incidence, Attendee::PartStat status,
const QString& receiver ) const
{
Attendee::List attendees = incidence->attendees();
Attendee::List::ConstIterator it;
Attendee* myself = 0;
// Find myself. There will always be all attendees listed, even if
// only I need to answer it.
if ( attendees.count() == 1 )
// Only one attendee, that must be me
myself = *attendees.begin();
else {
for ( it = attendees.begin(); it != attendees.end(); ++it ) {
if( (*it)->email() == receiver ) {
// We are the current one, and even the receiver, note
// this and quit searching.
myself = (*it);
break;
}
#if 0
// This is postponed until we have shared identities.
// And then it might be unnecessary
if ( (*it)->email() == KOPrefs::instance()->email() ) {
// If we are the current one, note that. Still continue to
// search in case we find the receiver himself.
myself = (*it);
}
#endif
}
// TODO: If still not found, ask about it
}
Q_ASSERT( myself );
Attendee* newMyself = 0;
if( myself ) {
myself->setStatus( status );
// No more request response
myself->setRSVP(false);
newMyself = new Attendee( myself->name(),
receiver.isEmpty() ? myself->email() :
receiver,
myself->RSVP(),
myself->status(),
myself->role(),
myself->uid() );
}
// Make sure only ourselves is in the event
incidence->clearAttendees();
if( newMyself )
incidence->addAttendee( newMyself );
}
bool mail( Incidence* incidence, KMail::Callback& callback ) const
{
ICalFormat format;
QString msg = format.createScheduleMessage( incidence,
Scheduler::Reply );
QString subject;
if ( !incidence->summary().isEmpty() )
subject = i18n( "Answer: %1" ).arg( incidence->summary() );
else
subject = i18n( "Answer: Incidence with no summary" );
return callback.mailICal( incidence->organizer().fullName(), msg, subject );
}
bool saveFile( const QString& receiver, const QString& iCal,
const QString& type ) const
{
KTempFile file( locateLocal( "data", "korganizer/income." + type + '/',
true ) );
QTextStream* ts = file.textStream();
if ( !ts ) {
KMessageBox::error( 0, i18n("Could not save file to KOrganizer") );
return false;
}
ts->setEncoding( QTextStream::UnicodeUTF8 );
(*ts) << receiver << '\n' << iCal;
return true;
}
bool handleAccept( const QString& iCal, KMail::Callback& callback ) const
{
const QString receiver = callback.receiver();
if ( receiver.isEmpty() )
// Must be some error. Still return true though, since we did handle it
return true;
// First, save it for KOrganizer to handle
saveFile( receiver, iCal, "accepted" );
// Now produce the return message
ICalFormat format;
Incidence* incidence = icalToString( iCal, format );
if( !incidence ) return false;
setStatusOnMyself( incidence, Attendee::Accepted, receiver );
return mail( incidence, callback );
}
bool handleDecline( const QString& iCal, KMail::Callback& callback ) const
{
// Produce a decline message
ICalFormat format;
Incidence* incidence = icalToString( iCal, format );
if( !incidence ) return false;
setStatusOnMyself( incidence, Attendee::Declined, callback.receiver() );
return mail( incidence, callback );
}
bool handleClick( KMail::Interface::BodyPart *part,
const QString &path, KMail::Callback& c ) const
{
QString iCal = part->asText();
if ( path == "accept" )
return handleAccept( iCal, c );
if ( path == "decline" )
return handleDecline( iCal, c );
if ( path == "reply" || path == "cancel" )
// These should just be saved with their type as the dir
return saveFile( "Reciever Not Searched", iCal, path );
return false;
}
bool handleContextMenuRequest( KMail::Interface::BodyPart *,
const QString &,
const QPoint & ) const
{
return false;
}
QString statusBarMessage( KMail::Interface::BodyPart *,
const QString &path ) const
{
if ( !path.isEmpty() ) {
if ( path == "accept" )
return i18n("Accept incidence");
if ( path == "accept_conditionally" )
return i18n( "Accept incidence conditionally" );
if ( path == "decline" )
return i18n( "Decline incidence" );
if ( path == "check_calendar" )
return i18n("Check my calendar..." );
if ( path == "reply" )
return i18n( "Enter incidence into my calendar" );
if ( path == "cancel" )
return i18n( "Remove incidence from my calendar" );
}
return QString::null;
}
};
class Plugin : public KMail::Interface::BodyPartFormatterPlugin
{
public:
const KMail::Interface::BodyPartFormatter *bodyPartFormatter( int idx ) const
{
if ( idx == 0 ) return new Formatter();
else return 0;
}
const char *type( int idx ) const
{
if ( idx == 0 ) return "text";
else return 0;
}
const char *subtype( int idx ) const
{
if ( idx == 0 ) return "calendar";
else return 0;
}
const KMail::Interface::BodyPartURLHandler * urlHandler( int idx ) const
{
if ( idx == 0 ) return new UrlHandler();
else return 0;
}
};
}
extern "C"
KMail::Interface::BodyPartFormatterPlugin *
libkmail_bodypartformatter_text_calendar_create_bodypart_formatter_plugin()
{
KGlobal::locale()->insertCatalogue( "kmail_text_calendar_plugin" );
return new Plugin();
}
<commit_msg>Handle tentative acceptance links. There's more to come in this area all over pim.<commit_after>/*
This file is part of kdepim.
Copyright (c) 2004 Cornelius Schumacher <schumacher@kde.org>
This program is free software; you can redistribute it and/or modify it
under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful, but
WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
In addition, as a special exception, the copyright holders give
permission to link the code of this program with any edition of
the Qt library by Trolltech AS, Norway (or with modified versions
of Qt that use the same license as Qt), and distribute linked
combinations including the two. You must obey the GNU General
Public License in all respects for all of the code used other than
Qt. If you modify this file, you may extend this exception to
your version of the file, but you are not obligated to do so. If
you do not wish to do so, delete this exception statement from
your version.
*/
#include <interfaces/bodypartformatter.h>
#include <interfaces/bodypart.h>
#include <interfaces/bodyparturlhandler.h>
#include <khtmlparthtmlwriter.h>
#include <libkcal/calendarlocal.h>
#include <libkcal/icalformat.h>
#include <libkcal/attendee.h>
#include <libkcal/incidence.h>
#include <libkcal/incidenceformatter.h>
#include <kpimprefs.h> // for the timezone
#include <kmail/callback.h>
#include <kmail/kmmessage.h>
#include <kglobal.h>
#include <klocale.h>
#include <kstringhandler.h>
#include <kglobalsettings.h>
#include <kiconloader.h>
#include <kdebug.h>
#include <kmessagebox.h>
#include <kstandarddirs.h>
#include <kapplication.h>
#include <ktempfile.h>
#include <qurl.h>
#include <qdir.h>
#include <qtextstream.h>
using namespace KCal;
namespace {
class KMInvitationFormatterHelper : public KCal::InvitationFormatterHelper
{
public:
KMInvitationFormatterHelper( KMail::Interface::BodyPart *bodyPart ) : mBodyPart( bodyPart ) {}
virtual QString generateLinkURL( const QString &id ) { return mBodyPart->makeLink( id ); }
private:
KMail::Interface::BodyPart *mBodyPart;
};
class Formatter : public KMail::Interface::BodyPartFormatter
{
public:
Result format( KMail::Interface::BodyPart *bodyPart,
KMail::HtmlWriter *writer ) const
{
if ( !writer )
// Guard against crashes in createReply()
return Ok;
CalendarLocal cl( KPimPrefs::timezone() );
KMInvitationFormatterHelper helper( bodyPart );
QString html = IncidenceFormatter::formatICalInvitation( bodyPart->asText(), &cl, &helper );
if ( html.isEmpty() ) return AsIcon;
writer->queue( html );
return Ok;
}
};
class UrlHandler : public KMail::Interface::BodyPartURLHandler
{
public:
UrlHandler()
{
kdDebug() << "UrlHandler() (iCalendar)" << endl;
}
Incidence* icalToString( const QString& iCal, ICalFormat& format ) const
{
CalendarLocal calendar;
ScheduleMessage *message =
format.parseScheduleMessage( &calendar, iCal );
if ( !message )
//TODO: Error message?
return 0;
return dynamic_cast<Incidence*>( message->event() );
}
void setStatusOnMyself( Incidence* incidence, Attendee::PartStat status,
const QString& receiver ) const
{
Attendee::List attendees = incidence->attendees();
Attendee::List::ConstIterator it;
Attendee* myself = 0;
// Find myself. There will always be all attendees listed, even if
// only I need to answer it.
if ( attendees.count() == 1 )
// Only one attendee, that must be me
myself = *attendees.begin();
else {
for ( it = attendees.begin(); it != attendees.end(); ++it ) {
if( (*it)->email() == receiver ) {
// We are the current one, and even the receiver, note
// this and quit searching.
myself = (*it);
break;
}
#if 0
// This is postponed until we have shared identities.
// And then it might be unnecessary
if ( (*it)->email() == KOPrefs::instance()->email() ) {
// If we are the current one, note that. Still continue to
// search in case we find the receiver himself.
myself = (*it);
}
#endif
}
// TODO: If still not found, ask about it
}
Q_ASSERT( myself );
Attendee* newMyself = 0;
if( myself ) {
myself->setStatus( status );
// No more request response
myself->setRSVP(false);
newMyself = new Attendee( myself->name(),
receiver.isEmpty() ? myself->email() :
receiver,
myself->RSVP(),
myself->status(),
myself->role(),
myself->uid() );
}
// Make sure only ourselves is in the event
incidence->clearAttendees();
if( newMyself )
incidence->addAttendee( newMyself );
}
bool mail( Incidence* incidence, KMail::Callback& callback ) const
{
ICalFormat format;
QString msg = format.createScheduleMessage( incidence,
Scheduler::Reply );
QString subject;
if ( !incidence->summary().isEmpty() )
subject = i18n( "Answer: %1" ).arg( incidence->summary() );
else
subject = i18n( "Answer: Incidence with no summary" );
return callback.mailICal( incidence->organizer().fullName(), msg, subject );
}
bool saveFile( const QString& receiver, const QString& iCal,
const QString& type ) const
{
KTempFile file( locateLocal( "data", "korganizer/income." + type + '/',
true ) );
QTextStream* ts = file.textStream();
if ( !ts ) {
KMessageBox::error( 0, i18n("Could not save file to KOrganizer") );
return false;
}
ts->setEncoding( QTextStream::UnicodeUTF8 );
(*ts) << receiver << '\n' << iCal;
return true;
}
bool handleAccept( const QString& iCal, KMail::Callback& callback ) const
{
const QString receiver = callback.receiver();
if ( receiver.isEmpty() )
// Must be some error. Still return true though, since we did handle it
return true;
// First, save it for KOrganizer to handle
saveFile( receiver, iCal, "accepted" );
// Now produce the return message
ICalFormat format;
Incidence* incidence = icalToString( iCal, format );
if( !incidence ) return false;
setStatusOnMyself( incidence, Attendee::Accepted, receiver );
return mail( incidence, callback );
}
bool handleAcceptConditionally( const QString& iCal, KMail::Callback& callback ) const
{
const QString receiver = callback.receiver();
if ( receiver.isEmpty() )
// Must be some error. Still return true though, since we did handle it
return true;
// First, save it for KOrganizer to handle
saveFile( receiver, iCal, "tentative" );
// Now produce the return message
ICalFormat format;
Incidence* incidence = icalToString( iCal, format );
if( !incidence ) return false;
setStatusOnMyself( incidence, Attendee::Tentative, receiver );
return mail( incidence, callback );
}
bool handleDecline( const QString& iCal, KMail::Callback& callback ) const
{
// Produce a decline message
ICalFormat format;
Incidence* incidence = icalToString( iCal, format );
if( !incidence ) return false;
setStatusOnMyself( incidence, Attendee::Declined, callback.receiver() );
return mail( incidence, callback );
}
bool handleClick( KMail::Interface::BodyPart *part,
const QString &path, KMail::Callback& c ) const
{
QString iCal = part->asText();
if ( path == "accept" )
return handleAccept( iCal, c );
if ( path == "accept_conditionally" )
return handleAcceptConditionally( iCal, c );
if ( path == "decline" )
return handleDecline( iCal, c );
if ( path == "reply" || path == "cancel" )
// These should just be saved with their type as the dir
return saveFile( "Reciever Not Searched", iCal, path );
return false;
}
bool handleContextMenuRequest( KMail::Interface::BodyPart *,
const QString &,
const QPoint & ) const
{
return false;
}
QString statusBarMessage( KMail::Interface::BodyPart *,
const QString &path ) const
{
if ( !path.isEmpty() ) {
if ( path == "accept" )
return i18n("Accept incidence");
if ( path == "accept_conditionally" )
return i18n( "Accept incidence conditionally" );
if ( path == "decline" )
return i18n( "Decline incidence" );
if ( path == "check_calendar" )
return i18n("Check my calendar..." );
if ( path == "reply" )
return i18n( "Enter incidence into my calendar" );
if ( path == "cancel" )
return i18n( "Remove incidence from my calendar" );
}
return QString::null;
}
};
class Plugin : public KMail::Interface::BodyPartFormatterPlugin
{
public:
const KMail::Interface::BodyPartFormatter *bodyPartFormatter( int idx ) const
{
if ( idx == 0 ) return new Formatter();
else return 0;
}
const char *type( int idx ) const
{
if ( idx == 0 ) return "text";
else return 0;
}
const char *subtype( int idx ) const
{
if ( idx == 0 ) return "calendar";
else return 0;
}
const KMail::Interface::BodyPartURLHandler * urlHandler( int idx ) const
{
if ( idx == 0 ) return new UrlHandler();
else return 0;
}
};
}
extern "C"
KMail::Interface::BodyPartFormatterPlugin *
libkmail_bodypartformatter_text_calendar_create_bodypart_formatter_plugin()
{
KGlobal::locale()->insertCatalogue( "kmail_text_calendar_plugin" );
return new Plugin();
}
<|endoftext|> |
<commit_before>//
// Copyright 2014 The ANGLE Project Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
//
#include "libANGLE/renderer/d3d/HLSLCompiler.h"
#include <sstream>
#include "common/utilities.h"
#include "libANGLE/Context.h"
#include "libANGLE/Program.h"
#include "libANGLE/features.h"
#include "libANGLE/histogram_macros.h"
#include "libANGLE/renderer/d3d/ContextD3D.h"
#include "third_party/trace_event/trace_event.h"
namespace
{
#if ANGLE_APPEND_ASSEMBLY_TO_SHADER_DEBUG_INFO == ANGLE_ENABLED
# ifdef CREATE_COMPILER_FLAG_INFO
# undef CREATE_COMPILER_FLAG_INFO
# endif
# define CREATE_COMPILER_FLAG_INFO(flag) \
{ \
flag, #flag \
}
struct CompilerFlagInfo
{
UINT mFlag;
const char *mName;
};
CompilerFlagInfo CompilerFlagInfos[] = {
// NOTE: The data below is copied from d3dcompiler.h
// If something changes there it should be changed here as well
CREATE_COMPILER_FLAG_INFO(D3DCOMPILE_DEBUG), // (1 << 0)
CREATE_COMPILER_FLAG_INFO(D3DCOMPILE_SKIP_VALIDATION), // (1 << 1)
CREATE_COMPILER_FLAG_INFO(D3DCOMPILE_SKIP_OPTIMIZATION), // (1 << 2)
CREATE_COMPILER_FLAG_INFO(D3DCOMPILE_PACK_MATRIX_ROW_MAJOR), // (1 << 3)
CREATE_COMPILER_FLAG_INFO(D3DCOMPILE_PACK_MATRIX_COLUMN_MAJOR), // (1 << 4)
CREATE_COMPILER_FLAG_INFO(D3DCOMPILE_PARTIAL_PRECISION), // (1 << 5)
CREATE_COMPILER_FLAG_INFO(D3DCOMPILE_FORCE_VS_SOFTWARE_NO_OPT), // (1 << 6)
CREATE_COMPILER_FLAG_INFO(D3DCOMPILE_FORCE_PS_SOFTWARE_NO_OPT), // (1 << 7)
CREATE_COMPILER_FLAG_INFO(D3DCOMPILE_NO_PRESHADER), // (1 << 8)
CREATE_COMPILER_FLAG_INFO(D3DCOMPILE_AVOID_FLOW_CONTROL), // (1 << 9)
CREATE_COMPILER_FLAG_INFO(D3DCOMPILE_PREFER_FLOW_CONTROL), // (1 << 10)
CREATE_COMPILER_FLAG_INFO(D3DCOMPILE_ENABLE_STRICTNESS), // (1 << 11)
CREATE_COMPILER_FLAG_INFO(D3DCOMPILE_ENABLE_BACKWARDS_COMPATIBILITY), // (1 << 12)
CREATE_COMPILER_FLAG_INFO(D3DCOMPILE_IEEE_STRICTNESS), // (1 << 13)
CREATE_COMPILER_FLAG_INFO(D3DCOMPILE_OPTIMIZATION_LEVEL0), // (1 << 14)
CREATE_COMPILER_FLAG_INFO(D3DCOMPILE_OPTIMIZATION_LEVEL1), // 0
CREATE_COMPILER_FLAG_INFO(D3DCOMPILE_OPTIMIZATION_LEVEL2), // ((1 << 14) | (1 << 15))
CREATE_COMPILER_FLAG_INFO(D3DCOMPILE_OPTIMIZATION_LEVEL3), // (1 << 15)
CREATE_COMPILER_FLAG_INFO(D3DCOMPILE_RESERVED16), // (1 << 16)
CREATE_COMPILER_FLAG_INFO(D3DCOMPILE_RESERVED17), // (1 << 17)
CREATE_COMPILER_FLAG_INFO(D3DCOMPILE_WARNINGS_ARE_ERRORS) // (1 << 18)
};
# undef CREATE_COMPILER_FLAG_INFO
bool IsCompilerFlagSet(UINT mask, UINT flag)
{
bool isFlagSet = IsMaskFlagSet(mask, flag);
switch (flag)
{
case D3DCOMPILE_OPTIMIZATION_LEVEL0:
return isFlagSet && !IsMaskFlagSet(mask, UINT(D3DCOMPILE_OPTIMIZATION_LEVEL3));
case D3DCOMPILE_OPTIMIZATION_LEVEL1:
return (mask & D3DCOMPILE_OPTIMIZATION_LEVEL2) == UINT(0);
case D3DCOMPILE_OPTIMIZATION_LEVEL3:
return isFlagSet && !IsMaskFlagSet(mask, UINT(D3DCOMPILE_OPTIMIZATION_LEVEL0));
default:
return isFlagSet;
}
}
#endif // ANGLE_APPEND_ASSEMBLY_TO_SHADER_DEBUG_INFO == ANGLE_ENABLED
constexpr char kOldCompilerLibrary[] = "d3dcompiler_old.dll";
enum D3DCompilerLoadLibraryResult
{
D3DCompilerDefaultLibrarySuccess,
D3DCompilerOldLibrarySuccess,
D3DCompilerFailure,
D3DCompilerEnumBoundary,
};
} // anonymous namespace
namespace rx
{
CompileConfig::CompileConfig() : flags(0), name() {}
CompileConfig::CompileConfig(UINT flags, const std::string &name) : flags(flags), name(name) {}
HLSLCompiler::HLSLCompiler()
: mInitialized(false),
mD3DCompilerModule(nullptr),
mD3DCompileFunc(nullptr),
mD3DDisassembleFunc(nullptr)
{}
HLSLCompiler::~HLSLCompiler()
{
release();
}
angle::Result HLSLCompiler::ensureInitialized(d3d::Context *context)
{
if (mInitialized)
{
return angle::Result::Continue;
}
TRACE_EVENT0("gpu.angle", "HLSLCompiler::initialize");
#if !defined(ANGLE_ENABLE_WINDOWS_STORE)
# if defined(ANGLE_PRELOADED_D3DCOMPILER_MODULE_NAMES)
// Find a D3DCompiler module that had already been loaded based on a predefined list of
// versions.
static const char *d3dCompilerNames[] = ANGLE_PRELOADED_D3DCOMPILER_MODULE_NAMES;
for (size_t i = 0; i < ArraySize(d3dCompilerNames); ++i)
{
if (GetModuleHandleExA(0, d3dCompilerNames[i], &mD3DCompilerModule))
{
break;
}
}
# endif // ANGLE_PRELOADED_D3DCOMPILER_MODULE_NAMES
if (!mD3DCompilerModule)
{
// Load the version of the D3DCompiler DLL associated with the Direct3D version ANGLE was
// built with.
mD3DCompilerModule = LoadLibraryA(D3DCOMPILER_DLL_A);
if (mD3DCompilerModule)
{
ANGLE_HISTOGRAM_ENUMERATION("GPU.ANGLE.D3DCompilerLoadLibraryResult",
D3DCompilerDefaultLibrarySuccess, D3DCompilerEnumBoundary);
}
else
{
WARN() << "Failed to load HLSL compiler library. Using 'old' DLL.";
mD3DCompilerModule = LoadLibraryA(kOldCompilerLibrary);
if (mD3DCompilerModule)
{
ANGLE_HISTOGRAM_ENUMERATION("GPU.ANGLE.D3DCompilerLoadLibraryResult",
D3DCompilerOldLibrarySuccess, D3DCompilerEnumBoundary);
}
}
}
if (!mD3DCompilerModule)
{
DWORD lastError = GetLastError();
ERR() << "D3D Compiler LoadLibrary failed. GetLastError=" << lastError;
ANGLE_HISTOGRAM_ENUMERATION("GPU.ANGLE.D3DCompilerLoadLibraryResult", D3DCompilerFailure,
D3DCompilerEnumBoundary);
ANGLE_TRY_HR(context, E_OUTOFMEMORY, "LoadLibrary failed to load D3D Compiler DLL.");
}
mD3DCompileFunc =
reinterpret_cast<pD3DCompile>(GetProcAddress(mD3DCompilerModule, "D3DCompile"));
ASSERT(mD3DCompileFunc);
mD3DDisassembleFunc =
reinterpret_cast<pD3DDisassemble>(GetProcAddress(mD3DCompilerModule, "D3DDisassemble"));
ASSERT(mD3DDisassembleFunc);
#else
// D3D Shader compiler is linked already into this module, so the export
// can be directly assigned.
mD3DCompilerModule = nullptr;
mD3DCompileFunc = reinterpret_cast<pD3DCompile>(D3DCompile);
mD3DDisassembleFunc = reinterpret_cast<pD3DDisassemble>(D3DDisassemble);
#endif
ANGLE_CHECK_HR(context, mD3DCompileFunc, "Error finding D3DCompile entry point.",
E_OUTOFMEMORY);
mInitialized = true;
return angle::Result::Continue;
}
void HLSLCompiler::release()
{
if (mInitialized)
{
FreeLibrary(mD3DCompilerModule);
mD3DCompilerModule = nullptr;
mD3DCompileFunc = nullptr;
mD3DDisassembleFunc = nullptr;
mInitialized = false;
}
}
angle::Result HLSLCompiler::compileToBinary(d3d::Context *context,
gl::InfoLog &infoLog,
const std::string &hlsl,
const std::string &profile,
const std::vector<CompileConfig> &configs,
const D3D_SHADER_MACRO *overrideMacros,
ID3DBlob **outCompiledBlob,
std::string *outDebugInfo)
{
ASSERT(mInitialized);
#if !defined(ANGLE_ENABLE_WINDOWS_STORE)
ASSERT(mD3DCompilerModule);
#endif
ASSERT(mD3DCompileFunc);
#if !defined(ANGLE_ENABLE_WINDOWS_STORE)
if (gl::DebugAnnotationsActive())
{
std::string sourcePath = getTempPath();
std::ostringstream stream;
stream << "#line 2 \"" << sourcePath << "\"\n\n" << hlsl;
std::string sourceText = stream.str();
writeFile(sourcePath.c_str(), sourceText.c_str(), sourceText.size());
}
#endif
const D3D_SHADER_MACRO *macros = overrideMacros ? overrideMacros : nullptr;
for (size_t i = 0; i < configs.size(); ++i)
{
ID3DBlob *errorMessage = nullptr;
ID3DBlob *binary = nullptr;
HRESULT result = S_OK;
{
TRACE_EVENT0("gpu.angle", "D3DCompile");
SCOPED_ANGLE_HISTOGRAM_TIMER("GPU.ANGLE.D3DCompileMS");
result = mD3DCompileFunc(hlsl.c_str(), hlsl.length(), gl::g_fakepath, macros, nullptr,
"main", profile.c_str(), configs[i].flags, 0, &binary,
&errorMessage);
}
if (errorMessage)
{
std::string message = static_cast<const char *>(errorMessage->GetBufferPointer());
SafeRelease(errorMessage);
infoLog.appendSanitized(message.c_str());
// This produces unbelievable amounts of spam in about:gpu.
// WARN() << std::endl << hlsl;
WARN() << std::endl << message;
if ((message.find("error X3531:") !=
std::string::npos || // "can't unroll loops marked with loop attribute"
message.find("error X4014:") !=
std::string::npos) && // "cannot have gradient operations inside loops with
// divergent flow control", even though it is
// counter-intuitive to disable unrolling for this
// error, some very long shaders have trouble deciding
// which loops to unroll and turning off forced unrolls
// allows them to compile properly.
macros != nullptr)
{
macros = nullptr; // Disable [loop] and [flatten]
// Retry without changing compiler flags
i--;
continue;
}
}
if (SUCCEEDED(result))
{
*outCompiledBlob = binary;
(*outDebugInfo) +=
"// COMPILER INPUT HLSL BEGIN\n\n" + hlsl + "\n// COMPILER INPUT HLSL END\n";
#if ANGLE_APPEND_ASSEMBLY_TO_SHADER_DEBUG_INFO == ANGLE_ENABLED
(*outDebugInfo) += "\n\n// ASSEMBLY BEGIN\n\n";
(*outDebugInfo) += "// Compiler configuration: " + configs[i].name + "\n// Flags:\n";
for (size_t fIx = 0; fIx < ArraySize(CompilerFlagInfos); ++fIx)
{
if (IsCompilerFlagSet(configs[i].flags, CompilerFlagInfos[fIx].mFlag))
{
(*outDebugInfo) += std::string("// ") + CompilerFlagInfos[fIx].mName + "\n";
}
}
(*outDebugInfo) += "// Macros:\n";
if (macros == nullptr)
{
(*outDebugInfo) += "// - : -\n";
}
else
{
for (const D3D_SHADER_MACRO *mIt = macros; mIt->Name != nullptr; ++mIt)
{
(*outDebugInfo) +=
std::string("// ") + mIt->Name + " : " + mIt->Definition + "\n";
}
}
std::string disassembly;
ANGLE_TRY(disassembleBinary(context, binary, &disassembly));
(*outDebugInfo) += "\n" + disassembly + "\n// ASSEMBLY END\n";
#endif // ANGLE_APPEND_ASSEMBLY_TO_SHADER_DEBUG_INFO == ANGLE_ENABLED
return angle::Result::Continue;
}
if (result == E_OUTOFMEMORY)
{
*outCompiledBlob = nullptr;
ANGLE_TRY_HR(context, result, "HLSL compiler had an unexpected failure");
}
infoLog << "Warning: D3D shader compilation failed with " << configs[i].name << " flags. ("
<< profile << ")";
if (i + 1 < configs.size())
{
infoLog << " Retrying with " << configs[i + 1].name;
}
}
// None of the configurations succeeded in compiling this shader but the compiler is still
// intact
*outCompiledBlob = nullptr;
return angle::Result::Continue;
}
angle::Result HLSLCompiler::disassembleBinary(d3d::Context *context,
ID3DBlob *shaderBinary,
std::string *disassemblyOut)
{
ANGLE_TRY(ensureInitialized(context));
// Retrieve disassembly
UINT flags = D3D_DISASM_ENABLE_DEFAULT_VALUE_PRINTS | D3D_DISASM_ENABLE_INSTRUCTION_NUMBERING;
ID3DBlob *disassembly = nullptr;
pD3DDisassemble disassembleFunc = reinterpret_cast<pD3DDisassemble>(mD3DDisassembleFunc);
LPCVOID buffer = shaderBinary->GetBufferPointer();
SIZE_T bufSize = shaderBinary->GetBufferSize();
HRESULT result = disassembleFunc(buffer, bufSize, flags, "", &disassembly);
if (SUCCEEDED(result))
{
*disassemblyOut = std::string(static_cast<const char *>(disassembly->GetBufferPointer()));
}
else
{
*disassemblyOut = "";
}
SafeRelease(disassembly);
return angle::Result::Continue;
}
} // namespace rx
<commit_msg>Disable loop unrolling when encounting errors about invalid array indices.<commit_after>//
// Copyright 2014 The ANGLE Project Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
//
#include "libANGLE/renderer/d3d/HLSLCompiler.h"
#include <sstream>
#include "common/utilities.h"
#include "libANGLE/Context.h"
#include "libANGLE/Program.h"
#include "libANGLE/features.h"
#include "libANGLE/histogram_macros.h"
#include "libANGLE/renderer/d3d/ContextD3D.h"
#include "third_party/trace_event/trace_event.h"
namespace
{
#if ANGLE_APPEND_ASSEMBLY_TO_SHADER_DEBUG_INFO == ANGLE_ENABLED
# ifdef CREATE_COMPILER_FLAG_INFO
# undef CREATE_COMPILER_FLAG_INFO
# endif
# define CREATE_COMPILER_FLAG_INFO(flag) \
{ \
flag, #flag \
}
struct CompilerFlagInfo
{
UINT mFlag;
const char *mName;
};
CompilerFlagInfo CompilerFlagInfos[] = {
// NOTE: The data below is copied from d3dcompiler.h
// If something changes there it should be changed here as well
CREATE_COMPILER_FLAG_INFO(D3DCOMPILE_DEBUG), // (1 << 0)
CREATE_COMPILER_FLAG_INFO(D3DCOMPILE_SKIP_VALIDATION), // (1 << 1)
CREATE_COMPILER_FLAG_INFO(D3DCOMPILE_SKIP_OPTIMIZATION), // (1 << 2)
CREATE_COMPILER_FLAG_INFO(D3DCOMPILE_PACK_MATRIX_ROW_MAJOR), // (1 << 3)
CREATE_COMPILER_FLAG_INFO(D3DCOMPILE_PACK_MATRIX_COLUMN_MAJOR), // (1 << 4)
CREATE_COMPILER_FLAG_INFO(D3DCOMPILE_PARTIAL_PRECISION), // (1 << 5)
CREATE_COMPILER_FLAG_INFO(D3DCOMPILE_FORCE_VS_SOFTWARE_NO_OPT), // (1 << 6)
CREATE_COMPILER_FLAG_INFO(D3DCOMPILE_FORCE_PS_SOFTWARE_NO_OPT), // (1 << 7)
CREATE_COMPILER_FLAG_INFO(D3DCOMPILE_NO_PRESHADER), // (1 << 8)
CREATE_COMPILER_FLAG_INFO(D3DCOMPILE_AVOID_FLOW_CONTROL), // (1 << 9)
CREATE_COMPILER_FLAG_INFO(D3DCOMPILE_PREFER_FLOW_CONTROL), // (1 << 10)
CREATE_COMPILER_FLAG_INFO(D3DCOMPILE_ENABLE_STRICTNESS), // (1 << 11)
CREATE_COMPILER_FLAG_INFO(D3DCOMPILE_ENABLE_BACKWARDS_COMPATIBILITY), // (1 << 12)
CREATE_COMPILER_FLAG_INFO(D3DCOMPILE_IEEE_STRICTNESS), // (1 << 13)
CREATE_COMPILER_FLAG_INFO(D3DCOMPILE_OPTIMIZATION_LEVEL0), // (1 << 14)
CREATE_COMPILER_FLAG_INFO(D3DCOMPILE_OPTIMIZATION_LEVEL1), // 0
CREATE_COMPILER_FLAG_INFO(D3DCOMPILE_OPTIMIZATION_LEVEL2), // ((1 << 14) | (1 << 15))
CREATE_COMPILER_FLAG_INFO(D3DCOMPILE_OPTIMIZATION_LEVEL3), // (1 << 15)
CREATE_COMPILER_FLAG_INFO(D3DCOMPILE_RESERVED16), // (1 << 16)
CREATE_COMPILER_FLAG_INFO(D3DCOMPILE_RESERVED17), // (1 << 17)
CREATE_COMPILER_FLAG_INFO(D3DCOMPILE_WARNINGS_ARE_ERRORS) // (1 << 18)
};
# undef CREATE_COMPILER_FLAG_INFO
bool IsCompilerFlagSet(UINT mask, UINT flag)
{
bool isFlagSet = IsMaskFlagSet(mask, flag);
switch (flag)
{
case D3DCOMPILE_OPTIMIZATION_LEVEL0:
return isFlagSet && !IsMaskFlagSet(mask, UINT(D3DCOMPILE_OPTIMIZATION_LEVEL3));
case D3DCOMPILE_OPTIMIZATION_LEVEL1:
return (mask & D3DCOMPILE_OPTIMIZATION_LEVEL2) == UINT(0);
case D3DCOMPILE_OPTIMIZATION_LEVEL3:
return isFlagSet && !IsMaskFlagSet(mask, UINT(D3DCOMPILE_OPTIMIZATION_LEVEL0));
default:
return isFlagSet;
}
}
#endif // ANGLE_APPEND_ASSEMBLY_TO_SHADER_DEBUG_INFO == ANGLE_ENABLED
constexpr char kOldCompilerLibrary[] = "d3dcompiler_old.dll";
enum D3DCompilerLoadLibraryResult
{
D3DCompilerDefaultLibrarySuccess,
D3DCompilerOldLibrarySuccess,
D3DCompilerFailure,
D3DCompilerEnumBoundary,
};
} // anonymous namespace
namespace rx
{
CompileConfig::CompileConfig() : flags(0), name() {}
CompileConfig::CompileConfig(UINT flags, const std::string &name) : flags(flags), name(name) {}
HLSLCompiler::HLSLCompiler()
: mInitialized(false),
mD3DCompilerModule(nullptr),
mD3DCompileFunc(nullptr),
mD3DDisassembleFunc(nullptr)
{}
HLSLCompiler::~HLSLCompiler()
{
release();
}
angle::Result HLSLCompiler::ensureInitialized(d3d::Context *context)
{
if (mInitialized)
{
return angle::Result::Continue;
}
TRACE_EVENT0("gpu.angle", "HLSLCompiler::initialize");
#if !defined(ANGLE_ENABLE_WINDOWS_STORE)
# if defined(ANGLE_PRELOADED_D3DCOMPILER_MODULE_NAMES)
// Find a D3DCompiler module that had already been loaded based on a predefined list of
// versions.
static const char *d3dCompilerNames[] = ANGLE_PRELOADED_D3DCOMPILER_MODULE_NAMES;
for (size_t i = 0; i < ArraySize(d3dCompilerNames); ++i)
{
if (GetModuleHandleExA(0, d3dCompilerNames[i], &mD3DCompilerModule))
{
break;
}
}
# endif // ANGLE_PRELOADED_D3DCOMPILER_MODULE_NAMES
if (!mD3DCompilerModule)
{
// Load the version of the D3DCompiler DLL associated with the Direct3D version ANGLE was
// built with.
mD3DCompilerModule = LoadLibraryA(D3DCOMPILER_DLL_A);
if (mD3DCompilerModule)
{
ANGLE_HISTOGRAM_ENUMERATION("GPU.ANGLE.D3DCompilerLoadLibraryResult",
D3DCompilerDefaultLibrarySuccess, D3DCompilerEnumBoundary);
}
else
{
WARN() << "Failed to load HLSL compiler library. Using 'old' DLL.";
mD3DCompilerModule = LoadLibraryA(kOldCompilerLibrary);
if (mD3DCompilerModule)
{
ANGLE_HISTOGRAM_ENUMERATION("GPU.ANGLE.D3DCompilerLoadLibraryResult",
D3DCompilerOldLibrarySuccess, D3DCompilerEnumBoundary);
}
}
}
if (!mD3DCompilerModule)
{
DWORD lastError = GetLastError();
ERR() << "D3D Compiler LoadLibrary failed. GetLastError=" << lastError;
ANGLE_HISTOGRAM_ENUMERATION("GPU.ANGLE.D3DCompilerLoadLibraryResult", D3DCompilerFailure,
D3DCompilerEnumBoundary);
ANGLE_TRY_HR(context, E_OUTOFMEMORY, "LoadLibrary failed to load D3D Compiler DLL.");
}
mD3DCompileFunc =
reinterpret_cast<pD3DCompile>(GetProcAddress(mD3DCompilerModule, "D3DCompile"));
ASSERT(mD3DCompileFunc);
mD3DDisassembleFunc =
reinterpret_cast<pD3DDisassemble>(GetProcAddress(mD3DCompilerModule, "D3DDisassemble"));
ASSERT(mD3DDisassembleFunc);
#else
// D3D Shader compiler is linked already into this module, so the export
// can be directly assigned.
mD3DCompilerModule = nullptr;
mD3DCompileFunc = reinterpret_cast<pD3DCompile>(D3DCompile);
mD3DDisassembleFunc = reinterpret_cast<pD3DDisassemble>(D3DDisassemble);
#endif
ANGLE_CHECK_HR(context, mD3DCompileFunc, "Error finding D3DCompile entry point.",
E_OUTOFMEMORY);
mInitialized = true;
return angle::Result::Continue;
}
void HLSLCompiler::release()
{
if (mInitialized)
{
FreeLibrary(mD3DCompilerModule);
mD3DCompilerModule = nullptr;
mD3DCompileFunc = nullptr;
mD3DDisassembleFunc = nullptr;
mInitialized = false;
}
}
angle::Result HLSLCompiler::compileToBinary(d3d::Context *context,
gl::InfoLog &infoLog,
const std::string &hlsl,
const std::string &profile,
const std::vector<CompileConfig> &configs,
const D3D_SHADER_MACRO *overrideMacros,
ID3DBlob **outCompiledBlob,
std::string *outDebugInfo)
{
ASSERT(mInitialized);
#if !defined(ANGLE_ENABLE_WINDOWS_STORE)
ASSERT(mD3DCompilerModule);
#endif
ASSERT(mD3DCompileFunc);
#if !defined(ANGLE_ENABLE_WINDOWS_STORE)
if (gl::DebugAnnotationsActive())
{
std::string sourcePath = getTempPath();
std::ostringstream stream;
stream << "#line 2 \"" << sourcePath << "\"\n\n" << hlsl;
std::string sourceText = stream.str();
writeFile(sourcePath.c_str(), sourceText.c_str(), sourceText.size());
}
#endif
const D3D_SHADER_MACRO *macros = overrideMacros ? overrideMacros : nullptr;
for (size_t i = 0; i < configs.size(); ++i)
{
ID3DBlob *errorMessage = nullptr;
ID3DBlob *binary = nullptr;
HRESULT result = S_OK;
{
TRACE_EVENT0("gpu.angle", "D3DCompile");
SCOPED_ANGLE_HISTOGRAM_TIMER("GPU.ANGLE.D3DCompileMS");
result = mD3DCompileFunc(hlsl.c_str(), hlsl.length(), gl::g_fakepath, macros, nullptr,
"main", profile.c_str(), configs[i].flags, 0, &binary,
&errorMessage);
}
if (errorMessage)
{
std::string message = static_cast<const char *>(errorMessage->GetBufferPointer());
SafeRelease(errorMessage);
infoLog.appendSanitized(message.c_str());
// This produces unbelievable amounts of spam in about:gpu.
// WARN() << std::endl << hlsl;
WARN() << std::endl << message;
if (macros != nullptr)
{
constexpr const char *kLoopRelatedErrors[] = {
// "can't unroll loops marked with loop attribute"
"error X3531:",
// "cannot have gradient operations inside loops with divergent flow control",
// even though it is counter-intuitive to disable unrolling for this error, some
// very long shaders have trouble deciding which loops to unroll and turning off
// forced unrolls allows them to compile properly.
"error X4014:",
// "array index out of bounds", loop unrolling can result in invalid array
// access if the indices become constant, causing loops that may never be
// executed to generate compilation errors
"error X3504:",
};
bool hasLoopRelatedError = false;
for (const char *errorType : kLoopRelatedErrors)
{
if (message.find(errorType) != std::string::npos)
{
hasLoopRelatedError = true;
break;
}
}
if (hasLoopRelatedError)
{
// Disable [loop] and [flatten]
macros = nullptr;
// Retry without changing compiler flags
i--;
continue;
}
}
}
if (SUCCEEDED(result))
{
*outCompiledBlob = binary;
(*outDebugInfo) +=
"// COMPILER INPUT HLSL BEGIN\n\n" + hlsl + "\n// COMPILER INPUT HLSL END\n";
#if ANGLE_APPEND_ASSEMBLY_TO_SHADER_DEBUG_INFO == ANGLE_ENABLED
(*outDebugInfo) += "\n\n// ASSEMBLY BEGIN\n\n";
(*outDebugInfo) += "// Compiler configuration: " + configs[i].name + "\n// Flags:\n";
for (size_t fIx = 0; fIx < ArraySize(CompilerFlagInfos); ++fIx)
{
if (IsCompilerFlagSet(configs[i].flags, CompilerFlagInfos[fIx].mFlag))
{
(*outDebugInfo) += std::string("// ") + CompilerFlagInfos[fIx].mName + "\n";
}
}
(*outDebugInfo) += "// Macros:\n";
if (macros == nullptr)
{
(*outDebugInfo) += "// - : -\n";
}
else
{
for (const D3D_SHADER_MACRO *mIt = macros; mIt->Name != nullptr; ++mIt)
{
(*outDebugInfo) +=
std::string("// ") + mIt->Name + " : " + mIt->Definition + "\n";
}
}
std::string disassembly;
ANGLE_TRY(disassembleBinary(context, binary, &disassembly));
(*outDebugInfo) += "\n" + disassembly + "\n// ASSEMBLY END\n";
#endif // ANGLE_APPEND_ASSEMBLY_TO_SHADER_DEBUG_INFO == ANGLE_ENABLED
return angle::Result::Continue;
}
if (result == E_OUTOFMEMORY)
{
*outCompiledBlob = nullptr;
ANGLE_TRY_HR(context, result, "HLSL compiler had an unexpected failure");
}
infoLog << "Warning: D3D shader compilation failed with " << configs[i].name << " flags. ("
<< profile << ")";
if (i + 1 < configs.size())
{
infoLog << " Retrying with " << configs[i + 1].name;
}
}
// None of the configurations succeeded in compiling this shader but the compiler is still
// intact
*outCompiledBlob = nullptr;
return angle::Result::Continue;
}
angle::Result HLSLCompiler::disassembleBinary(d3d::Context *context,
ID3DBlob *shaderBinary,
std::string *disassemblyOut)
{
ANGLE_TRY(ensureInitialized(context));
// Retrieve disassembly
UINT flags = D3D_DISASM_ENABLE_DEFAULT_VALUE_PRINTS | D3D_DISASM_ENABLE_INSTRUCTION_NUMBERING;
ID3DBlob *disassembly = nullptr;
pD3DDisassemble disassembleFunc = reinterpret_cast<pD3DDisassemble>(mD3DDisassembleFunc);
LPCVOID buffer = shaderBinary->GetBufferPointer();
SIZE_T bufSize = shaderBinary->GetBufferSize();
HRESULT result = disassembleFunc(buffer, bufSize, flags, "", &disassembly);
if (SUCCEEDED(result))
{
*disassemblyOut = std::string(static_cast<const char *>(disassembly->GetBufferPointer()));
}
else
{
*disassemblyOut = "";
}
SafeRelease(disassembly);
return angle::Result::Continue;
}
} // namespace rx
<|endoftext|> |
<commit_before>#include "precompiled.h"
//
// Copyright (c) 2012-2013 The ANGLE Project Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
//
// SwapChain9.cpp: Implements a back-end specific class for the D3D9 swap chain.
#include "libGLESv2/renderer/d3d9/SwapChain9.h"
#include "libGLESv2/renderer/d3d9/renderer9_utils.h"
#include "libGLESv2/renderer/d3d9/Renderer9.h"
namespace rx
{
SwapChain9::SwapChain9(Renderer9 *renderer, HWND window, HANDLE shareHandle,
GLenum backBufferFormat, GLenum depthBufferFormat)
: mRenderer(renderer), SwapChain(window, shareHandle, backBufferFormat, depthBufferFormat)
{
mSwapChain = NULL;
mBackBuffer = NULL;
mDepthStencil = NULL;
mRenderTarget = NULL;
mOffscreenTexture = NULL;
mWidth = -1;
mHeight = -1;
mSwapInterval = -1;
}
SwapChain9::~SwapChain9()
{
release();
}
void SwapChain9::release()
{
if (mSwapChain)
{
mSwapChain->Release();
mSwapChain = NULL;
}
if (mBackBuffer)
{
mBackBuffer->Release();
mBackBuffer = NULL;
}
if (mDepthStencil)
{
mDepthStencil->Release();
mDepthStencil = NULL;
}
if (mRenderTarget)
{
mRenderTarget->Release();
mRenderTarget = NULL;
}
if (mOffscreenTexture)
{
mOffscreenTexture->Release();
mOffscreenTexture = NULL;
}
if (mWindow)
mShareHandle = NULL;
}
static DWORD convertInterval(EGLint interval)
{
#if ANGLE_FORCE_VSYNC_OFF
return D3DPRESENT_INTERVAL_IMMEDIATE;
#else
switch(interval)
{
case 0: return D3DPRESENT_INTERVAL_IMMEDIATE;
case 1: return D3DPRESENT_INTERVAL_ONE;
case 2: return D3DPRESENT_INTERVAL_TWO;
case 3: return D3DPRESENT_INTERVAL_THREE;
case 4: return D3DPRESENT_INTERVAL_FOUR;
default: UNREACHABLE();
}
return D3DPRESENT_INTERVAL_DEFAULT;
#endif
}
EGLint SwapChain9::resize(int backbufferWidth, int backbufferHeight)
{
// D3D9 does not support resizing swap chains without recreating them
return reset(backbufferWidth, backbufferHeight, mSwapInterval);
}
EGLint SwapChain9::reset(int backbufferWidth, int backbufferHeight, EGLint swapInterval)
{
IDirect3DDevice9 *device = mRenderer->getDevice();
if (device == NULL)
{
return EGL_BAD_ACCESS;
}
// Evict all non-render target textures to system memory and release all resources
// before reallocating them to free up as much video memory as possible.
device->EvictManagedResources();
HRESULT result;
// Release specific resources to free up memory for the new render target, while the
// old render target still exists for the purpose of preserving its contents.
if (mSwapChain)
{
mSwapChain->Release();
mSwapChain = NULL;
}
if (mBackBuffer)
{
mBackBuffer->Release();
mBackBuffer = NULL;
}
if (mOffscreenTexture)
{
mOffscreenTexture->Release();
mOffscreenTexture = NULL;
}
if (mDepthStencil)
{
mDepthStencil->Release();
mDepthStencil = NULL;
}
HANDLE *pShareHandle = NULL;
if (!mWindow && mRenderer->getShareHandleSupport())
{
pShareHandle = &mShareHandle;
}
result = device->CreateTexture(backbufferWidth, backbufferHeight, 1, D3DUSAGE_RENDERTARGET,
gl_d3d9::ConvertRenderbufferFormat(mBackBufferFormat), D3DPOOL_DEFAULT,
&mOffscreenTexture, pShareHandle);
if (FAILED(result))
{
ERR("Could not create offscreen texture: %08lX", result);
release();
if (d3d9::isDeviceLostError(result))
{
return EGL_CONTEXT_LOST;
}
else
{
return EGL_BAD_ALLOC;
}
}
IDirect3DSurface9 *oldRenderTarget = mRenderTarget;
result = mOffscreenTexture->GetSurfaceLevel(0, &mRenderTarget);
ASSERT(SUCCEEDED(result));
if (oldRenderTarget)
{
RECT rect =
{
0, 0,
mWidth, mHeight
};
if (rect.right > static_cast<LONG>(backbufferWidth))
{
rect.right = backbufferWidth;
}
if (rect.bottom > static_cast<LONG>(backbufferHeight))
{
rect.bottom = backbufferHeight;
}
mRenderer->endScene();
result = device->StretchRect(oldRenderTarget, &rect, mRenderTarget, &rect, D3DTEXF_NONE);
ASSERT(SUCCEEDED(result));
oldRenderTarget->Release();
}
if (mWindow)
{
D3DPRESENT_PARAMETERS presentParameters = {0};
presentParameters.AutoDepthStencilFormat = gl_d3d9::ConvertRenderbufferFormat(mDepthBufferFormat);
presentParameters.BackBufferCount = 1;
presentParameters.BackBufferFormat = gl_d3d9::ConvertRenderbufferFormat(mBackBufferFormat);
presentParameters.EnableAutoDepthStencil = FALSE;
presentParameters.Flags = 0;
presentParameters.hDeviceWindow = mWindow;
presentParameters.MultiSampleQuality = 0; // FIXME: Unimplemented
presentParameters.MultiSampleType = D3DMULTISAMPLE_NONE; // FIXME: Unimplemented
presentParameters.PresentationInterval = convertInterval(swapInterval);
presentParameters.SwapEffect = D3DSWAPEFFECT_DISCARD;
presentParameters.Windowed = TRUE;
presentParameters.BackBufferWidth = backbufferWidth;
presentParameters.BackBufferHeight = backbufferHeight;
// http://crbug.com/140239
// http://crbug.com/143434
//
// Some AMD/Intel switchable systems / drivers appear to round swap chain surfaces to a multiple of 64 pixels in width
// when using the integrated Intel. This rounds the width up rather than down.
//
// Some non-switchable AMD GPUs / drivers do not respect the source rectangle to Present. Therefore, when the vendor ID
// is not Intel, the back buffer width must be exactly the same width as the window or horizontal scaling will occur.
if (mRenderer->getAdapterVendor() == VENDOR_ID_INTEL)
{
presentParameters.BackBufferWidth = (presentParameters.BackBufferWidth + 63) / 64 * 64;
}
result = device->CreateAdditionalSwapChain(&presentParameters, &mSwapChain);
if (FAILED(result))
{
ASSERT(result == D3DERR_OUTOFVIDEOMEMORY || result == E_OUTOFMEMORY || result == D3DERR_INVALIDCALL || result == D3DERR_DEVICELOST);
ERR("Could not create additional swap chains or offscreen surfaces: %08lX", result);
release();
if (d3d9::isDeviceLostError(result))
{
return EGL_CONTEXT_LOST;
}
else
{
return EGL_BAD_ALLOC;
}
}
result = mSwapChain->GetBackBuffer(0, D3DBACKBUFFER_TYPE_MONO, &mBackBuffer);
ASSERT(SUCCEEDED(result));
InvalidateRect(mWindow, NULL, FALSE);
}
if (mDepthBufferFormat != GL_NONE)
{
result = device->CreateDepthStencilSurface(backbufferWidth, backbufferHeight,
gl_d3d9::ConvertRenderbufferFormat(mDepthBufferFormat),
D3DMULTISAMPLE_NONE, 0, FALSE, &mDepthStencil, NULL);
if (FAILED(result))
{
ASSERT(result == D3DERR_OUTOFVIDEOMEMORY || result == E_OUTOFMEMORY || result == D3DERR_INVALIDCALL);
ERR("Could not create depthstencil surface for new swap chain: 0x%08X", result);
release();
if (d3d9::isDeviceLostError(result))
{
return EGL_CONTEXT_LOST;
}
else
{
return EGL_BAD_ALLOC;
}
}
}
mWidth = backbufferWidth;
mHeight = backbufferHeight;
mSwapInterval = swapInterval;
return EGL_SUCCESS;
}
// parameters should be validated/clamped by caller
EGLint SwapChain9::swapRect(EGLint x, EGLint y, EGLint width, EGLint height)
{
if (!mSwapChain)
{
return EGL_SUCCESS;
}
IDirect3DDevice9 *device = mRenderer->getDevice();
// Disable all pipeline operations
device->SetRenderState(D3DRS_ZENABLE, D3DZB_FALSE);
device->SetRenderState(D3DRS_FILLMODE, D3DFILL_SOLID);
device->SetRenderState(D3DRS_ALPHATESTENABLE, FALSE);
device->SetRenderState(D3DRS_ALPHABLENDENABLE, FALSE);
device->SetRenderState(D3DRS_CULLMODE, D3DCULL_NONE);
device->SetRenderState(D3DRS_STENCILENABLE, FALSE);
device->SetRenderState(D3DRS_CLIPPLANEENABLE, 0);
device->SetRenderState(D3DRS_COLORWRITEENABLE, D3DCOLORWRITEENABLE_ALPHA | D3DCOLORWRITEENABLE_BLUE | D3DCOLORWRITEENABLE_GREEN | D3DCOLORWRITEENABLE_RED);
device->SetRenderState(D3DRS_SRGBWRITEENABLE, FALSE);
device->SetRenderState(D3DRS_SCISSORTESTENABLE, FALSE);
device->SetPixelShader(NULL);
device->SetVertexShader(NULL);
device->SetRenderTarget(0, mBackBuffer);
device->SetDepthStencilSurface(NULL);
device->SetTexture(0, mOffscreenTexture);
device->SetTextureStageState(0, D3DTSS_COLOROP, D3DTOP_SELECTARG1);
device->SetTextureStageState(0, D3DTSS_COLORARG1, D3DTA_TEXTURE);
device->SetTextureStageState(1, D3DTSS_COLOROP, D3DTOP_DISABLE);
device->SetSamplerState(0, D3DSAMP_MAGFILTER, D3DTEXF_POINT);
device->SetSamplerState(0, D3DSAMP_MINFILTER, D3DTEXF_POINT);
device->SetSamplerState(0, D3DSAMP_ADDRESSU, D3DTADDRESS_CLAMP);
device->SetSamplerState(0, D3DSAMP_ADDRESSV, D3DTADDRESS_CLAMP);
device->SetFVF(D3DFVF_XYZRHW | D3DFVF_TEX1);
for (UINT streamIndex = 0; streamIndex < gl::MAX_VERTEX_ATTRIBS; streamIndex++)
{
device->SetStreamSourceFreq(streamIndex, 1);
}
D3DVIEWPORT9 viewport = {0, 0, mWidth, mHeight, 0.0f, 1.0f};
device->SetViewport(&viewport);
float x1 = x - 0.5f;
float y1 = (mHeight - y - height) - 0.5f;
float x2 = (x + width) - 0.5f;
float y2 = (mHeight - y) - 0.5f;
float u1 = x / float(mWidth);
float v1 = y / float(mHeight);
float u2 = (x + width) / float(mWidth);
float v2 = (y + height) / float(mHeight);
float quad[4][6] = {{x1, y1, 0.0f, 1.0f, u1, v2},
{x2, y1, 0.0f, 1.0f, u2, v2},
{x2, y2, 0.0f, 1.0f, u2, v1},
{x1, y2, 0.0f, 1.0f, u1, v1}}; // x, y, z, rhw, u, v
mRenderer->startScene();
device->DrawPrimitiveUP(D3DPT_TRIANGLEFAN, 2, quad, 6 * sizeof(float));
mRenderer->endScene();
device->SetTexture(0, NULL);
RECT rect =
{
x, mHeight - y - height,
x + width, mHeight - y
};
HRESULT result = mSwapChain->Present(&rect, &rect, NULL, NULL, 0);
mRenderer->markAllStateDirty();
if (result == D3DERR_OUTOFVIDEOMEMORY || result == E_OUTOFMEMORY || result == D3DERR_DRIVERINTERNALERROR)
{
return EGL_BAD_ALLOC;
}
// http://crbug.com/313210
// If our swap failed, trigger a device lost event. Resetting will work around an AMD-specific
// device removed bug with lost contexts when reinstalling drivers.
if (FAILED(result))
{
mRenderer->notifyDeviceLost();
return EGL_CONTEXT_LOST;
}
return EGL_SUCCESS;
}
// Increments refcount on surface.
// caller must Release() the returned surface
IDirect3DSurface9 *SwapChain9::getRenderTarget()
{
if (mRenderTarget)
{
mRenderTarget->AddRef();
}
return mRenderTarget;
}
// Increments refcount on surface.
// caller must Release() the returned surface
IDirect3DSurface9 *SwapChain9::getDepthStencil()
{
if (mDepthStencil)
{
mDepthStencil->AddRef();
}
return mDepthStencil;
}
// Increments refcount on texture.
// caller must Release() the returned texture
IDirect3DTexture9 *SwapChain9::getOffscreenTexture()
{
if (mOffscreenTexture)
{
mOffscreenTexture->AddRef();
}
return mOffscreenTexture;
}
SwapChain9 *SwapChain9::makeSwapChain9(SwapChain *swapChain)
{
ASSERT(HAS_DYNAMIC_TYPE(rx::SwapChain9*, swapChain));
return static_cast<rx::SwapChain9*>(swapChain);
}
void SwapChain9::recreate()
{
if (!mSwapChain)
{
return;
}
IDirect3DDevice9 *device = mRenderer->getDevice();
if (device == NULL)
{
return;
}
D3DPRESENT_PARAMETERS presentParameters;
HRESULT result = mSwapChain->GetPresentParameters(&presentParameters);
ASSERT(SUCCEEDED(result));
IDirect3DSwapChain9* newSwapChain = NULL;
result = device->CreateAdditionalSwapChain(&presentParameters, &newSwapChain);
if (FAILED(result))
{
return;
}
mSwapChain->Release();
mSwapChain = newSwapChain;
mBackBuffer->Release();
result = mSwapChain->GetBackBuffer(0, D3DBACKBUFFER_TYPE_MONO, &mBackBuffer);
ASSERT(SUCCEEDED(result));
}
}
<commit_msg>Handle an unknown error when exiting fullscreen on Windows 8.<commit_after>#include "precompiled.h"
//
// Copyright (c) 2012-2013 The ANGLE Project Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
//
// SwapChain9.cpp: Implements a back-end specific class for the D3D9 swap chain.
#include "libGLESv2/renderer/d3d9/SwapChain9.h"
#include "libGLESv2/renderer/d3d9/renderer9_utils.h"
#include "libGLESv2/renderer/d3d9/Renderer9.h"
namespace rx
{
SwapChain9::SwapChain9(Renderer9 *renderer, HWND window, HANDLE shareHandle,
GLenum backBufferFormat, GLenum depthBufferFormat)
: mRenderer(renderer), SwapChain(window, shareHandle, backBufferFormat, depthBufferFormat)
{
mSwapChain = NULL;
mBackBuffer = NULL;
mDepthStencil = NULL;
mRenderTarget = NULL;
mOffscreenTexture = NULL;
mWidth = -1;
mHeight = -1;
mSwapInterval = -1;
}
SwapChain9::~SwapChain9()
{
release();
}
void SwapChain9::release()
{
if (mSwapChain)
{
mSwapChain->Release();
mSwapChain = NULL;
}
if (mBackBuffer)
{
mBackBuffer->Release();
mBackBuffer = NULL;
}
if (mDepthStencil)
{
mDepthStencil->Release();
mDepthStencil = NULL;
}
if (mRenderTarget)
{
mRenderTarget->Release();
mRenderTarget = NULL;
}
if (mOffscreenTexture)
{
mOffscreenTexture->Release();
mOffscreenTexture = NULL;
}
if (mWindow)
mShareHandle = NULL;
}
static DWORD convertInterval(EGLint interval)
{
#if ANGLE_FORCE_VSYNC_OFF
return D3DPRESENT_INTERVAL_IMMEDIATE;
#else
switch(interval)
{
case 0: return D3DPRESENT_INTERVAL_IMMEDIATE;
case 1: return D3DPRESENT_INTERVAL_ONE;
case 2: return D3DPRESENT_INTERVAL_TWO;
case 3: return D3DPRESENT_INTERVAL_THREE;
case 4: return D3DPRESENT_INTERVAL_FOUR;
default: UNREACHABLE();
}
return D3DPRESENT_INTERVAL_DEFAULT;
#endif
}
EGLint SwapChain9::resize(int backbufferWidth, int backbufferHeight)
{
// D3D9 does not support resizing swap chains without recreating them
return reset(backbufferWidth, backbufferHeight, mSwapInterval);
}
EGLint SwapChain9::reset(int backbufferWidth, int backbufferHeight, EGLint swapInterval)
{
IDirect3DDevice9 *device = mRenderer->getDevice();
if (device == NULL)
{
return EGL_BAD_ACCESS;
}
// Evict all non-render target textures to system memory and release all resources
// before reallocating them to free up as much video memory as possible.
device->EvictManagedResources();
HRESULT result;
// Release specific resources to free up memory for the new render target, while the
// old render target still exists for the purpose of preserving its contents.
if (mSwapChain)
{
mSwapChain->Release();
mSwapChain = NULL;
}
if (mBackBuffer)
{
mBackBuffer->Release();
mBackBuffer = NULL;
}
if (mOffscreenTexture)
{
mOffscreenTexture->Release();
mOffscreenTexture = NULL;
}
if (mDepthStencil)
{
mDepthStencil->Release();
mDepthStencil = NULL;
}
HANDLE *pShareHandle = NULL;
if (!mWindow && mRenderer->getShareHandleSupport())
{
pShareHandle = &mShareHandle;
}
result = device->CreateTexture(backbufferWidth, backbufferHeight, 1, D3DUSAGE_RENDERTARGET,
gl_d3d9::ConvertRenderbufferFormat(mBackBufferFormat), D3DPOOL_DEFAULT,
&mOffscreenTexture, pShareHandle);
if (FAILED(result))
{
ERR("Could not create offscreen texture: %08lX", result);
release();
if (d3d9::isDeviceLostError(result))
{
return EGL_CONTEXT_LOST;
}
else
{
return EGL_BAD_ALLOC;
}
}
IDirect3DSurface9 *oldRenderTarget = mRenderTarget;
result = mOffscreenTexture->GetSurfaceLevel(0, &mRenderTarget);
ASSERT(SUCCEEDED(result));
if (oldRenderTarget)
{
RECT rect =
{
0, 0,
mWidth, mHeight
};
if (rect.right > static_cast<LONG>(backbufferWidth))
{
rect.right = backbufferWidth;
}
if (rect.bottom > static_cast<LONG>(backbufferHeight))
{
rect.bottom = backbufferHeight;
}
mRenderer->endScene();
result = device->StretchRect(oldRenderTarget, &rect, mRenderTarget, &rect, D3DTEXF_NONE);
ASSERT(SUCCEEDED(result));
oldRenderTarget->Release();
}
if (mWindow)
{
D3DPRESENT_PARAMETERS presentParameters = {0};
presentParameters.AutoDepthStencilFormat = gl_d3d9::ConvertRenderbufferFormat(mDepthBufferFormat);
presentParameters.BackBufferCount = 1;
presentParameters.BackBufferFormat = gl_d3d9::ConvertRenderbufferFormat(mBackBufferFormat);
presentParameters.EnableAutoDepthStencil = FALSE;
presentParameters.Flags = 0;
presentParameters.hDeviceWindow = mWindow;
presentParameters.MultiSampleQuality = 0; // FIXME: Unimplemented
presentParameters.MultiSampleType = D3DMULTISAMPLE_NONE; // FIXME: Unimplemented
presentParameters.PresentationInterval = convertInterval(swapInterval);
presentParameters.SwapEffect = D3DSWAPEFFECT_DISCARD;
presentParameters.Windowed = TRUE;
presentParameters.BackBufferWidth = backbufferWidth;
presentParameters.BackBufferHeight = backbufferHeight;
// http://crbug.com/140239
// http://crbug.com/143434
//
// Some AMD/Intel switchable systems / drivers appear to round swap chain surfaces to a multiple of 64 pixels in width
// when using the integrated Intel. This rounds the width up rather than down.
//
// Some non-switchable AMD GPUs / drivers do not respect the source rectangle to Present. Therefore, when the vendor ID
// is not Intel, the back buffer width must be exactly the same width as the window or horizontal scaling will occur.
if (mRenderer->getAdapterVendor() == VENDOR_ID_INTEL)
{
presentParameters.BackBufferWidth = (presentParameters.BackBufferWidth + 63) / 64 * 64;
}
result = device->CreateAdditionalSwapChain(&presentParameters, &mSwapChain);
if (FAILED(result))
{
ASSERT(result == D3DERR_OUTOFVIDEOMEMORY || result == E_OUTOFMEMORY || result == D3DERR_INVALIDCALL || result == D3DERR_DEVICELOST);
ERR("Could not create additional swap chains or offscreen surfaces: %08lX", result);
release();
if (d3d9::isDeviceLostError(result))
{
return EGL_CONTEXT_LOST;
}
else
{
return EGL_BAD_ALLOC;
}
}
result = mSwapChain->GetBackBuffer(0, D3DBACKBUFFER_TYPE_MONO, &mBackBuffer);
ASSERT(SUCCEEDED(result));
InvalidateRect(mWindow, NULL, FALSE);
}
if (mDepthBufferFormat != GL_NONE)
{
result = device->CreateDepthStencilSurface(backbufferWidth, backbufferHeight,
gl_d3d9::ConvertRenderbufferFormat(mDepthBufferFormat),
D3DMULTISAMPLE_NONE, 0, FALSE, &mDepthStencil, NULL);
if (FAILED(result))
{
ASSERT(result == D3DERR_OUTOFVIDEOMEMORY || result == E_OUTOFMEMORY || result == D3DERR_INVALIDCALL);
ERR("Could not create depthstencil surface for new swap chain: 0x%08X", result);
release();
if (d3d9::isDeviceLostError(result))
{
return EGL_CONTEXT_LOST;
}
else
{
return EGL_BAD_ALLOC;
}
}
}
mWidth = backbufferWidth;
mHeight = backbufferHeight;
mSwapInterval = swapInterval;
return EGL_SUCCESS;
}
// parameters should be validated/clamped by caller
EGLint SwapChain9::swapRect(EGLint x, EGLint y, EGLint width, EGLint height)
{
if (!mSwapChain)
{
return EGL_SUCCESS;
}
IDirect3DDevice9 *device = mRenderer->getDevice();
// Disable all pipeline operations
device->SetRenderState(D3DRS_ZENABLE, D3DZB_FALSE);
device->SetRenderState(D3DRS_FILLMODE, D3DFILL_SOLID);
device->SetRenderState(D3DRS_ALPHATESTENABLE, FALSE);
device->SetRenderState(D3DRS_ALPHABLENDENABLE, FALSE);
device->SetRenderState(D3DRS_CULLMODE, D3DCULL_NONE);
device->SetRenderState(D3DRS_STENCILENABLE, FALSE);
device->SetRenderState(D3DRS_CLIPPLANEENABLE, 0);
device->SetRenderState(D3DRS_COLORWRITEENABLE, D3DCOLORWRITEENABLE_ALPHA | D3DCOLORWRITEENABLE_BLUE | D3DCOLORWRITEENABLE_GREEN | D3DCOLORWRITEENABLE_RED);
device->SetRenderState(D3DRS_SRGBWRITEENABLE, FALSE);
device->SetRenderState(D3DRS_SCISSORTESTENABLE, FALSE);
device->SetPixelShader(NULL);
device->SetVertexShader(NULL);
device->SetRenderTarget(0, mBackBuffer);
device->SetDepthStencilSurface(NULL);
device->SetTexture(0, mOffscreenTexture);
device->SetTextureStageState(0, D3DTSS_COLOROP, D3DTOP_SELECTARG1);
device->SetTextureStageState(0, D3DTSS_COLORARG1, D3DTA_TEXTURE);
device->SetTextureStageState(1, D3DTSS_COLOROP, D3DTOP_DISABLE);
device->SetSamplerState(0, D3DSAMP_MAGFILTER, D3DTEXF_POINT);
device->SetSamplerState(0, D3DSAMP_MINFILTER, D3DTEXF_POINT);
device->SetSamplerState(0, D3DSAMP_ADDRESSU, D3DTADDRESS_CLAMP);
device->SetSamplerState(0, D3DSAMP_ADDRESSV, D3DTADDRESS_CLAMP);
device->SetFVF(D3DFVF_XYZRHW | D3DFVF_TEX1);
for (UINT streamIndex = 0; streamIndex < gl::MAX_VERTEX_ATTRIBS; streamIndex++)
{
device->SetStreamSourceFreq(streamIndex, 1);
}
D3DVIEWPORT9 viewport = {0, 0, mWidth, mHeight, 0.0f, 1.0f};
device->SetViewport(&viewport);
float x1 = x - 0.5f;
float y1 = (mHeight - y - height) - 0.5f;
float x2 = (x + width) - 0.5f;
float y2 = (mHeight - y) - 0.5f;
float u1 = x / float(mWidth);
float v1 = y / float(mHeight);
float u2 = (x + width) / float(mWidth);
float v2 = (y + height) / float(mHeight);
float quad[4][6] = {{x1, y1, 0.0f, 1.0f, u1, v2},
{x2, y1, 0.0f, 1.0f, u2, v2},
{x2, y2, 0.0f, 1.0f, u2, v1},
{x1, y2, 0.0f, 1.0f, u1, v1}}; // x, y, z, rhw, u, v
mRenderer->startScene();
device->DrawPrimitiveUP(D3DPT_TRIANGLEFAN, 2, quad, 6 * sizeof(float));
mRenderer->endScene();
device->SetTexture(0, NULL);
RECT rect =
{
x, mHeight - y - height,
x + width, mHeight - y
};
HRESULT result = mSwapChain->Present(&rect, &rect, NULL, NULL, 0);
mRenderer->markAllStateDirty();
if (result == D3DERR_OUTOFVIDEOMEMORY || result == E_OUTOFMEMORY || result == D3DERR_DRIVERINTERNALERROR)
{
return EGL_BAD_ALLOC;
}
// On Windows 8 systems, IDirect3DSwapChain9::Present sometimes returns 0x88760873 when the windows is
// in the process of entering/exiting fullscreen. This code doesn't seem to have any documentation. The
// device appears to be ok after emitting this error so simply return a failure to swap.
if (result == 0x88760873)
{
return EGL_BAD_NATIVE_WINDOW;
}
// http://crbug.com/313210
// If our swap failed, trigger a device lost event. Resetting will work around an AMD-specific
// device removed bug with lost contexts when reinstalling drivers.
if (FAILED(result))
{
mRenderer->notifyDeviceLost();
return EGL_CONTEXT_LOST;
}
return EGL_SUCCESS;
}
// Increments refcount on surface.
// caller must Release() the returned surface
IDirect3DSurface9 *SwapChain9::getRenderTarget()
{
if (mRenderTarget)
{
mRenderTarget->AddRef();
}
return mRenderTarget;
}
// Increments refcount on surface.
// caller must Release() the returned surface
IDirect3DSurface9 *SwapChain9::getDepthStencil()
{
if (mDepthStencil)
{
mDepthStencil->AddRef();
}
return mDepthStencil;
}
// Increments refcount on texture.
// caller must Release() the returned texture
IDirect3DTexture9 *SwapChain9::getOffscreenTexture()
{
if (mOffscreenTexture)
{
mOffscreenTexture->AddRef();
}
return mOffscreenTexture;
}
SwapChain9 *SwapChain9::makeSwapChain9(SwapChain *swapChain)
{
ASSERT(HAS_DYNAMIC_TYPE(rx::SwapChain9*, swapChain));
return static_cast<rx::SwapChain9*>(swapChain);
}
void SwapChain9::recreate()
{
if (!mSwapChain)
{
return;
}
IDirect3DDevice9 *device = mRenderer->getDevice();
if (device == NULL)
{
return;
}
D3DPRESENT_PARAMETERS presentParameters;
HRESULT result = mSwapChain->GetPresentParameters(&presentParameters);
ASSERT(SUCCEEDED(result));
IDirect3DSwapChain9* newSwapChain = NULL;
result = device->CreateAdditionalSwapChain(&presentParameters, &newSwapChain);
if (FAILED(result))
{
return;
}
mSwapChain->Release();
mSwapChain = newSwapChain;
mBackBuffer->Release();
result = mSwapChain->GetBackBuffer(0, D3DBACKBUFFER_TYPE_MONO, &mBackBuffer);
ASSERT(SUCCEEDED(result));
}
}
<|endoftext|> |
<commit_before>/*
* Copyright 2009-2011 The VOTCA Development Team (http://www.votca.org)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
#include <iostream>
#include <fstream>
#include <boost/lexical_cast.hpp>
#include <votca/tools/getline.h>
#include "grotopologyreader.h"
namespace votca { namespace csg {
bool GROTopologyReader::ReadTopology(string file, Topology &top)
{
// cleanup topology to store new data
ifstream fl;
string tmp;
top.Cleanup();
fl.open(file.c_str());
if(!fl.is_open())
return false;
string title;
getline(fl, title);
getline(fl, tmp);
int natoms = atoi(tmp.c_str());
for(;natoms>0; natoms--) {
char c[6];
fl.read(c, 5);
c[5] = 0;
string resname;
fl >> resname;
int resnr = atoi(c);
if(resnr >= top.ResidueCount()) {
if (top.ResidueCount()==0) //gro resnr start with 1 but VOTCA starts with 0
top.CreateResidue("ZERO"); // create 0 res, to allow to keep gro numbering
top.CreateResidue(resname);
//cout << " created residue " << c << " " << resnr << " " << resname<<"-\n";
}
string atomname;
string x, y, z;
fl >> atomname;
fl >> tmp;
fl >> x; fl >> y; fl >> z;
//BeadType=atomname is not correct, but still better than no type at all!
top.CreateBead(1, atomname, top.GetOrCreateBeadType(atomname), resnr, 1., 0.);
getline(fl, tmp);
}
getline(fl, tmp); //read box line
if(fl.eof())
throw std::runtime_error("unexpected end of file in poly file, when boxline");
Tokenizer tok(tmp, " ");
vector<double> fields;
tok.ConvertToVector<double>(fields);
matrix box;
if ( fields.size() == 3 ) {
box.ZeroMatrix();
for (int i=0;i<3;i++) box[i][i] = fields[i];
} else if ( fields.size() == 9 ) {
box[0][0]= fields[0];
box[1][1]= fields[1];
box[2][2]= fields[2];
box[0][1]= fields[3];
box[0][2]= fields[4];
box[1][1]= fields[5];
box[1][2]= fields[6];
box[2][1]= fields[7];
box[2][2]= fields[8];
} else {
throw std::runtime_error("Error while reading box (last) line of"+ file);
}
top.setBox(box);
fl.close();
cout << "WARNING: topology created from .gro file, masses and charges are wrong!\n";
return true;
}
}}
<commit_msg>grotopologyreader: fail if file cannot be opened<commit_after>/*
* Copyright 2009-2011 The VOTCA Development Team (http://www.votca.org)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
#include <iostream>
#include <fstream>
#include <boost/lexical_cast.hpp>
#include <votca/tools/getline.h>
#include "grotopologyreader.h"
namespace votca { namespace csg {
bool GROTopologyReader::ReadTopology(string file, Topology &top)
{
// cleanup topology to store new data
ifstream fl;
string tmp;
top.Cleanup();
fl.open(file.c_str());
if(!fl.is_open())
throw std::runtime_error("Could not open file: " + file);
string title;
getline(fl, title);
getline(fl, tmp);
int natoms = atoi(tmp.c_str());
for(;natoms>0; natoms--) {
char c[6];
fl.read(c, 5);
c[5] = 0;
string resname;
fl >> resname;
int resnr = atoi(c);
if(resnr >= top.ResidueCount()) {
if (top.ResidueCount()==0) //gro resnr start with 1 but VOTCA starts with 0
top.CreateResidue("ZERO"); // create 0 res, to allow to keep gro numbering
top.CreateResidue(resname);
//cout << " created residue " << c << " " << resnr << " " << resname<<"-\n";
}
string atomname;
string x, y, z;
fl >> atomname;
fl >> tmp;
fl >> x; fl >> y; fl >> z;
//BeadType=atomname is not correct, but still better than no type at all!
top.CreateBead(1, atomname, top.GetOrCreateBeadType(atomname), resnr, 1., 0.);
getline(fl, tmp);
}
getline(fl, tmp); //read box line
if(fl.eof())
throw std::runtime_error("unexpected end of file in poly file, when boxline");
Tokenizer tok(tmp, " ");
vector<double> fields;
tok.ConvertToVector<double>(fields);
matrix box;
if ( fields.size() == 3 ) {
box.ZeroMatrix();
for (int i=0;i<3;i++) box[i][i] = fields[i];
} else if ( fields.size() == 9 ) {
box[0][0]= fields[0];
box[1][1]= fields[1];
box[2][2]= fields[2];
box[0][1]= fields[3];
box[0][2]= fields[4];
box[1][1]= fields[5];
box[1][2]= fields[6];
box[2][1]= fields[7];
box[2][2]= fields[8];
} else {
throw std::runtime_error("Error while reading box (last) line of"+ file);
}
top.setBox(box);
fl.close();
cout << "WARNING: topology created from .gro file, masses and charges are wrong!\n";
return true;
}
}}
<|endoftext|> |
<commit_before>/*
* Copyright 2009-2011 The VOTCA Development Team (http://www.votca.org)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
#ifndef HAVE_NO_CONFIG
#include <votca_config.h>
#endif
#include <iostream>
#include "pdbtopologyreader.h"
#if GMX == 50
#include <gromacs/legacyheaders/statutil.h>
#include <gromacs/legacyheaders/typedefs.h>
#include <gromacs/legacyheaders/smalloc.h>
#include <gromacs/legacyheaders/confio.h>
#include <gromacs/legacyheaders/vec.h>
#include <gromacs/legacyheaders/copyrite.h>
#include <gromacs/legacyheaders/statutil.h>
#include <gromacs/legacyheaders/tpxio.h>
#elif GMX == 45
#include <gromacs/statutil.h>
#include <gromacs/typedefs.h>
#include <gromacs/smalloc.h>
#include <gromacs/confio.h>
#include <gromacs/vec.h>
#include <gromacs/copyrite.h>
#include <gromacs/statutil.h>
#include <gromacs/tpxio.h>
#elif GMX == 40
extern "C" {
#include <statutil.h>
#include <typedefs.h>
#include <smalloc.h>
#include <confio.h>
#include <vec.h>
#include <copyrite.h>
#include <statutil.h>
#include <tpxio.h>
}
#else
#error Unsupported GMX version
#endif
// this one is needed because of bool is defined in one of the headers included by gmx
#undef bool
#define snew2(ptr,nelem) (ptr)=(rvec*)save_calloc(#ptr,__FILE__,__LINE__,\
(nelem),sizeof(*(ptr)))
namespace votca { namespace csg {
bool PDBTopologyReader::ReadTopology(string file, Topology &top)
{
char title[512];
rvec *x, *v;
::matrix box;
int ePBC;
t_atoms atoms;
set_program_name("VOTCA");
//snew(atoms,1);
get_stx_coordnum((char*)file.c_str(),&(atoms.nr));
init_t_atoms(&atoms,atoms.nr,TRUE);
snew2(x,atoms.nr);
snew2(v,atoms.nr);
fprintf(stderr,"\nReading structure file\n");
read_stx_conf((char*)file.c_str(), title,&atoms,
x,NULL,&ePBC,box);
for(int i=0; i < atoms.nres; i++) {
#if GMX == 50
top.CreateResidue(*(atoms.resinfo[i].name));
#elif GMX == 45
top.CreateResidue(*(atoms.resinfo[i].name));
#elif GMX == 40
top.CreateResidue(*(atoms.resname[i]));
#else
#error Unsupported GMX version
#endif
}
// read the atoms
for(int i=0; i < atoms.nr; i++) {
t_atom *a;
a = &(atoms.atom[i]);
string name=string(atoms.pdbinfo[i].atomnm);
boost::trim(name);
BeadType *type = top.GetOrCreateBeadType(name);
top.CreateBead(1, *(atoms.atomname[i]), type, a->resind, a->m, a->q);
//cout << *(gtp.atoms.atomname[i]) << " residue: " << a->resnr << endl;
}
return true;
}
}}
<commit_msg>pdbtopologyreader: make name the type for now, gmx40 support<commit_after>/*
* Copyright 2009-2011 The VOTCA Development Team (http://www.votca.org)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
#ifndef HAVE_NO_CONFIG
#include <votca_config.h>
#endif
#include <iostream>
#include "pdbtopologyreader.h"
#if GMX == 50
#include <gromacs/legacyheaders/statutil.h>
#include <gromacs/legacyheaders/typedefs.h>
#include <gromacs/legacyheaders/smalloc.h>
#include <gromacs/legacyheaders/confio.h>
#include <gromacs/legacyheaders/vec.h>
#include <gromacs/legacyheaders/copyrite.h>
#include <gromacs/legacyheaders/statutil.h>
#include <gromacs/legacyheaders/tpxio.h>
#elif GMX == 45
#include <gromacs/statutil.h>
#include <gromacs/typedefs.h>
#include <gromacs/smalloc.h>
#include <gromacs/confio.h>
#include <gromacs/vec.h>
#include <gromacs/copyrite.h>
#include <gromacs/statutil.h>
#include <gromacs/tpxio.h>
#elif GMX == 40
extern "C" {
#include <statutil.h>
#include <typedefs.h>
#include <smalloc.h>
#include <confio.h>
#include <vec.h>
#include <copyrite.h>
#include <statutil.h>
#include <tpxio.h>
}
#else
#error Unsupported GMX version
#endif
// this one is needed because of bool is defined in one of the headers included by gmx
#undef bool
#define snew2(ptr,nelem) (ptr)=(rvec*)save_calloc(#ptr,__FILE__,__LINE__,\
(nelem),sizeof(*(ptr)))
namespace votca { namespace csg {
bool PDBTopologyReader::ReadTopology(string file, Topology &top)
{
char title[512];
rvec *x, *v;
::matrix box;
int ePBC;
t_atoms atoms;
set_program_name("VOTCA");
//snew(atoms,1);
get_stx_coordnum((char*)file.c_str(),&(atoms.nr));
init_t_atoms(&atoms,atoms.nr,TRUE);
snew2(x,atoms.nr);
snew2(v,atoms.nr);
fprintf(stderr,"\nReading structure file\n");
read_stx_conf((char*)file.c_str(), title,&atoms,
x,NULL,&ePBC,box);
for(int i=0; i < atoms.nres; i++) {
#if GMX == 50
top.CreateResidue(*(atoms.resinfo[i].name));
#elif GMX == 45
top.CreateResidue(*(atoms.resinfo[i].name));
#elif GMX == 40
top.CreateResidue(*(atoms.resname[i]));
#else
#error Unsupported GMX version
#endif
}
// read the atoms
for(int i=0; i < atoms.nr; i++) {
t_atom *a;
a = &(atoms.atom[i]);
//this is not correct, but still better than no type at all!
BeadType *type = top.GetOrCreateBeadType(*(atoms.atomname[i]));
#if GMX == 50
top.CreateBead(1, *(atoms.atomname[i]), type, a->resind, a->m, a->q);
#elif GMX == 45
top.CreateBead(1, *(atoms.atomname[i]), type, a->resind, a->m, a->q);
#elif GMX == 40
top.CreateBead(1, *(atoms.atomname[i]), type, a->resnr, a->m, a->q);
#else
#error Unsupported GMX version
#endif
//cout << *(gtp.atoms.atomname[i]) << " residue: " << a->resnr << endl;
}
return true;
}
}}
<|endoftext|> |
<commit_before>#pragma once
#ifndef ARRAYDELEGATE_HPP
# define ARRAYDELEGATE_HPP
#include <cassert>
#include <cstddef>
#include <memory>
#include <new>
#include <type_traits>
#include <utility>
template <typename T> class delegate;
template<class R, class ...A>
class delegate<R (A...)>
{
static constexpr auto max_store_size = 10 * sizeof(::std::size_t);
using stub_ptr_type = R (*)(void*, A&&...);
delegate(void* const o, stub_ptr_type const m) noexcept
: object_ptr_(o),
stub_ptr_(m)
{
}
public:
delegate() = default;
delegate(delegate const& other) { *this = other; }
delegate(delegate&& other) { *this = ::std::move(other); }
delegate(::std::nullptr_t const) noexcept : delegate() { }
template <class C>
explicit delegate(C const* const o) noexcept
: object_ptr_(const_cast<C*>(o))
{
}
template <class C>
explicit delegate(C const& o) noexcept
: object_ptr_(const_cast<C*>(&o))
{
}
delegate(R (* const function_ptr)(A...))
{
*this = from(function_ptr);
}
template <class C>
delegate(C* const object_ptr, R (C::* const method_ptr)(A...))
{
*this = from(object_ptr, method_ptr);
}
template <class C>
delegate(C* const object_ptr, R (C::* const method_ptr)(A...) const)
{
*this = from(object_ptr, method_ptr);
}
template <class C>
delegate(C& object, R (C::* const method_ptr)(A...))
{
*this = from(object, method_ptr);
}
template <class C>
delegate(C const& object, R (C::* const method_ptr)(A...) const)
{
*this = from(object, method_ptr);
}
template <
typename T,
typename = typename ::std::enable_if<
!::std::is_same<delegate, typename ::std::decay<T>::type>{}
>::type
>
delegate(T&& f)
{
using functor_type = typename ::std::decay<T>::type;
static_assert(sizeof(T) <= sizeof(store_), "increase store_ size");
new (store_) functor_type(::std::forward<T>(f));
object_ptr_ = store_;
stub_ptr_ = functor_stub<functor_type>;
deleter_ = deleter_stub<functor_type>;
copier_ = copier_stub<functor_type>;
mover_ = mover_stub<functor_type>;
}
delegate& operator=(delegate const& rhs)
{
if (rhs.deleter_)
{
rhs.copier_(*this, rhs);
}
else
{
object_ptr_ = rhs.object_ptr_;
stub_ptr_ = rhs.stub_ptr_;
}
return *this;
}
delegate& operator=(delegate&& rhs)
{
if (rhs.deleter_)
{
rhs.mover_(*this, ::std::move(rhs));
}
else
{
object_ptr_ = rhs.object_ptr_;
stub_ptr_ = rhs.stub_ptr_;
}
return *this;
}
delegate& operator=(R (* const rhs)(A...))
{
return *this = from(rhs);
}
template <class C>
delegate& operator=(R (C::* const rhs)(A...))
{
return *this = from(static_cast<C*>(object_ptr_), rhs);
}
template <class C>
delegate& operator=(R (C::* const rhs)(A...) const)
{
return *this = from(static_cast<C const*>(object_ptr_), rhs);
}
template <
typename T,
typename = typename ::std::enable_if<
!::std::is_same<delegate, typename ::std::decay<T>::type>{}
>::type
>
delegate& operator=(T&& f)
{
using functor_type = typename ::std::decay<T>::type;
if (deleter_)
{
deleter_(store_);
deleter_ = nullptr;
}
// else do nothing
static_assert(sizeof(T) <= sizeof(store_), "increase store_ size");
new (store_) functor_type(::std::forward<T>(f));
object_ptr_ = store_;
stub_ptr_ = functor_stub<functor_type>;
deleter_ = deleter_stub<functor_type>;
copier_ = copier_stub<functor_type>;
mover_ = mover_stub<functor_type>;
return *this;
}
template <R (* const function_ptr)(A...)>
static delegate from() noexcept
{
return { nullptr, function_stub<function_ptr> };
}
template <class C, R (C::* const method_ptr)(A...)>
static delegate from(C* const object_ptr) noexcept
{
return { object_ptr, method_stub<C, method_ptr> };
}
template <class C, R (C::* const method_ptr)(A...) const>
static delegate from(C const* const object_ptr) noexcept
{
return { const_cast<C*>(object_ptr), const_method_stub<C, method_ptr> };
}
template <class C, R (C::* const method_ptr)(A...)>
static delegate from(C& object) noexcept
{
return { &object, method_stub<C, method_ptr> };
}
template <class C, R (C::* const method_ptr)(A...) const>
static delegate from(C const& object) noexcept
{
return { const_cast<C*>(&object), const_method_stub<C, method_ptr> };
}
template <typename T>
static delegate from(T&& f)
{
return ::std::forward<T>(f);
}
static delegate from(R (* const function_ptr)(A...))
{
return [function_ptr](A&&... args) {
return (*function_ptr)(::std::forward<A>(args)...); };
}
template <class C>
static delegate from(C* const object_ptr,
R (C::* const method_ptr)(A...))
{
return [object_ptr, method_ptr](A&&... args) {
return (object_ptr->*method_ptr)(::std::forward<A>(args)...); };
}
template <class C>
static delegate from(C const* const object_ptr,
R (C::* const method_ptr)(A...) const)
{
return [object_ptr, method_ptr](A&&... args) {
return (object_ptr->*method_ptr)(::std::forward<A>(args)...); };
}
template <class C>
static delegate from(C& object, R (C::* const method_ptr)(A...))
{
return [&object, method_ptr](A&&... args) {
return (object.*method_ptr)(::std::forward<A>(args)...); };
}
template <class C>
static delegate from(C const& object,
R (C::* const method_ptr)(A...) const)
{
return [&object, method_ptr](A&&... args) {
return (object.*method_ptr)(::std::forward<A>(args)...); };
}
void reset() { stub_ptr_ = nullptr; }
void reset_stub() noexcept { stub_ptr_ = nullptr; }
void swap(delegate& other) noexcept { ::std::swap(*this, other); }
bool operator==(delegate const& rhs) const noexcept
{
return (object_ptr_ == rhs.object_ptr_) && (stub_ptr_ == rhs.stub_ptr_);
}
bool operator!=(delegate const& rhs) const noexcept
{
return !operator==(rhs);
}
bool operator<(delegate const& rhs) const noexcept
{
return (object_ptr_ < rhs.object_ptr_) ||
((object_ptr_ == rhs.object_ptr_) && (stub_ptr_ < rhs.stub_ptr_));
}
bool operator==(::std::nullptr_t const) const noexcept
{
return !stub_ptr_;
}
bool operator!=(::std::nullptr_t const) const noexcept
{
return stub_ptr_;
}
explicit operator bool() const noexcept { return stub_ptr_; }
R operator()(A... args) const
{
// assert(stub_ptr);
return stub_ptr_(object_ptr_, ::std::forward<A>(args)...);
}
private:
friend class ::std::hash<delegate>;
using copier_type = void (*)(delegate&, delegate const&);
using mover_type = void (*)(delegate&, delegate&&);
using deleter_type = void (*)(void*);
void* object_ptr_;
stub_ptr_type stub_ptr_{};
copier_type copier_;
mover_type mover_;
deleter_type deleter_{};
alignas(::max_align_t) char store_[max_store_size];
template <typename T>
static void copier_stub(delegate& dst, delegate const& src)
{
new (dst.store_) T(*static_cast<T const*>(
static_cast<void const*>(src.store_)));
dst.stub_ptr_ = src.stub_ptr_;
dst.object_ptr_ = dst.store_;
assert(src.deleter_);
dst.deleter_ = src.deleter_;
dst.copier_ = src.copier_;
dst.mover_ = src.mover_;
}
template <typename T>
static void mover_stub(delegate& dst, delegate&& src)
{
new (dst.store_) T(::std::move(*static_cast<T*>(
static_cast<void*>(src.store_))));
dst.stub_ptr_ = src.stub_ptr_;
dst.object_ptr_ = dst.store_;
assert(src.deleter_);
dst.deleter_ = src.deleter_;
dst.copier_ = src.copier_;
dst.mover_ = src.mover_;
}
template <class T>
static void deleter_stub(void* const p)
{
static_cast<T*>(p)->~T();
}
template <R (*function_ptr)(A...)>
static R function_stub(void* const, A&&... args)
{
return function_ptr(::std::forward<A>(args)...);
}
template <class C, R (C::*method_ptr)(A...)>
static R method_stub(void* const object_ptr, A&&... args)
{
return (static_cast<C*>(object_ptr)->*method_ptr)(
::std::forward<A>(args)...);
}
template <class C, R (C::*method_ptr)(A...) const>
static R const_method_stub(void* const object_ptr, A&&... args)
{
return (static_cast<C const*>(object_ptr)->*method_ptr)(
::std::forward<A>(args)...);
}
template <typename T>
static R functor_stub(void* const object_ptr, A&&... args)
{
return (*static_cast<T*>(object_ptr))(::std::forward<A>(args)...);
}
};
namespace std
{
template <typename R, typename ...A>
struct hash<delegate<R (A...)> >
{
size_t operator()(delegate<R (A...)> const& d) const noexcept
{
auto const seed(hash<void*>()(d.object_ptr_));
return hash<typename delegate<R (A...)>::stub_ptr_type>()(
d.stub_ptr_) + 0x9e3779b9 + (seed << 6) + (seed >> 2);
}
};
}
#endif // ARRAYDELEGATE_HPP
<commit_msg>some fixes<commit_after>#pragma once
#ifndef ARRAYDELEGATE_HPP
# define ARRAYDELEGATE_HPP
#include <cassert>
#include <cstddef>
#include <memory>
#include <new>
#include <type_traits>
#include <utility>
template <typename T> class delegate;
template<class R, class ...A>
class delegate<R (A...)>
{
static constexpr auto max_store_size = 10 * sizeof(::std::size_t);
using stub_ptr_type = R (*)(void*, A&&...);
delegate(void* const o, stub_ptr_type const m) noexcept
: object_ptr_(o),
stub_ptr_(m)
{
}
public:
delegate() = default;
delegate(delegate const& other) { *this = other; }
delegate(delegate&& other) { *this = ::std::move(other); }
delegate(::std::nullptr_t const) noexcept : delegate() { }
template <class C>
explicit delegate(C const* const o) noexcept
: object_ptr_(const_cast<C*>(o))
{
}
template <class C>
explicit delegate(C const& o) noexcept
: object_ptr_(const_cast<C*>(&o))
{
}
delegate(R (* const function_ptr)(A...))
{
*this = from(function_ptr);
}
template <class C>
delegate(C* const object_ptr, R (C::* const method_ptr)(A...))
{
*this = from(object_ptr, method_ptr);
}
template <class C>
delegate(C* const object_ptr, R (C::* const method_ptr)(A...) const)
{
*this = from(object_ptr, method_ptr);
}
template <class C>
delegate(C& object, R (C::* const method_ptr)(A...))
{
*this = from(object, method_ptr);
}
template <class C>
delegate(C const& object, R (C::* const method_ptr)(A...) const)
{
*this = from(object, method_ptr);
}
template <
typename T,
typename = typename ::std::enable_if<
!::std::is_same<delegate, typename ::std::decay<T>::type>{}
>::type
>
delegate(T&& f)
{
using functor_type = typename ::std::decay<T>::type;
static_assert(sizeof(T) <= sizeof(store_), "increase store_ size");
new (store_) functor_type(::std::forward<T>(f));
object_ptr_ = store_;
stub_ptr_ = functor_stub<functor_type>;
deleter_ = deleter_stub<functor_type>;
copier_ = copier_stub<functor_type>;
mover_ = mover_stub<functor_type>;
}
~delegate()
{
if (deleter_)
{
deleter_(this);
}
// else do nothing
}
delegate& operator=(delegate const& rhs)
{
if (rhs.deleter_)
{
rhs.copier_(*this, rhs);
}
else
{
object_ptr_ = rhs.object_ptr_;
stub_ptr_ = rhs.stub_ptr_;
deleter_ = nullptr;
}
return *this;
}
delegate& operator=(delegate&& rhs)
{
if (rhs.deleter_)
{
rhs.mover_(*this, ::std::move(rhs));
}
else
{
object_ptr_ = rhs.object_ptr_;
stub_ptr_ = rhs.stub_ptr_;
deleter_ = nullptr;
}
return *this;
}
delegate& operator=(R (* const rhs)(A...))
{
return *this = from(rhs);
}
template <class C>
delegate& operator=(R (C::* const rhs)(A...))
{
return *this = from(static_cast<C*>(object_ptr_), rhs);
}
template <class C>
delegate& operator=(R (C::* const rhs)(A...) const)
{
return *this = from(static_cast<C const*>(object_ptr_), rhs);
}
template <
typename T,
typename = typename ::std::enable_if<
!::std::is_same<delegate, typename ::std::decay<T>::type>{}
>::type
>
delegate& operator=(T&& f)
{
using functor_type = typename ::std::decay<T>::type;
if (deleter_)
{
deleter_(store_);
deleter_ = nullptr;
}
// else do nothing
static_assert(sizeof(T) <= sizeof(store_), "increase store_ size");
new (store_) functor_type(::std::forward<T>(f));
object_ptr_ = store_;
stub_ptr_ = functor_stub<functor_type>;
deleter_ = deleter_stub<functor_type>;
copier_ = copier_stub<functor_type>;
mover_ = mover_stub<functor_type>;
return *this;
}
template <R (* const function_ptr)(A...)>
static delegate from() noexcept
{
return { nullptr, function_stub<function_ptr> };
}
template <class C, R (C::* const method_ptr)(A...)>
static delegate from(C* const object_ptr) noexcept
{
return { object_ptr, method_stub<C, method_ptr> };
}
template <class C, R (C::* const method_ptr)(A...) const>
static delegate from(C const* const object_ptr) noexcept
{
return { const_cast<C*>(object_ptr), const_method_stub<C, method_ptr> };
}
template <class C, R (C::* const method_ptr)(A...)>
static delegate from(C& object) noexcept
{
return { &object, method_stub<C, method_ptr> };
}
template <class C, R (C::* const method_ptr)(A...) const>
static delegate from(C const& object) noexcept
{
return { const_cast<C*>(&object), const_method_stub<C, method_ptr> };
}
template <typename T>
static delegate from(T&& f)
{
return ::std::forward<T>(f);
}
static delegate from(R (* const function_ptr)(A...))
{
return [function_ptr](A&&... args) {
return (*function_ptr)(::std::forward<A>(args)...); };
}
template <class C>
static delegate from(C* const object_ptr,
R (C::* const method_ptr)(A...))
{
return [object_ptr, method_ptr](A&&... args) {
return (object_ptr->*method_ptr)(::std::forward<A>(args)...); };
}
template <class C>
static delegate from(C const* const object_ptr,
R (C::* const method_ptr)(A...) const)
{
return [object_ptr, method_ptr](A&&... args) {
return (object_ptr->*method_ptr)(::std::forward<A>(args)...); };
}
template <class C>
static delegate from(C& object, R (C::* const method_ptr)(A...))
{
return [&object, method_ptr](A&&... args) {
return (object.*method_ptr)(::std::forward<A>(args)...); };
}
template <class C>
static delegate from(C const& object,
R (C::* const method_ptr)(A...) const)
{
return [&object, method_ptr](A&&... args) {
return (object.*method_ptr)(::std::forward<A>(args)...); };
}
void reset() { stub_ptr_ = nullptr; }
void reset_stub() noexcept { stub_ptr_ = nullptr; }
void swap(delegate& other) noexcept { ::std::swap(*this, other); }
bool operator==(delegate const& rhs) const noexcept
{
return (object_ptr_ == rhs.object_ptr_) && (stub_ptr_ == rhs.stub_ptr_);
}
bool operator!=(delegate const& rhs) const noexcept
{
return !operator==(rhs);
}
bool operator<(delegate const& rhs) const noexcept
{
return (object_ptr_ < rhs.object_ptr_) ||
((object_ptr_ == rhs.object_ptr_) && (stub_ptr_ < rhs.stub_ptr_));
}
bool operator==(::std::nullptr_t const) const noexcept
{
return !stub_ptr_;
}
bool operator!=(::std::nullptr_t const) const noexcept
{
return stub_ptr_;
}
explicit operator bool() const noexcept { return stub_ptr_; }
R operator()(A... args) const
{
// assert(stub_ptr);
return stub_ptr_(object_ptr_, ::std::forward<A>(args)...);
}
private:
friend class ::std::hash<delegate>;
using copier_type = void (*)(delegate&, delegate const&);
using mover_type = void (*)(delegate&, delegate&&);
using deleter_type = void (*)(void*);
void* object_ptr_;
stub_ptr_type stub_ptr_{};
copier_type copier_;
mover_type mover_;
deleter_type deleter_{};
alignas(::max_align_t) char store_[max_store_size];
template <typename T>
static void copier_stub(delegate& dst, delegate const& src)
{
new (dst.store_) T(*static_cast<T const*>(
static_cast<void const*>(src.store_)));
dst.stub_ptr_ = src.stub_ptr_;
dst.object_ptr_ = dst.store_;
assert(src.deleter_);
dst.deleter_ = src.deleter_;
dst.copier_ = src.copier_;
dst.mover_ = src.mover_;
}
template <typename T>
static void mover_stub(delegate& dst, delegate&& src)
{
new (dst.store_) T(::std::move(*static_cast<T*>(
static_cast<void*>(src.store_))));
dst.stub_ptr_ = src.stub_ptr_;
dst.object_ptr_ = dst.store_;
assert(src.deleter_);
dst.deleter_ = src.deleter_;
dst.copier_ = src.copier_;
dst.mover_ = src.mover_;
}
template <class T>
static void deleter_stub(void* const p)
{
static_cast<T*>(p)->~T();
}
template <R (*function_ptr)(A...)>
static R function_stub(void* const, A&&... args)
{
return function_ptr(::std::forward<A>(args)...);
}
template <class C, R (C::*method_ptr)(A...)>
static R method_stub(void* const object_ptr, A&&... args)
{
return (static_cast<C*>(object_ptr)->*method_ptr)(
::std::forward<A>(args)...);
}
template <class C, R (C::*method_ptr)(A...) const>
static R const_method_stub(void* const object_ptr, A&&... args)
{
return (static_cast<C const*>(object_ptr)->*method_ptr)(
::std::forward<A>(args)...);
}
template <typename T>
static R functor_stub(void* const object_ptr, A&&... args)
{
return (*static_cast<T*>(object_ptr))(::std::forward<A>(args)...);
}
};
namespace std
{
template <typename R, typename ...A>
struct hash<delegate<R (A...)> >
{
size_t operator()(delegate<R (A...)> const& d) const noexcept
{
auto const seed(hash<void*>()(d.object_ptr_));
return hash<typename delegate<R (A...)>::stub_ptr_type>()(
d.stub_ptr_) + 0x9e3779b9 + (seed << 6) + (seed >> 2);
}
};
}
#endif // ARRAYDELEGATE_HPP
<|endoftext|> |
<commit_before>/*
# Copyright (c) 2015, Ole-André Rodlie <olear@dracolinux.org>
# All rights reserved.
#
# OpenFX-Arena is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License version 2. You should have received a copy of the GNU General Public License version 2 along with OpenFX-Arena. If not, see http://www.gnu.org/licenses/.
# OpenFX-Arena 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 "ofxsMacros.h"
#include "ofxsMultiThread.h"
#include "ofxsImageEffect.h"
#include <Magick++.h>
#include <iostream>
#include <stdint.h>
#include <cmath>
#define kPluginName "RollOFX"
#define kPluginGrouping "Extra/Transform"
#define kPluginIdentifier "net.fxarena.openfx.Roll"
#define kPluginVersionMajor 2
#define kPluginVersionMinor 1
#define kParamRollX "x"
#define kParamRollXLabel "X"
#define kParamRollXHint "Adjust roll X"
#define kParamRollXDefault 0
#define kParamRollY "y"
#define kParamRollYLabel "Y"
#define kParamRollYHint "Adjust roll Y"
#define kParamRollYDefault 0
#define kSupportsTiles 0
#define kSupportsMultiResolution 1
#define kSupportsRenderScale 1
#define kRenderThreadSafety eRenderFullySafe
#define kHostFrameThreading false
using namespace OFX;
class RollPlugin : public OFX::ImageEffect
{
public:
RollPlugin(OfxImageEffectHandle handle);
virtual ~RollPlugin();
virtual void render(const OFX::RenderArguments &args) OVERRIDE FINAL;
virtual bool getRegionOfDefinition(const OFX::RegionOfDefinitionArguments &args, OfxRectD &rod) OVERRIDE FINAL;
private:
OFX::Clip *dstClip_;
OFX::Clip *srcClip_;
OFX::DoubleParam *rollX_;
OFX::DoubleParam *rollY_;
};
RollPlugin::RollPlugin(OfxImageEffectHandle handle)
: OFX::ImageEffect(handle)
, dstClip_(0)
, srcClip_(0)
{
Magick::InitializeMagick(NULL);
dstClip_ = fetchClip(kOfxImageEffectOutputClipName);
assert(dstClip_ && dstClip_->getPixelComponents() == OFX::ePixelComponentRGBA);
srcClip_ = fetchClip(kOfxImageEffectSimpleSourceClipName);
assert(srcClip_ && srcClip_->getPixelComponents() == OFX::ePixelComponentRGBA);
rollX_ = fetchDoubleParam(kParamRollX);
rollY_ = fetchDoubleParam(kParamRollY);
assert(rollX_ && rollY_);
}
RollPlugin::~RollPlugin()
{
}
void RollPlugin::render(const OFX::RenderArguments &args)
{
// render scale
if (!kSupportsRenderScale && (args.renderScale.x != 1. || args.renderScale.y != 1.)) {
OFX::throwSuiteStatusException(kOfxStatFailed);
return;
}
// get src clip
if (!srcClip_) {
OFX::throwSuiteStatusException(kOfxStatFailed);
return;
}
assert(srcClip_);
std::auto_ptr<const OFX::Image> srcImg(srcClip_->fetchImage(args.time));
OfxRectI srcRod,srcBounds;
if (srcImg.get()) {
srcRod = srcImg->getRegionOfDefinition();
srcBounds = srcImg->getBounds();
if (srcImg->getRenderScale().x != args.renderScale.x ||
srcImg->getRenderScale().y != args.renderScale.y ||
srcImg->getField() != args.fieldToRender) {
setPersistentMessage(OFX::Message::eMessageError, "", "OFX Host gave image with wrong scale or field properties");
OFX::throwSuiteStatusException(kOfxStatFailed);
return;
}
} else {
OFX::throwSuiteStatusException(kOfxStatFailed);
}
// get dest clip
if (!dstClip_) {
OFX::throwSuiteStatusException(kOfxStatFailed);
return;
}
assert(dstClip_);
std::auto_ptr<OFX::Image> dstImg(dstClip_->fetchImage(args.time));
if (!dstImg.get()) {
OFX::throwSuiteStatusException(kOfxStatFailed);
return;
}
if (dstImg->getRenderScale().x != args.renderScale.x ||
dstImg->getRenderScale().y != args.renderScale.y ||
dstImg->getField() != args.fieldToRender) {
setPersistentMessage(OFX::Message::eMessageError, "", "OFX Host gave image with wrong scale or field properties");
OFX::throwSuiteStatusException(kOfxStatFailed);
return;
}
// get bit depth
OFX::BitDepthEnum dstBitDepth = dstImg->getPixelDepth();
if (dstBitDepth != OFX::eBitDepthFloat || (srcImg.get() && (dstBitDepth != srcImg->getPixelDepth()))) {
OFX::throwSuiteStatusException(kOfxStatErrFormat);
return;
}
// get pixel component
OFX::PixelComponentEnum dstComponents = dstImg->getPixelComponents();
if (dstComponents != OFX::ePixelComponentRGBA || (srcImg.get() && (dstComponents != srcImg->getPixelComponents()))) {
OFX::throwSuiteStatusException(kOfxStatErrFormat);
return;
}
// are we in the image bounds?
OfxRectI dstBounds = dstImg->getBounds();
if(args.renderWindow.x1 < dstBounds.x1 || args.renderWindow.x1 >= dstBounds.x2 || args.renderWindow.y1 < dstBounds.y1 || args.renderWindow.y1 >= dstBounds.y2 ||
args.renderWindow.x2 <= dstBounds.x1 || args.renderWindow.x2 > dstBounds.x2 || args.renderWindow.y2 <= dstBounds.y1 || args.renderWindow.y2 > dstBounds.y2) {
OFX::throwSuiteStatusException(kOfxStatErrValue);
return;
}
// get params
double x,y;
rollX_->getValueAtTime(args.time, x);
rollY_->getValueAtTime(args.time, y);
// setup
int width = srcRod.x2-srcRod.x1;
int height = srcRod.y2-srcRod.y1;
// Set max threads allowed by host
unsigned int threads = 0;
threads = OFX::MultiThread::getNumCPUs();
if (threads>0) {
Magick::ResourceLimits::thread(threads);
#ifdef DEBUG
std::cout << "Setting max threads to " << threads << std::endl;
#endif
}
// read image
Magick::Image image(Magick::Geometry(width,height),Magick::Color("rgba(0,0,0,0)"));
Magick::Image output(Magick::Geometry(width,height),Magick::Color("rgba(0,0,0,1)"));
if (srcClip_ && srcClip_->isConnected())
image.read(width,height,"RGBA",Magick::FloatPixel,(float*)srcImg->getPixelData());
// roll image
image.roll(std::floor(x * args.renderScale.x + 0.5),std::floor(y * args.renderScale.x + 0.5));
// return image
if (dstClip_ && dstClip_->isConnected()) {
output.composite(image, 0, 0, Magick::OverCompositeOp);
output.composite(image, 0, 0, Magick::CopyOpacityCompositeOp);
output.write(0,0,args.renderWindow.x2 - args.renderWindow.x1,args.renderWindow.y2 - args.renderWindow.y1,"RGBA",Magick::FloatPixel,(float*)dstImg->getPixelData());
}
}
bool RollPlugin::getRegionOfDefinition(const OFX::RegionOfDefinitionArguments &args, OfxRectD &rod)
{
if (!kSupportsRenderScale && (args.renderScale.x != 1. || args.renderScale.y != 1.)) {
OFX::throwSuiteStatusException(kOfxStatFailed);
return false;
}
if (srcClip_ && srcClip_->isConnected()) {
rod = srcClip_->getRegionOfDefinition(args.time);
} else {
rod.x1 = rod.y1 = kOfxFlagInfiniteMin;
rod.x2 = rod.y2 = kOfxFlagInfiniteMax;
}
return true;
}
mDeclarePluginFactory(RollPluginFactory, {}, {});
/** @brief The basic describe function, passed a plugin descriptor */
void RollPluginFactory::describe(OFX::ImageEffectDescriptor &desc)
{
// basic labels
desc.setLabel(kPluginName);
desc.setPluginGrouping(kPluginGrouping);
size_t magickNumber;
std::string magickString = MagickCore::GetMagickVersion(&magickNumber);
desc.setPluginDescription("Roll transform node.\n\nPowered by "+magickString+"\n\nImageMagick (R) is Copyright 1999-2015 ImageMagick Studio LLC, a non-profit organization dedicated to making software imaging solutions freely available.\n\nImageMagick is distributed under the Apache 2.0 license.");
// add the supported contexts
desc.addSupportedContext(eContextGeneral);
desc.addSupportedContext(eContextFilter);
// add supported pixel depths
desc.addSupportedBitDepth(eBitDepthFloat);
desc.setSupportsTiles(kSupportsTiles);
desc.setSupportsMultiResolution(kSupportsMultiResolution);
desc.setRenderThreadSafety(kRenderThreadSafety);
desc.setHostFrameThreading(kHostFrameThreading);
desc.setHostMaskingEnabled(true);
desc.setHostMixingEnabled(true);
}
/** @brief The describe in context function, passed a plugin descriptor and a context */
void RollPluginFactory::describeInContext(OFX::ImageEffectDescriptor &desc, ContextEnum /*context*/)
{
// create the mandated source clip
ClipDescriptor *srcClip = desc.defineClip(kOfxImageEffectSimpleSourceClipName);
srcClip->addSupportedComponent(ePixelComponentRGBA);
srcClip->setTemporalClipAccess(false);
srcClip->setSupportsTiles(kSupportsTiles);
srcClip->setIsMask(false);
// create the mandated output clip
ClipDescriptor *dstClip = desc.defineClip(kOfxImageEffectOutputClipName);
dstClip->addSupportedComponent(ePixelComponentRGBA);
dstClip->setSupportsTiles(kSupportsTiles);
// make some pages
PageParamDescriptor *page = desc.definePageParam(kPluginName);
{
DoubleParamDescriptor *param = desc.defineDoubleParam(kParamRollX);
param->setLabel(kParamRollXLabel);
param->setHint(kParamRollXHint);
param->setRange(-100000, 100000);
param->setDisplayRange(-2000, 2000);
param->setDefault(kParamRollXDefault);
page->addChild(*param);
}
{
DoubleParamDescriptor *param = desc.defineDoubleParam(kParamRollY);
param->setLabel(kParamRollYLabel);
param->setHint(kParamRollYHint);
param->setRange(-100000, 100000);
param->setDisplayRange(-2000, 2000);
param->setDefault(kParamRollYDefault);
page->addChild(*param);
}
}
/** @brief The create instance function, the plugin must return an object derived from the \ref OFX::ImageEffect class */
ImageEffect* RollPluginFactory::createInstance(OfxImageEffectHandle handle, ContextEnum /*context*/)
{
return new RollPlugin(handle);
}
static RollPluginFactory p(kPluginIdentifier, kPluginVersionMajor, kPluginVersionMinor);
mRegisterPluginFactoryInstance(p)
<commit_msg>Roll: make OpenMP a param<commit_after>/*
# Copyright (c) 2015, Ole-André Rodlie <olear@dracolinux.org>
# All rights reserved.
#
# OpenFX-Arena is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License version 2. You should have received a copy of the GNU General Public License version 2 along with OpenFX-Arena. If not, see http://www.gnu.org/licenses/.
# OpenFX-Arena 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 "ofxsMacros.h"
#include "ofxsMultiThread.h"
#include "ofxsImageEffect.h"
#include <Magick++.h>
#include <iostream>
#include <stdint.h>
#include <cmath>
#define kPluginName "RollOFX"
#define kPluginGrouping "Extra/Transform"
#define kPluginIdentifier "net.fxarena.openfx.Roll"
#define kPluginVersionMajor 2
#define kPluginVersionMinor 2
#define kParamRollX "x"
#define kParamRollXLabel "X"
#define kParamRollXHint "Adjust roll X"
#define kParamRollXDefault 0
#define kParamRollY "y"
#define kParamRollYLabel "Y"
#define kParamRollYHint "Adjust roll Y"
#define kParamRollYDefault 0
#define kParamOpenMP "openmp"
#define kParamOpenMPLabel "OpenMP"
#define kParamOpenMPHint "Enable/Disable OpenMP support. This will enable the plugin to use as many threads as allowed by host."
#define kParamOpenMPDefault false
#define kSupportsTiles 0
#define kSupportsMultiResolution 1
#define kSupportsRenderScale 1
#define kRenderThreadSafety eRenderFullySafe
#define kHostFrameThreading false
using namespace OFX;
static bool _hasOpenMP = false;
class RollPlugin : public OFX::ImageEffect
{
public:
RollPlugin(OfxImageEffectHandle handle);
virtual ~RollPlugin();
virtual void render(const OFX::RenderArguments &args) OVERRIDE FINAL;
virtual bool getRegionOfDefinition(const OFX::RegionOfDefinitionArguments &args, OfxRectD &rod) OVERRIDE FINAL;
private:
OFX::Clip *dstClip_;
OFX::Clip *srcClip_;
OFX::DoubleParam *rollX_;
OFX::DoubleParam *rollY_;
OFX::BooleanParam *enableOpenMP_;
};
RollPlugin::RollPlugin(OfxImageEffectHandle handle)
: OFX::ImageEffect(handle)
, dstClip_(0)
, srcClip_(0)
{
Magick::InitializeMagick(NULL);
dstClip_ = fetchClip(kOfxImageEffectOutputClipName);
assert(dstClip_ && dstClip_->getPixelComponents() == OFX::ePixelComponentRGBA);
srcClip_ = fetchClip(kOfxImageEffectSimpleSourceClipName);
assert(srcClip_ && srcClip_->getPixelComponents() == OFX::ePixelComponentRGBA);
rollX_ = fetchDoubleParam(kParamRollX);
rollY_ = fetchDoubleParam(kParamRollY);
enableOpenMP_ = fetchBooleanParam(kParamOpenMP);
assert(rollX_ && rollY_ && enableOpenMP_);
}
RollPlugin::~RollPlugin()
{
}
void RollPlugin::render(const OFX::RenderArguments &args)
{
// render scale
if (!kSupportsRenderScale && (args.renderScale.x != 1. || args.renderScale.y != 1.)) {
OFX::throwSuiteStatusException(kOfxStatFailed);
return;
}
// get src clip
if (!srcClip_) {
OFX::throwSuiteStatusException(kOfxStatFailed);
return;
}
assert(srcClip_);
std::auto_ptr<const OFX::Image> srcImg(srcClip_->fetchImage(args.time));
OfxRectI srcRod,srcBounds;
if (srcImg.get()) {
srcRod = srcImg->getRegionOfDefinition();
srcBounds = srcImg->getBounds();
if (srcImg->getRenderScale().x != args.renderScale.x ||
srcImg->getRenderScale().y != args.renderScale.y ||
srcImg->getField() != args.fieldToRender) {
setPersistentMessage(OFX::Message::eMessageError, "", "OFX Host gave image with wrong scale or field properties");
OFX::throwSuiteStatusException(kOfxStatFailed);
return;
}
} else {
OFX::throwSuiteStatusException(kOfxStatFailed);
}
// get dest clip
if (!dstClip_) {
OFX::throwSuiteStatusException(kOfxStatFailed);
return;
}
assert(dstClip_);
std::auto_ptr<OFX::Image> dstImg(dstClip_->fetchImage(args.time));
if (!dstImg.get()) {
OFX::throwSuiteStatusException(kOfxStatFailed);
return;
}
if (dstImg->getRenderScale().x != args.renderScale.x ||
dstImg->getRenderScale().y != args.renderScale.y ||
dstImg->getField() != args.fieldToRender) {
setPersistentMessage(OFX::Message::eMessageError, "", "OFX Host gave image with wrong scale or field properties");
OFX::throwSuiteStatusException(kOfxStatFailed);
return;
}
// get bit depth
OFX::BitDepthEnum dstBitDepth = dstImg->getPixelDepth();
if (dstBitDepth != OFX::eBitDepthFloat || (srcImg.get() && (dstBitDepth != srcImg->getPixelDepth()))) {
OFX::throwSuiteStatusException(kOfxStatErrFormat);
return;
}
// get pixel component
OFX::PixelComponentEnum dstComponents = dstImg->getPixelComponents();
if (dstComponents != OFX::ePixelComponentRGBA || (srcImg.get() && (dstComponents != srcImg->getPixelComponents()))) {
OFX::throwSuiteStatusException(kOfxStatErrFormat);
return;
}
// are we in the image bounds?
OfxRectI dstBounds = dstImg->getBounds();
if(args.renderWindow.x1 < dstBounds.x1 || args.renderWindow.x1 >= dstBounds.x2 || args.renderWindow.y1 < dstBounds.y1 || args.renderWindow.y1 >= dstBounds.y2 ||
args.renderWindow.x2 <= dstBounds.x1 || args.renderWindow.x2 > dstBounds.x2 || args.renderWindow.y2 <= dstBounds.y1 || args.renderWindow.y2 > dstBounds.y2) {
OFX::throwSuiteStatusException(kOfxStatErrValue);
return;
}
// get params
double x,y;
bool enableOpenMP = false;
rollX_->getValueAtTime(args.time, x);
rollY_->getValueAtTime(args.time, y);
enableOpenMP_->getValueAtTime(args.time, enableOpenMP);
// setup
int width = srcRod.x2-srcRod.x1;
int height = srcRod.y2-srcRod.y1;
// OpenMP
unsigned int threads = 1;
if (_hasOpenMP && enableOpenMP)
threads = OFX::MultiThread::getNumCPUs();
Magick::ResourceLimits::thread(threads);
#ifdef DEBUG
std::cout << "Roll threads: " << threads << std::endl;
#endif
// read image
Magick::Image image(Magick::Geometry(width,height),Magick::Color("rgba(0,0,0,0)"));
Magick::Image output(Magick::Geometry(width,height),Magick::Color("rgba(0,0,0,1)"));
if (srcClip_ && srcClip_->isConnected())
image.read(width,height,"RGBA",Magick::FloatPixel,(float*)srcImg->getPixelData());
// roll image
image.roll(std::floor(x * args.renderScale.x + 0.5),std::floor(y * args.renderScale.x + 0.5));
// return image
if (dstClip_ && dstClip_->isConnected()) {
output.composite(image, 0, 0, Magick::OverCompositeOp);
output.composite(image, 0, 0, Magick::CopyOpacityCompositeOp);
output.write(0,0,args.renderWindow.x2 - args.renderWindow.x1,args.renderWindow.y2 - args.renderWindow.y1,"RGBA",Magick::FloatPixel,(float*)dstImg->getPixelData());
}
}
bool RollPlugin::getRegionOfDefinition(const OFX::RegionOfDefinitionArguments &args, OfxRectD &rod)
{
if (!kSupportsRenderScale && (args.renderScale.x != 1. || args.renderScale.y != 1.)) {
OFX::throwSuiteStatusException(kOfxStatFailed);
return false;
}
if (srcClip_ && srcClip_->isConnected()) {
rod = srcClip_->getRegionOfDefinition(args.time);
} else {
rod.x1 = rod.y1 = kOfxFlagInfiniteMin;
rod.x2 = rod.y2 = kOfxFlagInfiniteMax;
}
return true;
}
mDeclarePluginFactory(RollPluginFactory, {}, {});
/** @brief The basic describe function, passed a plugin descriptor */
void RollPluginFactory::describe(OFX::ImageEffectDescriptor &desc)
{
// basic labels
desc.setLabel(kPluginName);
desc.setPluginGrouping(kPluginGrouping);
size_t magickNumber;
std::string magickString = MagickCore::GetMagickVersion(&magickNumber);
desc.setPluginDescription("Roll transform node.\n\nPowered by "+magickString+"\n\nImageMagick (R) is Copyright 1999-2015 ImageMagick Studio LLC, a non-profit organization dedicated to making software imaging solutions freely available.\n\nImageMagick is distributed under the Apache 2.0 license.");
// add the supported contexts
desc.addSupportedContext(eContextGeneral);
desc.addSupportedContext(eContextFilter);
// add supported pixel depths
desc.addSupportedBitDepth(eBitDepthFloat);
desc.setSupportsTiles(kSupportsTiles);
desc.setSupportsMultiResolution(kSupportsMultiResolution);
desc.setRenderThreadSafety(kRenderThreadSafety);
desc.setHostFrameThreading(kHostFrameThreading);
desc.setHostMaskingEnabled(true);
desc.setHostMixingEnabled(true);
}
/** @brief The describe in context function, passed a plugin descriptor and a context */
void RollPluginFactory::describeInContext(OFX::ImageEffectDescriptor &desc, ContextEnum /*context*/)
{
std::string features = MagickCore::GetMagickFeatures();
if (features.find("OpenMP") != std::string::npos)
_hasOpenMP = true;
// create the mandated source clip
ClipDescriptor *srcClip = desc.defineClip(kOfxImageEffectSimpleSourceClipName);
srcClip->addSupportedComponent(ePixelComponentRGBA);
srcClip->setTemporalClipAccess(false);
srcClip->setSupportsTiles(kSupportsTiles);
srcClip->setIsMask(false);
// create the mandated output clip
ClipDescriptor *dstClip = desc.defineClip(kOfxImageEffectOutputClipName);
dstClip->addSupportedComponent(ePixelComponentRGBA);
dstClip->setSupportsTiles(kSupportsTiles);
// make some pages
PageParamDescriptor *page = desc.definePageParam(kPluginName);
{
DoubleParamDescriptor *param = desc.defineDoubleParam(kParamRollX);
param->setLabel(kParamRollXLabel);
param->setHint(kParamRollXHint);
param->setRange(-100000, 100000);
param->setDisplayRange(-2000, 2000);
param->setDefault(kParamRollXDefault);
page->addChild(*param);
}
{
DoubleParamDescriptor *param = desc.defineDoubleParam(kParamRollY);
param->setLabel(kParamRollYLabel);
param->setHint(kParamRollYHint);
param->setRange(-100000, 100000);
param->setDisplayRange(-2000, 2000);
param->setDefault(kParamRollYDefault);
param->setLayoutHint(OFX::eLayoutHintDivider);
page->addChild(*param);
}
{
BooleanParamDescriptor *param = desc.defineBooleanParam(kParamOpenMP);
param->setLabel(kParamOpenMPLabel);
param->setHint(kParamOpenMPHint);
param->setDefault(kParamOpenMPDefault);
param->setAnimates(false);
if (!_hasOpenMP)
param->setEnabled(false);
param->setLayoutHint(OFX::eLayoutHintDivider);
page->addChild(*param);
}
}
/** @brief The create instance function, the plugin must return an object derived from the \ref OFX::ImageEffect class */
ImageEffect* RollPluginFactory::createInstance(OfxImageEffectHandle handle, ContextEnum /*context*/)
{
return new RollPlugin(handle);
}
static RollPluginFactory p(kPluginIdentifier, kPluginVersionMajor, kPluginVersionMinor);
mRegisterPluginFactoryInstance(p)
<|endoftext|> |
<commit_before>/*
* Boost.Foreach support for pugixml classes.
* This file is provided to the public domain.
* Written by Arseny Kapoulkine (arseny.kapoulkine@gmail.com)
*/
#ifndef HEADER_PUGIXML_FOREACH_HPP
#define HEADER_PUGIXML_FOREACH_HPP
#include "pugixml.hpp"
/*
* These types add support for BOOST_FOREACH macro to xml_node and xml_document classes (child iteration only).
* Example usage:
* BOOST_FOREACH(xml_node n, doc) {}
*/
namespace boost
{
template <typename> struct range_mutable_iterator;
template <typename> struct range_const_iterator;
template<> struct range_mutable_iterator<pugi::xml_node>
{
typedef pugi::xml_node::iterator type;
};
template<> struct range_const_iterator<pugi::xml_node>
{
typedef pugi::xml_node::iterator type;
};
template<> struct range_mutable_iterator<pugi::xml_document>
{
typedef pugi::xml_document::iterator type;
};
template<> struct range_const_iterator<pugi::xml_document>
{
typedef pugi::xml_document::iterator type;
};
}
/*
* These types add support for BOOST_FOREACH macro to xml_node and xml_document classes (child/attribute iteration).
* Example usage:
* BOOST_FOREACH(xml_node n, children(doc)) {}
* BOOST_FOREACH(xml_node n, attributes(doc)) {}
*/
namespace pugi
{
inline xml_object_range<xml_node_iterator> children(const pugi::xml_node& node)
{
return node.children();
}
inline xml_object_range<xml_attribute_iterator> attributes(const pugi::xml_node& node)
{
return node.attributes();
}
}
#endif
<commit_msg>contrib: Fix foreach.hpp for Boost 1.56.0<commit_after>/*
* Boost.Foreach support for pugixml classes.
* This file is provided to the public domain.
* Written by Arseny Kapoulkine (arseny.kapoulkine@gmail.com)
*/
#ifndef HEADER_PUGIXML_FOREACH_HPP
#define HEADER_PUGIXML_FOREACH_HPP
#include <boost/range/iterator.hpp>
#include "pugixml.hpp"
/*
* These types add support for BOOST_FOREACH macro to xml_node and xml_document classes (child iteration only).
* Example usage:
* BOOST_FOREACH(xml_node n, doc) {}
*/
namespace boost
{
template<> struct range_mutable_iterator<pugi::xml_node>
{
typedef pugi::xml_node::iterator type;
};
template<> struct range_const_iterator<pugi::xml_node>
{
typedef pugi::xml_node::iterator type;
};
template<> struct range_mutable_iterator<pugi::xml_document>
{
typedef pugi::xml_document::iterator type;
};
template<> struct range_const_iterator<pugi::xml_document>
{
typedef pugi::xml_document::iterator type;
};
}
/*
* These types add support for BOOST_FOREACH macro to xml_node and xml_document classes (child/attribute iteration).
* Example usage:
* BOOST_FOREACH(xml_node n, children(doc)) {}
* BOOST_FOREACH(xml_node n, attributes(doc)) {}
*/
namespace pugi
{
inline xml_object_range<xml_node_iterator> children(const pugi::xml_node& node)
{
return node.children();
}
inline xml_object_range<xml_attribute_iterator> attributes(const pugi::xml_node& node)
{
return node.attributes();
}
}
#endif
<|endoftext|> |
<commit_before>/****************************************************************************
*
* Copyright (C) 2013 PX4 Development Team. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
* 3. Neither the name PX4 nor the names of its contributors may be
* used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
* OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
* AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
****************************************************************************/
/**
* @file gyro_calibration.cpp
* Gyroscope calibration routine
*/
#include "gyro_calibration.h"
#include "commander_helper.h"
#include <stdio.h>
#include <fcntl.h>
#include <poll.h>
#include <math.h>
#include <drivers/drv_hrt.h>
#include <uORB/topics/sensor_combined.h>
#include <drivers/drv_gyro.h>
#include <mavlink/mavlink_log.h>
#include <systemlib/param/param.h>
#include <systemlib/err.h>
void do_gyro_calibration(int mavlink_fd)
{
mavlink_log_info(mavlink_fd, "gyro calibration starting, hold still");
const int calibration_count = 5000;
int sub_sensor_combined = orb_subscribe(ORB_ID(sensor_combined));
struct sensor_combined_s raw;
int calibration_counter = 0;
float gyro_offset[3] = {0.0f, 0.0f, 0.0f};
/* set offsets to zero */
int fd = open(GYRO_DEVICE_PATH, 0);
struct gyro_scale gscale_null = {
0.0f,
1.0f,
0.0f,
1.0f,
0.0f,
1.0f,
};
if (OK != ioctl(fd, GYROIOCSSCALE, (long unsigned int)&gscale_null))
warn("WARNING: failed to set scale / offsets for gyro");
close(fd);
while (calibration_counter < calibration_count) {
/* wait blocking for new data */
struct pollfd fds[1];
fds[0].fd = sub_sensor_combined;
fds[0].events = POLLIN;
int poll_ret = poll(fds, 1, 1000);
if (poll_ret) {
orb_copy(ORB_ID(sensor_combined), sub_sensor_combined, &raw);
gyro_offset[0] += raw.gyro_rad_s[0];
gyro_offset[1] += raw.gyro_rad_s[1];
gyro_offset[2] += raw.gyro_rad_s[2];
calibration_counter++;
} else if (poll_ret == 0) {
/* any poll failure for 1s is a reason to abort */
mavlink_log_info(mavlink_fd, "gyro calibration aborted, retry");
return;
}
}
gyro_offset[0] = gyro_offset[0] / calibration_count;
gyro_offset[1] = gyro_offset[1] / calibration_count;
gyro_offset[2] = gyro_offset[2] / calibration_count;
if (isfinite(gyro_offset[0]) && isfinite(gyro_offset[1]) && isfinite(gyro_offset[2])) {
if (param_set(param_find("SENS_GYRO_XOFF"), &(gyro_offset[0]))
|| param_set(param_find("SENS_GYRO_YOFF"), &(gyro_offset[1]))
|| param_set(param_find("SENS_GYRO_ZOFF"), &(gyro_offset[2]))) {
mavlink_log_critical(mavlink_fd, "Setting gyro offsets failed!");
}
/* set offsets to actual value */
fd = open(GYRO_DEVICE_PATH, 0);
struct gyro_scale gscale = {
gyro_offset[0],
1.0f,
gyro_offset[1],
1.0f,
gyro_offset[2],
1.0f,
};
if (OK != ioctl(fd, GYROIOCSSCALE, (long unsigned int)&gscale))
warn("WARNING: failed to set scale / offsets for gyro");
close(fd);
/* auto-save to EEPROM */
int save_ret = param_save_default();
if (save_ret != 0) {
warnx("WARNING: auto-save of params to storage failed");
mavlink_log_critical(mavlink_fd, "gyro store failed");
// XXX negative tune
return;
}
mavlink_log_info(mavlink_fd, "gyro calibration done");
tune_positive();
/* third beep by cal end routine */
} else {
mavlink_log_info(mavlink_fd, "offset cal FAILED (NaN)");
return;
}
/*** --- SCALING --- ***/
mavlink_log_info(mavlink_fd, "offset calibration finished. Rotate for scale 130x");
mavlink_log_info(mavlink_fd, "or do not rotate and wait for 5 seconds to skip.");
warnx("offset calibration finished. Rotate for scale 30x, or do not rotate and wait for 5 seconds to skip.");
unsigned rotations_count = 30;
float gyro_integral = 0.0f;
float baseline_integral = 0.0f;
// XXX change to mag topic
orb_copy(ORB_ID(sensor_combined), sub_sensor_combined, &raw);
float mag_last = -atan2f(raw.magnetometer_ga[1],raw.magnetometer_ga[0]);
if (mag_last > M_PI_F) mag_last -= 2*M_PI_F;
if (mag_last < -M_PI_F) mag_last += 2*M_PI_F;
uint64_t last_time = hrt_absolute_time();
uint64_t start_time = hrt_absolute_time();
while ((int)fabsf(baseline_integral / (2.0f * M_PI_F)) < rotations_count) {
/* abort this loop if not rotated more than 180 degrees within 5 seconds */
if ((fabsf(baseline_integral / (2.0f * M_PI_F)) < 0.6f)
&& (hrt_absolute_time() - start_time > 5 * 1e6)) {
mavlink_log_info(mavlink_fd, "gyro scale calibration skipped");
mavlink_log_info(mavlink_fd, "gyro calibration done");
tune_positive();
return;
}
/* wait blocking for new data */
struct pollfd fds[1];
fds[0].fd = sub_sensor_combined;
fds[0].events = POLLIN;
int poll_ret = poll(fds, 1, 1000);
if (poll_ret) {
float dt_ms = (hrt_absolute_time() - last_time) / 1e3f;
last_time = hrt_absolute_time();
orb_copy(ORB_ID(sensor_combined), sub_sensor_combined, &raw);
// XXX this is just a proof of concept and needs world / body
// transformation and more
//math::Vector2f magNav(raw.magnetometer_ga);
// calculate error between estimate and measurement
// apply declination correction for true heading as well.
//float mag = -atan2f(magNav(1),magNav(0));
float mag = -atan2f(raw.magnetometer_ga[1],raw.magnetometer_ga[0]);
if (mag > M_PI_F) mag -= 2*M_PI_F;
if (mag < -M_PI_F) mag += 2*M_PI_F;
float diff = mag - mag_last;
if (diff > M_PI_F) diff -= 2*M_PI_F;
if (diff < -M_PI_F) diff += 2*M_PI_F;
baseline_integral += diff;
mag_last = mag;
// Jump through some timing scale hoops to avoid
// operating near the 1e6/1e8 max sane resolution of float.
gyro_integral += (raw.gyro_rad_s[2] * dt_ms) / 1e3f;
warnx("dbg: b: %6.4f, g: %6.4f", baseline_integral, gyro_integral);
// } else if (poll_ret == 0) {
// /* any poll failure for 1s is a reason to abort */
// mavlink_log_info(mavlink_fd, "gyro calibration aborted, retry");
// return;
}
}
float gyro_scale = baseline_integral / gyro_integral;
float gyro_scales[] = { gyro_scale, gyro_scale, gyro_scale };
warnx("gyro scale: yaw (z): %6.4f", gyro_scale);
mavlink_log_info(mavlink_fd, "gyro scale: yaw (z): %6.4f", gyro_scale);
if (isfinite(gyro_scales[0]) && isfinite(gyro_scales[1]) && isfinite(gyro_scales[2])) {
if (param_set(param_find("SENS_GYRO_XSCALE"), &(gyro_scales[0]))
|| param_set(param_find("SENS_GYRO_YSCALE"), &(gyro_scales[1]))
|| param_set(param_find("SENS_GYRO_ZSCALE"), &(gyro_scales[2]))) {
mavlink_log_critical(mavlink_fd, "Setting gyro scale failed!");
}
/* set offsets to actual value */
fd = open(GYRO_DEVICE_PATH, 0);
struct gyro_scale gscale = {
gyro_offset[0],
gyro_scales[0],
gyro_offset[1],
gyro_scales[1],
gyro_offset[2],
gyro_scales[2],
};
if (OK != ioctl(fd, GYROIOCSSCALE, (long unsigned int)&gscale))
warn("WARNING: failed to set scale / offsets for gyro");
close(fd);
/* auto-save to EEPROM */
int save_ret = param_save_default();
if (save_ret != 0) {
warn("WARNING: auto-save of params to storage failed");
}
// char buf[50];
// sprintf(buf, "cal: x:%8.4f y:%8.4f z:%8.4f", (double)gyro_offset[0], (double)gyro_offset[1], (double)gyro_offset[2]);
// mavlink_log_info(mavlink_fd, buf);
mavlink_log_info(mavlink_fd, "gyro calibration done");
tune_positive();
/* third beep by cal end routine */
} else {
mavlink_log_info(mavlink_fd, "gyro calibration FAILED (NaN)");
}
close(sub_sensor_combined);
}
<commit_msg>gyro_calibration: confusing typo in mavlink message fixed<commit_after>/****************************************************************************
*
* Copyright (C) 2013 PX4 Development Team. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
* 3. Neither the name PX4 nor the names of its contributors may be
* used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
* OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
* AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
****************************************************************************/
/**
* @file gyro_calibration.cpp
* Gyroscope calibration routine
*/
#include "gyro_calibration.h"
#include "commander_helper.h"
#include <stdio.h>
#include <fcntl.h>
#include <poll.h>
#include <math.h>
#include <drivers/drv_hrt.h>
#include <uORB/topics/sensor_combined.h>
#include <drivers/drv_gyro.h>
#include <mavlink/mavlink_log.h>
#include <systemlib/param/param.h>
#include <systemlib/err.h>
void do_gyro_calibration(int mavlink_fd)
{
mavlink_log_info(mavlink_fd, "gyro calibration starting, hold still");
const int calibration_count = 5000;
int sub_sensor_combined = orb_subscribe(ORB_ID(sensor_combined));
struct sensor_combined_s raw;
int calibration_counter = 0;
float gyro_offset[3] = {0.0f, 0.0f, 0.0f};
/* set offsets to zero */
int fd = open(GYRO_DEVICE_PATH, 0);
struct gyro_scale gscale_null = {
0.0f,
1.0f,
0.0f,
1.0f,
0.0f,
1.0f,
};
if (OK != ioctl(fd, GYROIOCSSCALE, (long unsigned int)&gscale_null))
warn("WARNING: failed to set scale / offsets for gyro");
close(fd);
while (calibration_counter < calibration_count) {
/* wait blocking for new data */
struct pollfd fds[1];
fds[0].fd = sub_sensor_combined;
fds[0].events = POLLIN;
int poll_ret = poll(fds, 1, 1000);
if (poll_ret) {
orb_copy(ORB_ID(sensor_combined), sub_sensor_combined, &raw);
gyro_offset[0] += raw.gyro_rad_s[0];
gyro_offset[1] += raw.gyro_rad_s[1];
gyro_offset[2] += raw.gyro_rad_s[2];
calibration_counter++;
} else if (poll_ret == 0) {
/* any poll failure for 1s is a reason to abort */
mavlink_log_info(mavlink_fd, "gyro calibration aborted, retry");
return;
}
}
gyro_offset[0] = gyro_offset[0] / calibration_count;
gyro_offset[1] = gyro_offset[1] / calibration_count;
gyro_offset[2] = gyro_offset[2] / calibration_count;
if (isfinite(gyro_offset[0]) && isfinite(gyro_offset[1]) && isfinite(gyro_offset[2])) {
if (param_set(param_find("SENS_GYRO_XOFF"), &(gyro_offset[0]))
|| param_set(param_find("SENS_GYRO_YOFF"), &(gyro_offset[1]))
|| param_set(param_find("SENS_GYRO_ZOFF"), &(gyro_offset[2]))) {
mavlink_log_critical(mavlink_fd, "Setting gyro offsets failed!");
}
/* set offsets to actual value */
fd = open(GYRO_DEVICE_PATH, 0);
struct gyro_scale gscale = {
gyro_offset[0],
1.0f,
gyro_offset[1],
1.0f,
gyro_offset[2],
1.0f,
};
if (OK != ioctl(fd, GYROIOCSSCALE, (long unsigned int)&gscale))
warn("WARNING: failed to set scale / offsets for gyro");
close(fd);
/* auto-save to EEPROM */
int save_ret = param_save_default();
if (save_ret != 0) {
warnx("WARNING: auto-save of params to storage failed");
mavlink_log_critical(mavlink_fd, "gyro store failed");
// XXX negative tune
return;
}
mavlink_log_info(mavlink_fd, "gyro calibration done");
tune_positive();
/* third beep by cal end routine */
} else {
mavlink_log_info(mavlink_fd, "offset cal FAILED (NaN)");
return;
}
/*** --- SCALING --- ***/
mavlink_log_info(mavlink_fd, "offset calibration finished. Rotate for scale 30x");
mavlink_log_info(mavlink_fd, "or do not rotate and wait for 5 seconds to skip.");
warnx("offset calibration finished. Rotate for scale 30x, or do not rotate and wait for 5 seconds to skip.");
unsigned rotations_count = 30;
float gyro_integral = 0.0f;
float baseline_integral = 0.0f;
// XXX change to mag topic
orb_copy(ORB_ID(sensor_combined), sub_sensor_combined, &raw);
float mag_last = -atan2f(raw.magnetometer_ga[1],raw.magnetometer_ga[0]);
if (mag_last > M_PI_F) mag_last -= 2*M_PI_F;
if (mag_last < -M_PI_F) mag_last += 2*M_PI_F;
uint64_t last_time = hrt_absolute_time();
uint64_t start_time = hrt_absolute_time();
while ((int)fabsf(baseline_integral / (2.0f * M_PI_F)) < rotations_count) {
/* abort this loop if not rotated more than 180 degrees within 5 seconds */
if ((fabsf(baseline_integral / (2.0f * M_PI_F)) < 0.6f)
&& (hrt_absolute_time() - start_time > 5 * 1e6)) {
mavlink_log_info(mavlink_fd, "gyro scale calibration skipped");
mavlink_log_info(mavlink_fd, "gyro calibration done");
tune_positive();
return;
}
/* wait blocking for new data */
struct pollfd fds[1];
fds[0].fd = sub_sensor_combined;
fds[0].events = POLLIN;
int poll_ret = poll(fds, 1, 1000);
if (poll_ret) {
float dt_ms = (hrt_absolute_time() - last_time) / 1e3f;
last_time = hrt_absolute_time();
orb_copy(ORB_ID(sensor_combined), sub_sensor_combined, &raw);
// XXX this is just a proof of concept and needs world / body
// transformation and more
//math::Vector2f magNav(raw.magnetometer_ga);
// calculate error between estimate and measurement
// apply declination correction for true heading as well.
//float mag = -atan2f(magNav(1),magNav(0));
float mag = -atan2f(raw.magnetometer_ga[1],raw.magnetometer_ga[0]);
if (mag > M_PI_F) mag -= 2*M_PI_F;
if (mag < -M_PI_F) mag += 2*M_PI_F;
float diff = mag - mag_last;
if (diff > M_PI_F) diff -= 2*M_PI_F;
if (diff < -M_PI_F) diff += 2*M_PI_F;
baseline_integral += diff;
mag_last = mag;
// Jump through some timing scale hoops to avoid
// operating near the 1e6/1e8 max sane resolution of float.
gyro_integral += (raw.gyro_rad_s[2] * dt_ms) / 1e3f;
warnx("dbg: b: %6.4f, g: %6.4f", baseline_integral, gyro_integral);
// } else if (poll_ret == 0) {
// /* any poll failure for 1s is a reason to abort */
// mavlink_log_info(mavlink_fd, "gyro calibration aborted, retry");
// return;
}
}
float gyro_scale = baseline_integral / gyro_integral;
float gyro_scales[] = { gyro_scale, gyro_scale, gyro_scale };
warnx("gyro scale: yaw (z): %6.4f", gyro_scale);
mavlink_log_info(mavlink_fd, "gyro scale: yaw (z): %6.4f", gyro_scale);
if (isfinite(gyro_scales[0]) && isfinite(gyro_scales[1]) && isfinite(gyro_scales[2])) {
if (param_set(param_find("SENS_GYRO_XSCALE"), &(gyro_scales[0]))
|| param_set(param_find("SENS_GYRO_YSCALE"), &(gyro_scales[1]))
|| param_set(param_find("SENS_GYRO_ZSCALE"), &(gyro_scales[2]))) {
mavlink_log_critical(mavlink_fd, "Setting gyro scale failed!");
}
/* set offsets to actual value */
fd = open(GYRO_DEVICE_PATH, 0);
struct gyro_scale gscale = {
gyro_offset[0],
gyro_scales[0],
gyro_offset[1],
gyro_scales[1],
gyro_offset[2],
gyro_scales[2],
};
if (OK != ioctl(fd, GYROIOCSSCALE, (long unsigned int)&gscale))
warn("WARNING: failed to set scale / offsets for gyro");
close(fd);
/* auto-save to EEPROM */
int save_ret = param_save_default();
if (save_ret != 0) {
warn("WARNING: auto-save of params to storage failed");
}
// char buf[50];
// sprintf(buf, "cal: x:%8.4f y:%8.4f z:%8.4f", (double)gyro_offset[0], (double)gyro_offset[1], (double)gyro_offset[2]);
// mavlink_log_info(mavlink_fd, buf);
mavlink_log_info(mavlink_fd, "gyro calibration done");
tune_positive();
/* third beep by cal end routine */
} else {
mavlink_log_info(mavlink_fd, "gyro calibration FAILED (NaN)");
}
close(sub_sensor_combined);
}
<|endoftext|> |
<commit_before>#include <iostream>
#include <string>
#include <map>
using namespace std;
void printMap(map<string, map<string, bool> > nodes) {
cout << "start ------" << endl;
map<string, map<string, bool> >::reverse_iterator rit;
for (rit=nodes.rbegin(); rit!=nodes.rend(); ++rit) {
cout << rit->first << " => length: " << rit->second.size() << '\n' << endl;
map<string, bool>::reverse_iterator rit2;
for (rit2=rit->second.rbegin(); rit2!=rit->second.rend(); ++rit2) {
cout << " " << rit2->first << " => " << rit2->second << '\n' << endl;
}
}
cout << "end ------" << endl;
}
void verifyHamiltonianPath() {
unsigned int N(0), M(0);
cin >> N >> M;
// cout << "N: " << N << ", M: " << M << endl;
map<string, map<string, bool> > nodes;
map<string, bool> graphNodes;
for (unsigned int j = 0; j < M; j++) {
string srcNode, dstNode;
cin >> srcNode >> dstNode;
if (nodes.find(srcNode) == nodes.end()) {
map<string, bool> connectedNodes;
nodes[srcNode] = connectedNodes;
}
nodes[srcNode][dstNode] = true;
graphNodes[srcNode] = true;
if (nodes.find(dstNode) == nodes.end()) {
map<string, bool> connectedNodes;
nodes[dstNode] = connectedNodes;
}
nodes[dstNode][srcNode] = true;
graphNodes[dstNode] = true;
// cout << "Src: " << srcNode << ", Dst: " << dstNode << endl;
}
unsigned int P;
bool isHamiltonianPath = true;
cin >> P;
string startNode, pathNode, prevNode;
map<string, bool> uniquePathNodes;
string * pathNodesArray = new string[P];
for (unsigned int j = 0; j < P; j++) {
cin >> pathNodesArray[j];
}
for (unsigned int j = 0; j < P; j++) {
pathNode = pathNodesArray[j];
if (j == 0) {
if (nodes.find(pathNode) == nodes.end()) {
isHamiltonianPath = false;
break;
} else {
startNode = pathNode;
}
} else {
if (nodes.find(pathNode) == nodes.end() ||
nodes.find(prevNode) == nodes.end() ||
!nodes[prevNode][pathNode] ||
!nodes[pathNode][prevNode]) {
nodes[prevNode][pathNode] = false;
nodes[pathNode][prevNode] = false;
isHamiltonianPath = false;
break;
}
}
uniquePathNodes[pathNode] = true;
prevNode = pathNode;
}
if (startNode != prevNode ||
uniquePathNodes.size() != P-1 ||
uniquePathNodes != graphNodes ||
uniquePathNodes.size() != graphNodes.size()) {
// 1. Must start and end at the same node
// 2. Path nodes must be unique
// 3. Path nodes must have same nodes as G
// 4. Path nodes must have same number of nodes as G
isHamiltonianPath = false;
}
map<string, bool>::reverse_iterator rit;
for (rit = graphNodes.rbegin(); rit != graphNodes.rend(); ++rit) {
if (!uniquePathNodes[rit->first]) {
isHamiltonianPath = false;
}
}
for (rit = uniquePathNodes.rbegin(); rit != uniquePathNodes.rend(); ++rit) {
if (!graphNodes[rit->first]) {
isHamiltonianPath = false;
}
}
cout << (isHamiltonianPath ? "YES" : "NO") << endl;
delete [] pathNodesArray;
}
int main() {
int T;
cin >> T;
for (int i = 0; i < T; i++) {
// cout << endl << "Block " << i << endl;
verifyHamiltonianPath();
}
return 0;
}
<commit_msg>[PA2] Changed to new representation of graph<commit_after>#include <iostream>
#include <string>
#include <map>
using namespace std;
void printMap(map<string, map<string, int> > nodes) {
cout << "start ------" << endl;
map<string, map<string, int> >::reverse_iterator rit;
for (rit=nodes.rbegin(); rit!=nodes.rend(); ++rit) {
cout << rit->first << " => length: " << rit->second.size() << '\n' << endl;
map<string, int>::reverse_iterator rit2;
for (rit2=rit->second.rbegin(); rit2!=rit->second.rend(); ++rit2) {
cout << " " << rit2->first << " => " << rit2->second << '\n' << endl;
}
}
cout << "end ------" << endl;
}
void verifyHamiltonianPath() {
unsigned int N(0), M(0);
cin >> N >> M;
// cout << "N: " << N << ", M: " << M << endl;
map<string, map<string, int> > nodes;
map<string, bool> graphNodes;
for (unsigned int j = 0; j < M; j++) {
string srcNode, dstNode;
cin >> srcNode >> dstNode;
if (nodes.find(srcNode) == nodes.end()) {
map<string, int> connectedNodes;
nodes[srcNode] = connectedNodes;
nodes[srcNode][dstNode] = 0;
}
nodes[srcNode][dstNode] += 1;
graphNodes[srcNode] = true;
if (nodes.find(dstNode) == nodes.end()) {
map<string, int> connectedNodes;
nodes[dstNode] = connectedNodes;
nodes[dstNode][srcNode] = 0;
}
nodes[dstNode][srcNode] += 1;
graphNodes[dstNode] = true;
// cout << "Src: " << srcNode << ", Dst: " << dstNode << endl;
}
unsigned int P;
bool isHamiltonianPath = true;
cin >> P;
string startNode, pathNode, prevNode;
map<string, bool> uniquePathNodes;
string * pathNodesArray = new string[P];
for (unsigned int j = 0; j < P; j++) {
cin >> pathNodesArray[j];
}
for (unsigned int j = 0; j < P; j++) {
pathNode = pathNodesArray[j];
if (j == 0) {
if (nodes.find(pathNode) == nodes.end()) {
isHamiltonianPath = false;
break;
} else {
startNode = pathNode;
}
} else {
// cout << "Src:" << prevNode << ", Dst: " << pathNode << endl;
if (nodes.find(pathNode) == nodes.end() ||
nodes.find(prevNode) == nodes.end() ||
nodes[prevNode][pathNode] == 0 ||
nodes[pathNode][prevNode] == 0) {
nodes[prevNode][pathNode] = false;
nodes[pathNode][prevNode] = false;
// cout << nodes[prevNode][pathNode] << ", " << nodes[pathNode][prevNode] << endl;
// cout << "Cannot find ^ edge!" << endl;
isHamiltonianPath = false;
break;
}
nodes[prevNode][pathNode] -= 1;
nodes[pathNode][prevNode] -= 1;
}
uniquePathNodes[pathNode] = true;
prevNode = pathNode;
}
if (startNode != prevNode ||
uniquePathNodes.size() != P-1 ||
uniquePathNodes != graphNodes ||
uniquePathNodes.size() != graphNodes.size()) {
// 1. Must start and end at the same node
// 2. Path nodes must be unique
// 3. Path nodes must have same nodes as G
// 4. Path nodes must have same number of nodes as G
isHamiltonianPath = false;
}
map<string, bool>::reverse_iterator rit;
for (rit = graphNodes.rbegin(); rit != graphNodes.rend(); ++rit) {
if (!uniquePathNodes[rit->first]) {
isHamiltonianPath = false;
}
}
for (rit = uniquePathNodes.rbegin(); rit != uniquePathNodes.rend(); ++rit) {
if (!graphNodes[rit->first]) {
isHamiltonianPath = false;
}
}
cout << (isHamiltonianPath ? "YES" : "NO") << endl;
delete [] pathNodesArray;
}
int main() {
int T;
cin >> T;
for (int i = 0; i < T; i++) {
// cout << endl << "Block " << i << endl;
verifyHamiltonianPath();
}
return 0;
}
<|endoftext|> |
<commit_before>#include "include/couchbase_admin.h"
CallbackInterface storage;
CallbackInterface retrieval;
CallbackInterface deletion;
void CouchbaseAdmin::initialize (const char * conn)
{
//Initializing
logging->info("CB_Admin:DB: Couchbase Admin Initializing");
struct lcb_create_st cropts;
cropts.version = 3;
cropts.v.v3.connstr = conn;
//Add a password if authentication is active
if (authentication_active == true) {
cropts.v.v3.passwd = password;
}
//Couchbase Connection Creation
//Create an error and instance
lcb_error_t err;
lcb_t private_instance;
//Schedule Bootstrap Creation
err = lcb_create(&private_instance, &cropts);
if (err != LCB_SUCCESS) {
logging->error("CB_Admin:DB: Couldn't create instance!");
logging->error(lcb_strerror(NULL, err));
}
//Schedule Connection
err = lcb_connect(private_instance);
if (err != LCB_SUCCESS) {
logging->error("CB_Admin:DB: Couldn't schedule connection");
logging->error(lcb_strerror(NULL, err));
}
//Yield to IO
lcb_wait(private_instance);
err = lcb_get_bootstrap_status(instance);
if (err != LCB_SUCCESS) {
logging->error("CB Admin:DB: Bootstrapping failed");
logging->error(lcb_strerror(NULL, err));
lcb_destroy(instance);
}
lcb_set_remove_callback(private_instance, del_callback);
lcb_set_store_callback(private_instance, storage_callback);
lcb_set_get_callback(private_instance, get_callback);
}
CouchbaseAdmin::CouchbaseAdmin( const char * conn )
{
authentication_active = false;
initialize (conn);
}
CouchbaseAdmin::CouchbaseAdmin( const char * conn, const char * pswd )
{
authentication_active = true;
password = pswd;
initialize (conn);
}
CouchbaseAdmin::~CouchbaseAdmin ()
{
lcb_destroy(private_instance);
}
void CouchbaseAdmin::load_object ( const char * key )
{
logging->info("CB_Admin:DB: Object being loaded with key:");
logging->info(key);
//Initialize the variables
lcb_error_t err;
lcb_get_cmd_t gcmd;
const lcb_get_cmd_t *gcmdlist = &gcmd;
gcmd.v.v0.key = key;
gcmd.v.v0.nkey = strlen(key);
//Schedule a Get operation
err = lcb_get(private_instance, NULL, 1, &gcmdlist);
if (err != LCB_SUCCESS) {
logging->error("CB_Admin:DB: Couldn't schedule get operation!");
}
}
void CouchbaseAdmin::save_object ( Writeable *obj )
{
logging->info("CB_Admin:DB: Object being saved");
lcb_store_cmd_t scmd;
lcb_error_t err;
const lcb_store_cmd_t *scmdlist = &scmd;
std::string key = obj->get_key();
scmd.v.v0.key = key.c_str();
scmd.v.v0.nkey = key.length();
std::string obj_json_str = obj->to_json();
const char * object_string = obj_json_str.c_str();
scmd.v.v0.bytes = object_string;
scmd.v.v0.nbytes = strlen(object_string);
scmd.v.v0.operation = LCB_REPLACE;
err = lcb_store(private_instance, NULL, 1, &scmdlist);
if (err != LCB_SUCCESS) {
logging->error("CB_Admin:Couldn't schedule storage operation!");
}
}
void CouchbaseAdmin::create_object ( Writeable *obj )
{
logging->info("CB_Admin:Create Object Called");
lcb_error_t err;
lcb_store_cmd_t scmd;
const lcb_store_cmd_t *scmdlist = &scmd;
std::string key = obj->get_key();
scmd.v.v0.key = key.c_str();
scmd.v.v0.nkey = key.length();
std::string obj_json_str = obj->to_json();
const char * object_string = obj_json_str.c_str();
scmd.v.v0.bytes = object_string;
scmd.v.v0.nbytes = strlen(object_string);
scmd.v.v0.operation = LCB_SET;
err = lcb_store(private_instance, NULL, 1, &scmdlist);
if (err != LCB_SUCCESS) {
logging->error("CB_Admin:Couldn't schedule storage operation!");
}
}
void CouchbaseAdmin::delete_object ( const char * key ) {
logging->info("CB_Admin:Delete Object Called with key: ");
logging->info(key);
lcb_error_t err;
lcb_remove_cmd_t cmd;
const lcb_remove_cmd_t *cmdlist = &cmd;
cmd.v.v0.key = key;
cmd.v.v0.nkey = strlen(key);
err = lcb_remove(private_instance, NULL, 1, &cmdlist);
if (err != LCB_SUCCESS) {
logging->error("CB_Admin:Couldn't schedule remove operation: ");
logging->error( lcb_strerror(private_instance, err));
}
}
//Bind the Get Callback for the couchbase calls
void CouchbaseAdmin::bind_get_callback(CallbackInterface gc)
{
retrieval = gc;
}
//Bind the Storage Callback for the couchbase calls
void CouchbaseAdmin::bind_storage_callback(CallbackInterface sc)
{
storage = sc;
}
//Bind the Delete Callback for the couchbase calls
void CouchbaseAdmin::bind_delete_callback(CallbackInterface dc)
{
deletion = dc;
}
lcb_t CouchbaseAdmin::get_instance ()
{
return private_instance;
}
void CouchbaseAdmin::wait ()
{
logging->info("CB_Admin:DB: Clear Function Stack Called");
lcb_wait(private_instance);
logging->info("CB_Admin:Done waiting");
}
<commit_msg>More detailed Couchbase Startup<commit_after>#include "include/couchbase_admin.h"
CallbackInterface storage;
CallbackInterface retrieval;
CallbackInterface deletion;
void CouchbaseAdmin::initialize (const char * conn)
{
//Initializing
logging->info("CB_Admin:DB: Couchbase Admin Initializing");
struct lcb_create_st cropts;
cropts.version = 3;
cropts.v.v3.connstr = conn;
//Add a password if authentication is active
if (authentication_active == true) {
cropts.v.v3.passwd = password;
}
//Couchbase Connection Creation
//Create an error and instance
lcb_error_t err;
lcb_t private_instance;
//Schedule Bootstrap Creation
err = lcb_create(&private_instance, &cropts);
if (err != LCB_SUCCESS) {
logging->error("CB_Admin:DB: Couldn't create instance!");
logging->error(lcb_strerror(NULL, err));
}
//Schedule Connection
err = lcb_connect(private_instance);
if (err != LCB_SUCCESS) {
logging->error("CB_Admin:DB: Couldn't schedule connection");
logging->error(lcb_strerror(NULL, err));
}
//Yield to IO
lcb_wait(private_instance);
err = lcb_get_bootstrap_status(private_instance);
if (err != LCB_SUCCESS) {
logging->error("CB Admin:DB: Bootstrapping failed");
logging->error(lcb_strerror(NULL, err));
lcb_destroy(private_instance);
}
lcb_set_remove_callback(private_instance, del_callback);
lcb_set_store_callback(private_instance, storage_callback);
lcb_set_get_callback(private_instance, get_callback);
}
CouchbaseAdmin::CouchbaseAdmin( const char * conn )
{
authentication_active = false;
initialize (conn);
}
CouchbaseAdmin::CouchbaseAdmin( const char * conn, const char * pswd )
{
authentication_active = true;
password = pswd;
initialize (conn);
}
CouchbaseAdmin::~CouchbaseAdmin ()
{
lcb_destroy(private_instance);
}
void CouchbaseAdmin::load_object ( const char * key )
{
logging->info("CB_Admin:DB: Object being loaded with key:");
logging->info(key);
//Initialize the variables
lcb_error_t err;
lcb_get_cmd_t gcmd;
const lcb_get_cmd_t *gcmdlist = &gcmd;
gcmd.v.v0.key = key;
gcmd.v.v0.nkey = strlen(key);
//Schedule a Get operation
err = lcb_get(private_instance, NULL, 1, &gcmdlist);
if (err != LCB_SUCCESS) {
logging->error("CB_Admin:DB: Couldn't schedule get operation!");
}
}
void CouchbaseAdmin::save_object ( Writeable *obj )
{
logging->info("CB_Admin:DB: Object being saved");
lcb_store_cmd_t scmd;
lcb_error_t err;
const lcb_store_cmd_t *scmdlist = &scmd;
std::string key = obj->get_key();
scmd.v.v0.key = key.c_str();
scmd.v.v0.nkey = key.length();
std::string obj_json_str = obj->to_json();
const char * object_string = obj_json_str.c_str();
scmd.v.v0.bytes = object_string;
scmd.v.v0.nbytes = strlen(object_string);
scmd.v.v0.operation = LCB_REPLACE;
err = lcb_store(private_instance, NULL, 1, &scmdlist);
if (err != LCB_SUCCESS) {
logging->error("CB_Admin:Couldn't schedule storage operation!");
}
}
void CouchbaseAdmin::create_object ( Writeable *obj )
{
logging->info("CB_Admin:Create Object Called");
lcb_error_t err;
lcb_store_cmd_t scmd;
const lcb_store_cmd_t *scmdlist = &scmd;
std::string key = obj->get_key();
scmd.v.v0.key = key.c_str();
scmd.v.v0.nkey = key.length();
std::string obj_json_str = obj->to_json();
const char * object_string = obj_json_str.c_str();
scmd.v.v0.bytes = object_string;
scmd.v.v0.nbytes = strlen(object_string);
scmd.v.v0.operation = LCB_SET;
err = lcb_store(private_instance, NULL, 1, &scmdlist);
if (err != LCB_SUCCESS) {
logging->error("CB_Admin:Couldn't schedule storage operation!");
}
}
void CouchbaseAdmin::delete_object ( const char * key ) {
logging->info("CB_Admin:Delete Object Called with key: ");
logging->info(key);
lcb_error_t err;
lcb_remove_cmd_t cmd;
const lcb_remove_cmd_t *cmdlist = &cmd;
cmd.v.v0.key = key;
cmd.v.v0.nkey = strlen(key);
err = lcb_remove(private_instance, NULL, 1, &cmdlist);
if (err != LCB_SUCCESS) {
logging->error("CB_Admin:Couldn't schedule remove operation: ");
logging->error( lcb_strerror(private_instance, err));
}
}
//Bind the Get Callback for the couchbase calls
void CouchbaseAdmin::bind_get_callback(CallbackInterface gc)
{
retrieval = gc;
}
//Bind the Storage Callback for the couchbase calls
void CouchbaseAdmin::bind_storage_callback(CallbackInterface sc)
{
storage = sc;
}
//Bind the Delete Callback for the couchbase calls
void CouchbaseAdmin::bind_delete_callback(CallbackInterface dc)
{
deletion = dc;
}
lcb_t CouchbaseAdmin::get_instance ()
{
return private_instance;
}
void CouchbaseAdmin::wait ()
{
logging->info("CB_Admin:DB: Clear Function Stack Called");
lcb_wait(private_instance);
logging->info("CB_Admin:Done waiting");
}
<|endoftext|> |
<commit_before>#pragma once
#include <glm>
#include <vector>
#include <algorithm>
#include <cstdint>
#include <KDTree3D.hpp>
namespace haste {
namespace v2 {
using std::vector;
using std::move;
using std::swap;
using std::pair;
using std::make_pair;
using std::uint32_t;
inline size_t max_axis(const pair<vec3, vec3>& aabb) {
vec3 diff = abs(aabb.first - aabb.second);
if (diff.x < diff.y) {
return diff.y < diff.z ? 2 : 1;
}
else {
return diff.x < diff.z ? 2 : 0;
}
}
template <class T> class KDTree3D {
private:
struct QueryKState {
T* heap;
size_t capacity;
size_t size;
float limit;
vec3 query;
};
struct Point {
vec3 position;
uint32_t _axis;
size_t axis() const {
return _axis;
}
void setAxis(size_t axis) {
_axis = axis;
}
float operator[](size_t index) const {
return position[index];
}
};
static const size_t leaf = 3;
public:
KDTree3D() { }
KDTree3D(vector<T>&& that) {
_data = move(that);
_points.resize(_data.size());
if (!_points.empty()) {
vec3 lower = _points[0].position, upper = _points[0].position;
for (size_t i = 0; i < _data.size(); ++i) {
_points[i].position = _data[i].position();
lower = min(lower, _data[i].position());
upper = max(upper, _data[i].position());
}
vector<size_t> X(_points.size());
vector<size_t> Y(_points.size());
vector<size_t> Z(_points.size());
vector<size_t> unique(_points.size());
vector<size_t> scratch(_points.size());
iota(X);
iota(Y);
iota(Z);
iota(unique);
sort<0>(X, unique, _points);
sort<1>(Y, unique, _points);
sort<2>(Z, unique, _points);
size_t* ranges[3] = {
X.data(),
Y.data(),
Z.data()
};
build(
0,
_points.size(),
make_pair(lower, upper),
ranges,
unique.data(),
scratch.data());
for (size_t i = 0; i < _points.size(); ++i) {
size_t j = i;
size_t k = X[j];
while (k != X[k]) {
std::swap(_points[j].position, _points[X[j]].position);
swap(_data[j], _data[X[j]]);
// _flags.swap(j, X[j]);
X[j] = j;
j = k;
k = X[k];
}
}
}
}
KDTree3D(const vector<T>& that)
: KDTree3D(vector<T>(that)) { }
size_t query_k(T* dst, const vec3& q, size_t k, float d) const {
QueryKState state;
state.heap = dst;
state.capacity = k;
state.size = 0;
state.limit = d * d;
state.query = q;
query_k(state, 0, _data.size());
return state.size;
}
template <class Callback> void rQuery(
Callback callback,
const vec3& query,
const float radius) const
{
// As the tree is balanced, assuming no more than 2^32 elements
// the stack will be no bigger than 32.
struct Stack {
size_t begin;
size_t end;
};
Stack stack[32];
stack[0].begin = 0;
stack[0].end = _points.size();
size_t stackSize = 1;
const float radiusSq = radius * radius;
while (stackSize) {
size_t begin = stack[stackSize - 1].begin;
size_t end = stack[stackSize - 1].end;
if (end == begin) {
--stackSize;
continue;
}
size_t median = begin + (end - begin) / 2;
size_t axis = _points[median].axis();
vec3 point = _points[median].position;
float distanceSq = distance2(query, point);
if (distanceSq < radiusSq) {
callback(_data[median]);
if (axis != leaf) {
++stackSize;
stack[stackSize - 2].begin = begin;
stack[stackSize - 2].end = median;
stack[stackSize - 1].begin = median + 1;
stack[stackSize - 1].end = end;
}
else {
--stackSize;
}
}
else if (axis != leaf) {
float axisDistance = query[axis] - point[axis];
float axisDistanceSq = axisDistance * axisDistance;
if (axisDistance < 0.0) {
stack[stackSize - 1].begin = begin;
stack[stackSize - 1].end = median;
if (axisDistanceSq < radiusSq) {
stack[stackSize].begin = median + 1;
stack[stackSize].end = end;
++stackSize;
}
}
else {
stack[stackSize - 1].begin = median + 1;
stack[stackSize - 1].end = end;
if (axisDistanceSq < radiusSq) {
stack[stackSize].begin = begin;
stack[stackSize].end = median;
++stackSize;
}
}
}
else {
--stackSize;
}
}
}
size_t rQuery(T* result, const vec3& query, const float radius) const {
size_t itr = 0;
auto callback = [&](const T& value) {
result[itr] = value;
++itr;
};
rQuery(callback, query, radius);
return itr;
}
const T* data() const {
return _data.data();
}
size_t size() const {
return _data.size();
}
private:
vector<T> _data;
vector<Point> _points;
BitfieldVector<2> _axes;
size_t query_k(
QueryKState& state,
size_t begin,
size_t end) const
{
if (end != begin) {
size_t median = begin + (end - begin) / 2;
size_t axis = _points[median].axis();
vec3 point = position(_data[median]);
float query_dist = distance2(point, state.query);
auto less = [&](const T& a, const T& b) -> bool {
return distance2(position(a), state.query) < distance2(position(b), state.query);
};
if (query_dist < state.limit) {
if (state.size < state.capacity) {
state.heap[state.size] = _data[median];
++state.size;
std::push_heap(state.heap, state.heap + state.size, less);
if (state.size == state.capacity) {
state.limit = min(
state.limit,
distance2(position(state.heap[0]), state.query));
}
}
else {
std::pop_heap(state.heap, state.heap + state.size, less);
state.heap[state.size - 1] = _data[median];
std::push_heap(state.heap, state.heap + state.size, less);
state.limit = min(
state.limit,
distance2(position(state.heap[0]), state.query));
}
}
if (axis != 3) {
float split_dist = state.query[axis] - _data[median][axis];
if (split_dist < 0.0) {
query_k(state, begin, median);
if (split_dist * split_dist < state.limit) {
query_k(state, median + 1, end);
}
}
else {
query_k(state, median + 1, end);
if (split_dist * split_dist < state.limit) {
query_k(state, begin, median);
}
}
}
}
}
static void iota(vector<size_t>& a) {
for (size_t i = 0; i < a.size(); ++i) {
a[i] = i;
}
}
template <size_t D> static void sort(
vector<size_t>& v,
const vector<size_t>& unique,
const vector<Point>& data) {
std::sort(v.begin(), v.end(), [&](size_t a, size_t b) -> bool {
return data[a][D] == data[b][D] ? unique[a] < unique[b] : data[a][D] < data[b][D];
});
}
void rearrange(
size_t axis,
size_t begin,
size_t end,
size_t median,
size_t* subranges[3],
size_t* unique,
size_t* scratch)
{
size_t median_index = subranges[axis][median];
for (size_t j = 0; j < 3; ++j) {
if (axis != j) {
size_t* subrange = subranges[j];
size_t itr = begin;
while (subrange[itr] != median_index) {
++itr;
}
while (itr < median) {
swap(subrange[itr], subrange[itr + 1]);
++itr;
}
while (median < itr) {
swap(subrange[itr - 1], subrange[itr]);
--itr;
}
}
}
auto less = [&](size_t a, size_t b) -> bool {
return _points[a][axis] == _points[b][axis]
? unique[a] < unique[b]
: _points[a][axis] < _points[b][axis];
};
for (size_t j = 0; j < 3; ++j) {
size_t* subrange = subranges[j];
for (size_t i = begin; i < end; ++i) {
scratch[i] = subrange[i];
}
size_t lst_dst = begin;
size_t geq_dst = median + 1;
size_t lst_src = begin;
size_t geq_src = median + 1;
while (lst_src < median) {
if (less(scratch[lst_src], median_index)) {
subrange[lst_dst] = scratch[lst_src];
++lst_dst;
}
else {
subrange[geq_dst] = scratch[lst_src];
++geq_dst;
}
++lst_src;
}
while (geq_src < end) {
if (less(scratch[geq_src], median_index)) {
subrange[lst_dst] = scratch[geq_src];
++lst_dst;
}
else {
subrange[geq_dst] = scratch[geq_src];
++geq_dst;
}
++geq_src;
}
}
}
void build(
size_t begin,
size_t end,
const pair<vec3, vec3>& aabb,
size_t* subranges[3],
size_t* unique,
size_t* scratch)
{
size_t size = end - begin;
if (size > 1) {
size_t axis = max_axis(aabb);
size_t median = begin + size / 2;
rearrange(axis, begin, end, median, subranges, unique, scratch);
_points[median].setAxis(axis);
pair<vec3, vec3> left_aabb = aabb, right_aabb = aabb;
left_aabb.second[axis] = _points[median][axis];
right_aabb.first[axis] = _points[median][axis];
build(begin, median, left_aabb, subranges, unique, scratch);
build(median + 1, end, right_aabb, subranges, unique, scratch);
}
else if (size == 1) {
_points[begin].setAxis(leaf);
}
}
static vec3 position(const T& x) {
return vec3(x[0], x[1], x[2]);
}
};
}
}
<commit_msg>52% improvement.<commit_after>#pragma once
#include <glm>
#include <vector>
#include <algorithm>
#include <cstdint>
#include <KDTree3D.hpp>
namespace haste {
namespace v2 {
using std::vector;
using std::move;
using std::swap;
using std::pair;
using std::make_pair;
using std::uint32_t;
inline size_t max_axis(const pair<vec3, vec3>& aabb) {
vec3 diff = abs(aabb.first - aabb.second);
if (diff.x < diff.y) {
return diff.y < diff.z ? 2 : 1;
}
else {
return diff.x < diff.z ? 2 : 0;
}
}
template <class T> class KDTree3D {
private:
struct QueryKState {
T* heap;
size_t capacity;
size_t size;
float limit;
vec3 query;
};
struct Point {
vec3 position;
float operator[](size_t index) const {
return position[index];
}
};
static const size_t leaf = 3;
public:
KDTree3D() { }
KDTree3D(vector<T>&& that) {
_data = move(that);
_points.resize(_data.size());
_axes.resize(_data.size());
if (!_points.empty()) {
vec3 lower = _points[0], upper = _points[0];
for (size_t i = 0; i < _data.size(); ++i) {
_points[i] = _data[i].position();
lower = min(lower, _data[i].position());
upper = max(upper, _data[i].position());
}
vector<size_t> X(_points.size());
vector<size_t> Y(_points.size());
vector<size_t> Z(_points.size());
vector<size_t> unique(_points.size());
vector<size_t> scratch(_points.size());
iota(X);
iota(Y);
iota(Z);
iota(unique);
sort<0>(X, unique, _points);
sort<1>(Y, unique, _points);
sort<2>(Z, unique, _points);
size_t* ranges[3] = {
X.data(),
Y.data(),
Z.data()
};
build(
0,
_points.size(),
make_pair(lower, upper),
ranges,
unique.data(),
scratch.data());
for (size_t i = 0; i < _points.size(); ++i) {
size_t j = i;
size_t k = X[j];
while (k != X[k]) {
std::swap(_points[j], _points[X[j]]);
swap(_data[j], _data[X[j]]);
// _flags.swap(j, X[j]);
X[j] = j;
j = k;
k = X[k];
}
}
}
}
KDTree3D(const vector<T>& that)
: KDTree3D(vector<T>(that)) { }
size_t query_k(T* dst, const vec3& q, size_t k, float d) const {
QueryKState state;
state.heap = dst;
state.capacity = k;
state.size = 0;
state.limit = d * d;
state.query = q;
query_k(state, 0, _data.size());
return state.size;
}
template <class Callback> void rQuery(
Callback callback,
const vec3& query,
const float radius) const
{
// As the tree is balanced, assuming no more than 2^32 elements
// the stack will be no bigger than 32.
struct Stack {
size_t begin;
size_t end;
};
Stack stack[32];
stack[0].begin = 0;
stack[0].end = _points.size();
size_t stackSize = 1;
const float radiusSq = radius * radius;
while (stackSize) {
size_t begin = stack[stackSize - 1].begin;
size_t end = stack[stackSize - 1].end;
if (end == begin) {
--stackSize;
continue;
}
size_t median = begin + (end - begin) / 2;
size_t axis = _axes.get(median);
vec3 point = _points[median];
float distanceSq = distance2(query, point);
if (distanceSq < radiusSq) {
callback(_data[median]);
if (axis != leaf) {
++stackSize;
stack[stackSize - 2].begin = begin;
stack[stackSize - 2].end = median;
stack[stackSize - 1].begin = median + 1;
stack[stackSize - 1].end = end;
}
else {
--stackSize;
}
}
else if (axis != leaf) {
float axisDistance = query[axis] - point[axis];
float axisDistanceSq = axisDistance * axisDistance;
if (axisDistance < 0.0) {
stack[stackSize - 1].begin = begin;
stack[stackSize - 1].end = median;
if (axisDistanceSq < radiusSq) {
stack[stackSize].begin = median + 1;
stack[stackSize].end = end;
++stackSize;
}
}
else {
stack[stackSize - 1].begin = median + 1;
stack[stackSize - 1].end = end;
if (axisDistanceSq < radiusSq) {
stack[stackSize].begin = begin;
stack[stackSize].end = median;
++stackSize;
}
}
}
else {
--stackSize;
}
}
}
size_t rQuery(T* result, const vec3& query, const float radius) const {
size_t itr = 0;
auto callback = [&](const T& value) {
result[itr] = value;
++itr;
};
rQuery(callback, query, radius);
return itr;
}
const T* data() const {
return _data.data();
}
size_t size() const {
return _data.size();
}
private:
vector<T> _data;
vector<vec3> _points;
BitfieldVector<2> _axes;
size_t query_k(
QueryKState& state,
size_t begin,
size_t end) const
{
if (end != begin) {
size_t median = begin + (end - begin) / 2;
size_t axis = _axes.get(median);
vec3 point = position(_data[median]);
float query_dist = distance2(point, state.query);
auto less = [&](const T& a, const T& b) -> bool {
return distance2(position(a), state.query) < distance2(position(b), state.query);
};
if (query_dist < state.limit) {
if (state.size < state.capacity) {
state.heap[state.size] = _data[median];
++state.size;
std::push_heap(state.heap, state.heap + state.size, less);
if (state.size == state.capacity) {
state.limit = min(
state.limit,
distance2(position(state.heap[0]), state.query));
}
}
else {
std::pop_heap(state.heap, state.heap + state.size, less);
state.heap[state.size - 1] = _data[median];
std::push_heap(state.heap, state.heap + state.size, less);
state.limit = min(
state.limit,
distance2(position(state.heap[0]), state.query));
}
}
if (axis != 3) {
float split_dist = state.query[axis] - _data[median][axis];
if (split_dist < 0.0) {
query_k(state, begin, median);
if (split_dist * split_dist < state.limit) {
query_k(state, median + 1, end);
}
}
else {
query_k(state, median + 1, end);
if (split_dist * split_dist < state.limit) {
query_k(state, begin, median);
}
}
}
}
}
static void iota(vector<size_t>& a) {
for (size_t i = 0; i < a.size(); ++i) {
a[i] = i;
}
}
template <size_t D> static void sort(
vector<size_t>& v,
const vector<size_t>& unique,
const vector<vec3>& data) {
std::sort(v.begin(), v.end(), [&](size_t a, size_t b) -> bool {
return data[a][D] == data[b][D] ? unique[a] < unique[b] : data[a][D] < data[b][D];
});
}
void rearrange(
size_t axis,
size_t begin,
size_t end,
size_t median,
size_t* subranges[3],
size_t* unique,
size_t* scratch)
{
size_t median_index = subranges[axis][median];
for (size_t j = 0; j < 3; ++j) {
if (axis != j) {
size_t* subrange = subranges[j];
size_t itr = begin;
while (subrange[itr] != median_index) {
++itr;
}
while (itr < median) {
swap(subrange[itr], subrange[itr + 1]);
++itr;
}
while (median < itr) {
swap(subrange[itr - 1], subrange[itr]);
--itr;
}
}
}
auto less = [&](size_t a, size_t b) -> bool {
return _points[a][axis] == _points[b][axis]
? unique[a] < unique[b]
: _points[a][axis] < _points[b][axis];
};
for (size_t j = 0; j < 3; ++j) {
size_t* subrange = subranges[j];
for (size_t i = begin; i < end; ++i) {
scratch[i] = subrange[i];
}
size_t lst_dst = begin;
size_t geq_dst = median + 1;
size_t lst_src = begin;
size_t geq_src = median + 1;
while (lst_src < median) {
if (less(scratch[lst_src], median_index)) {
subrange[lst_dst] = scratch[lst_src];
++lst_dst;
}
else {
subrange[geq_dst] = scratch[lst_src];
++geq_dst;
}
++lst_src;
}
while (geq_src < end) {
if (less(scratch[geq_src], median_index)) {
subrange[lst_dst] = scratch[geq_src];
++lst_dst;
}
else {
subrange[geq_dst] = scratch[geq_src];
++geq_dst;
}
++geq_src;
}
}
}
void build(
size_t begin,
size_t end,
const pair<vec3, vec3>& aabb,
size_t* subranges[3],
size_t* unique,
size_t* scratch)
{
size_t size = end - begin;
if (size > 1) {
size_t axis = max_axis(aabb);
size_t median = begin + size / 2;
rearrange(axis, begin, end, median, subranges, unique, scratch);
_axes.set(median, axis);
pair<vec3, vec3> left_aabb = aabb, right_aabb = aabb;
left_aabb.second[axis] = _points[median][axis];
right_aabb.first[axis] = _points[median][axis];
build(begin, median, left_aabb, subranges, unique, scratch);
build(median + 1, end, right_aabb, subranges, unique, scratch);
}
else if (size == 1) {
_axes.set(begin, leaf);
}
}
static vec3 position(const T& x) {
return vec3(x[0], x[1], x[2]);
}
};
}
}
<|endoftext|> |
<commit_before>/************************************************************
COSC 501
Elliott Plack
19 NOV 2013 Due 25 NOV 2013
Problem: Create a 1-dimensional array with n elements; get
the size of the array as user input (validate!), max size
should be 10 (declared as class constant). Perform a
variety of functions with the array.
Algorithm: Get array size from user, validate, get values,
perform functions.
************************************************************/
#include <iostream>
#include <iomanip>
using namespace std;
// various array handling functions
float average(float numbers[], int arraySize);
void even(float numbers[], int arraySize);
void odd(float numbers[], int arraySize);
float evenSum(float numbers[], int arraySize);
float oddSum(float numbers[], int arraySize);
int main()
{
// redo with arrays
// copy back in commit c864814b032eff90c493701556f869aff79629d4
//https://github.com/talllguy/Lab12/blob/c864814b032eff90c493701556f869aff79629d4/Lab12array.cpp
// variables
int arraySize = 0; // size of the array
const int maxArraySize = 10; // max size of the array
float averageNum(0), evenSumNum(0), oddSumNum(0); // variables that returns will be stored in
// array size determination
cout << "This program does a number of calculations on an array.\n"
<< "Enter the size of the array up to 10.\n";
while (!(cin >> arraySize) || arraySize < 1 || arraySize > maxArraySize) // validate
{
cin.clear(); // Clear the error flags
cin.ignore(100, '\n'); // Remove unwanted characters from buffer
cout << "\aEnter a positive integer, less than 10: "; // Re-issue the prompt
}
cout << "Now enter the " << arraySize << " values.\n";
// set up array
float *numbers;
numbers = new float[arraySize]; // declare numbers array with 'elements' (n) positions
// loop to fill array
for (int i = 0; i < arraySize; i++)
{
cout << (i + 1) << ": "; // display the iterator + 1 since it begins as 0
while ((!(cin >> numbers[i]))) //detects errors in input
{
cin.clear(); // Clear the error flags
cin.ignore(100, '\n'); // Remove unwanted characters from buffer
cout << "\aInput Error. Please enter a number only.\n"; // if error, sound the alarm
cout << (i + 1) << ": ";
}
}
// display array
cout << "\nThe array elements are:\n";
cout << " "; // indent separator for clarity
for (int i = 0; i < arraySize; i++) // test loop to output variables in positions
{
cout << numbers[i] << " "; // space separated
}
cout << endl; // break in output
// output average
averageNum = average(numbers, arraySize);
cout << "The average value = " << averageNum << endl;
// even subscripts
even(numbers, arraySize);
// even sum
cout << "\nThe sum of the elements with even subscripts = " << evenSum(numbers, arraySize) << endl;
// odd subscripts
odd(numbers, arraySize);
return 0;
}
float average(float numbers[], int arraySize)
{
float sum(0), average(0); // define variables
for (int i = 0; i < arraySize; i++)
{
sum += numbers[i];
}
average = (sum / arraySize);
return average;
}
void even(float numbers[], int arraySize) // display even values
{
int temp = 0;
// format output
cout << "Index Value\n"
<< "=============\n";
// even check subs
for (int i = 0; i < arraySize; i++)
{
temp = (int)numbers[i] % 2; // if integer version of value in numbers array is even..
if (temp == 0)
cout << setw(5) << (i+1) << setw(8) << numbers[i] << endl; // output the value
}
}
void odd(float numbers[], int arraySize) // display odd values
{
int temp = 0;
// format output
cout << "Index Value\n"
<< "=============\n";
// even check subs
for (int i = 0; i < arraySize; i++)
{
temp = (int)numbers[i] % 2; // if integer version of value in numbers array is odd..
if (temp != 0)
cout << setw(5) << (i+1) << setw(8) << numbers[i] << endl; // output the value
}
}
float evenSum(float numbers[], int arraySize) // return even sums
{
int temp = 0;
float sum(0), average(0); // define variables
for (int i = 0; i < arraySize; i++)
{
temp = (int)numbers[i] % 2; // find mod array index div by 2
if (temp == 0)
sum += numbers[i]; // if mod is zero (even) add to sum)
sum += numbers[i];
}
return sum;
}
float oddSum(float numbers[], int arraySize) // return odd sums
{
return 0;
}<commit_msg>success<commit_after>/************************************************************
COSC 501
Elliott Plack
19 NOV 2013 Due 25 NOV 2013
Problem: Create a 1-dimensional array with n elements; get
the size of the array as user input (validate!), max size
should be 10 (declared as class constant). Perform a
variety of functions with the array.
Algorithm: Get array size from user, validate, get values,
perform functions.
************************************************************/
#include <iostream>
#include <iomanip>
using namespace std;
// various array handling functions
float average(float numbers[], int arraySize);
void even(float numbers[], int arraySize);
void odd(float numbers[], int arraySize);
float evenSum(float numbers[], int arraySize);
float oddSum(float numbers[], int arraySize);
int main()
{
// redo with arrays
// copy back in commit c864814b032eff90c493701556f869aff79629d4
//https://github.com/talllguy/Lab12/blob/c864814b032eff90c493701556f869aff79629d4/Lab12array.cpp
// variables
int arraySize = 0; // size of the array
const int maxArraySize = 10; // max size of the array
float averageNum(0), evenSumNum(0), oddSumNum(0); // variables that returns will be stored in
// array size determination
cout << "This program does a number of calculations on an array.\n"
<< "Enter the size of the array up to 10.\n";
while (!(cin >> arraySize) || arraySize < 1 || arraySize > maxArraySize) // validate
{
cin.clear(); // Clear the error flags
cin.ignore(100, '\n'); // Remove unwanted characters from buffer
cout << "\aEnter a positive integer, less than 10: "; // Re-issue the prompt
}
cout << "Now enter the " << arraySize << " values.\n";
// set up array
float *numbers;
numbers = new float[arraySize]; // declare numbers array with 'elements' (n) positions
// loop to fill array
for (int i = 0; i < arraySize; i++)
{
cout << (i + 1) << ": "; // display the iterator + 1 since it begins as 0
while ((!(cin >> numbers[i]))) //detects errors in input
{
cin.clear(); // Clear the error flags
cin.ignore(100, '\n'); // Remove unwanted characters from buffer
cout << "\aInput Error. Please enter a number only.\n"; // if error, sound the alarm
cout << (i + 1) << ": ";
}
}
// display array
cout << "\nThe array elements are:\n";
cout << " "; // indent separator for clarity
for (int i = 0; i < arraySize; i++) // test loop to output variables in positions
{
cout << numbers[i] << " "; // space separated
}
cout << endl; // break in output
// output average
averageNum = average(numbers, arraySize);
cout << "The average value = " << averageNum << endl;
// even subscripts
even(numbers, arraySize);
// even sum
cout << "The sum of the elements with even subscripts = " << evenSum(numbers, arraySize) << endl;
// odd subscripts
odd(numbers, arraySize);
// odd sum
cout << "The sum of the elements with odd subscripts = " << oddSum(numbers, arraySize) << endl;
return 0;
}
float average(float numbers[], int arraySize)
{
float sum(0), average(0); // define variables
for (int i = 0; i < arraySize; i++)
{
sum += numbers[i];
}
average = (sum / arraySize);
return average;
}
void even(float numbers[], int arraySize) // display even values
{
int temp = 0;
// format output
cout << "The elements with even subscripts are:\n"
<< "Index Value\n"
<< "=============\n";
// even check subs
for (int i = 0; i < arraySize; i++)
{
temp = (int)numbers[i] % 2; // if integer version of value in numbers array is even..
if (temp == 0)
cout << setw(5) << (i+1) << setw(8) << numbers[i] << endl; // output the value
}
}
void odd(float numbers[], int arraySize) // display odd values
{
int temp = 0;
// format output
cout << "The elements with odd subscripts are:\n"
<< "Index Value\n"
<< "=============\n";
// even check subs
for (int i = 0; i < arraySize; i++)
{
temp = (int)numbers[i] % 2; // if integer version of value in numbers array is odd..
if (temp != 0)
cout << setw(5) << (i+1) << setw(8) << numbers[i] << endl; // output the value
}
}
float evenSum(float numbers[], int arraySize) // return even sums
{
int temp = 0;
float sum(0), average(0); // define variables
for (int i = 0; i < arraySize; i++)
{
temp = (int)numbers[i] % 2; // find mod array index div by 2
if (temp == 0)
sum += numbers[i]; // if mod is zero (even) add to sum)
}
return sum;
}
float oddSum(float numbers[], int arraySize) // return odd sums
{
int temp = 0;
float sum(0), average(0); // define variables
for (int i = 0; i < arraySize; i++)
{
temp = (int)numbers[i] % 2; // find mod array index div by 2
if (temp != 0)
sum += numbers[i]; // if mod is not zero (odd) add to sum)
}
return sum;
}<|endoftext|> |
<commit_before>/*************************************************************************
*
* $RCSfile: testcomponent.cxx,v $
*
* $Revision: 1.6 $
*
* last change: $Author: jl $ $Date: 2001-03-19 10:20:56 $
*
* The Contents of this file are made available subject to the terms of
* either of the following licenses
*
* - GNU Lesser General Public License Version 2.1
* - Sun Industry Standards Source License Version 1.1
*
* Sun Microsystems Inc., October, 2000
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2000 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
*
* Sun Industry Standards Source License Version 1.1
* =================================================
* The contents of this file are subject to the Sun Industry Standards
* Source License Version 1.1 (the "License"); You may not use this file
* except in compliance with the License. You may obtain a copy of the
* License at http://www.openoffice.org/license.html.
*
* Software provided under this License is provided on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
* WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
* MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
* See the License for the specific provisions governing your rights and
* obligations concerning the Software.
*
* The Initial Developer of the Original Code is: Sun Microsystems, Inc.
*
* Copyright: 2000 by Sun Microsystems, Inc.
*
* All Rights Reserved.
*
* Contributor(s): _______________________________________
*
*
************************************************************************/
//------------------------------------------------------
// testcomponent - Loads a service and its testcomponent from dlls performs a test.
// Expands the dll-names depending on the actual environment.
// Example : testcomponent stardiv.uno.io.Pipe stm
//
// Therefor the testcode must exist in teststm and the testservice must be named test.stardiv.uno.io.Pipe
//
#include <stdio.h>
#include <com/sun/star/registry/XImplementationRegistration.hpp>
#include <com/sun/star/lang/XComponent.hpp>
#include <com/sun/star/test/XSimpleTest.hpp>
#include <cppuhelper/servicefactory.hxx>
#include <assert.h>
using namespace ::rtl;
using namespace ::cppu;
using namespace ::com::sun::star::uno;
using namespace ::com::sun::star::test;
using namespace ::com::sun::star::lang;
using namespace ::com::sun::star::registry;
// Needed to switch on solaris threads
int main (int argc, char **argv)
{
if( argc < 3) {
printf( "usage : testcomponent service dll [additional dlls]\n" );
exit( 0 );
}
// create service manager
Reference< XMultiServiceFactory > xSMgr = createRegistryServiceFactory(
OUString( RTL_CONSTASCII_USTRINGPARAM( "applicat.rdb" ) ) );
Reference < XImplementationRegistration > xReg;
Reference < XSimpleRegistry > xSimpleReg;
try
{
// Create registration service
Reference < XInterface > x = xSMgr->createInstance(
OUString::createFromAscii( "com.sun.star.registry.ImplementationRegistration" ) );
xReg = Reference< XImplementationRegistration > ( x , UNO_QUERY );
}
catch( Exception & ) {
printf( "Couldn't create ImplementationRegistration service\n" );
exit(1);
}
sal_Char szBuf[1024];
OString sTestName;
try
{
// Load dll for the tested component
for( int n = 2 ; n <argc ; n ++ ) {
#ifdef SAL_W32
OUString aDllName = OStringToOUString( argv[n] , RTL_TEXTENCODING_ASCII_US );
#else
OUString aDllName = OUString::createFromAscii("lib");
aDllName += OStringToOUString( argv[n] , RTL_TEXTENCODING_ASCII_US );
aDllName += OUString::createFromAscii(".so");
#endif
xReg->registerImplementation(
OUString::createFromAscii( "com.sun.star.loader.SharedLibrary" ),
aDllName,
xSimpleReg );
}
}
catch( Exception &e ) {
printf( "Couldn't reach dll %s\n" , szBuf );
printf( "%s\n" , OUStringToOString( e.Message , RTL_TEXTENCODING_ASCII_US ).getStr() );
exit(1);
}
try
{
// Load dll for the test component
sTestName = "test";
sTestName += argv[2];
#ifdef SAL_W32
OUString aDllName = OStringToOUString( sTestName , RTL_TEXTENCODING_ASCII_US );
#else
OUString aDllName = OUString::createFromAscii("lib");
aDllName += OStringToOUString( sTestName , RTL_TEXTENCODING_ASCII_US );
aDllName += OUString::createFromAscii(".so");
#endif
xReg->registerImplementation(
OUString::createFromAscii( "com.sun.star.loader.SharedLibrary" ) ,
aDllName,
xSimpleReg );
}
catch( Exception & e )
{
printf( "Couldn't reach dll %s\n" , szBuf );
exit(1);
}
// Instantiate test service
sTestName = "test.";
sTestName += argv[1];
Reference < XInterface > xIntTest =
xSMgr->createInstance( OStringToOUString( sTestName , RTL_TEXTENCODING_ASCII_US ) );
Reference< XSimpleTest > xTest( xIntTest , UNO_QUERY );
if( ! xTest.is() ) {
printf( "Couldn't instantiate test service \n" );
exit( 1 );
}
sal_Int32 nHandle = 0;
sal_Int32 nNewHandle;
sal_Int32 nErrorCount = 0;
sal_Int32 nWarningCount = 0;
// loop until all test are performed
while( nHandle != -1 )
{
// Instantiate serivce
Reference< XInterface > x =
xSMgr->createInstance( OStringToOUString( argv[1] , RTL_TEXTENCODING_ASCII_US ) );
if( ! x.is() )
{
printf( "Couldn't instantiate service !\n" );
exit( 1 );
}
// do the test
try
{
nNewHandle = xTest->test(
OStringToOUString( argv[1] , RTL_TEXTENCODING_ASCII_US ) , x , nHandle );
}
catch( Exception & e ) {
OString o = OUStringToOString( e.Message, RTL_TEXTENCODING_ASCII_US );
printf( "testcomponent : uncaught exception %s\n" , o.getStr() );
exit(1);
}
catch( ... )
{
printf( "testcomponent : uncaught unknown exception\n" );
exit(1);
}
// print errors and warning
Sequence<OUString> seqErrors = xTest->getErrors();
Sequence<OUString> seqWarnings = xTest->getWarnings();
if( seqWarnings.getLength() > nWarningCount )
{
printf( "Warnings during test %d!\n" , nHandle );
for( ; nWarningCount < seqWarnings.getLength() ; nWarningCount ++ )
{
OString o = OUStringToOString(
seqWarnings.getArray()[nWarningCount], RTL_TEXTENCODING_ASCII_US );
printf( "Warning\n%s\n---------\n" , o.getStr() );
}
}
if( seqErrors.getLength() > nErrorCount ) {
printf( "Errors during test %d!\n" , nHandle );
for( ; nErrorCount < seqErrors.getLength() ; nErrorCount ++ )
{
OString o = OUStringToOString(
seqErrors.getArray()[nErrorCount], RTL_TEXTENCODING_ASCII_US );
printf( "%s\n" , o.getStr() );
}
}
nHandle = nNewHandle;
}
if( xTest->testPassed() ) {
printf( "Test passed !\n" );
}
else {
printf( "Test failed !\n" );
}
Reference <XComponent > rComp( xSMgr , UNO_QUERY );
rComp->dispose();
return 0;
}
<commit_msg>INTEGRATION: CWS dbgmacros1 (1.6.52); FILE MERGED 2003/04/09 11:59:07 kso 1.6.52.1: #108413# - debug macro unification.<commit_after>/*************************************************************************
*
* $RCSfile: testcomponent.cxx,v $
*
* $Revision: 1.7 $
*
* last change: $Author: vg $ $Date: 2003-04-15 15:59:08 $
*
* The Contents of this file are made available subject to the terms of
* either of the following licenses
*
* - GNU Lesser General Public License Version 2.1
* - Sun Industry Standards Source License Version 1.1
*
* Sun Microsystems Inc., October, 2000
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2000 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
*
* Sun Industry Standards Source License Version 1.1
* =================================================
* The contents of this file are subject to the Sun Industry Standards
* Source License Version 1.1 (the "License"); You may not use this file
* except in compliance with the License. You may obtain a copy of the
* License at http://www.openoffice.org/license.html.
*
* Software provided under this License is provided on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
* WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
* MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
* See the License for the specific provisions governing your rights and
* obligations concerning the Software.
*
* The Initial Developer of the Original Code is: Sun Microsystems, Inc.
*
* Copyright: 2000 by Sun Microsystems, Inc.
*
* All Rights Reserved.
*
* Contributor(s): _______________________________________
*
*
************************************************************************/
//------------------------------------------------------
// testcomponent - Loads a service and its testcomponent from dlls performs a test.
// Expands the dll-names depending on the actual environment.
// Example : testcomponent stardiv.uno.io.Pipe stm
//
// Therefor the testcode must exist in teststm and the testservice must be named test.stardiv.uno.io.Pipe
//
#include <stdio.h>
#include <com/sun/star/registry/XImplementationRegistration.hpp>
#include <com/sun/star/lang/XComponent.hpp>
#include <com/sun/star/test/XSimpleTest.hpp>
#include <cppuhelper/servicefactory.hxx>
using namespace ::rtl;
using namespace ::cppu;
using namespace ::com::sun::star::uno;
using namespace ::com::sun::star::test;
using namespace ::com::sun::star::lang;
using namespace ::com::sun::star::registry;
// Needed to switch on solaris threads
int main (int argc, char **argv)
{
if( argc < 3) {
printf( "usage : testcomponent service dll [additional dlls]\n" );
exit( 0 );
}
// create service manager
Reference< XMultiServiceFactory > xSMgr = createRegistryServiceFactory(
OUString( RTL_CONSTASCII_USTRINGPARAM( "applicat.rdb" ) ) );
Reference < XImplementationRegistration > xReg;
Reference < XSimpleRegistry > xSimpleReg;
try
{
// Create registration service
Reference < XInterface > x = xSMgr->createInstance(
OUString::createFromAscii( "com.sun.star.registry.ImplementationRegistration" ) );
xReg = Reference< XImplementationRegistration > ( x , UNO_QUERY );
}
catch( Exception & ) {
printf( "Couldn't create ImplementationRegistration service\n" );
exit(1);
}
sal_Char szBuf[1024];
OString sTestName;
try
{
// Load dll for the tested component
for( int n = 2 ; n <argc ; n ++ ) {
#ifdef SAL_W32
OUString aDllName = OStringToOUString( argv[n] , RTL_TEXTENCODING_ASCII_US );
#else
OUString aDllName = OUString::createFromAscii("lib");
aDllName += OStringToOUString( argv[n] , RTL_TEXTENCODING_ASCII_US );
aDllName += OUString::createFromAscii(".so");
#endif
xReg->registerImplementation(
OUString::createFromAscii( "com.sun.star.loader.SharedLibrary" ),
aDllName,
xSimpleReg );
}
}
catch( Exception &e ) {
printf( "Couldn't reach dll %s\n" , szBuf );
printf( "%s\n" , OUStringToOString( e.Message , RTL_TEXTENCODING_ASCII_US ).getStr() );
exit(1);
}
try
{
// Load dll for the test component
sTestName = "test";
sTestName += argv[2];
#ifdef SAL_W32
OUString aDllName = OStringToOUString( sTestName , RTL_TEXTENCODING_ASCII_US );
#else
OUString aDllName = OUString::createFromAscii("lib");
aDllName += OStringToOUString( sTestName , RTL_TEXTENCODING_ASCII_US );
aDllName += OUString::createFromAscii(".so");
#endif
xReg->registerImplementation(
OUString::createFromAscii( "com.sun.star.loader.SharedLibrary" ) ,
aDllName,
xSimpleReg );
}
catch( Exception & e )
{
printf( "Couldn't reach dll %s\n" , szBuf );
exit(1);
}
// Instantiate test service
sTestName = "test.";
sTestName += argv[1];
Reference < XInterface > xIntTest =
xSMgr->createInstance( OStringToOUString( sTestName , RTL_TEXTENCODING_ASCII_US ) );
Reference< XSimpleTest > xTest( xIntTest , UNO_QUERY );
if( ! xTest.is() ) {
printf( "Couldn't instantiate test service \n" );
exit( 1 );
}
sal_Int32 nHandle = 0;
sal_Int32 nNewHandle;
sal_Int32 nErrorCount = 0;
sal_Int32 nWarningCount = 0;
// loop until all test are performed
while( nHandle != -1 )
{
// Instantiate serivce
Reference< XInterface > x =
xSMgr->createInstance( OStringToOUString( argv[1] , RTL_TEXTENCODING_ASCII_US ) );
if( ! x.is() )
{
printf( "Couldn't instantiate service !\n" );
exit( 1 );
}
// do the test
try
{
nNewHandle = xTest->test(
OStringToOUString( argv[1] , RTL_TEXTENCODING_ASCII_US ) , x , nHandle );
}
catch( Exception & e ) {
OString o = OUStringToOString( e.Message, RTL_TEXTENCODING_ASCII_US );
printf( "testcomponent : uncaught exception %s\n" , o.getStr() );
exit(1);
}
catch( ... )
{
printf( "testcomponent : uncaught unknown exception\n" );
exit(1);
}
// print errors and warning
Sequence<OUString> seqErrors = xTest->getErrors();
Sequence<OUString> seqWarnings = xTest->getWarnings();
if( seqWarnings.getLength() > nWarningCount )
{
printf( "Warnings during test %d!\n" , nHandle );
for( ; nWarningCount < seqWarnings.getLength() ; nWarningCount ++ )
{
OString o = OUStringToOString(
seqWarnings.getArray()[nWarningCount], RTL_TEXTENCODING_ASCII_US );
printf( "Warning\n%s\n---------\n" , o.getStr() );
}
}
if( seqErrors.getLength() > nErrorCount ) {
printf( "Errors during test %d!\n" , nHandle );
for( ; nErrorCount < seqErrors.getLength() ; nErrorCount ++ )
{
OString o = OUStringToOString(
seqErrors.getArray()[nErrorCount], RTL_TEXTENCODING_ASCII_US );
printf( "%s\n" , o.getStr() );
}
}
nHandle = nNewHandle;
}
if( xTest->testPassed() ) {
printf( "Test passed !\n" );
}
else {
printf( "Test failed !\n" );
}
Reference <XComponent > rComp( xSMgr , UNO_QUERY );
rComp->dispose();
return 0;
}
<|endoftext|> |
<commit_before>#include "mitkGeometry2DDataVtkMapper3D.h"
#include "mitkPlaneGeometry.h"
#include "mitkDataTree.h"
#include "mitkImageMapper2D.h"
#include "mitkSurfaceData.h"
#include "mitkGeometry2DDataToSurfaceDataFilter.h"
#include "vtkActor.h"
#include "vtkProperty.h"
#include "vtkTexture.h"
#include "vtkPlaneSource.h"
#include "vtkPolyDataMapper.h"
#include "vtkLookupTable.h"
//#include "vtkImageMapToWindowLevelColors";
#include "mitkColorProperty.h"
#include "mitkFloatProperty.h"
#include "mitkLookupTableProperty.h"
#include "mitkLevelWindowProperty.h"
#include "mitkSmartPointerProperty.h"
#include <vtkActor.h>
#include <vtkImageData.h>
#include "pic2vtk.h"
//##ModelId=3E691E09038E
mitk::Geometry2DDataVtkMapper3D::Geometry2DDataVtkMapper3D() : m_DataTreeIterator(NULL), m_LastTextureUpdateTime(0)
{
m_VtkPlaneSource = vtkPlaneSource::New();
m_VtkPolyDataMapper = vtkPolyDataMapper::New();
// m_VtkPolyDataMapper->SetInput(m_VtkPlaneSource->GetOutput());
m_VtkPolyDataMapper->ImmediateModeRenderingOn();
m_Actor = vtkActor::New();
m_Actor->SetMapper(m_VtkPolyDataMapper);
m_Prop3D = m_Actor;
m_Prop3D->Register(NULL);
m_VtkLookupTable = vtkLookupTable::New();
m_VtkLookupTable->SetTableRange (-1024, 4096);
m_VtkLookupTable->SetSaturationRange (0, 0);
m_VtkLookupTable->SetHueRange (0, 0);
m_VtkLookupTable->SetValueRange (0, 1);
m_VtkLookupTable->Build ();
m_VtkLookupTableDefault = m_VtkLookupTable;
m_VtkTexture = vtkTexture::New();
m_VtkTexture->InterpolateOn();
m_VtkTexture->SetLookupTable(m_VtkLookupTable);
m_VtkTexture->MapColorScalarsThroughLookupTableOn();
// m_Actor->SetTexture(axialTexture);
// axialTexture->SetInput(axialSection->GetOutput());
// axialTexture->InterpolateOn();
// axialTexture->SetLookupTable (lut);
// axialTexture->MapColorScalarsThroughLookupTableOn();
//m_VtkPlaneSource = vtkPlaneSource::New();
// m_VtkPlaneSource->SetXResolution(1);
// m_VtkPlaneSource->SetYResolution(1);
// m_VtkPlaneSource->SetOrigin(0.0, 0.0, slice);
// m_VtkPlaneSource->SetPoint1(xDim, 0.0, slice);
// m_VtkPlaneSource->SetPoint2(0.0, yDim, slice);
//m_VtkPolyDataMapper = vtkPolyDataMapper::New();
// m_VtkPolyDataMapper->SetInput(m_VtkPlaneSource->GetOutput());
// m_VtkPolyDataMapper->ImmediateModeRenderingOn();
//axial = vtkActor::New();
// axial->SetMapper(m_VtkPolyDataMapper);
// axial->SetTexture(axialTexture);
}
//##ModelId=3E691E090394
mitk::Geometry2DDataVtkMapper3D::~Geometry2DDataVtkMapper3D()
{
delete m_DataTreeIterator;
m_VtkPlaneSource->Delete();
m_VtkPolyDataMapper->Delete();
m_Actor->Delete();
m_VtkLookupTable->Delete();
m_VtkTexture->Delete();
}
//##ModelId=3E691E090380
const mitk::Geometry2DData *mitk::Geometry2DDataVtkMapper3D::GetInput()
{
if (this->GetNumberOfInputs() < 1)
{
return 0;
}
return static_cast<const mitk::Geometry2DData * > ( GetData() );
}
//##ModelId=3E691E09038A
void mitk::Geometry2DDataVtkMapper3D::Update()
{
}
//##ModelId=3E691E090396
void mitk::Geometry2DDataVtkMapper3D::GenerateOutputInformation()
{
}
//##ModelId=3E691E09038C
void mitk::Geometry2DDataVtkMapper3D::GenerateData()
{
}
//##ModelId=3E6E874F0007
void mitk::Geometry2DDataVtkMapper3D::SetDataIteratorForTexture(mitk::DataTreeIterator* iterator)
{
delete m_DataTreeIterator;
m_DataTreeIterator = iterator->clone();
}
//##ModelId=3EF19F850151
void mitk::Geometry2DDataVtkMapper3D::Update(mitk::BaseRenderer* renderer)
{
if(IsVisible(renderer)==false)
{
m_Actor->VisibilityOff();
return;
}
m_Actor->VisibilityOn();
mitk::Geometry2DData::Pointer input = const_cast<mitk::Geometry2DData*>(this->GetInput());
if(input.IsNotNull())
{
mitk::Geometry2DDataToSurfaceDataFilter::Pointer surfaceCreator;
mitk::SmartPointerProperty::Pointer surfacecreatorprop;
surfacecreatorprop=dynamic_cast<mitk::SmartPointerProperty*>(GetDataTreeNode()->GetProperty("surfacegeometry", renderer).GetPointer());
if( (surfacecreatorprop.IsNull()) ||
(surfacecreatorprop->GetSmartPointer().IsNull()) ||
((surfaceCreator=dynamic_cast<mitk::Geometry2DDataToSurfaceDataFilter*>(surfacecreatorprop->GetSmartPointer().GetPointer())).IsNull())
)
{
surfaceCreator = mitk::Geometry2DDataToSurfaceDataFilter::New();
surfacecreatorprop=new mitk::SmartPointerProperty(surfaceCreator);
GetDataTreeNode()->SetProperty("surfacegeometry", surfacecreatorprop);
}
surfaceCreator->SetInput(input);
int res;
if(GetDataTreeNode()->GetIntProperty("xresolution", res, renderer))
surfaceCreator->SetXResolution(res);
if(GetDataTreeNode()->GetIntProperty("yresolution", res, renderer))
surfaceCreator->SetYResolution(res);
surfaceCreator->Update(); //@FIXME ohne das crash
m_VtkPolyDataMapper->SetInput(surfaceCreator->GetOutput()->GetVtkPolyData());
if(m_DataTreeIterator)
{
mitk::DataTreeIterator* it=m_DataTreeIterator->clone();
while(it->hasNext())
{
it->next();
mitk::DataTreeNode* node=it->get();
mitk::Mapper::Pointer mapper = node->GetMapper(1);
mitk::ImageMapper2D* imagemapper = dynamic_cast<ImageMapper2D*>(mapper.GetPointer());
if((node->IsVisible(renderer)) && (imagemapper))
{
mitk::SmartPointerProperty::Pointer rendererProp = dynamic_cast<mitk::SmartPointerProperty*>(GetDataTreeNode()->GetPropertyList()->GetProperty("renderer").GetPointer());
if(rendererProp.IsNotNull())
{
mitk::BaseRenderer::Pointer renderer = dynamic_cast<mitk::BaseRenderer*>(rendererProp->GetSmartPointer().GetPointer());
if(renderer.IsNotNull())
{
// check for LookupTable
mitk::LookupTableProperty::Pointer lut;
lut = dynamic_cast<mitk::LookupTableProperty*>(node->GetPropertyList()->GetProperty("LookupTable").GetPointer());
if (lut.IsNotNull() )
{
m_VtkLookupTable = lut->GetLookupTable().GetVtkLookupTable();
m_VtkTexture->SetLookupTable(m_VtkLookupTable);
// m_VtkTexture->Modified();
} else {
m_VtkLookupTable = m_VtkLookupTableDefault;
}
// check for level window prop and use it for display if it exists
mitk::LevelWindow levelWindow;
if(node->GetLevelWindow(levelWindow, renderer))
m_VtkLookupTable->SetTableRange(levelWindow.GetMin(),levelWindow.GetMax());
//we have to do this before GenerateAllData() is called there may be
//no RendererInfo for renderer yet, thus GenerateAllData won't update
//the (non-existing) RendererInfo for renderer. By calling GetRendererInfo
//a RendererInfo will be created for renderer (if it does not exist yet).
const ImageMapper2D::RendererInfo* ri=imagemapper->GetRendererInfo(renderer);
imagemapper->GenerateAllData();
if((ri!=NULL) && (m_LastTextureUpdateTime<ri->m_LastUpdateTime))
{
ipPicDescriptor *p=ri->m_Pic;
vtkImageData* vtkimage=Pic2vtk::convert(p);
m_VtkTexture->SetInput(vtkimage); vtkimage->Delete(); vtkimage=NULL;
m_Actor->SetTexture(m_VtkTexture);
m_LastTextureUpdateTime=ri->m_LastUpdateTime;
}
break;
}
}
}
}
}
//apply properties read from the PropertyList
ApplyProperties(m_Actor, renderer);
}
StandardUpdate();
}
<commit_msg>changed internal Property name: lut -> LookupTableProb<commit_after>#include "mitkGeometry2DDataVtkMapper3D.h"
#include "mitkPlaneGeometry.h"
#include "mitkDataTree.h"
#include "mitkImageMapper2D.h"
#include "mitkSurfaceData.h"
#include "mitkGeometry2DDataToSurfaceDataFilter.h"
#include "vtkActor.h"
#include "vtkProperty.h"
#include "vtkTexture.h"
#include "vtkPlaneSource.h"
#include "vtkPolyDataMapper.h"
#include "vtkLookupTable.h"
//#include "vtkImageMapToWindowLevelColors";
#include "mitkColorProperty.h"
#include "mitkFloatProperty.h"
#include "mitkLookupTableProperty.h"
#include "mitkLevelWindowProperty.h"
#include "mitkSmartPointerProperty.h"
#include <vtkActor.h>
#include <vtkImageData.h>
#include "pic2vtk.h"
//##ModelId=3E691E09038E
mitk::Geometry2DDataVtkMapper3D::Geometry2DDataVtkMapper3D() : m_DataTreeIterator(NULL), m_LastTextureUpdateTime(0)
{
m_VtkPlaneSource = vtkPlaneSource::New();
m_VtkPolyDataMapper = vtkPolyDataMapper::New();
// m_VtkPolyDataMapper->SetInput(m_VtkPlaneSource->GetOutput());
m_VtkPolyDataMapper->ImmediateModeRenderingOn();
m_Actor = vtkActor::New();
m_Actor->SetMapper(m_VtkPolyDataMapper);
m_Prop3D = m_Actor;
m_Prop3D->Register(NULL);
m_VtkLookupTable = vtkLookupTable::New();
m_VtkLookupTable->SetTableRange (-1024, 4096);
m_VtkLookupTable->SetSaturationRange (0, 0);
m_VtkLookupTable->SetHueRange (0, 0);
m_VtkLookupTable->SetValueRange (0, 1);
m_VtkLookupTable->Build ();
m_VtkLookupTableDefault = m_VtkLookupTable;
m_VtkTexture = vtkTexture::New();
m_VtkTexture->InterpolateOn();
m_VtkTexture->SetLookupTable(m_VtkLookupTable);
m_VtkTexture->MapColorScalarsThroughLookupTableOn();
// m_Actor->SetTexture(axialTexture);
// axialTexture->SetInput(axialSection->GetOutput());
// axialTexture->InterpolateOn();
// axialTexture->SetLookupTable (lut);
// axialTexture->MapColorScalarsThroughLookupTableOn();
//m_VtkPlaneSource = vtkPlaneSource::New();
// m_VtkPlaneSource->SetXResolution(1);
// m_VtkPlaneSource->SetYResolution(1);
// m_VtkPlaneSource->SetOrigin(0.0, 0.0, slice);
// m_VtkPlaneSource->SetPoint1(xDim, 0.0, slice);
// m_VtkPlaneSource->SetPoint2(0.0, yDim, slice);
//m_VtkPolyDataMapper = vtkPolyDataMapper::New();
// m_VtkPolyDataMapper->SetInput(m_VtkPlaneSource->GetOutput());
// m_VtkPolyDataMapper->ImmediateModeRenderingOn();
//axial = vtkActor::New();
// axial->SetMapper(m_VtkPolyDataMapper);
// axial->SetTexture(axialTexture);
}
//##ModelId=3E691E090394
mitk::Geometry2DDataVtkMapper3D::~Geometry2DDataVtkMapper3D()
{
delete m_DataTreeIterator;
m_VtkPlaneSource->Delete();
m_VtkPolyDataMapper->Delete();
m_Actor->Delete();
m_VtkLookupTable->Delete();
m_VtkTexture->Delete();
}
//##ModelId=3E691E090380
const mitk::Geometry2DData *mitk::Geometry2DDataVtkMapper3D::GetInput()
{
if (this->GetNumberOfInputs() < 1)
{
return 0;
}
return static_cast<const mitk::Geometry2DData * > ( GetData() );
}
//##ModelId=3E691E09038A
void mitk::Geometry2DDataVtkMapper3D::Update()
{
}
//##ModelId=3E691E090396
void mitk::Geometry2DDataVtkMapper3D::GenerateOutputInformation()
{
}
//##ModelId=3E691E09038C
void mitk::Geometry2DDataVtkMapper3D::GenerateData()
{
}
//##ModelId=3E6E874F0007
void mitk::Geometry2DDataVtkMapper3D::SetDataIteratorForTexture(mitk::DataTreeIterator* iterator)
{
delete m_DataTreeIterator;
m_DataTreeIterator = iterator->clone();
}
//##ModelId=3EF19F850151
void mitk::Geometry2DDataVtkMapper3D::Update(mitk::BaseRenderer* renderer)
{
if(IsVisible(renderer)==false)
{
m_Actor->VisibilityOff();
return;
}
m_Actor->VisibilityOn();
mitk::Geometry2DData::Pointer input = const_cast<mitk::Geometry2DData*>(this->GetInput());
if(input.IsNotNull())
{
mitk::Geometry2DDataToSurfaceDataFilter::Pointer surfaceCreator;
mitk::SmartPointerProperty::Pointer surfacecreatorprop;
surfacecreatorprop=dynamic_cast<mitk::SmartPointerProperty*>(GetDataTreeNode()->GetProperty("surfacegeometry", renderer).GetPointer());
if( (surfacecreatorprop.IsNull()) ||
(surfacecreatorprop->GetSmartPointer().IsNull()) ||
((surfaceCreator=dynamic_cast<mitk::Geometry2DDataToSurfaceDataFilter*>(surfacecreatorprop->GetSmartPointer().GetPointer())).IsNull())
)
{
surfaceCreator = mitk::Geometry2DDataToSurfaceDataFilter::New();
surfacecreatorprop=new mitk::SmartPointerProperty(surfaceCreator);
GetDataTreeNode()->SetProperty("surfacegeometry", surfacecreatorprop);
}
surfaceCreator->SetInput(input);
int res;
if(GetDataTreeNode()->GetIntProperty("xresolution", res, renderer))
surfaceCreator->SetXResolution(res);
if(GetDataTreeNode()->GetIntProperty("yresolution", res, renderer))
surfaceCreator->SetYResolution(res);
surfaceCreator->Update(); //@FIXME ohne das crash
m_VtkPolyDataMapper->SetInput(surfaceCreator->GetOutput()->GetVtkPolyData());
if(m_DataTreeIterator)
{
mitk::DataTreeIterator* it=m_DataTreeIterator->clone();
while(it->hasNext())
{
it->next();
mitk::DataTreeNode* node=it->get();
mitk::Mapper::Pointer mapper = node->GetMapper(1);
mitk::ImageMapper2D* imagemapper = dynamic_cast<ImageMapper2D*>(mapper.GetPointer());
if((node->IsVisible(renderer)) && (imagemapper))
{
mitk::SmartPointerProperty::Pointer rendererProp = dynamic_cast<mitk::SmartPointerProperty*>(GetDataTreeNode()->GetPropertyList()->GetProperty("renderer").GetPointer());
if(rendererProp.IsNotNull())
{
mitk::BaseRenderer::Pointer renderer = dynamic_cast<mitk::BaseRenderer*>(rendererProp->GetSmartPointer().GetPointer());
if(renderer.IsNotNull())
{
// check for LookupTable
mitk::LookupTableProperty::Pointer LookupTableProb;
LookupTableProb = dynamic_cast<mitk::LookupTableProperty*>(node->GetPropertyList()->GetProperty("LookupTable").GetPointer());
if (LookupTableProb.IsNotNull() )
{
m_VtkLookupTable = LookupTableProb->GetLookupTable().GetVtkLookupTable();
m_VtkTexture->SetLookupTable(m_VtkLookupTable);
// m_VtkTexture->Modified();
} else {
m_VtkLookupTable = m_VtkLookupTableDefault;
}
// check for level window prop and use it for display if it exists
mitk::LevelWindow levelWindow;
if(node->GetLevelWindow(levelWindow, renderer))
m_VtkLookupTable->SetTableRange(levelWindow.GetMin(),levelWindow.GetMax());
//we have to do this before GenerateAllData() is called there may be
//no RendererInfo for renderer yet, thus GenerateAllData won't update
//the (non-existing) RendererInfo for renderer. By calling GetRendererInfo
//a RendererInfo will be created for renderer (if it does not exist yet).
const ImageMapper2D::RendererInfo* ri=imagemapper->GetRendererInfo(renderer);
imagemapper->GenerateAllData();
if((ri!=NULL) && (m_LastTextureUpdateTime<ri->m_LastUpdateTime))
{
ipPicDescriptor *p=ri->m_Pic;
vtkImageData* vtkimage=Pic2vtk::convert(p);
m_VtkTexture->SetInput(vtkimage); vtkimage->Delete(); vtkimage=NULL;
m_Actor->SetTexture(m_VtkTexture);
m_LastTextureUpdateTime=ri->m_LastUpdateTime;
}
break;
}
}
}
}
}
//apply properties read from the PropertyList
ApplyProperties(m_Actor, renderer);
}
StandardUpdate();
}
<|endoftext|> |
<commit_before>#pragma once
#ifndef CUDA_EVENT_H_
#define CUDA_EVENT_H_
#include "types.h"
#include "cuda/api/error.hpp"
#include <cuda_runtime_api.h>
namespace cuda {
namespace event {
enum : bool {
dont_use_blocking_sync = false,
use_blocking_sync = true,
};
enum : bool {
dont_record_timings = false,
do_record_timings = true,
};
enum : bool {
not_interprocess = false,
interprocess = true,
};
} // namespace event
class event_t {
public: // constructors and destructor
event_t() : owning(true)
{
auto status = cudaEventCreate(&id_);
throw_if_error(status, "failed creating a CUDA event");
}
event_t(
bool uses_blocking_sync = false,
bool records_timing = true,
bool interprocess = false)
:
owning(true), uses_blocking_sync_(uses_blocking_sync),
records_timing_(records_timing), interprocess_(interprocess)
{
auto status = cudaEventCreate(&id_, flags());
throw_if_error(status, "failed creating a CUDA event");
}
event_t(const event_t& other) :
id_(other.id_), owning(false),
uses_blocking_sync_(other.uses_blocking_sync_),
records_timing_(other.records_timing_),
interprocess_(other.interprocess_) { };
event_t(event_t&& other) : owning(other.owning), id_(other.id_),
uses_blocking_sync_(other.uses_blocking_sync_),
records_timing_(other.records_timing_),
interprocess_(other.interprocess_) { other.owning = false; };
~event_t() { if (owning) cudaEventDestroy(id_); }
protected:
unsigned flags() const {
return
(uses_blocking_sync_ ? cudaEventBlockingSync : 0)
| (records_timing_ ? 0 : cudaEventDisableTiming)
| (interprocess_ ? cudaEventInterprocess : 0)
;
}
public: // data member getter
event::id_t id() const { return id_; }
bool is_owning() const { return owning; }
bool interprocess() const { return interprocess_; }
bool records_timing() const { return records_timing_; }
bool uses_blocking_sync() const { return uses_blocking_sync_; }
public: // other mutator methods
status_t query()
{
// Note we can't throw on failure since this is a destructor... let's
// home for the best.
return cudaEventQuery(id_);
}
/**
* @note No protection against repeated calls.
*
* @note Not using cuda::stream::Default to avoid the extra include
*/
void record(stream::id_t stream = (stream::id_t) nullptr)
{
throw_if_error(cudaEventRecord(id_, stream), "failed recording an event");
}
void synchronize()
{
throw_if_error(cudaEventSynchronize(id_), "failed synchronizing an event");
}
protected: // data members
bool owning; // not const, to enable move assignment / construction
event::id_t id_; // it can't be a const, since we're making
// a CUDA API call during construction
const bool uses_blocking_sync_ { false };
const bool records_timing_ { false };
const bool interprocess_ { false };
};
namespace event {
float milliseconds_elapsed_between(id_t start, id_t end)
{
float elapsed_ms;
auto result = cudaEventElapsedTime(&elapsed_ms, start, end);
throw_if_error(result, "determining the time elapsed between events");
return elapsed_ms;
}
float milliseconds_elapsed_between(const event_t& start, const event_t& end)
{
return milliseconds_elapsed_between(start.id(), end.id());
}
} // namespace event
} // namespace cuda
#endif /* CUDA_EVENT_H_ */
<commit_msg>Event proxy:<commit_after>#pragma once
#ifndef CUDA_EVENT_H_
#define CUDA_EVENT_H_
#include "types.h"
#include "cuda/api/error.hpp"
#include <cuda_runtime_api.h>
namespace cuda {
namespace event {
enum : bool {
dont_use_blocking_sync = false,
use_blocking_sync = true,
};
enum : bool {
dont_record_timings = false,
do_record_timings = true,
};
enum : bool {
not_interprocess = false,
interprocess = true,
};
} // namespace event
class event_t {
public: // constructors and destructor
event_t() : owning(true)
{
auto status = cudaEventCreate(&id_);
throw_if_error(status, "failed creating a CUDA event");
}
event_t(
bool uses_blocking_sync,
// I would have liked to default to false, but this would
// occlude the trivial (argument-less) constructor)
bool records_timing = event::do_record_timings,
bool interprocess = event::not_interprocess)
:
owning(true), uses_blocking_sync_(uses_blocking_sync),
records_timing_(records_timing), interprocess_(interprocess)
{
auto status = cudaEventCreate(&id_, flags());
throw_if_error(status, "failed creating a CUDA event");
}
event_t(const event_t& other) :
id_(other.id_), owning(false),
uses_blocking_sync_(other.uses_blocking_sync_),
records_timing_(other.records_timing_),
interprocess_(other.interprocess_) { };
event_t(event_t&& other) : owning(other.owning), id_(other.id_),
uses_blocking_sync_(other.uses_blocking_sync_),
records_timing_(other.records_timing_),
interprocess_(other.interprocess_) { other.owning = false; };
~event_t() { if (owning) cudaEventDestroy(id_); }
protected:
unsigned flags() const {
return
(uses_blocking_sync_ ? cudaEventBlockingSync : 0)
| (records_timing_ ? 0 : cudaEventDisableTiming)
| (interprocess_ ? cudaEventInterprocess : 0)
;
}
public: // data member getter
event::id_t id() const { return id_; }
bool is_owning() const { return owning; }
bool interprocess() const { return interprocess_; }
bool records_timing() const { return records_timing_; }
bool uses_blocking_sync() const { return uses_blocking_sync_; }
public: // other mutator methods
status_t query()
{
// Note we can't throw on failure since this is a destructor... let's
// home for the best.
return cudaEventQuery(id_);
}
/**
* @note No protection against repeated calls.
*
* @note Not using cuda::stream::Default to avoid the extra include
*/
void record(stream::id_t stream = (stream::id_t) nullptr)
{
throw_if_error(cudaEventRecord(id_, stream), "failed recording an event");
}
void synchronize()
{
throw_if_error(cudaEventSynchronize(id_), "failed synchronizing an event");
}
protected: // data members
bool owning; // not const, to enable move assignment / construction
event::id_t id_; // it can't be a const, since we're making
// a CUDA API call during construction
const bool uses_blocking_sync_ { false };
const bool records_timing_ { false };
const bool interprocess_ { false };
};
namespace event {
float milliseconds_elapsed_between(id_t start, id_t end)
{
float elapsed_ms;
auto result = cudaEventElapsedTime(&elapsed_ms, start, end);
throw_if_error(result, "determining the time elapsed between events");
return elapsed_ms;
}
float milliseconds_elapsed_between(const event_t& start, const event_t& end)
{
return milliseconds_elapsed_between(start.id(), end.id());
}
} // namespace event
} // namespace cuda
#endif /* CUDA_EVENT_H_ */
<|endoftext|> |
<commit_before>#ifndef __JSON_HPP__
#define __JSON_HPP__
#include <cctype>
#include <iostream>
#include <string>
#include <vector>
#include <array>
#include <regex>
namespace JSON {
using namespace std;
struct Error {};
struct SyntaxError : public Error {};
struct LoadError : public Error {};
struct AccessError : public Error {};
template<typename _Value, char const ..._szName>
struct Field {
static char const s_szName;
typedef _Value Type;
};
template<char const ..._sz>
struct FieldName {};
template<typename _Name, typename ..._Fields>
struct FieldType {};
template<typename _Value, char const ..._szName, typename ..._OtherFields>
struct FieldType<FieldName<_szName...>, Field<_Value, _szName...>, _OtherFields...> {
typedef _Value Type;
};
template<char const ..._szFieldName, typename _FirstField, typename ..._OtherFields>
struct FieldType<FieldName<_szFieldName...>, _FirstField, _OtherFields...> {
typedef typename FieldType<FieldName<_szFieldName...>, _OtherFields...>::Type Type;
};
template<typename _Value, char const ..._szName>
char const Field<_Value, _szName...>::s_szName = { _szName... };
template<typename ..._Fields>
struct Object {};
template<typename _Field, typename ..._Fields>
struct Getter {};
template<typename _Value, char const ..._szName, typename ..._OtherFields>
struct Getter<Field<_Value, _szName...>, Field<_Value, _szName...>, _OtherFields...> {
inline static _Value &Get(Object<Field<_Value, _szName...>, _OtherFields...> &rObject) {
return rObject.m_Value;
}
inline static _Value const &Get(Object<Field<_Value, _szName...>, _OtherFields...> const &rObject) {
return rObject.m_Value;
}
};
template<typename _Value, char const ..._szName, typename _FirstField, typename ..._OtherFields>
struct Getter<Field<_Value, _szName...>, _FirstField, _OtherFields...> {
inline static _Value &Get(Object<_FirstField, _OtherFields...> &rObject) {
return Getter<Field<_Value, _szName...>, _OtherFields...>::Get(rObject);
}
inline static _Value const &Get(Object<_FirstField, _OtherFields...> const &rObject) {
return Getter<Field<_Value, _szName...>, _FirstField, _OtherFields...>::Get(rObject);
}
};
template<>
struct Object<> {
Object() {}
virtual ~Object() {}
};
template<typename _Value, char const ..._szName, typename ..._OtherFields>
struct Object<Field<_Value, _szName...>, _OtherFields...> :
public Object<_OtherFields...>
{
static char const s_szName[];
_Value m_Value;
Object() {}
virtual ~Object() {}
template<char const ..._szFieldName>
inline typename FieldType<FieldName<_szFieldName...>, Field<_Value, _szName...>, _OtherFields...>::Type &Get() {
return Getter<
Field<typename FieldType<
FieldName<_szFieldName...>,
Field<_Value, _szName...>,
_OtherFields...
>::Type, _szFieldName...>,
Field<_Value, _szName...>,
_OtherFields...
>::Get(*this);
}
template<char const ..._szFieldName>
inline typename FieldType<FieldName<_szFieldName...>, Field<_Value, _szName...>, _OtherFields...>::Type const &Get() const {
return Getter<
Field<typename FieldType<
FieldName<_szFieldName...>,
Field<_Value, _szName...>,
_OtherFields...
>::Type, _szFieldName...>,
Field<_Value, _szName...>,
_OtherFields...
>::Get(*this);
}
};
template<typename _Value, char const ..._szName, typename ..._OtherFields>
char const Object<Field<_Value, _szName...>, _OtherFields...>::s_szName[] = { _szName... };
template<typename _Type>
struct Serializer {
static _Type Load(istream &ris);
static ostream &Store(ostream &ros, _Type const &r);
};
template<>
struct Serializer<nullptr_t> {
static nullptr_t Load(istream &ris) {
// TODO
throw Error();
}
static ostream &Store(ostream &ros, nullptr_t const &r) {
return ros << "null";
}
};
template<>
struct Serializer<bool> {
static bool Load(istream &ris) {
// TODO
throw Error();
}
static ostream &Store(ostream &ros, bool const &r) {
if (r) {
return ros << "true";
} else {
return ros << "false";
}
}
};
template<>
struct Serializer<int> {
static int Load(istream &ris) {
// TODO
throw Error();
}
static ostream &Store(ostream &ros, int const &r) {
return ros << r;
}
};
template<>
struct Serializer<unsigned int> {
static unsigned int Load(istream &ris) {
// TODO
throw Error();
}
static ostream &Store(ostream &ros, unsigned int const &r) {
return ros << r;
}
};
template<>
struct Serializer<double> {
static double Load(istream &ris) {
// TODO
throw Error();
}
static ostream &Store(ostream &ros, double const &r) {
return ros << r;
}
};
template<>
struct Serializer<string> {
static string Load(istream &ris) {
// TODO
throw Error();
}
static ostream &Store(ostream &ros, string const &r) {
return ros << '\"' << r << '\"'; // FIXME escape special characters
}
};
template<typename ..._Fields>
struct Serializer<Object<_Fields...>> {
static Object<_Fields...> Load(istream &ris) {
// TODO
throw Error();
}
};
template<typename _Element>
struct Serializer<vector<_Element>> {
static vector<_Element> Load(istream &ris) {
// TODO
throw Error();
}
};
template<typename _Element, unsigned int _c>
struct Serializer<array<_Element, _c>> {
static array<_Element, _c> Load(istream &ris) {
// TODO
throw Error();
}
};
template<typename _Type>
inline _Type Load(istream &ris) {
return Serializer<_Type>::Load(ris);
}
template<typename _Type>
inline ostream &Store(ostream &ros, _Type const &r) {
return Serializer<_Type>::Store(ros, r);
}
}
template<typename ..._Fields>
inline std::istream &operator >> (std::istream &ris, JSON::Object<_Fields...> &rObject) {
rObject = JSON::Load<JSON::Object<_Fields...>>(ris);
return ris;
}
template<typename ..._Fields>
inline std::ostream &operator << (std::ostream &ros, JSON::Object<_Fields...> &rObject) {
return JSON::Store<JSON::Object<_Fields...>>(ros, rObject);
}
#define UNPACK(sz) (sz)[0], ((sz)[0] > 0) ? UNPACK((sz) + 1) : 0
#endif
<commit_msg>Minor<commit_after>#ifndef __JSON_HPP__
#define __JSON_HPP__
#include <cctype>
#include <iostream>
#include <string>
#include <vector>
#include <array>
#include <regex>
namespace JSON {
using namespace std;
struct Error {};
struct SyntaxError : public Error {};
struct LoadError : public Error {};
struct AccessError : public Error {};
template<typename _Value, char const ..._szName>
struct Field {
static char const s_szName;
typedef _Value Type;
};
template<typename _Value, char const ..._szName>
char const Field<_Value, _szName...>::s_szName = { _szName... };
template<char const ..._sz>
struct FieldName {};
template<typename _Name, typename ..._Fields>
struct FieldType {};
template<typename _Value, char const ..._szName, typename ..._OtherFields>
struct FieldType<FieldName<_szName...>, Field<_Value, _szName...>, _OtherFields...> {
typedef _Value Type;
};
template<char const ..._szFieldName, typename _FirstField, typename ..._OtherFields>
struct FieldType<FieldName<_szFieldName...>, _FirstField, _OtherFields...> {
typedef typename FieldType<FieldName<_szFieldName...>, _OtherFields...>::Type Type;
};
template<typename ..._Fields>
struct Object {};
template<typename _Field, typename ..._Fields>
struct Getter {};
template<typename _Value, char const ..._szName, typename ..._OtherFields>
struct Getter<Field<_Value, _szName...>, Field<_Value, _szName...>, _OtherFields...> {
inline static _Value &Get(Object<Field<_Value, _szName...>, _OtherFields...> &rObject) {
return rObject.m_Value;
}
inline static _Value const &Get(Object<Field<_Value, _szName...>, _OtherFields...> const &rObject) {
return rObject.m_Value;
}
};
template<typename _Value, char const ..._szName, typename _FirstField, typename ..._OtherFields>
struct Getter<Field<_Value, _szName...>, _FirstField, _OtherFields...> {
inline static _Value &Get(Object<_FirstField, _OtherFields...> &rObject) {
return Getter<Field<_Value, _szName...>, _OtherFields...>::Get(rObject);
}
inline static _Value const &Get(Object<_FirstField, _OtherFields...> const &rObject) {
return Getter<Field<_Value, _szName...>, _FirstField, _OtherFields...>::Get(rObject);
}
};
template<>
struct Object<> {
Object() {}
virtual ~Object() {}
};
template<typename _Value, char const ..._szName, typename ..._OtherFields>
struct Object<Field<_Value, _szName...>, _OtherFields...> :
public Object<_OtherFields...>
{
static char const s_szName[];
_Value m_Value;
Object() {}
virtual ~Object() {}
template<char const ..._szFieldName>
inline typename FieldType<FieldName<_szFieldName...>, Field<_Value, _szName...>, _OtherFields...>::Type &Get() {
return Getter<
Field<typename FieldType<
FieldName<_szFieldName...>,
Field<_Value, _szName...>,
_OtherFields...
>::Type, _szFieldName...>,
Field<_Value, _szName...>,
_OtherFields...
>::Get(*this);
}
template<char const ..._szFieldName>
inline typename FieldType<FieldName<_szFieldName...>, Field<_Value, _szName...>, _OtherFields...>::Type const &Get() const {
return Getter<
Field<typename FieldType<
FieldName<_szFieldName...>,
Field<_Value, _szName...>,
_OtherFields...
>::Type, _szFieldName...>,
Field<_Value, _szName...>,
_OtherFields...
>::Get(*this);
}
};
template<typename _Value, char const ..._szName, typename ..._OtherFields>
char const Object<Field<_Value, _szName...>, _OtherFields...>::s_szName[] = { _szName... };
template<typename _Type>
struct Serializer {
static _Type Load(istream &ris);
static ostream &Store(ostream &ros, _Type const &r);
};
template<>
struct Serializer<nullptr_t> {
static nullptr_t Load(istream &ris) {
// TODO
throw Error();
}
static ostream &Store(ostream &ros, nullptr_t const &r) {
return ros << "null";
}
};
template<>
struct Serializer<bool> {
static bool Load(istream &ris) {
// TODO
throw Error();
}
static ostream &Store(ostream &ros, bool const &r) {
if (r) {
return ros << "true";
} else {
return ros << "false";
}
}
};
template<>
struct Serializer<int> {
static int Load(istream &ris) {
// TODO
throw Error();
}
static ostream &Store(ostream &ros, int const &r) {
return ros << r;
}
};
template<>
struct Serializer<unsigned int> {
static unsigned int Load(istream &ris) {
// TODO
throw Error();
}
static ostream &Store(ostream &ros, unsigned int const &r) {
return ros << r;
}
};
template<>
struct Serializer<double> {
static double Load(istream &ris) {
// TODO
throw Error();
}
static ostream &Store(ostream &ros, double const &r) {
return ros << r;
}
};
template<>
struct Serializer<string> {
static string Load(istream &ris) {
// TODO
throw Error();
}
static ostream &Store(ostream &ros, string const &r) {
return ros << '\"' << r << '\"'; // FIXME escape special characters
}
};
template<typename ..._Fields>
struct Serializer<Object<_Fields...>> {
static Object<_Fields...> Load(istream &ris) {
// TODO
throw Error();
}
};
template<typename _Element>
struct Serializer<vector<_Element>> {
static vector<_Element> Load(istream &ris) {
// TODO
throw Error();
}
};
template<typename _Element, unsigned int _c>
struct Serializer<array<_Element, _c>> {
static array<_Element, _c> Load(istream &ris) {
// TODO
throw Error();
}
};
template<typename _Type>
inline _Type Load(istream &ris) {
return Serializer<_Type>::Load(ris);
}
template<typename _Type>
inline ostream &Store(ostream &ros, _Type const &r) {
return Serializer<_Type>::Store(ros, r);
}
}
template<typename ..._Fields>
inline std::istream &operator >> (std::istream &ris, JSON::Object<_Fields...> &rObject) {
rObject = JSON::Load<JSON::Object<_Fields...>>(ris);
return ris;
}
template<typename ..._Fields>
inline std::ostream &operator << (std::ostream &ros, JSON::Object<_Fields...> &rObject) {
return JSON::Store<JSON::Object<_Fields...>>(ros, rObject);
}
#define UNPACK(sz) (sz)[0], ((sz)[0] > 0) ? UNPACK((sz) + 1) : 0
#endif
<|endoftext|> |
<commit_before>#include "Encoder.h"
#include "LuaPbIntfImpl.h" // for MakeSharedMessage()
#include "MessageSptr.h"
#include <LuaIntf/LuaIntf.h>
#include <LuaIntf/LuaState.h> // for LuaException
#include <google/protobuf/message.h> // for Message
#include <iostream>
namespace LuaIntf
{
LUA_USING_SHARED_PTR_TYPE(std::shared_ptr)
}
using namespace LuaIntf;
using google::protobuf::Message;
using std::string;
namespace {
// The key to index C++ Message object in proxy table.
LuaRef GetMessageKey(lua_State* L)
{
assert(L);
// In lua: c = require("luapbintf.c")
LuaRef require(L, "require");
LuaRef c = require.call<LuaRef>("luapbintf.c");
assert(c.isTable());
return c;
}
// Get MessageSptr in table.
MessageSptr GetMessageSptrInTable(const LuaRef& luaTable)
{
assert(luaTable.isTable());
// Key is always the same.
static LuaRef s_key = GetMessageKey(luaTable.state());
LuaRef c_msg = luaTable.rawget(s_key);
if (!c_msg) return nullptr;
return c_msg.toValue<MessageSptr>();
}
} // namespace
// luaTable may be a normal lua table,
// a message proxy table which has a C++ MessageSptr object,
string Encoder::Encode(const string& sMsgTypeName, const LuaRef& luaTable) const
{
assert(luaTable.isTable());
MessageSptr pMsg = EncodeToMessage(sMsgTypeName, luaTable);
assert(pMsg);
return pMsg->SerializeAsString();
} // Encode()
MessageSptr Encoder::EncodeToMessage(const string& sMsgTypeName,
const LuaRef& luaTable) const
{
assert(luaTable.isTable());
MessageSptr pMsg = GetMessageSptr(sMsgTypeName, luaTable);
assert(pMsg);
const auto itrEnd = luaTable.end();
for (auto itr = luaTable.begin(); itr != itrEnd; ++itr)
{
const LuaRef& key = itr.key();
if (LuaTypeID::STRING != key.type())
continue;
const string& sKey = key.toValue<string>();
std::cout << sKey << std::endl;
// XXX
}
return pMsg;
} // EncodeToMessage()
// Get MessageSptr in table or make a new one.
MessageSptr Encoder::GetMessageSptr(const string& sMsgTypeName,
const LuaRef& luaTable) const
{
MessageSptr pMsg = GetMessageSptrInTable(luaTable);
if (!pMsg)
return m_luaPbIntfImpl.MakeSharedMessage(sMsgTypeName);
if (pMsg->GetTypeName() == sMsgTypeName)
return pMsg;
throw LuaException("Message type mismatch (" + sMsgTypeName +
" expected, got " + pMsg->GetTypeName() + ").");
}
<commit_msg>Set message field.<commit_after>#include "Encoder.h"
#include "LuaPbIntfImpl.h" // for MakeSharedMessage()
#include "MessageSptr.h"
#include <LuaIntf/LuaIntf.h>
#include <LuaIntf/LuaState.h> // for LuaException
#include <google/protobuf/message.h> // for Message
#include <iostream>
#include "MessageSetField.h"
namespace LuaIntf
{
LUA_USING_SHARED_PTR_TYPE(std::shared_ptr)
}
using namespace LuaIntf;
using google::protobuf::Message;
using std::string;
namespace {
// The key to index C++ Message object in proxy table.
LuaRef GetMessageKey(lua_State* L)
{
assert(L);
// In lua: c = require("luapbintf.c")
LuaRef require(L, "require");
LuaRef c = require.call<LuaRef>("luapbintf.c");
assert(c.isTable());
return c;
}
// Get MessageSptr in table.
MessageSptr GetMessageSptrInTable(const LuaRef& luaTable)
{
assert(luaTable.isTable());
// Key is always the same.
static LuaRef s_key = GetMessageKey(luaTable.state());
LuaRef c_msg = luaTable.rawget(s_key);
if (!c_msg) return nullptr;
return c_msg.toValue<MessageSptr>();
}
} // namespace
// luaTable may be a normal lua table,
// a message proxy table which has a C++ MessageSptr object,
string Encoder::Encode(const string& sMsgTypeName, const LuaRef& luaTable) const
{
assert(luaTable.isTable());
MessageSptr pMsg = EncodeToMessage(sMsgTypeName, luaTable);
assert(pMsg);
return pMsg->SerializeAsString();
} // Encode()
MessageSptr Encoder::EncodeToMessage(const string& sMsgTypeName,
const LuaRef& luaTable) const
{
assert(luaTable.isTable());
MessageSptr pMsg = GetMessageSptr(sMsgTypeName, luaTable);
assert(pMsg);
const auto itrEnd = luaTable.end();
for (auto itr = luaTable.begin(); itr != itrEnd; ++itr)
{
const LuaRef& key = itr.key();
if (LuaTypeID::STRING != key.type())
continue;
const string& sKey = key.toValue<string>();
std::cout << sKey << std::endl; // DEL
const LuaRef& val = itr.value();
MessageSetField(pMsg.get(), sKey, val);
}
return pMsg;
} // EncodeToMessage()
// Get MessageSptr in table or make a new one.
MessageSptr Encoder::GetMessageSptr(const string& sMsgTypeName,
const LuaRef& luaTable) const
{
MessageSptr pMsg = GetMessageSptrInTable(luaTable);
if (!pMsg)
return m_luaPbIntfImpl.MakeSharedMessage(sMsgTypeName);
if (pMsg->GetTypeName() == sMsgTypeName)
return pMsg;
throw LuaException("Message type mismatch (" + sMsgTypeName +
" expected, got " + pMsg->GetTypeName() + ").");
}
<|endoftext|> |
<commit_before>#include "rapidcheck/detail/Utility.h"
#include <cxxabi.h>
#include <cstdlib>
namespace rc {
namespace detail {
std::string demangle(const char *name)
{
std::string demangled(name);
int status;
std::size_t length;
char *buf = abi::__cxa_demangle(name, NULL, &length, &status);
if (status == 0)
demangled = std::string(buf, length);
free(buf);
return demangled;
}
} // namespace detail
} // namespace rc
<commit_msg>demangle: Don't rely on buffer length for content length<commit_after>#include "rapidcheck/detail/Utility.h"
#include <cxxabi.h>
#include <cstdlib>
namespace rc {
namespace detail {
std::string demangle(const char *name)
{
std::string demangled(name);
int status;
std::size_t length;
char *buf = abi::__cxa_demangle(name, 0, 0, &status);
if (status == 0)
demangled = std::string(buf);
free(buf);
return demangled;
}
} // namespace detail
} // namespace rc
<|endoftext|> |
<commit_before>/*
* Odometer.cpp - Handles the gyroscope (L3G4200D) sensor of the Smartcar.
* Version: 0.3
* Author: Dimitris Platis (based on the bildr.org example: http://bildr.org/2011/06/l3g4200d-arduino/)
* License: GNU GPL v3 http://www.gnu.org/licenses/gpl-3.0.html
*/
#include "CaroloCup.h"
/* ---- GYROSCOPE (L3G4200D) ---- */
const unsigned short Gyroscope::DEFAULT_GYRO_SAMPLING = 80;
static const int GYRO_OFFSET = 15; //The value that is usually given by the gyroscope when not moving. Determined experimentally, adapt accordingly.
static const float GYRO_SENSITIVITY = 0.07; //L3G4200D specific.
static const int GYRO_THRESHOLD = 12; //Tolerance threshold. Determined experimentally, adapt accordingly.
static const int CTRL_REG1 = 0x20;
static const int CTRL_REG2 = 0x21;
static const int CTRL_REG3 = 0x22;
static const int CTRL_REG4 = 0x23;
static const int CTRL_REG5 = 0x24;
static const int L3G4200D_Address = 105; //gyroscope I2C address
volatile int _angularDisplacement = 0;
volatile unsigned long _prevSample = 0;
Gyroscope::Gyroscope(){
}
void Gyroscope::attach(){
initializeGyro();
}
void Gyroscope::initMeasurement(){
_angularDisplacement = 0;
_prevSample = 0;
}
void Gyroscope::begin(unsigned short samplingRate){
initMeasurement();
_prevSample = millis();
_samplingRate = samplingRate;
}
int Gyroscope::getAngularDisplacement(){
return _angularDisplacement;
}
/* based on http://www.pieter-jan.com/node/7 integration algorithm */
void Gyroscope::update(){
if (millis()- _prevSample > _samplingRate){
float gyroRate = 0;
int gyroValue = getGyroValues();
short drift = GYRO_OFFSET - gyroValue;
if (abs(drift) > GYRO_THRESHOLD){ //if there has been a big enough drift (trying to contemplate for the noise)
gyroRate = (gyroValue - GYRO_OFFSET) * GYRO_SENSITIVITY;
}
unsigned long now = millis();
_angularDisplacement += gyroRate / (1000 / (now - _prevSample));
_prevSample = now;
}
}
void Gyroscope::initializeGyro(){
Wire.begin();
setupL3G4200D(2000); // Configure L3G4200 at 2000 deg/sec. Other options: 250, 500 (NOT suggested, will have to redetermine offset)
}
/* based on the bildr.org example: http://bildr.org/2011/06/l3g4200d-arduino/ */
int Gyroscope::getGyroValues(){
byte zMSB = readRegister(L3G4200D_Address, 0x2D);
byte zLSB = readRegister(L3G4200D_Address, 0x2C);
return ((zMSB << 8) | zLSB);
}
int Gyroscope::setupL3G4200D(int scale){
//From Jim Lindblom of Sparkfun's code
// Enable x, y, z and turn off power down:
writeRegister(L3G4200D_Address, CTRL_REG1, 0b00001111);
// If you'd like to adjust/use the HPF, you can edit the line below to configure CTRL_REG2:
writeRegister(L3G4200D_Address, CTRL_REG2, 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:
writeRegister(L3G4200D_Address, CTRL_REG3, 0b00001000);
// CTRL_REG4 controls the full-scale range, among other things:
if(scale == 250){
writeRegister(L3G4200D_Address, CTRL_REG4, 0b00000000);
}else if(scale == 500){
writeRegister(L3G4200D_Address, CTRL_REG4, 0b00010000);
}else{
writeRegister(L3G4200D_Address, CTRL_REG4, 0b00110000);
}
// CTRL_REG5 controls high-pass filtering of outputs, use it
// if you'd like:
writeRegister(L3G4200D_Address, CTRL_REG5, 0b00000000);
}
void Gyroscope::writeRegister(int deviceAddress, byte address, byte val) {
Wire.beginTransmission(deviceAddress); // start transmission to device
Wire.write(address); // send register address
Wire.write(val); // send value to write
Wire.endTransmission(); // end transmission
}
int Gyroscope::readRegister(int deviceAddress, byte address){
interrupts(); //sei();
int v;
Wire.beginTransmission(deviceAddress);
Wire.write(address); // register to read
Wire.endTransmission();
Wire.requestFrom(deviceAddress, 1); // read a byte
while(!Wire.available()) {
//waiting
}
v = Wire.read();
return v;
}
<commit_msg>removed useless interrupts() call and fixed sign in the returned angles<commit_after>/*
* Odometer.cpp - Handles the gyroscope (L3G4200D) sensor of the Smartcar.
* Version: 0.3
* Author: Dimitris Platis (based on the bildr.org example: http://bildr.org/2011/06/l3g4200d-arduino/)
* License: GNU GPL v3 http://www.gnu.org/licenses/gpl-3.0.html
*/
#include "CaroloCup.h"
/* ---- GYROSCOPE (L3G4200D) ---- */
const unsigned short Gyroscope::DEFAULT_GYRO_SAMPLING = 90;
static const int GYRO_OFFSET = 15; //The value that is usually given by the gyroscope when not moving. Determined experimentally, adapt accordingly.
static const float GYRO_SENSITIVITY = 0.07; //L3G4200D specific.
static const int GYRO_THRESHOLD = 12; //Tolerance threshold. Determined experimentally, adapt accordingly.
static const int CTRL_REG1 = 0x20;
static const int CTRL_REG2 = 0x21;
static const int CTRL_REG3 = 0x22;
static const int CTRL_REG4 = 0x23;
static const int CTRL_REG5 = 0x24;
static const int L3G4200D_Address = 105; //gyroscope I2C address
volatile int _angularDisplacement = 0;
volatile unsigned long _prevSample = 0;
Gyroscope::Gyroscope(){
}
void Gyroscope::attach(){
initializeGyro();
}
void Gyroscope::initMeasurement(){
_angularDisplacement = 0;
_prevSample = 0;
}
void Gyroscope::begin(unsigned short samplingRate){
initMeasurement();
_prevSample = millis();
_samplingRate = samplingRate;
}
int Gyroscope::getAngularDisplacement(){
return - _angularDisplacement;
}
/* based on http://www.pieter-jan.com/node/7 integration algorithm */
void Gyroscope::update(){
if (millis()- _prevSample > _samplingRate){
float gyroRate = 0;
int gyroValue = getGyroValues();
short drift = GYRO_OFFSET - gyroValue;
if (abs(drift) > GYRO_THRESHOLD){ //if there has been a big enough drift (trying to contemplate for the noise)
gyroRate = (gyroValue - GYRO_OFFSET) * GYRO_SENSITIVITY;
}
unsigned long now = millis();
_angularDisplacement += gyroRate / (1000 / (now - _prevSample));
_prevSample = now;
}
}
void Gyroscope::initializeGyro(){
Wire.begin();
setupL3G4200D(2000); // Configure L3G4200 at 2000 deg/sec. Other options: 250, 500 (NOT suggested, will have to redetermine offset)
}
/* based on the bildr.org example: http://bildr.org/2011/06/l3g4200d-arduino/ */
int Gyroscope::getGyroValues(){
byte zMSB = readRegister(L3G4200D_Address, 0x2D);
byte zLSB = readRegister(L3G4200D_Address, 0x2C);
return ((zMSB << 8) | zLSB);
}
int Gyroscope::setupL3G4200D(int scale){
//From Jim Lindblom of Sparkfun's code
// Enable x, y, z and turn off power down:
writeRegister(L3G4200D_Address, CTRL_REG1, 0b00001111);
// If you'd like to adjust/use the HPF, you can edit the line below to configure CTRL_REG2:
writeRegister(L3G4200D_Address, CTRL_REG2, 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:
writeRegister(L3G4200D_Address, CTRL_REG3, 0b00001000);
// CTRL_REG4 controls the full-scale range, among other things:
if(scale == 250){
writeRegister(L3G4200D_Address, CTRL_REG4, 0b00000000);
}else if(scale == 500){
writeRegister(L3G4200D_Address, CTRL_REG4, 0b00010000);
}else{
writeRegister(L3G4200D_Address, CTRL_REG4, 0b00110000);
}
// CTRL_REG5 controls high-pass filtering of outputs, use it
// if you'd like:
writeRegister(L3G4200D_Address, CTRL_REG5, 0b00000000);
}
void Gyroscope::writeRegister(int deviceAddress, byte address, byte val) {
Wire.beginTransmission(deviceAddress); // start transmission to device
Wire.write(address); // send register address
Wire.write(val); // send value to write
Wire.endTransmission(); // end transmission
}
int Gyroscope::readRegister(int deviceAddress, byte address){
int v;
Wire.beginTransmission(deviceAddress);
Wire.write(address); // register to read
Wire.endTransmission();
Wire.requestFrom(deviceAddress, 1); // read a byte
while(!Wire.available()) {
//waiting
}
v = Wire.read();
return v;
}
<|endoftext|> |
<commit_before>#include <iostream>
#include <fstream>
#include <sstream>
#include "snowman.hpp"
int main(int argc, char *argv[]) {
Snowman sm = Snowman();
std::string VERSION_STRING = "v" + std::to_string(Snowman::MAJOR_VERSION) +
"." + std::to_string(Snowman::MINOR_VERSION) + "." +
std::to_string(Snowman::PATCH_VERSION);
// parse arguments
std::string filename;
bool minify = false;
for (int i = 1; i < argc; ++i) {
std::string arg(argv[i]);
if (arg[0] == '-') {
arg = arg.substr(1);
if (arg.length() >= 1 && arg[0] == '-') {
arg = arg.substr(1);
// no switch on strings :(
if (arg == "help") arg = "h";
else if (arg == "interactive") arg = "i";
else if (arg == "debug") arg = "d";
else if (arg == "evaluate") arg = "e";
else if (arg == "minify") arg = "m";
else {
std::cerr << "Unknown long argument `" << arg << "'" <<
std::endl;
return 1;
}
}
for (char& argid : arg) {
switch (argid) {
case 'h':
std::cout << "Usage: " << argv[0] << " [OPTION]... "
"[FILENAME]\n" <<
"Options:\n"
" -h, --help: (without filename) display this "
"message\n"
" -i, --interactive: (without filename) start a "
"REPL\n"
" -e, --evaluate: (without filename) takes one "
"parameter, runs as Snowman code\n"
" -d, --debug: include debug output\n"
" -m, --minify: don't evaluate code; output "
"minified version instead\n"
"Snowman will read from STDIN if you do not specify a "
"file name or the -h or -i options.\n"
"Snowman version: " << VERSION_STRING << "\n";
return 0;
case 'i': {
std::cout << "Snowman REPL, " << VERSION_STRING <<
std::endl;
std::cout << ">> ";
std::string line;
while (std::getline(std::cin, line)) {
sm.run(line);
std::cout << sm.debug();
std::cout << ">> ";
}
}
case 'd':
sm.debugOutput = true;
break;
case 'e':
if ((++i) == argc) {
std::cerr << "Argument `-e' requires a parameter" <<
std::endl;
return 1;
}
sm.run(std::string(argv[i]));
return 0;
case 'm':
minify = true;
break;
default:
std::cerr << "Unknown argument `-" << arg << "'" <<
std::endl;
return 1;
}
}
} else if (filename == "") {
filename = arg;
} else {
std::cerr << "Multiple filenames specified (" << filename << ", "
<< arg << ")" << std::endl;
return 1;
}
}
// retrieve code to run
std::string code;
if (filename == "") {
std::string line;
while (std::getline(std::cin, line) && line != "__END__") code += line;
} else {
std::ifstream infile(filename.c_str());
if (infile.good()) {
std::stringstream buf;
buf << infile.rdbuf() << std::endl;
code = buf.str();
} else {
std::cerr << "Could not read file " << filename << std::endl;
return 1;
}
}
// process -m (--minify) flag
if (minify) {
for (std::string s : Snowman::tokenize(code)) {
std::cout << s;
}
return 0;
}
// run code
sm.run(code);
}
<commit_msg>make minify flag significant with interactive mode<commit_after>#include <iostream>
#include <fstream>
#include <sstream>
#include "snowman.hpp"
int main(int argc, char *argv[]) {
Snowman sm = Snowman();
std::string VERSION_STRING = "v" + std::to_string(Snowman::MAJOR_VERSION) +
"." + std::to_string(Snowman::MINOR_VERSION) + "." +
std::to_string(Snowman::PATCH_VERSION);
// parse arguments
std::string filename;
bool minify = false;
for (int i = 1; i < argc; ++i) {
std::string arg(argv[i]);
if (arg[0] == '-') {
arg = arg.substr(1);
if (arg.length() >= 1 && arg[0] == '-') {
arg = arg.substr(1);
// no switch on strings :(
if (arg == "help") arg = "h";
else if (arg == "interactive") arg = "i";
else if (arg == "debug") arg = "d";
else if (arg == "evaluate") arg = "e";
else if (arg == "minify") arg = "m";
else {
std::cerr << "Unknown long argument `" << arg << "'" <<
std::endl;
return 1;
}
}
for (char& argid : arg) {
switch (argid) {
case 'h':
std::cout << "Usage: " << argv[0] << " [OPTION]... "
"[FILENAME]\n" <<
"Options:\n"
" -h, --help: (without filename) display this "
"message\n"
" -i, --interactive: (without filename) start a "
"REPL\n"
" -e, --evaluate: (without filename) takes one "
"parameter, runs as Snowman code\n"
" -d, --debug: include debug output\n"
" -m, --minify: don't evaluate code; output "
"minified version instead\n"
"Snowman will read from STDIN if you do not specify a "
"file name or the -h or -i options.\n"
"Snowman version: " << VERSION_STRING << "\n";
return 0;
case 'i': {
std::cout << "Snowman REPL, " << VERSION_STRING <<
std::endl;
std::cout << ">> ";
std::string line;
while (std::getline(std::cin, line)) {
if (minify) {
for (std::string s : Snowman::tokenize(line)) {
std::cout << s;
}
std::cout << std::endl << ">> ";
} else {
sm.run(line);
std::cout << sm.debug();
std::cout << ">> ";
}
}
return 0;
}
case 'd':
sm.debugOutput = true;
break;
case 'e':
if ((++i) == argc) {
std::cerr << "Argument `-e' requires a parameter" <<
std::endl;
return 1;
}
sm.run(std::string(argv[i]));
return 0;
case 'm':
minify = true;
break;
default:
std::cerr << "Unknown argument `-" << arg << "'" <<
std::endl;
return 1;
}
}
} else if (filename == "") {
filename = arg;
} else {
std::cerr << "Multiple filenames specified (" << filename << ", "
<< arg << ")" << std::endl;
return 1;
}
}
// retrieve code to run
std::string code;
if (filename == "") {
std::string line;
while (std::getline(std::cin, line) && line != "__END__") code += line;
} else {
std::ifstream infile(filename.c_str());
if (infile.good()) {
std::stringstream buf;
buf << infile.rdbuf() << std::endl;
code = buf.str();
} else {
std::cerr << "Could not read file " << filename << std::endl;
return 1;
}
}
// process -m (--minify) flag
if (minify) {
for (std::string s : Snowman::tokenize(code)) {
std::cout << s;
}
return 0;
}
// run code
sm.run(code);
}
<|endoftext|> |
<commit_before>//#include <stdio.h> //
#include <stdlib.h> //rand, srand
#include "testmain.cc"
#include "gtest/gtest.h"
//for dice rolls
#include <numeric>
#include <algorithm>
#include <cmath>
#include <vector>
TEST(Initialization,Pip24){
Board *b = new Board();
b->initialize();
ASSERT_EQ(b->pips[24],2) << "we don't have 2 white stones on pip 24";
}
//TODO: count stones in locations other than pips
TEST(Initialization,WhiteCount){
Board *b = new Board();
b->initialize();
// Count up the white stones
int count = 0;
int pipval;
for(int i = 1; i < 25; ++i){
pipval = b->pips[i];
if(pipval > 0){ // white stones are here
count += pipval;
}
}
// now count = # white stones on the board
ASSERT_EQ(count,15) << "we want 15 white stones on the board";
}
TEST(Initialization,ColorEqualityCount){
Board *b = new Board();
b->initialize();
// Count up all of the stones
int count = 0;
int pipval;
for(int i = 1; i < 25; ++i){
pipval = b->pips[i];
count += pipval;
}
ASSERT_EQ(count,0) << "should be the same # of white and black stones";
}
/////////////////////////////////////////////////////////////////////////////
TEST(Turns, First4TurnsAlternate){
Game *g = new Game();
Color first = g->turn;
g->passTurn();
Color second = g->turn;
g->passTurn();
Color third = g->turn;
g->passTurn();
Color fourth= g->turn;
EXPECT_EQ(first,third) << "first and third turns should be the same color";
EXPECT_EQ(second,fourth) << "second and fourth turns should be the same color";
EXPECT_NE(first,second) << "first and second turns shouldn't be the same color";
}
TEST(Turns, EvenOddRandomized){
Game *g = new Game();
Color first = g->turn;
g->passTurn();
Color second = g->turn;
int n = rand() % 1000; //in the range between 0 and 999
for(int i = 0; i < n; ++i){
g->passTurn();
}
//if n is odd, then the color should be same as the first color
//if n is even, then the color should be the same as the second color
if(n%2==1){//n is odd
EXPECT_EQ(first,g->turn)<< "all odd numbered turns should be the same color";
}
else{//n is even
EXPECT_EQ(second,g->turn) << "all even numbered turns should be the same color";
}
EXPECT_NE(first,second) << "first and second turns shouldn't be the same color";
}
///////////////////////////////////////////////////////////////////////
TEST(DiceRolls,VerifyValidDiceValues){
Dice *d = new Dice();
std::pair<uint8_t,uint8_t> returnedRoll;
returnedRoll = d->rollDice();
uint8_t firstRoll = returnedRoll.first;
uint8_t secondRoll = returnedRoll.second;
EXPECT_LE(firstRoll,6);
EXPECT_LE(secondRoll,6);
EXPECT_GE(firstRoll,1);
EXPECT_GE(secondRoll,1);
}
TEST(DiceRolls,MeanAndStdDev){
//TODO As of now this is a sanity check, it needs to be much more statistically valid in the future
Dice *d = new Dice();
std::pair<uint8_t,uint8_t> returnedRoll;
returnedRoll = d->rollDice();
uint8_t firstRoll;
uint8_t secondRoll;
std::vector<double> vectorOfRolls(100);
std::vector<double>::iterator iter;
iter = vectorOfRolls.begin();
for(int i = 0; i < 50 ; i = i + 1 ){
returnedRoll = d->rollDice();
firstRoll = returnedRoll.first;
secondRoll = returnedRoll.second;
// vectorOfRolls.insert( iter, (double)firstRoll);
// vectorOfRolls.insert( iter, (double)secondRoll);
}
//double sum = std::accumulate(vectorOfRolls.begin(),vectorOfRolls.end(),0.0);
//double mean = sum / vectorOfRolls.size();
double mean = 3.5;
/*
std::vector<double> diff(vectorOfRolls.size());
std::transform(vectorOfRolls.begin(), vectorOfRolls.end(), diff.begin(),std::bind2nd(std::minus<double>(), mean));
double sq_sum = std::inner_product(diff.begin(), diff.end(), diff.begin(), 0.0);
double stdev = std::sqrt(sq_sum / vectorOfRolls.size());
*/
double mean_actual = 3.5;
double mean_tolerance = 0.5;
double stdev_actual = 1.709;
double stdev_tolerance = 0.25;
EXPECT_LE(mean,mean_actual + mean_tolerance);
EXPECT_GE(mean,mean_actual - mean_tolerance);
//EXPECT_LE(stdev,stdev_actual + stdev_tolerance);
//EXPECT_GE(stdev,stdev_actual - stdev_tolerance);
}
<commit_msg>RED: failing test cases for dice rolls [Task 704]<commit_after>//#include <stdio.h> //
#include <stdlib.h> //rand, srand
#include "testmain.cc"
#include "gtest/gtest.h"
//for dice rolls
#include <numeric>
#include <algorithm>
#include <cmath>
#include <vector>
TEST(Initialization,Pip24){
Board *b = new Board();
b->initialize();
ASSERT_EQ(b->pips[24],2) << "we don't have 2 white stones on pip 24";
}
//TODO: count stones in locations other than pips
TEST(Initialization,WhiteCount){
Board *b = new Board();
b->initialize();
// Count up the white stones
int count = 0;
int pipval;
for(int i = 1; i < 25; ++i){
pipval = b->pips[i];
if(pipval > 0){ // white stones are here
count += pipval;
}
}
// now count = # white stones on the board
ASSERT_EQ(count,15) << "we want 15 white stones on the board";
}
TEST(Initialization,ColorEqualityCount){
Board *b = new Board();
b->initialize();
// Count up all of the stones
int count = 0;
int pipval;
for(int i = 1; i < 25; ++i){
pipval = b->pips[i];
count += pipval;
}
ASSERT_EQ(count,0) << "should be the same # of white and black stones";
}
/////////////////////////////////////////////////////////////////////////////
TEST(Turns, First4TurnsAlternate){
Game *g = new Game();
Color first = g->turn;
g->passTurn();
Color second = g->turn;
g->passTurn();
Color third = g->turn;
g->passTurn();
Color fourth= g->turn;
EXPECT_EQ(first,third) << "first and third turns should be the same color";
EXPECT_EQ(second,fourth) << "second and fourth turns should be the same color";
EXPECT_NE(first,second) << "first and second turns shouldn't be the same color";
}
TEST(Turns, EvenOddRandomized){
Game *g = new Game();
Color first = g->turn;
g->passTurn();
Color second = g->turn;
int n = rand() % 1000; //in the range between 0 and 999
for(int i = 0; i < n; ++i){
g->passTurn();
}
//if n is odd, then the color should be same as the first color
//if n is even, then the color should be the same as the second color
if(n%2==1){//n is odd
EXPECT_EQ(first,g->turn)<< "all odd numbered turns should be the same color";
}
else{//n is even
EXPECT_EQ(second,g->turn) << "all even numbered turns should be the same color";
}
EXPECT_NE(first,second) << "first and second turns shouldn't be the same color";
}
///////////////////////////////////////////////////////////////////////
TEST(DiceRolls,VerifyValidDiceValues){
Dice *d = new Dice();
std::pair<uint8_t,uint8_t> returnedRoll;
returnedRoll = d->rollDice();
uint8_t firstRoll = returnedRoll.first;
uint8_t secondRoll = returnedRoll.second;
EXPECT_LE(firstRoll,6);
EXPECT_LE(secondRoll,6);
EXPECT_GE(firstRoll,1);
EXPECT_GE(secondRoll,1);
}
TEST(DiceRolls,MeanAndStdDev){
//TODO As of now this is a sanity check, it needs to be much more statistically valid in the future
Dice *d = new Dice();
std::pair<uint8_t,uint8_t> returnedRoll;
returnedRoll = d->rollDice();
uint8_t firstRoll;
uint8_t secondRoll;
std::vector<double> vectorOfRolls(100);
//std::vector<double>::iterator iter;
//iter = vectorOfRolls.begin();
for(int i = 0; i < 50 ; i = i + 1 ){
returnedRoll = d->rollDice();
firstRoll = returnedRoll.first;
secondRoll = returnedRoll.second;
vectorOfRolls.push_back( (double) firstRoll);
vectorOfRolls.push_back( (double) secondRoll);
}
double sum = std::accumulate(vectorOfRolls.begin(),vectorOfRolls.end(),0.0);
double mean = sum / vectorOfRolls.size();
//double mean = 3.5;
std::vector<double> diff(vectorOfRolls.size());
std::transform(vectorOfRolls.begin(), vectorOfRolls.end(), diff.begin(),std::bind2nd(std::minus<double>(), mean));
double sq_sum = std::inner_product(diff.begin(), diff.end(), diff.begin(), 0.0);
double stdev = std::sqrt(sq_sum / vectorOfRolls.size());
double mean_actual = 3.5;
double mean_tolerance = 0.5;
double stdev_actual = 1.709;
double stdev_tolerance = 0.25;
EXPECT_LE(mean,mean_actual + mean_tolerance);
EXPECT_GE(mean,mean_actual - mean_tolerance);
EXPECT_LE(stdev,stdev_actual + stdev_tolerance);
EXPECT_GE(stdev,stdev_actual - stdev_tolerance);
}
<|endoftext|> |
<commit_before>#include <iostream>
#include <boost/foreach.hpp>
#include "connectors.h"
#include "gtfs_parser.h"
#include "bdtopo_parser.h"
#include <fstream>
#include <boost/date_time/posix_time/posix_time.hpp>
#include <boost/program_options.hpp>
#include <boost/filesystem.hpp>
namespace po = boost::program_options;
namespace pt = boost::posix_time;
int main(int argc, char * argv[])
{
std::string type, input, output, date, topo_path;
po::options_description desc("Allowed options");
desc.add_options()
("help,h", "Affiche l'aide")
("type,t", po::value<std::string>(&type), "Type du format d'entrée [fusio, gtfs]")
("date,d", po::value<std::string>(&date), "Date de début")
("input,i", po::value<std::string>(&input), "Repertoire d'entrée")
("topo", po::value<std::string>(&topo_path), "Repertoire contenant la bd topo")
("output,o", po::value<std::string>(&output)->default_value("data.nav"), "Fichier de sortie");
po::variables_map vm;
po::store(po::parse_command_line(argc, argv, desc), vm);
po::notify(vm);
if(vm.count("help") || !vm.count("input") || !vm.count("type")) {
std::cout << desc << "\n";
return 1;
}
if(!vm.count("topo")) {
std::cout << "Pas de topologie chargee" << std::endl;
}
pt::ptime start, end;
int read, clean, sort, transform, save, first_letter, sn;
navimake::Data data; // Structure temporaire
navitia::type::Data nav_data; // Structure définitive
//@TODO définir la date de validé en fonction des données
auto tmp_date = boost::gregorian::from_undelimited_string(date);
nav_data.meta.production_date = boost::gregorian::date_period(tmp_date, tmp_date + boost::gregorian::years(1));
// Est-ce que l'on charge la carto ?
start = pt::microsec_clock::local_time();
if(vm.count("topo")){
nav_data.meta.data_sources.push_back(boost::filesystem::absolute(topo_path).native());
navimake::connectors::BDTopoParser topo_parser(topo_path);
//gtfs ne contient pas le référentiel des villes, on le charges depuis la BDTOPO
topo_parser.load_city(data);
topo_parser.load_streetnetwork(nav_data.street_network);
nav_data.set_cities(); // Assigne les villes aux voiries du filaire
}
sn = (pt::microsec_clock::local_time() - start).total_milliseconds();
start = pt::microsec_clock::local_time();
nav_data.meta.data_sources.push_back(boost::filesystem::absolute(input).native());
if(type == "fusio") {
navimake::connectors::CsvFusio connector(input, date);
connector.fill(data);
}
else if(type == "gtfs") {
navimake::connectors::GtfsParser connector(input, date);
connector.fill(data);
}
else {
std::cout << desc << "\n";
return 1;
}
read = (pt::microsec_clock::local_time() - start).total_milliseconds();
std::cout << "line: " << data.lines.size() << std::endl;
std::cout << "route: " << data.routes.size() << std::endl;
std::cout << "stoparea: " << data.stop_areas.size() << std::endl;
std::cout << "stoppoint: " << data.stop_points.size() << std::endl;
std::cout << "vehiclejourney: " << data.vehicle_journeys.size() << std::endl;
std::cout << "stop: " << data.stops.size() << std::endl;
std::cout << "connection: " << data.connections.size() << std::endl;
std::cout << "route points: " << data.route_points.size() << std::endl;
std::cout << "city: " << data.cities.size() << std::endl;
std::cout << "modes: " << data.modes.size() << std::endl;
std::cout << "validity pattern : " << data.validity_patterns.size() << std::endl;
start = pt::microsec_clock::local_time();
data.clean();
clean = (pt::microsec_clock::local_time() - start).total_milliseconds();
start = pt::microsec_clock::local_time();
data.sort();
sort = (pt::microsec_clock::local_time() - start).total_milliseconds();
start = pt::microsec_clock::local_time();
data.transform(nav_data.pt_data);
transform = (pt::microsec_clock::local_time() - start).total_milliseconds();
start = pt::microsec_clock::local_time();
nav_data.build_first_letter();
nav_data.build_proximity_list();
first_letter = (pt::microsec_clock::local_time() - start).total_milliseconds();
std::cout <<"Debut sauvegarde ..." << std::endl;
start = pt::microsec_clock::local_time();
nav_data.lz4(output);
save = (pt::microsec_clock::local_time() - start).total_milliseconds();
std::cout << "temps de traitement" << std::endl;
std::cout << "\t lecture des fichiers " << read << "ms" << std::endl;
std::cout << "\t netoyage des données " << clean << "ms" << std::endl;
std::cout << "\t trie des données " << sort << "ms" << std::endl;
std::cout << "\t transformation " << transform << "ms" << std::endl;
std::cout << "\t street network " << sn << "ms" << std::endl;
std::cout << "\t construction de firstletter " << first_letter << "ms" << std::endl;
std::cout << "\t serialization " << save << "ms" << std::endl;
return 0;
}
<commit_msg>gtfs_parser : Ajout des map external_code->idx<commit_after>#include <iostream>
#include <boost/foreach.hpp>
#include "connectors.h"
#include "gtfs_parser.h"
#include "bdtopo_parser.h"
#include <fstream>
#include <boost/date_time/posix_time/posix_time.hpp>
#include <boost/program_options.hpp>
#include <boost/filesystem.hpp>
namespace po = boost::program_options;
namespace pt = boost::posix_time;
int main(int argc, char * argv[])
{
std::string type, input, output, date, topo_path;
po::options_description desc("Allowed options");
desc.add_options()
("help,h", "Affiche l'aide")
("type,t", po::value<std::string>(&type), "Type du format d'entrée [fusio, gtfs]")
("date,d", po::value<std::string>(&date), "Date de début")
("input,i", po::value<std::string>(&input), "Repertoire d'entrée")
("topo", po::value<std::string>(&topo_path), "Repertoire contenant la bd topo")
("output,o", po::value<std::string>(&output)->default_value("data.nav"), "Fichier de sortie");
po::variables_map vm;
po::store(po::parse_command_line(argc, argv, desc), vm);
po::notify(vm);
if(vm.count("help") || !vm.count("input") || !vm.count("type")) {
std::cout << desc << "\n";
return 1;
}
if(!vm.count("topo")) {
std::cout << "Pas de topologie chargee" << std::endl;
}
pt::ptime start, end;
int read, clean, sort, transform, save, first_letter, sn;
navimake::Data data; // Structure temporaire
navitia::type::Data nav_data; // Structure définitive
//@TODO définir la date de validé en fonction des données
auto tmp_date = boost::gregorian::from_undelimited_string(date);
nav_data.meta.production_date = boost::gregorian::date_period(tmp_date, tmp_date + boost::gregorian::years(1));
// Est-ce que l'on charge la carto ?
start = pt::microsec_clock::local_time();
if(vm.count("topo")){
nav_data.meta.data_sources.push_back(boost::filesystem::absolute(topo_path).native());
navimake::connectors::BDTopoParser topo_parser(topo_path);
//gtfs ne contient pas le référentiel des villes, on le charges depuis la BDTOPO
topo_parser.load_city(data);
topo_parser.load_streetnetwork(nav_data.street_network);
nav_data.set_cities(); // Assigne les villes aux voiries du filaire
}
sn = (pt::microsec_clock::local_time() - start).total_milliseconds();
start = pt::microsec_clock::local_time();
nav_data.meta.data_sources.push_back(boost::filesystem::absolute(input).native());
if(type == "fusio") {
navimake::connectors::CsvFusio connector(input, date);
connector.fill(data);
}
else if(type == "gtfs") {
navimake::connectors::GtfsParser connector(input, date);
connector.fill(data);
}
else {
std::cout << desc << "\n";
return 1;
}
read = (pt::microsec_clock::local_time() - start).total_milliseconds();
std::cout << "line: " << data.lines.size() << std::endl;
std::cout << "route: " << data.routes.size() << std::endl;
std::cout << "stoparea: " << data.stop_areas.size() << std::endl;
std::cout << "stoppoint: " << data.stop_points.size() << std::endl;
std::cout << "vehiclejourney: " << data.vehicle_journeys.size() << std::endl;
std::cout << "stop: " << data.stops.size() << std::endl;
std::cout << "connection: " << data.connections.size() << std::endl;
std::cout << "route points: " << data.route_points.size() << std::endl;
std::cout << "city: " << data.cities.size() << std::endl;
std::cout << "modes: " << data.modes.size() << std::endl;
std::cout << "validity pattern : " << data.validity_patterns.size() << std::endl;
start = pt::microsec_clock::local_time();
data.clean();
clean = (pt::microsec_clock::local_time() - start).total_milliseconds();
start = pt::microsec_clock::local_time();
data.sort();
sort = (pt::microsec_clock::local_time() - start).total_milliseconds();
start = pt::microsec_clock::local_time();
data.transform(nav_data.pt_data);
transform = (pt::microsec_clock::local_time() - start).total_milliseconds();
start = pt::microsec_clock::local_time();
nav_data.build_first_letter();
nav_data.build_proximity_list();
nav_data.build_external_code();
first_letter = (pt::microsec_clock::local_time() - start).total_milliseconds();
std::cout <<"Debut sauvegarde ..." << std::endl;
start = pt::microsec_clock::local_time();
nav_data.lz4(output);
save = (pt::microsec_clock::local_time() - start).total_milliseconds();
std::cout << "temps de traitement" << std::endl;
std::cout << "\t lecture des fichiers " << read << "ms" << std::endl;
std::cout << "\t netoyage des données " << clean << "ms" << std::endl;
std::cout << "\t trie des données " << sort << "ms" << std::endl;
std::cout << "\t transformation " << transform << "ms" << std::endl;
std::cout << "\t street network " << sn << "ms" << std::endl;
std::cout << "\t construction de firstletter " << first_letter << "ms" << std::endl;
std::cout << "\t serialization " << save << "ms" << std::endl;
return 0;
}
<|endoftext|> |
<commit_before>#include "Cursor.h"
#include <QApplication>
#include <QDesktopWidget>
#include <cassert>
#include <set>
#include <stdint.h>
#include "CaptureConfig.h"
#include "MurmurHash3.h"
#include "ObjectiveCBridge.h"
namespace screencast {
std::set<uint32_t> Cursor::m_cachedImages;
Cursor::Cursor() : m_imageID(0)
{
}
Cursor::Cursor(const CaptureConfig &config)
{
id cursor = cursor_currentSystemCursor();
BridgePoint hotSpot = cursor_hotSpot(cursor);
BridgePoint mouseLocation = event_mouseLocation();
id cursorImage = cursor_image(cursor);
id tiffData = cursorImage != nil ?
image_TIFFRepresentation(cursorImage) : nil;
if (tiffData == nil) {
m_imageID = Cursor::blankCursor();
m_position.rx() = 0;
m_position.ry() = 0;
return;
}
MurmurHash3_x86_32(
data_bytes(tiffData),
data_length(tiffData),
0,
&m_imageID);
if (m_cachedImages.find(m_imageID) == m_cachedImages.end()) {
bridgeWriteCursorFile(tiffData, m_imageID);
}
// The NSCursor Y coordinate's origin is at the bottom of the screen.
// Invert it.
mouseLocation.y =
QApplication::desktop()->screenGeometry().height() - mouseLocation.y;
m_position.rx() = mouseLocation.x - hotSpot.x - config.captureX;
m_position.ry() = mouseLocation.y - hotSpot.y - config.captureY;
}
} // namespace screencast
<commit_msg>Fix a performance bug introduced during the ObjC++ rewriting.<commit_after>#include "Cursor.h"
#include <QApplication>
#include <QDesktopWidget>
#include <cassert>
#include <set>
#include <stdint.h>
#include "CaptureConfig.h"
#include "MurmurHash3.h"
#include "ObjectiveCBridge.h"
namespace screencast {
std::set<uint32_t> Cursor::m_cachedImages;
Cursor::Cursor() : m_imageID(0)
{
}
Cursor::Cursor(const CaptureConfig &config)
{
id cursor = cursor_currentSystemCursor();
BridgePoint hotSpot = cursor_hotSpot(cursor);
BridgePoint mouseLocation = event_mouseLocation();
id cursorImage = cursor_image(cursor);
id tiffData = cursorImage != nil ?
image_TIFFRepresentation(cursorImage) : nil;
if (tiffData == nil) {
m_imageID = Cursor::blankCursor();
m_position.rx() = 0;
m_position.ry() = 0;
return;
}
MurmurHash3_x86_32(
data_bytes(tiffData),
data_length(tiffData),
0,
&m_imageID);
if (m_cachedImages.find(m_imageID) == m_cachedImages.end()) {
m_cachedImages.insert(m_imageID);
bridgeWriteCursorFile(tiffData, m_imageID);
}
// The NSCursor Y coordinate's origin is at the bottom of the screen.
// Invert it.
mouseLocation.y =
QApplication::desktop()->screenGeometry().height() - mouseLocation.y;
m_position.rx() = mouseLocation.x - hotSpot.x - config.captureX;
m_position.ry() = mouseLocation.y - hotSpot.y - config.captureY;
}
} // namespace screencast
<|endoftext|> |
<commit_before>#include "SDLWindow.h"
#include "SDLApplication.h"
#ifdef HX_WINDOWS
#include <SDL_syswm.h>
#include <Windows.h>
#undef CreateWindow
#endif
namespace lime {
SDLWindow::SDLWindow (Application* application, int width, int height, int flags, const char* title) {
currentApplication = application;
this->flags = flags;
int sdlFlags = 0;
if (flags & WINDOW_FLAG_FULLSCREEN) sdlFlags |= SDL_WINDOW_FULLSCREEN_DESKTOP;
if (flags & WINDOW_FLAG_RESIZABLE) sdlFlags |= SDL_WINDOW_RESIZABLE;
if (flags & WINDOW_FLAG_BORDERLESS) sdlFlags |= SDL_WINDOW_BORDERLESS;
if (flags & WINDOW_FLAG_HARDWARE) {
sdlFlags |= SDL_WINDOW_OPENGL;
//sdlFlags |= SDL_WINDOW_ALLOW_HIGHDPI;
#if defined (HX_WINDOWS) && defined (NATIVE_TOOLKIT_SDL_ANGLE)
SDL_GL_SetAttribute (SDL_GL_CONTEXT_PROFILE_MASK, SDL_GL_CONTEXT_PROFILE_ES);
SDL_GL_SetAttribute (SDL_GL_CONTEXT_MAJOR_VERSION, 2);
SDL_GL_SetAttribute (SDL_GL_CONTEXT_MINOR_VERSION, 0);
SDL_SetHint (SDL_HINT_VIDEO_WIN_D3DCOMPILER, "d3dcompiler_47.dll");
#endif
if (flags & WINDOW_FLAG_DEPTH_BUFFER) {
SDL_GL_SetAttribute (SDL_GL_DEPTH_SIZE, 32 - (flags & WINDOW_FLAG_STENCIL_BUFFER) ? 8 : 0);
}
if (flags & WINDOW_FLAG_STENCIL_BUFFER) {
SDL_GL_SetAttribute (SDL_GL_STENCIL_SIZE, 8);
}
if (flags & WINDOW_FLAG_HW_AA_HIRES) {
SDL_GL_SetAttribute (SDL_GL_MULTISAMPLEBUFFERS, true);
SDL_GL_SetAttribute (SDL_GL_MULTISAMPLESAMPLES, 4);
} else if (flags & WINDOW_FLAG_HW_AA) {
SDL_GL_SetAttribute (SDL_GL_MULTISAMPLEBUFFERS, true);
SDL_GL_SetAttribute (SDL_GL_MULTISAMPLESAMPLES, 2);
}
}
sdlWindow = SDL_CreateWindow (title, SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, width, height, sdlFlags);
if (!sdlWindow) {
printf ("Could not create SDL window: %s.\n", SDL_GetError ());
}
((SDLApplication*)currentApplication)->RegisterWindow (this);
#ifdef HX_WINDOWS
HINSTANCE handle = ::GetModuleHandle (nullptr);
HICON icon = ::LoadIcon (handle, MAKEINTRESOURCE (1));
if (icon != nullptr) {
SDL_SysWMinfo wminfo;
SDL_VERSION (&wminfo.version);
if (SDL_GetWindowWMInfo (sdlWindow, &wminfo) == 1) {
HWND hwnd = wminfo.info.win.window;
::SetClassLong (hwnd, GCL_HICON, reinterpret_cast<LONG>(icon));
}
}
#endif
}
SDLWindow::~SDLWindow () {
if (sdlWindow) {
SDL_DestroyWindow (sdlWindow);
}
}
void SDLWindow::Close () {
if (sdlWindow) {
SDL_DestroyWindow (sdlWindow);
}
}
void SDLWindow::Focus () {
SDL_RaiseWindow (sdlWindow);
}
bool SDLWindow::GetEnableTextEvents () {
return SDL_IsTextInputActive ();
}
int SDLWindow::GetHeight () {
int width;
int height;
SDL_GetWindowSize (sdlWindow, &width, &height);
return height;
}
uint32_t SDLWindow::GetID () {
return SDL_GetWindowID (sdlWindow);
}
int SDLWindow::GetWidth () {
int width;
int height;
SDL_GetWindowSize (sdlWindow, &width, &height);
return width;
}
int SDLWindow::GetX () {
int x;
int y;
SDL_GetWindowPosition (sdlWindow, &x, &y);
return x;
}
int SDLWindow::GetY () {
int x;
int y;
SDL_GetWindowPosition (sdlWindow, &x, &y);
return y;
}
void SDLWindow::Move (int x, int y) {
SDL_SetWindowPosition (sdlWindow, x, y);
}
void SDLWindow::Resize (int width, int height) {
SDL_SetWindowSize (sdlWindow, width, height);
}
void SDLWindow::SetEnableTextEvents (bool enabled) {
if (enabled) {
SDL_StartTextInput ();
} else {
SDL_StopTextInput ();
}
}
bool SDLWindow::SetFullscreen (bool fullscreen) {
if (fullscreen) {
SDL_SetWindowFullscreen (sdlWindow, SDL_WINDOW_FULLSCREEN_DESKTOP);
} else {
SDL_SetWindowFullscreen (sdlWindow, 0);
}
return fullscreen;
}
void SDLWindow::SetIcon (ImageBuffer *imageBuffer) {
SDL_Surface *surface = SDL_CreateRGBSurfaceFrom (imageBuffer->data->Data (), imageBuffer->width, imageBuffer->height, imageBuffer->bitsPerPixel, imageBuffer->Stride (), 0x000000FF, 0x0000FF00, 0x00FF0000, 0xFF000000);
if (surface) {
SDL_SetWindowIcon (sdlWindow, surface);
SDL_FreeSurface (surface);
}
}
bool SDLWindow::SetMinimized (bool minimized) {
if (minimized) {
SDL_MinimizeWindow (sdlWindow);
} else {
SDL_RestoreWindow (sdlWindow);
}
return minimized;
}
const char* SDLWindow::SetTitle (const char* title) {
SDL_SetWindowTitle (sdlWindow, title);
return title;
}
Window* CreateWindow (Application* application, int width, int height, int flags, const char* title) {
return new SDLWindow (application, width, height, flags, title);
}
}<commit_msg>Added Alert function<commit_after>#include "SDLWindow.h"
#include "SDLApplication.h"
#ifdef HX_WINDOWS
#include <SDL_syswm.h>
#include <Windows.h>
#undef CreateWindow
#endif
namespace lime {
SDLWindow::SDLWindow (Application* application, int width, int height, int flags, const char* title) {
currentApplication = application;
this->flags = flags;
int sdlFlags = 0;
if (flags & WINDOW_FLAG_FULLSCREEN) sdlFlags |= SDL_WINDOW_FULLSCREEN_DESKTOP;
if (flags & WINDOW_FLAG_RESIZABLE) sdlFlags |= SDL_WINDOW_RESIZABLE;
if (flags & WINDOW_FLAG_BORDERLESS) sdlFlags |= SDL_WINDOW_BORDERLESS;
if (flags & WINDOW_FLAG_HARDWARE) {
sdlFlags |= SDL_WINDOW_OPENGL;
//sdlFlags |= SDL_WINDOW_ALLOW_HIGHDPI;
#if defined (HX_WINDOWS) && defined (NATIVE_TOOLKIT_SDL_ANGLE)
SDL_GL_SetAttribute (SDL_GL_CONTEXT_PROFILE_MASK, SDL_GL_CONTEXT_PROFILE_ES);
SDL_GL_SetAttribute (SDL_GL_CONTEXT_MAJOR_VERSION, 2);
SDL_GL_SetAttribute (SDL_GL_CONTEXT_MINOR_VERSION, 0);
SDL_SetHint (SDL_HINT_VIDEO_WIN_D3DCOMPILER, "d3dcompiler_47.dll");
#endif
if (flags & WINDOW_FLAG_DEPTH_BUFFER) {
SDL_GL_SetAttribute (SDL_GL_DEPTH_SIZE, 32 - (flags & WINDOW_FLAG_STENCIL_BUFFER) ? 8 : 0);
}
if (flags & WINDOW_FLAG_STENCIL_BUFFER) {
SDL_GL_SetAttribute (SDL_GL_STENCIL_SIZE, 8);
}
if (flags & WINDOW_FLAG_HW_AA_HIRES) {
SDL_GL_SetAttribute (SDL_GL_MULTISAMPLEBUFFERS, true);
SDL_GL_SetAttribute (SDL_GL_MULTISAMPLESAMPLES, 4);
} else if (flags & WINDOW_FLAG_HW_AA) {
SDL_GL_SetAttribute (SDL_GL_MULTISAMPLEBUFFERS, true);
SDL_GL_SetAttribute (SDL_GL_MULTISAMPLESAMPLES, 2);
}
}
sdlWindow = SDL_CreateWindow (title, SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, width, height, sdlFlags);
if (!sdlWindow) {
printf ("Could not create SDL window: %s.\n", SDL_GetError ());
}
((SDLApplication*)currentApplication)->RegisterWindow (this);
#ifdef HX_WINDOWS
HINSTANCE handle = ::GetModuleHandle (nullptr);
HICON icon = ::LoadIcon (handle, MAKEINTRESOURCE (1));
if (icon != nullptr) {
SDL_SysWMinfo wminfo;
SDL_VERSION (&wminfo.version);
if (SDL_GetWindowWMInfo (sdlWindow, &wminfo) == 1) {
HWND hwnd = wminfo.info.win.window;
::SetClassLong (hwnd, GCL_HICON, reinterpret_cast<LONG>(icon));
}
}
#endif
}
SDLWindow::~SDLWindow () {
if (sdlWindow) {
SDL_DestroyWindow (sdlWindow);
}
}
void SDLWindow::Close () {
if (sdlWindow) {
SDL_DestroyWindow (sdlWindow);
}
}
void SDLWindow::Focus () {
SDL_RaiseWindow (sdlWindow);
}
bool SDLWindow::GetEnableTextEvents () {
return SDL_IsTextInputActive ();
}
int SDLWindow::GetHeight () {
int width;
int height;
SDL_GetWindowSize (sdlWindow, &width, &height);
return height;
}
uint32_t SDLWindow::GetID () {
return SDL_GetWindowID (sdlWindow);
}
int SDLWindow::GetWidth () {
int width;
int height;
SDL_GetWindowSize (sdlWindow, &width, &height);
return width;
}
int SDLWindow::GetX () {
int x;
int y;
SDL_GetWindowPosition (sdlWindow, &x, &y);
return x;
}
int SDLWindow::GetY () {
int x;
int y;
SDL_GetWindowPosition (sdlWindow, &x, &y);
return y;
}
void SDLWindow::Move (int x, int y) {
SDL_SetWindowPosition (sdlWindow, x, y);
}
void SDLWindow::Resize (int width, int height) {
SDL_SetWindowSize (sdlWindow, width, height);
}
void SDLWindow::SetEnableTextEvents (bool enabled) {
if (enabled) {
SDL_StartTextInput ();
} else {
SDL_StopTextInput ();
}
}
bool SDLWindow::SetFullscreen (bool fullscreen) {
if (fullscreen) {
SDL_SetWindowFullscreen (sdlWindow, SDL_WINDOW_FULLSCREEN_DESKTOP);
} else {
SDL_SetWindowFullscreen (sdlWindow, 0);
}
return fullscreen;
}
void SDLWindow::SetIcon (ImageBuffer *imageBuffer) {
SDL_Surface *surface = SDL_CreateRGBSurfaceFrom (imageBuffer->data->Data (), imageBuffer->width, imageBuffer->height, imageBuffer->bitsPerPixel, imageBuffer->Stride (), 0x000000FF, 0x0000FF00, 0x00FF0000, 0xFF000000);
if (surface) {
SDL_SetWindowIcon (sdlWindow, surface);
SDL_FreeSurface (surface);
}
}
bool SDLWindow::SetMinimized (bool minimized) {
if (minimized) {
SDL_MinimizeWindow (sdlWindow);
} else {
SDL_RestoreWindow (sdlWindow);
}
return minimized;
}
const char* SDLWindow::SetTitle (const char* title) {
SDL_SetWindowTitle (sdlWindow, title);
return title;
}
void SDLWindow::Alert (int count, int speed, bool stop_on_foreground) {
SDL_SysWMinfo info;
SDL_VERSION (&info.version);
SDL_GetWindowWMInfo(sdlWindow, &info);
FLASHWINFO fi;
fi.cbSize = sizeof(FLASHWINFO);
fi.hwnd = info.info.win.window;
fi.dwFlags = stop_on_foreground ? FLASHW_ALL | FLASHW_TIMERNOFG : FLASHW_ALL | FLASHW_TIMER;
fi.uCount = count;
fi.dwTimeout = speed;
FlashWindowEx(&fi);
}
Window* CreateWindow (Application* application, int width, int height, int flags, const char* title) {
return new SDLWindow (application, width, height, flags, title);
}
}
<|endoftext|> |
<commit_before>/* This file is part of the KDE project
Copyright (C) 2007 Matthias Kretz <kretz@kde.org>
Permission to use, copy, modify, and distribute this software
and its documentation for any purpose and without fee is hereby
granted, provided that the above copyright notice appear in all
copies and that both that the copyright notice and this
permission notice and warranty disclaimer appear in supporting
documentation, and that the name of the author not be used in
advertising or publicity pertaining to distribution of the
software without specific, written prior permission.
The author disclaim 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, 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 <Phonon/MediaObject>
#include <QtGui/QApplication>
#include <QtGui/QMainWindow>
#include <QtGui/QDirModel>
#include <QtGui/QColumnView>
class MainWindow : public QMainWindow
{
Q_OBJECT
public:
MainWindow();
~MainWindow();
private slots:
void play(const QModelIndex &index);
private:
QColumnView m_fileView;
QDirModel m_model;
Phonon::MediaObject *m_media;
};
MainWindow::MainWindow()
: m_fileView(this),
m_media(0)
{
setCentralWidget(&m_fileView);
m_fileView.setModel(&m_model);
m_fileView.setFrameStyle(QFrame::NoFrame);
connect(&m_fileView, SIGNAL(updatePreviewWidget(const QModelIndex &)), SLOT(play(const QModelIndex &)));
}
MainWindow::~MainWindow()
{
delete m_media;
}
void MainWindow::play(const QModelIndex &index)
{
if (!m_media) {
m_media = Phonon::createPlayer(Phonon::MusicCategory);
}
m_media->setCurrentSource(m_model.filePath(index));
m_media->play();
}
int main(int argc, char **argv)
{
QApplication app(argc, argv);
QApplication::setApplicationName("Phonon Tutorial 1");
MainWindow mw;
mw.show();
return app.exec();
}
#include "tutorial1.moc"
<commit_msg>a simple commandline player<commit_after>/* This file is part of the KDE project
Copyright (C) 2008 Matthias Kretz <kretz@kde.org>
Permission to use, copy, modify, and distribute this software
and its documentation for any purpose and without fee is hereby
granted, provided that the above copyright notice appear in all
copies and that both that the copyright notice and this
permission notice and warranty disclaimer appear in supporting
documentation, and that the name of the author not be used in
advertising or publicity pertaining to distribution of the
software without specific, written prior permission.
The author disclaim 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, 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 <Phonon/MediaObject>
#include <Phonon/AudioOutput>
#include <QtCore/QCoreApplication>
#include <QtCore/QStringList>
int main(int argc, char **argv)
{
QCoreApplication app(argc, argv);
if (app.arguments().size() != 2) {
return -1;
}
QCoreApplication::setApplicationName("Phonon Tutorial 1");
Phonon::MediaObject media;
media.setCurrentSource(app.arguments().at(1));
Phonon::AudioOutput output;
Phonon::createPath(&media, &output);
QObject::connect(&media, SIGNAL(finished()), &app, SLOT(quit()));
media.play();
return app.exec();
}
<|endoftext|> |
<commit_before>/**
* @file sparse_coding_test.cpp
*
* Test for Sparse Coding
*/
// Note: We don't use BOOST_REQUIRE_CLOSE in the code below because we need
// to use FPC_WEAK, and it's not at all intuitive how to do that.
#include <armadillo>
#include <mlpack/methods/sparse_coding/sparse_coding.hpp>
#include <boost/test/unit_test.hpp>
using namespace arma;
using namespace mlpack;
using namespace mlpack::regression;
using namespace mlpack::sparse_coding;
BOOST_AUTO_TEST_SUITE(SparseCodingTest);
void VerifyCorrectness(vec beta, vec errCorr, double lambda)
{
const double tol = 1e-12;
size_t nDims = beta.n_elem;
for(size_t j = 0; j < nDims; j++)
{
if (beta(j) == 0)
{
// make sure that errCorr(j) <= lambda
BOOST_REQUIRE_SMALL(std::max(fabs(errCorr(j)) - lambda, 0.0), tol);
}
else if (beta(j) < 0)
{
// make sure that errCorr(j) == lambda
BOOST_REQUIRE_SMALL(errCorr(j) - lambda, tol);
}
else
{ // beta(j) > 0
// make sure that errCorr(j) == -lambda
BOOST_REQUIRE_SMALL(errCorr(j) + lambda, tol);
}
}
}
BOOST_AUTO_TEST_CASE(SparseCodingTestCodingStepLasso)
{
double lambda1 = 0.1;
uword nAtoms = 25;
mat X;
X.load("mnist_first250_training_4s_and_9s.arm");
uword nPoints = X.n_cols;
// normalize each point since these are images
for(uword i = 0; i < nPoints; i++) {
X.col(i) /= norm(X.col(i), 2);
}
SparseCoding sc(X, nAtoms, lambda1);
sc.DataDependentRandomInitDictionary();
sc.OptimizeCode();
mat D = sc.MatD();
mat Z = sc.MatZ();
for(uword i = 0; i < nPoints; i++) {
vec errCorr = trans(D) * (D * Z.unsafe_col(i) - X.unsafe_col(i));
VerifyCorrectness(Z.unsafe_col(i), errCorr, lambda1);
}
}
BOOST_AUTO_TEST_CASE(SparseCodingTestCodingStepElasticNet)
{
double lambda1 = 0.1;
double lambda2 = 0.2;
uword nAtoms = 25;
mat X;
X.load("mnist_first250_training_4s_and_9s.arm");
uword nPoints = X.n_cols;
// normalize each point since these are images
for(uword i = 0; i < nPoints; i++) {
X.col(i) /= norm(X.col(i), 2);
}
SparseCoding sc(X, nAtoms, lambda1, lambda2);
sc.DataDependentRandomInitDictionary();
sc.OptimizeCode();
mat D = sc.MatD();
mat Z = sc.MatZ();
for(uword i = 0; i < nPoints; i++) {
vec errCorr =
(trans(D) * D + lambda2 *
eye(nAtoms, nAtoms)) * Z.unsafe_col(i) - trans(D) * X.unsafe_col(i);
VerifyCorrectness(Z.unsafe_col(i), errCorr, lambda1);
}
}
BOOST_AUTO_TEST_CASE(SparseCodingTestDictionaryStep)
{
const double tol = 1e-12;
double lambda1 = 0.1;
uword nAtoms = 25;
mat X;
X.load("mnist_first250_training_4s_and_9s.arm");
uword nPoints = X.n_cols;
// normalize each point since these are images
for(uword i = 0; i < nPoints; i++) {
X.col(i) /= norm(X.col(i), 2);
}
SparseCoding sc(X, nAtoms, lambda1);
sc.DataDependentRandomInitDictionary();
sc.OptimizeCode();
mat D = sc.MatD();
mat Z = sc.MatZ();
X = D * Z;
sc.SetData(X);
sc.DataDependentRandomInitDictionary();
uvec adjacencies = find(Z);
sc.OptimizeDictionary(adjacencies);
mat D_hat = sc.MatD();
BOOST_REQUIRE_SMALL(norm(D - D_hat, "fro"), tol);
}
/*
BOOST_AUTO_TEST_CASE(SparseCodingTestWhole)
{
}
*/
BOOST_AUTO_TEST_SUITE_END();
<commit_msg>Update tests to reflect new method names.<commit_after>/**
* @file sparse_coding_test.cpp
*
* Test for Sparse Coding
*/
// Note: We don't use BOOST_REQUIRE_CLOSE in the code below because we need
// to use FPC_WEAK, and it's not at all intuitive how to do that.
#include <mlpack/core.hpp>
#include <mlpack/methods/sparse_coding/sparse_coding.hpp>
#include <boost/test/unit_test.hpp>
using namespace arma;
using namespace mlpack;
using namespace mlpack::regression;
using namespace mlpack::sparse_coding;
BOOST_AUTO_TEST_SUITE(SparseCodingTest);
void VerifyCorrectness(vec beta, vec errCorr, double lambda)
{
const double tol = 1e-12;
size_t nDims = beta.n_elem;
for(size_t j = 0; j < nDims; j++)
{
if (beta(j) == 0)
{
// Make sure that errCorr(j) <= lambda.
BOOST_REQUIRE_SMALL(std::max(fabs(errCorr(j)) - lambda, 0.0), tol);
}
else if (beta(j) < 0)
{
// Make sure that errCorr(j) == lambda.
BOOST_REQUIRE_SMALL(errCorr(j) - lambda, tol);
}
else // beta(j) > 0.
{
// Make sure that errCorr(j) == -lambda.
BOOST_REQUIRE_SMALL(errCorr(j) + lambda, tol);
}
}
}
BOOST_AUTO_TEST_CASE(SparseCodingTestCodingStepLasso)
{
double lambda1 = 0.1;
uword nAtoms = 25;
mat X;
X.load("mnist_first250_training_4s_and_9s.arm");
uword nPoints = X.n_cols;
// Normalize each point since these are images.
for (uword i = 0; i < nPoints; ++i)
X.col(i) /= norm(X.col(i), 2);
SparseCoding sc(X, nAtoms, lambda1);
sc.DataDependentRandomInitDictionary();
sc.OptimizeCode();
mat D = sc.Dictionary();
mat Z = sc.Codes();
for (uword i = 0; i < nPoints; ++i)
{
vec errCorr = trans(D) * (D * Z.unsafe_col(i) - X.unsafe_col(i));
VerifyCorrectness(Z.unsafe_col(i), errCorr, lambda1);
}
}
BOOST_AUTO_TEST_CASE(SparseCodingTestCodingStepElasticNet)
{
double lambda1 = 0.1;
double lambda2 = 0.2;
uword nAtoms = 25;
mat X;
X.load("mnist_first250_training_4s_and_9s.arm");
uword nPoints = X.n_cols;
// Normalize each point since these are images.
for (uword i = 0; i < nPoints; ++i)
X.col(i) /= norm(X.col(i), 2);
SparseCoding sc(X, nAtoms, lambda1, lambda2);
sc.DataDependentRandomInitDictionary();
sc.OptimizeCode();
mat D = sc.Dictionary();
mat Z = sc.Codes();
for(uword i = 0; i < nPoints; ++i)
{
vec errCorr = (trans(D) * D + lambda2 *
eye(nAtoms, nAtoms)) * Z.unsafe_col(i) - trans(D) * X.unsafe_col(i);
VerifyCorrectness(Z.unsafe_col(i), errCorr, lambda1);
}
}
BOOST_AUTO_TEST_CASE(SparseCodingTestDictionaryStep)
{
const double tol = 1e-12;
double lambda1 = 0.1;
uword nAtoms = 25;
mat X;
X.load("mnist_first250_training_4s_and_9s.arm");
uword nPoints = X.n_cols;
// Normalize each point since these are images.
for(uword i = 0; i < nPoints; ++i)
X.col(i) /= norm(X.col(i), 2);
SparseCoding sc(X, nAtoms, lambda1);
sc.DataDependentRandomInitDictionary();
sc.OptimizeCode();
mat D = sc.Dictionary();
mat Z = sc.Codes();
X = D * Z;
sc.Data() = X;
sc.DataDependentRandomInitDictionary();
uvec adjacencies = find(Z);
sc.OptimizeDictionary(adjacencies);
mat D_hat = sc.Dictionary();
BOOST_REQUIRE_SMALL(norm(D - D_hat, "fro"), tol);
}
/*
BOOST_AUTO_TEST_CASE(SparseCodingTestWhole)
{
}
*/
BOOST_AUTO_TEST_SUITE_END();
<|endoftext|> |
<commit_before>/*=========================================================================
*
* Copyright 2011-2013 The University of North Carolina at Chapel Hill
* All rights reserved.
*
* Licensed under the MADAI Software License. You may obtain a copy of
* this license at
*
* https://madai-public.cs.unc.edu/software/license/
*
* 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.
*
*=========================================================================*/
/**
PCADecompose
Decompose the model data from a directory structure.
*/
#include <iostream>
#include <fstream>
#include "ApplicationUtilities.h"
#include "GaussianProcessEmulator.h"
#include "GaussianProcessEmulatorDirectoryReader.h"
#include "GaussianProcessEmulatorSingleFileReader.h"
#include "GaussianProcessEmulatorSingleFileWriter.h"
#include "RuntimeParameterFileReader.h"
#include "Paths.h"
using madai::Paths;
int main( int argc, char ** argv ) {
std::string StatisticsDirectory;
std::string ModelOutputDirectory = Paths::DEFAULT_MODEL_OUTPUT_DIRECTORY;
std::string ExperimentalResultsDirectory = Paths::DEFAULT_EXPERIMENTAL_RESULTS_DIRECTORY;
double fractionResolvingPower = 0.95;
if ( argc > 1 ) {
StatisticsDirectory = std::string( argv[1] );
} else {
std::cerr << "Usage:\n"
<< " PCADecompose <StatisticsDirectory>\n"
<< "\n"
<< "This program performs a principal components analysis on \n"
<< "experimental data. It stores the results in \n"
<< "<StatisticsDirectory>" << Paths::SEPARATOR
<< Paths::PCA_DECOMPOSITION_FILE << "\n"
<< "\n"
<< "<StatisticsDirectory> is the directory in which all \n"
<< "statistics data are stored. It contains the parameter file "
<< Paths::RUNTIME_PARAMETER_FILE << "\n"
<< "\n"
<< "Format of entries in " << Paths::RUNTIME_PARAMETER_FILE
<< ":\n\n"
<< "MODEL_OUTPUT_DIRECTORY <value> (default: "
<< Paths::DEFAULT_MODEL_OUTPUT_DIRECTORY << ")\n"
<< "EXPERIMENTAL_RESULTS_DIRECTORY <value> (default: "
<< Paths::DEFAULT_EXPERIMENTAL_RESULTS_DIRECTORY << ")\n";
return EXIT_FAILURE;
}
madai::GaussianProcessEmulator gpme;
if ( StatisticsDirectory == "-" ) { // Check to see if read from cin
madai::GaussianProcessEmulatorSingleFileReader singleFileReader;
singleFileReader.LoadTrainingData(&gpme, std::cin);
} else { // Reads from directory structure
madai::EnsurePathSeparatorAtEnd( StatisticsDirectory );
madai::RuntimeParameterFileReader RPFR;
RPFR.ParseFile( StatisticsDirectory +
madai::Paths::RUNTIME_PARAMETER_FILE ); // Read in runtime parameters
char** Args = RPFR.GetArguments();
int NArgs = RPFR.GetNumberOfArguments();
for ( unsigned int i = 0; i < NArgs; i++ ) {
std::string argString(Args[i]);
if ( argString == "MODEL_OUTPUT_DIRECTORY" ) {
ModelOutputDirectory = std::string( Args[i+1] );
i++;
} else if ( argString == "EXPERIMENTAL_RESULTS_DIRECTORY" ) {
ExperimentalResultsDirectory = std::string( Args[i+1] );
i++;
} else {
// Skip other elements since I'm using a single configuration file
}
}
// Read in the training data
std::string MOD = StatisticsDirectory + ModelOutputDirectory;
std::string ERD = StatisticsDirectory + ExperimentalResultsDirectory;
madai::GaussianProcessEmulatorDirectoryReader directoryReader;
if ( !directoryReader.LoadTrainingData(&gpme, MOD, StatisticsDirectory, ERD ) ) {
std::cerr << "Error Loading Training Data.\n";
return EXIT_FAILURE;
}
}
std::string outputFileName = StatisticsDirectory + madai::Paths::PCA_DECOMPOSITION_FILE;
// get the PCA decomposition
if ( !gpme.PrincipalComponentDecompose() ) {
return EXIT_FAILURE;
}
std::ofstream os( outputFileName.c_str() );
madai::GaussianProcessEmulatorSingleFileWriter singleFileWriter;
singleFileWriter.WritePCA(&gpme,os);
return EXIT_SUCCESS;
}
<commit_msg>Cleaned up PCADecompose<commit_after>/*=========================================================================
*
* Copyright 2011-2013 The University of North Carolina at Chapel Hill
* All rights reserved.
*
* Licensed under the MADAI Software License. You may obtain a copy of
* this license at
*
* https://madai-public.cs.unc.edu/software/license/
*
* 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 "ApplicationUtilities.h"
#include "GaussianProcessEmulator.h"
#include "GaussianProcessEmulatorDirectoryReader.h"
#include "GaussianProcessEmulatorSingleFileWriter.h"
#include "RuntimeParameterFileReader.h"
#include "Paths.h"
using madai::Paths;
int main( int argc, char ** argv )
{
std::string statisticsDirectory;
if ( argc > 1 ) {
statisticsDirectory = std::string( argv[1] );
madai::EnsurePathSeparatorAtEnd( statisticsDirectory );
} else {
std::cerr << "Usage:\n"
<< " PCADecompose <StatisticsDirectory>\n"
<< "\n"
<< "This program performs a principal components analysis on \n"
<< "experimental data. It stores the results in \n"
<< "<StatisticsDirectory>" << Paths::SEPARATOR
<< Paths::PCA_DECOMPOSITION_FILE << "\n"
<< "\n"
<< "<StatisticsDirectory> is the directory in which all \n"
<< "statistics data are stored. It contains the parameter file "
<< Paths::RUNTIME_PARAMETER_FILE << "\n"
<< "\n"
<< "Format of entries in " << Paths::RUNTIME_PARAMETER_FILE
<< ":\n\n"
<< "MODEL_OUTPUT_DIRECTORY <value> (default: "
<< Paths::DEFAULT_MODEL_OUTPUT_DIRECTORY << ")\n"
<< "EXPERIMENTAL_RESULTS_DIRECTORY <value> (default: "
<< Paths::DEFAULT_EXPERIMENTAL_RESULTS_DIRECTORY << ")\n";
return EXIT_FAILURE;
}
madai::GaussianProcessEmulator gpme;
// Read in runtime parameters
madai::RuntimeParameterFileReader runtimeParameters;
std::string runtimeParameterFile = statisticsDirectory +
madai::Paths::RUNTIME_PARAMETER_FILE;
if ( !runtimeParameters.ParseFile( runtimeParameterFile ) ) {
std::cerr << "Could not open runtime parameter file '"
<< runtimeParameterFile << "'\n";
return EXIT_FAILURE;
}
std::string modelOutputDirectory =
Paths::DEFAULT_MODEL_OUTPUT_DIRECTORY;
std::string experimentalResultsDirectory =
Paths::DEFAULT_EXPERIMENTAL_RESULTS_DIRECTORY;
if ( runtimeParameters.HasOption( "MODEL_OUTPUT_DIRECTORY" ) ) {
modelOutputDirectory =
runtimeParameters.GetOption( "MODEL_OUTPUT_DIRECTORY" );
}
if ( runtimeParameters.HasOption( "EXPERIMENTAL_RESULTS_DIRECTORY" ) ) {
experimentalResultsDirectory =
runtimeParameters.GetOption( "EXPERIMENTAL_RESULTS_DIRECTORY" );
}
// Read in the training data
std::string modelOutputPath = statisticsDirectory + modelOutputDirectory;
std::string experimentalResultsPath = statisticsDirectory +
experimentalResultsDirectory;
madai::GaussianProcessEmulatorDirectoryReader directoryReader;
if ( !directoryReader.LoadTrainingData(&gpme,
modelOutputPath,
statisticsDirectory,
experimentalResultsPath ) ) {
std::cerr << "Error loading training data.\n";
return EXIT_FAILURE;
}
std::string outputFileName = statisticsDirectory +
madai::Paths::PCA_DECOMPOSITION_FILE;
// get the PCA decomposition
if ( !gpme.PrincipalComponentDecompose() ) {
return EXIT_FAILURE;
}
std::ofstream os( outputFileName.c_str() );
madai::GaussianProcessEmulatorSingleFileWriter singleFileWriter;
singleFileWriter.WritePCA(&gpme,os);
return EXIT_SUCCESS;
}
<|endoftext|> |
<commit_before>/** \copyright
* Copyright (c) 2016, Sidney McHarg
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* - Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* - Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
* \file main.cxx
*
* For now just a test bed for FreeRTOSTCP integration. Eventually:
*
* A simple application to act as a CAN-TCP bridge. This application creates no
* OpenLCB node, just forwards CAN packets to/from the host, in gridconnect
* format.
* Based on work by Balazs Racz
*
* @author Sidney McHarg
* @date 26 March 2016
*/
#include <fcntl.h>
#include <stdio.h>
#include <unistd.h>
#include "can_frame.h"
#include "executor/Executor.hxx"
#include "nmranet_config.h"
#include "os/os.h"
#include "utils/GridConnectHub.hxx"
#include "utils/GcTcpHub.hxx"
#include "utils/Hub.hxx"
#include "utils/HubDevice.hxx"
#include "utils/blinker.h"
#include <netinet/tcp.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#define VERSION "can_eth Vrs 0.1"
Executor<1> g_executor("g_executor", 0, 1024);
Service g_service(&g_executor);
CanHubFlow can_hub0(&g_service);
OVERRIDE_CONST(gc_generate_newlines, 0);
OVERRIDE_CONST(can_tx_buffer_size, 8);
OVERRIDE_CONST(can_rx_buffer_size, 8);
OVERRIDE_CONST(serial_tx_buffer_size, 64);
OVERRIDE_CONST(serial_rx_buffer_size, 64);
#ifdef BOARD_LAUNCHPAD_EK
OVERRIDE_CONST(main_thread_stack_size, 2500);
#else
OVERRIDE_CONST(main_thread_stack_size, 900);
#endif
/** Entry point to application.
* @param argc number of command line arguments
* @param argv array of command line arguments
* @return 0, should never return
*/
int appl_main(int argc, char* argv[])
{
const int listen_port = 12021;
int serial_fd = ::open("/dev/ser0", O_RDWR); // or /dev/ser0
HASSERT(serial_fd >= 0);
printf(VERSION);
printf(" started, listening on port %d\n",listen_port);
GcTcpHub hub(&can_hub0,listen_port);
int can_fd = ::open("/dev/can0", O_RDWR);
HASSERT(can_fd >= 0);
FdHubPort<CanHubFlow> can_hub_port(
&can_hub0, can_fd, EmptyNotifiable::DefaultInstance());
while(1) {
sleep(1);
resetblink(1);
sleep(1);
resetblink(0);
}
return 0;
}
<commit_msg>Adds an (optional) USB port to the can-eth application.<commit_after>/** \copyright
* Copyright (c) 2016, Sidney McHarg
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* - Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* - Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
* \file main.cxx
*
* For now just a test bed for FreeRTOSTCP integration. Eventually:
*
* A simple application to act as a CAN-TCP bridge. This application creates no
* OpenLCB node, just forwards CAN packets to/from the host, in gridconnect
* format.
* Based on work by Balazs Racz
*
* @author Sidney McHarg
* @date 26 March 2016
*/
#include <fcntl.h>
#include <stdio.h>
#include <unistd.h>
#include "can_frame.h"
#include "executor/Executor.hxx"
#include "nmranet_config.h"
#include "os/os.h"
#include "utils/GridConnectHub.hxx"
#include "utils/GcTcpHub.hxx"
#include "utils/Hub.hxx"
#include "utils/HubDevice.hxx"
#include "utils/blinker.h"
#include <netinet/tcp.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#define VERSION "can_eth Vrs 0.1"
// Uncomment this to enable the USB port as well.
// #define SNIFF_ON_USB
Executor<1> g_executor("g_executor", 0, 1024);
Service g_service(&g_executor);
CanHubFlow can_hub0(&g_service);
OVERRIDE_CONST(gc_generate_newlines, 0);
OVERRIDE_CONST(can_tx_buffer_size, 8);
OVERRIDE_CONST(can_rx_buffer_size, 8);
OVERRIDE_CONST(serial_tx_buffer_size, 64);
OVERRIDE_CONST(serial_rx_buffer_size, 64);
#ifdef BOARD_LAUNCHPAD_EK
OVERRIDE_CONST(main_thread_stack_size, 2500);
#else
OVERRIDE_CONST(main_thread_stack_size, 900);
#endif
/** Entry point to application.
* @param argc number of command line arguments
* @param argv array of command line arguments
* @return 0, should never return
*/
int appl_main(int argc, char* argv[])
{
const int listen_port = 12021;
int serial_fd = ::open("/dev/ser0", O_RDWR); // or /dev/ser0
HASSERT(serial_fd >= 0);
printf(VERSION);
printf(" started, listening on port %d\n",listen_port);
GcTcpHub hub(&can_hub0,listen_port);
#ifdef SNIFF_ON_USB
int usb_fd = ::open("/dev/serUSB0", O_RDWR);
HASSERT(usb_fd >= 0);
create_gc_port_for_can_hub(&can_hub0, usb_fd);
#endif
int can_fd = ::open("/dev/can0", O_RDWR);
HASSERT(can_fd >= 0);
FdHubPort<CanHubFlow> can_hub_port(
&can_hub0, can_fd, EmptyNotifiable::DefaultInstance());
while(1) {
sleep(1);
resetblink(1);
sleep(1);
resetblink(0);
}
return 0;
}
<|endoftext|> |
<commit_before>/* -*- mode: c++; c-basic-offset:4 -*-
uiserver/encryptemailcontroller.cpp
This file is part of Kleopatra, the KDE keymanager
Copyright (c) 2007 Klarälvdalens Datakonsult AB
Kleopatra 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.
Kleopatra 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
In addition, as a special exception, the copyright holders give
permission to link the code of this program with any edition of
the Qt library by Trolltech AS, Norway (or with modified versions
of Qt that use the same license as Qt), and distribute linked
combinations including the two. You must obey the GNU General
Public License in all respects for all of the code used other than
Qt. If you modify this file, you may extend this exception to
your version of the file, but you are not obligated to do so. If
you do not wish to do so, delete this exception statement from
your version.
*/
#include "encryptemailcontroller.h"
#include "kleo-assuan.h"
#include "assuancommand.h"
#include "certificateresolver.h"
#include "signencryptwizard.h"
#include "encryptemailtask.h"
#include "input.h"
#include "output.h"
#include <utils/stl_util.h>
#include <kmime/kmime_header_parsing.h>
#include <KLocale>
#include <QPointer>
#include <QTimer>
#include <boost/bind.hpp>
using namespace Kleo;
using namespace boost;
using namespace GpgME;
using namespace KMime::Types;
class EncryptEMailController::Private {
friend class ::Kleo::EncryptEMailController;
EncryptEMailController * const q;
public:
explicit Private( EncryptEMailController * qq );
private:
void slotWizardRecipientsResolved();
void slotWizardCanceled();
void slotTaskDone();
private:
void ensureWizardCreated();
void ensureWizardVisible();
void cancelAllTasks();
void schedule();
shared_ptr<EncryptEMailTask> takeRunnable( GpgME::Protocol proto );
void connectTask( const shared_ptr<Task> & task, unsigned int idx );
private:
std::vector< shared_ptr<EncryptEMailTask> > runnable, completed;
shared_ptr<EncryptEMailTask> cms, openpgp;
weak_ptr<AssuanCommand> command;
QPointer<SignEncryptWizard> wizard;
Protocol protocol;
};
EncryptEMailController::Private::Private( EncryptEMailController * qq )
: q( qq ),
runnable(),
cms(),
openpgp(),
command(),
wizard(),
protocol( UnknownProtocol )
{
}
EncryptEMailController::EncryptEMailController( QObject * p )
: QObject( p ), d( new Private( this ) )
{
}
EncryptEMailController::~EncryptEMailController() {
if ( d->wizard && !d->wizard->isVisible() )
delete d->wizard;
//d->wizard->close(); ### ?
}
void EncryptEMailController::setProtocol( Protocol proto ) {
assuan_assert( d->protocol == UnknownProtocol ||
d->protocol == proto );
d->protocol = proto;
if ( d->wizard )
d->wizard->setProtocol( proto );
}
Protocol EncryptEMailController::protocol() const {
return d->protocol;
}
const char * EncryptEMailController::protocolAsString() const {
switch ( d->protocol ) {
case OpenPGP: return "OpenPGP";
case CMS: return "CMS";
default:
throw assuan_exception( gpg_error( GPG_ERR_INTERNAL ),
i18n("Call to EncryptEMailController::protocolAsString() is ambiguous.") );
}
}
void EncryptEMailController::setCommand( const shared_ptr<AssuanCommand> & cmd ) {
d->command = cmd;
}
void EncryptEMailController::startResolveRecipients( const std::vector<Mailbox> & recipients ) {
const std::vector< std::vector<Key> > keys = CertificateResolver::resolveRecipients( recipients, d->protocol );
assuan_assert( keys.size() == static_cast<size_t>( recipients.size() ) );
d->ensureWizardCreated();
d->wizard->setRecipientsAndCandidates( recipients, keys );
if ( d->wizard->canGoToNextPage() ) {
d->wizard->next();
QTimer::singleShot( 0, this, SIGNAL(recipientsResolved()) );
} else {
d->ensureWizardVisible();
}
}
void EncryptEMailController::Private::slotWizardRecipientsResolved() {
emit q->recipientsResolved();
}
void EncryptEMailController::Private::slotWizardCanceled() {
emit q->error( gpg_error( GPG_ERR_CANCELED ), i18n("User cancel") );
}
void EncryptEMailController::importIO() {
const shared_ptr<AssuanCommand> cmd = d->command.lock();
assuan_assert( cmd );
const std::vector< shared_ptr<Input> > & inputs = cmd->inputs();
assuan_assert( !inputs.empty() );
const std::vector< shared_ptr<Output> > & outputs = cmd->outputs();
assuan_assert( outputs.size() == inputs.size() );
std::vector< shared_ptr<EncryptEMailTask> > tasks;
tasks.reserve( inputs.size() );
d->ensureWizardCreated();
const std::vector<Key> keys = d->wizard->resolvedCertificates();
assuan_assert( !keys.empty() );
for ( unsigned int i = 0, end = inputs.size() ; i < end ; ++i ) {
const shared_ptr<EncryptEMailTask> task( new EncryptEMailTask );
task->setInput( inputs[i] );
task->setOutput( outputs[i] );
task->setRecipients( keys );
tasks.push_back( task );
}
d->runnable.swap( tasks );
}
void EncryptEMailController::start() {
int i = 0;
Q_FOREACH( const shared_ptr<Task> task, d->runnable )
d->connectTask( task, i++ );
d->schedule();
}
void EncryptEMailController::Private::schedule() {
if ( !cms )
if ( const shared_ptr<EncryptEMailTask> t = takeRunnable( CMS ) ) {
t->start();
cms = t;
}
if ( !openpgp )
if ( const shared_ptr<EncryptEMailTask> t = takeRunnable( OpenPGP ) ) {
t->start();
openpgp = t;
}
if ( !cms && !openpgp ) {
assuan_assert( runnable.empty() );
emit q->done();
}
}
shared_ptr<EncryptEMailTask> EncryptEMailController::Private::takeRunnable( GpgME::Protocol proto ) {
const std::vector< shared_ptr<EncryptEMailTask> >::iterator it
= std::find_if( runnable.begin(), runnable.end(),
bind( &Task::protocol, _1 ) == proto );
if ( it == runnable.end() )
return shared_ptr<EncryptEMailTask>();
shared_ptr<EncryptEMailTask> result = *it;
runnable.erase( it );
return result;
}
void EncryptEMailController::Private::connectTask( const shared_ptr<Task> & t, unsigned int idx ) {
connect( t.get(), SIGNAL(result(boost::shared_ptr<const Kleo::Task::Result>)),
q, SLOT(slotTaskDone()) );
connect( t.get(), SIGNAL(error(int,QString)), q, SLOT(slotTaskDone()) );
ensureWizardCreated();
wizard->connectTask( t, idx );
}
void EncryptEMailController::Private::slotTaskDone() {
assert( q->sender() );
// We could just delete the tasks here, but we can't use
// Qt::QueuedConnection here (we need sender()) and other slots
// might not yet have executed. Therefore, we push completed tasks
// into a burial container
if ( q->sender() == cms.get() ) {
completed.push_back( cms );
cms.reset();
} else if ( q->sender() == openpgp.get() ) {
completed.push_back( openpgp );
openpgp.reset();
}
QTimer::singleShot( 0, q, SIGNAL(schedule()) );
}
void EncryptEMailController::cancel() {
try {
if ( d->wizard )
d->wizard->close();
d->cancelAllTasks();
} catch ( const std::exception & e ) {
qDebug( "Caught exception: %s", e.what() );
}
}
void EncryptEMailController::Private::cancelAllTasks() {
// we just kill all runnable tasks - this will not result in
// signal emissions.
runnable.clear();
// a cancel() will result in a call to
if ( cms )
cms->cancel();
if ( openpgp )
openpgp->cancel();
}
void EncryptEMailController::Private::ensureWizardCreated() {
if ( wizard )
return;
SignEncryptWizard * w = new SignEncryptWizard;
if ( const shared_ptr<AssuanCommand> cmd = command.lock() )
w = cmd->applyWindowID( w );
w->setWindowTitle( i18n("Encrypt EMail Wizard") );
w->setMode( SignEncryptWizard::EncryptEMail );
w->setAttribute( Qt::WA_DeleteOnClose );
connect( w, SIGNAL(recipientsResolved()), q, SLOT(slotWizardRecipientsResolved()) );
connect( w, SIGNAL(canceled()), q, SLOT(slotWizardCanceled()) );
w->setProtocol( protocol );
w->show();//temporary hack to initialize and start the wizard
w->hide();
wizard = w;
}
void EncryptEMailController::Private::ensureWizardVisible() {
ensureWizardCreated();
if ( wizard->isVisible() )
wizard->raise();
else
wizard->show();
}
#include "moc_encryptemailcontroller.cpp"
<commit_msg>++const<commit_after>/* -*- mode: c++; c-basic-offset:4 -*-
uiserver/encryptemailcontroller.cpp
This file is part of Kleopatra, the KDE keymanager
Copyright (c) 2007 Klarälvdalens Datakonsult AB
Kleopatra 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.
Kleopatra 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
In addition, as a special exception, the copyright holders give
permission to link the code of this program with any edition of
the Qt library by Trolltech AS, Norway (or with modified versions
of Qt that use the same license as Qt), and distribute linked
combinations including the two. You must obey the GNU General
Public License in all respects for all of the code used other than
Qt. If you modify this file, you may extend this exception to
your version of the file, but you are not obligated to do so. If
you do not wish to do so, delete this exception statement from
your version.
*/
#include "encryptemailcontroller.h"
#include "kleo-assuan.h"
#include "assuancommand.h"
#include "certificateresolver.h"
#include "signencryptwizard.h"
#include "encryptemailtask.h"
#include "input.h"
#include "output.h"
#include <utils/stl_util.h>
#include <kmime/kmime_header_parsing.h>
#include <KLocale>
#include <QPointer>
#include <QTimer>
#include <boost/bind.hpp>
using namespace Kleo;
using namespace boost;
using namespace GpgME;
using namespace KMime::Types;
class EncryptEMailController::Private {
friend class ::Kleo::EncryptEMailController;
EncryptEMailController * const q;
public:
explicit Private( EncryptEMailController * qq );
private:
void slotWizardRecipientsResolved();
void slotWizardCanceled();
void slotTaskDone();
private:
void ensureWizardCreated();
void ensureWizardVisible();
void cancelAllTasks();
void schedule();
shared_ptr<EncryptEMailTask> takeRunnable( GpgME::Protocol proto );
void connectTask( const shared_ptr<Task> & task, unsigned int idx );
private:
std::vector< shared_ptr<EncryptEMailTask> > runnable, completed;
shared_ptr<EncryptEMailTask> cms, openpgp;
weak_ptr<AssuanCommand> command;
QPointer<SignEncryptWizard> wizard;
Protocol protocol;
};
EncryptEMailController::Private::Private( EncryptEMailController * qq )
: q( qq ),
runnable(),
cms(),
openpgp(),
command(),
wizard(),
protocol( UnknownProtocol )
{
}
EncryptEMailController::EncryptEMailController( QObject * p )
: QObject( p ), d( new Private( this ) )
{
}
EncryptEMailController::~EncryptEMailController() {
if ( d->wizard && !d->wizard->isVisible() )
delete d->wizard;
//d->wizard->close(); ### ?
}
void EncryptEMailController::setProtocol( Protocol proto ) {
assuan_assert( d->protocol == UnknownProtocol ||
d->protocol == proto );
d->protocol = proto;
if ( d->wizard )
d->wizard->setProtocol( proto );
}
Protocol EncryptEMailController::protocol() const {
return d->protocol;
}
const char * EncryptEMailController::protocolAsString() const {
switch ( d->protocol ) {
case OpenPGP: return "OpenPGP";
case CMS: return "CMS";
default:
throw assuan_exception( gpg_error( GPG_ERR_INTERNAL ),
i18n("Call to EncryptEMailController::protocolAsString() is ambiguous.") );
}
}
void EncryptEMailController::setCommand( const shared_ptr<AssuanCommand> & cmd ) {
d->command = cmd;
}
void EncryptEMailController::startResolveRecipients( const std::vector<Mailbox> & recipients ) {
const std::vector< std::vector<Key> > keys = CertificateResolver::resolveRecipients( recipients, d->protocol );
assuan_assert( keys.size() == static_cast<size_t>( recipients.size() ) );
d->ensureWizardCreated();
d->wizard->setRecipientsAndCandidates( recipients, keys );
if ( d->wizard->canGoToNextPage() ) {
d->wizard->next();
QTimer::singleShot( 0, this, SIGNAL(recipientsResolved()) );
} else {
d->ensureWizardVisible();
}
}
void EncryptEMailController::Private::slotWizardRecipientsResolved() {
emit q->recipientsResolved();
}
void EncryptEMailController::Private::slotWizardCanceled() {
emit q->error( gpg_error( GPG_ERR_CANCELED ), i18n("User cancel") );
}
void EncryptEMailController::importIO() {
const shared_ptr<AssuanCommand> cmd = d->command.lock();
assuan_assert( cmd );
const std::vector< shared_ptr<Input> > & inputs = cmd->inputs();
assuan_assert( !inputs.empty() );
const std::vector< shared_ptr<Output> > & outputs = cmd->outputs();
assuan_assert( outputs.size() == inputs.size() );
std::vector< shared_ptr<EncryptEMailTask> > tasks;
tasks.reserve( inputs.size() );
d->ensureWizardCreated();
const std::vector<Key> keys = d->wizard->resolvedCertificates();
assuan_assert( !keys.empty() );
for ( unsigned int i = 0, end = inputs.size() ; i < end ; ++i ) {
const shared_ptr<EncryptEMailTask> task( new EncryptEMailTask );
task->setInput( inputs[i] );
task->setOutput( outputs[i] );
task->setRecipients( keys );
tasks.push_back( task );
}
d->runnable.swap( tasks );
}
void EncryptEMailController::start() {
int i = 0;
Q_FOREACH( const shared_ptr<Task> task, d->runnable )
d->connectTask( task, i++ );
d->schedule();
}
void EncryptEMailController::Private::schedule() {
if ( !cms )
if ( const shared_ptr<EncryptEMailTask> t = takeRunnable( CMS ) ) {
t->start();
cms = t;
}
if ( !openpgp )
if ( const shared_ptr<EncryptEMailTask> t = takeRunnable( OpenPGP ) ) {
t->start();
openpgp = t;
}
if ( !cms && !openpgp ) {
assuan_assert( runnable.empty() );
emit q->done();
}
}
shared_ptr<EncryptEMailTask> EncryptEMailController::Private::takeRunnable( GpgME::Protocol proto ) {
const std::vector< shared_ptr<EncryptEMailTask> >::iterator it
= std::find_if( runnable.begin(), runnable.end(),
bind( &Task::protocol, _1 ) == proto );
if ( it == runnable.end() )
return shared_ptr<EncryptEMailTask>();
const shared_ptr<EncryptEMailTask> result = *it;
runnable.erase( it );
return result;
}
void EncryptEMailController::Private::connectTask( const shared_ptr<Task> & t, unsigned int idx ) {
connect( t.get(), SIGNAL(result(boost::shared_ptr<const Kleo::Task::Result>)),
q, SLOT(slotTaskDone()) );
connect( t.get(), SIGNAL(error(int,QString)), q, SLOT(slotTaskDone()) );
ensureWizardCreated();
wizard->connectTask( t, idx );
}
void EncryptEMailController::Private::slotTaskDone() {
assert( q->sender() );
// We could just delete the tasks here, but we can't use
// Qt::QueuedConnection here (we need sender()) and other slots
// might not yet have executed. Therefore, we push completed tasks
// into a burial container
if ( q->sender() == cms.get() ) {
completed.push_back( cms );
cms.reset();
} else if ( q->sender() == openpgp.get() ) {
completed.push_back( openpgp );
openpgp.reset();
}
QTimer::singleShot( 0, q, SIGNAL(schedule()) );
}
void EncryptEMailController::cancel() {
try {
if ( d->wizard )
d->wizard->close();
d->cancelAllTasks();
} catch ( const std::exception & e ) {
qDebug( "Caught exception: %s", e.what() );
}
}
void EncryptEMailController::Private::cancelAllTasks() {
// we just kill all runnable tasks - this will not result in
// signal emissions.
runnable.clear();
// a cancel() will result in a call to
if ( cms )
cms->cancel();
if ( openpgp )
openpgp->cancel();
}
void EncryptEMailController::Private::ensureWizardCreated() {
if ( wizard )
return;
SignEncryptWizard * w = new SignEncryptWizard;
if ( const shared_ptr<AssuanCommand> cmd = command.lock() )
w = cmd->applyWindowID( w );
w->setWindowTitle( i18n("Encrypt EMail Wizard") );
w->setMode( SignEncryptWizard::EncryptEMail );
w->setAttribute( Qt::WA_DeleteOnClose );
connect( w, SIGNAL(recipientsResolved()), q, SLOT(slotWizardRecipientsResolved()) );
connect( w, SIGNAL(canceled()), q, SLOT(slotWizardCanceled()) );
w->setProtocol( protocol );
w->show();//temporary hack to initialize and start the wizard
w->hide();
wizard = w;
}
void EncryptEMailController::Private::ensureWizardVisible() {
ensureWizardCreated();
if ( wizard->isVisible() )
wizard->raise();
else
wizard->show();
}
#include "moc_encryptemailcontroller.cpp"
<|endoftext|> |
<commit_before>#include "extended_infomax.h"
#include <cmath>
#include "fastapprox-0/fasthyperbolic.h"
#include "fastapprox-0/fastlog.h"
#include <pmmintrin.h>
#include <cstddef>
namespace curveica{
template<>
void extended_infomax_ica<float>::operator()(float * z1, float * b, int const * signs, float* phi, float* means_logp) const {
for(unsigned int c = 0 ; c < NC_ ; ++c){
__m128d vsum = _mm_set1_pd(0.0d);
float k = signs[c];
const __m128 bias = _mm_set1_ps(b[c]);
__m128 phi_signs = (k<0)?_mm_set1_ps(-1):_mm_set1_ps(1);
for(unsigned int f = 0; f < NF_ ; f+=4){
__m128 z2 = _mm_load_ps(&z1[c*NF_+f]);
z2 = _mm_add_ps(z2,bias);
//Computes mean_logp
const __m128 _1 = _mm_set1_ps(1);
const __m128 m0_5 = _mm_set1_ps(-0.5);
if(k<0){
__m128 a = _mm_sub_ps(z2,_1);
a = _mm_mul_ps(a,a);
a = _mm_mul_ps(m0_5,a);
a = vfastexp(a);
__m128 b = _mm_add_ps(z2,_1);
b = _mm_mul_ps(b,b);
b = _mm_mul_ps(m0_5,b);
b = vfastexp(b);
a = _mm_add_ps(a,b);
a = vfastlog(a);
vsum=_mm_add_pd(vsum,_mm_cvtps_pd(a));
vsum=_mm_add_pd(vsum,_mm_cvtps_pd(_mm_movehl_ps(a,a)));
}
else{
__m128 y = vfastcosh(z2);
y = vfastlog(y);
__m128 z2sq = _mm_mul_ps(z2,z2);
y = _mm_mul_ps(_mm_set1_ps(-1),y);
z2sq = _mm_mul_ps(_mm_set1_ps(0.5),z2sq);
y = _mm_sub_ps(y,z2sq);
vsum=_mm_add_pd(vsum,_mm_cvtps_pd(y));
vsum=_mm_add_pd(vsum,_mm_cvtps_pd(_mm_movehl_ps(y,y)));
}
//compute phi
__m128 y = vfasttanh(z2);
y = _mm_mul_ps(phi_signs,y);
__m128 v = _mm_add_ps(z2,y);
_mm_store_ps(&phi[c*NF_+f],v);
}
double sum;
vsum = _mm_hadd_pd(vsum, vsum);
_mm_store_sd(&sum, vsum);
means_logp[c] = 1/(float)NF_*sum;
}
}
//template<>
//void extended_infomax_ica<double>::operator()(double * z1, double * b, double * signs, double* phi, double* means_logp) const {
// for(unsigned int c = 0 ; c < NC_ ; ++c){
// double current = 0;
// double k = signs[c];
// double bias = b[c];
// for(unsigned int f = 0; f < NF_ ; f++){
// double z2 = z1[c*NF_+f] + bias;
// double y = std::tanh(z2);
// if(k<0){
// current+= std::log((std::exp(-0.5*std::pow(z2-1,2)) + std::exp(-0.5*std::pow(z2+1,2))));
// phi[c*NF_+f] = z2 - y;
// }
// else{
// current+= -std::log(std::cosh(z2)) - 0.5*z2*z2;
// phi[c*NF_+f] = z2 + y;
// }
// }
// means_logp[c] = current/(double)NF_;
// }
//}
template<>
void extended_infomax_ica<double>::operator()(double * z1, double * b, int const * signs, double* phi, double* means_logp) const {
for(unsigned int c = 0 ; c < NC_ ; ++c){
__m128d vsum = _mm_set1_pd(0.0d);
float k = signs[c];
const __m128 bias = _mm_set1_ps(b[c]);
__m128 phi_signs = (k<0)?_mm_set1_ps(-1):_mm_set1_ps(1);
for(unsigned int f = 0; f < NF_ ; f+=4){
__m128d z2lo = _mm_load_pd(&z1[c*NF_+f]);
__m128d z2hi = _mm_load_pd(&z1[c*NF_+f+2]);
__m128 z2 = _mm_movelh_ps(_mm_cvtpd_ps(z2lo), _mm_cvtpd_ps(z2hi));
z2 = _mm_add_ps(z2,bias);
const __m128 _1 = _mm_set1_ps(1);
const __m128 m0_5 = _mm_set1_ps(-0.5);
if(k<0){
const __m128 vln0_5 = _mm_set1_ps(-0.693147);
__m128 a = _mm_sub_ps(z2,_1);
a = _mm_mul_ps(a,a);
a = _mm_mul_ps(m0_5,a);
a = vfastexp(a);
__m128 b = _mm_add_ps(z2,_1);
b = _mm_mul_ps(b,b);
b = _mm_mul_ps(m0_5,b);
b = vfastexp(b);
a = _mm_add_ps(a,b);
a = vfastlog(a);
a = _mm_add_ps(vln0_5,a);
vsum=_mm_add_pd(vsum,_mm_cvtps_pd(a));
vsum=_mm_add_pd(vsum,_mm_cvtps_pd(_mm_movehl_ps(a,a)));
}
else{
__m128 y = vfastcosh(z2);
y = vfastlog(y);
__m128 z2sq = _mm_mul_ps(z2,z2);
y = _mm_mul_ps(_mm_set1_ps(-1),y);
z2sq = _mm_mul_ps(_mm_set1_ps(0.5),z2sq);
y = _mm_sub_ps(y,z2sq);
vsum=_mm_add_pd(vsum,_mm_cvtps_pd(y));
vsum=_mm_add_pd(vsum,_mm_cvtps_pd(_mm_movehl_ps(y,y)));
}
//compute phi
__m128 y = vfasttanh(z2);
y = _mm_mul_ps(phi_signs,y);
__m128 v = _mm_add_ps(z2,y);
_mm_store_pd(&phi[c*NF_+f],_mm_cvtps_pd(v));
_mm_store_pd(&phi[c*NF_+f+2],_mm_cvtps_pd(_mm_movehl_ps(v,v)));
}
double sum;
vsum = _mm_hadd_pd(vsum, vsum);
_mm_store_sd(&sum, vsum);
means_logp[c] = 1/(double)NF_*sum;
}
}
}
<commit_msg>Fixed headers wrt previous commit<commit_after>#include "extended_infomax.h"
#include <cmath>
#include "src/fastapprox.h"
#include <pmmintrin.h>
#include <cstddef>
namespace curveica{
template<>
void extended_infomax_ica<float>::operator()(float * z1, float * b, int const * signs, float* phi, float* means_logp) const {
for(unsigned int c = 0 ; c < NC_ ; ++c){
__m128d vsum = _mm_set1_pd(0.0d);
float k = signs[c];
const __m128 bias = _mm_set1_ps(b[c]);
__m128 phi_signs = (k<0)?_mm_set1_ps(-1):_mm_set1_ps(1);
for(unsigned int f = 0; f < NF_ ; f+=4){
__m128 z2 = _mm_load_ps(&z1[c*NF_+f]);
z2 = _mm_add_ps(z2,bias);
//Computes mean_logp
const __m128 _1 = _mm_set1_ps(1);
const __m128 m0_5 = _mm_set1_ps(-0.5);
if(k<0){
__m128 a = _mm_sub_ps(z2,_1);
a = _mm_mul_ps(a,a);
a = _mm_mul_ps(m0_5,a);
a = vfastexp(a);
__m128 b = _mm_add_ps(z2,_1);
b = _mm_mul_ps(b,b);
b = _mm_mul_ps(m0_5,b);
b = vfastexp(b);
a = _mm_add_ps(a,b);
a = vfastlog(a);
vsum=_mm_add_pd(vsum,_mm_cvtps_pd(a));
vsum=_mm_add_pd(vsum,_mm_cvtps_pd(_mm_movehl_ps(a,a)));
}
else{
__m128 y = vfastcosh(z2);
y = vfastlog(y);
__m128 z2sq = _mm_mul_ps(z2,z2);
y = _mm_mul_ps(_mm_set1_ps(-1),y);
z2sq = _mm_mul_ps(_mm_set1_ps(0.5),z2sq);
y = _mm_sub_ps(y,z2sq);
vsum=_mm_add_pd(vsum,_mm_cvtps_pd(y));
vsum=_mm_add_pd(vsum,_mm_cvtps_pd(_mm_movehl_ps(y,y)));
}
//compute phi
__m128 y = vfasttanh(z2);
y = _mm_mul_ps(phi_signs,y);
__m128 v = _mm_add_ps(z2,y);
_mm_store_ps(&phi[c*NF_+f],v);
}
double sum;
vsum = _mm_hadd_pd(vsum, vsum);
_mm_store_sd(&sum, vsum);
means_logp[c] = 1/(float)NF_*sum;
}
}
//template<>
//void extended_infomax_ica<double>::operator()(double * z1, double * b, double * signs, double* phi, double* means_logp) const {
// for(unsigned int c = 0 ; c < NC_ ; ++c){
// double current = 0;
// double k = signs[c];
// double bias = b[c];
// for(unsigned int f = 0; f < NF_ ; f++){
// double z2 = z1[c*NF_+f] + bias;
// double y = std::tanh(z2);
// if(k<0){
// current+= std::log((std::exp(-0.5*std::pow(z2-1,2)) + std::exp(-0.5*std::pow(z2+1,2))));
// phi[c*NF_+f] = z2 - y;
// }
// else{
// current+= -std::log(std::cosh(z2)) - 0.5*z2*z2;
// phi[c*NF_+f] = z2 + y;
// }
// }
// means_logp[c] = current/(double)NF_;
// }
//}
template<>
void extended_infomax_ica<double>::operator()(double * z1, double * b, int const * signs, double* phi, double* means_logp) const {
for(unsigned int c = 0 ; c < NC_ ; ++c){
__m128d vsum = _mm_set1_pd(0.0d);
float k = signs[c];
const __m128 bias = _mm_set1_ps(b[c]);
__m128 phi_signs = (k<0)?_mm_set1_ps(-1):_mm_set1_ps(1);
for(unsigned int f = 0; f < NF_ ; f+=4){
__m128d z2lo = _mm_load_pd(&z1[c*NF_+f]);
__m128d z2hi = _mm_load_pd(&z1[c*NF_+f+2]);
__m128 z2 = _mm_movelh_ps(_mm_cvtpd_ps(z2lo), _mm_cvtpd_ps(z2hi));
z2 = _mm_add_ps(z2,bias);
const __m128 _1 = _mm_set1_ps(1);
const __m128 m0_5 = _mm_set1_ps(-0.5);
if(k<0){
const __m128 vln0_5 = _mm_set1_ps(-0.693147);
__m128 a = _mm_sub_ps(z2,_1);
a = _mm_mul_ps(a,a);
a = _mm_mul_ps(m0_5,a);
a = vfastexp(a);
__m128 b = _mm_add_ps(z2,_1);
b = _mm_mul_ps(b,b);
b = _mm_mul_ps(m0_5,b);
b = vfastexp(b);
a = _mm_add_ps(a,b);
a = vfastlog(a);
a = _mm_add_ps(vln0_5,a);
vsum=_mm_add_pd(vsum,_mm_cvtps_pd(a));
vsum=_mm_add_pd(vsum,_mm_cvtps_pd(_mm_movehl_ps(a,a)));
}
else{
__m128 y = vfastcosh(z2);
y = vfastlog(y);
__m128 z2sq = _mm_mul_ps(z2,z2);
y = _mm_mul_ps(_mm_set1_ps(-1),y);
z2sq = _mm_mul_ps(_mm_set1_ps(0.5),z2sq);
y = _mm_sub_ps(y,z2sq);
vsum=_mm_add_pd(vsum,_mm_cvtps_pd(y));
vsum=_mm_add_pd(vsum,_mm_cvtps_pd(_mm_movehl_ps(y,y)));
}
//compute phi
__m128 y = vfasttanh(z2);
y = _mm_mul_ps(phi_signs,y);
__m128 v = _mm_add_ps(z2,y);
_mm_store_pd(&phi[c*NF_+f],_mm_cvtps_pd(v));
_mm_store_pd(&phi[c*NF_+f+2],_mm_cvtps_pd(_mm_movehl_ps(v,v)));
}
double sum;
vsum = _mm_hadd_pd(vsum, vsum);
_mm_store_sd(&sum, vsum);
means_logp[c] = 1/(double)NF_*sum;
}
}
}
<|endoftext|> |
<commit_before>#include "DSL_bless.hpp"
using namespace std;
namespace snarkfront {
////////////////////////////////////////////////////////////////////////////////
// blessing (initialize variables)
//
// 32-bit value from data buffer stream (useful for templates)
void bless(uint32_t& a, DataBufferStream& ss) {
a = ss.getWord<uint32_t>();
}
// 64-bit value from data buffer stream (useful for templates)
void bless(uint64_t& a, DataBufferStream& ss) {
a = ss.getWord<uint64_t>();
}
} // namespace snarkfront
<commit_msg>8-bit unsigned int type<commit_after>#include "DSL_bless.hpp"
using namespace std;
namespace snarkfront {
////////////////////////////////////////////////////////////////////////////////
// blessing (initialize variables)
//
// 8-bit value from data buffer stream (useful for templates)
void bless(uint8_t& a, DataBufferStream& ss) {
a = ss.getWord<uint8_t>();
}
// 32-bit value from data buffer stream (useful for templates)
void bless(uint32_t& a, DataBufferStream& ss) {
a = ss.getWord<uint32_t>();
}
// 64-bit value from data buffer stream (useful for templates)
void bless(uint64_t& a, DataBufferStream& ss) {
a = ss.getWord<uint64_t>();
}
} // namespace snarkfront
<|endoftext|> |
<commit_before>//
// Definition of 'Comparator' type input (InputType::kCMP).
//
// Teensy 3.x has up to 4 comparator modules: CMP0, CMP1, CMP2 and CMP3. Each of them can issue an interrupt when
// input pin voltage is crossing a threshold, both up and down. The threshold can be adjusted dynamically
// in 64 steps from 0V to 3.3V. This allows for more flexibility when dealing with analog sensors like the one
// described in this repo, but not really needed for commercial sensors.
//
// PROs:
// * Threshold can be dynamically adjusted.
// CONs:
// * Up to 4 (3 on Teensy 3.2) sensors at the same time; Only particular pins are supported (see comparator_defs below).
// * Timing is calculated in ISR, potentially increasing jitter.
//
#include "input_cmp.h"
#include "settings.h"
#include <Arduino.h>
// Teensy comparator port address block. Order is significant.
struct ComparatorPorts {
volatile uint8_t cr0, cr1, fpr, scr, daccr, muxcr;
};
static_assert(sizeof(ComparatorPorts) == 6, "ComparatorPorts struct must be packed.");
constexpr int NA = -1; // Pin Not Available
// Static configuration of a comparator: control ports base address, irq number and pin numbers
struct ComparatorDef {
union {
volatile uint8_t *port_cr0;
ComparatorPorts *ports;
};
int irq;
int input_pins[6]; // CMPx_INy to Teensy digital pin # mapping. DAC0=100, DAC1=101.
};
// Comparator pin definitions.
const static ComparatorDef comparator_defs[] = {
#if defined(__MK20DX128__) // Teensy 3.0. Chip 64 LQFP pin numbers in comments. Teensy digital pins as numbers.
{&CMP0_CR0, IRQ_CMP0, {/*51 */11, /*52 */12, /*53 */28, /*54 */ 27, /*-- */NA, /*17*/NA}},
{&CMP1_CR0, IRQ_CMP1, {/*45 */23, /*46 */ 9, NA, NA, NA, /*17*/NA}},
#elif defined(__MK20DX256__) // Teensy 3.1, 3.2. Chip 64 LQFP pin numbers in comments. Teensy digital pins as numbers, DAC0=100
{&CMP0_CR0, IRQ_CMP0, {/*51 */11, /*52 */12, /*53 */28, /*54 */ 27, /*55 */29, /*17*/NA}},
{&CMP1_CR0, IRQ_CMP1, {/*45 */23, /*46 */ 9, NA, /*18 */100, NA, /*17*/NA}},
{&CMP2_CR0, IRQ_CMP2, {/*28 */ 3, /*29 */ 4, NA, NA, NA, NA}},
#elif defined(__MK64FX512__) || defined(__MK66FX1M0__) // Teensy 3.5, 3.6. Chip 144 MAPBGA pin id-s in comments. Teensy digitial pins as numbers, DAC0=100, DAC1=101
{&CMP0_CR0, IRQ_CMP0, {/*C8 */11, /*B8 */12, /*A8 */35, /*D7 */ 36, /*L4 */101, /*M3 */NA}},
{&CMP1_CR0, IRQ_CMP1, {/*A12*/23, /*A11*/ 9, /*J3 */NA, /*L3 */100, NA, /*M3 */NA}},
{&CMP2_CR0, IRQ_CMP2, {/*K9 */ 3, /*J9 */ 4, /*K3 */NA, /*L4 */101, NA, NA}},
#if defined(__MK66FX1M0__)
{&CMP3_CR0, IRQ_CMP3, { NA, /*L11*/27, /*K10*/28, NA, /*K12*/ NA, /*J12*/NA}},
#endif
#endif
};
constexpr int num_comparators = sizeof(comparator_defs) / sizeof(comparator_defs[0]);
// Registered InputCmpNode-s, by comparator num. Used by interrupt handlers.
static InputCmpNode *input_cmps[num_comparators];
void InputCmpNode::setCmpThreshold(uint32_t level) { // level = 0..63, from 0V to 3V3.
if (!pulse_polarity_)
level = 63 - level;
// DAC Control: Enable; Reference=3v3 (Vin1=VREF_OUT=1V2; Vin2=VDD=3V3); Output select=0
ports_->daccr = CMP_DACCR_DACEN | CMP_DACCR_VRSEL | CMP_DACCR_VOSEL(level);
}
/*
inline ComparatorData *cmpDataFromInputIdx(uint32_t input_idx) {
ComparatorData *pCmp = comparator_data_by_input_idx[input_idx];
if (!pCmp || !pCmp->is_active)
return NULL;
return pCmp;
}
void changeCmpThreshold(uint32_t input_idx, int delta) {
if (ComparatorData *pCmp = cmpDataFromInputIdx(input_idx)) {
pCmp->cmp_threshold = (uint32_t)max(0, min(63, (int)pCmp->cmp_threshold + delta));
setCmpThreshold(pCmp, pCmp->cmp_threshold);
}
}
int getCmpLevel(uint32_t input_idx) { // Current signal level: 0 or 1 (basically, below or above threshold)
if (ComparatorData *pCmp = cmpDataFromInputIdx(input_idx))
return *pCmp->ports->daccr & CMP_SCR_COUT;
else
return 0;
}
int getCmpThreshold(uint32_t input_idx) {
if (ComparatorData *pCmp = cmpDataFromInputIdx(input_idx))
return pCmp->cmp_threshold;
else
return 0;
}
*/
/*
void dynamicThresholdAdjustment() {
// TODO.
// 1. Comparator level dynamic adjustment.
__disable_irq();
uint32_t crossings = d.crossings; d.crossings = 0;
uint32_t big_pulses = d.big_pulses; d.big_pulses = 0;
uint32_t small_pulses = d.small_pulses; d.small_pulses = 0;
//uint32_t fake_big_pulses = d.fake_big_pulses; d.fake_big_pulses = 0;
__enable_irq();
if (crossings > 100) { // Comparator level is at the background noise level. Try to increase it.
changeCmpThreshold(d, +3);
} else if (crossings == 0) { // No crossings of comparator level => too high or too low.
if (getCmpLevel(d) == 1) { // Level is too low
changeCmpThreshold(d, +16);
} else { // Level is too high
changeCmpThreshold(d, -9);
}
} else {
if (big_pulses <= 6) {
changeCmpThreshold(d, -4);
} else if (big_pulses > 10) {
changeCmpThreshold(d, +4);
} else if (small_pulses < 4) {
// Fine tune - we need 4 small pulses.
changeCmpThreshold(d, -1);
}
}
}
*/
InputCmpNode::InputCmpNode(uint32_t input_idx, const InputDef &input_def)
: InputNode(input_idx)
, rise_time_()
, rise_valid_(false)
, cmp_threshold_(input_def.initial_cmp_threshold)
, pulse_polarity_(input_def.pulse_polarity) {
// Find comparator and input num for given pin.
int cmp_idx, cmp_input_idx;
bool pin_found = false;
for (cmp_idx = 0; cmp_idx < num_comparators && !pin_found; cmp_idx++)
for (cmp_input_idx = 0; cmp_input_idx < 6 && !pin_found; cmp_input_idx++)
if (comparator_defs[cmp_idx].input_pins[cmp_input_idx] == (int)input_def.pin)
pin_found = true;
if (!pin_found)
throw_printf("Pin %lu is not supported for 'cmp' input type.\n", input_def.pin);
InputCmpNode *otherInput = input_cmps[cmp_idx];
if (otherInput)
throw_printf("Can't use pin %lu for a 'cmp' input type: CMP%lu is already in use by pin %lu.\n",
input_def.pin, cmp_idx, comparator_defs[cmp_idx].input_pins[otherInput->cmp_input_idx_]);
if (input_def.initial_cmp_threshold >= 64)
throw_printf("Invalid threshold value for 'cmp' input type on pin %lu. Supported values: 0-63\n", input_def.pin);
cmp_idx_ = cmp_idx;
cmp_input_idx_ = cmp_input_idx;
cmp_def_ = &comparator_defs[cmp_idx_];
ports_ = cmp_def_->ports;
input_cmps[cmp_idx_] = this;
}
InputNode::CreatorRegistrar InputCmpNode::creator_([](uint32_t input_idx, const InputDef &input_def) -> std::unique_ptr<InputNode> {
if (input_def.input_type == InputType::kCMP)
return std::make_unique<InputCmpNode>(input_idx, input_def);
return nullptr;
});
InputCmpNode::~InputCmpNode() {
input_cmps[cmp_idx_] = nullptr;
}
void InputCmpNode::start() {
InputNode::start();
NVIC_SET_PRIORITY(cmp_def_->irq, 64); // very high prio (0 = highest priority, 128 = medium, 255 = lowest)
NVIC_ENABLE_IRQ(cmp_def_->irq);
SIM_SCGC4 |= SIM_SCGC4_CMP; // Enable clock for comparator
// Filter disabled; Hysteresis level 0 (0=5mV; 1=10mV; 2=20mV; 3=30mV)
ports_->cr0 = CMP_CR0_FILTER_CNT(0) | CMP_CR0_HYSTCTR(0);
// Filter period - disabled
ports_->fpr = 0;
// Input/MUX Control
pinMode(cmp_def_->input_pins[cmp_input_idx_], INPUT);
const static uint32_t ref_input = 7; // CMPn_IN7 (DAC Reference Voltage, which we control in setCmpThreshold())
ports_->muxcr = pulse_polarity_
? CMP_MUXCR_PSEL(cmp_input_idx_) | CMP_MUXCR_MSEL(ref_input)
: CMP_MUXCR_PSEL(ref_input) | CMP_MUXCR_MSEL(cmp_input_idx_);
// Comparator ON; Sampling disabled; Windowing disabled; Power mode: High speed; Output Pin disabled;
ports_->cr1 = CMP_CR1_PMODE | CMP_CR1_EN;
setCmpThreshold(cmp_threshold_);
delay(5);
// Status & Control: DMA Off; Interrupt: both rising & falling; Reset current state.
ports_->scr = CMP_SCR_IER | CMP_SCR_IEF | CMP_SCR_CFR | CMP_SCR_CFF;
}
bool InputCmpNode::debug_cmd(HashedWord *input_words) {
// TODO: Threshold manipulation (changeCmpThreshold).
return InputNode::debug_cmd(input_words);
}
void InputCmpNode::debug_print(PrintStream& stream) {
InputNode::debug_print(stream);
}
inline void __attribute__((always_inline)) InputCmpNode::_isr_handler(volatile uint8_t *scr) {
const uint32_t cmpState = *scr;
const Timestamp timestamp = Timestamp::cur_time();
if (rise_valid_ && (cmpState & CMP_SCR_CFF)) { // Falling edge registered
InputNode::enqueue_pulse(rise_time_, timestamp - rise_time_);
rise_valid_ = false;
}
const static uint32_t mask = CMP_SCR_CFR | CMP_SCR_COUT;
if ((cmpState & mask) == mask) { // Rising edge registered and state is now high
rise_time_ = timestamp;
rise_valid_ = true;
}
// Clear flags, re-enable interrupts.
*scr = CMP_SCR_IER | CMP_SCR_IEF | CMP_SCR_CFR | CMP_SCR_CFF;
}
void cmp0_isr() { if (input_cmps[0]) input_cmps[0]->_isr_handler(&CMP0_SCR); }
void cmp1_isr() { if (input_cmps[1]) input_cmps[1]->_isr_handler(&CMP1_SCR); }
#if defined(__MK20DX256__) || defined(__MK64FX512__) || defined(__MK66FX1M0__)
void cmp2_isr() { if (input_cmps[2]) input_cmps[2]->_isr_handler(&CMP2_SCR); }
#endif
#if defined(__MK66FX1M0__)
void cmp3_isr() { if (input_cmps[3]) input_cmps[3]->_isr_handler(&CMP3_SCR); }
#endif<commit_msg>Fix InputCmpNode - it wasn't working because of off-by-one mistake<commit_after>//
// Definition of 'Comparator' type input (InputType::kCMP).
//
// Teensy 3.x has up to 4 comparator modules: CMP0, CMP1, CMP2 and CMP3. Each of them can issue an interrupt when
// input pin voltage is crossing a threshold, both up and down. The threshold can be adjusted dynamically
// in 64 steps from 0V to 3.3V. This allows for more flexibility when dealing with analog sensors like the one
// described in this repo, but not really needed for commercial sensors.
//
// PROs:
// * Threshold can be dynamically adjusted.
// CONs:
// * Up to 4 (3 on Teensy 3.2) sensors at the same time; Only particular pins are supported (see comparator_defs below).
// * Timing is calculated in ISR, potentially increasing jitter.
//
#include "input_cmp.h"
#include "settings.h"
#include <Arduino.h>
// Teensy comparator port address block. Order is significant.
struct ComparatorPorts {
volatile uint8_t cr0, cr1, fpr, scr, daccr, muxcr;
};
static_assert(sizeof(ComparatorPorts) == 6, "ComparatorPorts struct must be packed.");
constexpr int NA = -1; // Pin Not Available
// Static configuration of a comparator: control ports base address, irq number and pin numbers
struct ComparatorDef {
union {
volatile uint8_t *port_cr0;
ComparatorPorts *ports;
};
int irq;
int input_pins[6]; // CMPx_INy to Teensy digital pin # mapping. DAC0=100, DAC1=101.
};
// Comparator pin definitions.
const static ComparatorDef comparator_defs[] = {
#if defined(__MK20DX128__) // Teensy 3.0. Chip 64 LQFP pin numbers in comments. Teensy digital pins as numbers.
{&CMP0_CR0, IRQ_CMP0, {/*51 */11, /*52 */12, /*53 */28, /*54 */ 27, /*-- */NA, /*17*/NA}},
{&CMP1_CR0, IRQ_CMP1, {/*45 */23, /*46 */ 9, NA, NA, NA, /*17*/NA}},
#elif defined(__MK20DX256__) // Teensy 3.1, 3.2. Chip 64 LQFP pin numbers in comments. Teensy digital pins as numbers, DAC0=100
{&CMP0_CR0, IRQ_CMP0, {/*51 */11, /*52 */12, /*53 */28, /*54 */ 27, /*55 */29, /*17*/NA}},
{&CMP1_CR0, IRQ_CMP1, {/*45 */23, /*46 */ 9, NA, /*18 */100, NA, /*17*/NA}},
{&CMP2_CR0, IRQ_CMP2, {/*28 */ 3, /*29 */ 4, NA, NA, NA, NA}},
#elif defined(__MK64FX512__) || defined(__MK66FX1M0__) // Teensy 3.5, 3.6. Chip 144 MAPBGA pin id-s in comments. Teensy digitial pins as numbers, DAC0=100, DAC1=101
{&CMP0_CR0, IRQ_CMP0, {/*C8 */11, /*B8 */12, /*A8 */35, /*D7 */ 36, /*L4 */101, /*M3 */NA}},
{&CMP1_CR0, IRQ_CMP1, {/*A12*/23, /*A11*/ 9, /*J3 */NA, /*L3 */100, NA, /*M3 */NA}},
{&CMP2_CR0, IRQ_CMP2, {/*K9 */ 3, /*J9 */ 4, /*K3 */NA, /*L4 */101, NA, NA}},
#if defined(__MK66FX1M0__)
{&CMP3_CR0, IRQ_CMP3, { NA, /*L11*/27, /*K10*/28, NA, /*K12*/ NA, /*J12*/NA}},
#endif
#endif
};
constexpr int num_comparators = sizeof(comparator_defs) / sizeof(comparator_defs[0]);
constexpr int num_inputs = sizeof(comparator_defs[0].input_pins) / sizeof(comparator_defs[0].input_pins[0]);
// Registered InputCmpNode-s, by comparator num. Used by interrupt handlers.
static InputCmpNode *input_cmps[num_comparators];
void InputCmpNode::setCmpThreshold(uint32_t level) { // level = 0..63, from 0V to 3V3.
if (!pulse_polarity_)
level = 63 - level;
// DAC Control: Enable; Reference=3v3 (Vin1=VREF_OUT=1V2; Vin2=VDD=3V3); Output select=0
ports_->daccr = CMP_DACCR_DACEN | CMP_DACCR_VRSEL | CMP_DACCR_VOSEL(level);
}
/*
inline ComparatorData *cmpDataFromInputIdx(uint32_t input_idx) {
ComparatorData *pCmp = comparator_data_by_input_idx[input_idx];
if (!pCmp || !pCmp->is_active)
return NULL;
return pCmp;
}
void changeCmpThreshold(uint32_t input_idx, int delta) {
if (ComparatorData *pCmp = cmpDataFromInputIdx(input_idx)) {
pCmp->cmp_threshold = (uint32_t)max(0, min(63, (int)pCmp->cmp_threshold + delta));
setCmpThreshold(pCmp, pCmp->cmp_threshold);
}
}
int getCmpLevel(uint32_t input_idx) { // Current signal level: 0 or 1 (basically, below or above threshold)
if (ComparatorData *pCmp = cmpDataFromInputIdx(input_idx))
return *pCmp->ports->daccr & CMP_SCR_COUT;
else
return 0;
}
int getCmpThreshold(uint32_t input_idx) {
if (ComparatorData *pCmp = cmpDataFromInputIdx(input_idx))
return pCmp->cmp_threshold;
else
return 0;
}
*/
/*
void dynamicThresholdAdjustment() {
// TODO.
// 1. Comparator level dynamic adjustment.
__disable_irq();
uint32_t crossings = d.crossings; d.crossings = 0;
uint32_t big_pulses = d.big_pulses; d.big_pulses = 0;
uint32_t small_pulses = d.small_pulses; d.small_pulses = 0;
//uint32_t fake_big_pulses = d.fake_big_pulses; d.fake_big_pulses = 0;
__enable_irq();
if (crossings > 100) { // Comparator level is at the background noise level. Try to increase it.
changeCmpThreshold(d, +3);
} else if (crossings == 0) { // No crossings of comparator level => too high or too low.
if (getCmpLevel(d) == 1) { // Level is too low
changeCmpThreshold(d, +16);
} else { // Level is too high
changeCmpThreshold(d, -9);
}
} else {
if (big_pulses <= 6) {
changeCmpThreshold(d, -4);
} else if (big_pulses > 10) {
changeCmpThreshold(d, +4);
} else if (small_pulses < 4) {
// Fine tune - we need 4 small pulses.
changeCmpThreshold(d, -1);
}
}
}
*/
InputCmpNode::InputCmpNode(uint32_t input_idx, const InputDef &input_def)
: InputNode(input_idx)
, rise_time_()
, rise_valid_(false)
, cmp_threshold_(input_def.initial_cmp_threshold)
, pulse_polarity_(input_def.pulse_polarity) {
// Find comparator and input num for given pin.
int cmp_idx, cmp_input_idx;
bool pin_found = false;
for (int i = 0; i < num_comparators; i++)
for (int j = 0; j < num_inputs; j++)
if (comparator_defs[i].input_pins[j] == (int)input_def.pin) {
cmp_idx = i;
cmp_input_idx = j;
pin_found = true;
}
if (!pin_found)
throw_printf("Pin %lu is not supported for 'cmp' input type.\n", input_def.pin);
InputCmpNode *otherInput = input_cmps[cmp_idx];
if (otherInput)
throw_printf("Can't use pin %lu for a 'cmp' input type: CMP%lu is already in use by pin %lu.\n",
input_def.pin, cmp_idx, comparator_defs[cmp_idx].input_pins[otherInput->cmp_input_idx_]);
if (input_def.initial_cmp_threshold >= 64)
throw_printf("Invalid threshold value for 'cmp' input type on pin %lu. Supported values: 0-63\n", input_def.pin);
cmp_idx_ = cmp_idx;
cmp_input_idx_ = cmp_input_idx;
cmp_def_ = &comparator_defs[cmp_idx_];
ports_ = cmp_def_->ports;
input_cmps[cmp_idx_] = this;
}
InputNode::CreatorRegistrar InputCmpNode::creator_([](uint32_t input_idx, const InputDef &input_def) -> std::unique_ptr<InputNode> {
if (input_def.input_type == InputType::kCMP)
return std::make_unique<InputCmpNode>(input_idx, input_def);
return nullptr;
});
InputCmpNode::~InputCmpNode() {
input_cmps[cmp_idx_] = nullptr;
}
void InputCmpNode::start() {
InputNode::start();
NVIC_SET_PRIORITY(cmp_def_->irq, 64); // very high prio (0 = highest priority, 128 = medium, 255 = lowest)
NVIC_ENABLE_IRQ(cmp_def_->irq);
SIM_SCGC4 |= SIM_SCGC4_CMP; // Enable clock for comparator
// Filter disabled; Hysteresis level 0 (0=5mV; 1=10mV; 2=20mV; 3=30mV)
ports_->cr0 = CMP_CR0_FILTER_CNT(0) | CMP_CR0_HYSTCTR(0);
// Filter period - disabled
ports_->fpr = 0;
// Input/MUX Control
pinMode(cmp_def_->input_pins[cmp_input_idx_], INPUT);
const static uint32_t ref_input = 7; // CMPn_IN7 (DAC Reference Voltage, which we control in setCmpThreshold())
ports_->muxcr = pulse_polarity_
? CMP_MUXCR_PSEL(cmp_input_idx_) | CMP_MUXCR_MSEL(ref_input)
: CMP_MUXCR_PSEL(ref_input) | CMP_MUXCR_MSEL(cmp_input_idx_);
// Comparator ON; Sampling disabled; Windowing disabled; Power mode: High speed; Output Pin disabled;
ports_->cr1 = CMP_CR1_PMODE | CMP_CR1_EN;
setCmpThreshold(cmp_threshold_);
delay(5);
// Status & Control: DMA Off; Interrupt: both rising & falling; Reset current state.
ports_->scr = CMP_SCR_IER | CMP_SCR_IEF | CMP_SCR_CFR | CMP_SCR_CFF;
}
bool InputCmpNode::debug_cmd(HashedWord *input_words) {
// TODO: Threshold manipulation (changeCmpThreshold).
return InputNode::debug_cmd(input_words);
}
void InputCmpNode::debug_print(PrintStream& stream) {
InputNode::debug_print(stream);
}
inline void __attribute__((always_inline)) InputCmpNode::_isr_handler(volatile uint8_t *scr) {
const uint32_t cmpState = *scr;
const Timestamp timestamp = Timestamp::cur_time();
if (rise_valid_ && (cmpState & CMP_SCR_CFF)) { // Falling edge registered
InputNode::enqueue_pulse(rise_time_, timestamp - rise_time_);
rise_valid_ = false;
}
const static uint32_t mask = CMP_SCR_CFR | CMP_SCR_COUT;
if ((cmpState & mask) == mask) { // Rising edge registered and state is now high
rise_time_ = timestamp;
rise_valid_ = true;
}
// Clear flags, re-enable interrupts.
*scr = CMP_SCR_IER | CMP_SCR_IEF | CMP_SCR_CFR | CMP_SCR_CFF;
}
void cmp0_isr() { if (input_cmps[0]) input_cmps[0]->_isr_handler(&CMP0_SCR); }
void cmp1_isr() { if (input_cmps[1]) input_cmps[1]->_isr_handler(&CMP1_SCR); }
#if defined(__MK20DX256__) || defined(__MK64FX512__) || defined(__MK66FX1M0__)
void cmp2_isr() { if (input_cmps[2]) input_cmps[2]->_isr_handler(&CMP2_SCR); }
#endif
#if defined(__MK66FX1M0__)
void cmp3_isr() { if (input_cmps[3]) input_cmps[3]->_isr_handler(&CMP3_SCR); }
#endif<|endoftext|> |
<commit_before>// Copyright 2016 Chirstopher Torres (Raven), L3nn0x
//
// 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 "cmapserver.h"
#include "cmapisc.h"
#include "cmapclient.h"
#include "epackettype.h"
#include "database.h"
#include "entityComponents.h"
#include <cmath>
using namespace RoseCommon;
CMapClient::CMapClient()
: CRoseClient(),
access_rights_(0),
login_state_(eSTATE::DEFAULT),
session_id_(0),
userid_(0),
charid_(0) {}
CMapClient::CMapClient(tcp::socket _sock, std::shared_ptr<EntitySystem> entitySystem)
: CRoseClient(std::move(_sock)),
access_rights_(0),
login_state_(eSTATE::DEFAULT),
session_id_(0),
userid_(0),
charid_(0),
entitySystem_(entitySystem)
{}
bool CMapClient::HandlePacket(uint8_t* _buffer) {
switch (CRosePacket::type(_buffer)) {
case ePacketType::PAKCS_JOIN_SERVER_REQ:
return JoinServerReply(getPacket<ePacketType::PAKCS_JOIN_SERVER_REQ>(
_buffer)); // Allow client to connect
case ePacketType::PAKCS_CHANGE_MAP_REQ:
return ChangeMapReply(
getPacket<ePacketType::PAKCS_CHANGE_MAP_REQ>(_buffer));
// case ePacketType::PAKCS_LOGOUT_REQ:
// return LogoutReply();
case ePacketType::PAKCS_NORMAL_CHAT:
return ChatReply(getPacket<ePacketType::PAKCS_NORMAL_CHAT>(_buffer));
case ePacketType::PAKCS_WHISPER_CHAT:
return ChatWhisper(getPacket<ePacketType::PAKCS_WHISPER_CHAT>(_buffer));
case ePacketType::PAKCS_MOUSE_CMD:
return MouseCmdRcv(getPacket<ePacketType::PAKCS_MOUSE_CMD>(_buffer));
case ePacketType::PAKCS_STOP_MOVING:
return StopMovingRcv(getPacket<ePacketType::PAKCS_STOP_MOVING>(_buffer));
default: {
// logger_->debug( "cmapclient default handle: 0x{1:04x}",
// (uint16_t)CRosePacket::type(_buffer) );
return CRoseClient::HandlePacket(_buffer);
}
}
return true;
}
CMapClient::~CMapClient() {
}
bool CMapClient::OnReceived() { return CRoseClient::OnReceived(); }
void CMapClient::OnDisconnected() {
entitySystem_->saveCharacter(charid_, entity_);
CMapServer::SendPacket(this, CMapServer::eSendType::EVERYONE_BUT_ME, *makePacket<ePacketType::PAKWC_REMOVE_OBJECT>(entity_));
entitySystem_->destroy(entity_);
}
bool CMapClient::JoinServerReply(
std::unique_ptr<RoseCommon::CliJoinServerReq> P) {
logger_->trace("CMapClient::JoinServerReply()");
if (login_state_ != eSTATE::DEFAULT) {
logger_->warn("Client {} is attempting to login when already logged in.",
GetId());
return true;
}
uint32_t sessionID = P->session_id();
std::string password = P->password();
std::unique_ptr<Core::IResult> res, itemres;
std::string query = fmt::format("CALL get_session({}, '{}');", sessionID, password);
Core::IDatabase& database = Core::databasePool.getDatabase();
res = database.QStore(query);
if (res != nullptr) { // Query the DB
if (res->size() != 0) {
logger_->debug("Client {} auth OK.", GetId());
login_state_ = eSTATE::LOGGEDIN;
res->getInt("userid", userid_);
res->getInt("charid", charid_);
session_id_ = sessionID;
bool platinium = false;
res->getInt("platinium", platinium);
entity_ = entitySystem_->loadCharacter(charid_, platinium);
if (entity_) {
auto basic =entity_.component<BasicInfo>();
basic->id_ = GetId();
basic->tag_ = GetId();
auto packet = makePacket<ePacketType::PAKSC_JOIN_SERVER_REPLY>(
SrvJoinServerReply::OK, std::time(nullptr));
Send(*packet);
entity_.assign<SocketConnector>(this);
// SEND PLAYER DATA HERE!!!!!!
auto packet2 = makePacket<ePacketType::PAKWC_SELECT_CHAR_REPLY>(entity_);
Send(*packet2);
auto packet3 = makePacket<ePacketType::PAKWC_INVENTORY_DATA>(entity_);
Send(*packet3);
auto packet4 = makePacket<ePacketType::PAKWC_QUEST_DATA>();
Send(*packet4);
auto packet5 = makePacket<ePacketType::PAKWC_BILLING_MESSAGE>();
Send(*packet5);
} else {
logger_->debug("Something wrong happened when creating the entity");
}
} else {
logger_->debug("Client {} auth INVALID_PASS.", GetId());
auto packet = makePacket<ePacketType::PAKSC_JOIN_SERVER_REPLY>(
SrvJoinServerReply::INVALID_PASSWORD, 0);
Send(*packet);
}
} else {
logger_->debug("Client {} auth FAILED.", GetId());
auto packet = makePacket<ePacketType::PAKSC_JOIN_SERVER_REPLY>(
SrvJoinServerReply::FAILED, 0);
Send(*packet);
}
return true;
};
bool CMapClient::ChangeMapReply(
std::unique_ptr<RoseCommon::CliChangeMapReq> P) {
logger_->trace("CMapClient::ChangeMapReply()");
if (login_state_ != eSTATE::LOGGEDIN) {
logger_->warn("Client {} is attempting to change map before logging in.",
GetId());
return true;
}
(void)P;
auto advanced = entity_.component<AdvancedInfo>();
auto basic = entity_.component<BasicInfo>();
auto info = entity_.component<CharacterInfo>();
Send(*makePacket<ePacketType::PAKWC_CHANGE_MAP_REPLY>(GetId(), advanced->hp_, advanced->mp_, basic->xp_, info->penaltyXp_, std::time(nullptr), 0));
CMapServer::SendPacket(this, CMapServer::eSendType::EVERYONE_BUT_ME,
*makePacket<ePacketType::PAKWC_PLAYER_CHAR>(entity_));
entitySystem_->processEntities<CharacterGraphics, BasicInfo>([entity_ = entity_, this](Entity entity) {
auto basic = entity.component<BasicInfo>();
if (entity != entity_ && basic->loggedIn_)
this->Send(*makePacket<ePacketType::PAKWC_PLAYER_CHAR>(entity));
return true;
});
basic->loggedIn_ = true;
return true;
}
bool CMapClient::ChatReply(std::unique_ptr<RoseCommon::CliChat> P) {
logger_->trace("CMapClient::ChatReply()");
if (login_state_ != eSTATE::LOGGEDIN) {
logger_->warn("Client {} is attempting to chat before logging in.",
GetId());
return true;
}
uint16_t _charID = GetId();
std::string _message = P->getMessage();
auto packet = makePacket<ePacketType::PAKWC_NORMAL_CHAT>(
_message, _charID);
logger_->trace("client {} is sending '{}'", _charID, _message);
CMapServer::SendPacket(this, CMapServer::eSendType::NEARBY, *packet);
return true;
}
bool CMapClient::ChatWhisper(std::unique_ptr<RoseCommon::CliWhisper> P) {
logger_->trace("CMapClient::ChatWhisper()");
if (login_state_ != eSTATE::LOGGEDIN) {
logger_->warn("Client {} is attempting to whisper before logging in.",
GetId());
return true;
}
uint16_t _charID = GetId();
std::string _sender_name = entity_.component<BasicInfo>()->name_;
std::string _recipient_name = P->targetId();
_recipient_name.erase(_recipient_name.size()-1); // for some reason this string has an extra char
std::string _message = P->message();
CMapClient *_recipient_client = nullptr;
entitySystem_->process<BasicInfo, SocketConnector>([&_recipient_client, _recipient_name] (Entity entity) -> bool {
if(_recipient_name == entity.component<BasicInfo>()->name_) {
_recipient_client = entity.component<SocketConnector>()->client_;
return true;
}
return false;
});
logger_->trace("{} ({}) is whispering '{}' to {}", _sender_name, _charID, _message, _recipient_name);
if(_recipient_client) {
auto packet = makePacket<ePacketType::PAKWC_WHISPER_CHAT>(_message, _sender_name);
_recipient_client->Send(*packet);
return true;
} else {
auto packet = makePacket<ePacketType::PAKWC_WHISPER_CHAT>(std::string(""), std::string("User cannot be found or is offline"));
this->Send(*packet);
return true;
}
return false;
}
bool CMapClient::IsNearby(const IObject* _otherClient) const {
(void)_otherClient;
logger_->trace("CMapClient::IsNearby()");
//TODO: Call the entity distance calc here
return true;
}
bool CMapClient::MouseCmdRcv(std::unique_ptr<RoseCommon::CliMouseCmd> P) {
logger_->trace("CMapClient::MouseCmdRcv()");
if (login_state_ != eSTATE::LOGGEDIN) {
logger_->warn("Client {} is attempting to issue mouse commands before logging in.", GetId());
return true;
}
// TODO : set target
auto pos = entity_.component<Position>();
float dx = pos->x_ - P->x(), dy = pos->y_ - P->y();
entitySystem_->get<MovementSystem>().move(entity_, P->x(), P->y());
CMapServer::SendPacket(this, CMapServer::eSendType::EVERYONE,
*makePacket<ePacketType::PAKWC_MOUSE_CMD>(GetId(), P->targetId(), std::sqrt(dx*dx + dy*dy), P->x(), P->y(), P->z()));
return true;
}
bool CMapClient::StopMovingRcv(std::unique_ptr<RoseCommon::CliStopMoving> P) {
logger_->trace("CMapClient::StopMovingRcv()");
if (login_state_ != eSTATE::LOGGEDIN) {
logger_->warn("Client {} is attempting to stop moving before logging in.", GetId());
return true;
}
entitySystem_->get<MovementSystem>().stop(entity_, P->x(), P->y());
CMapServer::SendPacket(this, CMapServer::eSendType::EVERYONE_BUT_ME,
*makePacket<ePacketType::PAKWC_STOP>(entity_));
return true;
}
<commit_msg>recreates PR from fork's trunk branch -- from #69<commit_after>// Copyright 2016 Chirstopher Torres (Raven), L3nn0x
//
// 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 "cmapserver.h"
#include "cmapisc.h"
#include "cmapclient.h"
#include "epackettype.h"
#include "database.h"
#include "entityComponents.h"
#include <cmath>
using namespace RoseCommon;
CMapClient::CMapClient()
: CRoseClient(),
access_rights_(0),
login_state_(eSTATE::DEFAULT),
session_id_(0),
userid_(0),
charid_(0) {}
CMapClient::CMapClient(tcp::socket _sock, std::shared_ptr<EntitySystem> entitySystem)
: CRoseClient(std::move(_sock)),
access_rights_(0),
login_state_(eSTATE::DEFAULT),
session_id_(0),
userid_(0),
charid_(0),
entitySystem_(entitySystem)
{}
bool CMapClient::HandlePacket(uint8_t* _buffer) {
switch (CRosePacket::type(_buffer)) {
case ePacketType::PAKCS_JOIN_SERVER_REQ:
return JoinServerReply(getPacket<ePacketType::PAKCS_JOIN_SERVER_REQ>(
_buffer)); // Allow client to connect
case ePacketType::PAKCS_CHANGE_MAP_REQ:
return ChangeMapReply(
getPacket<ePacketType::PAKCS_CHANGE_MAP_REQ>(_buffer));
// case ePacketType::PAKCS_LOGOUT_REQ:
// return LogoutReply();
case ePacketType::PAKCS_NORMAL_CHAT:
return ChatReply(getPacket<ePacketType::PAKCS_NORMAL_CHAT>(_buffer));
case ePacketType::PAKCS_WHISPER_CHAT:
return ChatWhisper(getPacket<ePacketType::PAKCS_WHISPER_CHAT>(_buffer));
case ePacketType::PAKCS_MOUSE_CMD:
return MouseCmdRcv(getPacket<ePacketType::PAKCS_MOUSE_CMD>(_buffer));
case ePacketType::PAKCS_STOP_MOVING:
return StopMovingRcv(getPacket<ePacketType::PAKCS_STOP_MOVING>(_buffer));
default: {
// logger_->debug( "cmapclient default handle: 0x{1:04x}",
// (uint16_t)CRosePacket::type(_buffer) );
return CRoseClient::HandlePacket(_buffer);
}
}
return true;
}
CMapClient::~CMapClient() {
}
bool CMapClient::OnReceived() { return CRoseClient::OnReceived(); }
void CMapClient::OnDisconnected() {
entitySystem_->saveCharacter(charid_, entity_);
CMapServer::SendPacket(this, CMapServer::eSendType::EVERYONE_BUT_ME, *makePacket<ePacketType::PAKWC_REMOVE_OBJECT>(entity_));
entitySystem_->destroy(entity_);
}
bool CMapClient::JoinServerReply(
std::unique_ptr<RoseCommon::CliJoinServerReq> P) {
logger_->trace("CMapClient::JoinServerReply()");
if (login_state_ != eSTATE::DEFAULT) {
logger_->warn("Client {} is attempting to login when already logged in.",
GetId());
return true;
}
uint32_t sessionID = P->session_id();
std::string password = P->password();
std::unique_ptr<Core::IResult> res, itemres;
std::string query = fmt::format("CALL get_session({}, '{}');", sessionID, password);
Core::IDatabase& database = Core::databasePool.getDatabase();
res = database.QStore(query);
if (res != nullptr) { // Query the DB
if (res->size() != 0) {
logger_->debug("Client {} auth OK.", GetId());
login_state_ = eSTATE::LOGGEDIN;
res->getInt("userid", userid_);
res->getInt("charid", charid_);
session_id_ = sessionID;
bool platinium = false;
res->getInt("platinium", platinium);
entity_ = entitySystem_->loadCharacter(charid_, platinium);
if (entity_) {
auto basic =entity_.component<BasicInfo>();
basic->id_ = GetId();
basic->tag_ = GetId();
auto packet = makePacket<ePacketType::PAKSC_JOIN_SERVER_REPLY>(
SrvJoinServerReply::OK, std::time(nullptr));
Send(*packet);
entity_.assign<SocketConnector>(this);
// SEND PLAYER DATA HERE!!!!!!
auto packet2 = makePacket<ePacketType::PAKWC_SELECT_CHAR_REPLY>(entity_);
Send(*packet2);
auto packet3 = makePacket<ePacketType::PAKWC_INVENTORY_DATA>(entity_);
Send(*packet3);
auto packet4 = makePacket<ePacketType::PAKWC_QUEST_DATA>();
Send(*packet4);
auto packet5 = makePacket<ePacketType::PAKWC_BILLING_MESSAGE>();
Send(*packet5);
} else {
logger_->debug("Something wrong happened when creating the entity");
}
} else {
logger_->debug("Client {} auth INVALID_PASS.", GetId());
auto packet = makePacket<ePacketType::PAKSC_JOIN_SERVER_REPLY>(
SrvJoinServerReply::INVALID_PASSWORD, 0);
Send(*packet);
}
} else {
logger_->debug("Client {} auth FAILED.", GetId());
auto packet = makePacket<ePacketType::PAKSC_JOIN_SERVER_REPLY>(
SrvJoinServerReply::FAILED, 0);
Send(*packet);
}
return true;
};
bool CMapClient::ChangeMapReply(
std::unique_ptr<RoseCommon::CliChangeMapReq> P) {
logger_->trace("CMapClient::ChangeMapReply()");
if (login_state_ != eSTATE::LOGGEDIN) {
logger_->warn("Client {} is attempting to change map before logging in.",
GetId());
return true;
}
(void)P;
auto advanced = entity_.component<AdvancedInfo>();
auto basic = entity_.component<BasicInfo>();
auto info = entity_.component<CharacterInfo>();
Send(*makePacket<ePacketType::PAKWC_CHANGE_MAP_REPLY>(GetId(), advanced->hp_, advanced->mp_, basic->xp_, info->penaltyXp_, std::time(nullptr), 0));
CMapServer::SendPacket(this, CMapServer::eSendType::EVERYONE_BUT_ME,
*makePacket<ePacketType::PAKWC_PLAYER_CHAR>(entity_));
entitySystem_->processEntities<CharacterGraphics, BasicInfo>([entity_ = entity_, this](Entity entity) {
auto basic = entity.component<BasicInfo>();
if (entity != entity_ && basic->loggedIn_)
this->Send(*makePacket<ePacketType::PAKWC_PLAYER_CHAR>(entity));
return true;
});
basic->loggedIn_ = true;
return true;
}
bool CMapClient::ChatReply(std::unique_ptr<RoseCommon::CliChat> P) {
logger_->trace("CMapClient::ChatReply()");
if (login_state_ != eSTATE::LOGGEDIN) {
logger_->warn("Client {} is attempting to chat before logging in.",
GetId());
return true;
}
uint16_t _charID = GetId();
std::string _message = P->getMessage();
auto packet = makePacket<ePacketType::PAKWC_NORMAL_CHAT>(
_message, _charID);
logger_->trace("client {} is sending '{}'", _charID, _message);
CMapServer::SendPacket(this, CMapServer::eSendType::NEARBY, *packet);
return true;
}
bool CMapClient::ChatWhisper(std::unique_ptr<RoseCommon::CliWhisper> P) {
logger_->trace("CMapClient::ChatWhisper()");
if (login_state_ != eSTATE::LOGGEDIN) {
logger_->warn("Client {} is attempting to whisper before logging in.",
GetId());
return true;
}
uint16_t _charID = GetId();
std::string _sender_name = entity_.component<BasicInfo>()->name_;
std::string _recipient_name = P->targetId();
_recipient_name.erase(_recipient_name.size()-1); // for some reason this string has an extra char
std::string _message = P->message();
CMapClient *_recipient_client = nullptr;
entitySystem_->processEntities<BasicInfo, SocketConnector>([&_recipient_client, &_recipient_name] (Entity entity) {
if(_recipient_name == entity.component<BasicInfo>()->name_) {
_recipient_client = entity.component<SocketConnector>()->client_;
return true;
}
return false;
});
logger_->trace("{} ({}) is whispering '{}' to {}", _sender_name, _charID, _message, _recipient_name);
if(_recipient_client) {
auto packet = makePacket<ePacketType::PAKWC_WHISPER_CHAT>(_message, _sender_name);
_recipient_client->Send(*packet);
return true;
} else {
auto packet = makePacket<ePacketType::PAKWC_WHISPER_CHAT>(std::string(""), std::string("User cannot be found or is offline"));
this->Send(*packet);
return true;
}
return false;
}
bool CMapClient::IsNearby(const IObject* _otherClient) const {
(void)_otherClient;
logger_->trace("CMapClient::IsNearby()");
//TODO: Call the entity distance calc here
return true;
}
bool CMapClient::MouseCmdRcv(std::unique_ptr<RoseCommon::CliMouseCmd> P) {
logger_->trace("CMapClient::MouseCmdRcv()");
if (login_state_ != eSTATE::LOGGEDIN) {
logger_->warn("Client {} is attempting to issue mouse commands before logging in.", GetId());
return true;
}
// TODO : set target
auto pos = entity_.component<Position>();
float dx = pos->x_ - P->x(), dy = pos->y_ - P->y();
entitySystem_->get<MovementSystem>().move(entity_, P->x(), P->y());
CMapServer::SendPacket(this, CMapServer::eSendType::EVERYONE,
*makePacket<ePacketType::PAKWC_MOUSE_CMD>(GetId(), P->targetId(), std::sqrt(dx*dx + dy*dy), P->x(), P->y(), P->z()));
return true;
}
bool CMapClient::StopMovingRcv(std::unique_ptr<RoseCommon::CliStopMoving> P) {
logger_->trace("CMapClient::StopMovingRcv()");
if (login_state_ != eSTATE::LOGGEDIN) {
logger_->warn("Client {} is attempting to stop moving before logging in.", GetId());
return true;
}
entitySystem_->get<MovementSystem>().stop(entity_, P->x(), P->y());
CMapServer::SendPacket(this, CMapServer::eSendType::EVERYONE_BUT_ME,
*makePacket<ePacketType::PAKWC_STOP>(entity_));
return true;
}
<|endoftext|> |
<commit_before>/* mbed USBHost Library
* Copyright (c) 2006-2013 ARM Limited
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* 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 "dbg.h"
#include "USBEndpoint.h"
void USBEndpoint::init(HCED * hced_, ENDPOINT_TYPE type_, ENDPOINT_DIRECTION dir_, uint32_t size, uint8_t ep_number, HCTD* td_list_[2])
{
hced = hced_;
type = type_;
dir = dir_;
setup = (type == CONTROL_ENDPOINT) ? true : false;
//TDs have been allocated by the host
memcpy((HCTD**)td_list, td_list_, sizeof(HCTD*)*2); //TODO: Maybe should add a param for td_list size... at least a define
memcpy(td_list_[0], 0, sizeof(HCTD));
memcpy(td_list_[1], 0, sizeof(HCTD));
td_list[0]->ep = this;
td_list[1]->ep = this;
hced->control = 0;
//Empty queue
hced->tailTD = td_list[0];
hced->headTD = td_list[0];
hced->nextED = 0;
address = (ep_number & 0x7F) | ((dir - 1) << 7);
hced->control = ((ep_number & 0x7F) << 7) // Endpoint address
| (type != CONTROL_ENDPOINT ? ( dir << 11) : 0 ) // direction : Out = 1, 2 = In
| ((size & 0x3ff) << 16); // MaxPkt Size
transfer_len = 0;
transferred = 0;
buf_start = 0;
nextEp = NULL;
td_current = td_list[0];
td_next = td_list[1];
intf_nb = 0;
state = USB_TYPE_IDLE;
}
void USBEndpoint::setSize(uint32_t size)
{
hced->control &= ~(0x3ff << 16);
hced->control |= (size << 16);
}
void USBEndpoint::setDeviceAddress(uint8_t addr)
{
hced->control &= ~(0x7f);
hced->control |= (addr & 0x7F);
}
void USBEndpoint::setSpeed(uint8_t speed)
{
hced->control &= ~(1 << 13);
hced->control |= (speed << 13);
}
//Only for control Eps
void USBEndpoint::setNextToken(uint32_t token)
{
switch (token) {
case TD_SETUP:
dir = OUT;
setup = true;
break;
case TD_IN:
dir = IN;
setup = false;
break;
case TD_OUT:
dir = OUT;
setup = false;
break;
}
}
struct {
USB_TYPE type;
const char * str;
} static type_string[] = {
/*0*/ {USB_TYPE_OK, "USB_TYPE_OK"},
{USB_TYPE_CRC_ERROR, "USB_TYPE_CRC_ERROR"},
{USB_TYPE_BIT_STUFFING_ERROR, "USB_TYPE_BIT_STUFFING_ERROR"},
{USB_TYPE_DATA_TOGGLE_MISMATCH_ERROR, "USB_TYPE_DATA_TOGGLE_MISMATCH_ERROR"},
{USB_TYPE_STALL_ERROR, "USB_TYPE_STALL_ERROR"},
/*5*/ {USB_TYPE_DEVICE_NOT_RESPONDING_ERROR, "USB_TYPE_DEVICE_NOT_RESPONDING_ERROR"},
{USB_TYPE_PID_CHECK_FAILURE_ERROR, "USB_TYPE_PID_CHECK_FAILURE_ERROR"},
{USB_TYPE_UNEXPECTED_PID_ERROR, "USB_TYPE_UNEXPECTED_PID_ERROR"},
{USB_TYPE_DATA_OVERRUN_ERROR, "USB_TYPE_DATA_OVERRUN_ERROR"},
{USB_TYPE_DATA_UNDERRUN_ERROR, "USB_TYPE_DATA_UNDERRUN_ERROR"},
/*10*/ {USB_TYPE_ERROR, "USB_TYPE_ERROR"},
{USB_TYPE_ERROR, "USB_TYPE_ERROR"},
{USB_TYPE_BUFFER_OVERRUN_ERROR, "USB_TYPE_BUFFER_OVERRUN_ERROR"},
{USB_TYPE_BUFFER_UNDERRUN_ERROR, "USB_TYPE_BUFFER_UNDERRUN_ERROR"},
{USB_TYPE_DISCONNECTED, "USB_TYPE_DISCONNECTED"},
/*15*/ {USB_TYPE_FREE, "USB_TYPE_FREE"},
{USB_TYPE_IDLE, "USB_TYPE_IDLE"},
{USB_TYPE_PROCESSING, "USB_TYPE_PROCESSING"},
{USB_TYPE_ERROR, "USB_TYPE_ERROR"}
};
void USBEndpoint::setState(uint8_t st) {
if (st > 18)
return;
state = type_string[st].type;
}
const char * USBEndpoint::getStateString() {
return type_string[state].str;
}
void USBEndpoint::queueTransfer()
{
transfer_len = (uint32_t)td_current->bufEnd - (uint32_t)td_current->currBufPtr + 1;
transferred = transfer_len;
buf_start = (uint8_t *)td_current->currBufPtr;
//Now add this free TD at this end of the queue
state = USB_TYPE_PROCESSING;
td_current->nextTD = td_next;
hced->tailTD = td_next;
}
void USBEndpoint::unqueueTransfer(volatile HCTD * td)
{
td->control=0;
td->currBufPtr=0;
td->bufEnd=0;
td->nextTD=0;
hced->headTD = (HCTD *)((uint32_t)hced->tailTD | ((uint32_t)hced->headTD & 0x2)); //Carry bit
td_current = td_next;
td_next = td;
}
void USBEndpoint::queueEndpoint(USBEndpoint * ed)
{
nextEp = ed;
hced->nextED = (ed == NULL) ? 0 : ed->getHCED();
}
<commit_msg>USBHost: Calling memcpy() instead of memset()?<commit_after>/* mbed USBHost Library
* Copyright (c) 2006-2013 ARM Limited
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* 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 "dbg.h"
#include "USBEndpoint.h"
void USBEndpoint::init(HCED * hced_, ENDPOINT_TYPE type_, ENDPOINT_DIRECTION dir_, uint32_t size, uint8_t ep_number, HCTD* td_list_[2])
{
hced = hced_;
type = type_;
dir = dir_;
setup = (type == CONTROL_ENDPOINT) ? true : false;
//TDs have been allocated by the host
memcpy((HCTD**)td_list, td_list_, sizeof(HCTD*)*2); //TODO: Maybe should add a param for td_list size... at least a define
memset(td_list_[0], 0, sizeof(HCTD));
memset(td_list_[1], 0, sizeof(HCTD));
td_list[0]->ep = this;
td_list[1]->ep = this;
hced->control = 0;
//Empty queue
hced->tailTD = td_list[0];
hced->headTD = td_list[0];
hced->nextED = 0;
address = (ep_number & 0x7F) | ((dir - 1) << 7);
hced->control = ((ep_number & 0x7F) << 7) // Endpoint address
| (type != CONTROL_ENDPOINT ? ( dir << 11) : 0 ) // direction : Out = 1, 2 = In
| ((size & 0x3ff) << 16); // MaxPkt Size
transfer_len = 0;
transferred = 0;
buf_start = 0;
nextEp = NULL;
td_current = td_list[0];
td_next = td_list[1];
intf_nb = 0;
state = USB_TYPE_IDLE;
}
void USBEndpoint::setSize(uint32_t size)
{
hced->control &= ~(0x3ff << 16);
hced->control |= (size << 16);
}
void USBEndpoint::setDeviceAddress(uint8_t addr)
{
hced->control &= ~(0x7f);
hced->control |= (addr & 0x7F);
}
void USBEndpoint::setSpeed(uint8_t speed)
{
hced->control &= ~(1 << 13);
hced->control |= (speed << 13);
}
//Only for control Eps
void USBEndpoint::setNextToken(uint32_t token)
{
switch (token) {
case TD_SETUP:
dir = OUT;
setup = true;
break;
case TD_IN:
dir = IN;
setup = false;
break;
case TD_OUT:
dir = OUT;
setup = false;
break;
}
}
struct {
USB_TYPE type;
const char * str;
} static type_string[] = {
/*0*/ {USB_TYPE_OK, "USB_TYPE_OK"},
{USB_TYPE_CRC_ERROR, "USB_TYPE_CRC_ERROR"},
{USB_TYPE_BIT_STUFFING_ERROR, "USB_TYPE_BIT_STUFFING_ERROR"},
{USB_TYPE_DATA_TOGGLE_MISMATCH_ERROR, "USB_TYPE_DATA_TOGGLE_MISMATCH_ERROR"},
{USB_TYPE_STALL_ERROR, "USB_TYPE_STALL_ERROR"},
/*5*/ {USB_TYPE_DEVICE_NOT_RESPONDING_ERROR, "USB_TYPE_DEVICE_NOT_RESPONDING_ERROR"},
{USB_TYPE_PID_CHECK_FAILURE_ERROR, "USB_TYPE_PID_CHECK_FAILURE_ERROR"},
{USB_TYPE_UNEXPECTED_PID_ERROR, "USB_TYPE_UNEXPECTED_PID_ERROR"},
{USB_TYPE_DATA_OVERRUN_ERROR, "USB_TYPE_DATA_OVERRUN_ERROR"},
{USB_TYPE_DATA_UNDERRUN_ERROR, "USB_TYPE_DATA_UNDERRUN_ERROR"},
/*10*/ {USB_TYPE_ERROR, "USB_TYPE_ERROR"},
{USB_TYPE_ERROR, "USB_TYPE_ERROR"},
{USB_TYPE_BUFFER_OVERRUN_ERROR, "USB_TYPE_BUFFER_OVERRUN_ERROR"},
{USB_TYPE_BUFFER_UNDERRUN_ERROR, "USB_TYPE_BUFFER_UNDERRUN_ERROR"},
{USB_TYPE_DISCONNECTED, "USB_TYPE_DISCONNECTED"},
/*15*/ {USB_TYPE_FREE, "USB_TYPE_FREE"},
{USB_TYPE_IDLE, "USB_TYPE_IDLE"},
{USB_TYPE_PROCESSING, "USB_TYPE_PROCESSING"},
{USB_TYPE_ERROR, "USB_TYPE_ERROR"}
};
void USBEndpoint::setState(uint8_t st) {
if (st > 18)
return;
state = type_string[st].type;
}
const char * USBEndpoint::getStateString() {
return type_string[state].str;
}
void USBEndpoint::queueTransfer()
{
transfer_len = (uint32_t)td_current->bufEnd - (uint32_t)td_current->currBufPtr + 1;
transferred = transfer_len;
buf_start = (uint8_t *)td_current->currBufPtr;
//Now add this free TD at this end of the queue
state = USB_TYPE_PROCESSING;
td_current->nextTD = td_next;
hced->tailTD = td_next;
}
void USBEndpoint::unqueueTransfer(volatile HCTD * td)
{
td->control=0;
td->currBufPtr=0;
td->bufEnd=0;
td->nextTD=0;
hced->headTD = (HCTD *)((uint32_t)hced->tailTD | ((uint32_t)hced->headTD & 0x2)); //Carry bit
td_current = td_next;
td_next = td;
}
void USBEndpoint::queueEndpoint(USBEndpoint * ed)
{
nextEp = ed;
hced->nextED = (ed == NULL) ? 0 : ed->getHCED();
}
<|endoftext|> |
<commit_before>/*
Copyright (c) 2016 VOCA AS / Harald Nkland
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to
deal in the Software without restriction, including without limitation the
rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
sell copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
IN THE SOFTWARE.
*/
#ifndef __ZMQ_ADDON_HPP_INCLUDED__
#define __ZMQ_ADDON_HPP_INCLUDED__
#include <zmq.hpp>
#include <deque>
#include <iomanip>
#include <sstream>
namespace zmq {
#ifdef ZMQ_HAS_RVALUE_REFS
/*
This class handles multipart messaging. It is the C++ equivalent of zmsg.h,
which is part of CZMQ (the high-level C binding). Furthermore, it is a major
improvement compared to zmsg.hpp, which is part of the examples in the MQ
Guide. Unnecessary copying is avoided by using move semantics to efficiently
add/remove parts.
*/
class multipart_t
{
private:
std::deque<message_t> m_parts;
public:
multipart_t()
{}
multipart_t(socket_t& socket)
{
recv(socket);
}
multipart_t(const void *src, size_t size)
{
addmem(src, size);
}
multipart_t(const std::string& string)
{
addstr(string);
}
multipart_t(message_t&& message)
{
add(std::move(message));
}
multipart_t(multipart_t&& other)
{
std::swap(m_parts, other.m_parts);
}
multipart_t& operator=(multipart_t&& other)
{
std::swap(m_parts, other.m_parts);
return *this;
}
virtual ~multipart_t()
{
clear();
}
void clear()
{
m_parts.clear();
}
size_t size() const
{
return m_parts.size();
}
bool empty() const
{
return m_parts.empty();
}
bool recv(socket_t& socket, int flags = 0)
{
clear();
bool more = true;
while (more)
{
message_t message;
if (!socket.recv(&message, flags))
return false;
more = message.more();
add(std::move(message));
}
return true;
}
bool send(socket_t& socket, int flags = 0)
{
flags &= ~(ZMQ_SNDMORE);
bool more = size() > 0;
while (more)
{
message_t message = pop();
more = size() > 0;
if (!socket.send(message, (more ? ZMQ_SNDMORE : 0) | flags))
return false;
}
clear();
return true;
}
void prepend(multipart_t&& other)
{
while (!other.empty())
push(other.remove());
}
void append(multipart_t&& other)
{
while (!other.empty())
add(other.pop());
}
void pushmem(const void *src, size_t size)
{
m_parts.push_front(message_t(src, size));
}
void addmem(const void *src, size_t size)
{
m_parts.push_back(message_t(src, size));
}
void pushstr(const std::string& string)
{
m_parts.push_front(message_t(string.data(), string.size()));
}
void addstr(const std::string& string)
{
m_parts.push_back(message_t(string.data(), string.size()));
}
template<typename T>
void pushtyp(const T& type)
{
m_parts.push_front(message_t(&type, sizeof(type)));
}
template<typename T>
void addtyp(const T& type)
{
m_parts.push_back(message_t(&type, sizeof(type)));
}
void push(message_t&& message)
{
m_parts.push_front(std::move(message));
}
void add(message_t&& message)
{
m_parts.push_back(std::move(message));
}
std::string popstr()
{
if (m_parts.empty())
return "";
std::string string(m_parts.front().data<char>(), m_parts.front().size());
m_parts.pop_front();
return string;
}
template<typename T>
T poptyp()
{
if (m_parts.empty())
return T();
T type = *m_parts.front().data<T>();
m_parts.pop_front();
return type;
}
message_t pop()
{
if (m_parts.empty())
return message_t(0);
message_t message = std::move(m_parts.front());
m_parts.pop_front();
return message;
}
message_t remove()
{
if (m_parts.empty())
return message_t(0);
message_t message = std::move(m_parts.back());
m_parts.pop_back();
return message;
}
const message_t* peek(size_t index) const
{
if (index >= size())
return nullptr;
return &m_parts[index];
}
template<typename T>
static multipart_t create(const T& type)
{
multipart_t multipart;
multipart.addtyp(type);
return multipart;
}
multipart_t clone() const
{
multipart_t multipart;
for (size_t i = 0; i < size(); i++)
multipart.addmem(m_parts[i].data(), m_parts[i].size());
return multipart;
}
std::string str() const
{
std::stringstream ss;
for (size_t i = 0; i < m_parts.size(); i++)
{
const unsigned char* data = m_parts[i].data<unsigned char>();
size_t size = m_parts[i].size();
// Dump the message as text or binary
bool isText = true;
for (size_t j = 0; j < size; j++)
{
if (data[j] < 32 || data[j] > 127)
{
isText = false;
break;
}
}
ss << "\n[" << std::dec << std::setw(3) << std::setfill('0') << size << "] ";
if (size >= 1000)
{
ss << "... (to big to print)";
continue;
}
for (size_t j = 0; j < size; j++)
{
if (isText)
ss << static_cast<char>(data[j]);
else
ss << std::hex << std::setw(2) << std::setfill('0') << static_cast<short>(data[j]);
}
}
return ss.str();
}
bool equal(const multipart_t* other) const
{
if (size() != other->size())
return false;
for (size_t i = 0; i < size(); i++)
if (!peek(i)->equal(other->peek(i)))
return false;
return true;
}
static int test()
{
bool ok = true;
float num = 0;
std::string str = "";
message_t msg;
// Create two PAIR sockets and connect over inproc
context_t context(1);
socket_t output(context, ZMQ_PAIR);
socket_t input(context, ZMQ_PAIR);
output.bind("inproc://multipart.test");
input.connect("inproc://multipart.test");
// Test send and receive of single-frame message
multipart_t multipart;
assert(multipart.empty());
multipart.push(message_t("Hello", 5));
assert(multipart.size() == 1);
ok = multipart.send(output);
assert(multipart.empty());
assert(ok);
ok = multipart.recv(input);
assert(multipart.size() == 1);
assert(ok);
msg = multipart.pop();
assert(multipart.empty());
assert(std::string(msg.data<char>(), msg.size()) == "Hello");
// Test send and receive of multi-frame message
multipart.addstr("A");
multipart.addstr("BB");
multipart.addstr("CCC");
assert(multipart.size() == 3);
multipart_t copy = multipart.clone();
assert(copy.size() == 3);
ok = copy.send(output);
assert(copy.empty());
assert(ok);
ok = copy.recv(input);
assert(copy.size() == 3);
assert(ok);
assert(copy.equal(&multipart));
multipart.clear();
assert(multipart.empty());
// Test message frame manipulation
multipart.add(message_t("Frame5", 6));
multipart.addstr("Frame6");
multipart.addstr("Frame7");
multipart.addtyp(8.0f);
multipart.addmem("Frame9", 6);
multipart.push(message_t("Frame4", 6));
multipart.pushstr("Frame3");
multipart.pushstr("Frame2");
multipart.pushtyp(1.0f);
multipart.pushmem("Frame0", 6);
assert(multipart.size() == 10);
msg = multipart.remove();
assert(multipart.size() == 9);
assert(std::string(msg.data<char>(), msg.size()) == "Frame9");
msg = multipart.pop();
assert(multipart.size() == 8);
assert(std::string(msg.data<char>(), msg.size()) == "Frame0");
num = multipart.poptyp<float>();
assert(multipart.size() == 7);
assert(num == 1.0f);
str = multipart.popstr();
assert(multipart.size() == 6);
assert(str == "Frame2");
str = multipart.popstr();
assert(multipart.size() == 5);
assert(str == "Frame3");
str = multipart.popstr();
assert(multipart.size() == 4);
assert(str == "Frame4");
str = multipart.popstr();
assert(multipart.size() == 3);
assert(str == "Frame5");
str = multipart.popstr();
assert(multipart.size() == 2);
assert(str == "Frame6");
str = multipart.popstr();
assert(multipart.size() == 1);
assert(str == "Frame7");
num = multipart.poptyp<float>();
assert(multipart.empty());
assert(num == 8.0f);
// Test message constructors and concatenation
multipart_t head("One", 3);
head.addstr("Two");
assert(head.size() == 2);
multipart_t tail("One-hundred");
tail.pushstr("Ninety-nine");
assert(tail.size() == 2);
multipart_t tmp(message_t("Fifty", 5));
assert(tmp.size() == 1);
multipart_t mid = multipart_t::create(49.0f);
mid.append(std::move(tmp));
assert(mid.size() == 2);
assert(tmp.empty());
multipart_t merged(std::move(mid));
merged.prepend(std::move(head));
merged.append(std::move(tail));
assert(merged.size() == 6);
assert(head.empty());
assert(tail.empty());
ok = merged.send(output);
assert(merged.empty());
assert(ok);
multipart_t received(input);
assert(received.size() == 6);
str = received.popstr();
assert(received.size() == 5);
assert(str == "One");
str = received.popstr();
assert(received.size() == 4);
assert(str == "Two");
num = received.poptyp<float>();
assert(received.size() == 3);
assert(num == 49.0f);
str = received.popstr();
assert(received.size() == 2);
assert(str == "Fifty");
str = received.popstr();
assert(received.size() == 1);
assert(str == "Ninety-nine");
str = received.popstr();
assert(received.empty());
assert(str == "One-hundred");
return 0;
}
private:
// Disable implicit copying (moving is more efficient)
multipart_t(const multipart_t& other) ZMQ_DELETED_FUNCTION;
void operator=(const multipart_t& other) ZMQ_DELETED_FUNCTION;
};
#endif
}
#endif
<commit_msg>Add comments, optimize some functions, add static asserts<commit_after>/*
Copyright (c) 2016 VOCA AS / Harald Nkland
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to
deal in the Software without restriction, including without limitation the
rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
sell copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
IN THE SOFTWARE.
*/
#ifndef __ZMQ_ADDON_HPP_INCLUDED__
#define __ZMQ_ADDON_HPP_INCLUDED__
#include <zmq.hpp>
#include <deque>
#include <iomanip>
#include <sstream>
namespace zmq {
#ifdef ZMQ_HAS_RVALUE_REFS
/*
This class handles multipart messaging. It is the C++ equivalent of zmsg.h,
which is part of CZMQ (the high-level C binding). Furthermore, it is a major
improvement compared to zmsg.hpp, which is part of the examples in the MQ
Guide. Unnecessary copying is avoided by using move semantics to efficiently
add/remove parts.
*/
class multipart_t
{
private:
std::deque<message_t> m_parts;
public:
// Default constructor
multipart_t()
{}
// Construct from socket receive
multipart_t(socket_t& socket)
{
recv(socket);
}
// Construct from memory block
multipart_t(const void *src, size_t size)
{
addmem(src, size);
}
// Construct from string
multipart_t(const std::string& string)
{
addstr(string);
}
// Construct from message part
multipart_t(message_t&& message)
{
add(std::move(message));
}
// Move constructor
multipart_t(multipart_t&& other)
{
m_parts = std::move(other.m_parts);
}
// Move assignment operator
multipart_t& operator=(multipart_t&& other)
{
m_parts = std::move(other.m_parts);
return *this;
}
// Destructor
virtual ~multipart_t()
{
clear();
}
// Delete all parts
void clear()
{
m_parts.clear();
}
// Get number of parts
size_t size() const
{
return m_parts.size();
}
// Check if number of parts is zero
bool empty() const
{
return m_parts.empty();
}
// Receive multipart message from socket
bool recv(socket_t& socket, int flags = 0)
{
clear();
bool more = true;
while (more)
{
message_t message;
if (!socket.recv(&message, flags))
return false;
more = message.more();
add(std::move(message));
}
return true;
}
// Send multipart message to socket
bool send(socket_t& socket, int flags = 0)
{
flags &= ~(ZMQ_SNDMORE);
bool more = size() > 0;
while (more)
{
message_t message = pop();
more = size() > 0;
if (!socket.send(message, (more ? ZMQ_SNDMORE : 0) | flags))
return false;
}
clear();
return true;
}
// Concatenate other multipart to front
void prepend(multipart_t&& other)
{
while (!other.empty())
push(other.remove());
}
// Concatenate other multipart to back
void append(multipart_t&& other)
{
while (!other.empty())
add(other.pop());
}
// Push memory block to front
void pushmem(const void *src, size_t size)
{
m_parts.push_front(message_t(src, size));
}
// Push memory block to back
void addmem(const void *src, size_t size)
{
m_parts.push_back(message_t(src, size));
}
// Push string to front
void pushstr(const std::string& string)
{
m_parts.push_front(message_t(string.data(), string.size()));
}
// Push string to back
void addstr(const std::string& string)
{
m_parts.push_back(message_t(string.data(), string.size()));
}
// Push type (fixed-size) to front
template<typename T>
void pushtyp(const T& type)
{
static_assert(!std::is_same<T, std::string>::value, "Use pushstr() instead of pushtyp<std::string>()");
m_parts.push_front(message_t(&type, sizeof(type)));
}
// Push type (fixed-size) to back
template<typename T>
void addtyp(const T& type)
{
static_assert(!std::is_same<T, std::string>::value, "Use addstr() instead of addtyp<std::string>()");
m_parts.push_back(message_t(&type, sizeof(type)));
}
// Push message part to front
void push(message_t&& message)
{
m_parts.push_front(std::move(message));
}
// Push message part to back
void add(message_t&& message)
{
m_parts.push_back(std::move(message));
}
// Pop string from front
std::string popstr()
{
std::string string(m_parts.front().data<char>(), m_parts.front().size());
m_parts.pop_front();
return string;
}
// Pop type (fixed-size) from front
template<typename T>
T poptyp()
{
static_assert(!std::is_same<T, std::string>::value, "Use popstr() instead of poptyp<std::string>()");
if (sizeof(T) != m_parts.front().size())
throw std::exception("Invalid type, size does not match the message size");
T type = *m_parts.front().data<T>();
m_parts.pop_front();
return type;
}
// Pop message part from front
message_t pop()
{
message_t message = std::move(m_parts.front());
m_parts.pop_front();
return message;
}
// Pop message part from back
message_t remove()
{
message_t message = std::move(m_parts.back());
m_parts.pop_back();
return message;
}
// Get pointer to a specific message part
const message_t* peek(size_t index) const
{
return &m_parts[index];
}
// Create multipart from type (fixed-size)
template<typename T>
static multipart_t create(const T& type)
{
multipart_t multipart;
multipart.addtyp(type);
return multipart;
}
// Copy multipart
multipart_t clone() const
{
multipart_t multipart;
for (size_t i = 0; i < size(); i++)
multipart.addmem(m_parts[i].data(), m_parts[i].size());
return multipart;
}
// Dump content to string
std::string str() const
{
std::stringstream ss;
for (size_t i = 0; i < m_parts.size(); i++)
{
const unsigned char* data = m_parts[i].data<unsigned char>();
size_t size = m_parts[i].size();
// Dump the message as text or binary
bool isText = true;
for (size_t j = 0; j < size; j++)
{
if (data[j] < 32 || data[j] > 127)
{
isText = false;
break;
}
}
ss << "\n[" << std::dec << std::setw(3) << std::setfill('0') << size << "] ";
if (size >= 1000)
{
ss << "... (to big to print)";
continue;
}
for (size_t j = 0; j < size; j++)
{
if (isText)
ss << static_cast<char>(data[j]);
else
ss << std::hex << std::setw(2) << std::setfill('0') << static_cast<short>(data[j]);
}
}
return ss.str();
}
// Check if equal to other multipart
bool equal(const multipart_t* other) const
{
if (size() != other->size())
return false;
for (size_t i = 0; i < size(); i++)
if (!peek(i)->equal(other->peek(i)))
return false;
return true;
}
// Self test
static int test()
{
bool ok = true;
float num = 0;
std::string str = "";
message_t msg;
// Create two PAIR sockets and connect over inproc
context_t context(1);
socket_t output(context, ZMQ_PAIR);
socket_t input(context, ZMQ_PAIR);
output.bind("inproc://multipart.test");
input.connect("inproc://multipart.test");
// Test send and receive of single-frame message
multipart_t multipart;
assert(multipart.empty());
multipart.push(message_t("Hello", 5));
assert(multipart.size() == 1);
ok = multipart.send(output);
assert(multipart.empty());
assert(ok);
ok = multipart.recv(input);
assert(multipart.size() == 1);
assert(ok);
msg = multipart.pop();
assert(multipart.empty());
assert(std::string(msg.data<char>(), msg.size()) == "Hello");
// Test send and receive of multi-frame message
multipart.addstr("A");
multipart.addstr("BB");
multipart.addstr("CCC");
assert(multipart.size() == 3);
multipart_t copy = multipart.clone();
assert(copy.size() == 3);
ok = copy.send(output);
assert(copy.empty());
assert(ok);
ok = copy.recv(input);
assert(copy.size() == 3);
assert(ok);
assert(copy.equal(&multipart));
multipart.clear();
assert(multipart.empty());
// Test message frame manipulation
multipart.add(message_t("Frame5", 6));
multipart.addstr("Frame6");
multipart.addstr("Frame7");
multipart.addtyp(8.0f);
multipart.addmem("Frame9", 6);
multipart.push(message_t("Frame4", 6));
multipart.pushstr("Frame3");
multipart.pushstr("Frame2");
multipart.pushtyp(1.0f);
multipart.pushmem("Frame0", 6);
assert(multipart.size() == 10);
msg = multipart.remove();
assert(multipart.size() == 9);
assert(std::string(msg.data<char>(), msg.size()) == "Frame9");
msg = multipart.pop();
assert(multipart.size() == 8);
assert(std::string(msg.data<char>(), msg.size()) == "Frame0");
num = multipart.poptyp<float>();
assert(multipart.size() == 7);
assert(num == 1.0f);
str = multipart.popstr();
assert(multipart.size() == 6);
assert(str == "Frame2");
str = multipart.popstr();
assert(multipart.size() == 5);
assert(str == "Frame3");
str = multipart.popstr();
assert(multipart.size() == 4);
assert(str == "Frame4");
str = multipart.popstr();
assert(multipart.size() == 3);
assert(str == "Frame5");
str = multipart.popstr();
assert(multipart.size() == 2);
assert(str == "Frame6");
str = multipart.popstr();
assert(multipart.size() == 1);
assert(str == "Frame7");
num = multipart.poptyp<float>();
assert(multipart.empty());
assert(num == 8.0f);
// Test message constructors and concatenation
multipart_t head("One", 3);
head.addstr("Two");
assert(head.size() == 2);
multipart_t tail("One-hundred");
tail.pushstr("Ninety-nine");
assert(tail.size() == 2);
multipart_t tmp(message_t("Fifty", 5));
assert(tmp.size() == 1);
multipart_t mid = multipart_t::create(49.0f);
mid.append(std::move(tmp));
assert(mid.size() == 2);
assert(tmp.empty());
multipart_t merged(std::move(mid));
merged.prepend(std::move(head));
merged.append(std::move(tail));
assert(merged.size() == 6);
assert(head.empty());
assert(tail.empty());
ok = merged.send(output);
assert(merged.empty());
assert(ok);
multipart_t received(input);
assert(received.size() == 6);
str = received.popstr();
assert(received.size() == 5);
assert(str == "One");
str = received.popstr();
assert(received.size() == 4);
assert(str == "Two");
num = received.poptyp<float>();
assert(received.size() == 3);
assert(num == 49.0f);
str = received.popstr();
assert(received.size() == 2);
assert(str == "Fifty");
str = received.popstr();
assert(received.size() == 1);
assert(str == "Ninety-nine");
str = received.popstr();
assert(received.empty());
assert(str == "One-hundred");
return 0;
}
private:
// Disable implicit copying (moving is more efficient)
multipart_t(const multipart_t& other) ZMQ_DELETED_FUNCTION;
void operator=(const multipart_t& other) ZMQ_DELETED_FUNCTION;
};
#endif
}
#endif
<|endoftext|> |
<commit_before>/* Siconos-sample , Copyright INRIA 2005-2011.
* Siconos is a program dedicated to modeling, simulation and control
* of non smooth dynamical systems.
* Siconos is a free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
* Siconos is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY 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 Siconos; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*
* Contact: Vincent ACARY vincent.acary@inrialpes.fr
*/
// =============================== Double Pendulum Example ===============================
//
// Author: Vincent Acary
//
// Keywords: LagrangianDS, LagrangianLinear relation, MoreauJeanOSI TimeStepping, LCP.
//
// =============================================================================================
#include "SiconosKernel.hpp"
#include <stdlib.h>
using namespace std;
#include <boost/progress.hpp>
double gravity = 10.0;
double m1 = 1.0;
double m2 = 1.0 ;
double l1 = 1.0 ;
double l2 = 1.0 ;
int main(int argc, char* argv[])
{
try
{
// ================= Creation of the model =======================
// User-defined main parameters
unsigned int nDof = 2; // degrees of freedom for robot arm
double t0 = 0; // initial computation time
double T = 5.0; // final computation time
double h = 0.0005; // time step
double criterion = 0.05;
unsigned int maxIter = 20000;
double e = 1.0; // nslaw
double e1 = 0.0;
// -> mind to set the initial conditions below.
// -------------------------
// --- Dynamical systems ---
// -------------------------
// --- DS: Double Pendulum ---
// Initial position (angles in radian)
SP::SiconosVector q0(new SiconosVector(nDof));
SP::SiconosVector v0(new SiconosVector(nDof));
q0->zero();
v0->zero();
// (*q0)(0) = 1.5;
// (*q0)(1) = 1.5;
// for sympy plugins uncomment below (relative parametrization)
// (*q0)(0) = 0.1;
// (*q0)(1) = 0.1;
(*q0)(0) = 0.1;
(*q0)(1) = 0.2;
/*REGULAR PLUGINS - uncomment to use*/
SP::LagrangianDS doublependulum(new LagrangianDS(q0, v0, "DoublePendulumPlugin:mass"));
doublependulum->setComputeNNLFunction("DoublePendulumPlugin", "NNL");
doublependulum->setComputeJacobianNNLqDotFunction("DoublePendulumPlugin", "jacobianVNNL");
doublependulum->setComputeJacobianNNLqFunction("DoublePendulumPlugin", "jacobianNNLq");
doublependulum->setComputeFIntFunction("DoublePendulumPlugin", "FInt");
doublependulum->setComputeJacobianFIntqDotFunction("DoublePendulumPlugin", "jacobianVFInt");
doublependulum->setComputeJacobianFIntqFunction("DoublePendulumPlugin", "jacobianFIntq");
/*SYMPY PLUGINS - uncomment to use*/
// SP::LagrangianDS doublependulum(new LagrangianDS(q0, v0, "DoublePendulumSymPyPlugin:mass"));
// doublependulum->setComputeNNLFunction("DoublePendulumSymPyPlugin", "NNL");
// doublependulum->setComputeJacobianNNLqDotFunction("DoublePendulumSymPyPlugin", "jacobianVNNL");
// doublependulum->setComputeJacobianNNLqFunction("DoublePendulumSymPyPlugin", "jacobianNNLq");
// -------------------
// --- Interactions---
// -------------------
// -- relations --
string G = "DoublePendulumPlugin:G0";
SP::NonSmoothLaw nslaw(new NewtonImpactNSL(e));
SP::Relation relation(new LagrangianScleronomousR("DoublePendulumPlugin:h0", G));
SP::Interaction inter(new Interaction(1, nslaw, relation));
string G1 = "DoublePendulumPlugin:G1";
SP::NonSmoothLaw nslaw1(new NewtonImpactNSL(e1));
SP::Relation relation1(new LagrangianScleronomousR("DoublePendulumPlugin:h1", G1));
SP::Interaction inter1(new Interaction(1, nslaw1, relation1));
// -------------
// --- Model ---
// -------------
SP::Model Pendulum(new Model(t0, T));
Pendulum->nonSmoothDynamicalSystem()->insertDynamicalSystem(doublependulum);
Pendulum->nonSmoothDynamicalSystem()->link(inter,doublependulum);
Pendulum->nonSmoothDynamicalSystem()->link(inter1,doublependulum);
// ----------------
// --- Simulation ---
// ----------------
// -- Time discretisation --
SP::TimeDiscretisation t(new TimeDiscretisation(t0, h));
SP::TimeStepping s(new TimeStepping(t));
// s->setUseRelativeConvergenceCriteron(true);
// -- OneStepIntegrators --
//double theta=0.500001;
double theta = 0.500001;
SP::MoreauJeanOSI OSI(new MoreauJeanOSI(doublependulum, theta));
s->insertIntegrator(OSI);
// -- OneStepNsProblem --
SP::OneStepNSProblem osnspb(new LCP());
s->insertNonSmoothProblem(osnspb);
cout << "=== End of model loading === " << endl;
// =========================== End of model definition =========================== dataPlot(k,7) = (*inter->y(0))(0);
// ================================= Computation =================================
// --- Simulation initialization ---
Pendulum->initialize(s);
cout << "End of simulation initialisation" << endl;
int k = 0;
int N = ceil((T - t0) / h);
cout << "Number of time step " << N << endl;
// --- Get the values to be plotted ---
// -> saved in a matrix dataPlot
unsigned int outputSize = 12;
SimpleMatrix dataPlot(N + 1, outputSize);
// For the initial time step:
// time
SP::SiconosVector q = doublependulum->q();
SP::SiconosVector v = doublependulum->velocity();
dataPlot(k, 0) = t0;
dataPlot(k, 1) = (*q)(0);
dataPlot(k, 2) = (*v)(0);
dataPlot(k, 3) = (*q)(1);
dataPlot(k, 4) = (*v)(1);
dataPlot(k, 5) = l1 * sin((*q)(0));
dataPlot(k, 6) = -l1 * cos((*q)(0));
dataPlot(k, 7) = l1 * sin((*q)(0)) + l2 * sin((*q)(1));
dataPlot(k, 8) = -l1 * cos((*q)(0)) - l2 * cos((*q)(1));
dataPlot(k, 9) = l1 * cos((*q)(0)) * ((*v)(0));
dataPlot(k, 10) = l1 * cos((*q)(0)) * ((*v)(0)) + l2 * cos((*q)(1)) * ((*v)(1));
boost::timer time;
time.restart();
// --- Time loop ---
cout << "Start computation ... " << endl;
boost::progress_display show_progress(N);
while (s->hasNextEvent())
{
k++;
++show_progress;
// if (!(div(k,1000).rem)) cout <<"Step number "<< k << "\n";
// Solve problem
s->newtonSolve(criterion, maxIter);
// Data Output
dataPlot(k, 0) = s->nextTime();
dataPlot(k, 1) = (*q)(0);
dataPlot(k, 2) = (*v)(0);
dataPlot(k, 3) = (*q)(1);
dataPlot(k, 4) = (*v)(1);
dataPlot(k, 5) = l1 * sin((*q)(0));
dataPlot(k, 6) = -l1 * cos((*q)(0));
dataPlot(k, 7) = l1 * sin((*q)(0)) + l2 * sin((*q)(1));
dataPlot(k, 8) = -l1 * cos((*q)(0)) - l2 * cos((*q)(1));
dataPlot(k, 9) = l1 * cos((*q)(0)) * ((*v)(0));
dataPlot(k, 10) = l1 * cos((*q)(0)) * ((*v)(0)) + l2 * cos((*q)(1)) * ((*v)(1));
s->nextStep();
}
cout << "End of computation - Number of iterations done: " << k << endl;
cout << "Computation Time " << time.elapsed() << endl;
// --- Output files ---
ioMatrix::write("DoublePendulumResult.dat", "ascii", dataPlot, "noDim");
}
catch (SiconosException e)
{
cout << e.report() << endl;
}
catch (...)
{
cout << "Exception caught in \'sample/MultiBeadsColumn\'" << endl;
}
}
<commit_msg>[Examples] double pendulum plugin<commit_after>/* Siconos-sample , Copyright INRIA 2005-2011.
* Siconos is a program dedicated to modeling, simulation and control
* of non smooth dynamical systems.
* Siconos is a free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
* Siconos is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY 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 Siconos; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*
* Contact: Vincent ACARY vincent.acary@inrialpes.fr
*/
// =============================== Double Pendulum Example ===============================
//
// Author: Vincent Acary
//
// Keywords: LagrangianDS, LagrangianLinear relation, MoreauJeanOSI TimeStepping, LCP.
//
// =============================================================================================
#include "SiconosKernel.hpp"
#include <stdlib.h>
using namespace std;
#include <boost/progress.hpp>
double gravity = 10.0;
double m1 = 1.0;
double m2 = 1.0 ;
double l1 = 1.0 ;
double l2 = 1.0 ;
int main(int argc, char* argv[])
{
try
{
// ================= Creation of the model =======================
// User-defined main parameters
unsigned int nDof = 2; // degrees of freedom for robot arm
double t0 = 0; // initial computation time
double T = 5.0; // final computation time
double h = 0.0005; // time step
double criterion = 0.05;
unsigned int maxIter = 20000;
double e = 1.0; // nslaw
double e1 = 0.0;
// -> mind to set the initial conditions below.
// -------------------------
// --- Dynamical systems ---
// -------------------------
// --- DS: Double Pendulum ---
// Initial position (angles in radian)
SP::SiconosVector q0(new SiconosVector(nDof));
SP::SiconosVector v0(new SiconosVector(nDof));
q0->zero();
v0->zero();
// (*q0)(0) = 1.5;
// (*q0)(1) = 1.5;
// for sympy plugins uncomment below (relative parametrization)
// Note, we have the relation :
// absolute[(*q0)(0)] + relative[(*q0)(1)] = absolute[(*q0)(1)]
// (*q0)(0) = 0.1;
// (*q0)(1) = 0.1;
(*q0)(0) = 0.1;
(*q0)(1) = 0.2;
/*REGULAR PLUGINS - uncomment to use*/
SP::LagrangianDS doublependulum(new LagrangianDS(q0, v0, "DoublePendulumPlugin:mass"));
doublependulum->setComputeNNLFunction("DoublePendulumPlugin", "NNL");
doublependulum->setComputeJacobianNNLqDotFunction("DoublePendulumPlugin", "jacobianVNNL");
doublependulum->setComputeJacobianNNLqFunction("DoublePendulumPlugin", "jacobianNNLq");
doublependulum->setComputeFIntFunction("DoublePendulumPlugin", "FInt");
doublependulum->setComputeJacobianFIntqDotFunction("DoublePendulumPlugin", "jacobianVFInt");
doublependulum->setComputeJacobianFIntqFunction("DoublePendulumPlugin", "jacobianFIntq");
/*SYMPY PLUGINS - uncomment to use*/
// SP::LagrangianDS doublependulum(new LagrangianDS(q0, v0, "DoublePendulumSymPyPlugin:mass"));
// doublependulum->setComputeNNLFunction("DoublePendulumSymPyPlugin", "NNL");
// doublependulum->setComputeJacobianNNLqDotFunction("DoublePendulumSymPyPlugin", "jacobianVNNL");
// doublependulum->setComputeJacobianNNLqFunction("DoublePendulumSymPyPlugin", "jacobianNNLq");
// -------------------
// --- Interactions---
// -------------------
// -- relations --
string G = "DoublePendulumPlugin:G0";
SP::NonSmoothLaw nslaw(new NewtonImpactNSL(e));
SP::Relation relation(new LagrangianScleronomousR("DoublePendulumPlugin:h0", G));
SP::Interaction inter(new Interaction(1, nslaw, relation));
string G1 = "DoublePendulumPlugin:G1";
SP::NonSmoothLaw nslaw1(new NewtonImpactNSL(e1));
SP::Relation relation1(new LagrangianScleronomousR("DoublePendulumPlugin:h1", G1));
SP::Interaction inter1(new Interaction(1, nslaw1, relation1));
// -------------
// --- Model ---
// -------------
SP::Model Pendulum(new Model(t0, T));
Pendulum->nonSmoothDynamicalSystem()->insertDynamicalSystem(doublependulum);
Pendulum->nonSmoothDynamicalSystem()->link(inter,doublependulum);
Pendulum->nonSmoothDynamicalSystem()->link(inter1,doublependulum);
// ----------------
// --- Simulation ---
// ----------------
// -- Time discretisation --
SP::TimeDiscretisation t(new TimeDiscretisation(t0, h));
SP::TimeStepping s(new TimeStepping(t));
// s->setUseRelativeConvergenceCriteron(true);
// -- OneStepIntegrators --
//double theta=0.500001;
double theta = 0.500001;
SP::MoreauJeanOSI OSI(new MoreauJeanOSI(doublependulum, theta));
s->insertIntegrator(OSI);
// -- OneStepNsProblem --
SP::OneStepNSProblem osnspb(new LCP());
s->insertNonSmoothProblem(osnspb);
cout << "=== End of model loading === " << endl;
// =========================== End of model definition =========================== dataPlot(k,7) = (*inter->y(0))(0);
// ================================= Computation =================================
// --- Simulation initialization ---
Pendulum->initialize(s);
cout << "End of simulation initialisation" << endl;
int k = 0;
int N = ceil((T - t0) / h);
cout << "Number of time step " << N << endl;
// --- Get the values to be plotted ---
// -> saved in a matrix dataPlot
unsigned int outputSize = 12;
SimpleMatrix dataPlot(N + 1, outputSize);
// For the initial time step:
// time
SP::SiconosVector q = doublependulum->q();
SP::SiconosVector v = doublependulum->velocity();
dataPlot(k, 0) = t0;
dataPlot(k, 1) = (*q)(0);
dataPlot(k, 2) = (*v)(0);
dataPlot(k, 3) = (*q)(1);
dataPlot(k, 4) = (*v)(1);
dataPlot(k, 5) = l1 * sin((*q)(0));
dataPlot(k, 6) = -l1 * cos((*q)(0));
dataPlot(k, 7) = l1 * sin((*q)(0)) + l2 * sin((*q)(1));
dataPlot(k, 8) = -l1 * cos((*q)(0)) - l2 * cos((*q)(1));
dataPlot(k, 9) = l1 * cos((*q)(0)) * ((*v)(0));
dataPlot(k, 10) = l1 * cos((*q)(0)) * ((*v)(0)) + l2 * cos((*q)(1)) * ((*v)(1));
boost::timer time;
time.restart();
// --- Time loop ---
cout << "Start computation ... " << endl;
boost::progress_display show_progress(N);
while (s->hasNextEvent())
{
k++;
++show_progress;
// if (!(div(k,1000).rem)) cout <<"Step number "<< k << "\n";
// Solve problem
s->newtonSolve(criterion, maxIter);
// Data Output
dataPlot(k, 0) = s->nextTime();
dataPlot(k, 1) = (*q)(0);
dataPlot(k, 2) = (*v)(0);
dataPlot(k, 3) = (*q)(1);
// sympy plugin with relative parametrization:
// dataPlot(k, 3) = (*q)(0) + (*q)(1);
dataPlot(k, 4) = (*v)(1);
// sympy plugin with relative parametrization:
// dataPlot(k, 4) = (*v)(0) + (*v)(1);
dataPlot(k, 5) = l1 * sin((*q)(0));
dataPlot(k, 6) = -l1 * cos((*q)(0));
dataPlot(k, 7) = l1 * sin((*q)(0)) + l2 * sin((*q)(1));
dataPlot(k, 8) = -l1 * cos((*q)(0)) - l2 * cos((*q)(1));
dataPlot(k, 9) = l1 * cos((*q)(0)) * ((*v)(0));
dataPlot(k, 10) = l1 * cos((*q)(0)) * ((*v)(0)) + l2 * cos((*q)(1)) * ((*v)(1));
s->nextStep();
}
cout << "End of computation - Number of iterations done: " << k << endl;
cout << "Computation Time " << time.elapsed() << endl;
// --- Output files ---
ioMatrix::write("DoublePendulumResult.dat", "ascii", dataPlot, "noDim");
}
catch (SiconosException e)
{
cout << e.report() << endl;
}
catch (...)
{
cout << "Exception caught in \'sample/MultiBeadsColumn\'" << endl;
}
}
<|endoftext|> |
<commit_before>#include "SampleCode.h"
#include "SkView.h"
#include "SkCanvas.h"
#include "SkTypeface.h"
#include "SkPath.h"
#include "SkRegion.h"
#include "SkShader.h"
#include "SkUtils.h"
#include "Sk1DPathEffect.h"
#include "SkCornerPathEffect.h"
#include "SkPathMeasure.h"
#include "SkRandom.h"
#include "SkColorPriv.h"
#include "SkColorFilter.h"
#include "SkDither.h"
static int dither_4444(int x) {
return ((x << 1) - ((x >> 4 << 4) | (x >> 4))) >> 4;
}
/** Ensure that the max of the original and dithered value (for alpha) is always
>= any other dithered value. We apply this "max" in colorpriv.h when we
predither down to 4444, to be sure that we stay in legal premultiplied form
*/
static void test_4444_dither() {
int buckets[16];
sk_bzero(buckets, sizeof(buckets));
for (int a = 0; a <= 0xFF; a++) {
int da = dither_4444(a);
int maxa = SkMax32(a >> 4, da);
// SkDebugf("--- %02X %X\n", a, da);
buckets[da] += 1;
for (int c = 0; c <= a; c++) {
int dc = dither_4444(c);
if (maxa < dc) {
SkDebugf("------------ error a=%d da=%d c=%d dc=%d\n", a, da,
c, dc);
}
}
}
for (int i = 0; i < 16; i++) {
// SkDebugf("[%d] = %d\n", i, buckets[i]);
}
}
static const struct {
const char* fName;
SkTypeface::Style fStyle;
} gFaces[] = {
{ NULL, SkTypeface::kNormal },
{ NULL, SkTypeface::kBold },
{ "serif", SkTypeface::kNormal },
{ "serif", SkTypeface::kBold },
{ "serif", SkTypeface::kItalic },
{ "serif", SkTypeface::kBoldItalic },
{ "monospace", SkTypeface::kNormal }
};
static const int gFaceCount = SK_ARRAY_COUNT(gFaces);
class TypefaceView : public SkView {
SkTypeface* fFaces[gFaceCount];
public:
TypefaceView() {
test_4444_dither();
for (int i = 0; i < gFaceCount; i++) {
fFaces[i] = SkTypeface::CreateFromName(gFaces[i].fName,
gFaces[i].fStyle);
}
}
virtual ~TypefaceView() {
for (int i = 0; i < gFaceCount; i++) {
SkSafeUnref(fFaces[i]);
}
}
protected:
// overrides from SkEventSink
virtual bool onQuery(SkEvent* evt) {
if (SampleCode::TitleQ(*evt)) {
SampleCode::TitleR(evt, "Typefaces");
return true;
}
return this->INHERITED::onQuery(evt);
}
void drawBG(SkCanvas* canvas) {
canvas->drawColor(0xFFDDDDDD);
}
virtual void onDraw(SkCanvas* canvas) {
this->drawBG(canvas);
SkPaint paint;
paint.setAntiAlias(true);
paint.setTextSize(SkIntToScalar(30));
if (false) {
paint.setStyle(SkPaint::kStroke_Style);
paint.setStrokeWidth(SkIntToScalar(1));
}
const char* text = "Hamburgefons";
const size_t textLen = strlen(text);
SkScalar x = SkIntToScalar(10);
SkScalar dy = paint.getFontMetrics(NULL);
SkScalar y = dy;
for (int i = 0; i < gFaceCount; i++) {
paint.setTypeface(fFaces[i]);
canvas->drawText(text, textLen, x, y, paint);
y += dy;
}
SkRect r;
if (false) {
r.set(10, 10, 100, 100);
paint.setStyle(SkPaint::kStrokeAndFill_Style);
paint.setColor(SK_ColorBLUE);
paint.setStrokeWidth(1);
canvas->drawRect(r, paint);
paint.setStrokeWidth(0);
}
if (false) {
r.set(294912.75f, 294912.75f, 884738.25f, 884738.25f);
canvas->scale(2.4414E-4f, 2.4414E-4f);
paint.setStyle(SkPaint::kFill_Style);
canvas->drawRect(r, paint);
}
if (false) {
SkScalar rad = 90;
SkScalar angle = 210;
SkScalar cx = 150;
SkScalar cy = 105;
r.set(cx - rad, cy - rad, cx + rad, cy + rad);
SkPath path;
path.arcTo(r, angle, -(angle + 90), true);
path.close();
paint.setColor(SK_ColorRED);
canvas->drawRect(path.getBounds(), paint);
paint.setColor(SK_ColorBLUE);
canvas->drawPath(path, paint);
paint.setColor(SK_ColorGREEN);
SkPoint pts[100];
int count = path.getPoints(pts, 100);
paint.setStrokeWidth(5);
canvas->drawPoints(SkCanvas::kPoints_PointMode, count, pts, paint);
}
}
private:
typedef SkView INHERITED;
};
//////////////////////////////////////////////////////////////////////////////
static SkView* MyFactory() { return new TypefaceView; }
static SkViewRegister reg(MyFactory);
<commit_msg>add more styles to show<commit_after>#include "SampleCode.h"
#include "SkView.h"
#include "SkCanvas.h"
#include "SkTypeface.h"
#include "SkPath.h"
#include "SkRegion.h"
#include "SkShader.h"
#include "SkUtils.h"
#include "Sk1DPathEffect.h"
#include "SkCornerPathEffect.h"
#include "SkPathMeasure.h"
#include "SkRandom.h"
#include "SkColorPriv.h"
#include "SkColorFilter.h"
#include "SkDither.h"
static int dither_4444(int x) {
return ((x << 1) - ((x >> 4 << 4) | (x >> 4))) >> 4;
}
/** Ensure that the max of the original and dithered value (for alpha) is always
>= any other dithered value. We apply this "max" in colorpriv.h when we
predither down to 4444, to be sure that we stay in legal premultiplied form
*/
static void test_4444_dither() {
int buckets[16];
sk_bzero(buckets, sizeof(buckets));
for (int a = 0; a <= 0xFF; a++) {
int da = dither_4444(a);
int maxa = SkMax32(a >> 4, da);
// SkDebugf("--- %02X %X\n", a, da);
buckets[da] += 1;
for (int c = 0; c <= a; c++) {
int dc = dither_4444(c);
if (maxa < dc) {
SkDebugf("------------ error a=%d da=%d c=%d dc=%d\n", a, da,
c, dc);
}
}
}
for (int i = 0; i < 16; i++) {
// SkDebugf("[%d] = %d\n", i, buckets[i]);
}
}
static const struct {
const char* fName;
SkTypeface::Style fStyle;
} gFaces[] = {
{ NULL, SkTypeface::kNormal },
{ NULL, SkTypeface::kBold },
{ NULL, SkTypeface::kItalic },
{ NULL, SkTypeface::kBoldItalic },
{ "serif", SkTypeface::kNormal },
{ "serif", SkTypeface::kBold },
{ "serif", SkTypeface::kItalic },
{ "serif", SkTypeface::kBoldItalic },
{ "monospace", SkTypeface::kNormal },
{ "monospace", SkTypeface::kBold },
{ "monospace", SkTypeface::kItalic },
{ "monospace", SkTypeface::kBoldItalic },
};
static const int gFaceCount = SK_ARRAY_COUNT(gFaces);
class TypefaceView : public SkView {
SkTypeface* fFaces[gFaceCount];
public:
TypefaceView() {
test_4444_dither();
for (int i = 0; i < gFaceCount; i++) {
fFaces[i] = SkTypeface::CreateFromName(gFaces[i].fName,
gFaces[i].fStyle);
}
}
virtual ~TypefaceView() {
for (int i = 0; i < gFaceCount; i++) {
SkSafeUnref(fFaces[i]);
}
}
protected:
// overrides from SkEventSink
virtual bool onQuery(SkEvent* evt) {
if (SampleCode::TitleQ(*evt)) {
SampleCode::TitleR(evt, "Typefaces");
return true;
}
return this->INHERITED::onQuery(evt);
}
void drawBG(SkCanvas* canvas) {
canvas->drawColor(0xFFDDDDDD);
}
virtual void onDraw(SkCanvas* canvas) {
this->drawBG(canvas);
SkPaint paint;
paint.setAntiAlias(true);
paint.setTextSize(SkIntToScalar(30));
if (false) {
paint.setStyle(SkPaint::kStroke_Style);
paint.setStrokeWidth(SkIntToScalar(1));
}
const char* text = "Hamburgefons";
const size_t textLen = strlen(text);
SkScalar x = SkIntToScalar(10);
SkScalar dy = paint.getFontMetrics(NULL);
SkScalar y = dy;
for (int i = 0; i < gFaceCount; i++) {
paint.setTypeface(fFaces[i]);
canvas->drawText(text, textLen, x, y, paint);
y += dy;
}
SkRect r;
if (false) {
r.set(10, 10, 100, 100);
paint.setStyle(SkPaint::kStrokeAndFill_Style);
paint.setColor(SK_ColorBLUE);
paint.setStrokeWidth(1);
canvas->drawRect(r, paint);
paint.setStrokeWidth(0);
}
if (false) {
r.set(294912.75f, 294912.75f, 884738.25f, 884738.25f);
canvas->scale(2.4414E-4f, 2.4414E-4f);
paint.setStyle(SkPaint::kFill_Style);
canvas->drawRect(r, paint);
}
if (false) {
SkScalar rad = 90;
SkScalar angle = 210;
SkScalar cx = 150;
SkScalar cy = 105;
r.set(cx - rad, cy - rad, cx + rad, cy + rad);
SkPath path;
path.arcTo(r, angle, -(angle + 90), true);
path.close();
paint.setColor(SK_ColorRED);
canvas->drawRect(path.getBounds(), paint);
paint.setColor(SK_ColorBLUE);
canvas->drawPath(path, paint);
paint.setColor(SK_ColorGREEN);
SkPoint pts[100];
int count = path.getPoints(pts, 100);
paint.setStrokeWidth(5);
canvas->drawPoints(SkCanvas::kPoints_PointMode, count, pts, paint);
}
}
private:
typedef SkView INHERITED;
};
//////////////////////////////////////////////////////////////////////////////
static SkView* MyFactory() { return new TypefaceView; }
static SkViewRegister reg(MyFactory);
<|endoftext|> |
<commit_before>/****************************************************************************
**
** Copyright (C) 2013 Digia Plc and/or its subsidiary(-ies).
** Contact: http://www.qt-project.org/legal
**
** This file is part of Qt Creator.
**
** Commercial License Usage
** Licensees holding valid commercial Qt licenses may use this file in
** accordance with the commercial license agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and Digia. For licensing terms and
** conditions see http://qt.digia.com/licensing. For further information
** use the contact form at http://qt.digia.com/contact-us.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file. Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Digia gives you certain additional
** rights. These rights are described in the Digia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
****************************************************************************/
#include "searchresulttreeitems.h"
using namespace Find::Internal;
SearchResultTreeItem::SearchResultTreeItem(const SearchResultItem &item,
SearchResultTreeItem *parent)
: item(item),
m_parent(parent),
m_isUserCheckable(false),
m_isGenerated(false),
m_checkState(Qt::Unchecked)
{
}
SearchResultTreeItem::~SearchResultTreeItem()
{
clearChildren();
}
bool SearchResultTreeItem::isLeaf() const
{
return childrenCount() == 0 && parent() != 0;
}
bool SearchResultTreeItem::isUserCheckable() const
{
return m_isUserCheckable;
}
void SearchResultTreeItem::setIsUserCheckable(bool isUserCheckable)
{
m_isUserCheckable = isUserCheckable;
}
Qt::CheckState SearchResultTreeItem::checkState() const
{
return m_checkState;
}
void SearchResultTreeItem::setCheckState(Qt::CheckState checkState)
{
m_checkState = checkState;
}
void SearchResultTreeItem::clearChildren()
{
qDeleteAll(m_children);
m_children.clear();
}
int SearchResultTreeItem::childrenCount() const
{
return m_children.count();
}
int SearchResultTreeItem::rowOfItem() const
{
return (m_parent ? m_parent->m_children.indexOf(const_cast<SearchResultTreeItem*>(this)):0);
}
SearchResultTreeItem* SearchResultTreeItem::childAt(int index) const
{
return m_children.at(index);
}
SearchResultTreeItem *SearchResultTreeItem::parent() const
{
return m_parent;
}
static bool lessThanByText(SearchResultTreeItem *a, const QString &b)
{
return a->item.text < b;
}
int SearchResultTreeItem::insertionIndex(const QString &text, SearchResultTreeItem **existingItem) const
{
QList<SearchResultTreeItem *>::const_iterator insertionPosition =
qLowerBound(m_children.begin(), m_children.end(), text, lessThanByText);
if (existingItem) {
if (insertionPosition != m_children.end() && (*insertionPosition)->item.text == text)
(*existingItem) = (*insertionPosition);
else
*existingItem = 0;
}
return insertionPosition - m_children.begin();
}
int SearchResultTreeItem::insertionIndex(const SearchResultItem &item, SearchResultTreeItem **existingItem) const
{
return insertionIndex(item.text, existingItem);
}
void SearchResultTreeItem::insertChild(int index, SearchResultTreeItem *child)
{
m_children.insert(index, child);
}
void SearchResultTreeItem::insertChild(int index, const SearchResultItem &item)
{
SearchResultTreeItem *child = new SearchResultTreeItem(item, this);
if (isUserCheckable()) {
child->setIsUserCheckable(true);
child->setCheckState(Qt::Checked);
}
insertChild(index, child);
}
void SearchResultTreeItem::appendChild(const SearchResultItem &item)
{
insertChild(m_children.count(), item);
}
<commit_msg>Find: Compile fix<commit_after>/****************************************************************************
**
** Copyright (C) 2013 Digia Plc and/or its subsidiary(-ies).
** Contact: http://www.qt-project.org/legal
**
** This file is part of Qt Creator.
**
** Commercial License Usage
** Licensees holding valid commercial Qt licenses may use this file in
** accordance with the commercial license agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and Digia. For licensing terms and
** conditions see http://qt.digia.com/licensing. For further information
** use the contact form at http://qt.digia.com/contact-us.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file. Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Digia gives you certain additional
** rights. These rights are described in the Digia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
****************************************************************************/
#include "searchresulttreeitems.h"
namespace Find {
namespace Internal {
SearchResultTreeItem::SearchResultTreeItem(const SearchResultItem &item,
SearchResultTreeItem *parent)
: item(item),
m_parent(parent),
m_isUserCheckable(false),
m_isGenerated(false),
m_checkState(Qt::Unchecked)
{
}
SearchResultTreeItem::~SearchResultTreeItem()
{
clearChildren();
}
bool SearchResultTreeItem::isLeaf() const
{
return childrenCount() == 0 && parent() != 0;
}
bool SearchResultTreeItem::isUserCheckable() const
{
return m_isUserCheckable;
}
void SearchResultTreeItem::setIsUserCheckable(bool isUserCheckable)
{
m_isUserCheckable = isUserCheckable;
}
Qt::CheckState SearchResultTreeItem::checkState() const
{
return m_checkState;
}
void SearchResultTreeItem::setCheckState(Qt::CheckState checkState)
{
m_checkState = checkState;
}
void SearchResultTreeItem::clearChildren()
{
qDeleteAll(m_children);
m_children.clear();
}
int SearchResultTreeItem::childrenCount() const
{
return m_children.count();
}
int SearchResultTreeItem::rowOfItem() const
{
return (m_parent ? m_parent->m_children.indexOf(const_cast<SearchResultTreeItem*>(this)):0);
}
SearchResultTreeItem* SearchResultTreeItem::childAt(int index) const
{
return m_children.at(index);
}
SearchResultTreeItem *SearchResultTreeItem::parent() const
{
return m_parent;
}
static bool lessThanByText(SearchResultTreeItem *a, const QString &b)
{
return a->item.text < b;
}
int SearchResultTreeItem::insertionIndex(const QString &text, SearchResultTreeItem **existingItem) const
{
QList<SearchResultTreeItem *>::const_iterator insertionPosition =
qLowerBound(m_children.begin(), m_children.end(), text, lessThanByText);
if (existingItem) {
if (insertionPosition != m_children.end() && (*insertionPosition)->item.text == text)
(*existingItem) = (*insertionPosition);
else
*existingItem = 0;
}
return insertionPosition - m_children.begin();
}
int SearchResultTreeItem::insertionIndex(const SearchResultItem &item, SearchResultTreeItem **existingItem) const
{
return insertionIndex(item.text, existingItem);
}
void SearchResultTreeItem::insertChild(int index, SearchResultTreeItem *child)
{
m_children.insert(index, child);
}
void SearchResultTreeItem::insertChild(int index, const SearchResultItem &item)
{
SearchResultTreeItem *child = new SearchResultTreeItem(item, this);
if (isUserCheckable()) {
child->setIsUserCheckable(true);
child->setCheckState(Qt::Checked);
}
insertChild(index, child);
}
void SearchResultTreeItem::appendChild(const SearchResultItem &item)
{
insertChild(m_children.count(), item);
}
} // namespace Internal
} // namespace Find
<|endoftext|> |
<commit_before>/*
* Copyright 2011 Google Inc.
*
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*/
#include "TransitionView.h"
#include "OverView.h"
#include "SampleCode.h"
#include "SkView.h"
#include "SkCanvas.h"
#include "SkTime.h"
#include "SkInterpolator.h"
static const char gIsTransitionQuery[] = "is-transition";
static const char gReplaceTransitionEvt[] = "replace-transition-view";
bool is_transition(SkView* view) {
SkEvent isTransition(gIsTransitionQuery);
return view->doQuery(&isTransition);
}
class TransitionView : public SampleView {
enum {
// kDurationMS = 500
kDurationMS = 1
};
public:
TransitionView(SkView* prev, SkView* next, int direction) : fInterp(4, 2){
fAnimationDirection = (Direction)(1 << (direction % 8));
fPrev = prev;
fPrev->setClipToBounds(false);
fPrev->setVisibleP(true);
(void)SampleView::SetUsePipe(fPrev, SkOSMenu::kOffState);
//Not calling unref because fPrev is assumed to have been created, so
//this will result in a transfer of ownership
this->attachChildToBack(fPrev);
fNext = next;
fNext->setClipToBounds(true);
fNext->setVisibleP(true);
(void)SampleView::SetUsePipe(fNext, SkOSMenu::kOffState);
//Calling unref because next is a newly created view and TransitionView
//is now the sole owner of fNext
this->attachChildToFront(fNext)->unref();
fDone = false;
//SkDebugf("--created transition\n");
}
~TransitionView(){
//SkDebugf("--deleted transition\n");
}
virtual void requestMenu(SkOSMenu* menu) {
if (SampleView::IsSampleView(fNext))
((SampleView*)fNext)->requestMenu(menu);
}
protected:
virtual bool onQuery(SkEvent* evt) {
if (SampleCode::TitleQ(*evt)) {
SkString title;
if (SampleCode::RequestTitle(fNext, &title)) {
SampleCode::TitleR(evt, title.c_str());
return true;
}
return false;
}
if (evt->isType(gIsTransitionQuery)) {
return true;
}
return this->INHERITED::onQuery(evt);
}
virtual bool onEvent(const SkEvent& evt) {
if (evt.isType(gReplaceTransitionEvt)) {
fPrev->detachFromParent();
fPrev = (SkView*)SkEventSink::FindSink(evt.getFast32());
(void)SampleView::SetUsePipe(fPrev, SkOSMenu::kOffState);
//attach the new fPrev and call unref to balance the ref in onDraw
this->attachChildToBack(fPrev)->unref();
this->inval(NULL);
return true;
}
if (evt.isType("transition-done")) {
fNext->setLoc(0, 0);
fNext->setClipToBounds(false);
SkEvent* evt = new SkEvent(gReplaceTransitionEvt,
this->getParent()->getSinkID());
evt->setFast32(fNext->getSinkID());
//increate ref count of fNext so it survives detachAllChildren
fNext->ref();
this->detachAllChildren();
evt->post();
return true;
}
return this->INHERITED::onEvent(evt);
}
virtual void onDrawBackground(SkCanvas* canvas) {}
virtual void onDrawContent(SkCanvas* canvas) {
if (fDone)
return;
if (is_overview(fNext) || is_overview(fPrev)) {
fPipeState = SkOSMenu::kOffState;
}
SkScalar values[4];
SkInterpolator::Result result = fInterp.timeToValues(SkTime::GetMSecs(), values);
//SkDebugf("transition %x %d pipe:%d\n", this, result, fUsePipe);
//SkDebugf("%f %f %f %f %d\n", values[0], values[1], values[2], values[3], result);
if (SkInterpolator::kNormal_Result == result) {
fPrev->setLocX(values[kPrevX]);
fPrev->setLocY(values[kPrevY]);
fNext->setLocX(values[kNextX]);
fNext->setLocY(values[kNextY]);
this->inval(NULL);
}
else {
(new SkEvent("transition-done", this->getSinkID()))->post();
fDone = true;
}
}
virtual void onSizeChange() {
this->INHERITED::onSizeChange();
fNext->setSize(this->width(), this->height());
fPrev->setSize(this->width(), this->height());
SkScalar lr = 0, ud = 0;
if (fAnimationDirection & (kLeftDirection|kULDirection|kDLDirection))
lr = this->width();
if (fAnimationDirection & (kRightDirection|kURDirection|kDRDirection))
lr = -this->width();
if (fAnimationDirection & (kUpDirection|kULDirection|kURDirection))
ud = this->height();
if (fAnimationDirection & (kDownDirection|kDLDirection|kDRDirection))
ud = -this->height();
fBegin[kPrevX] = fBegin[kPrevY] = 0;
fBegin[kNextX] = lr;
fBegin[kNextY] = ud;
fNext->setLocX(lr);
fNext->setLocY(ud);
if (is_transition(fPrev))
lr = ud = 0;
fEnd[kPrevX] = -lr;
fEnd[kPrevY] = -ud;
fEnd[kNextX] = fEnd[kNextY] = 0;
SkScalar blend[] = { SkFloatToScalar(0.8f), SkFloatToScalar(0.0f),
SkFloatToScalar(0.0f), SK_Scalar1 };
fInterp.setKeyFrame(0, SkTime::GetMSecs(), fBegin, blend);
fInterp.setKeyFrame(1, SkTime::GetMSecs()+kDurationMS, fEnd, blend);
}
private:
enum {
kPrevX = 0,
kPrevY = 1,
kNextX = 2,
kNextY = 3
};
SkView* fPrev;
SkView* fNext;
bool fDone;
SkInterpolator fInterp;
enum Direction{
kUpDirection = 1,
kURDirection = 1 << 1,
kRightDirection = 1 << 2,
kDRDirection = 1 << 3,
kDownDirection = 1 << 4,
kDLDirection = 1 << 5,
kLeftDirection = 1 << 6,
kULDirection = 1 << 7
};
Direction fAnimationDirection;
SkScalar fBegin[4];
SkScalar fEnd[4];
typedef SampleView INHERITED;
};
SkView* create_transition(SkView* prev, SkView* next, int direction) {
return SkNEW_ARGS(TransitionView, (prev, next, direction));
}
<commit_msg>Disable transitions for the Android SampleApp.<commit_after>/*
* Copyright 2011 Google Inc.
*
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*/
#include "TransitionView.h"
#include "OverView.h"
#include "SampleCode.h"
#include "SkView.h"
#include "SkCanvas.h"
#include "SkTime.h"
#include "SkInterpolator.h"
static const char gIsTransitionQuery[] = "is-transition";
static const char gReplaceTransitionEvt[] = "replace-transition-view";
bool is_transition(SkView* view) {
SkEvent isTransition(gIsTransitionQuery);
return view->doQuery(&isTransition);
}
class TransitionView : public SampleView {
enum {
// kDurationMS = 500
kDurationMS = 1
};
public:
TransitionView(SkView* prev, SkView* next, int direction) : fInterp(4, 2){
fAnimationDirection = (Direction)(1 << (direction % 8));
fPrev = prev;
fPrev->setClipToBounds(false);
fPrev->setVisibleP(true);
(void)SampleView::SetUsePipe(fPrev, SkOSMenu::kOffState);
//Not calling unref because fPrev is assumed to have been created, so
//this will result in a transfer of ownership
this->attachChildToBack(fPrev);
fNext = next;
fNext->setClipToBounds(true);
fNext->setVisibleP(true);
(void)SampleView::SetUsePipe(fNext, SkOSMenu::kOffState);
//Calling unref because next is a newly created view and TransitionView
//is now the sole owner of fNext
this->attachChildToFront(fNext)->unref();
fDone = false;
//SkDebugf("--created transition\n");
}
~TransitionView(){
//SkDebugf("--deleted transition\n");
}
virtual void requestMenu(SkOSMenu* menu) {
if (SampleView::IsSampleView(fNext))
((SampleView*)fNext)->requestMenu(menu);
}
protected:
virtual bool onQuery(SkEvent* evt) {
if (SampleCode::TitleQ(*evt)) {
SkString title;
if (SampleCode::RequestTitle(fNext, &title)) {
SampleCode::TitleR(evt, title.c_str());
return true;
}
return false;
}
if (evt->isType(gIsTransitionQuery)) {
return true;
}
return this->INHERITED::onQuery(evt);
}
virtual bool onEvent(const SkEvent& evt) {
if (evt.isType(gReplaceTransitionEvt)) {
fPrev->detachFromParent();
fPrev = (SkView*)SkEventSink::FindSink(evt.getFast32());
(void)SampleView::SetUsePipe(fPrev, SkOSMenu::kOffState);
//attach the new fPrev and call unref to balance the ref in onDraw
this->attachChildToBack(fPrev)->unref();
this->inval(NULL);
return true;
}
if (evt.isType("transition-done")) {
fNext->setLoc(0, 0);
fNext->setClipToBounds(false);
SkEvent* evt = new SkEvent(gReplaceTransitionEvt,
this->getParent()->getSinkID());
evt->setFast32(fNext->getSinkID());
//increate ref count of fNext so it survives detachAllChildren
fNext->ref();
this->detachAllChildren();
evt->post();
return true;
}
return this->INHERITED::onEvent(evt);
}
virtual void onDrawBackground(SkCanvas* canvas) {}
virtual void onDrawContent(SkCanvas* canvas) {
if (fDone)
return;
if (is_overview(fNext) || is_overview(fPrev)) {
fPipeState = SkOSMenu::kOffState;
}
SkScalar values[4];
SkInterpolator::Result result = fInterp.timeToValues(SkTime::GetMSecs(), values);
//SkDebugf("transition %x %d pipe:%d\n", this, result, fUsePipe);
//SkDebugf("%f %f %f %f %d\n", values[0], values[1], values[2], values[3], result);
if (SkInterpolator::kNormal_Result == result) {
fPrev->setLocX(values[kPrevX]);
fPrev->setLocY(values[kPrevY]);
fNext->setLocX(values[kNextX]);
fNext->setLocY(values[kNextY]);
this->inval(NULL);
}
else {
(new SkEvent("transition-done", this->getSinkID()))->post();
fDone = true;
}
}
virtual void onSizeChange() {
this->INHERITED::onSizeChange();
fNext->setSize(this->width(), this->height());
fPrev->setSize(this->width(), this->height());
SkScalar lr = 0, ud = 0;
if (fAnimationDirection & (kLeftDirection|kULDirection|kDLDirection))
lr = this->width();
if (fAnimationDirection & (kRightDirection|kURDirection|kDRDirection))
lr = -this->width();
if (fAnimationDirection & (kUpDirection|kULDirection|kURDirection))
ud = this->height();
if (fAnimationDirection & (kDownDirection|kDLDirection|kDRDirection))
ud = -this->height();
fBegin[kPrevX] = fBegin[kPrevY] = 0;
fBegin[kNextX] = lr;
fBegin[kNextY] = ud;
fNext->setLocX(lr);
fNext->setLocY(ud);
if (is_transition(fPrev))
lr = ud = 0;
fEnd[kPrevX] = -lr;
fEnd[kPrevY] = -ud;
fEnd[kNextX] = fEnd[kNextY] = 0;
SkScalar blend[] = { SkFloatToScalar(0.8f), SkFloatToScalar(0.0f),
SkFloatToScalar(0.0f), SK_Scalar1 };
fInterp.setKeyFrame(0, SkTime::GetMSecs(), fBegin, blend);
fInterp.setKeyFrame(1, SkTime::GetMSecs()+kDurationMS, fEnd, blend);
}
private:
enum {
kPrevX = 0,
kPrevY = 1,
kNextX = 2,
kNextY = 3
};
SkView* fPrev;
SkView* fNext;
bool fDone;
SkInterpolator fInterp;
enum Direction{
kUpDirection = 1,
kURDirection = 1 << 1,
kRightDirection = 1 << 2,
kDRDirection = 1 << 3,
kDownDirection = 1 << 4,
kDLDirection = 1 << 5,
kLeftDirection = 1 << 6,
kULDirection = 1 << 7
};
Direction fAnimationDirection;
SkScalar fBegin[4];
SkScalar fEnd[4];
typedef SampleView INHERITED;
};
SkView* create_transition(SkView* prev, SkView* next, int direction) {
#ifdef SK_BUILD_FOR_ANDROID
// Disable transitions for Android
return next;
#else
return SkNEW_ARGS(TransitionView, (prev, next, direction));
#endif
}
<|endoftext|> |
<commit_before>#include <gmock/gmock.h>
#include <gtest/gtest.h>
#include <thread>
#include "../src/reactor/reactor.h"
using namespace testing;
class pair_socket_wrapper : public socket_wrapper_base
{
public:
pair_socket_wrapper(const std::shared_ptr<zmq::context_t> context, const std::string &addr)
: socket_wrapper_base(context, zmq::socket_type::pair, addr, false),
local_socket_(*context, zmq::socket_type::pair), context_(context)
{
local_socket_.setsockopt(ZMQ_LINGER, 0);
local_socket_.bind(addr_);
socket_.close();
}
void initialize() override
{
// called by the reactor
socket_ = zmq::socket_t(*context_, zmq::socket_type::pair);
socket_.setsockopt(ZMQ_LINGER, 0);
socket_.connect(addr_);
}
bool send_message(const message_container &message) override
{
return socket_send(socket_, message);
}
bool receive_message(message_container &message) override
{
return socket_receive(socket_, message);
}
bool send_message_local(const message_container &message)
{
return socket_send(local_socket_, message);
}
bool receive_message_local(message_container &message)
{
return socket_receive(local_socket_, message, true);
}
private:
zmq::socket_t local_socket_;
std::shared_ptr<zmq::context_t> context_;
bool socket_send(zmq::socket_t &socket, const message_container &message)
{
bool retval;
zmq::message_t zmessage(message.identity.c_str(), message.identity.size());
retval = socket.send(zmessage, ZMQ_SNDMORE);
if (!retval) {
return false;
}
for (auto it = std::begin(message.data); it != std::end(message.data); ++it) {
zmessage.rebuild(it->c_str(), it->size());
retval = socket.send(zmessage, std::next(it) != std::end(message.data) ? ZMQ_SNDMORE : 0);
if (!retval) {
return false;
}
}
return true;
}
bool socket_receive(zmq::socket_t &socket, message_container &message, bool noblock = false)
{
zmq::message_t received_message;
bool retval;
retval = socket.recv(&received_message, noblock ? ZMQ_NOBLOCK : 0);
if (!retval) {
return false;
}
message.identity = std::string((char *) received_message.data(), received_message.size());
while (received_message.more()) {
retval = socket.recv(&received_message);
if (!retval) {
return false;
}
message.data.emplace_back((char *) received_message.data(), received_message.size());
}
return true;
}
};
/**
* A handler driven by a function passed on creation
*/
class pluggable_handler : public handler_interface
{
public:
using fnc_t = std::function<void(const message_container &, const response_cb &)>;
std::vector<message_container> received;
pluggable_handler(fnc_t fnc) : fnc_(fnc)
{
}
static std::shared_ptr<pluggable_handler> create(fnc_t fnc)
{
return std::make_shared<pluggable_handler>(fnc);
}
void on_request(const message_container &message, const response_cb &response) override
{
received.push_back(message);
fnc_(message, response);
}
private:
fnc_t fnc_;
};
// Check if the reactor terminates when requested - if this test fails, the other ones will fail too
TEST(reactor, termination)
{
auto context = std::make_shared<zmq::context_t>(1);
reactor r(context);
auto socket = std::make_shared<pair_socket_wrapper>(context, "inproc://termination_1");
r.add_socket("socket", socket);
std::thread thread([&r]() { r.start_loop(); });
std::this_thread::sleep_for(std::chrono::milliseconds(10));
r.terminate();
thread.join();
}
TEST(reactor, synchronous_handler)
{
auto context = std::make_shared<zmq::context_t>(1);
reactor r(context);
auto socket = std::make_shared<pair_socket_wrapper>(context, "inproc://synchronous_handler_1");
auto handler = pluggable_handler::create([](const message_container &msg, handler_interface::response_cb respond) {
respond(message_container("socket", "id1", {"Hello!"}));
});
r.add_socket("socket", socket);
r.add_handler({"socket"}, handler);
std::thread thread([&r]() { r.start_loop(); });
socket->send_message_local(message_container("", "id1", {"Hello??"}));
std::this_thread::sleep_for(std::chrono::milliseconds(10));
EXPECT_THAT(handler->received, ElementsAre(message_container("socket", "id1", {"Hello??"})));
message_container message;
socket->receive_message_local(message);
EXPECT_EQ("id1", message.identity);
EXPECT_THAT(message.data, ElementsAre("Hello!"));
r.terminate();
thread.join();
}
TEST(reactor, asynchronous_handler)
{
auto context = std::make_shared<zmq::context_t>(1);
reactor r(context);
auto socket = std::make_shared<pair_socket_wrapper>(context, "inproc://asynchronous_handler_1");
auto handler = pluggable_handler::create([](const message_container &msg, handler_interface::response_cb respond) {
respond(message_container("socket", "id1", {"Hello!"}));
});
r.add_socket("socket", socket);
r.add_async_handler({"socket"}, handler);
std::thread thread([&r]() { r.start_loop(); });
socket->send_message_local(message_container("", "id1", {"Hello??"}));
std::this_thread::sleep_for(std::chrono::milliseconds(10));
EXPECT_THAT(handler->received, ElementsAre(message_container("socket", "id1", {"Hello??"})));
message_container message;
socket->receive_message_local(message);
EXPECT_EQ("id1", message.identity);
EXPECT_THAT(message.data, ElementsAre("Hello!"));
r.terminate();
thread.join();
}
TEST(reactor, timers)
{
auto context = std::make_shared<zmq::context_t>(1);
reactor r(context);
auto handler =
pluggable_handler::create([](const message_container &msg, handler_interface::response_cb respond) {});
r.add_async_handler({r.KEY_TIMER}, handler);
std::thread thread([&r]() { r.start_loop(); });
std::this_thread::sleep_for(std::chrono::milliseconds(200));
ASSERT_GE(1u, handler->received.size());
r.terminate();
thread.join();
}
// Make sure that messages to asynchronous handlers don't get mixed up
TEST(reactor, multiple_asynchronous_handlers)
{
auto context = std::make_shared<zmq::context_t>(1);
reactor r(context);
auto socket_1 = std::make_shared<pair_socket_wrapper>(context, "inproc://asynchronous_handler_1");
auto socket_2 = std::make_shared<pair_socket_wrapper>(context, "inproc://asynchronous_handler_2");
auto handler_1 =
pluggable_handler::create([](const message_container &msg, handler_interface::response_cb respond) {});
auto handler_2a =
pluggable_handler::create([](const message_container &msg, handler_interface::response_cb respond) {});
auto handler_2b =
pluggable_handler::create([](const message_container &msg, handler_interface::response_cb respond) {});
std::size_t message_count = 100;
r.add_socket("socket_1", socket_1);
r.add_socket("socket_2", socket_2);
r.add_async_handler({"socket_1"}, handler_1);
r.add_async_handler({"socket_2"}, handler_2a);
r.add_async_handler({"socket_2"}, handler_2b);
std::thread thread([&r]() { r.start_loop(); });
for (std::size_t i = 0; i < message_count; i++) {
socket_1->send_message_local(message_container("", "id1", {"socket_1"}));
socket_2->send_message_local(message_container("", "id1", {"socket_2"}));
}
std::this_thread::sleep_for(std::chrono::milliseconds(30));
ASSERT_EQ(message_count, handler_1->received.size());
ASSERT_EQ(message_count, handler_2a->received.size());
ASSERT_EQ(message_count, handler_2b->received.size());
for (std::size_t i = 0; i < message_count; i++) {
EXPECT_EQ(handler_1->received.at(i), message_container("socket_1", "id1", {"socket_1"}));
EXPECT_EQ(handler_2a->received.at(i), message_container("socket_2", "id1", {"socket_2"}));
EXPECT_EQ(handler_2b->received.at(i), message_container("socket_2", "id1", {"socket_2"}));
}
r.terminate();
thread.join();
}
<commit_msg>Longer sleep in async test<commit_after>#include <gmock/gmock.h>
#include <gtest/gtest.h>
#include <thread>
#include "../src/reactor/reactor.h"
using namespace testing;
class pair_socket_wrapper : public socket_wrapper_base
{
public:
pair_socket_wrapper(const std::shared_ptr<zmq::context_t> context, const std::string &addr)
: socket_wrapper_base(context, zmq::socket_type::pair, addr, false),
local_socket_(*context, zmq::socket_type::pair), context_(context)
{
local_socket_.setsockopt(ZMQ_LINGER, 0);
local_socket_.bind(addr_);
socket_.close();
}
void initialize() override
{
// called by the reactor
socket_ = zmq::socket_t(*context_, zmq::socket_type::pair);
socket_.setsockopt(ZMQ_LINGER, 0);
socket_.connect(addr_);
}
bool send_message(const message_container &message) override
{
return socket_send(socket_, message);
}
bool receive_message(message_container &message) override
{
return socket_receive(socket_, message);
}
bool send_message_local(const message_container &message)
{
return socket_send(local_socket_, message);
}
bool receive_message_local(message_container &message)
{
return socket_receive(local_socket_, message, true);
}
private:
zmq::socket_t local_socket_;
std::shared_ptr<zmq::context_t> context_;
bool socket_send(zmq::socket_t &socket, const message_container &message)
{
bool retval;
zmq::message_t zmessage(message.identity.c_str(), message.identity.size());
retval = socket.send(zmessage, ZMQ_SNDMORE);
if (!retval) {
return false;
}
for (auto it = std::begin(message.data); it != std::end(message.data); ++it) {
zmessage.rebuild(it->c_str(), it->size());
retval = socket.send(zmessage, std::next(it) != std::end(message.data) ? ZMQ_SNDMORE : 0);
if (!retval) {
return false;
}
}
return true;
}
bool socket_receive(zmq::socket_t &socket, message_container &message, bool noblock = false)
{
zmq::message_t received_message;
bool retval;
retval = socket.recv(&received_message, noblock ? ZMQ_NOBLOCK : 0);
if (!retval) {
return false;
}
message.identity = std::string((char *) received_message.data(), received_message.size());
while (received_message.more()) {
retval = socket.recv(&received_message);
if (!retval) {
return false;
}
message.data.emplace_back((char *) received_message.data(), received_message.size());
}
return true;
}
};
/**
* A handler driven by a function passed on creation
*/
class pluggable_handler : public handler_interface
{
public:
using fnc_t = std::function<void(const message_container &, const response_cb &)>;
std::vector<message_container> received;
pluggable_handler(fnc_t fnc) : fnc_(fnc)
{
}
static std::shared_ptr<pluggable_handler> create(fnc_t fnc)
{
return std::make_shared<pluggable_handler>(fnc);
}
void on_request(const message_container &message, const response_cb &response) override
{
received.push_back(message);
fnc_(message, response);
}
private:
fnc_t fnc_;
};
// Check if the reactor terminates when requested - if this test fails, the other ones will fail too
TEST(reactor, termination)
{
auto context = std::make_shared<zmq::context_t>(1);
reactor r(context);
auto socket = std::make_shared<pair_socket_wrapper>(context, "inproc://termination_1");
r.add_socket("socket", socket);
std::thread thread([&r]() { r.start_loop(); });
std::this_thread::sleep_for(std::chrono::milliseconds(10));
r.terminate();
thread.join();
}
TEST(reactor, synchronous_handler)
{
auto context = std::make_shared<zmq::context_t>(1);
reactor r(context);
auto socket = std::make_shared<pair_socket_wrapper>(context, "inproc://synchronous_handler_1");
auto handler = pluggable_handler::create([](const message_container &msg, handler_interface::response_cb respond) {
respond(message_container("socket", "id1", {"Hello!"}));
});
r.add_socket("socket", socket);
r.add_handler({"socket"}, handler);
std::thread thread([&r]() { r.start_loop(); });
socket->send_message_local(message_container("", "id1", {"Hello??"}));
std::this_thread::sleep_for(std::chrono::milliseconds(10));
EXPECT_THAT(handler->received, ElementsAre(message_container("socket", "id1", {"Hello??"})));
message_container message;
socket->receive_message_local(message);
EXPECT_EQ("id1", message.identity);
EXPECT_THAT(message.data, ElementsAre("Hello!"));
r.terminate();
thread.join();
}
TEST(reactor, asynchronous_handler)
{
auto context = std::make_shared<zmq::context_t>(1);
reactor r(context);
auto socket = std::make_shared<pair_socket_wrapper>(context, "inproc://asynchronous_handler_1");
auto handler = pluggable_handler::create([](const message_container &msg, handler_interface::response_cb respond) {
respond(message_container("socket", "id1", {"Hello!"}));
});
r.add_socket("socket", socket);
r.add_async_handler({"socket"}, handler);
std::thread thread([&r]() { r.start_loop(); });
socket->send_message_local(message_container("", "id1", {"Hello??"}));
std::this_thread::sleep_for(std::chrono::milliseconds(100));
EXPECT_THAT(handler->received, ElementsAre(message_container("socket", "id1", {"Hello??"})));
message_container message;
socket->receive_message_local(message);
EXPECT_EQ("id1", message.identity);
EXPECT_THAT(message.data, ElementsAre("Hello!"));
r.terminate();
thread.join();
}
TEST(reactor, timers)
{
auto context = std::make_shared<zmq::context_t>(1);
reactor r(context);
auto handler =
pluggable_handler::create([](const message_container &msg, handler_interface::response_cb respond) {});
r.add_async_handler({r.KEY_TIMER}, handler);
std::thread thread([&r]() { r.start_loop(); });
std::this_thread::sleep_for(std::chrono::milliseconds(200));
ASSERT_GE(1u, handler->received.size());
r.terminate();
thread.join();
}
// Make sure that messages to asynchronous handlers don't get mixed up
TEST(reactor, multiple_asynchronous_handlers)
{
auto context = std::make_shared<zmq::context_t>(1);
reactor r(context);
auto socket_1 = std::make_shared<pair_socket_wrapper>(context, "inproc://asynchronous_handler_1");
auto socket_2 = std::make_shared<pair_socket_wrapper>(context, "inproc://asynchronous_handler_2");
auto handler_1 =
pluggable_handler::create([](const message_container &msg, handler_interface::response_cb respond) {});
auto handler_2a =
pluggable_handler::create([](const message_container &msg, handler_interface::response_cb respond) {});
auto handler_2b =
pluggable_handler::create([](const message_container &msg, handler_interface::response_cb respond) {});
std::size_t message_count = 100;
r.add_socket("socket_1", socket_1);
r.add_socket("socket_2", socket_2);
r.add_async_handler({"socket_1"}, handler_1);
r.add_async_handler({"socket_2"}, handler_2a);
r.add_async_handler({"socket_2"}, handler_2b);
std::thread thread([&r]() { r.start_loop(); });
for (std::size_t i = 0; i < message_count; i++) {
socket_1->send_message_local(message_container("", "id1", {"socket_1"}));
socket_2->send_message_local(message_container("", "id1", {"socket_2"}));
}
std::this_thread::sleep_for(std::chrono::milliseconds(30));
ASSERT_EQ(message_count, handler_1->received.size());
ASSERT_EQ(message_count, handler_2a->received.size());
ASSERT_EQ(message_count, handler_2b->received.size());
for (std::size_t i = 0; i < message_count; i++) {
EXPECT_EQ(handler_1->received.at(i), message_container("socket_1", "id1", {"socket_1"}));
EXPECT_EQ(handler_2a->received.at(i), message_container("socket_2", "id1", {"socket_2"}));
EXPECT_EQ(handler_2b->received.at(i), message_container("socket_2", "id1", {"socket_2"}));
}
r.terminate();
thread.join();
}
<|endoftext|> |
<commit_before>#include "stdafx.h"
#include "include/script.h"
#include "include/exceptions.h"
#include "include/debug.h"
#include "include/file.h"
namespace yappy {
namespace lua {
LuaError::LuaError(const std::string &msg, lua_State *L) :
runtime_error("")
{
const char *str = lua_tostring(L, -1);
if (str == nullptr) {
m_what = msg;
}
else {
m_what = msg + ": " + str;
}
lua_pop(L, 1);
}
namespace {
// Error happens outside protected env
// This is fatal and exit application
int atpanic(lua_State *L)
{
throw std::runtime_error("Lua panic");
// Don't return
}
///////////////////////////////////////////////////////////////////////////////
// Copied from linit.c
///////////////////////////////////////////////////////////////////////////////
const luaL_Reg loadedlibs[] = {
{ "_G", luaopen_base },
// { LUA_LOADLIBNAME, luaopen_package },
{ LUA_COLIBNAME, luaopen_coroutine },
{ LUA_TABLIBNAME, luaopen_table },
// { LUA_IOLIBNAME, luaopen_io },
// { LUA_OSLIBNAME, luaopen_os },
{ LUA_STRLIBNAME, luaopen_string },
{ LUA_MATHLIBNAME, luaopen_math },
{ LUA_UTF8LIBNAME, luaopen_utf8 },
// { LUA_DBLIBNAME, luaopen_debug },
{ NULL, NULL }
};
LUALIB_API void my_luaL_openlibs(lua_State *L) {
const luaL_Reg *lib;
/* "require" functions from 'loadedlibs' and set results to global table */
for (lib = loadedlibs; lib->func; lib++) {
luaL_requiref(L, lib->name, lib->func, 1);
lua_pop(L, 1); /* remove lib */
}
}
///////////////////////////////////////////////////////////////////////////////
// Copied from linit.c END
///////////////////////////////////////////////////////////////////////////////
} // namespace
void Lua::LuaDeleter::operator()(lua_State *lua)
{
::lua_close(lua);
}
void *Lua::luaAlloc(void *ud, void *ptr, size_t osize, size_t nsize)
{
auto *lua = reinterpret_cast<Lua *>(ud);
if (nsize == 0) {
// free(ptr);
//debug::writef(L"luaAlloc(free) %p, %08zx, %08zx", ptr, osize, nsize);
if (ptr != nullptr) {
BOOL ret = ::HeapFree(lua->m_heap.get(), 0, ptr);
if (!ret) {
debug::writeLine(L"[warning] HeapFree() failed");
}
}
return nullptr;
}
else {
// realloc(ptr, nsize);
if (nsize >= 0x7FFF8) {
debug::writef(L"[warning] Attempt to allocate %zu bytes", nsize);
}
if (ptr == nullptr) {
//debug::writef(L"luaAlloc(alloc) %p, %08zx, %08zx", ptr, osize, nsize);
return ::HeapAlloc(lua->m_heap.get(), 0, nsize);
}
else {
//debug::writef(L"luaAlloc(realloc) %p, %08zx, %08zx", ptr, osize, nsize);
return ::HeapReAlloc(lua->m_heap.get(), 0, ptr, nsize);
}
}
}
Lua::Lua(bool debugEnable, size_t maxHeapSize, size_t initHeapSize,
int instLimit) :
m_debugEnable(debugEnable)
{
debug::writeLine("Initializing lua...");
HANDLE tmpHeap = ::HeapCreate(HeapOption, initHeapSize, maxHeapSize);
error::checkWin32Result(tmpHeap != nullptr, "HeapCreate() failed");
m_heap.reset(tmpHeap);
lua_State *tmpLua = lua_newstate(luaAlloc, this);
if (tmpLua == nullptr) {
throw std::bad_alloc();
}
m_lua.reset(tmpLua);
m_dbg = std::make_unique<debugger::LuaDebugger>(m_lua.get(), debugEnable, instLimit);
debug::writeLine("Initializing lua OK");
::lua_atpanic(m_lua.get(), atpanic);
my_luaL_openlibs(m_lua.get());
// delete load function
lua_State *L = m_lua.get();
lua_pushnil(L);
lua_setglobal(L, "dofile");
lua_pushnil(L);
lua_setglobal(L, "loadfile");
lua_pushnil(L);
lua_setglobal(L, "load");
}
lua_State *Lua::getLuaState() const
{
return m_lua.get();
}
Lua::~Lua()
{
debug::writeLine("Finalize lua");
}
void Lua::loadTraceLib()
{
lua_State *L = m_lua.get();
luaL_newlib(L, export::trace_RegList);
lua_setglobal(L, "trace");
}
void Lua::loadSysLib()
{
lua_State *L = m_lua.get();
luaL_newlibtable(L, export::trace_RegList);
// upvalue[1]: Lua *this
lua_pushlightuserdata(L, this);
luaL_setfuncs(L, export::sys_RegList, 1);
lua_setglobal(L, "sys");
}
void Lua::loadResourceLib(framework::Application *app)
{
lua_State *L = m_lua.get();
luaL_newlib(L, export::resource_RegList);
lua_pushstring(L, export::resource_RawFieldName);
lua_pushlightuserdata(L, app);
lua_settable(L, -3);
lua_setglobal(L, "resource");
}
void Lua::loadGraphLib(framework::Application *app)
{
lua_State *L = m_lua.get();
luaL_newlib(L, export::graph_RegList);
lua_pushstring(L, export::graph_RawFieldName);
lua_pushlightuserdata(L, app);
lua_settable(L, -3);
lua_setglobal(L, "graph");
}
void Lua::loadSoundLib(framework::Application *app)
{
lua_State *L = m_lua.get();
luaL_newlib(L, export::sound_RegList);
lua_pushstring(L, export::sound_RawFieldName);
lua_pushlightuserdata(L, app);
lua_settable(L, -3);
lua_setglobal(L, "sound");
}
void Lua::loadFile(const wchar_t *fileName, bool autoBreak, bool prot)
{
lua_State *L = m_lua.get();
file::Bytes buf = file::loadFile(fileName);
// push chunk function
std::string chunkName("@");
chunkName += util::wc2utf8(fileName).get();
int ret = ::luaL_loadbufferx(L,
reinterpret_cast<const char *>(buf.data()), buf.size(),
chunkName.c_str(), "t");
if (ret != LUA_OK) {
throw LuaError("Load script failed", L);
}
// prepare debug info
m_dbg->loadDebugInfo(chunkName.c_str(),
reinterpret_cast<const char *>(buf.data()), buf.size());
// call it
if (prot) {
pcallInternal(0, 0, autoBreak);
}
else {
lua_call(L, 0, 0);
}
}
void Lua::pcallInternal(int narg, int nret, bool autoBreak)
{
m_dbg->pcall(narg, nret, autoBreak);
}
std::vector<std::string> luaValueToStrList(lua_State *L, int ind, int maxDepth, int depth)
{
std::vector<std::string> result;
int tind = lua_absindex(L, ind);
int type = lua_type(L, ind);
if (type == LUA_TNONE) {
throw std::logic_error("invalid index: " + std::to_string(ind));
}
const char *typestr = lua_typename(L, type);
// copy and tostring it
lua_pushvalue(L, ind);
const char *valstr = lua_tostring(L, -1);
valstr = (valstr == NULL) ? "" : valstr;
// pop copy
lua_pop(L, 1);
// boolean cannot be tostring
if (type == LUA_TBOOLEAN) {
valstr = lua_toboolean(L, ind) ? "true" : "false";
}
{
std::string str;
for (int i = 0; i < depth; i++) {
str += " ";
}
str += "(";
str += typestr;
str += ") ";
str += valstr;
result.emplace_back(std::move(str));
}
if (type == LUA_TTABLE && depth < maxDepth) {
lua_pushnil(L);
while (lua_next(L, tind) != 0) {
// key:-2, value:-1
auto key = luaValueToStrList(L, -2, maxDepth, depth + 1);
auto val = luaValueToStrList(L, -1, maxDepth, depth + 1);
result.insert(result.end(), key.begin(), key.end());
result.insert(result.end(), val.begin(), val.end());
// pop value, keep key
lua_pop(L, 1);
}
}
return result;
}
}
}
<commit_msg>Set upvalue (execution failed yet)<commit_after>#include "stdafx.h"
#include "include/script.h"
#include "include/exceptions.h"
#include "include/debug.h"
#include "include/file.h"
namespace yappy {
namespace lua {
LuaError::LuaError(const std::string &msg, lua_State *L) :
runtime_error("")
{
const char *str = lua_tostring(L, -1);
if (str == nullptr) {
m_what = msg;
}
else {
m_what = msg + ": " + str;
}
lua_pop(L, 1);
}
namespace {
// Error happens outside protected env
// This is fatal and exit application
int atpanic(lua_State *L)
{
throw std::runtime_error("Lua panic");
// Don't return
}
///////////////////////////////////////////////////////////////////////////////
// Copied from linit.c
///////////////////////////////////////////////////////////////////////////////
const luaL_Reg loadedlibs[] = {
{ "_G", luaopen_base },
// { LUA_LOADLIBNAME, luaopen_package },
{ LUA_COLIBNAME, luaopen_coroutine },
{ LUA_TABLIBNAME, luaopen_table },
// { LUA_IOLIBNAME, luaopen_io },
// { LUA_OSLIBNAME, luaopen_os },
{ LUA_STRLIBNAME, luaopen_string },
{ LUA_MATHLIBNAME, luaopen_math },
{ LUA_UTF8LIBNAME, luaopen_utf8 },
// { LUA_DBLIBNAME, luaopen_debug },
{ NULL, NULL }
};
LUALIB_API void my_luaL_openlibs(lua_State *L) {
const luaL_Reg *lib;
/* "require" functions from 'loadedlibs' and set results to global table */
for (lib = loadedlibs; lib->func; lib++) {
luaL_requiref(L, lib->name, lib->func, 1);
lua_pop(L, 1); /* remove lib */
}
}
///////////////////////////////////////////////////////////////////////////////
// Copied from linit.c END
///////////////////////////////////////////////////////////////////////////////
} // namespace
void Lua::LuaDeleter::operator()(lua_State *lua)
{
::lua_close(lua);
}
void *Lua::luaAlloc(void *ud, void *ptr, size_t osize, size_t nsize)
{
auto *lua = reinterpret_cast<Lua *>(ud);
if (nsize == 0) {
// free(ptr);
//debug::writef(L"luaAlloc(free) %p, %08zx, %08zx", ptr, osize, nsize);
if (ptr != nullptr) {
BOOL ret = ::HeapFree(lua->m_heap.get(), 0, ptr);
if (!ret) {
debug::writeLine(L"[warning] HeapFree() failed");
}
}
return nullptr;
}
else {
// realloc(ptr, nsize);
if (nsize >= 0x7FFF8) {
debug::writef(L"[warning] Attempt to allocate %zu bytes", nsize);
}
if (ptr == nullptr) {
//debug::writef(L"luaAlloc(alloc) %p, %08zx, %08zx", ptr, osize, nsize);
return ::HeapAlloc(lua->m_heap.get(), 0, nsize);
}
else {
//debug::writef(L"luaAlloc(realloc) %p, %08zx, %08zx", ptr, osize, nsize);
return ::HeapReAlloc(lua->m_heap.get(), 0, ptr, nsize);
}
}
}
Lua::Lua(bool debugEnable, size_t maxHeapSize, size_t initHeapSize,
int instLimit) :
m_debugEnable(debugEnable)
{
debug::writeLine("Initializing lua...");
HANDLE tmpHeap = ::HeapCreate(HeapOption, initHeapSize, maxHeapSize);
error::checkWin32Result(tmpHeap != nullptr, "HeapCreate() failed");
m_heap.reset(tmpHeap);
lua_State *tmpLua = lua_newstate(luaAlloc, this);
if (tmpLua == nullptr) {
throw std::bad_alloc();
}
m_lua.reset(tmpLua);
m_dbg = std::make_unique<debugger::LuaDebugger>(m_lua.get(), debugEnable, instLimit);
debug::writeLine("Initializing lua OK");
::lua_atpanic(m_lua.get(), atpanic);
my_luaL_openlibs(m_lua.get());
// delete load function
lua_State *L = m_lua.get();
lua_pushnil(L);
lua_setglobal(L, "dofile");
lua_pushnil(L);
lua_setglobal(L, "loadfile");
lua_pushnil(L);
lua_setglobal(L, "load");
}
lua_State *Lua::getLuaState() const
{
return m_lua.get();
}
Lua::~Lua()
{
debug::writeLine("Finalize lua");
}
void Lua::loadTraceLib()
{
lua_State *L = m_lua.get();
luaL_newlib(L, export::trace_RegList);
lua_setglobal(L, "trace");
}
void Lua::loadSysLib()
{
lua_State *L = m_lua.get();
luaL_newlibtable(L, export::trace_RegList);
// upvalue[1]: Lua *
lua_pushlightuserdata(L, this);
luaL_setfuncs(L, export::sys_RegList, 1);
lua_setglobal(L, "sys");
}
void Lua::loadResourceLib(framework::Application *app)
{
lua_State *L = m_lua.get();
luaL_newlibtable(L, export::resource_RegList);
// upvalue[1]: Application *
lua_pushlightuserdata(L, app);
luaL_setfuncs(L, export::resource_RegList, 1);
lua_setglobal(L, "resource");
}
void Lua::loadGraphLib(framework::Application *app)
{
lua_State *L = m_lua.get();
luaL_newlibtable(L, export::graph_RegList);
// upvalue[1]: Application *
lua_pushlightuserdata(L, app);
luaL_setfuncs(L, export::graph_RegList, 1);
lua_setglobal(L, "graph");
}
void Lua::loadSoundLib(framework::Application *app)
{
lua_State *L = m_lua.get();
luaL_newlibtable(L, export::sound_RegList);
// upvalue[1]: Application *
lua_pushlightuserdata(L, app);
luaL_setfuncs(L, export::sound_RegList, 1);
lua_setglobal(L, "sound");
}
void Lua::loadFile(const wchar_t *fileName, bool autoBreak, bool prot)
{
lua_State *L = m_lua.get();
file::Bytes buf = file::loadFile(fileName);
// push chunk function
std::string chunkName("@");
chunkName += util::wc2utf8(fileName).get();
int ret = ::luaL_loadbufferx(L,
reinterpret_cast<const char *>(buf.data()), buf.size(),
chunkName.c_str(), "t");
if (ret != LUA_OK) {
throw LuaError("Load script failed", L);
}
// prepare debug info
m_dbg->loadDebugInfo(chunkName.c_str(),
reinterpret_cast<const char *>(buf.data()), buf.size());
// call it
if (prot) {
pcallInternal(0, 0, autoBreak);
}
else {
lua_call(L, 0, 0);
}
}
void Lua::pcallInternal(int narg, int nret, bool autoBreak)
{
m_dbg->pcall(narg, nret, autoBreak);
}
std::vector<std::string> luaValueToStrList(lua_State *L, int ind, int maxDepth, int depth)
{
std::vector<std::string> result;
int tind = lua_absindex(L, ind);
int type = lua_type(L, ind);
if (type == LUA_TNONE) {
throw std::logic_error("invalid index: " + std::to_string(ind));
}
const char *typestr = lua_typename(L, type);
// copy and tostring it
lua_pushvalue(L, ind);
const char *valstr = lua_tostring(L, -1);
valstr = (valstr == NULL) ? "" : valstr;
// pop copy
lua_pop(L, 1);
// boolean cannot be tostring
if (type == LUA_TBOOLEAN) {
valstr = lua_toboolean(L, ind) ? "true" : "false";
}
{
std::string str;
for (int i = 0; i < depth; i++) {
str += " ";
}
str += "(";
str += typestr;
str += ") ";
str += valstr;
result.emplace_back(std::move(str));
}
if (type == LUA_TTABLE && depth < maxDepth) {
lua_pushnil(L);
while (lua_next(L, tind) != 0) {
// key:-2, value:-1
auto key = luaValueToStrList(L, -2, maxDepth, depth + 1);
auto val = luaValueToStrList(L, -1, maxDepth, depth + 1);
result.insert(result.end(), key.begin(), key.end());
result.insert(result.end(), val.begin(), val.end());
// pop value, keep key
lua_pop(L, 1);
}
}
return result;
}
}
}
<|endoftext|> |
<commit_before>// The MIT License (MIT)
// Copyright (c) 2013 lailongwei<lailongwei@126.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 "llbc/common/Export.h"
#include "llbc/common/BeforeIncl.h"
#include "llbc/comm/Session.h"
#include "llbc/comm/protocol/ProtocolLayer.h"
#include "llbc/comm/protocol/ProtoReportLevel.h"
#include "llbc/comm/protocol/PacketProtocol.h"
#include "llbc/comm/protocol/ProtocolStack.h"
#include "llbc/comm/IService.h"
namespace
{
typedef LLBC_NS LLBC_ProtocolLayer _Layer;
}
__LLBC_INTERNAL_NS_BEGIN
static const size_t __llbc_headerLen = 20;
void inline __DelBlock(void *data)
{
LLBC_Delete(reinterpret_cast<LLBC_NS LLBC_MessageBlock *>(data));
}
void inline __DelPacketList(void *&data)
{
if (!data)
return;
LLBC_NS LLBC_MessageBlock *block =
reinterpret_cast<LLBC_NS LLBC_MessageBlock *>(data);
LLBC_NS LLBC_Packet *packet;
while (block->Read(&packet, sizeof(LLBC_NS LLBC_Packet *)) == LLBC_OK)
LLBC_Delete(packet);
LLBC_Delete(block);
data = NULL;
}
__LLBC_INTERNAL_NS_END
__LLBC_NS_BEGIN
LLBC_PacketProtocol::LLBC_PacketProtocol()
: _headerAssembler(LLBC_INL_NS __llbc_headerLen)
, _packet(NULL)
, _payloadNeedRecv(0)
, _payloadRecved(0)
{
}
LLBC_PacketProtocol::~LLBC_PacketProtocol()
{
LLBC_XDelete(_packet);
}
int LLBC_PacketProtocol::GetLayer() const
{
return _Layer::PackLayer;
}
int LLBC_PacketProtocol::Connect(LLBC_SockAddr_IN &local, LLBC_SockAddr_IN &peer)
{
return LLBC_OK;
}
int LLBC_PacketProtocol::Send(void *in, void *&out, bool &removeSession)
{
LLBC_Packet *packet = reinterpret_cast<LLBC_Packet *>(in);
uint32 length = static_cast<uint32>(
LLBC_INL_NS __llbc_headerLen + packet->GetPayloadLength());
// Create block and write header in.
LLBC_MessageBlock *block = LLBC_New1(LLBC_MessageBlock, length);
sint32 opcode = packet->GetOpcode();
uint16 status = static_cast<uint16>(packet->GetStatus());
int senderServiceId = packet->GetSenderServiceId();
int recverServiceId = packet->GetRecverServiceId();
uint16 flags = static_cast<uint16>(packet->GetFlags());
#if LLBC_CFG_COMM_ORDER_IS_NET_ORDER
LLBC_Host2Net(length);
LLBC_Host2Net(opcode);
LLBC_Host2Net(status);
LLBC_Host2Net(senderServiceId);
LLBC_Host2Net(recverServiceId);
LLBC_Host2Net(flags);
#endif // Net order.
block->Write(&length, sizeof(length));
block->Write(&opcode, sizeof(opcode));
block->Write(&status, sizeof(status));
block->Write(&senderServiceId, sizeof(senderServiceId));
block->Write(&recverServiceId, sizeof(recverServiceId));
block->Write(&flags, sizeof(flags));
// Write packet data and delete packet.
block->Write(packet->GetPayload(), packet->GetPayloadLength());
LLBC_Delete(packet);
out = block;
return LLBC_OK;
}
int LLBC_PacketProtocol::Recv(void *in, void *&out, bool &removeSession)
{
out = NULL;
LLBC_MessageBlock *block = reinterpret_cast<LLBC_MessageBlock *>(in);
LLBC_InvokeGuard guard(&LLBC_INL_NS __DelBlock, block);
size_t readableSize;
while ((readableSize = block->GetReadableSize()) > 0)
{
const char *readableBuf = reinterpret_cast<const char *>(block->GetDataStartWithReadPos());
// Construct packet header.
if (!_packet)
{
size_t headerUsed;
if (!_headerAssembler.Assemble(readableBuf, readableSize, headerUsed)) // If header recv not done, return.
return LLBC_OK;
// Create new packet.
_packet = LLBC_New(LLBC_Packet);
_headerAssembler.SetToPacket(*_packet);
_packet->SetSessionId(_sessionId);
// Check length.
const size_t packetLen = _packet->GetLength();
if (packetLen < LLBC_INL_NS __llbc_headerLen)
{
_stack->Report(this,
LLBC_ProtoReportLevel::Error,
LLBC_String().format("invalid packet len: %lu", _packet->GetLength()));
_headerAssembler.Reset();
LLBC_XDelete(_packet);
_payloadNeedRecv = 0;
LLBC_INL_NS __DelPacketList(out);
removeSession = true;
LLBC_SetLastError(LLBC_ERROR_PACK);
return LLBC_FAILED;
}
// Calculate payload need receive bytes.
_payloadNeedRecv = packetLen - LLBC_INL_NS __llbc_headerLen;
// Reset the header assembler.
_headerAssembler.Reset();
if (headerUsed == readableSize) // If readable size equal headerUsed, just return.
return LLBC_OK;
// Offset the readable buffer pointer and modify readable size value.
readableBuf += headerUsed;
readableSize -= headerUsed;
// Shift block read pos.
#if LLBC_TARGET_PLATFORM_WIN32 && defined(_WIN64)
block->ShiftReadPos(static_cast<long>(headerUsed));
#else
block->ShiftReadPos(headerUsed);
#endif // target platform is WIN32 and in x64 module.
}
// Content packet content.
size_t contentNeedRecv = _payloadNeedRecv - _payloadRecved;
if (readableSize < contentNeedRecv) // if the readable data size < content need receive size, copy the data and return.
{
_packet->Write(readableBuf, readableSize);
_payloadRecved += readableSize;
return LLBC_OK;
}
// Readable data size >= content need receive size.
_packet->Write(readableBuf, contentNeedRecv);
if (!out)
out = LLBC_New1(LLBC_MessageBlock, sizeof(LLBC_Packet *));
(reinterpret_cast<LLBC_MessageBlock *>(out))->Write(&_packet, sizeof(LLBC_Packet *));
// Reset packet about data members.
_packet = NULL;
_payloadRecved = 0;
_payloadNeedRecv = 0;
// Shift block read position.
#if LLBC_TARGET_PLATFORM_WIN32 && defined(_WIN64)
block->ShiftReadPos(static_cast<long>(contentNeedRecv));
#else
block->ShiftReadPos(contentNeedRecv);
#endif // target platform is WIN32 and defined _WIN64 macro.
}
return LLBC_OK;
}
__LLBC_NS_END
#include "llbc/common/AfterIncl.h"
<commit_msg>Fix PacketProtocol receive empty packet error.<commit_after>// The MIT License (MIT)
// Copyright (c) 2013 lailongwei<lailongwei@126.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 "llbc/common/Export.h"
#include "llbc/common/BeforeIncl.h"
#include "llbc/comm/Session.h"
#include "llbc/comm/protocol/ProtocolLayer.h"
#include "llbc/comm/protocol/ProtoReportLevel.h"
#include "llbc/comm/protocol/PacketProtocol.h"
#include "llbc/comm/protocol/ProtocolStack.h"
#include "llbc/comm/IService.h"
namespace
{
typedef LLBC_NS LLBC_ProtocolLayer _Layer;
}
__LLBC_INTERNAL_NS_BEGIN
static const size_t __llbc_headerLen = 20;
void inline __DelBlock(void *data)
{
LLBC_Delete(reinterpret_cast<LLBC_NS LLBC_MessageBlock *>(data));
}
void inline __DelPacketList(void *&data)
{
if (!data)
return;
LLBC_NS LLBC_MessageBlock *block =
reinterpret_cast<LLBC_NS LLBC_MessageBlock *>(data);
LLBC_NS LLBC_Packet *packet;
while (block->Read(&packet, sizeof(LLBC_NS LLBC_Packet *)) == LLBC_OK)
LLBC_Delete(packet);
LLBC_Delete(block);
data = NULL;
}
__LLBC_INTERNAL_NS_END
__LLBC_NS_BEGIN
LLBC_PacketProtocol::LLBC_PacketProtocol()
: _headerAssembler(LLBC_INL_NS __llbc_headerLen)
, _packet(NULL)
, _payloadNeedRecv(0)
, _payloadRecved(0)
{
}
LLBC_PacketProtocol::~LLBC_PacketProtocol()
{
LLBC_XDelete(_packet);
}
int LLBC_PacketProtocol::GetLayer() const
{
return _Layer::PackLayer;
}
int LLBC_PacketProtocol::Connect(LLBC_SockAddr_IN &local, LLBC_SockAddr_IN &peer)
{
return LLBC_OK;
}
int LLBC_PacketProtocol::Send(void *in, void *&out, bool &removeSession)
{
LLBC_Packet *packet = reinterpret_cast<LLBC_Packet *>(in);
uint32 length = static_cast<uint32>(
LLBC_INL_NS __llbc_headerLen + packet->GetPayloadLength());
// Create block and write header in.
LLBC_MessageBlock *block = LLBC_New1(LLBC_MessageBlock, length);
sint32 opcode = packet->GetOpcode();
uint16 status = static_cast<uint16>(packet->GetStatus());
int senderServiceId = packet->GetSenderServiceId();
int recverServiceId = packet->GetRecverServiceId();
uint16 flags = static_cast<uint16>(packet->GetFlags());
#if LLBC_CFG_COMM_ORDER_IS_NET_ORDER
LLBC_Host2Net(length);
LLBC_Host2Net(opcode);
LLBC_Host2Net(status);
LLBC_Host2Net(senderServiceId);
LLBC_Host2Net(recverServiceId);
LLBC_Host2Net(flags);
#endif // Net order.
block->Write(&length, sizeof(length));
block->Write(&opcode, sizeof(opcode));
block->Write(&status, sizeof(status));
block->Write(&senderServiceId, sizeof(senderServiceId));
block->Write(&recverServiceId, sizeof(recverServiceId));
block->Write(&flags, sizeof(flags));
// Write packet data and delete packet.
block->Write(packet->GetPayload(), packet->GetPayloadLength());
LLBC_Delete(packet);
out = block;
return LLBC_OK;
}
int LLBC_PacketProtocol::Recv(void *in, void *&out, bool &removeSession)
{
out = NULL;
LLBC_MessageBlock *block = reinterpret_cast<LLBC_MessageBlock *>(in);
LLBC_InvokeGuard guard(&LLBC_INL_NS __DelBlock, block);
size_t readableSize;
while ((readableSize = block->GetReadableSize()) > 0)
{
const char *readableBuf = reinterpret_cast<const char *>(block->GetDataStartWithReadPos());
// Construct packet header.
if (!_packet)
{
size_t headerUsed;
if (!_headerAssembler.Assemble(readableBuf, readableSize, headerUsed)) // If header recv not done, return.
return LLBC_OK;
// Create new packet.
_packet = LLBC_New(LLBC_Packet);
_headerAssembler.SetToPacket(*_packet);
_packet->SetSessionId(_sessionId);
// Check length.
const size_t packetLen = _packet->GetLength();
if (packetLen < LLBC_INL_NS __llbc_headerLen)
{
_stack->Report(this,
LLBC_ProtoReportLevel::Error,
LLBC_String().format("invalid packet len: %lu", _packet->GetLength()));
_headerAssembler.Reset();
LLBC_XDelete(_packet);
_payloadNeedRecv = 0;
LLBC_INL_NS __DelPacketList(out);
removeSession = true;
LLBC_SetLastError(LLBC_ERROR_PACK);
return LLBC_FAILED;
}
// Calculate payload need receive bytes.
_payloadNeedRecv = packetLen - LLBC_INL_NS __llbc_headerLen;
// Reset the header assembler.
_headerAssembler.Reset();
// Offset the readable buffer pointer and modify readable size value.
readableBuf += headerUsed;
readableSize -= headerUsed;
// Shift block read pos.
#if LLBC_TARGET_PLATFORM_WIN32 && defined(_WIN64)
block->ShiftReadPos(static_cast<long>(headerUsed));
#else
block->ShiftReadPos(headerUsed);
#endif // target platform is WIN32 and in x64 module.
}
// Content packet content.
size_t contentNeedRecv = _payloadNeedRecv - _payloadRecved;
if (readableSize < contentNeedRecv) // if the readable data size < content need receive size, copy the data and return.
{
_packet->Write(readableBuf, readableSize);
_payloadRecved += readableSize;
return LLBC_OK;
}
// Readable data size >= content need receive size.
_packet->Write(readableBuf, contentNeedRecv);
if (!out)
out = LLBC_New1(LLBC_MessageBlock, sizeof(LLBC_Packet *));
(reinterpret_cast<LLBC_MessageBlock *>(out))->Write(&_packet, sizeof(LLBC_Packet *));
// Reset packet about data members.
_packet = NULL;
_payloadRecved = 0;
_payloadNeedRecv = 0;
// Shift block read position.
#if LLBC_TARGET_PLATFORM_WIN32 && defined(_WIN64)
block->ShiftReadPos(static_cast<long>(contentNeedRecv));
#else
block->ShiftReadPos(contentNeedRecv);
#endif // target platform is WIN32 and defined _WIN64 macro.
}
return LLBC_OK;
}
__LLBC_NS_END
#include "llbc/common/AfterIncl.h"
<|endoftext|> |
<commit_before>#include <iostream>
#include <myo/myo.hpp>
#include "../src/features/RootFeature.h"
#include "../src/features/filters/Debounce.h"
#include "../src/features/Orientation.h"
#include "../src/features/OrientationPoses.h"
#include "../src/features/filters/ExponentialMovingAverage.h"
#include "../src/features/filters/MovingAverage.h"
#include "../src/features/gestures/PoseGesturesV2.h"
#include "ExampleFeature.h"
int main() {
try {
myo::Hub hub("com.voidingwarranties.myo-intelligesture");
myo::Myo* myo = hub.waitForMyo(10000);
if (!myo) {
throw std::runtime_error("Unable to find a Myo!");
}
features::RootFeature root_feature;
features::filters::Debounce debounce(root_feature);
// This filter averages only orientation data.
features::filters::MovingAverage moving_average(
root_feature, features::filters::MovingAverage::OrientationData, 10);
// This filter averages only accelerometer and gyroscope data.
features::filters::ExponentialMovingAverage exponential_moving_average(
moving_average,
features::filters::ExponentialMovingAverage::AccelerometerData |
features::filters::ExponentialMovingAverage::GyroscopeData,
0.2);
features::Orientation orientation(exponential_moving_average);
features::OrientationPoses orientation_poses(debounce, orientation);
features::gestures::PoseGestures pose_gestures(orientation_poses);
ExampleFeature example_feature(pose_gestures, orientation);
hub.addListener(&root_feature);
// Event loop.
while (true) {
myo->unlock(myo::Myo::unlockTimed);
hub.run(1000 / 20);
root_feature.onPeriodic(myo);
}
} catch (const std::exception& ex) {
std::cerr << "Error: " << ex.what() << std::endl;
return 1;
}
return 0;
}
<commit_msg>Fix typo in include<commit_after>#include <iostream>
#include <myo/myo.hpp>
#include "../src/features/RootFeature.h"
#include "../src/features/filters/Debounce.h"
#include "../src/features/Orientation.h"
#include "../src/features/OrientationPoses.h"
#include "../src/features/filters/ExponentialMovingAverage.h"
#include "../src/features/filters/MovingAverage.h"
#include "../src/features/gestures/PoseGestures.h"
#include "ExampleFeature.h"
int main() {
try {
myo::Hub hub("com.voidingwarranties.myo-intelligesture");
myo::Myo* myo = hub.waitForMyo(10000);
if (!myo) {
throw std::runtime_error("Unable to find a Myo!");
}
features::RootFeature root_feature;
features::filters::Debounce debounce(root_feature);
// This filter averages only orientation data.
features::filters::MovingAverage moving_average(
root_feature, features::filters::MovingAverage::OrientationData, 10);
// This filter averages only accelerometer and gyroscope data.
features::filters::ExponentialMovingAverage exponential_moving_average(
moving_average,
features::filters::ExponentialMovingAverage::AccelerometerData |
features::filters::ExponentialMovingAverage::GyroscopeData,
0.2);
features::Orientation orientation(exponential_moving_average);
features::OrientationPoses orientation_poses(debounce, orientation);
features::gestures::PoseGestures pose_gestures(orientation_poses);
ExampleFeature example_feature(pose_gestures, orientation);
hub.addListener(&root_feature);
// Event loop.
while (true) {
myo->unlock(myo::Myo::unlockTimed);
hub.run(1000 / 20);
root_feature.onPeriodic(myo);
}
} catch (const std::exception& ex) {
std::cerr << "Error: " << ex.what() << std::endl;
return 1;
}
return 0;
}
<|endoftext|> |
<commit_before>/*
* yosys -- Yosys Open SYnthesis Suite
*
* Copyright (C) 2012 Clifford Wolf <clifford@clifford.at>
*
* Permission to use, copy, modify, and/or distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
* ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
* ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
* OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*
*/
#include "kernel/register.h"
#include "kernel/celltypes.h"
#include "kernel/log.h"
#include <stdlib.h>
#include <stdio.h>
#include <set>
struct SubmodWorker
{
CellTypes ct;
RTLIL::Design *design;
RTLIL::Module *module;
std::string opt_name;
struct SubModule
{
std::string name, full_name;
std::set<RTLIL::Cell*> cells;
};
std::map<std::string, SubModule> submodules;
struct wire_flags_t {
RTLIL::Wire *new_wire;
bool is_int_driven, is_int_used, is_ext_driven, is_ext_used;
wire_flags_t() : new_wire(NULL), is_int_driven(false), is_int_used(false), is_ext_driven(false), is_ext_used(false) { }
};
std::map<RTLIL::Wire*, wire_flags_t> wire_flags;
bool flag_found_something;
void flag_wire(RTLIL::Wire *wire, bool create, bool set_int_driven, bool set_int_used, bool set_ext_driven, bool set_ext_used)
{
if (wire_flags.count(wire) == 0) {
if (!create)
return;
wire_flags[wire] = wire_flags_t();
}
if (set_int_driven)
wire_flags[wire].is_int_driven = true;
if (set_int_used)
wire_flags[wire].is_int_used = true;
if (set_ext_driven)
wire_flags[wire].is_ext_driven = true;
if (set_ext_used)
wire_flags[wire].is_ext_used = true;
flag_found_something = true;
}
void flag_signal(RTLIL::SigSpec &sig, bool create, bool set_int_driven, bool set_int_used, bool set_ext_driven, bool set_ext_used)
{
for (auto &c : sig.chunks)
if (c.wire != NULL)
flag_wire(c.wire, create, set_int_driven, set_int_used, set_ext_driven, set_ext_used);
}
void handle_submodule(SubModule &submod)
{
log("Creating submodule %s (%s) of module %s.\n", submod.name.c_str(), submod.full_name.c_str(), module->name.c_str());
wire_flags.clear();
for (RTLIL::Cell *cell : submod.cells) {
if (ct.cell_known(cell->type)) {
for (auto &conn : cell->connections)
flag_signal(conn.second, true, ct.cell_output(cell->type, conn.first), ct.cell_input(cell->type, conn.first), false, false);
} else {
log("WARNING: Port directions for cell %s (%s) are unknown. Assuming inout for all ports.\n", cell->name.c_str(), cell->type.c_str());
for (auto &conn : cell->connections)
flag_signal(conn.second, true, true, true, false, false);
}
}
for (auto &it : module->cells) {
RTLIL::Cell *cell = it.second;
if (submod.cells.count(cell) > 0)
continue;
if (ct.cell_known(cell->type)) {
for (auto &conn : cell->connections)
flag_signal(conn.second, false, false, false, ct.cell_output(cell->type, conn.first), ct.cell_input(cell->type, conn.first));
} else {
flag_found_something = false;
for (auto &conn : cell->connections)
flag_signal(conn.second, false, false, false, true, true);
if (flag_found_something)
log("WARNING: Port directions for cell %s (%s) are unknown. Assuming inout for all ports.\n", cell->name.c_str(), cell->type.c_str());
}
}
RTLIL::Module *new_mod = new RTLIL::Module;
new_mod->name = submod.full_name;
design->modules[new_mod->name] = new_mod;
int port_counter = 1, auto_name_counter = 1;
std::set<std::string> all_wire_names;
for (auto &it : wire_flags) {
all_wire_names.insert(it.first->name);
}
for (auto &it : wire_flags)
{
RTLIL::Wire *wire = it.first;
wire_flags_t &flags = it.second;
if (wire->port_input)
flags.is_ext_driven = true;
if (wire->port_output)
flags.is_ext_used = true;
RTLIL::Wire *new_wire = new RTLIL::Wire;
new_wire->name = wire->name;
new_wire->width = wire->width;
new_wire->start_offset = wire->start_offset;
new_wire->attributes = wire->attributes;
if (flags.is_int_driven && flags.is_ext_used)
new_wire->port_output = true;
if (flags.is_ext_driven && flags.is_int_used)
new_wire->port_input = true;
if (flags.is_int_driven && flags.is_ext_driven)
new_wire->port_input = true, new_wire->port_output = true;
if (new_wire->port_input || new_wire->port_output) {
new_wire->port_id = port_counter++;
while (new_wire->name[0] == '$') {
std::string new_wire_name = stringf("\\n%d", auto_name_counter++);
if (all_wire_names.count(new_wire_name) == 0) {
all_wire_names.insert(new_wire_name);
new_wire->name = new_wire_name;
}
}
}
if (new_wire->port_input && new_wire->port_output)
log(" signal %s: inout %s\n", wire->name.c_str(), new_wire->name.c_str());
else if (new_wire->port_input)
log(" signal %s: input %s\n", wire->name.c_str(), new_wire->name.c_str());
else if (new_wire->port_output)
log(" signal %s: output %s\n", wire->name.c_str(), new_wire->name.c_str());
else
log(" signal %s: internal\n", wire->name.c_str());
new_mod->wires[new_wire->name] = new_wire;
flags.new_wire = new_wire;
}
for (RTLIL::Cell *cell : submod.cells) {
RTLIL::Cell *new_cell = new RTLIL::Cell(*cell);
for (auto &conn : new_cell->connections)
for (auto &c : conn.second.chunks)
if (c.wire != NULL) {
assert(wire_flags.count(c.wire) > 0);
c.wire = wire_flags[c.wire].new_wire;
}
log(" cell %s (%s)\n", new_cell->name.c_str(), new_cell->type.c_str());
new_mod->cells[new_cell->name] = new_cell;
module->cells.erase(cell->name);
delete cell;
}
submod.cells.clear();
RTLIL::Cell *new_cell = new RTLIL::Cell;
new_cell->name = submod.full_name;
new_cell->type = submod.full_name;
for (auto &it : wire_flags)
{
RTLIL::Wire *old_wire = it.first;
RTLIL::Wire *new_wire = it.second.new_wire;
if (new_wire->port_id > 0)
new_cell->connections[new_wire->name] = RTLIL::SigSpec(old_wire);
}
module->cells[new_cell->name] = new_cell;
}
SubmodWorker(RTLIL::Design *design, RTLIL::Module *module, std::string opt_name = std::string()) : design(design), module(module), opt_name(opt_name)
{
if (!design->selected_whole_module(module->name) && opt_name.empty())
return;
if (module->processes.size() > 0) {
log("Skipping module %s as it contains processes (run 'proc' pass first).\n", module->name.c_str());
return;
}
if (module->memories.size() > 0) {
log("Skipping module %s as it contains memories (run 'memory' pass first).\n", module->name.c_str());
return;
}
ct.setup_internals();
ct.setup_internals_mem();
ct.setup_stdcells();
ct.setup_stdcells_mem();
if (opt_name.empty())
{
for (auto &it : module->wires)
it.second->attributes.erase("\\submod");
for (auto &it : module->cells)
{
RTLIL::Cell *cell = it.second;
if (cell->attributes.count("\\submod") == 0 || cell->attributes["\\submod"].str.size() == 0) {
cell->attributes.erase("\\submod");
continue;
}
std::string submod_str = cell->attributes["\\submod"].str;
cell->attributes.erase("\\submod");
if (submodules.count(submod_str) == 0) {
submodules[submod_str].name = submod_str;
submodules[submod_str].full_name = module->name + "_" + submod_str;
while (design->modules.count(submodules[submod_str].full_name) != 0 ||
module->count_id(submodules[submod_str].full_name) != 0)
submodules[submod_str].full_name += "_";
}
submodules[submod_str].cells.insert(cell);
}
}
else
{
for (auto &it : module->cells)
{
RTLIL::Cell *cell = it.second;
if (!design->selected(module, cell))
continue;
submodules[opt_name].name = opt_name;
submodules[opt_name].full_name = RTLIL::escape_id(opt_name);
submodules[opt_name].cells.insert(cell);
}
if (submodules.size() == 0)
log("Nothing selected -> do nothing.\n");
}
for (auto &it : submodules)
handle_submodule(it.second);
}
};
struct SubmodPass : public Pass {
SubmodPass() : Pass("submod", "moving part of a module to a new submodule") { }
virtual void help()
{
// |---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|
log("\n");
log(" submod [selection]\n");
log("\n");
log("This pass identifies all cells with the 'submod' attribute and moves them to\n");
log("a newly created module. The value of the attribute is used as name for the\n");
log("cell that replaces the group of cells with the same attribute value.\n");
log("\n");
log("This pass can be used to create a design hierarchy in flat design. This can\n");
log("be useful for analyzing or reverse-engineering a design.\n");
log("\n");
log("This pass only operates on completely selected modules with no processes\n");
log("or memories.\n");
log("\n");
log("\n");
log(" submod -name <name> [selection]\n");
log("\n");
log("As above, but don't use the 'submod' attribute but instead use the selection.\n");
log("Only objects from one module might be selected. The value of the -name option\n");
log("is used as the value of the 'submod' attribute above.\n");
log("\n");
}
virtual void execute(std::vector<std::string> args, RTLIL::Design *design)
{
log_header("Executing SUBMOD pass (moving cells to submodules as requested).\n");
log_push();
std::string opt_name;
size_t argidx;
for (argidx = 1; argidx < args.size(); argidx++) {
if (args[argidx] == "-name" && argidx+1 < args.size()) {
opt_name = args[++argidx];
continue;
}
break;
}
extra_args(args, argidx, design);
if (opt_name.empty())
{
Pass::call(design, "opt_clean");
log_header("Continuing SUBMOD pass.\n");
std::set<std::string> handled_modules;
bool did_something = true;
while (did_something) {
did_something = false;
std::vector<std::string> queued_modules;
for (auto &mod_it : design->modules)
if (handled_modules.count(mod_it.first) == 0 && design->selected_whole_module(mod_it.first))
queued_modules.push_back(mod_it.first);
for (auto &modname : queued_modules)
if (design->modules.count(modname) != 0) {
SubmodWorker worker(design, design->modules[modname]);
handled_modules.insert(modname);
did_something = true;
}
}
Pass::call(design, "opt_clean");
}
else
{
RTLIL::Module *module = NULL;
for (auto &mod_it : design->modules) {
if (!design->selected_module(mod_it.first))
continue;
if (module != NULL)
log_cmd_error("More than one module selected: %s %s\n", module->name.c_str(), mod_it.first.c_str());
module = mod_it.second;
}
if (module == NULL)
log("Nothing selected -> do nothing.\n");
else {
Pass::call_newsel(design, stringf("opt_clean %s", module->name.c_str()));
log_header("Continuing SUBMOD pass.\n");
SubmodWorker worker(design, module, opt_name);
}
}
log_pop();
}
} SubmodPass;
<commit_msg>Fixed submod for non-primitive cells<commit_after>/*
* yosys -- Yosys Open SYnthesis Suite
*
* Copyright (C) 2012 Clifford Wolf <clifford@clifford.at>
*
* Permission to use, copy, modify, and/or distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
* ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
* ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
* OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*
*/
#include "kernel/register.h"
#include "kernel/celltypes.h"
#include "kernel/log.h"
#include <stdlib.h>
#include <stdio.h>
#include <set>
struct SubmodWorker
{
CellTypes ct;
RTLIL::Design *design;
RTLIL::Module *module;
std::string opt_name;
struct SubModule
{
std::string name, full_name;
std::set<RTLIL::Cell*> cells;
};
std::map<std::string, SubModule> submodules;
struct wire_flags_t {
RTLIL::Wire *new_wire;
bool is_int_driven, is_int_used, is_ext_driven, is_ext_used;
wire_flags_t() : new_wire(NULL), is_int_driven(false), is_int_used(false), is_ext_driven(false), is_ext_used(false) { }
};
std::map<RTLIL::Wire*, wire_flags_t> wire_flags;
bool flag_found_something;
void flag_wire(RTLIL::Wire *wire, bool create, bool set_int_driven, bool set_int_used, bool set_ext_driven, bool set_ext_used)
{
if (wire_flags.count(wire) == 0) {
if (!create)
return;
wire_flags[wire] = wire_flags_t();
}
if (set_int_driven)
wire_flags[wire].is_int_driven = true;
if (set_int_used)
wire_flags[wire].is_int_used = true;
if (set_ext_driven)
wire_flags[wire].is_ext_driven = true;
if (set_ext_used)
wire_flags[wire].is_ext_used = true;
flag_found_something = true;
}
void flag_signal(RTLIL::SigSpec &sig, bool create, bool set_int_driven, bool set_int_used, bool set_ext_driven, bool set_ext_used)
{
for (auto &c : sig.chunks)
if (c.wire != NULL)
flag_wire(c.wire, create, set_int_driven, set_int_used, set_ext_driven, set_ext_used);
}
void handle_submodule(SubModule &submod)
{
log("Creating submodule %s (%s) of module %s.\n", submod.name.c_str(), submod.full_name.c_str(), module->name.c_str());
wire_flags.clear();
for (RTLIL::Cell *cell : submod.cells) {
if (ct.cell_known(cell->type)) {
for (auto &conn : cell->connections)
flag_signal(conn.second, true, ct.cell_output(cell->type, conn.first), ct.cell_input(cell->type, conn.first), false, false);
} else {
log("WARNING: Port directions for cell %s (%s) are unknown. Assuming inout for all ports.\n", cell->name.c_str(), cell->type.c_str());
for (auto &conn : cell->connections)
flag_signal(conn.second, true, true, true, false, false);
}
}
for (auto &it : module->cells) {
RTLIL::Cell *cell = it.second;
if (submod.cells.count(cell) > 0)
continue;
if (ct.cell_known(cell->type)) {
for (auto &conn : cell->connections)
flag_signal(conn.second, false, false, false, ct.cell_output(cell->type, conn.first), ct.cell_input(cell->type, conn.first));
} else {
flag_found_something = false;
for (auto &conn : cell->connections)
flag_signal(conn.second, false, false, false, true, true);
if (flag_found_something)
log("WARNING: Port directions for cell %s (%s) are unknown. Assuming inout for all ports.\n", cell->name.c_str(), cell->type.c_str());
}
}
RTLIL::Module *new_mod = new RTLIL::Module;
new_mod->name = submod.full_name;
design->modules[new_mod->name] = new_mod;
int port_counter = 1, auto_name_counter = 1;
std::set<std::string> all_wire_names;
for (auto &it : wire_flags) {
all_wire_names.insert(it.first->name);
}
for (auto &it : wire_flags)
{
RTLIL::Wire *wire = it.first;
wire_flags_t &flags = it.second;
if (wire->port_input)
flags.is_ext_driven = true;
if (wire->port_output)
flags.is_ext_used = true;
RTLIL::Wire *new_wire = new RTLIL::Wire;
new_wire->name = wire->name;
new_wire->width = wire->width;
new_wire->start_offset = wire->start_offset;
new_wire->attributes = wire->attributes;
if (flags.is_int_driven && flags.is_ext_used)
new_wire->port_output = true;
if (flags.is_ext_driven && flags.is_int_used)
new_wire->port_input = true;
if (flags.is_int_driven && flags.is_ext_driven)
new_wire->port_input = true, new_wire->port_output = true;
if (new_wire->port_input || new_wire->port_output) {
new_wire->port_id = port_counter++;
while (new_wire->name[0] == '$') {
std::string new_wire_name = stringf("\\n%d", auto_name_counter++);
if (all_wire_names.count(new_wire_name) == 0) {
all_wire_names.insert(new_wire_name);
new_wire->name = new_wire_name;
}
}
}
if (new_wire->port_input && new_wire->port_output)
log(" signal %s: inout %s\n", wire->name.c_str(), new_wire->name.c_str());
else if (new_wire->port_input)
log(" signal %s: input %s\n", wire->name.c_str(), new_wire->name.c_str());
else if (new_wire->port_output)
log(" signal %s: output %s\n", wire->name.c_str(), new_wire->name.c_str());
else
log(" signal %s: internal\n", wire->name.c_str());
new_mod->wires[new_wire->name] = new_wire;
flags.new_wire = new_wire;
}
for (RTLIL::Cell *cell : submod.cells) {
RTLIL::Cell *new_cell = new RTLIL::Cell(*cell);
for (auto &conn : new_cell->connections)
for (auto &c : conn.second.chunks)
if (c.wire != NULL) {
assert(wire_flags.count(c.wire) > 0);
c.wire = wire_flags[c.wire].new_wire;
}
log(" cell %s (%s)\n", new_cell->name.c_str(), new_cell->type.c_str());
new_mod->cells[new_cell->name] = new_cell;
module->cells.erase(cell->name);
delete cell;
}
submod.cells.clear();
RTLIL::Cell *new_cell = new RTLIL::Cell;
new_cell->name = submod.full_name;
new_cell->type = submod.full_name;
for (auto &it : wire_flags)
{
RTLIL::Wire *old_wire = it.first;
RTLIL::Wire *new_wire = it.second.new_wire;
if (new_wire->port_id > 0)
new_cell->connections[new_wire->name] = RTLIL::SigSpec(old_wire);
}
module->cells[new_cell->name] = new_cell;
}
SubmodWorker(RTLIL::Design *design, RTLIL::Module *module, std::string opt_name = std::string()) : design(design), module(module), opt_name(opt_name)
{
if (!design->selected_whole_module(module->name) && opt_name.empty())
return;
if (module->processes.size() > 0) {
log("Skipping module %s as it contains processes (run 'proc' pass first).\n", module->name.c_str());
return;
}
if (module->memories.size() > 0) {
log("Skipping module %s as it contains memories (run 'memory' pass first).\n", module->name.c_str());
return;
}
ct.setup_internals();
ct.setup_internals_mem();
ct.setup_stdcells();
ct.setup_stdcells_mem();
ct.setup_design(design);
if (opt_name.empty())
{
for (auto &it : module->wires)
it.second->attributes.erase("\\submod");
for (auto &it : module->cells)
{
RTLIL::Cell *cell = it.second;
if (cell->attributes.count("\\submod") == 0 || cell->attributes["\\submod"].str.size() == 0) {
cell->attributes.erase("\\submod");
continue;
}
std::string submod_str = cell->attributes["\\submod"].str;
cell->attributes.erase("\\submod");
if (submodules.count(submod_str) == 0) {
submodules[submod_str].name = submod_str;
submodules[submod_str].full_name = module->name + "_" + submod_str;
while (design->modules.count(submodules[submod_str].full_name) != 0 ||
module->count_id(submodules[submod_str].full_name) != 0)
submodules[submod_str].full_name += "_";
}
submodules[submod_str].cells.insert(cell);
}
}
else
{
for (auto &it : module->cells)
{
RTLIL::Cell *cell = it.second;
if (!design->selected(module, cell))
continue;
submodules[opt_name].name = opt_name;
submodules[opt_name].full_name = RTLIL::escape_id(opt_name);
submodules[opt_name].cells.insert(cell);
}
if (submodules.size() == 0)
log("Nothing selected -> do nothing.\n");
}
for (auto &it : submodules)
handle_submodule(it.second);
}
};
struct SubmodPass : public Pass {
SubmodPass() : Pass("submod", "moving part of a module to a new submodule") { }
virtual void help()
{
// |---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|
log("\n");
log(" submod [selection]\n");
log("\n");
log("This pass identifies all cells with the 'submod' attribute and moves them to\n");
log("a newly created module. The value of the attribute is used as name for the\n");
log("cell that replaces the group of cells with the same attribute value.\n");
log("\n");
log("This pass can be used to create a design hierarchy in flat design. This can\n");
log("be useful for analyzing or reverse-engineering a design.\n");
log("\n");
log("This pass only operates on completely selected modules with no processes\n");
log("or memories.\n");
log("\n");
log("\n");
log(" submod -name <name> [selection]\n");
log("\n");
log("As above, but don't use the 'submod' attribute but instead use the selection.\n");
log("Only objects from one module might be selected. The value of the -name option\n");
log("is used as the value of the 'submod' attribute above.\n");
log("\n");
}
virtual void execute(std::vector<std::string> args, RTLIL::Design *design)
{
log_header("Executing SUBMOD pass (moving cells to submodules as requested).\n");
log_push();
std::string opt_name;
size_t argidx;
for (argidx = 1; argidx < args.size(); argidx++) {
if (args[argidx] == "-name" && argidx+1 < args.size()) {
opt_name = args[++argidx];
continue;
}
break;
}
extra_args(args, argidx, design);
if (opt_name.empty())
{
Pass::call(design, "opt_clean");
log_header("Continuing SUBMOD pass.\n");
std::set<std::string> handled_modules;
bool did_something = true;
while (did_something) {
did_something = false;
std::vector<std::string> queued_modules;
for (auto &mod_it : design->modules)
if (handled_modules.count(mod_it.first) == 0 && design->selected_whole_module(mod_it.first))
queued_modules.push_back(mod_it.first);
for (auto &modname : queued_modules)
if (design->modules.count(modname) != 0) {
SubmodWorker worker(design, design->modules[modname]);
handled_modules.insert(modname);
did_something = true;
}
}
Pass::call(design, "opt_clean");
}
else
{
RTLIL::Module *module = NULL;
for (auto &mod_it : design->modules) {
if (!design->selected_module(mod_it.first))
continue;
if (module != NULL)
log_cmd_error("More than one module selected: %s %s\n", module->name.c_str(), mod_it.first.c_str());
module = mod_it.second;
}
if (module == NULL)
log("Nothing selected -> do nothing.\n");
else {
Pass::call_newsel(design, stringf("opt_clean %s", module->name.c_str()));
log_header("Continuing SUBMOD pass.\n");
SubmodWorker worker(design, module, opt_name);
}
}
log_pop();
}
} SubmodPass;
<|endoftext|> |
<commit_before>//
// embedded.cpp
// integral
//
// Copyright (C) 2013, 2014 André Pereira Henriques
// aphenriques (at) outlook (dot) com
//
// This file is part of integral.
//
// integral 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.
//
// integral 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 integral. If not, see <http://www.gnu.org/licenses/>.
//
#include <iostream>
#include <lua.hpp>
#include "integral.h"
class Object {
public:
void printMessage() const {
std::cout << "Object " << this << " message!" << std::endl;
}
};
int main(int argc, char * argv[]) {
lua_State *luaState = nullptr;
try {
luaState = luaL_newstate();
integral::pushClassMetatable<Object>(luaState);
integral::setConstructor<Object>(luaState, "new");
// lua function name need not be the same as the C++ function name
integral::setFunction(luaState, "print", &Object::printMessage);
lua_setglobal(luaState, "Object");
luaL_dostring(luaState, "local object = Object.new()\n"
"object:print()");
lua_close(luaState);
return 0;
} catch (const std::exception &exception) {
std::cout << exception.what() << std::endl;
} catch (...) {
std::cout << "unknown exception thrown" << std::endl;
}
lua_close(luaState);
return 1;
}
<commit_msg>added luaState nullptr safety check<commit_after>//
// embedded.cpp
// integral
//
// Copyright (C) 2013, 2014 André Pereira Henriques
// aphenriques (at) outlook (dot) com
//
// This file is part of integral.
//
// integral 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.
//
// integral 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 integral. If not, see <http://www.gnu.org/licenses/>.
//
#include <iostream>
#include <lua.hpp>
#include "integral.h"
class Object {
public:
void printMessage() const {
std::cout << "Object " << this << " message!" << std::endl;
}
};
int main(int argc, char * argv[]) {
lua_State *luaState = nullptr;
try {
luaState = luaL_newstate();
integral::pushClassMetatable<Object>(luaState);
integral::setConstructor<Object>(luaState, "new");
// lua function name need not be the same as the C++ function name
integral::setFunction(luaState, "print", &Object::printMessage);
lua_setglobal(luaState, "Object");
luaL_dostring(luaState, "local object = Object.new()\n"
"object:print()");
lua_close(luaState);
return 0;
} catch (const std::exception &exception) {
std::cout << exception.what() << std::endl;
} catch (...) {
std::cout << "unknown exception thrown" << std::endl;
}
if (luaState != nullptr) {
lua_close(luaState);
}
return 1;
}
<|endoftext|> |
<commit_before>#include "systems/CollisionSystem.h"
void CollisionSystem::update(int elapsedMs, World &world)
{
for(auto collidable : world.getEntitiesForType(ComponentTypes::COLLIDABLE))
{
if(collidable->hasComponent(ComponentTypes::VELOCITY))
{
Velocity *v = (Velocity *)collidable->getComponent(ComponentTypes::VELOCITY);
Position *p = (Position *)collidable->getComponent(ComponentTypes::POSITION);
RenderRect *r = (RenderRect *)collidable->getComponent(ComponentTypes::RENDERRECT);
float deltaX, deltaY = 0.0f;
deltaX = v->dx * elapsedMs;
deltaY = v->dy * elapsedMs;
SDL_Rect updated = {p->x, p->y, static_cast<int>(r->rect.w + deltaX), static_cast<int>(r->rect.h + deltaY)};
/**
* For each other entity:
* 1) Check to see if there AABB overlap
* 2) Damage and remove if bullet hitting zombie
* 3) Bump if map boundary
* 4) Damage player if zombie hitting player and bump
*/
for(auto entity : world.getEntitiesForType(ComponentTypes::COLLIDABLE))
{
if(entity == collidable) { continue; }
//Minkowski Sum
if(didCollide(collidable, entity, elapsedMs))
{
bulletHitsMonster(collidable, entity);
playerHitsCorpse(collidable, entity);
playerHitsMonster(collidable, entity, elapsedMs);
}
//Remove the onCorpse if it's there.
else if(collidable->hasComponent(ComponentTypes::PLAYERINPUT) && collidable->hasComponent(ComponentTypes::ONCORPSE))
{
SDL_Log("Player %d, no longer on corpse", collidable->getId());
collidable->removeComponent(ComponentTypes::ONCORPSE);
}
}
p->x += deltaX;
p->y += deltaY;
//Check world boundaries
bool remove = false;
if(p->x >= 800) {
if(collidable->hasComponent(ComponentTypes::BULLET)) {
remove = true;
}
p->x = 800 - 16;
}
if(p->x <= 0) {
if(collidable->hasComponent(ComponentTypes::BULLET)) {
remove = true;
}
p->x = 0;
}
if(p->y >= 600) {
if(collidable->hasComponent(ComponentTypes::BULLET)) {
remove = true;
}
p->y = 600 - 16;
}
if(p->y <= 0) {
if(collidable->hasComponent(ComponentTypes::BULLET)) {
remove = true;
}
p->y = 0;
}
if(remove)
{
collidable->addComponent(ComponentTypes::REMOVE, new Remove());
}
}
}
}
bool CollisionSystem::didCollide(Entity *first, Entity *second, int elapsedMs)
{
Velocity *v = (Velocity *)first->getComponent(ComponentTypes::VELOCITY);
Position *p = (Position *)first->getComponent(ComponentTypes::POSITION);
RenderRect *r = (RenderRect *)first->getComponent(ComponentTypes::RENDERRECT);
float deltaX, deltaY = 0.0f;
deltaX = v->dx * elapsedMs;
deltaY = v->dy * elapsedMs;
SDL_Rect updated = {p->x, p->y, static_cast<int>(r->rect.w + deltaX), static_cast<int>(r->rect.h + deltaY)};
Position *testPosition = (Position *)second->getComponent(ComponentTypes::POSITION);
RenderRect *testRender = (RenderRect *)second->getComponent(ComponentTypes::RENDERRECT);
SDL_Rect minkowskiSquare;
float halfWidth = updated.w/2;
float halfHeight = updated.h/2;
minkowskiSquare.x = testPosition->x - halfWidth;
minkowskiSquare.y = testPosition->y - halfHeight;
minkowskiSquare.w = testRender->rect.w + 2 * halfWidth;
minkowskiSquare.h = testRender->rect.h + 2 * halfHeight;
Position centerPoint = Position();
centerPoint.x = p->x + halfWidth;
centerPoint.y = p->y + halfHeight;
return centerPoint.x > minkowskiSquare.x &&
centerPoint.x <= minkowskiSquare.x + minkowskiSquare.w &&
centerPoint.y >= minkowskiSquare.y &&
centerPoint.y <= minkowskiSquare.y + minkowskiSquare.h;
}
void CollisionSystem::bulletHitsMonster(Entity *first, Entity *second)
{
if(first->hasComponent(ComponentTypes::BULLET) && second->hasComponent(ComponentTypes::MONSTER))
{
SDL_Log("Bullet hit monster!");
first->addComponent(ComponentTypes::REMOVE, new Remove());
Life *life = (Life *)second->getComponent(ComponentTypes::LIFE);
life->damage++;
}
}
void CollisionSystem::playerHitsCorpse(Entity *first, Entity *second)
{
if(first->hasComponent(ComponentTypes::PLAYERINPUT) && second->hasComponent(ComponentTypes::CORPSE))
{
if(!first->hasComponent(ComponentTypes::ONCORPSE))
{
OnCorpse *c = new OnCorpse();
c->corpseEntityId = second->getId();
SDL_Log("Standing on corpse: %d", c->corpseEntityId);
first->addComponent(ComponentTypes::ONCORPSE, c);
}
}
}
void CollisionSystem::playerHitsMonster(Entity *first, Entity *second, int elapsedMs)
{
if(first->hasComponent(ComponentTypes::PLAYERINPUT) && second->hasComponent(ComponentTypes::MONSTER))
{
Collidable *collision = (Collidable *)first->getComponent(ComponentTypes::COLLIDABLE);
if(collision->currentMs == 0 || collision->currentMs >= collision->msBetweenHits)
{
SDL_Log("Monster hit player!");
Life *life = (Life *)first->getComponent(ComponentTypes::LIFE);
life->damage++;
collision->currentMs = 0;
}
collision->currentMs += elapsedMs;
}
}
<commit_msg>fixed goofy collision hiccup with corpses<commit_after>#include "systems/CollisionSystem.h"
void CollisionSystem::update(int elapsedMs, World &world)
{
for(auto collidable : world.getEntitiesForType(ComponentTypes::COLLIDABLE))
{
if(collidable->hasComponent(ComponentTypes::VELOCITY))
{
Velocity *v = (Velocity *)collidable->getComponent(ComponentTypes::VELOCITY);
Position *p = (Position *)collidable->getComponent(ComponentTypes::POSITION);
float deltaX, deltaY = 0.0f;
deltaX = v->dx * elapsedMs;
deltaY = v->dy * elapsedMs;
bool collided = false;
/**
* For each other entity:
* 1) Check to see if there AABB overlap
* 2) Damage and remove if bullet hitting zombie
* 3) Bump if map boundary
* 4) Damage player if zombie hitting player and bump
*/
for(auto entity : world.getEntitiesForType(ComponentTypes::COLLIDABLE))
{
if(entity == collidable) { continue; }
//Minkowski Sum
if(didCollide(collidable, entity, elapsedMs))
{
bulletHitsMonster(collidable, entity);
playerHitsCorpse(collidable, entity);
playerHitsMonster(collidable, entity, elapsedMs);
collided = true;
}
}
//Remove the onCorpse if it's there.
if(collidable->hasComponent(ComponentTypes::PLAYERINPUT) && collidable->hasComponent(ComponentTypes::ONCORPSE) && !collided)
{
SDL_Log("Player %d, no longer on corpse", collidable->getId());
collidable->removeComponent(ComponentTypes::ONCORPSE);
}
p->x += deltaX;
p->y += deltaY;
//Check world boundaries
bool remove = false;
if(p->x >= 800) {
if(collidable->hasComponent(ComponentTypes::BULLET)) {
remove = true;
}
p->x = 800 - 16;
}
if(p->x <= 0) {
if(collidable->hasComponent(ComponentTypes::BULLET)) {
remove = true;
}
p->x = 0;
}
if(p->y >= 600) {
if(collidable->hasComponent(ComponentTypes::BULLET)) {
remove = true;
}
p->y = 600 - 16;
}
if(p->y <= 0) {
if(collidable->hasComponent(ComponentTypes::BULLET)) {
remove = true;
}
p->y = 0;
}
if(remove)
{
collidable->addComponent(ComponentTypes::REMOVE, new Remove());
}
}
}
}
bool CollisionSystem::didCollide(Entity *first, Entity *second, int elapsedMs)
{
Velocity *v = (Velocity *)first->getComponent(ComponentTypes::VELOCITY);
Position *p = (Position *)first->getComponent(ComponentTypes::POSITION);
RenderRect *r = (RenderRect *)first->getComponent(ComponentTypes::RENDERRECT);
float deltaX, deltaY = 0.0f;
deltaX = v->dx * elapsedMs;
deltaY = v->dy * elapsedMs;
SDL_Rect updated = {p->x, p->y, static_cast<int>(r->rect.w + deltaX), static_cast<int>(r->rect.h + deltaY)};
Position *testPosition = (Position *)second->getComponent(ComponentTypes::POSITION);
RenderRect *testRender = (RenderRect *)second->getComponent(ComponentTypes::RENDERRECT);
SDL_Rect minkowskiSquare;
float halfWidth = updated.w/2;
float halfHeight = updated.h/2;
minkowskiSquare.x = testPosition->x - halfWidth;
minkowskiSquare.y = testPosition->y - halfHeight;
minkowskiSquare.w = testRender->rect.w + 2 * halfWidth;
minkowskiSquare.h = testRender->rect.h + 2 * halfHeight;
Position centerPoint = Position();
centerPoint.x = p->x + halfWidth;
centerPoint.y = p->y + halfHeight;
return centerPoint.x > minkowskiSquare.x &&
centerPoint.x <= minkowskiSquare.x + minkowskiSquare.w &&
centerPoint.y >= minkowskiSquare.y &&
centerPoint.y <= minkowskiSquare.y + minkowskiSquare.h;
}
void CollisionSystem::bulletHitsMonster(Entity *first, Entity *second)
{
if(first->hasComponent(ComponentTypes::BULLET) && second->hasComponent(ComponentTypes::MONSTER))
{
SDL_Log("Bullet hit monster!");
first->addComponent(ComponentTypes::REMOVE, new Remove());
Life *life = (Life *)second->getComponent(ComponentTypes::LIFE);
life->damage++;
}
}
void CollisionSystem::playerHitsCorpse(Entity *first, Entity *second)
{
if(first->hasComponent(ComponentTypes::PLAYERINPUT) && second->hasComponent(ComponentTypes::CORPSE))
{
if(!first->hasComponent(ComponentTypes::ONCORPSE))
{
OnCorpse *c = new OnCorpse();
c->corpseEntityId = second->getId();
SDL_Log("Standing on corpse: %d", c->corpseEntityId);
first->addComponent(ComponentTypes::ONCORPSE, c);
}
}
}
void CollisionSystem::playerHitsMonster(Entity *first, Entity *second, int elapsedMs)
{
if(first->hasComponent(ComponentTypes::PLAYERINPUT) && second->hasComponent(ComponentTypes::MONSTER))
{
Collidable *collision = (Collidable *)first->getComponent(ComponentTypes::COLLIDABLE);
if(collision->currentMs == 0 || collision->currentMs >= collision->msBetweenHits)
{
SDL_Log("Monster hit player!");
Life *life = (Life *)first->getComponent(ComponentTypes::LIFE);
life->damage++;
collision->currentMs = 0;
}
collision->currentMs += elapsedMs;
}
}
<|endoftext|> |
<commit_before>#include "entity_manager.h"
#include "gameengine.h"
#include <fstream>
#include <iostream>
void EntityManager::initialise (GameEngineInterface* engine)
{
maxId = 1;
m_engine = engine;
m_player = 0;
}
EntityId EntityManager::createEntity () {
EntityId l_entity = maxId++;
AddEntityEvent* l_event = new AddEntityEvent;
l_event->entity = l_entity;
m_engine->raiseEvent (l_event);
return l_entity;
}
void EntityManager::destroyEntity (EntityId id) {
getColliders()->remove (id);
getSprites()->remove (id);
getHealths()->remove (id);
getDescriptions()->remove (id);
getPlayers()->remove (id);
getNpcs()->remove (id);
getLocations()->remove (id);
getStairs()->remove(id);
getEquipments()->remove (id);
getWearables()->remove (id);
getWieldables()->remove (id);
// Raise event for removal
RemoveEntityEvent* l_event = new RemoveEntityEvent();
l_event->entity = id;
m_engine->raiseEvent (l_event);
}
EntityId EntityManager::getPlayer () {
if (m_player == 0) {
std::map<EntityId, PlayerComponent>& l_players = getPlayers()->getAll();
std::map<EntityId, PlayerComponent>::iterator iter = l_players.begin();
m_player = iter->first;
}
return m_player;
}
EntityId EntityManager::createWallPrefab (unsigned int x, unsigned int y, unsigned int z)
{
EntityId l_entity = createEntity();
// Location Component
LocationComponent l_loc;
l_loc.x = x;
l_loc.y = y;
l_loc.z = (z == 0) ? m_engine->getLevel() : z;
getLocations()->add (l_entity, l_loc);
// Sprite Component
SpriteComponent l_sprite;
l_sprite.fgColor = Color (GREY);
l_sprite.bgColor = Color (BLACK);
l_sprite.sprite = 'W';
getSprites()->add (l_entity, l_sprite);
// Collider Component
ColliderComponent l_collider;
getColliders()->add (l_entity, l_collider);
DescriptionComponent l_description;
l_description.title = "Wall";
l_description.text = "A smooth granite wall";
getDescriptions()->add (l_entity, l_description);
return l_entity;
}
EntityId EntityManager::createPlayerPrefab (unsigned int x, unsigned int y, unsigned int z)
{
EntityId l_entity = createEntity();
// Location Component
LocationComponent l_loc;
l_loc.x = x;
l_loc.y = y;
l_loc.z = (z == 0) ? m_engine->getLevel() : z;
getLocations()->add (l_entity, l_loc);
// Sprite Component
SpriteComponent l_sprite;
l_sprite.fgColor = Color (WHITE);
l_sprite.bgColor = Color (BLACK);
l_sprite.sprite = '@';
getSprites()->add (l_entity, l_sprite);
// Collider Component
ColliderComponent l_collider;
getColliders()->add (l_entity, l_collider);
// Description Component
DescriptionComponent l_description;
l_description.title = "You";
l_description.text = "Time for introspection";
getDescriptions()->add (l_entity, l_description);
// Health Component
HealthComponent l_health;
l_health.health = 10;
getHealths()->add (l_entity, l_health);
// Player Component
PlayerComponent l_player;
getPlayers()->add (l_entity, l_player);
return l_entity;
}
EntityId EntityManager::createEnemyPrefab (unsigned int x, unsigned int y, unsigned int z)
{
EntityId l_entity = createEntity();
// Location Component
LocationComponent l_loc;
l_loc.x = x;
l_loc.y = y;
l_loc.z = (z == 0) ? m_engine->getLevel() : z;
getLocations()->add (l_entity, l_loc);
// Sprite Component
SpriteComponent l_sprite;
l_sprite.fgColor = Color (RED);
l_sprite.bgColor = Color (BLACK);
l_sprite.sprite = 'O';
getSprites()->add (l_entity, l_sprite);
// Collider Component
ColliderComponent l_collider;
getColliders()->add (l_entity, l_collider);
// Description Component
DescriptionComponent l_description;
l_description.title = "Orc";
l_description.text = "A vile, stinking creature";
getDescriptions()->add (l_entity, l_description);
// Health Component
HealthComponent l_health;
l_health.health = 1;
getHealths()->add (l_entity, l_health);
// NPC Component
NpcComponent l_npc;
getNpcs()->add (l_entity, l_npc);
// Euipment Component
EquipmentComponent l_equipment;
l_equipment.rightHandWieldable = createWeaponPrefab();
l_equipment.leftHandWieldable = createShieldPrefab();
l_equipment.headWearable = createHelmetPrefab();
getEquipments()->add (l_entity, l_equipment);
return l_entity;
}
EntityId EntityManager::createTilePrefab (unsigned int x, unsigned int y, unsigned int z)
{
EntityId l_entity = createEntity();
// Location Component
LocationComponent l_loc;
l_loc.x = x;
l_loc.y = y;
l_loc.z = (z == 0) ? m_engine->getLevel() : z;
getLocations()->add (l_entity, l_loc);
//Sprite Component
SpriteComponent l_sprite;
l_sprite.fgColor = Color (GREY);
l_sprite.bgColor = Color (BLACK);
l_sprite.sprite = '.';
getSprites()->add (l_entity, l_sprite);
// Description Component
DescriptionComponent l_description;
l_description.title = "Floor tile";
l_description.text = "It's a bit scuffed";
getDescriptions()->add (l_entity, l_description);
return l_entity;
}
EntityId EntityManager::createMarkerPrefab (unsigned int x, unsigned int y, unsigned int z)
{
EntityId l_entity = createEntity();
// Location Component
LocationComponent l_loc;
l_loc.x = x;
l_loc.y = y;
l_loc.z = (z == 0) ? m_engine->getLevel() : z;
getLocations()->add (l_entity, l_loc);
//Sprite Component
SpriteComponent l_sprite;
l_sprite.fgColor = Color (YELLOW);
l_sprite.bgColor = Color (BLACK);
l_sprite.sprite = 'X';
getSprites()->add (l_entity, l_sprite);
return l_entity;
}
EntityId EntityManager::createStairPrefab (STAIR dir, unsigned int x, unsigned int y, unsigned int z)
{
EntityId l_entity = createEntity();
// Location Component
LocationComponent l_loc;
l_loc.x = x;
l_loc.y = y;
l_loc.z = (z == 0) ? m_engine->getLevel() : z;
getLocations()->add (l_entity, l_loc);
//Sprite Component
SpriteComponent l_sprite;
l_sprite.fgColor = Color (WHITE);
l_sprite.bgColor = Color (BLACK);
l_sprite.sprite = (dir == STAIR_DOWN) ? '>' : '<';
getSprites()->add (l_entity, l_sprite);
// Description Component
DescriptionComponent l_description;
l_description.title = (dir == STAIR_DOWN) ? "A stairway down" : "A stairway up";
l_description.text = "It has rough-hewn steps.";
getDescriptions()->add (l_entity, l_description);
// StairComponent
StairComponent l_stair;
l_stair.direction = dir;
getStairs()->add (l_entity, l_stair);
return l_entity;
}
EntityId EntityManager::createWeaponPrefab ()
{
EntityId l_entity = createEntity();
WieldableComponent l_wieldable;
l_wieldable.position = WieldableRightHand;
l_wieldable.baseDamage = 2;
l_wieldable.baseDefence = 0;
getWieldables()->add (l_entity, l_wieldable);
return l_entity;
}
EntityId EntityManager::createShieldPrefab ()
{
EntityId l_entity = createEntity();
WieldableComponent l_wieldable;
l_wieldable.position = WieldableLeftHand;
l_wieldable.baseDamage = 0;
l_wieldable.baseDefence = 4;
getWieldables()->add (l_entity, l_wieldable);
return l_entity;
}
EntityId EntityManager::createHelmetPrefab ()
{
EntityId l_entity = createEntity();
WearableComponent l_wearable;
l_wearable.position = WearableHead;
getWearables()->add (l_entity, l_wearable);
return l_entity;
}
std::vector<EntityId> EntityManager::findEntitiesAt (unsigned int x, unsigned int y)
{
return findEntitiesNear (x, y, 0);
}
std::vector<EntityId> EntityManager::findEntitiesNear (unsigned int x, unsigned int y, unsigned radius)
{
std::vector<EntityId> l_entities;
std::map<EntityId, LocationComponent>& l_locations = m_engine->getEntities()->getLocations()->getAll();
std::map<EntityId, LocationComponent>::iterator it = l_locations.begin();
for (; it != l_locations.end(); it++) {
if (it->second.x >= x - radius &&
it->second.x <= x + radius &&
it->second.y >= y - radius &&
it->second.y <= y + radius &&
it->second.z == m_engine->getLevel()) {
l_entities.push_back (it->first);
}
}
return l_entities;
}
std::vector<EntityId> EntityManager::findEntitiesToThe (DIRECTION a_direction, EntityId a_entity)
{
std::vector<EntityId> l_entities;
LocationComponent* l_location = m_engine->getEntities()->getLocations()->get (a_entity);
if (!l_location) return l_entities;
unsigned int newX = l_location->x;
unsigned int newY = l_location->y;
switch (a_direction) {
case Direction::North: newY--; break;
case Direction::South: newY++; break;
case Direction::West: newX--; break;
case Direction::East: newX++; break;
default: return l_entities;
}
return findEntitiesAt (newX, newY);
}
<commit_msg>Gave descriptions to the equipment prefabs<commit_after>#include "entity_manager.h"
#include "gameengine.h"
#include <fstream>
#include <iostream>
void EntityManager::initialise (GameEngineInterface* engine)
{
maxId = 1;
m_engine = engine;
m_player = 0;
}
EntityId EntityManager::createEntity () {
EntityId l_entity = maxId++;
AddEntityEvent* l_event = new AddEntityEvent;
l_event->entity = l_entity;
m_engine->raiseEvent (l_event);
return l_entity;
}
void EntityManager::destroyEntity (EntityId id) {
getColliders()->remove (id);
getSprites()->remove (id);
getHealths()->remove (id);
getDescriptions()->remove (id);
getPlayers()->remove (id);
getNpcs()->remove (id);
getLocations()->remove (id);
getStairs()->remove(id);
getEquipments()->remove (id);
getWearables()->remove (id);
getWieldables()->remove (id);
// Raise event for removal
RemoveEntityEvent* l_event = new RemoveEntityEvent();
l_event->entity = id;
m_engine->raiseEvent (l_event);
}
EntityId EntityManager::getPlayer () {
if (m_player == 0) {
std::map<EntityId, PlayerComponent>& l_players = getPlayers()->getAll();
std::map<EntityId, PlayerComponent>::iterator iter = l_players.begin();
m_player = iter->first;
}
return m_player;
}
EntityId EntityManager::createWallPrefab (unsigned int x, unsigned int y, unsigned int z)
{
EntityId l_entity = createEntity();
// Location Component
LocationComponent l_loc;
l_loc.x = x;
l_loc.y = y;
l_loc.z = (z == 0) ? m_engine->getLevel() : z;
getLocations()->add (l_entity, l_loc);
// Sprite Component
SpriteComponent l_sprite;
l_sprite.fgColor = Color (GREY);
l_sprite.bgColor = Color (BLACK);
l_sprite.sprite = 'W';
getSprites()->add (l_entity, l_sprite);
// Collider Component
ColliderComponent l_collider;
getColliders()->add (l_entity, l_collider);
DescriptionComponent l_description;
l_description.title = "Wall";
l_description.text = "A smooth granite wall";
getDescriptions()->add (l_entity, l_description);
return l_entity;
}
EntityId EntityManager::createPlayerPrefab (unsigned int x, unsigned int y, unsigned int z)
{
EntityId l_entity = createEntity();
// Location Component
LocationComponent l_loc;
l_loc.x = x;
l_loc.y = y;
l_loc.z = (z == 0) ? m_engine->getLevel() : z;
getLocations()->add (l_entity, l_loc);
// Sprite Component
SpriteComponent l_sprite;
l_sprite.fgColor = Color (WHITE);
l_sprite.bgColor = Color (BLACK);
l_sprite.sprite = '@';
getSprites()->add (l_entity, l_sprite);
// Collider Component
ColliderComponent l_collider;
getColliders()->add (l_entity, l_collider);
// Description Component
DescriptionComponent l_description;
l_description.title = "You";
l_description.text = "Time for introspection";
getDescriptions()->add (l_entity, l_description);
// Health Component
HealthComponent l_health;
l_health.health = 10;
getHealths()->add (l_entity, l_health);
// Player Component
PlayerComponent l_player;
getPlayers()->add (l_entity, l_player);
return l_entity;
}
EntityId EntityManager::createEnemyPrefab (unsigned int x, unsigned int y, unsigned int z)
{
EntityId l_entity = createEntity();
// Location Component
LocationComponent l_loc;
l_loc.x = x;
l_loc.y = y;
l_loc.z = (z == 0) ? m_engine->getLevel() : z;
getLocations()->add (l_entity, l_loc);
// Sprite Component
SpriteComponent l_sprite;
l_sprite.fgColor = Color (RED);
l_sprite.bgColor = Color (BLACK);
l_sprite.sprite = 'O';
getSprites()->add (l_entity, l_sprite);
// Collider Component
ColliderComponent l_collider;
getColliders()->add (l_entity, l_collider);
// Description Component
DescriptionComponent l_description;
l_description.title = "Orc";
l_description.text = "A vile, stinking creature";
getDescriptions()->add (l_entity, l_description);
// Health Component
HealthComponent l_health;
l_health.health = 1;
getHealths()->add (l_entity, l_health);
// NPC Component
NpcComponent l_npc;
getNpcs()->add (l_entity, l_npc);
// Euipment Component
EquipmentComponent l_equipment;
l_equipment.rightHandWieldable = createWeaponPrefab();
l_equipment.leftHandWieldable = createShieldPrefab();
l_equipment.headWearable = createHelmetPrefab();
getEquipments()->add (l_entity, l_equipment);
return l_entity;
}
EntityId EntityManager::createTilePrefab (unsigned int x, unsigned int y, unsigned int z)
{
EntityId l_entity = createEntity();
// Location Component
LocationComponent l_loc;
l_loc.x = x;
l_loc.y = y;
l_loc.z = (z == 0) ? m_engine->getLevel() : z;
getLocations()->add (l_entity, l_loc);
//Sprite Component
SpriteComponent l_sprite;
l_sprite.fgColor = Color (GREY);
l_sprite.bgColor = Color (BLACK);
l_sprite.sprite = '.';
getSprites()->add (l_entity, l_sprite);
// Description Component
DescriptionComponent l_description;
l_description.title = "Floor tile";
l_description.text = "It's a bit scuffed";
getDescriptions()->add (l_entity, l_description);
return l_entity;
}
EntityId EntityManager::createMarkerPrefab (unsigned int x, unsigned int y, unsigned int z)
{
EntityId l_entity = createEntity();
// Location Component
LocationComponent l_loc;
l_loc.x = x;
l_loc.y = y;
l_loc.z = (z == 0) ? m_engine->getLevel() : z;
getLocations()->add (l_entity, l_loc);
//Sprite Component
SpriteComponent l_sprite;
l_sprite.fgColor = Color (YELLOW);
l_sprite.bgColor = Color (BLACK);
l_sprite.sprite = 'X';
getSprites()->add (l_entity, l_sprite);
return l_entity;
}
EntityId EntityManager::createStairPrefab (STAIR dir, unsigned int x, unsigned int y, unsigned int z)
{
EntityId l_entity = createEntity();
// Location Component
LocationComponent l_loc;
l_loc.x = x;
l_loc.y = y;
l_loc.z = (z == 0) ? m_engine->getLevel() : z;
getLocations()->add (l_entity, l_loc);
//Sprite Component
SpriteComponent l_sprite;
l_sprite.fgColor = Color (WHITE);
l_sprite.bgColor = Color (BLACK);
l_sprite.sprite = (dir == STAIR_DOWN) ? '>' : '<';
getSprites()->add (l_entity, l_sprite);
// Description Component
DescriptionComponent l_description;
l_description.title = (dir == STAIR_DOWN) ? "A stairway down" : "A stairway up";
l_description.text = "It has rough-hewn steps.";
getDescriptions()->add (l_entity, l_description);
// StairComponent
StairComponent l_stair;
l_stair.direction = dir;
getStairs()->add (l_entity, l_stair);
return l_entity;
}
EntityId EntityManager::createWeaponPrefab ()
{
EntityId l_entity = createEntity();
WieldableComponent l_wieldable;
l_wieldable.position = WieldableRightHand;
l_wieldable.baseDamage = 2;
l_wieldable.baseDefence = 0;
getWieldables()->add (l_entity, l_wieldable);
DescriptionComponent l_description;
l_description.title = "A Sword";
l_description.text = "Stick 'em with the pointy end!";
getDescriptions()->add (l_entity, l_description);
return l_entity;
}
EntityId EntityManager::createShieldPrefab ()
{
EntityId l_entity = createEntity();
WieldableComponent l_wieldable;
l_wieldable.position = WieldableLeftHand;
l_wieldable.baseDamage = 0;
l_wieldable.baseDefence = 4;
getWieldables()->add (l_entity, l_wieldable);
DescriptionComponent l_description;
l_description.title = "A Shield";
l_description.text = "Return to your mother...";
getDescriptions()->add (l_entity, l_description);
return l_entity;
}
EntityId EntityManager::createHelmetPrefab ()
{
EntityId l_entity = createEntity();
WearableComponent l_wearable;
l_wearable.position = WearableHead;
getWearables()->add (l_entity, l_wearable);
DescriptionComponent l_description;
l_description.title = "A helmet";
l_description.text = "It says: One Size Fits All";
getDescriptions()->add (l_entity, l_description);
return l_entity;
}
std::vector<EntityId> EntityManager::findEntitiesAt (unsigned int x, unsigned int y)
{
return findEntitiesNear (x, y, 0);
}
std::vector<EntityId> EntityManager::findEntitiesNear (unsigned int x, unsigned int y, unsigned radius)
{
std::vector<EntityId> l_entities;
std::map<EntityId, LocationComponent>& l_locations = m_engine->getEntities()->getLocations()->getAll();
std::map<EntityId, LocationComponent>::iterator it = l_locations.begin();
for (; it != l_locations.end(); it++) {
if (it->second.x >= x - radius &&
it->second.x <= x + radius &&
it->second.y >= y - radius &&
it->second.y <= y + radius &&
it->second.z == m_engine->getLevel()) {
l_entities.push_back (it->first);
}
}
return l_entities;
}
std::vector<EntityId> EntityManager::findEntitiesToThe (DIRECTION a_direction, EntityId a_entity)
{
std::vector<EntityId> l_entities;
LocationComponent* l_location = m_engine->getEntities()->getLocations()->get (a_entity);
if (!l_location) return l_entities;
unsigned int newX = l_location->x;
unsigned int newY = l_location->y;
switch (a_direction) {
case Direction::North: newY--; break;
case Direction::South: newY++; break;
case Direction::West: newX--; break;
case Direction::East: newX++; break;
default: return l_entities;
}
return findEntitiesAt (newX, newY);
}
<|endoftext|> |
<commit_before>#pragma ident "$Id$"
//============================================================================
//
// This file is part of GPSTk, the GPS Toolkit.
//
// The GPSTk 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
// any later version.
//
// The GPSTk 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 GPSTk; if not, write to the Free Software Foundation,
// Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
//
// Copyright 2004, The University of Texas at Austin
//
//============================================================================
/**
* @file EditRinex.cpp
* Edit a Rinex observation file using the RinexEditor in gpstk.
*/
#include "RinexObsBase.hpp"
#include "RinexObsData.hpp"
#include "RinexObsHeader.hpp"
#include "RinexObsStream.hpp"
#include "DayTime.hpp"
#include "CommandOptionParser.hpp"
#include "CommandOption.hpp"
#include "RinexUtilities.hpp"
#include "StringUtils.hpp"
#include "RinexEditor.hpp"
#include <string>
#include <vector>
#include <iostream>
#include <fstream>
#include <time.h>
using namespace std;
using namespace gpstk;
using namespace StringUtils;
//------------------------------------------------------------------------------------
// NB Version for this prgm is just the RinexEditor version.
//------------------------------------------------------------------------------------
// data input from command line
string LogFile("EditRinex.log");
bool Verbose=false,Debug=false;
string Title;
// timer
clock_t totaltime;
// log file
ofstream oflog;
//------------------------------------------------------------------------------------
// prototypes
int GetCommandLine(int argc, char **argv, RinexEditor& re) throw(Exception);
void PreProcessArgs(const char *arg, vector<string>& Args) throw(Exception);
//------------------------------------------------------------------------------------
int main(int argc, char **argv)
{
try {
totaltime = clock();
int iret;
DayTime last;
// NB. Do not instantiate editor outside main(), b/c DayTime::END_OF_TIME is a
// static const that can produce static intialization order problems under some OS.
RinexEditor REC;
// Title and description
Title = string("EditRinex, part of the GPSTK ToolKit, Ver ")
+ REC.getRinexEditVersion() + string(", Run ");
time_t timer;
struct tm *tblock;
timer = time(NULL);
tblock = localtime(&timer);
last.setYMDHMS(1900+tblock->tm_year,1+tblock->tm_mon,
tblock->tm_mday,tblock->tm_hour,tblock->tm_min,tblock->tm_sec);
Title += last.printf("%04Y/%02m/%02d %02H:%02M:%02S\n");
cout << Title;
// define extended types
iret = RegisterARLUTExtendedTypes();
if(iret) goto quit;
// get command line
iret=GetCommandLine(argc, argv, REC);
if(iret) goto quit;
iret=REC.EditFile();
if(iret) goto quit;
quit:
// compute run time
totaltime = clock()-totaltime;
oflog << "EditRinex timing: " << setprecision(3)
<< double(totaltime)/double(CLOCKS_PER_SEC) << " seconds.\n";
return iret;
}
catch(gpstk::FFStreamError& e) { cerr << e; }
catch(gpstk::Exception& e) { cerr << e; }
catch(exception& e) { cerr << e.what(); }
catch (...) { cerr << "Unknown error. Abort." << endl; }
return 1;
} // end main()
//------------------------------------------------------------------------------------
int GetCommandLine(int argc, char **argv, RinexEditor& REC) throw(Exception)
{
bool help=false;
int i,j,iret=0;
vector<string> values; // to get values found on command line
try {
// required options
// optional options
// this only so it will show up in help page...
CommandOption dashf(CommandOption::hasArgument, CommandOption::stdType,
'f',""," [-f|--file] <file> file containing more options");
CommandOption dashl(CommandOption::hasArgument, CommandOption::stdType,
0,"log"," [-l|--log] <file> Output log file name");
dashl.setMaxCount(1);
CommandOptionNoArg dashh('h', "help",
" [-h|--help] print syntax and quit.");
CommandOptionNoArg dashd('d', "debug",
" [-d|--debug] print extended output info.");
CommandOptionNoArg dashv('v', "verbose",
" [-v|--verbose] print extended output info."
"\n [<REC>] Rinex editing commands - cf. following");
// ... other options
CommandOptionRest Rest("");
CommandOptionParser Par(
" Prgm EditRinex will open and read one RINEX file, apply editing commands,\n"
" and write the modified RINEX data to another RINEX file(s).\n"
" Input is on the command line, or of the same format in a file (-f<file>).\n");
// allow user to put all options in a file
// could also scan for debug here
vector<string> Args;
for(j=1; j<argc; j++) PreProcessArgs(argv[j],Args);
if(Args.size()==0 || dashh.getCount())
help = true;
// open the log file first
oflog.open(LogFile.c_str(),ios_base::out);
if(!oflog) {
cerr << "Failed to open log file " << LogFile << endl;
return -1;
}
cout << "EditRinex output directed to log file " << LogFile << endl;
REC.oflog = &oflog;
oflog << Title;
//if(Debug) {
//cout << "List passed to REditCommandLine:\n";
//for(i=0; i<Args.size(); i++) cout << i << " " << Args[i] << endl;
// strip out the REditCmds
//}
// set up editor and pull out (delete) editing commands
REC.REVerbose = Verbose;
REC.REDebug = Debug;
REC.AddCommandLine(Args);
//if(Debug) {
//deque<REditCmd>::iterator jt=REC.Cmds.begin();
//cout << "\nHere is the list of RE cmds\n";
//while(jt != REC.Cmds.end()) { jt->Dump(cout,string("")); ++jt; }
//cout << "End of list of RE cmds" << endl;
//}
// preprocess the commands
iret = REC.ParseCommands();
if(iret) {
cerr << "EditRinex Error: no " << (iret==-1 ? "input" : "output")
<< " file specified\n";
oflog << "EditRinex Error: no " << (iret==-1 ? "input" : "output")
<< " file specified\n";
}
//if(Debug) {
//cout << "\nHere is the parsed list of RE cmds\n";
//it=REC.Cmds.begin();
//while(it != REC.Cmds.end()) { it->Dump(cout,string("")); ++it; }
//cout << "End of sorted list of RE cmds" << endl;
//}
// pass the rest
argc = Args.size()+1;
char **CArgs=new char*[argc];
if(!CArgs) { cerr << "Failed to allocate CArgs\n"; return -1; }
CArgs[0] = argv[0];
for(j=1; j<argc; j++) {
CArgs[j] = new char[Args[j-1].size()+1];
if(!CArgs[j]) { cerr << "Failed to allocate CArgs[j]\n"; return -1; }
strcpy(CArgs[j],Args[j-1].c_str());
}
//if(Debug) {
//cout << "List passed to parse\n";
//for(i=0; i<argc; i++) cout << i << " " << CArgs[i] << endl;
//}
Par.parseOptions(argc, CArgs);
delete[] CArgs;
if(iret != 0 || dashh.getCount() > 0) { // iret from ParseCommands
Par.displayUsage((help ? cout : oflog),false);
(help ? cout : oflog) << endl;
DisplayRinexEditUsage((help ? cout : oflog));
help = true; //return 1;
}
if (Par.hasErrors())
{
cerr << "\nErrors found in command line input:\n";
oflog << "\nErrors found in command line input:\n";
Par.dumpErrors(cerr);
Par.dumpErrors(oflog);
cerr << "...end of Errors\n\n";
oflog << "...end of Errors\n\n";
help = true;
}
// f never appears because we intercept it in PreProcessArgs
//if(dashf.getCount()) { cout << "Option f "; dashf.dumpValue(cout); }
// get log file name - pull out in PreProcessArgs
//if(dashl.getCount()) {
// values = dashl.getValue();
// LogFile = values[0];
// if(help) cout << "Output log file is: " << LogFile << endl;
//}
//if(dashh.getCount() && help)
// oflog << "Option h appears " << dashh.getCount() << " times\n";
if(dashv.getCount() && help) {
Verbose = true;
//if(help) oflog << "Option v appears " << dashv.getCount() << " times\n";
}
if(dashd.getCount() && help) {
Debug = true;
//if(help) oflog << "Option d appears " << dashd.getCount() << " times\n";
}
if(Rest.getCount() && help) {
oflog << "Remaining options:" << endl;
values = Rest.getValue();
for (i=0; i<values.size(); i++) oflog << values[i] << endl;
}
if(Verbose && help) {
oflog << "\nTokens on command line (" << Args.size() << ") are:" << endl;
for(j=0; j<Args.size(); j++) oflog << Args[j] << endl;
}
if(help) return 1;
return 0;
}
catch(Exception& e) { GPSTK_RETHROW(e); }
catch(exception& e) { Exception E("std except: "+string(e.what())); GPSTK_THROW(E); }
catch(...) { Exception e("Unknown exception"); GPSTK_THROW(e); }
return -1;
}
//------------------------------------------------------------------------------------
// Pull out --debug --verbose -f<f> and --file <f> and -l<f> --log <f> options.
void PreProcessArgs(const char *arg, vector<string>& Args) throw(Exception)
{
try {
static bool found_cfg_file=false;
static bool found_log_file=false;
if(found_cfg_file || (arg[0]=='-' && arg[1]=='f')) {
string filename(arg);
if(!found_cfg_file) filename.erase(0,2); else found_cfg_file = false;
if(Debug) cout << "Found a file of options: " << filename << endl;
ifstream infile(filename.c_str());
if(!infile) {
cout << "Error: could not open options file " << filename << endl;
return;
}
bool again_cfg_file=false;
bool again_log_file=false;
char c;
string buffer,word;
while(1) {
getline(infile,buffer);
stripTrailing(buffer,'\r');
// process the buffer before checking eof or bad b/c there can be
// a line at EOF that has no CRLF...
while(!buffer.empty()) {
word = firstWord(buffer);
if(again_cfg_file) {
word = "-f" + word;
again_cfg_file = false;
PreProcessArgs(word.c_str(),Args);
}
else if(again_log_file) {
word = "-l" + word;
again_log_file = false;
PreProcessArgs(word.c_str(),Args);
}
else if(word[0] == '#') { // skip to end of line
buffer.clear();
}
else if(word == "--file" || word == "-f")
again_cfg_file = true;
else if(word == "--log" || word == "-l")
again_log_file = true;
else if(word[0] == '"') {
word = stripFirstWord(buffer,'"');
buffer = "dummy " + buffer; // to be stripped later
PreProcessArgs(word.c_str(),Args);
}
else
PreProcessArgs(word.c_str(),Args);
word = stripFirstWord(buffer); // now remove it from buffer
}
if(infile.eof() || !infile.good()) break;
}
}
else if(found_log_file || (arg[0]=='-' && arg[1]=='l')) {
LogFile = string(arg);
if(!found_log_file) LogFile.erase(0,2); else found_log_file = false;
}
else if((arg[0]=='-' && arg[1]=='d') || string(arg)==string("--debug"))
Debug = true;
else if((arg[0]=='-' && arg[1]=='v') || string(arg)==string("--verbose"))
Verbose = true;
else if(string(arg) == "--file" || string(arg) == "-f")
found_cfg_file = true;
else if(string(arg) == "--log")
found_log_file = true;
else Args.push_back(arg);
}
catch(Exception& e) { GPSTK_RETHROW(e); }
catch(exception& e) { Exception E("std except: "+string(e.what())); GPSTK_THROW(E); }
catch(...) { Exception e("Unknown exception"); GPSTK_THROW(e); }
}
//------------------------------------------------------------------------------------
//------------------------------------------------------------------------------------
<commit_msg>One correction to the last submission for the Windows build<commit_after>#pragma ident "$Id$"
//============================================================================
//
// This file is part of GPSTk, the GPS Toolkit.
//
// The GPSTk 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
// any later version.
//
// The GPSTk 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 GPSTk; if not, write to the Free Software Foundation,
// Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
//
// Copyright 2004, The University of Texas at Austin
//
//============================================================================
/**
* @file EditRinex.cpp
* Edit a Rinex observation file using the RinexEditor in gpstk.
*/
#include "RinexObsBase.hpp"
#include "RinexObsData.hpp"
#include "RinexObsHeader.hpp"
#include "RinexObsStream.hpp"
#include "DayTime.hpp"
#include "CommandOptionParser.hpp"
#include "CommandOption.hpp"
#include "RinexUtilities.hpp"
#include "StringUtils.hpp"
#include "RinexEditor.hpp"
#include <string>
#include <vector>
#include <iostream>
#include <fstream>
#include <time.h>
using namespace std;
using namespace gpstk;
using namespace StringUtils;
//------------------------------------------------------------------------------------
// NB Version for this prgm is just the RinexEditor version.
//------------------------------------------------------------------------------------
// data input from command line
string LogFile("EditRinex.log");
bool Verbose=false,Debug=false;
string Title;
// timer
clock_t totaltime;
// log file
ofstream oflog;
//------------------------------------------------------------------------------------
// prototypes
int GetCommandLine(int argc, char **argv, RinexEditor& re) throw(Exception);
void PreProcessArgs(const char *arg, vector<string>& Args) throw(Exception);
//------------------------------------------------------------------------------------
int main(int argc, char **argv)
{
try {
totaltime = clock();
int iret;
DayTime last;
// NB. Do not instantiate editor outside main(), b/c DayTime::END_OF_TIME is a
// static const that can produce static intialization order problems under some OS.
RinexEditor REC;
// Title and description
Title = string("EditRinex, part of the GPSTK ToolKit, Ver ")
+ REC.getRinexEditVersion() + string(", Run ");
time_t timer;
struct tm *tblock;
timer = time(NULL);
tblock = localtime(&timer);
last.setYMDHMS(1900+tblock->tm_year,1+tblock->tm_mon,
tblock->tm_mday,tblock->tm_hour,tblock->tm_min,tblock->tm_sec);
Title += last.printf("%04Y/%02m/%02d %02H:%02M:%02S\n");
cout << Title;
// define extended types
iret = RegisterARLUTExtendedTypes();
if(iret) goto quit;
// get command line
iret=GetCommandLine(argc, argv, REC);
if(iret) goto quit;
iret=REC.EditFile();
if(iret) goto quit;
quit:
// compute run time
totaltime = clock()-totaltime;
oflog << "EditRinex timing: " << setprecision(3)
<< double(totaltime)/double(CLOCKS_PER_SEC) << " seconds.\n";
return iret;
}
catch(gpstk::FFStreamError& e) { cerr << e; }
catch(gpstk::Exception& e) { cerr << e; }
catch(exception& e) { cerr << e.what(); }
catch (...) { cerr << "Unknown error. Abort." << endl; }
return 1;
} // end main()
//------------------------------------------------------------------------------------
int GetCommandLine(int argc, char **argv, RinexEditor& REC) throw(Exception)
{
bool help=false;
int i,j,iret=0;
vector<string> values; // to get values found on command line
try {
// required options
// optional options
// this only so it will show up in help page...
CommandOption dashf(CommandOption::hasArgument, CommandOption::stdType,
'f',""," [-f|--file] <file> file containing more options");
CommandOption dashl(CommandOption::hasArgument, CommandOption::stdType,
0,"log"," [-l|--log] <file> Output log file name");
dashl.setMaxCount(1);
CommandOptionNoArg dashh('h', "help",
" [-h|--help] print syntax and quit.");
CommandOptionNoArg dashd('d', "debug",
" [-d|--debug] print extended output info.");
CommandOptionNoArg dashv('v', "verbose",
" [-v|--verbose] print extended output info."
"\n [<REC>] Rinex editing commands - cf. following");
// ... other options
CommandOptionRest Rest("");
CommandOptionParser Par(
" Prgm EditRinex will open and read one RINEX file, apply editing commands,\n"
" and write the modified RINEX data to another RINEX file(s).\n"
" Input is on the command line, or of the same format in a file (-f<file>).\n");
// allow user to put all options in a file
// could also scan for debug here
vector<string> Args;
for(j=1; j<argc; j++) PreProcessArgs(argv[j],Args);
if(Args.size()==0 || dashh.getCount())
help = true;
// open the log file first
oflog.open(LogFile.c_str(),ios_base::out);
if(!oflog) {
cerr << "Failed to open log file " << LogFile << endl;
return -1;
}
cout << "EditRinex output directed to log file " << LogFile << endl;
REC.oflog = &oflog;
oflog << Title;
//if(Debug) {
//cout << "List passed to REditCommandLine:\n";
//for(i=0; i<Args.size(); i++) cout << i << " " << Args[i] << endl;
// strip out the REditCmds
//}
// set up editor and pull out (delete) editing commands
REC.REVerbose = Verbose;
REC.REDebug = Debug;
REC.AddCommandLine(Args);
//if(Debug) {
//deque<REditCmd>::iterator jt=REC.Cmds.begin();
//cout << "\nHere is the list of RE cmds\n";
//while(jt != REC.Cmds.end()) { jt->Dump(cout,string("")); ++jt; }
//cout << "End of list of RE cmds" << endl;
//}
// preprocess the commands
iret = REC.ParseCommands();
if(iret) {
cerr << "EditRinex Error: no " << (iret==-1 ? "input" : "output")
<< " file specified\n";
oflog << "EditRinex Error: no " << (iret==-1 ? "input" : "output")
<< " file specified\n";
}
//if(Debug) {
//cout << "\nHere is the parsed list of RE cmds\n";
//it=REC.Cmds.begin();
//while(it != REC.Cmds.end()) { it->Dump(cout,string("")); ++it; }
//cout << "End of sorted list of RE cmds" << endl;
//}
// pass the rest
argc = Args.size()+1;
char **CArgs=new char*[argc];
if(!CArgs) { cerr << "Failed to allocate CArgs\n"; return -1; }
CArgs[0] = argv[0];
for(j=1; j<argc; j++) {
CArgs[j] = new char[Args[j-1].size()+1];
if(!CArgs[j]) { cerr << "Failed to allocate CArgs[j]\n"; return -1; }
strcpy(CArgs[j],Args[j-1].c_str());
}
//if(Debug) {
//cout << "List passed to parse\n";
//for(i=0; i<argc; i++) cout << i << " " << CArgs[i] << endl;
//}
Par.parseOptions(argc, CArgs);
delete[] CArgs;
if(iret != 0 || dashh.getCount() > 0) { // iret from ParseCommands
if(help) {
Par.displayUsage(cout,false);
cout << endl;
DisplayRinexEditUsage(cout);
}
else {
Par.displayUsage(oflog,false);
oflog << endl;
DisplayRinexEditUsage(oflog);
}
help = true; //return 1;
}
if (Par.hasErrors())
{
cerr << "\nErrors found in command line input:\n";
oflog << "\nErrors found in command line input:\n";
Par.dumpErrors(cerr);
Par.dumpErrors(oflog);
cerr << "...end of Errors\n\n";
oflog << "...end of Errors\n\n";
help = true;
}
// f never appears because we intercept it in PreProcessArgs
//if(dashf.getCount()) { cout << "Option f "; dashf.dumpValue(cout); }
// get log file name - pull out in PreProcessArgs
//if(dashl.getCount()) {
// values = dashl.getValue();
// LogFile = values[0];
// if(help) cout << "Output log file is: " << LogFile << endl;
//}
//if(dashh.getCount() && help)
// oflog << "Option h appears " << dashh.getCount() << " times\n";
if(dashv.getCount() && help) {
Verbose = true;
//if(help) oflog << "Option v appears " << dashv.getCount() << " times\n";
}
if(dashd.getCount() && help) {
Debug = true;
//if(help) oflog << "Option d appears " << dashd.getCount() << " times\n";
}
if(Rest.getCount() && help) {
oflog << "Remaining options:" << endl;
values = Rest.getValue();
for (i=0; i<values.size(); i++) oflog << values[i] << endl;
}
if(Verbose && help) {
oflog << "\nTokens on command line (" << Args.size() << ") are:" << endl;
for(j=0; j<Args.size(); j++) oflog << Args[j] << endl;
}
if(help) return 1;
return 0;
}
catch(Exception& e) { GPSTK_RETHROW(e); }
catch(exception& e) { Exception E("std except: "+string(e.what())); GPSTK_THROW(E); }
catch(...) { Exception e("Unknown exception"); GPSTK_THROW(e); }
return -1;
}
//------------------------------------------------------------------------------------
// Pull out --debug --verbose -f<f> and --file <f> and -l<f> --log <f> options.
void PreProcessArgs(const char *arg, vector<string>& Args) throw(Exception)
{
try {
static bool found_cfg_file=false;
static bool found_log_file=false;
if(found_cfg_file || (arg[0]=='-' && arg[1]=='f')) {
string filename(arg);
if(!found_cfg_file) filename.erase(0,2); else found_cfg_file = false;
if(Debug) cout << "Found a file of options: " << filename << endl;
ifstream infile(filename.c_str());
if(!infile) {
cout << "Error: could not open options file " << filename << endl;
return;
}
bool again_cfg_file=false;
bool again_log_file=false;
char c;
string buffer,word;
while(1) {
getline(infile,buffer);
stripTrailing(buffer,'\r');
// process the buffer before checking eof or bad b/c there can be
// a line at EOF that has no CRLF...
while(!buffer.empty()) {
word = firstWord(buffer);
if(again_cfg_file) {
word = "-f" + word;
again_cfg_file = false;
PreProcessArgs(word.c_str(),Args);
}
else if(again_log_file) {
word = "-l" + word;
again_log_file = false;
PreProcessArgs(word.c_str(),Args);
}
else if(word[0] == '#') { // skip to end of line
buffer.clear();
}
else if(word == "--file" || word == "-f")
again_cfg_file = true;
else if(word == "--log" || word == "-l")
again_log_file = true;
else if(word[0] == '"') {
word = stripFirstWord(buffer,'"');
buffer = "dummy " + buffer; // to be stripped later
PreProcessArgs(word.c_str(),Args);
}
else
PreProcessArgs(word.c_str(),Args);
word = stripFirstWord(buffer); // now remove it from buffer
}
if(infile.eof() || !infile.good()) break;
}
}
else if(found_log_file || (arg[0]=='-' && arg[1]=='l')) {
LogFile = string(arg);
if(!found_log_file) LogFile.erase(0,2); else found_log_file = false;
}
else if((arg[0]=='-' && arg[1]=='d') || string(arg)==string("--debug"))
Debug = true;
else if((arg[0]=='-' && arg[1]=='v') || string(arg)==string("--verbose"))
Verbose = true;
else if(string(arg) == "--file" || string(arg) == "-f")
found_cfg_file = true;
else if(string(arg) == "--log")
found_log_file = true;
else Args.push_back(arg);
}
catch(Exception& e) { GPSTK_RETHROW(e); }
catch(exception& e) { Exception E("std except: "+string(e.what())); GPSTK_THROW(E); }
catch(...) { Exception e("Unknown exception"); GPSTK_THROW(e); }
}
//------------------------------------------------------------------------------------
//------------------------------------------------------------------------------------
<|endoftext|> |
<commit_before>// TasksFrame.cpp : implmentation of the CTasksFrame class
//
/////////////////////////////////////////////////////////////////////////////
#include "stdafx.h"
#include "resource.h"
#include "AboutDlg.h"
#include "ConnectionDlg.h"
#include "TasksView.h"
#include "TasksFrame.h"
#include <jira/jira.hpp>
#include <jira/server.hpp>
#include <net/utf8.hpp>
#include <net/xhr.hpp>
#include <sstream>
#include <thread>
#include "AppSettings.h"
#include "wincrypt.h"
#pragma comment(lib, "crypt32.lib")
std::string contents(LPCWSTR path)
{
std::unique_ptr<FILE, decltype(&fclose)> f{ _wfopen(path, L"r"), fclose };
if (!f)
return std::string();
std::string out;
char buffer[8192];
int read = 0;
while ((read = fread(buffer, 1, sizeof(buffer), f.get())) > 0)
out.append(buffer, buffer + read);
return out;
}
void print(FILE* f, const std::string& s)
{
fwrite(s.c_str(), 1, s.length(), f);
}
void print(FILE* f, const char* s)
{
if (!s)
return;
fwrite(s, 1, strlen(s), f);
}
template <size_t length>
void print(FILE* f, const char(&s)[length])
{
if (!s)
return;
fwrite(s, 1, strlen(s), f);
}
BOOL CTasksFrame::PreTranslateMessage(MSG* pMsg)
{
if (CFameSuper::PreTranslateMessage(pMsg))
return TRUE;
return m_view.PreTranslateMessage(pMsg);
}
BOOL CTasksFrame::OnIdle()
{
UIUpdateToolBar();
return FALSE;
}
LRESULT CTasksFrame::OnCreate(UINT /*uMsg*/, WPARAM /*wParam*/, LPARAM /*lParam*/, BOOL& /*bHandled*/)
{
// Check if Common Controls 6.0 are used. If yes, use 32-bit (alpha) images
// for the toolbar and command bar. If not, use the old, 4-bit images.
UINT uResID = IDR_MAINFRAME_OLD;
DWORD dwMajor = 0;
DWORD dwMinor = 0;
HRESULT hRet = AtlGetCommCtrlVersion(&dwMajor, &dwMinor);
if (SUCCEEDED(hRet) && dwMajor >= 6)
uResID = IDR_MAINFRAME;
CreateSimpleToolBar(uResID);
m_view.m_model = m_model;
m_hWndClient = m_view.Create(m_hWnd, rcDefault, NULL, WS_CHILD | WS_VISIBLE | WS_CLIPSIBLINGS | WS_CLIPCHILDREN, 0);
m_font = AtlCreateControlFont();
m_view.SetFont(m_font);
// register object for message filtering and idle updates
CMessageLoop* pLoop = _Module.GetMessageLoop();
ATLASSERT(pLoop != NULL);
pLoop->AddMessageFilter(this);
pLoop->AddIdleHandler(this);
m_taskIcon.Install(m_hWnd, 1, IDR_TASKBAR);
auto hwnd = m_hWnd;
m_model->startup();
return 0;
}
LRESULT CTasksFrame::OnDestroy(UINT /*uMsg*/, WPARAM /*wParam*/, LPARAM /*lParam*/, BOOL& bHandled)
{
// unregister message filtering and idle updates
CMessageLoop* pLoop = _Module.GetMessageLoop();
ATLASSERT(pLoop != NULL);
pLoop->RemoveMessageFilter(this);
pLoop->RemoveIdleHandler(this);
bHandled = FALSE;
return 1;
}
LRESULT CTasksFrame::OnTaskIconClick(LPARAM /*uMsg*/, BOOL& /*bHandled*/)
{
return 0;
}
LRESULT CTasksFrame::OnFileExit(WORD /*wNotifyCode*/, WORD /*wID*/, HWND /*hWndCtl*/, BOOL& /*bHandled*/)
{
PostMessage(WM_CLOSE);
return 0;
}
LRESULT CTasksFrame::OnFileNew(WORD /*wNotifyCode*/, WORD /*wID*/, HWND /*hWndCtl*/, BOOL& /*bHandled*/)
{
CConnectionDlg dlg;
dlg.DoModal();
return 0;
}
LRESULT CTasksFrame::OnTasksRefersh(WORD /*wNotifyCode*/, WORD /*wID*/, HWND /*hWndCtl*/, BOOL& /*bHandled*/)
{
auto local = m_model->servers();
for (auto server : local) {
std::thread{ [server] {
server->loadFields();
server->refresh();
} }.detach();
}
return 0;
}
LRESULT CTasksFrame::OnAppAbout(WORD /*wNotifyCode*/, WORD /*wID*/, HWND /*hWndCtl*/, BOOL& /*bHandled*/)
{
CAboutDlg dlg;
dlg.DoModal();
return 0;
}
<commit_msg>Adding a connection from the dialog<commit_after>// TasksFrame.cpp : implmentation of the CTasksFrame class
//
/////////////////////////////////////////////////////////////////////////////
#include "stdafx.h"
#include "resource.h"
#include "AboutDlg.h"
#include "ConnectionDlg.h"
#include "TasksView.h"
#include "TasksFrame.h"
#include <jira/jira.hpp>
#include <jira/server.hpp>
#include <net/utf8.hpp>
#include <net/xhr.hpp>
#include <sstream>
#include <thread>
#include "AppSettings.h"
#include "wincrypt.h"
#pragma comment(lib, "crypt32.lib")
std::string contents(LPCWSTR path)
{
std::unique_ptr<FILE, decltype(&fclose)> f{ _wfopen(path, L"r"), fclose };
if (!f)
return std::string();
std::string out;
char buffer[8192];
int read = 0;
while ((read = fread(buffer, 1, sizeof(buffer), f.get())) > 0)
out.append(buffer, buffer + read);
return out;
}
void print(FILE* f, const std::string& s)
{
fwrite(s.c_str(), 1, s.length(), f);
}
void print(FILE* f, const char* s)
{
if (!s)
return;
fwrite(s, 1, strlen(s), f);
}
template <size_t length>
void print(FILE* f, const char(&s)[length])
{
if (!s)
return;
fwrite(s, 1, strlen(s), f);
}
BOOL CTasksFrame::PreTranslateMessage(MSG* pMsg)
{
if (CFameSuper::PreTranslateMessage(pMsg))
return TRUE;
return m_view.PreTranslateMessage(pMsg);
}
BOOL CTasksFrame::OnIdle()
{
UIUpdateToolBar();
return FALSE;
}
LRESULT CTasksFrame::OnCreate(UINT /*uMsg*/, WPARAM /*wParam*/, LPARAM /*lParam*/, BOOL& /*bHandled*/)
{
// Check if Common Controls 6.0 are used. If yes, use 32-bit (alpha) images
// for the toolbar and command bar. If not, use the old, 4-bit images.
UINT uResID = IDR_MAINFRAME_OLD;
DWORD dwMajor = 0;
DWORD dwMinor = 0;
HRESULT hRet = AtlGetCommCtrlVersion(&dwMajor, &dwMinor);
if (SUCCEEDED(hRet) && dwMajor >= 6)
uResID = IDR_MAINFRAME;
CreateSimpleToolBar(uResID);
m_view.m_model = m_model;
m_hWndClient = m_view.Create(m_hWnd, rcDefault, NULL, WS_CHILD | WS_VISIBLE | WS_CLIPSIBLINGS | WS_CLIPCHILDREN, 0);
m_font = AtlCreateControlFont();
m_view.SetFont(m_font);
// register object for message filtering and idle updates
CMessageLoop* pLoop = _Module.GetMessageLoop();
ATLASSERT(pLoop != NULL);
pLoop->AddMessageFilter(this);
pLoop->AddIdleHandler(this);
m_taskIcon.Install(m_hWnd, 1, IDR_TASKBAR);
auto hwnd = m_hWnd;
m_model->startup();
return 0;
}
LRESULT CTasksFrame::OnDestroy(UINT /*uMsg*/, WPARAM /*wParam*/, LPARAM /*lParam*/, BOOL& bHandled)
{
// unregister message filtering and idle updates
CMessageLoop* pLoop = _Module.GetMessageLoop();
ATLASSERT(pLoop != NULL);
pLoop->RemoveMessageFilter(this);
pLoop->RemoveIdleHandler(this);
bHandled = FALSE;
return 1;
}
LRESULT CTasksFrame::OnTaskIconClick(LPARAM /*uMsg*/, BOOL& /*bHandled*/)
{
return 0;
}
LRESULT CTasksFrame::OnFileExit(WORD /*wNotifyCode*/, WORD /*wID*/, HWND /*hWndCtl*/, BOOL& /*bHandled*/)
{
PostMessage(WM_CLOSE);
return 0;
}
LRESULT CTasksFrame::OnFileNew(WORD /*wNotifyCode*/, WORD /*wID*/, HWND /*hWndCtl*/, BOOL& /*bHandled*/)
{
CConnectionDlg dlg;
if (dlg.DoModal() == IDOK) {
auto conn = std::make_shared<jira::server>(dlg.serverName, dlg.userName, dlg.userPassword, dlg.serverUrl, jira::search_def{});
m_model->add(conn);
};
return 0;
}
LRESULT CTasksFrame::OnTasksRefersh(WORD /*wNotifyCode*/, WORD /*wID*/, HWND /*hWndCtl*/, BOOL& /*bHandled*/)
{
auto local = m_model->servers();
for (auto server : local) {
std::thread{ [server] {
server->loadFields();
server->refresh();
} }.detach();
}
return 0;
}
LRESULT CTasksFrame::OnAppAbout(WORD /*wNotifyCode*/, WORD /*wID*/, HWND /*hWndCtl*/, BOOL& /*bHandled*/)
{
CAboutDlg dlg;
dlg.DoModal();
return 0;
}
<|endoftext|> |
<commit_before>#include <string>
#include <fstream>
#include <sstream>
#include <streambuf>
#include "3rdparty/nlohmann/json.h"
#include "appc/schema/image.h"
#include "appc/schema/container.h"
using Json = nlohmann::json;
int dumpAIM(const Json& json);
int dumpCRM(const Json& json);
int main(int args, char** argv) {
if (args < 2) {
std::cerr << "Usage: " << argv[0] << " <image or container manifest to parse>" << std::endl;
return EXIT_FAILURE;
}
std::ifstream f(argv[1]);
if (!f) {
std::cerr << "Could not open " << argv[1] << std::endl;
return EXIT_FAILURE;
}
std::stringstream buffer {};
buffer << f.rdbuf();
std::string json_str { buffer.str() };
// Will throw invalid_argument if not valid JSON
Json manifest = Json::parse(json_str);
if (manifest["acKind"] == "ContainerRuntimeManifest") {
return dumpCRM(manifest);
}
else if (manifest["acKind"] == "ImageManifest") {
return dumpAIM(manifest);
}
else {
std::cerr << "Unknown manifest type." << std::endl;
return EXIT_FAILURE;
}
return EXIT_SUCCESS;
}
int dumpAIM(const Json& json)
{
auto manifest_try = appc::schema::ImageManifest::from_json(json);
if (!manifest_try) {
std::cerr << "Could not parse manifest: " << std::endl;
std::cerr << manifest_try.failure_reason() << std::endl;
return EXIT_FAILURE;
}
appc::schema::ImageManifest manifest = *manifest_try;
std::cout << "Kind: " << manifest.ac_kind.value << std::endl;
std::cout << "Version: " << manifest.ac_version.value << std::endl;
std::cout << "Image Name: " << manifest.image_name.value << std::endl;
std::cout << "Labels:" << std::endl;
for (auto& label : manifest.labels.array) {
std::cout << " " << label.name << " -> " << label.value << std::endl;
}
std::cout << "App:" << std::endl;
std::cout << " Exec:" << std::endl;
for (auto& arg : manifest.app.exec.array) {
std::cout << " " << arg.value << std::endl;
}
std::cout << " User: " << manifest.app.user.value << std::endl;
std::cout << " Group: " << manifest.app.group.value << std::endl;
std::cout << " Event Handlers:" << std::endl;
for (auto& handler : manifest.app.event_handlers.array) {
std::cout << " " << handler.name.value << std::endl;
for (auto& arg : handler.exec.array) {
std::cout << " " << arg.value << std::endl;
}
}
std::cout << " Isolators:" << std::endl;
for (auto& isolator : manifest.app.isolators.array) {
std::cout << " " << isolator.name << " -> " << isolator.value << std::endl;
}
std::cout << " Mount Points:" << std::endl;
for (auto& mount : manifest.app.mount_points.array) {
std::cout << " " << mount.name << std::endl;
std::cout << " Path: " << mount.path << std::endl;
std::cout << " Read Only: " << mount.readOnly << std::endl;
}
std::cout << "Dependencies:" << std::endl;
for (auto& dep : manifest.dependencies.array) {
std::cout << " " << dep.app_name.value << std::endl;
std::cout << " Image ID: " << dep.image_id.value << std::endl;
std::cout << " Labels:" << std::endl;
for (auto& label : dep.labels.array) {
std::cout << " " << label.name << " -> " << label.value << std::endl;
}
}
std::cout << "Path Whitelist:" << std::endl;
for (auto& path : manifest.path_whitelist.array) {
std::cout << " " << path.value << std::endl;
}
std::cout << "Annotations:" << std::endl;
for (auto& annotation : manifest.annotations.array) {
std::cout << " " << annotation.name << " -> " << annotation.value << std::endl;
}
return EXIT_SUCCESS;
}
int dumpCRM(const Json& json)
{
auto manifest_try = appc::schema::ContainerRuntimeManifest::from_json(json);
if (!manifest_try) {
std::cerr << "Could not parse manifest: " << std::endl;
std::cerr << manifest_try.failure_reason() << std::endl;
return EXIT_FAILURE;
}
appc::schema::ContainerRuntimeManifest manifest = *manifest_try;
auto valid = manifest.validate();
if (!valid) {
std::cerr << "Manifest is invalid: " << valid.message << std::endl;
return EXIT_FAILURE;
}
std::cout << "Kind: " << manifest.ac_kind.value << std::endl;
std::cout << "Version: " << manifest.ac_version.value << std::endl;
std::cout << "UUID: " << manifest.uuid.value << std::endl;
std::cout << "Apps:" << std::endl;
for (auto& app : manifest.app_refs.array) {
std::cout << " ImageID: " << app.image_id.value << std::endl;
if (app.app_name) {
std::cout << " App: " << app.app_name->value << std::endl;
}
std::cout << " Isolators:" << std::endl;
if (app.isolators) {
auto& isolators = *app.isolators;
for (auto& isolator : isolators.array) {
std::cout << " " << isolator.name << " -> " << isolator.value << std::endl;
}
}
std::cout << " Annotations:" << std::endl;
if (app.annotations) {
auto& annotations = *app.annotations;
for (auto& annotation : annotations.array) {
std::cout << " " << annotation.name << " -> " << annotation.value << std::endl;
}
}
}
if (manifest.volumes) {
auto volumes = *manifest.volumes;
std::cout << "Volumes:" << std::endl;
for (auto& volume : volumes.array) {
std::cout << " Kind: " << volume.kind.value << std::endl;
std::cout << " Fulfills: " << std::endl;
for (auto& target : volume.fulfills.array) {
std::cout << " " << target.value << std::endl;
}
}
}
else {
std::cout << "No Volumes" << std::endl;
}
if (manifest.isolators) {
auto isolators = *manifest.isolators;
std::cout << "Isolators:" << std::endl;
for (auto& isolator : isolators.array) {
std::cout << " " << isolator.name << " -> " << isolator.value << std::endl;
}
}
else {
std::cout << "No Isolators" << std::endl;
}
if (manifest.annotations) {
auto annotations = *manifest.annotations;
std::cout << "Annotations:" << std::endl;
for (auto& annotation : annotations.array) {
std::cout << " " << annotation.name << " -> " << annotation.value << std::endl;
}
}
else {
std::cout << "No Annotations" << std::endl;
}
return EXIT_SUCCESS;
}
<commit_msg>examples: Update examples/parse with optional fields.<commit_after>#include <string>
#include <fstream>
#include <sstream>
#include <streambuf>
#include "3rdparty/nlohmann/json.h"
#include "appc/schema/image.h"
#include "appc/schema/container.h"
using Json = nlohmann::json;
int dumpAIM(const Json& json);
int dumpCRM(const Json& json);
// There isn't any real point to dumpAIM and dumpCRM other than anillustration of how to parse
// and access a manifest.
int main(int args, char** argv) {
if (args < 2) {
std::cerr << "Usage: " << argv[0] << " <image or container manifest to parse>" << std::endl;
return EXIT_FAILURE;
}
std::ifstream f(argv[1]);
if (!f) {
std::cerr << "Could not open " << argv[1] << std::endl;
return EXIT_FAILURE;
}
std::stringstream buffer {};
buffer << f.rdbuf();
std::string json_str { buffer.str() };
// Will throw invalid_argument if not valid JSON
Json manifest = Json::parse(json_str);
if (manifest["acKind"] == "ContainerRuntimeManifest") {
return dumpCRM(manifest);
}
else if (manifest["acKind"] == "ImageManifest") {
return dumpAIM(manifest);
}
else {
std::cerr << "Unknown manifest type." << std::endl;
return EXIT_FAILURE;
}
return EXIT_SUCCESS;
}
int dumpAIM(const Json& json)
{
auto manifest_try = appc::schema::ImageManifest::from_json(json);
if (!manifest_try) {
std::cerr << "Could not parse manifest: " << std::endl;
std::cerr << manifest_try.failure_reason() << std::endl;
return EXIT_FAILURE;
}
appc::schema::ImageManifest manifest = *manifest_try;
std::cout << "Kind: " << manifest.ac_kind.value << std::endl;
std::cout << "Version: " << manifest.ac_version.value << std::endl;
std::cout << "Name: " << manifest.name.value << std::endl;
if (manifest.labels) {
auto labels = *manifest.labels;
std::cout << "Labels:" << std::endl;
for (auto& label : labels.array) {
std::cout << " " << label.name << " -> " << label.value << std::endl;
}
}
if (manifest.app) {
auto app = *manifest.app;
std::cout << "App:" << std::endl;
std::cout << " Exec:" << std::endl;
for (auto& arg : app.exec.array) {
std::cout << " " << arg.value << std::endl;
}
std::cout << " User: " << app.user.value << std::endl;
std::cout << " Group: " << app.group.value << std::endl;
if (app.event_handlers) {
auto event_handlers = *app.event_handlers;
std::cout << " Event Handlers:" << std::endl;
for (auto& handler : event_handlers.array) {
std::cout << " " << handler.name.value << std::endl;
for (auto& arg : handler.exec.array) {
std::cout << " " << arg.value << std::endl;
}
}
}
if (app.isolators) {
auto isolators = *app.isolators;
std::cout << " Isolators:" << std::endl;
for (auto& isolator : isolators.array) {
std::cout << " " << isolator.name << " -> " << isolator.value << std::endl;
}
}
if (app.mount_points) {
auto mount_points = *app.mount_points;
std::cout << " Mount Points:" << std::endl;
for (auto& mount : mount_points.array) {
std::cout << " " << mount.name << std::endl;
std::cout << " Path: " << mount.path << std::endl;
std::cout << " Read Only: " << mount.readOnly << std::endl;
}
}
}
if (manifest.dependencies) {
auto dependencies = *manifest.dependencies;
std::cout << "Dependencies:" << std::endl;
for (auto& dep : dependencies.array) {
std::cout << " " << dep.app_name.value << std::endl;
if (dep.image_id) {
auto image_id = *dep.image_id;
std::cout << " Image ID: " << image_id.value << std::endl;
}
if (dep.labels) {
auto labels = *dep.labels;
std::cout << " Labels:" << std::endl;
for (auto& label : labels.array) {
std::cout << " " << label.name << " -> " << label.value << std::endl;
}
}
}
}
if (manifest.path_whitelist) {
auto path_whitelist = *manifest.path_whitelist;
std::cout << "Path Whitelist:" << std::endl;
for (auto& path : path_whitelist.array) {
std::cout << " " << path.value << std::endl;
}
}
if (manifest.annotations) {
auto annotations = *manifest.annotations;
std::cout << "Annotations:" << std::endl;
for (auto& annotation : annotations.array) {
std::cout << " " << annotation.name << " -> " << annotation.value << std::endl;
}
}
return EXIT_SUCCESS;
}
int dumpCRM(const Json& json)
{
auto manifest_try = appc::schema::ContainerRuntimeManifest::from_json(json);
if (!manifest_try) {
std::cerr << "Could not parse manifest: " << std::endl;
std::cerr << manifest_try.failure_reason() << std::endl;
return EXIT_FAILURE;
}
appc::schema::ContainerRuntimeManifest manifest = *manifest_try;
auto valid = manifest.validate();
if (!valid) {
std::cerr << "Manifest is invalid: " << valid.message << std::endl;
return EXIT_FAILURE;
}
std::cout << "Kind: " << manifest.ac_kind.value << std::endl;
std::cout << "Version: " << manifest.ac_version.value << std::endl;
std::cout << "UUID: " << manifest.uuid.value << std::endl;
std::cout << "Apps:" << std::endl;
for (auto& app : manifest.app_refs.array) {
std::cout << " ImageID: " << app.image_id.value << std::endl;
if (app.app_name) {
std::cout << " App: " << app.app_name->value << std::endl;
}
std::cout << " Isolators:" << std::endl;
if (app.isolators) {
auto& isolators = *app.isolators;
for (auto& isolator : isolators.array) {
std::cout << " " << isolator.name << " -> " << isolator.value << std::endl;
}
}
std::cout << " Annotations:" << std::endl;
if (app.annotations) {
auto& annotations = *app.annotations;
for (auto& annotation : annotations.array) {
std::cout << " " << annotation.name << " -> " << annotation.value << std::endl;
}
}
}
if (manifest.volumes) {
auto volumes = *manifest.volumes;
std::cout << "Volumes:" << std::endl;
for (auto& volume : volumes.array) {
std::cout << " Kind: " << volume.kind.value << std::endl;
std::cout << " Fulfills: " << std::endl;
for (auto& target : volume.fulfills.array) {
std::cout << " " << target.value << std::endl;
}
}
}
else {
std::cout << "No Volumes" << std::endl;
}
if (manifest.isolators) {
auto isolators = *manifest.isolators;
std::cout << "Isolators:" << std::endl;
for (auto& isolator : isolators.array) {
std::cout << " " << isolator.name << " -> " << isolator.value << std::endl;
}
}
else {
std::cout << "No Isolators" << std::endl;
}
if (manifest.annotations) {
auto annotations = *manifest.annotations;
std::cout << "Annotations:" << std::endl;
for (auto& annotation : annotations.array) {
std::cout << " " << annotation.name << " -> " << annotation.value << std::endl;
}
}
else {
std::cout << "No Annotations" << std::endl;
}
return EXIT_SUCCESS;
}
<|endoftext|> |
<commit_before>/*
* This file is part of meego-keyboard
*
* Copyright (C) 2010-2011 Nokia Corporation and/or its subsidiary(-ies). All rights reserved.
*
* Contact: Mohammad Anwari <Mohammad.Anwari@nokia.com>
*
* Redistribution and use in source and binary forms, with or without modification,
* are permitted provided that the following conditions are met:
*
* Redistributions of source code must retain the above copyright notice, this list
* of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice, this list
* of conditions and the following disclaimer in the documentation and/or other materials
* provided with the distribution.
* Neither the name of Nokia Corporation nor the names of its contributors may be
* used to endorse or promote products derived from this software without specific
* prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL
* THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include "horizontalswitcher.h"
#include "mimabstractkey.h"
#include "mimabstractkeyarea.h"
#include "layoutpanner.h"
#include <QGraphicsSceneResizeEvent>
#include <QGraphicsScene>
#include <QDebug>
namespace
{
const int SwitchDuration = 500;
const int SwitchFrames = 300;
void setHorizontalFlickRecognition(QGraphicsWidget *widget, bool recognition)
{
MImAbstractKeyArea * const keyArea = qobject_cast<MImAbstractKeyArea *>(widget);
if (keyArea) {
keyArea->enableHorizontalFlick(recognition);
}
}
}
HorizontalSwitcher::HorizontalSwitcher(QGraphicsItem *parent) :
QGraphicsWidget(parent),
currentIndex(-1),
animTimeLine(SwitchDuration),
loopingEnabled(false),
playAnimations(true),
m_enableSinglePageFlick(true)
{
setFlag(QGraphicsItem::ItemHasNoContents); // doesn't paint itself anything
setObjectName("HorizontalSwitcher");
animTimeLine.setFrameRange(0, SwitchFrames);
enterAnim.setTimeLine(&animTimeLine);
leaveAnim.setTimeLine(&animTimeLine);
connect(&animTimeLine, SIGNAL(finished()), this, SLOT(finishAnimation()));
}
HorizontalSwitcher::~HorizontalSwitcher()
{
if (isRunning())
finishAnimation();
// Delete all widgets that were not removed with removeWidget().
qDeleteAll(slides);
slides.clear();
}
void HorizontalSwitcher::switchTo(SwitchDirection direction)
{
if (isRunning()) {
finishAnimation();
}
if (slides.count() < 2 ||
(!loopingEnabled && isAtBoundary(direction))) {
return;
}
int newIndex = (direction == Left ? (currentIndex - 1)
: (currentIndex + 1) % slides.count());
if (newIndex < 0) {
newIndex += slides.count();
}
QGraphicsWidget *currentWidget = slides.at(currentIndex);
QGraphicsWidget *nextWidget = slides.at(newIndex);
// Current item is about to leave
leaveAnim.setItem(currentWidget);
currentWidget->setEnabled(false);
// New item is about to enter
enterAnim.setItem(nextWidget);
nextWidget->setEnabled(false);
// reset current and next key area
MImAbstractKeyArea *const currentKeyArea = dynamic_cast<MImAbstractKeyArea *>(currentWidget);
if (currentKeyArea) {
currentKeyArea->resetActiveKeys();
}
MImAbstractKeyArea *const nextKeyArea = dynamic_cast<MImAbstractKeyArea *>(nextWidget);
if (nextKeyArea) {
nextKeyArea->resetActiveKeys();
}
// Try to fit current size.
nextWidget->resize(size());
currentIndex = newIndex;
emit switchStarting(currentIndex, newIndex);
emit switchStarting(currentWidget, nextWidget);
if (!playAnimations) {
nextWidget->setPos(0.0, 0.0);
nextWidget->show();
finishAnimation();
} else {
nextWidget->setPos((direction == Right ? size().width()
: -(nextWidget->size().width())), 0.0);
enterAnim.setPosAt(0.0, nextWidget->pos());
enterAnim.setPosAt(1.0, QPointF(0.0, 0.0));
leaveAnim.setPosAt(0.0, currentWidget->pos());
leaveAnim.setPosAt(1.0, QPointF((direction == Right ? -(currentWidget->size().width())
: size().width()), 0.0));
// Enable painting background in black during playing animations.
setFlag(QGraphicsItem::ItemHasNoContents, false);
nextWidget->show();
animTimeLine.start();
}
}
bool HorizontalSwitcher::isAtBoundary(SwitchDirection direction) const
{
return (currentIndex == (direction == Left ? 0
: slides.count() - 1));
}
void HorizontalSwitcher::setCurrent(QGraphicsWidget *widget)
{
if (!widget || !slides.contains(widget)) {
qWarning() << "HorizontalSwitcher::setCurrent() - "
<< "Cannot set switcher to specified widget. Add widget to switcher first?";
return;
}
setCurrent(slides.indexOf(widget));
}
void HorizontalSwitcher::setCurrent(int index)
{
if (isValidIndex(index) && index != currentIndex) {
int oldIndex = -1;
QGraphicsWidget *old = 0;
if (isValidIndex(currentIndex)) {
oldIndex = currentIndex;
old = slides.at(currentIndex);
}
currentIndex = index;
QGraphicsWidget *widget = slides.at(index);
widget->setPos(0, 0);
if (widget->preferredHeight() != size().height())
widget->resize(QSizeF(size().width(), widget->preferredHeight()));
else
widget->resize(size());
widget->setEnabled(true);
widget->show();
// Ultimately might lead to a reaction map update in MKeyboardHost,
// has no other purpose:
emit switchDone(old, widget);
updateGeometry();
if (old) {
old->hide();
MImAbstractKeyArea *const keyArea = dynamic_cast<MImAbstractKeyArea *>(old);
if (keyArea) {
keyArea->modifiersChanged(false);
keyArea->resetActiveKeys();
}
}
}
}
int HorizontalSwitcher::current() const
{
return (slides.isEmpty() ? -1 : currentIndex);
}
QGraphicsWidget *HorizontalSwitcher::currentWidget() const
{
return (current() < 0 ? 0
: slides.at(currentIndex));
}
QGraphicsWidget *HorizontalSwitcher::widget(int index)
{
return (isValidIndex(index) ? slides.at(index)
: 0);
}
int HorizontalSwitcher::indexOf(QGraphicsWidget *widget) const
{
return slides.indexOf(widget);
}
int HorizontalSwitcher::count() const
{
return slides.count();
}
bool HorizontalSwitcher::isRunning() const
{
return (animTimeLine.state() == QTimeLine::Running);
}
void HorizontalSwitcher::setLooping(bool enable)
{
loopingEnabled = enable;
}
void HorizontalSwitcher::setDuration(int ms)
{
animTimeLine.setDuration(ms);
animTimeLine.setFrameRange(0, ms * SwitchFrames / qMax(1, SwitchDuration));
}
void HorizontalSwitcher::setEasingCurve(const QEasingCurve &curve)
{
animTimeLine.setEasingCurve(curve);
}
void HorizontalSwitcher::addWidget(QGraphicsWidget *widget)
{
if (!widget) {
return;
}
widget->setParentItem(this);
widget->setPreferredWidth(size().width());
slides.append(widget);
widget->hide();
// HS was empty before, this was the first widget added:
if (slides.size() == 1) {
setCurrent(0);
}
switch(count()) {
case 1:
setHorizontalFlickRecognition(widget, m_enableSinglePageFlick);
break;
case 2:
setHorizontalFlickRecognition(slides.at(0), true);
setHorizontalFlickRecognition(slides.at(1), true);
break;
default:
setHorizontalFlickRecognition(widget, true);
break;
}
}
void HorizontalSwitcher::removeAll()
{
foreach(QGraphicsWidget * slide, slides) {
slide->setParentItem(0);
if (slide->scene()) {
slide->scene()->removeItem(slide);
}
}
slides.clear();
currentIndex = -1;
updateGeometry();
}
void HorizontalSwitcher::deleteAll()
{
qDeleteAll(slides);
slides.clear();
currentIndex = -1;
updateGeometry();
}
void HorizontalSwitcher::resizeEvent(QGraphicsSceneResizeEvent *event)
{
QGraphicsWidget *widget = currentWidget();
if (widget) {
widget->resize(event->newSize());
}
}
QSizeF HorizontalSwitcher::sizeHint(Qt::SizeHint which, const QSizeF &constraint) const
{
// return the size hint of the currently visible widget
QGraphicsWidget *widget = currentWidget();
QSizeF hint;
if (widget) {
hint = widget->effectiveSizeHint(which, constraint);
} else {
hint = QGraphicsWidget::sizeHint(which, constraint);
}
return hint;
}
void HorizontalSwitcher::finishAnimation()
{
int oldIndex = -1;
// Hide old item
QGraphicsWidget *old = static_cast<QGraphicsWidget *>(leaveAnim.item());
if (old) {
oldIndex = slides.indexOf(old);
old->setEnabled(true);
old->hide();
}
// Clear transformations
leaveAnim.clear();
enterAnim.clear();
animTimeLine.stop();
// Restore original painting flag.
setFlag(QGraphicsItem::ItemHasNoContents);
// Discard cached sizehint info before telling that the switch is done.
updateGeometry();
if (currentWidget()) {
currentWidget()->setEnabled(true);
}
emit switchDone(oldIndex, currentIndex);
emit switchDone(old, slides.at(currentIndex));
}
void HorizontalSwitcher::updatePanningSwitchIncomingWidget(PanGesture::PanDirection direction)
{
qDebug() << __PRETTY_FUNCTION__
<< ", CURRENT INDEX:" << currentIndex;
int newIndex = (direction == PanGesture::PanLeft)
? (currentIndex - 1)
: (currentIndex + 1) % slides.count();
if (newIndex < 0) {
newIndex += slides.count();
}
QGraphicsWidget *nextWidget = slides.at(newIndex);
MImAbstractKeyArea *const nextKeyArea = dynamic_cast<MImAbstractKeyArea *>(nextWidget);
if (nextKeyArea) {
nextKeyArea->resetActiveKeys();
}
// Try to fit current size.
nextWidget->resize(size());
if (nextWidget->pos().y() + nextWidget->size().height() < size().height()) {
nextWidget->setPos(0.0, (size().height() - nextWidget->size().height()));
}
LayoutPanner::instance().addIncomingWidget(direction, nextWidget);
}
void HorizontalSwitcher::prepareLayoutSwitch(PanGesture::PanDirection direction)
{
SwitchDirection switchDirection = direction == PanGesture::PanRight ? Left : Right;
QGraphicsWidget *currentWidget = slides.at(currentIndex);
// reset current and next key area
MImAbstractKeyArea *const currentKeyArea = dynamic_cast<MImAbstractKeyArea *>(currentWidget);
if (currentKeyArea) {
currentKeyArea->hidePopup();
currentKeyArea->resetActiveKeys();
currentKeyArea->setEnabled(false);
}
LayoutPanner::instance().addOutgoingWidget(currentWidget);
// if it is switching plugin, don't need next widget.
if (LayoutPanner::instance().isSwitchingPlugin())
return;
int newIndex = (switchDirection == Left ? (currentIndex - 1)
: (currentIndex + 1) % slides.count());
if (newIndex < 0) {
newIndex += slides.count();
}
QGraphicsWidget *nextWidget = slides.at(newIndex);
emit switchStarting(currentIndex, newIndex);
emit switchStarting(currentWidget, nextWidget);
}
void HorizontalSwitcher::finalizeLayoutSwitch(PanGesture::PanDirection direction)
{
qDebug() << __PRETTY_FUNCTION__ << direction;
const int oldIndex = currentIndex;
int newIndex = currentIndex;
switch (direction) {
case PanGesture::PanLeft:
newIndex = (currentIndex + 1) % slides.count();
break;
case PanGesture::PanRight:
newIndex = (currentIndex - 1);
if (newIndex < 0)
newIndex += slides.count();
break;
case PanGesture::PanNone:
default:
// canceled and no change.
break;
}
// re-enable old keyarea
slides.at(oldIndex)->setEnabled(true);
qDebug() << ", pan from:" << oldIndex << " to :" << newIndex;
if (newIndex != oldIndex) {
emit switchDone(slides.at(oldIndex), slides.at(newIndex));
emit layoutChanged(newIndex);
}
}
bool HorizontalSwitcher::isValidIndex(int index) const
{
return (index >= 0 && index < slides.size());
}
bool HorizontalSwitcher::isAnimationEnabled() const
{
return playAnimations;
}
void HorizontalSwitcher::setAnimationEnabled(bool enabled)
{
if (playAnimations != enabled) {
if (isRunning())
finishAnimation();
playAnimations = enabled;
}
}
void HorizontalSwitcher::setKeyOverrides(const QMap<QString, QSharedPointer<MKeyOverride> > &overrides)
{
for (int i = 0; i < count(); ++i) {
MImAbstractKeyArea *mainKba = qobject_cast<MImAbstractKeyArea *>(widget(i));
if (mainKba) {
mainKba->setKeyOverrides(overrides);
}
}
}
void HorizontalSwitcher::setContentType(M::TextContentType type)
{
foreach(QGraphicsWidget *slide, slides) {
MImAbstractKeyArea *mainKba = qobject_cast<MImAbstractKeyArea *>(slide);
if (mainKba) {
mainKba->setContentType(type);
}
}
}
void HorizontalSwitcher::paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget)
{
Q_UNUSED(option);
Q_UNUSED(widget);
// Make the background black during playing animations.
painter->fillRect(rect(), Qt::black);
}
void HorizontalSwitcher::enableSinglePageHorizontalFlick(bool enable)
{
if (m_enableSinglePageFlick == enable) {
return;
}
m_enableSinglePageFlick = enable;
updateHorizontalFlickRecognition();
}
void HorizontalSwitcher::updateHorizontalFlickRecognition()
{
const bool enable = (m_enableSinglePageFlick || (count() > 1));
foreach(QGraphicsWidget *slide, slides) {
MImAbstractKeyArea *keyArea = qobject_cast<MImAbstractKeyArea *>(slide);
if (keyArea) {
keyArea->enableHorizontalFlick(enable);
}
}
}
<commit_msg>Fixes: alignment issue for next incoming layout during panning<commit_after>/*
* This file is part of meego-keyboard
*
* Copyright (C) 2010-2011 Nokia Corporation and/or its subsidiary(-ies). All rights reserved.
*
* Contact: Mohammad Anwari <Mohammad.Anwari@nokia.com>
*
* Redistribution and use in source and binary forms, with or without modification,
* are permitted provided that the following conditions are met:
*
* Redistributions of source code must retain the above copyright notice, this list
* of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice, this list
* of conditions and the following disclaimer in the documentation and/or other materials
* provided with the distribution.
* Neither the name of Nokia Corporation nor the names of its contributors may be
* used to endorse or promote products derived from this software without specific
* prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL
* THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include "horizontalswitcher.h"
#include "mimabstractkey.h"
#include "mimabstractkeyarea.h"
#include "layoutpanner.h"
#include <QGraphicsSceneResizeEvent>
#include <QGraphicsScene>
#include <QDebug>
namespace
{
const int SwitchDuration = 500;
const int SwitchFrames = 300;
void setHorizontalFlickRecognition(QGraphicsWidget *widget, bool recognition)
{
MImAbstractKeyArea * const keyArea = qobject_cast<MImAbstractKeyArea *>(widget);
if (keyArea) {
keyArea->enableHorizontalFlick(recognition);
}
}
}
HorizontalSwitcher::HorizontalSwitcher(QGraphicsItem *parent) :
QGraphicsWidget(parent),
currentIndex(-1),
animTimeLine(SwitchDuration),
loopingEnabled(false),
playAnimations(true),
m_enableSinglePageFlick(true)
{
setFlag(QGraphicsItem::ItemHasNoContents); // doesn't paint itself anything
setObjectName("HorizontalSwitcher");
animTimeLine.setFrameRange(0, SwitchFrames);
enterAnim.setTimeLine(&animTimeLine);
leaveAnim.setTimeLine(&animTimeLine);
connect(&animTimeLine, SIGNAL(finished()), this, SLOT(finishAnimation()));
}
HorizontalSwitcher::~HorizontalSwitcher()
{
if (isRunning())
finishAnimation();
// Delete all widgets that were not removed with removeWidget().
qDeleteAll(slides);
slides.clear();
}
void HorizontalSwitcher::switchTo(SwitchDirection direction)
{
if (isRunning()) {
finishAnimation();
}
if (slides.count() < 2 ||
(!loopingEnabled && isAtBoundary(direction))) {
return;
}
int newIndex = (direction == Left ? (currentIndex - 1)
: (currentIndex + 1) % slides.count());
if (newIndex < 0) {
newIndex += slides.count();
}
QGraphicsWidget *currentWidget = slides.at(currentIndex);
QGraphicsWidget *nextWidget = slides.at(newIndex);
// Current item is about to leave
leaveAnim.setItem(currentWidget);
currentWidget->setEnabled(false);
// New item is about to enter
enterAnim.setItem(nextWidget);
nextWidget->setEnabled(false);
// reset current and next key area
MImAbstractKeyArea *const currentKeyArea = dynamic_cast<MImAbstractKeyArea *>(currentWidget);
if (currentKeyArea) {
currentKeyArea->resetActiveKeys();
}
MImAbstractKeyArea *const nextKeyArea = dynamic_cast<MImAbstractKeyArea *>(nextWidget);
if (nextKeyArea) {
nextKeyArea->resetActiveKeys();
}
// Try to fit current size.
nextWidget->resize(size());
currentIndex = newIndex;
emit switchStarting(currentIndex, newIndex);
emit switchStarting(currentWidget, nextWidget);
if (!playAnimations) {
nextWidget->setPos(0.0, 0.0);
nextWidget->show();
finishAnimation();
} else {
nextWidget->setPos((direction == Right ? size().width()
: -(nextWidget->size().width())), 0.0);
enterAnim.setPosAt(0.0, nextWidget->pos());
enterAnim.setPosAt(1.0, QPointF(0.0, 0.0));
leaveAnim.setPosAt(0.0, currentWidget->pos());
leaveAnim.setPosAt(1.0, QPointF((direction == Right ? -(currentWidget->size().width())
: size().width()), 0.0));
// Enable painting background in black during playing animations.
setFlag(QGraphicsItem::ItemHasNoContents, false);
nextWidget->show();
animTimeLine.start();
}
}
bool HorizontalSwitcher::isAtBoundary(SwitchDirection direction) const
{
return (currentIndex == (direction == Left ? 0
: slides.count() - 1));
}
void HorizontalSwitcher::setCurrent(QGraphicsWidget *widget)
{
if (!widget || !slides.contains(widget)) {
qWarning() << "HorizontalSwitcher::setCurrent() - "
<< "Cannot set switcher to specified widget. Add widget to switcher first?";
return;
}
setCurrent(slides.indexOf(widget));
}
void HorizontalSwitcher::setCurrent(int index)
{
if (isValidIndex(index) && index != currentIndex) {
int oldIndex = -1;
QGraphicsWidget *old = 0;
if (isValidIndex(currentIndex)) {
oldIndex = currentIndex;
old = slides.at(currentIndex);
}
currentIndex = index;
QGraphicsWidget *widget = slides.at(index);
widget->setPos(0, 0);
if (widget->preferredHeight() != size().height())
widget->resize(QSizeF(size().width(), widget->preferredHeight()));
else
widget->resize(size());
widget->setEnabled(true);
widget->show();
// Ultimately might lead to a reaction map update in MKeyboardHost,
// has no other purpose:
emit switchDone(old, widget);
updateGeometry();
if (old) {
old->hide();
MImAbstractKeyArea *const keyArea = dynamic_cast<MImAbstractKeyArea *>(old);
if (keyArea) {
keyArea->modifiersChanged(false);
keyArea->resetActiveKeys();
}
}
}
}
int HorizontalSwitcher::current() const
{
return (slides.isEmpty() ? -1 : currentIndex);
}
QGraphicsWidget *HorizontalSwitcher::currentWidget() const
{
return (current() < 0 ? 0
: slides.at(currentIndex));
}
QGraphicsWidget *HorizontalSwitcher::widget(int index)
{
return (isValidIndex(index) ? slides.at(index)
: 0);
}
int HorizontalSwitcher::indexOf(QGraphicsWidget *widget) const
{
return slides.indexOf(widget);
}
int HorizontalSwitcher::count() const
{
return slides.count();
}
bool HorizontalSwitcher::isRunning() const
{
return (animTimeLine.state() == QTimeLine::Running);
}
void HorizontalSwitcher::setLooping(bool enable)
{
loopingEnabled = enable;
}
void HorizontalSwitcher::setDuration(int ms)
{
animTimeLine.setDuration(ms);
animTimeLine.setFrameRange(0, ms * SwitchFrames / qMax(1, SwitchDuration));
}
void HorizontalSwitcher::setEasingCurve(const QEasingCurve &curve)
{
animTimeLine.setEasingCurve(curve);
}
void HorizontalSwitcher::addWidget(QGraphicsWidget *widget)
{
if (!widget) {
return;
}
widget->setParentItem(this);
widget->setPreferredWidth(size().width());
slides.append(widget);
widget->hide();
// HS was empty before, this was the first widget added:
if (slides.size() == 1) {
setCurrent(0);
}
switch(count()) {
case 1:
setHorizontalFlickRecognition(widget, m_enableSinglePageFlick);
break;
case 2:
setHorizontalFlickRecognition(slides.at(0), true);
setHorizontalFlickRecognition(slides.at(1), true);
break;
default:
setHorizontalFlickRecognition(widget, true);
break;
}
}
void HorizontalSwitcher::removeAll()
{
foreach(QGraphicsWidget * slide, slides) {
slide->setParentItem(0);
if (slide->scene()) {
slide->scene()->removeItem(slide);
}
}
slides.clear();
currentIndex = -1;
updateGeometry();
}
void HorizontalSwitcher::deleteAll()
{
qDeleteAll(slides);
slides.clear();
currentIndex = -1;
updateGeometry();
}
void HorizontalSwitcher::resizeEvent(QGraphicsSceneResizeEvent *event)
{
QGraphicsWidget *widget = currentWidget();
if (widget) {
widget->resize(event->newSize());
}
}
QSizeF HorizontalSwitcher::sizeHint(Qt::SizeHint which, const QSizeF &constraint) const
{
// return the size hint of the currently visible widget
QGraphicsWidget *widget = currentWidget();
QSizeF hint;
if (widget) {
hint = widget->effectiveSizeHint(which, constraint);
} else {
hint = QGraphicsWidget::sizeHint(which, constraint);
}
return hint;
}
void HorizontalSwitcher::finishAnimation()
{
int oldIndex = -1;
// Hide old item
QGraphicsWidget *old = static_cast<QGraphicsWidget *>(leaveAnim.item());
if (old) {
oldIndex = slides.indexOf(old);
old->setEnabled(true);
old->hide();
}
// Clear transformations
leaveAnim.clear();
enterAnim.clear();
animTimeLine.stop();
// Restore original painting flag.
setFlag(QGraphicsItem::ItemHasNoContents);
// Discard cached sizehint info before telling that the switch is done.
updateGeometry();
if (currentWidget()) {
currentWidget()->setEnabled(true);
}
emit switchDone(oldIndex, currentIndex);
emit switchDone(old, slides.at(currentIndex));
}
void HorizontalSwitcher::updatePanningSwitchIncomingWidget(PanGesture::PanDirection direction)
{
qDebug() << __PRETTY_FUNCTION__
<< ", CURRENT INDEX:" << currentIndex;
int newIndex = (direction == PanGesture::PanLeft)
? (currentIndex - 1)
: (currentIndex + 1) % slides.count();
if (newIndex < 0) {
newIndex += slides.count();
}
QGraphicsWidget *nextWidget = slides.at(newIndex);
MImAbstractKeyArea *const nextKeyArea = dynamic_cast<MImAbstractKeyArea *>(nextWidget);
if (nextKeyArea) {
nextKeyArea->resetActiveKeys();
}
// Try to fit current size.
nextWidget->resize(size());
if (nextWidget->pos().y() + nextWidget->size().height() < size().height()) {
nextWidget->setPos(0.0, (size().height() - nextWidget->size().height()));
}
if (nextWidget->size().height() == size().height()
&& nextWidget->pos().y() != 0.0) {
nextWidget->setPos(0.0, 0.0);
}
LayoutPanner::instance().addIncomingWidget(direction, nextWidget);
}
void HorizontalSwitcher::prepareLayoutSwitch(PanGesture::PanDirection direction)
{
SwitchDirection switchDirection = direction == PanGesture::PanRight ? Left : Right;
QGraphicsWidget *currentWidget = slides.at(currentIndex);
// reset current and next key area
MImAbstractKeyArea *const currentKeyArea = dynamic_cast<MImAbstractKeyArea *>(currentWidget);
if (currentKeyArea) {
currentKeyArea->hidePopup();
currentKeyArea->resetActiveKeys();
currentKeyArea->setEnabled(false);
}
LayoutPanner::instance().addOutgoingWidget(currentWidget);
// if it is switching plugin, don't need next widget.
if (LayoutPanner::instance().isSwitchingPlugin())
return;
int newIndex = (switchDirection == Left ? (currentIndex - 1)
: (currentIndex + 1) % slides.count());
if (newIndex < 0) {
newIndex += slides.count();
}
QGraphicsWidget *nextWidget = slides.at(newIndex);
emit switchStarting(currentIndex, newIndex);
emit switchStarting(currentWidget, nextWidget);
}
void HorizontalSwitcher::finalizeLayoutSwitch(PanGesture::PanDirection direction)
{
qDebug() << __PRETTY_FUNCTION__ << direction;
const int oldIndex = currentIndex;
int newIndex = currentIndex;
switch (direction) {
case PanGesture::PanLeft:
newIndex = (currentIndex + 1) % slides.count();
break;
case PanGesture::PanRight:
newIndex = (currentIndex - 1);
if (newIndex < 0)
newIndex += slides.count();
break;
case PanGesture::PanNone:
default:
// canceled and no change.
break;
}
// re-enable old keyarea
slides.at(oldIndex)->setEnabled(true);
qDebug() << ", pan from:" << oldIndex << " to :" << newIndex;
if (newIndex != oldIndex) {
emit switchDone(slides.at(oldIndex), slides.at(newIndex));
emit layoutChanged(newIndex);
}
}
bool HorizontalSwitcher::isValidIndex(int index) const
{
return (index >= 0 && index < slides.size());
}
bool HorizontalSwitcher::isAnimationEnabled() const
{
return playAnimations;
}
void HorizontalSwitcher::setAnimationEnabled(bool enabled)
{
if (playAnimations != enabled) {
if (isRunning())
finishAnimation();
playAnimations = enabled;
}
}
void HorizontalSwitcher::setKeyOverrides(const QMap<QString, QSharedPointer<MKeyOverride> > &overrides)
{
for (int i = 0; i < count(); ++i) {
MImAbstractKeyArea *mainKba = qobject_cast<MImAbstractKeyArea *>(widget(i));
if (mainKba) {
mainKba->setKeyOverrides(overrides);
}
}
}
void HorizontalSwitcher::setContentType(M::TextContentType type)
{
foreach(QGraphicsWidget *slide, slides) {
MImAbstractKeyArea *mainKba = qobject_cast<MImAbstractKeyArea *>(slide);
if (mainKba) {
mainKba->setContentType(type);
}
}
}
void HorizontalSwitcher::paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget)
{
Q_UNUSED(option);
Q_UNUSED(widget);
// Make the background black during playing animations.
painter->fillRect(rect(), Qt::black);
}
void HorizontalSwitcher::enableSinglePageHorizontalFlick(bool enable)
{
if (m_enableSinglePageFlick == enable) {
return;
}
m_enableSinglePageFlick = enable;
updateHorizontalFlickRecognition();
}
void HorizontalSwitcher::updateHorizontalFlickRecognition()
{
const bool enable = (m_enableSinglePageFlick || (count() > 1));
foreach(QGraphicsWidget *slide, slides) {
MImAbstractKeyArea *keyArea = qobject_cast<MImAbstractKeyArea *>(slide);
if (keyArea) {
keyArea->enableHorizontalFlick(enable);
}
}
}
<|endoftext|> |
<commit_before>// ======================================================================== //
// Copyright 2009-2015 Intel Corporation //
// //
// Licensed under the Apache License, Version 2.0 (the "License"); //
// you may not use this file except in compliance with the License. //
// You may obtain a copy of the License at //
// //
// http://www.apache.org/licenses/LICENSE-2.0 //
// //
// Unless required by applicable law or agreed to in writing, software //
// distributed under the License is distributed on an "AS IS" BASIS, //
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. //
// See the License for the specific language governing permissions and //
// limitations under the License. //
// ======================================================================== //
#include "ModelViewer.h"
#include "widgets/affineSpaceManipulator/HelperGeometry.h"
#include "sg/SceneGraph.h"
#include "sg/Renderer.h"
namespace ospray {
namespace viewer {
using std::cout;
using std::endl;
struct FPSCounter {
double fps;
double smooth_nom;
double smooth_den;
double frameStartTime;
FPSCounter()
{
smooth_nom = 0.;
smooth_den = 0.;
frameStartTime = 0.;
}
void startRender() { frameStartTime = ospray::getSysTime(); }
void doneRender() {
double seconds = ospray::getSysTime() - frameStartTime;
fps = 1./seconds;
smooth_nom = smooth_nom * 0.8 + seconds;
smooth_den = smooth_den * 0.8 + 1.;
}
double getSmoothFPS() const { return smooth_den / smooth_nom; }
double getFPS() const { return fps; }
};
FPSCounter fps;
OSPRayRenderWidget::OSPRayRenderWidget(Ref<sg::Renderer> renderer)
: QAffineSpaceManipulator(QAffineSpaceManipulator::INSPECT),
sgRenderer(renderer)
{
if (renderer->world) {
box3f worldBounds = renderer->world->getBounds();
if (!worldBounds.empty()) {
float moveSpeed = .25*length(worldBounds.size());
QAffineSpaceManipulator::setMoveSpeed(moveSpeed);
}
}
Ref<sg::PerspectiveCamera> camera = renderer->camera.cast<sg::PerspectiveCamera>();
if (camera) {
frame->sourcePoint = camera->getFrom();
frame->targetPoint = camera->getAt();
frame->upVector = camera->getUp();
frame->orientation.vz = normalize(camera->getUp());
frame->orientation.vy = normalize(camera->getAt() - camera->getFrom());
frame->orientation.vx = normalize(cross(frame->orientation.vy,frame->orientation.vz));
}
}
void OSPRayRenderWidget::setWorld(Ref<sg::World> world)
{
assert(sgRenderer);
sgRenderer->setWorld(world);
cout << "#ospQTV: world set, found "
<< sgRenderer->allNodes.size() << " nodes" << endl;
}
//! the QT callback that tells us that we have to redraw
void OSPRayRenderWidget::redraw()
{
if (!sgRenderer) return;
if (!sgRenderer->frameBuffer) return;
if (!sgRenderer->camera) return;
if (showFPS) {
static int frameID = 0;
if (frameID > 0) {
fps.doneRender();
printf("fps: %7.3f (smoothed: %7.3f)\n",fps.getFPS(),fps.getSmoothFPS());
}
fps.startRender();
++frameID;
}
sgRenderer->renderFrame();
vec2i size = sgRenderer->frameBuffer->getSize();
unsigned char *fbMem = sgRenderer->frameBuffer->map();
glDrawPixels(size.x, size.y, GL_RGBA, GL_UNSIGNED_BYTE, fbMem);
sgRenderer->frameBuffer->unmap(fbMem);
// accumulate, but only up to 32 frames
if (sgRenderer->accumID < 32)
update();
}
//! the QT callback that tells us that the image got resize
void OSPRayRenderWidget::resize(int width, int height)
{
sgRenderer->frameBuffer = new sg::FrameBuffer(vec2i(width,height));
sgRenderer->resetAccumulation();
Ref<sg::PerspectiveCamera> camera = sgRenderer->camera.cast<sg::PerspectiveCamera>();
camera->setAspect(width/float(height));
camera->commit();
}
//! update the ospray camera (ospCamera) from the widget camera (this->camera)
void OSPRayRenderWidget::updateOSPRayCamera()
{
if (!sgRenderer) return;
if (!sgRenderer->camera) return;
sgRenderer->resetAccumulation();
Ref<sg::PerspectiveCamera> camera = sgRenderer->camera.cast<sg::PerspectiveCamera>();
assert(camera);
const vec3f from = frame->sourcePoint;
const vec3f at = frame->targetPoint;
vec2i size = sgRenderer->frameBuffer->getSize();
camera->setFrom(from);
camera->setAt(at);
camera->setUp(frame->orientation.vz);
camera->setAspect(size.x/float(size.y));
camera->commit();
}
//! create the lower-side time step slider (for models that have
//! time steps; won't do anything for models that don't)
void ModelViewer::createTimeSlider()
{
}
//! create the widet on the side that'll host all the editing widgets
void ModelViewer::createEditorWidgetStack()
{
editorWidgetStack = new EditorWidgetStack;
editorWidgetDock = new QDockWidget(this);
editorWidgetDock->setWindowTitle("Editors");
editorWidgetDock->setWidget(editorWidgetStack);
editorWidgetDock->setFeatures(0);
addDockWidget(Qt::RightDockWidgetArea,editorWidgetDock);
}
void ModelViewer::createTransferFunctionEditor()
{
QWidget *xfEditorsPage = NULL;
// make a list of all transfer function nodes in the scene graph
std::vector<Ref<sg::TransferFunction> > xferFuncs;
for (int i=0;i<sgRenderer->uniqueNodes.size();i++) {
sg::TransferFunction *xf = dynamic_cast<sg::TransferFunction *>
(sgRenderer->uniqueNodes.object[i]->node.ptr);
if (xf) xferFuncs.push_back(xf);
}
std::cout << "#osp:qtv: found " << xferFuncs.size()
<< " transfer function nodes" << std::endl;
if (xferFuncs.empty()) {
xfEditorsPage = new QLabel("(no xfer fcts found)");
} else {
// -------------------------------------------------------
// found some transfer functions - create a stacked widget
// with an editor for each
// -------------------------------------------------------
xfEditorsPage = new QWidget;
QVBoxLayout *layout = new QVBoxLayout;
xfEditorsPage->setLayout(layout);
QStackedWidget *stackedWidget = new QStackedWidget;
QComboBox *pageComboBox = new QComboBox;
QObject::connect(pageComboBox, SIGNAL(activated(int)),
stackedWidget, SLOT(setCurrentIndex(int)));
layout->addWidget(pageComboBox);
layout->addWidget(stackedWidget);
// now, create widgets for all of them
for (int i=0;i<xferFuncs.size();i++) {
// take name from node, or create one
std::string name = xferFuncs[i]->name;
if (name == "") {
std::stringstream ss;
ss << "(unnamed xfr fct #" << i << ")";
name = ss.str();
}
// add combo box and stacked widget entries
pageComboBox->addItem(tr(name.c_str()));
// create a transfer function editor for this transfer function node
QOSPTransferFunctionEditor *xfEd
= new QOSPTransferFunctionEditor(xferFuncs[i]);
stackedWidget->addWidget(xfEd);
connect(xfEd, SIGNAL(transferFunctionChanged()),
this, SLOT(render()));
}
}
editorWidgetStack->addPage("Transfer Functions",xfEditorsPage);
}
void ModelViewer::createLightManipulator() {
QWidget *lmEditorsPage = new QWidget;
QVBoxLayout *layout = new QVBoxLayout;
lmEditorsPage->setLayout(layout);
QStackedWidget *stackedWidget = new QStackedWidget;
layout->addWidget(stackedWidget);
Ref<sg::PerspectiveCamera> camera = renderWidget->sgRenderer->camera.cast<sg::PerspectiveCamera>();
QLightManipulator *lManipulator = new QLightManipulator(sgRenderer, camera->getUp());
//stackedWidget->addWidget(lManipulator);
layout->addWidget(lManipulator);
editorWidgetStack->addPage("Light Editor", lManipulator);
connect(lManipulator, SIGNAL(lightsChanged()), this, SLOT(render()));
}
void ModelViewer::keyPressEvent(QKeyEvent *event) {
// std::cout << event->key() << std::endl;
switch (event->key()) {
case Qt::Key_Escape:
case Qt::Key_Q:
// TODO: Properly tell the app to quit?
exit(0);
// TODO wasd movement
case Qt::Key_F:
setWindowState(windowState() ^ Qt::WindowFullScreen);
if (windowState() & Qt::WindowFullScreen){
toolBar->hide();
editorWidgetDock->hide();
} else {
toolBar->show();
editorWidgetDock->show();
}
break;
default:
QMainWindow::keyPressEvent(event);
}
}
ModelViewer::ModelViewer(Ref<sg::Renderer> sgRenderer, bool fullscreen)
: editorWidgetStack(NULL),
transferFunctionEditor(NULL),
lightEditor(NULL),
toolBar(NULL),
sgRenderer(sgRenderer)
{
// resize to default window size
setWindowTitle(tr("OSPRay QT ModelViewer"));
resize(1024,768);
// create GUI elements
toolBar = addToolBar("toolbar");
QAction *printCameraAction = new QAction("Print Camera", this);
connect(printCameraAction, SIGNAL(triggered()), this, SLOT(printCameraAction()));
toolBar->addAction(printCameraAction);
QAction *screenShotAction = new QAction("Screenshot", this);
connect(screenShotAction, SIGNAL(triggered()), this, SLOT(screenShotAction()));
toolBar->addAction(screenShotAction);
renderWidget = new OSPRayRenderWidget(sgRenderer);
///renderWidget = new CheckeredSphereRotationEditor();
// renderWidget = new QCoordAxisFrameEditor(QAffineSpaceManipulator::FLY);
// renderWidget = new QCoordAxisFrameEditor(QAffineSpaceManipulator::INSPECT);
// renderWidget = new QCoordAxisFrameEditor(QAffineSpaceManipulator::FREE_ROTATION);
// renderWidget->setMoveSpeed(1.f);
connect(renderWidget,SIGNAL(affineSpaceChanged(QAffineSpaceManipulator *)),
this,SLOT(cameraChanged()));
setCentralWidget(renderWidget);
setFocusPolicy(Qt::StrongFocus);
createTimeSlider();
createEditorWidgetStack();
createLightManipulator();
createTransferFunctionEditor();
if (fullscreen) {
setWindowState(windowState() & Qt::WindowFullScreen);
toolBar->hide();
editorWidgetDock->hide();
}
}
void ModelViewer::setWorld(Ref<sg::World> world)
{
renderWidget->setWorld(world);
}
void ModelViewer::render() {
sgRenderer->resetAccumulation();
if (renderWidget) renderWidget->updateGL();
}
// this is a incoming signal that the render widget changed the camera
void ModelViewer::cameraChanged()
{
renderWidget->updateOSPRayCamera();
}
//! print the camera on the command line (triggered by toolbar/menu).
void ModelViewer::printCameraAction()
{
Ref<sg::PerspectiveCamera> camera = renderWidget->sgRenderer->camera.cast<sg::PerspectiveCamera>();
vec3f from = camera->getFrom();
vec3f up = camera->getUp();
vec3f at = camera->getAt();
std::cout << "#osp:qtv: camera is"
<< " -vp " << from.x << " " << from.y << " " << from.z
<< " -vi " << at.x << " " << at.y << " " << at.z
<< " -vu " << up.x << " " << up.y << " " << up.z
<< std::endl;
}
//! take a screen shot
void ModelViewer::screenShotAction()
{
vec2i size = sgRenderer->frameBuffer->getSize();
unsigned char *fbMem = sgRenderer->frameBuffer->map();
glDrawPixels(size.x, size.y, GL_RGBA, GL_UNSIGNED_BYTE, fbMem);
sgRenderer->frameBuffer->unmap(fbMem);
QImage fb = QImage(fbMem,size.x,size.y,QImage::Format_RGB32).rgbSwapped().mirrored();
const std::string fileName = "/tmp/ospQTV.screenshot.png";
fb.save(fileName.c_str());
std::cout << "screen shot saved in " << fileName << std::endl;
}
void ModelViewer::lightChanged()
{
}
}
}
<commit_msg>Properly quit QTViewer<commit_after>// ======================================================================== //
// Copyright 2009-2015 Intel Corporation //
// //
// Licensed under the Apache License, Version 2.0 (the "License"); //
// you may not use this file except in compliance with the License. //
// You may obtain a copy of the License at //
// //
// http://www.apache.org/licenses/LICENSE-2.0 //
// //
// Unless required by applicable law or agreed to in writing, software //
// distributed under the License is distributed on an "AS IS" BASIS, //
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. //
// See the License for the specific language governing permissions and //
// limitations under the License. //
// ======================================================================== //
#include "ModelViewer.h"
#include "widgets/affineSpaceManipulator/HelperGeometry.h"
#include "sg/SceneGraph.h"
#include "sg/Renderer.h"
namespace ospray {
namespace viewer {
using std::cout;
using std::endl;
struct FPSCounter {
double fps;
double smooth_nom;
double smooth_den;
double frameStartTime;
FPSCounter()
{
smooth_nom = 0.;
smooth_den = 0.;
frameStartTime = 0.;
}
void startRender() { frameStartTime = ospray::getSysTime(); }
void doneRender() {
double seconds = ospray::getSysTime() - frameStartTime;
fps = 1./seconds;
smooth_nom = smooth_nom * 0.8 + seconds;
smooth_den = smooth_den * 0.8 + 1.;
}
double getSmoothFPS() const { return smooth_den / smooth_nom; }
double getFPS() const { return fps; }
};
FPSCounter fps;
OSPRayRenderWidget::OSPRayRenderWidget(Ref<sg::Renderer> renderer)
: QAffineSpaceManipulator(QAffineSpaceManipulator::INSPECT),
sgRenderer(renderer)
{
if (renderer->world) {
box3f worldBounds = renderer->world->getBounds();
if (!worldBounds.empty()) {
float moveSpeed = .25*length(worldBounds.size());
QAffineSpaceManipulator::setMoveSpeed(moveSpeed);
}
}
Ref<sg::PerspectiveCamera> camera = renderer->camera.cast<sg::PerspectiveCamera>();
if (camera) {
frame->sourcePoint = camera->getFrom();
frame->targetPoint = camera->getAt();
frame->upVector = camera->getUp();
frame->orientation.vz = normalize(camera->getUp());
frame->orientation.vy = normalize(camera->getAt() - camera->getFrom());
frame->orientation.vx = normalize(cross(frame->orientation.vy,frame->orientation.vz));
}
}
void OSPRayRenderWidget::setWorld(Ref<sg::World> world)
{
assert(sgRenderer);
sgRenderer->setWorld(world);
cout << "#ospQTV: world set, found "
<< sgRenderer->allNodes.size() << " nodes" << endl;
}
//! the QT callback that tells us that we have to redraw
void OSPRayRenderWidget::redraw()
{
if (!sgRenderer) return;
if (!sgRenderer->frameBuffer) return;
if (!sgRenderer->camera) return;
if (showFPS) {
static int frameID = 0;
if (frameID > 0) {
fps.doneRender();
printf("fps: %7.3f (smoothed: %7.3f)\n",fps.getFPS(),fps.getSmoothFPS());
}
fps.startRender();
++frameID;
}
sgRenderer->renderFrame();
vec2i size = sgRenderer->frameBuffer->getSize();
unsigned char *fbMem = sgRenderer->frameBuffer->map();
glDrawPixels(size.x, size.y, GL_RGBA, GL_UNSIGNED_BYTE, fbMem);
sgRenderer->frameBuffer->unmap(fbMem);
// accumulate, but only up to 32 frames
if (sgRenderer->accumID < 32)
update();
}
//! the QT callback that tells us that the image got resize
void OSPRayRenderWidget::resize(int width, int height)
{
sgRenderer->frameBuffer = new sg::FrameBuffer(vec2i(width,height));
sgRenderer->resetAccumulation();
Ref<sg::PerspectiveCamera> camera = sgRenderer->camera.cast<sg::PerspectiveCamera>();
camera->setAspect(width/float(height));
camera->commit();
}
//! update the ospray camera (ospCamera) from the widget camera (this->camera)
void OSPRayRenderWidget::updateOSPRayCamera()
{
if (!sgRenderer) return;
if (!sgRenderer->camera) return;
sgRenderer->resetAccumulation();
Ref<sg::PerspectiveCamera> camera = sgRenderer->camera.cast<sg::PerspectiveCamera>();
assert(camera);
const vec3f from = frame->sourcePoint;
const vec3f at = frame->targetPoint;
vec2i size = sgRenderer->frameBuffer->getSize();
camera->setFrom(from);
camera->setAt(at);
camera->setUp(frame->orientation.vz);
camera->setAspect(size.x/float(size.y));
camera->commit();
}
//! create the lower-side time step slider (for models that have
//! time steps; won't do anything for models that don't)
void ModelViewer::createTimeSlider()
{
}
//! create the widet on the side that'll host all the editing widgets
void ModelViewer::createEditorWidgetStack()
{
editorWidgetStack = new EditorWidgetStack;
editorWidgetDock = new QDockWidget(this);
editorWidgetDock->setWindowTitle("Editors");
editorWidgetDock->setWidget(editorWidgetStack);
editorWidgetDock->setFeatures(0);
addDockWidget(Qt::RightDockWidgetArea,editorWidgetDock);
}
void ModelViewer::createTransferFunctionEditor()
{
QWidget *xfEditorsPage = NULL;
// make a list of all transfer function nodes in the scene graph
std::vector<Ref<sg::TransferFunction> > xferFuncs;
for (int i=0;i<sgRenderer->uniqueNodes.size();i++) {
sg::TransferFunction *xf = dynamic_cast<sg::TransferFunction *>
(sgRenderer->uniqueNodes.object[i]->node.ptr);
if (xf) xferFuncs.push_back(xf);
}
std::cout << "#osp:qtv: found " << xferFuncs.size()
<< " transfer function nodes" << std::endl;
if (xferFuncs.empty()) {
xfEditorsPage = new QLabel("(no xfer fcts found)");
} else {
// -------------------------------------------------------
// found some transfer functions - create a stacked widget
// with an editor for each
// -------------------------------------------------------
xfEditorsPage = new QWidget;
QVBoxLayout *layout = new QVBoxLayout;
xfEditorsPage->setLayout(layout);
QStackedWidget *stackedWidget = new QStackedWidget;
QComboBox *pageComboBox = new QComboBox;
QObject::connect(pageComboBox, SIGNAL(activated(int)),
stackedWidget, SLOT(setCurrentIndex(int)));
layout->addWidget(pageComboBox);
layout->addWidget(stackedWidget);
// now, create widgets for all of them
for (int i=0;i<xferFuncs.size();i++) {
// take name from node, or create one
std::string name = xferFuncs[i]->name;
if (name == "") {
std::stringstream ss;
ss << "(unnamed xfr fct #" << i << ")";
name = ss.str();
}
// add combo box and stacked widget entries
pageComboBox->addItem(tr(name.c_str()));
// create a transfer function editor for this transfer function node
QOSPTransferFunctionEditor *xfEd
= new QOSPTransferFunctionEditor(xferFuncs[i]);
stackedWidget->addWidget(xfEd);
connect(xfEd, SIGNAL(transferFunctionChanged()),
this, SLOT(render()));
}
}
editorWidgetStack->addPage("Transfer Functions",xfEditorsPage);
}
void ModelViewer::createLightManipulator() {
QWidget *lmEditorsPage = new QWidget;
QVBoxLayout *layout = new QVBoxLayout;
lmEditorsPage->setLayout(layout);
QStackedWidget *stackedWidget = new QStackedWidget;
layout->addWidget(stackedWidget);
Ref<sg::PerspectiveCamera> camera = renderWidget->sgRenderer->camera.cast<sg::PerspectiveCamera>();
QLightManipulator *lManipulator = new QLightManipulator(sgRenderer, camera->getUp());
//stackedWidget->addWidget(lManipulator);
layout->addWidget(lManipulator);
editorWidgetStack->addPage("Light Editor", lManipulator);
connect(lManipulator, SIGNAL(lightsChanged()), this, SLOT(render()));
}
void ModelViewer::keyPressEvent(QKeyEvent *event) {
// std::cout << event->key() << std::endl;
switch (event->key()) {
case Qt::Key_Escape:
case Qt::Key_Q:
QApplication::quit();
// TODO wasd movement
case Qt::Key_F:
setWindowState(windowState() ^ Qt::WindowFullScreen);
if (windowState() & Qt::WindowFullScreen){
toolBar->hide();
editorWidgetDock->hide();
} else {
toolBar->show();
editorWidgetDock->show();
}
break;
default:
QMainWindow::keyPressEvent(event);
}
}
ModelViewer::ModelViewer(Ref<sg::Renderer> sgRenderer, bool fullscreen)
: editorWidgetStack(NULL),
transferFunctionEditor(NULL),
lightEditor(NULL),
toolBar(NULL),
sgRenderer(sgRenderer)
{
// resize to default window size
setWindowTitle(tr("OSPRay QT ModelViewer"));
resize(1024,768);
// create GUI elements
toolBar = addToolBar("toolbar");
QAction *printCameraAction = new QAction("Print Camera", this);
connect(printCameraAction, SIGNAL(triggered()), this, SLOT(printCameraAction()));
toolBar->addAction(printCameraAction);
QAction *screenShotAction = new QAction("Screenshot", this);
connect(screenShotAction, SIGNAL(triggered()), this, SLOT(screenShotAction()));
toolBar->addAction(screenShotAction);
renderWidget = new OSPRayRenderWidget(sgRenderer);
///renderWidget = new CheckeredSphereRotationEditor();
// renderWidget = new QCoordAxisFrameEditor(QAffineSpaceManipulator::FLY);
// renderWidget = new QCoordAxisFrameEditor(QAffineSpaceManipulator::INSPECT);
// renderWidget = new QCoordAxisFrameEditor(QAffineSpaceManipulator::FREE_ROTATION);
// renderWidget->setMoveSpeed(1.f);
connect(renderWidget,SIGNAL(affineSpaceChanged(QAffineSpaceManipulator *)),
this,SLOT(cameraChanged()));
setCentralWidget(renderWidget);
setFocusPolicy(Qt::StrongFocus);
createTimeSlider();
createEditorWidgetStack();
createLightManipulator();
createTransferFunctionEditor();
if (fullscreen) {
setWindowState(windowState() & Qt::WindowFullScreen);
toolBar->hide();
editorWidgetDock->hide();
}
}
void ModelViewer::setWorld(Ref<sg::World> world)
{
renderWidget->setWorld(world);
}
void ModelViewer::render() {
sgRenderer->resetAccumulation();
if (renderWidget) renderWidget->updateGL();
}
// this is a incoming signal that the render widget changed the camera
void ModelViewer::cameraChanged()
{
renderWidget->updateOSPRayCamera();
}
//! print the camera on the command line (triggered by toolbar/menu).
void ModelViewer::printCameraAction()
{
Ref<sg::PerspectiveCamera> camera = renderWidget->sgRenderer->camera.cast<sg::PerspectiveCamera>();
vec3f from = camera->getFrom();
vec3f up = camera->getUp();
vec3f at = camera->getAt();
std::cout << "#osp:qtv: camera is"
<< " -vp " << from.x << " " << from.y << " " << from.z
<< " -vi " << at.x << " " << at.y << " " << at.z
<< " -vu " << up.x << " " << up.y << " " << up.z
<< std::endl;
}
//! take a screen shot
void ModelViewer::screenShotAction()
{
vec2i size = sgRenderer->frameBuffer->getSize();
unsigned char *fbMem = sgRenderer->frameBuffer->map();
glDrawPixels(size.x, size.y, GL_RGBA, GL_UNSIGNED_BYTE, fbMem);
sgRenderer->frameBuffer->unmap(fbMem);
QImage fb = QImage(fbMem,size.x,size.y,QImage::Format_RGB32).rgbSwapped().mirrored();
const std::string fileName = "/tmp/ospQTV.screenshot.png";
fb.save(fileName.c_str());
std::cout << "screen shot saved in " << fileName << std::endl;
}
void ModelViewer::lightChanged()
{
}
}
}
<|endoftext|> |
<commit_before>//
// This file is part of the Marble Virtual Globe.
//
// This program is free software licensed under the GNU LGPL. You can
// find a copy of this license in LICENSE.txt in the top directory of
// the source code.
//
// Copyright 2011 Dennis Nienhüser <earthwings@gentoo.org>
//
#include "AudioOutput.h"
#include "MarbleDirs.h"
#include "MarbleDebug.h"
#include "routing/instructions/RoutingInstruction.h"
#include <QtCore/QDirIterator>
#include <phonon/MediaObject>
#include <phonon/MediaSource>
#include <phonon/AudioOutput>
namespace Marble
{
class AudioOutputPrivate
{
public:
AudioOutput *q;
QMap<RoutingInstruction::TurnType, QString> m_turnTypeMap;
QMap<RoutingInstruction::TurnType, QString> m_announceMap;
QString m_speaker;
Phonon::MediaObject *m_output;
qreal m_lastDistance;
RoutingInstruction::TurnType m_lastTurnType;
bool m_muted;
bool m_soundEnabled;
GeoDataCoordinates m_lastTurnPoint;
AudioOutputPrivate( AudioOutput* parent );
void audioOutputFinished();
void setupAudio();
QString distanceAudioFile( qreal distance );
QString turnTypeAudioFile( RoutingInstruction::TurnType turnType, qreal distance );
QString audioFile( const QString &name );
void reset();
void enqueue( qreal distance, RoutingInstruction::TurnType turnType );
void enqueue( const QString &file );
};
AudioOutputPrivate::AudioOutputPrivate( AudioOutput* parent ) :
q( parent ), m_output( 0 ), m_lastDistance( 0.0 ),
m_muted( false ), m_soundEnabled( true )
{
// nothing to do
}
void AudioOutputPrivate::audioOutputFinished()
{
m_output->setCurrentSource( QString() );
m_output->clearQueue();
}
QString AudioOutputPrivate::distanceAudioFile( qreal dest )
{
if ( dest > 0.0 && dest < 900.0 ) {
qreal minDistance = 0.0;
int targetDistance = 0;
QVector<int> distances;
distances << 50 << 80 << 100 << 200 << 300 << 400 << 500 << 600 << 700 << 800;
foreach( int distance, distances ) {
QString file = audioFile( QString::number( distance ) );
qreal currentDistance = qAbs( distance - dest );
if ( !file.isEmpty() && ( minDistance == 0.0 || currentDistance < minDistance ) ) {
minDistance = currentDistance;
targetDistance = distance;
}
}
if ( targetDistance > 0 ) {
return audioFile( QString::number( targetDistance ) );
}
}
return QString();
}
QString AudioOutputPrivate::turnTypeAudioFile( RoutingInstruction::TurnType turnType, qreal distance )
{
QMap<RoutingInstruction::TurnType, QString> const & map = distance < 75 ? m_turnTypeMap : m_announceMap;
if ( map.contains( turnType ) ) {
return audioFile( map[turnType] );
}
return QString();
}
QString AudioOutputPrivate::audioFile( const QString &name )
{
if ( m_soundEnabled ) {
QString const audioTemplate = "audio/%1.ogg";
return MarbleDirs::path( audioTemplate.arg( name ) );
} else {
QString const audioTemplate = "audio/speakers/%1/%2.ogg";
return MarbleDirs::path( audioTemplate.arg( m_speaker ).arg( name ) );
}
}
void AudioOutputPrivate::setupAudio()
{
if ( !m_output ) {
m_output = new Phonon::MediaObject( q );
Phonon::AudioOutput *audioOutput = new Phonon::AudioOutput( Phonon::VideoCategory, q );
Phonon::createPath( m_output, audioOutput );
q->connect( m_output, SIGNAL( finished() ), q, SLOT( audioOutputFinished() ) );
}
}
void AudioOutputPrivate::enqueue( qreal distance, RoutingInstruction::TurnType turnType )
{
if ( !m_output ) {
return;
}
//QString distanceAudio = distanceAudioFile( distance );
QString turnTypeAudio = turnTypeAudioFile( turnType, distance );
if ( turnTypeAudio.isEmpty() ) {
mDebug() << "Missing audio file for turn type " << turnType;
return;
}
m_output->enqueue( turnTypeAudio );
// if ( !distanceAudio.isEmpty() ) {
// m_output->enqueue( audioFile( "After" ) );
// m_output->enqueue( distanceAudio );
// m_output->enqueue( audioFile( "Meters" ) );
// }
}
void AudioOutputPrivate::enqueue( const QString &file )
{
if ( m_output ) {
m_output->enqueue( audioFile( file ) );
}
}
void AudioOutputPrivate::reset()
{
if ( m_output ) {
m_output->stop();
m_output->setCurrentSource( QString() );
m_output->clearQueue();
}
m_lastDistance = 0.0;
}
AudioOutput::AudioOutput( QObject* parent ) : QObject( parent ),
d( new AudioOutputPrivate( this ) )
{
setSoundEnabled( false );
}
AudioOutput::~AudioOutput()
{
delete d;
}
void AudioOutput::update( const Route &route, qreal distance )
{
if ( d->m_muted ) {
return;
}
RoutingInstruction::TurnType turnType = route.currentSegment().nextRouteSegment().maneuver().direction();
if ( !( d->m_lastTurnPoint == route.currentSegment().nextRouteSegment().maneuver().position() ) || turnType != d->m_lastTurnType ) {
d->m_lastTurnPoint = route.currentSegment().nextRouteSegment().maneuver().position();
d->reset();
}
bool const announcement = ( d->m_lastDistance == 0 || d->m_lastDistance > 850 ) && distance <= 850;
bool const turn = ( d->m_lastDistance == 0 || d->m_lastDistance > 75 ) && distance <= 75;
if ( announcement || turn ) {
if ( !d->m_output || d->m_output->currentSource().fileName().isEmpty() ) {
d->setupAudio();
d->enqueue( distance, turnType );
if ( d->m_output ) {
d->m_output->play();
}
}
}
d->m_lastTurnType = turnType;
d->m_lastDistance = distance;
}
void AudioOutput::setMuted( bool muted )
{
d->m_muted = muted;
}
void AudioOutput::setSpeaker( const QString &speaker )
{
d->m_speaker = speaker;
}
QStringList AudioOutput::speakers() const
{
QString const voicePath = MarbleDirs::path( "audio/speakers" );
if ( !voicePath.isEmpty() ) {
QDir::Filters filter = QDir::Readable | QDir::Dirs | QDir::NoDotAndDotDot;
QDir voiceDir( voicePath );
return voiceDir.entryList( filter, QDir::Name );
}
return QStringList();
}
void AudioOutput::setSoundEnabled( bool enabled )
{
d->m_soundEnabled = enabled;
d->m_turnTypeMap.clear();
d->m_announceMap.clear();
if ( enabled ) {
d->m_announceMap[RoutingInstruction::Straight] = "KDE-Sys-List-End";
d->m_announceMap[RoutingInstruction::SlightRight] = "KDE-Sys-List-End";
d->m_announceMap[RoutingInstruction::Right] = "KDE-Sys-List-End";
d->m_announceMap[RoutingInstruction::SharpRight] = "KDE-Sys-List-End";
d->m_announceMap[RoutingInstruction::TurnAround] = "KDE-Sys-List-End";
d->m_announceMap[RoutingInstruction::SharpLeft] = "KDE-Sys-List-End";
d->m_announceMap[RoutingInstruction::Left] = "KDE-Sys-List-End";
d->m_announceMap[RoutingInstruction::SlightLeft] = "KDE-Sys-List-End";
d->m_announceMap[RoutingInstruction::RoundaboutFirstExit] = "KDE-Sys-List-End";
d->m_announceMap[RoutingInstruction::RoundaboutSecondExit] = "KDE-Sys-List-End";
d->m_announceMap[RoutingInstruction::RoundaboutThirdExit] = "KDE-Sys-List-End";
d->m_turnTypeMap[RoutingInstruction::Straight] = "KDE-Sys-App-Positive";
d->m_turnTypeMap[RoutingInstruction::SlightRight] = "KDE-Sys-App-Positive";
d->m_turnTypeMap[RoutingInstruction::Right] = "KDE-Sys-App-Positive";
d->m_turnTypeMap[RoutingInstruction::SharpRight] = "KDE-Sys-App-Positive";
d->m_turnTypeMap[RoutingInstruction::TurnAround] = "KDE-Sys-App-Positive";
d->m_turnTypeMap[RoutingInstruction::SharpLeft] = "KDE-Sys-App-Positive";
d->m_turnTypeMap[RoutingInstruction::Left] = "KDE-Sys-App-Positive";
d->m_turnTypeMap[RoutingInstruction::SlightLeft] = "KDE-Sys-App-Positive";
d->m_turnTypeMap[RoutingInstruction::RoundaboutFirstExit] = "KDE-Sys-App-Positive";
d->m_turnTypeMap[RoutingInstruction::RoundaboutSecondExit] = "KDE-Sys-App-Positive";
d->m_turnTypeMap[RoutingInstruction::RoundaboutThirdExit] = "KDE-Sys-App-Positive";
} else {
d->m_announceMap[RoutingInstruction::Straight] = "";
d->m_announceMap[RoutingInstruction::SlightRight] = "AhKeepRight";
d->m_announceMap[RoutingInstruction::Right] = "AhRightTurn";
d->m_announceMap[RoutingInstruction::SharpRight] = "AhRightTurn";
d->m_announceMap[RoutingInstruction::TurnAround] = "AhUTurn";
d->m_announceMap[RoutingInstruction::SharpLeft] = "AhLeftTurn";
d->m_announceMap[RoutingInstruction::Left] = "AhLeftTurn";
d->m_announceMap[RoutingInstruction::SlightLeft] = "AhKeepLeft";
d->m_announceMap[RoutingInstruction::RoundaboutFirstExit] = "RbExit1";
d->m_announceMap[RoutingInstruction::RoundaboutSecondExit] = "RbExit2";
d->m_announceMap[RoutingInstruction::RoundaboutThirdExit] = "RbExit3";
d->m_turnTypeMap[RoutingInstruction::Straight] = "Straight";
d->m_turnTypeMap[RoutingInstruction::SlightRight] = "BearRight";
d->m_turnTypeMap[RoutingInstruction::Right] = "TurnRight";
d->m_turnTypeMap[RoutingInstruction::SharpRight] = "SharpRight";
d->m_turnTypeMap[RoutingInstruction::TurnAround] = "UTurn";
d->m_turnTypeMap[RoutingInstruction::SharpLeft] = "SharpLeft";
d->m_turnTypeMap[RoutingInstruction::Left] = "TurnLeft";
d->m_turnTypeMap[RoutingInstruction::SlightLeft] = "BearLeft";
d->m_turnTypeMap[RoutingInstruction::RoundaboutFirstExit] = "";
d->m_turnTypeMap[RoutingInstruction::RoundaboutSecondExit] = "";
d->m_turnTypeMap[RoutingInstruction::RoundaboutThirdExit] = "";
}
}
void AudioOutput::announceStart()
{
if ( d->m_muted || d->m_soundEnabled ) {
return;
}
d->setupAudio();
// d->enqueue( "Depart" );
// if ( d->m_output ) {
// d->m_output->play();
// }
}
void AudioOutput::announceDestination()
{
if ( d->m_muted ) {
return;
}
d->setupAudio();
d->enqueue( d->m_soundEnabled ? "KDE-Sys-App-Positive" : "Arrive" );
if ( d->m_output ) {
d->m_output->play();
}
}
}
#include "AudioOutput.moc"
<commit_msg>Fall back to mp3/wav files if no ogg file can be found.<commit_after>//
// This file is part of the Marble Virtual Globe.
//
// This program is free software licensed under the GNU LGPL. You can
// find a copy of this license in LICENSE.txt in the top directory of
// the source code.
//
// Copyright 2011 Dennis Nienhüser <earthwings@gentoo.org>
//
#include "AudioOutput.h"
#include "MarbleDirs.h"
#include "MarbleDebug.h"
#include "routing/instructions/RoutingInstruction.h"
#include <QtCore/QDirIterator>
#include <phonon/MediaObject>
#include <phonon/MediaSource>
#include <phonon/AudioOutput>
namespace Marble
{
class AudioOutputPrivate
{
public:
AudioOutput *q;
QMap<RoutingInstruction::TurnType, QString> m_turnTypeMap;
QMap<RoutingInstruction::TurnType, QString> m_announceMap;
QString m_speaker;
Phonon::MediaObject *m_output;
qreal m_lastDistance;
RoutingInstruction::TurnType m_lastTurnType;
bool m_muted;
bool m_soundEnabled;
GeoDataCoordinates m_lastTurnPoint;
AudioOutputPrivate( AudioOutput* parent );
void audioOutputFinished();
void setupAudio();
QString distanceAudioFile( qreal distance );
QString turnTypeAudioFile( RoutingInstruction::TurnType turnType, qreal distance );
QString audioFile( const QString &name );
void reset();
void enqueue( qreal distance, RoutingInstruction::TurnType turnType );
void enqueue( const QString &file );
};
AudioOutputPrivate::AudioOutputPrivate( AudioOutput* parent ) :
q( parent ), m_output( 0 ), m_lastDistance( 0.0 ),
m_muted( false ), m_soundEnabled( true )
{
// nothing to do
}
void AudioOutputPrivate::audioOutputFinished()
{
m_output->setCurrentSource( QString() );
m_output->clearQueue();
}
QString AudioOutputPrivate::distanceAudioFile( qreal dest )
{
if ( dest > 0.0 && dest < 900.0 ) {
qreal minDistance = 0.0;
int targetDistance = 0;
QVector<int> distances;
distances << 50 << 80 << 100 << 200 << 300 << 400 << 500 << 600 << 700 << 800;
foreach( int distance, distances ) {
QString file = audioFile( QString::number( distance ) );
qreal currentDistance = qAbs( distance - dest );
if ( !file.isEmpty() && ( minDistance == 0.0 || currentDistance < minDistance ) ) {
minDistance = currentDistance;
targetDistance = distance;
}
}
if ( targetDistance > 0 ) {
return audioFile( QString::number( targetDistance ) );
}
}
return QString();
}
QString AudioOutputPrivate::turnTypeAudioFile( RoutingInstruction::TurnType turnType, qreal distance )
{
QMap<RoutingInstruction::TurnType, QString> const & map = distance < 75 ? m_turnTypeMap : m_announceMap;
if ( map.contains( turnType ) ) {
return audioFile( map[turnType] );
}
return QString();
}
QString AudioOutputPrivate::audioFile( const QString &name )
{
QStringList const formats = QStringList() << "ogg" << "mp3" << "wav";
if ( m_soundEnabled ) {
QString const audioTemplate = "audio/%1.%2";
foreach( const QString &format, formats ) {
QString const result = MarbleDirs::path( audioTemplate.arg( name ).arg( format ) );
if ( !result.isEmpty() ) {
return result;
}
}
} else {
QString const audioTemplate = "audio/speakers/%1/%2.%3";
foreach( const QString &format, formats ) {
QString const result = MarbleDirs::path( audioTemplate.arg( m_speaker ).arg( name ).arg( format ) );
if ( !result.isEmpty() ) {
return result;
}
}
}
return QString();
}
void AudioOutputPrivate::setupAudio()
{
if ( !m_output ) {
m_output = new Phonon::MediaObject( q );
Phonon::AudioOutput *audioOutput = new Phonon::AudioOutput( Phonon::VideoCategory, q );
Phonon::createPath( m_output, audioOutput );
q->connect( m_output, SIGNAL( finished() ), q, SLOT( audioOutputFinished() ) );
}
}
void AudioOutputPrivate::enqueue( qreal distance, RoutingInstruction::TurnType turnType )
{
if ( !m_output ) {
return;
}
//QString distanceAudio = distanceAudioFile( distance );
QString turnTypeAudio = turnTypeAudioFile( turnType, distance );
if ( turnTypeAudio.isEmpty() ) {
mDebug() << "Missing audio file for turn type " << turnType;
return;
}
m_output->enqueue( turnTypeAudio );
// if ( !distanceAudio.isEmpty() ) {
// m_output->enqueue( audioFile( "After" ) );
// m_output->enqueue( distanceAudio );
// m_output->enqueue( audioFile( "Meters" ) );
// }
}
void AudioOutputPrivate::enqueue( const QString &file )
{
if ( m_output ) {
m_output->enqueue( audioFile( file ) );
}
}
void AudioOutputPrivate::reset()
{
if ( m_output ) {
m_output->stop();
m_output->setCurrentSource( QString() );
m_output->clearQueue();
}
m_lastDistance = 0.0;
}
AudioOutput::AudioOutput( QObject* parent ) : QObject( parent ),
d( new AudioOutputPrivate( this ) )
{
setSoundEnabled( false );
}
AudioOutput::~AudioOutput()
{
delete d;
}
void AudioOutput::update( const Route &route, qreal distance )
{
if ( d->m_muted ) {
return;
}
RoutingInstruction::TurnType turnType = route.currentSegment().nextRouteSegment().maneuver().direction();
if ( !( d->m_lastTurnPoint == route.currentSegment().nextRouteSegment().maneuver().position() ) || turnType != d->m_lastTurnType ) {
d->m_lastTurnPoint = route.currentSegment().nextRouteSegment().maneuver().position();
d->reset();
}
bool const announcement = ( d->m_lastDistance == 0 || d->m_lastDistance > 850 ) && distance <= 850;
bool const turn = ( d->m_lastDistance == 0 || d->m_lastDistance > 75 ) && distance <= 75;
if ( announcement || turn ) {
if ( !d->m_output || d->m_output->currentSource().fileName().isEmpty() ) {
d->setupAudio();
d->enqueue( distance, turnType );
if ( d->m_output ) {
d->m_output->play();
}
}
}
d->m_lastTurnType = turnType;
d->m_lastDistance = distance;
}
void AudioOutput::setMuted( bool muted )
{
d->m_muted = muted;
}
void AudioOutput::setSpeaker( const QString &speaker )
{
d->m_speaker = speaker;
}
QStringList AudioOutput::speakers() const
{
QString const voicePath = MarbleDirs::path( "audio/speakers" );
if ( !voicePath.isEmpty() ) {
QDir::Filters filter = QDir::Readable | QDir::Dirs | QDir::NoDotAndDotDot;
QDir voiceDir( voicePath );
return voiceDir.entryList( filter, QDir::Name );
}
return QStringList();
}
void AudioOutput::setSoundEnabled( bool enabled )
{
d->m_soundEnabled = enabled;
d->m_turnTypeMap.clear();
d->m_announceMap.clear();
if ( enabled ) {
d->m_announceMap[RoutingInstruction::Straight] = "KDE-Sys-List-End";
d->m_announceMap[RoutingInstruction::SlightRight] = "KDE-Sys-List-End";
d->m_announceMap[RoutingInstruction::Right] = "KDE-Sys-List-End";
d->m_announceMap[RoutingInstruction::SharpRight] = "KDE-Sys-List-End";
d->m_announceMap[RoutingInstruction::TurnAround] = "KDE-Sys-List-End";
d->m_announceMap[RoutingInstruction::SharpLeft] = "KDE-Sys-List-End";
d->m_announceMap[RoutingInstruction::Left] = "KDE-Sys-List-End";
d->m_announceMap[RoutingInstruction::SlightLeft] = "KDE-Sys-List-End";
d->m_announceMap[RoutingInstruction::RoundaboutFirstExit] = "KDE-Sys-List-End";
d->m_announceMap[RoutingInstruction::RoundaboutSecondExit] = "KDE-Sys-List-End";
d->m_announceMap[RoutingInstruction::RoundaboutThirdExit] = "KDE-Sys-List-End";
d->m_turnTypeMap[RoutingInstruction::Straight] = "KDE-Sys-App-Positive";
d->m_turnTypeMap[RoutingInstruction::SlightRight] = "KDE-Sys-App-Positive";
d->m_turnTypeMap[RoutingInstruction::Right] = "KDE-Sys-App-Positive";
d->m_turnTypeMap[RoutingInstruction::SharpRight] = "KDE-Sys-App-Positive";
d->m_turnTypeMap[RoutingInstruction::TurnAround] = "KDE-Sys-App-Positive";
d->m_turnTypeMap[RoutingInstruction::SharpLeft] = "KDE-Sys-App-Positive";
d->m_turnTypeMap[RoutingInstruction::Left] = "KDE-Sys-App-Positive";
d->m_turnTypeMap[RoutingInstruction::SlightLeft] = "KDE-Sys-App-Positive";
d->m_turnTypeMap[RoutingInstruction::RoundaboutFirstExit] = "KDE-Sys-App-Positive";
d->m_turnTypeMap[RoutingInstruction::RoundaboutSecondExit] = "KDE-Sys-App-Positive";
d->m_turnTypeMap[RoutingInstruction::RoundaboutThirdExit] = "KDE-Sys-App-Positive";
} else {
d->m_announceMap[RoutingInstruction::Straight] = "";
d->m_announceMap[RoutingInstruction::SlightRight] = "AhKeepRight";
d->m_announceMap[RoutingInstruction::Right] = "AhRightTurn";
d->m_announceMap[RoutingInstruction::SharpRight] = "AhRightTurn";
d->m_announceMap[RoutingInstruction::TurnAround] = "AhUTurn";
d->m_announceMap[RoutingInstruction::SharpLeft] = "AhLeftTurn";
d->m_announceMap[RoutingInstruction::Left] = "AhLeftTurn";
d->m_announceMap[RoutingInstruction::SlightLeft] = "AhKeepLeft";
d->m_announceMap[RoutingInstruction::RoundaboutFirstExit] = "RbExit1";
d->m_announceMap[RoutingInstruction::RoundaboutSecondExit] = "RbExit2";
d->m_announceMap[RoutingInstruction::RoundaboutThirdExit] = "RbExit3";
d->m_turnTypeMap[RoutingInstruction::Straight] = "Straight";
d->m_turnTypeMap[RoutingInstruction::SlightRight] = "BearRight";
d->m_turnTypeMap[RoutingInstruction::Right] = "TurnRight";
d->m_turnTypeMap[RoutingInstruction::SharpRight] = "SharpRight";
d->m_turnTypeMap[RoutingInstruction::TurnAround] = "UTurn";
d->m_turnTypeMap[RoutingInstruction::SharpLeft] = "SharpLeft";
d->m_turnTypeMap[RoutingInstruction::Left] = "TurnLeft";
d->m_turnTypeMap[RoutingInstruction::SlightLeft] = "BearLeft";
d->m_turnTypeMap[RoutingInstruction::RoundaboutFirstExit] = "";
d->m_turnTypeMap[RoutingInstruction::RoundaboutSecondExit] = "";
d->m_turnTypeMap[RoutingInstruction::RoundaboutThirdExit] = "";
}
}
void AudioOutput::announceStart()
{
if ( d->m_muted || d->m_soundEnabled ) {
return;
}
d->setupAudio();
// d->enqueue( "Depart" );
// if ( d->m_output ) {
// d->m_output->play();
// }
}
void AudioOutput::announceDestination()
{
if ( d->m_muted ) {
return;
}
d->setupAudio();
d->enqueue( d->m_soundEnabled ? "KDE-Sys-App-Positive" : "Arrive" );
if ( d->m_output ) {
d->m_output->play();
}
}
}
#include "AudioOutput.moc"
<|endoftext|> |
<commit_before>/*
* The MIT License (MIT)
*
* Copyright (c) 2020 Franco Venturi
* 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 "SoapySDRPlay.hpp"
// Singleton class for SDRplay API (only one per process)
SoapySDRPlay::sdrplay_api::sdrplay_api()
{
sdrplay_api_ErrT err;
// Open API
err = sdrplay_api_Open();
if (err != sdrplay_api_Success) {
SoapySDR_logf(SOAPY_SDR_ERROR, "sdrplay_api_Open() Error: %s", sdrplay_api_GetErrorString(err));
throw std::runtime_error("sdrplay_api_Open() failed");
}
// Check API versions match
float ver;
err = sdrplay_api_ApiVersion(&ver);
if (err != sdrplay_api_Success) {
SoapySDR_logf(SOAPY_SDR_ERROR, "ApiVersion Error: %s", sdrplay_api_GetErrorString(err));
sdrplay_api_Close();
throw std::runtime_error("ApiVersion() failed");
}
if (ver != SDRPLAY_API_VERSION) {
SoapySDR_logf(SOAPY_SDR_WARNING, "sdrplay_api version: '%.3f' does not equal build version: '%.3f'", ver, SDRPLAY_API_VERSION);
}
}
SoapySDRPlay::sdrplay_api::~sdrplay_api()
{
sdrplay_api_ErrT err;
// Close API
err = sdrplay_api_Close();
if (err != sdrplay_api_Success) {
SoapySDR_logf(SOAPY_SDR_ERROR, "sdrplay_api_Close() failed: %s", sdrplay_api_GetErrorString(err));
}
}
<commit_msg>add explanatory message for the user when sdrplay_api_Open() fails<commit_after>/*
* The MIT License (MIT)
*
* Copyright (c) 2020 Franco Venturi
* 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 "SoapySDRPlay.hpp"
// Singleton class for SDRplay API (only one per process)
SoapySDRPlay::sdrplay_api::sdrplay_api()
{
sdrplay_api_ErrT err;
// Open API
err = sdrplay_api_Open();
if (err != sdrplay_api_Success) {
SoapySDR_logf(SOAPY_SDR_ERROR, "sdrplay_api_Open() Error: %s", sdrplay_api_GetErrorString(err));
SoapySDR_logf(SOAPY_SDR_ERROR, "Please check the sdrplay_api service to make sure it is up. If it is up, please restart it.");
throw std::runtime_error("sdrplay_api_Open() failed");
}
// Check API versions match
float ver;
err = sdrplay_api_ApiVersion(&ver);
if (err != sdrplay_api_Success) {
SoapySDR_logf(SOAPY_SDR_ERROR, "ApiVersion Error: %s", sdrplay_api_GetErrorString(err));
sdrplay_api_Close();
throw std::runtime_error("ApiVersion() failed");
}
if (ver != SDRPLAY_API_VERSION) {
SoapySDR_logf(SOAPY_SDR_WARNING, "sdrplay_api version: '%.3f' does not equal build version: '%.3f'", ver, SDRPLAY_API_VERSION);
}
}
SoapySDRPlay::sdrplay_api::~sdrplay_api()
{
sdrplay_api_ErrT err;
// Close API
err = sdrplay_api_Close();
if (err != sdrplay_api_Success) {
SoapySDR_logf(SOAPY_SDR_ERROR, "sdrplay_api_Close() failed: %s", sdrplay_api_GetErrorString(err));
}
}
<|endoftext|> |
<commit_before>/**************************************************************************
**
** This file is part of Qt Creator
**
** Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies).
**
** Contact: Nokia Corporation (qt-info@nokia.com)
**
** Commercial Usage
**
** Licensees holding valid Qt Commercial licenses may use this file in
** accordance with the Qt Commercial License Agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and Nokia.
**
** GNU Lesser General Public License Usage
**
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file. Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** If you are unsure which license is appropriate for your use, please
** contact the sales department at http://qt.nokia.com/contact.
**
**************************************************************************/
#include "plaintexteditor.h"
#include "tabsettings.h"
#include "texteditorconstants.h"
#include "texteditorplugin.h"
#include <coreplugin/coreconstants.h>
#include <coreplugin/uniqueidmanager.h>
using namespace TextEditor;
using namespace TextEditor::Internal;
PlainTextEditorEditable::PlainTextEditorEditable(PlainTextEditor *editor)
: BaseTextEditorEditable(editor)
{
Core::UniqueIDManager *uidm = Core::UniqueIDManager::instance();
m_context << uidm->uniqueIdentifier(Core::Constants::K_DEFAULT_TEXT_EDITOR);
m_context << uidm->uniqueIdentifier(TextEditor::Constants::C_TEXTEDITOR);
}
PlainTextEditor::PlainTextEditor(QWidget *parent)
: BaseTextEditor(parent)
{
setRevisionsVisible(true);
setMarksVisible(true);
setRequestMarkEnabled(false);
setLineSeparatorsAllowed(true);
setMimeType(QLatin1String(TextEditor::Constants::C_TEXTEDITOR_MIMETYPE_TEXT));
}
QList<int> PlainTextEditorEditable::context() const
{
return m_context;
}
Core::IEditor *PlainTextEditorEditable::duplicate(QWidget *parent)
{
PlainTextEditor *newEditor = new PlainTextEditor(parent);
newEditor->duplicateFrom(editor());
TextEditorPlugin::instance()->initializeEditor(newEditor);
return newEditor->editableInterface();
}
const char *PlainTextEditorEditable::kind() const
{
return Core::Constants::K_DEFAULT_TEXT_EDITOR;
}
// Indent a text block based on previous line.
// Simple text paragraph layout:
// aaaa aaaa
//
// bbb bb
// bbb bb
//
// - list
// list line2
//
// - listn
//
// ccc
//
// @todo{Add formatting to wrap paragraphs. This requires some
// hoops as the current indentation routines are not prepared
// for additional block being inserted. It might be possible
// to do in 2 steps (indenting/wrapping)}
//
void PlainTextEditor::indentBlock(QTextDocument *doc, QTextBlock block, QChar typedChar)
{
Q_UNUSED(typedChar)
// At beginning: Leave as is.
if (block == doc->begin())
return;
const QTextBlock previous = block.previous();
const QString previousText = previous.text();
// Empty line indicates a start of a new paragraph. Leave as is.
if (previousText.isEmpty() || previousText.trimmed().isEmpty())
return;
// Just use previous line.
// Skip non-alphanumerical characters when determining the indentation
// to enable writing bulleted lists whose items span several lines.
int i = 0;
while (i < previousText.size()) {
if (previousText.at(i).isLetterOrNumber()) {
const TextEditor::TabSettings &ts = tabSettings();
ts.indentLine(block, ts.columnAt(previousText, i));
break;
}
++i;
}
}
<commit_msg>PLain Text Editor: Remove list indentation<commit_after>/**************************************************************************
**
** This file is part of Qt Creator
**
** Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies).
**
** Contact: Nokia Corporation (qt-info@nokia.com)
**
** Commercial Usage
**
** Licensees holding valid Qt Commercial licenses may use this file in
** accordance with the Qt Commercial License Agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and Nokia.
**
** GNU Lesser General Public License Usage
**
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file. Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** If you are unsure which license is appropriate for your use, please
** contact the sales department at http://qt.nokia.com/contact.
**
**************************************************************************/
#include "plaintexteditor.h"
#include "tabsettings.h"
#include "texteditorconstants.h"
#include "texteditorplugin.h"
#include <coreplugin/coreconstants.h>
#include <coreplugin/uniqueidmanager.h>
using namespace TextEditor;
using namespace TextEditor::Internal;
PlainTextEditorEditable::PlainTextEditorEditable(PlainTextEditor *editor)
: BaseTextEditorEditable(editor)
{
Core::UniqueIDManager *uidm = Core::UniqueIDManager::instance();
m_context << uidm->uniqueIdentifier(Core::Constants::K_DEFAULT_TEXT_EDITOR);
m_context << uidm->uniqueIdentifier(TextEditor::Constants::C_TEXTEDITOR);
}
PlainTextEditor::PlainTextEditor(QWidget *parent)
: BaseTextEditor(parent)
{
setRevisionsVisible(true);
setMarksVisible(true);
setRequestMarkEnabled(false);
setLineSeparatorsAllowed(true);
setMimeType(QLatin1String(TextEditor::Constants::C_TEXTEDITOR_MIMETYPE_TEXT));
}
QList<int> PlainTextEditorEditable::context() const
{
return m_context;
}
Core::IEditor *PlainTextEditorEditable::duplicate(QWidget *parent)
{
PlainTextEditor *newEditor = new PlainTextEditor(parent);
newEditor->duplicateFrom(editor());
TextEditorPlugin::instance()->initializeEditor(newEditor);
return newEditor->editableInterface();
}
const char *PlainTextEditorEditable::kind() const
{
return Core::Constants::K_DEFAULT_TEXT_EDITOR;
}
// Indent a text block based on previous line.
// Simple text paragraph layout:
// aaaa aaaa
//
// bbb bb
// bbb bb
//
// - list
// list line2
//
// - listn
//
// ccc
//
// @todo{Add formatting to wrap paragraphs. This requires some
// hoops as the current indentation routines are not prepared
// for additional block being inserted. It might be possible
// to do in 2 steps (indenting/wrapping)}
//
void PlainTextEditor::indentBlock(QTextDocument *doc, QTextBlock block, QChar typedChar)
{
Q_UNUSED(typedChar)
// At beginning: Leave as is.
if (block == doc->begin())
return;
const QTextBlock previous = block.previous();
const QString previousText = previous.text();
// Empty line indicates a start of a new paragraph. Leave as is.
if (previousText.isEmpty() || previousText.trimmed().isEmpty())
return;
// Just use previous line.
// Skip blank characters when determining the indentation
int i = 0;
while (i < previousText.size()) {
if (!previousText.at(i).isSpace()) {
const TextEditor::TabSettings &ts = tabSettings();
ts.indentLine(block, ts.columnAt(previousText, i));
break;
}
++i;
}
}
<|endoftext|> |
<commit_before>/**************************************************************************
**
** This file is part of Qt Creator
**
** Copyright (c) 2010 Nokia Corporation and/or its subsidiary(-ies).
**
** Contact: Nokia Corporation (qt-info@nokia.com)
**
** Commercial Usage
**
** Licensees holding valid Qt Commercial licenses may use this file in
** accordance with the Qt Commercial License Agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and Nokia.
**
** GNU Lesser General Public License Usage
**
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file. Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** If you are unsure which license is appropriate for your use, please
** contact the sales department at http://qt.nokia.com/contact.
**
**************************************************************************/
#include "basecheckoutwizard.h"
#include "vcsbaseconstants.h"
#include "checkoutwizarddialog.h"
#include "checkoutjobs.h"
#include <projectexplorer/projectexplorer.h>
#include <projectexplorer/session.h>
#include <QtCore/QCoreApplication>
#include <QtCore/QFileInfo>
#include <QtCore/QDir>
#include <QtGui/QMessageBox>
namespace VCSBase {
struct BaseCheckoutWizardPrivate {
BaseCheckoutWizardPrivate() : dialog(0) {}
void clear();
Internal::CheckoutWizardDialog *dialog;
QList<QWizardPage *> parameterPages;
QString checkoutPath;
QString id;
};
void BaseCheckoutWizardPrivate::clear()
{
parameterPages.clear();
dialog = 0;
checkoutPath.clear();
}
BaseCheckoutWizard::BaseCheckoutWizard(QObject *parent) :
Core::IWizard(parent),
d(new BaseCheckoutWizardPrivate)
{
}
BaseCheckoutWizard::~BaseCheckoutWizard()
{
delete d;
}
Core::IWizard::WizardKind BaseCheckoutWizard::kind() const
{
return Core::IWizard::ProjectWizard;
}
QString BaseCheckoutWizard::category() const
{
return QLatin1String(VCSBase::Constants::VCS_WIZARD_CATEGORY);
}
QString BaseCheckoutWizard::displayCategory() const
{
return QCoreApplication::translate("VCSBase", VCSBase::Constants::VCS_WIZARD_TR_CATEGORY);
}
QString BaseCheckoutWizard::id() const
{
return d->id;
}
void BaseCheckoutWizard::setId(const QString &id)
{
d->id = id;
}
void BaseCheckoutWizard::runWizard(const QString &path, QWidget *parent)
{
// Create dialog and launch
d->parameterPages = createParameterPages(path);
Internal::CheckoutWizardDialog dialog(d->parameterPages, parent);
d->dialog = &dialog;
connect(&dialog, SIGNAL(progressPageShown()), this, SLOT(slotProgressPageShown()));
dialog.setWindowTitle(displayName());
if (dialog.exec() != QDialog::Accepted)
return;
// Now try to find the project file and open
const QString checkoutPath = d->checkoutPath;
d->clear();
QString errorMessage;
const QString projectFile = openProject(checkoutPath, &errorMessage);
if (projectFile.isEmpty()) {
QMessageBox msgBox(QMessageBox::Warning, tr("Cannot Open Project"),
tr("Failed to open project in '%1'.").arg(QDir::toNativeSeparators(checkoutPath)));
msgBox.setDetailedText(errorMessage);
msgBox.exec();
}
}
static inline QString msgNoProjectFiles(const QDir &dir, const QStringList &patterns)
{
return BaseCheckoutWizard::tr("Could not find any project files matching (%1) in the directory '%2'.").arg(patterns.join(QLatin1String(", ")), QDir::toNativeSeparators(dir.absolutePath()));
}
// Try to find the project files in a project directory with some smartness
static QFileInfoList findProjectFiles(const QDir &projectDir, QString *errorMessage)
{
const QStringList projectFilePatterns = ProjectExplorer::ProjectExplorerPlugin::projectFilePatterns();
// Project directory
QFileInfoList projectFiles = projectDir.entryInfoList(projectFilePatterns, QDir::Files|QDir::NoDotAndDotDot|QDir::Readable);
if (!projectFiles.empty())
return projectFiles;
// Try a 'src' directory
QFileInfoList srcDirs = projectDir.entryInfoList(QStringList(QLatin1String("src")), QDir::Dirs|QDir::NoDotAndDotDot|QDir::Readable);
if (srcDirs.empty()) {
*errorMessage = msgNoProjectFiles(projectDir, projectFilePatterns);
return QFileInfoList();
}
const QDir srcDir = QDir(srcDirs.front().absoluteFilePath());
projectFiles = srcDir.entryInfoList(projectFilePatterns, QDir::Files|QDir::NoDotAndDotDot|QDir::Readable);
if (projectFiles.empty()) {
*errorMessage = msgNoProjectFiles(srcDir, projectFilePatterns);
return QFileInfoList();
}
return projectFiles;;
}
QString BaseCheckoutWizard::openProject(const QString &path, QString *errorMessage)
{
ProjectExplorer::ProjectExplorerPlugin *pe = ProjectExplorer::ProjectExplorerPlugin::instance();
if (!pe) {
*errorMessage = tr("The Project Explorer is not available.");
return QString();
}
// Search the directory for project files
const QDir dir(path);
if (!dir.exists()) {
*errorMessage = tr("'%1' does not exist.").
arg(QDir::toNativeSeparators(path)); // Should not happen
return QString();
}
QFileInfoList projectFiles = findProjectFiles(dir, errorMessage);
if (projectFiles.empty())
return QString();
// Open. Do not use a busy cursor here as additional wizards might pop up
const QString projectFile = projectFiles.front().absoluteFilePath();
if (!pe->openProject(projectFile)) {
*errorMessage = tr("Unable to open the project '%1'.").
arg(QDir::toNativeSeparators(projectFile));
return QString();
}
return projectFile;
}
void BaseCheckoutWizard::slotProgressPageShown()
{
const QSharedPointer<AbstractCheckoutJob> job = createJob(d->parameterPages, &(d->checkoutPath));
if (!job.isNull())
d->dialog->start(job);
}
} // namespace VCSBase
<commit_msg>vcsbase: Remove uneeded include<commit_after>/**************************************************************************
**
** This file is part of Qt Creator
**
** Copyright (c) 2010 Nokia Corporation and/or its subsidiary(-ies).
**
** Contact: Nokia Corporation (qt-info@nokia.com)
**
** Commercial Usage
**
** Licensees holding valid Qt Commercial licenses may use this file in
** accordance with the Qt Commercial License Agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and Nokia.
**
** GNU Lesser General Public License Usage
**
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file. Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** If you are unsure which license is appropriate for your use, please
** contact the sales department at http://qt.nokia.com/contact.
**
**************************************************************************/
#include "basecheckoutwizard.h"
#include "vcsbaseconstants.h"
#include "checkoutwizarddialog.h"
#include "checkoutjobs.h"
#include <projectexplorer/projectexplorer.h>
#include <QtCore/QCoreApplication>
#include <QtCore/QFileInfo>
#include <QtCore/QDir>
#include <QtGui/QMessageBox>
namespace VCSBase {
struct BaseCheckoutWizardPrivate {
BaseCheckoutWizardPrivate() : dialog(0) {}
void clear();
Internal::CheckoutWizardDialog *dialog;
QList<QWizardPage *> parameterPages;
QString checkoutPath;
QString id;
};
void BaseCheckoutWizardPrivate::clear()
{
parameterPages.clear();
dialog = 0;
checkoutPath.clear();
}
BaseCheckoutWizard::BaseCheckoutWizard(QObject *parent) :
Core::IWizard(parent),
d(new BaseCheckoutWizardPrivate)
{
}
BaseCheckoutWizard::~BaseCheckoutWizard()
{
delete d;
}
Core::IWizard::WizardKind BaseCheckoutWizard::kind() const
{
return Core::IWizard::ProjectWizard;
}
QString BaseCheckoutWizard::category() const
{
return QLatin1String(VCSBase::Constants::VCS_WIZARD_CATEGORY);
}
QString BaseCheckoutWizard::displayCategory() const
{
return QCoreApplication::translate("VCSBase", VCSBase::Constants::VCS_WIZARD_TR_CATEGORY);
}
QString BaseCheckoutWizard::id() const
{
return d->id;
}
void BaseCheckoutWizard::setId(const QString &id)
{
d->id = id;
}
void BaseCheckoutWizard::runWizard(const QString &path, QWidget *parent)
{
// Create dialog and launch
d->parameterPages = createParameterPages(path);
Internal::CheckoutWizardDialog dialog(d->parameterPages, parent);
d->dialog = &dialog;
connect(&dialog, SIGNAL(progressPageShown()), this, SLOT(slotProgressPageShown()));
dialog.setWindowTitle(displayName());
if (dialog.exec() != QDialog::Accepted)
return;
// Now try to find the project file and open
const QString checkoutPath = d->checkoutPath;
d->clear();
QString errorMessage;
const QString projectFile = openProject(checkoutPath, &errorMessage);
if (projectFile.isEmpty()) {
QMessageBox msgBox(QMessageBox::Warning, tr("Cannot Open Project"),
tr("Failed to open project in '%1'.").arg(QDir::toNativeSeparators(checkoutPath)));
msgBox.setDetailedText(errorMessage);
msgBox.exec();
}
}
static inline QString msgNoProjectFiles(const QDir &dir, const QStringList &patterns)
{
return BaseCheckoutWizard::tr("Could not find any project files matching (%1) in the directory '%2'.").arg(patterns.join(QLatin1String(", ")), QDir::toNativeSeparators(dir.absolutePath()));
}
// Try to find the project files in a project directory with some smartness
static QFileInfoList findProjectFiles(const QDir &projectDir, QString *errorMessage)
{
const QStringList projectFilePatterns = ProjectExplorer::ProjectExplorerPlugin::projectFilePatterns();
// Project directory
QFileInfoList projectFiles = projectDir.entryInfoList(projectFilePatterns, QDir::Files|QDir::NoDotAndDotDot|QDir::Readable);
if (!projectFiles.empty())
return projectFiles;
// Try a 'src' directory
QFileInfoList srcDirs = projectDir.entryInfoList(QStringList(QLatin1String("src")), QDir::Dirs|QDir::NoDotAndDotDot|QDir::Readable);
if (srcDirs.empty()) {
*errorMessage = msgNoProjectFiles(projectDir, projectFilePatterns);
return QFileInfoList();
}
const QDir srcDir = QDir(srcDirs.front().absoluteFilePath());
projectFiles = srcDir.entryInfoList(projectFilePatterns, QDir::Files|QDir::NoDotAndDotDot|QDir::Readable);
if (projectFiles.empty()) {
*errorMessage = msgNoProjectFiles(srcDir, projectFilePatterns);
return QFileInfoList();
}
return projectFiles;;
}
QString BaseCheckoutWizard::openProject(const QString &path, QString *errorMessage)
{
ProjectExplorer::ProjectExplorerPlugin *pe = ProjectExplorer::ProjectExplorerPlugin::instance();
if (!pe) {
*errorMessage = tr("The Project Explorer is not available.");
return QString();
}
// Search the directory for project files
const QDir dir(path);
if (!dir.exists()) {
*errorMessage = tr("'%1' does not exist.").
arg(QDir::toNativeSeparators(path)); // Should not happen
return QString();
}
QFileInfoList projectFiles = findProjectFiles(dir, errorMessage);
if (projectFiles.empty())
return QString();
// Open. Do not use a busy cursor here as additional wizards might pop up
const QString projectFile = projectFiles.front().absoluteFilePath();
if (!pe->openProject(projectFile)) {
*errorMessage = tr("Unable to open the project '%1'.").
arg(QDir::toNativeSeparators(projectFile));
return QString();
}
return projectFile;
}
void BaseCheckoutWizard::slotProgressPageShown()
{
const QSharedPointer<AbstractCheckoutJob> job = createJob(d->parameterPages, &(d->checkoutPath));
if (!job.isNull())
d->dialog->start(job);
}
} // namespace VCSBase
<|endoftext|> |
<commit_before>/*
** Copyright 2015 Centreon
**
** 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.
**
** For more information : contact@centreon.com
*/
#include <QMutexLocker>
#include <sstream>
#include "com/centreon/broker/extcmd/command_listener.hh"
#include "com/centreon/broker/extcmd/command_request.hh"
#include "com/centreon/broker/extcmd/command_result.hh"
#include "com/centreon/broker/io/exceptions/shutdown.hh"
using namespace com::centreon::broker;
using namespace com::centreon::broker::extcmd;
/**
* Constructor.
*/
command_listener::command_listener() : _next_invalid(0) {}
/**
* Destructor.
*/
command_listener::~command_listener() {}
/**
* Get status of command.
*
* @param[in] command_uuid Command UUID.
*
* @return Command result.
*/
command_result command_listener::command_status(
QString const& command_uuid) {
// Check for entries that should be removed from cache.
_check_invalid();
command_result res;
QMutexLocker lock(&_pendingm);
std::map<std::string, pending_command>::iterator
it(_pending.find(command_uuid.toStdString()));
// Command result exists.
if (it != _pending.end()) {
res = it->second.result;
if (it->second.with_partial_result)
it->second.result.msg.clear();
}
// Fake command result.
else {
lock.unlock();
res.uuid = command_uuid;
res.destination_id = io::data::broker_id;
res.code = -1;
std::ostringstream oss;
oss << "Command " << command_uuid.toStdString()
<< " is not available (invalid command ID, timeout, ?)";
res.msg = oss.str().c_str();
}
return (res);
}
/**
* Read from command listener.
*
* @param[in] d Unused.
* @param[in] deadline Unused.
*
* @return This method will throw.
*/
bool command_listener::read(
misc::shared_ptr<io::data>& d,
time_t deadline) {
(void)deadline;
d.clear();
throw (io::exceptions::shutdown(true, false)
<< "cannot read from command listener");
return (true);
}
/**
* Write to command listener.
*
* @param[in] d Command listener only process command requests and
* command results.
*/
int command_listener::write(misc::shared_ptr<io::data> const& d) {
if (!validate(d, "command"))
return (1);
// Command request, store it in the cache.
if (d->type() == command_request::static_type()) {
command_request const& req(d.ref_as<command_request const>());
QMutexLocker lock(&_pendingm);
std::map<std::string, pending_command>::iterator
it(_pending.find(req.uuid.toStdString()));
if (it == _pending.end()) {
pending_command&
p(_pending[req.uuid.toStdString()]);
p.invalid_time = time(NULL) + _request_timeout;
p.result.uuid = req.uuid;
p.result.code = 1;
p.result.msg = "\"Pending\"";
p.with_partial_result = req.with_partial_result;
if (p.invalid_time < _next_invalid)
_next_invalid = p.invalid_time;
}
}
// Command result, store it in the cache.
else if (d->type() == command_result::static_type()) {
command_result const& res(d.ref_as<command_result const>());
QMutexLocker lock(&_pendingm);
pending_command&
p(_pending[res.uuid.toStdString()]);
if (p.with_partial_result == false)
p.result = res;
else
_merge_partial_result(p, res);
p.invalid_time = time(NULL) + _result_timeout;
if (p.invalid_time < _next_invalid)
_next_invalid = p.invalid_time;
}
// Check for entries that should be removed from cache.
_check_invalid();
return (1);
}
/**
* Check for invalid entries in cache.
*/
void command_listener::_check_invalid() {
time_t now(time(NULL));
_next_invalid = now + 24 * 60 * 60;
QMutexLocker lock(&_pendingm);
for (std::map<std::string, pending_command>::iterator
it(_pending.begin()),
end(_pending.end());
it != end;) {
if (it->second.invalid_time < now) {
if (it->second.result.code == 1) { // Pending.
it->second.invalid_time = now + _result_timeout;
it->second.result.code = -1;
it->second.result.msg = "\"Command timeout\"";
++it;
}
else {
std::map<std::string, pending_command>::iterator
to_delete(it);
++it;
_pending.erase(to_delete);
}
}
else if (it->second.invalid_time < _next_invalid) {
_next_invalid = it->second.invalid_time;
++it;
}
else
++it;
}
return ;
}
/**
* Merge partial result.
*
* @param[out] dest The destination of the merge.
* @param[in] res The partial result to merge.
*/
void command_listener::_merge_partial_result(
pending_command& dest,
command_result const& res) {
dest.result.msg.append(res.msg);
}
<commit_msg>Core: add forgotten \"\".<commit_after>/*
** Copyright 2015 Centreon
**
** 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.
**
** For more information : contact@centreon.com
*/
#include <QMutexLocker>
#include <sstream>
#include "com/centreon/broker/extcmd/command_listener.hh"
#include "com/centreon/broker/extcmd/command_request.hh"
#include "com/centreon/broker/extcmd/command_result.hh"
#include "com/centreon/broker/io/exceptions/shutdown.hh"
using namespace com::centreon::broker;
using namespace com::centreon::broker::extcmd;
/**
* Constructor.
*/
command_listener::command_listener() : _next_invalid(0) {}
/**
* Destructor.
*/
command_listener::~command_listener() {}
/**
* Get status of command.
*
* @param[in] command_uuid Command UUID.
*
* @return Command result.
*/
command_result command_listener::command_status(
QString const& command_uuid) {
// Check for entries that should be removed from cache.
_check_invalid();
command_result res;
QMutexLocker lock(&_pendingm);
std::map<std::string, pending_command>::iterator
it(_pending.find(command_uuid.toStdString()));
// Command result exists.
if (it != _pending.end()) {
res = it->second.result;
if (it->second.with_partial_result)
it->second.result.msg.clear();
}
// Fake command result.
else {
lock.unlock();
res.uuid = command_uuid;
res.destination_id = io::data::broker_id;
res.code = -1;
std::ostringstream oss;
oss << "\"Command " << command_uuid.toStdString()
<< " is not available (invalid command ID, timeout, ?)\"";
res.msg = oss.str().c_str();
}
return (res);
}
/**
* Read from command listener.
*
* @param[in] d Unused.
* @param[in] deadline Unused.
*
* @return This method will throw.
*/
bool command_listener::read(
misc::shared_ptr<io::data>& d,
time_t deadline) {
(void)deadline;
d.clear();
throw (io::exceptions::shutdown(true, false)
<< "cannot read from command listener");
return (true);
}
/**
* Write to command listener.
*
* @param[in] d Command listener only process command requests and
* command results.
*/
int command_listener::write(misc::shared_ptr<io::data> const& d) {
if (!validate(d, "command"))
return (1);
// Command request, store it in the cache.
if (d->type() == command_request::static_type()) {
command_request const& req(d.ref_as<command_request const>());
QMutexLocker lock(&_pendingm);
std::map<std::string, pending_command>::iterator
it(_pending.find(req.uuid.toStdString()));
if (it == _pending.end()) {
pending_command&
p(_pending[req.uuid.toStdString()]);
p.invalid_time = time(NULL) + _request_timeout;
p.result.uuid = req.uuid;
p.result.code = 1;
p.result.msg = "\"Pending\"";
p.with_partial_result = req.with_partial_result;
if (p.invalid_time < _next_invalid)
_next_invalid = p.invalid_time;
}
}
// Command result, store it in the cache.
else if (d->type() == command_result::static_type()) {
command_result const& res(d.ref_as<command_result const>());
QMutexLocker lock(&_pendingm);
pending_command&
p(_pending[res.uuid.toStdString()]);
if (p.with_partial_result == false)
p.result = res;
else
_merge_partial_result(p, res);
p.invalid_time = time(NULL) + _result_timeout;
if (p.invalid_time < _next_invalid)
_next_invalid = p.invalid_time;
}
// Check for entries that should be removed from cache.
_check_invalid();
return (1);
}
/**
* Check for invalid entries in cache.
*/
void command_listener::_check_invalid() {
time_t now(time(NULL));
_next_invalid = now + 24 * 60 * 60;
QMutexLocker lock(&_pendingm);
for (std::map<std::string, pending_command>::iterator
it(_pending.begin()),
end(_pending.end());
it != end;) {
if (it->second.invalid_time < now) {
if (it->second.result.code == 1) { // Pending.
it->second.invalid_time = now + _result_timeout;
it->second.result.code = -1;
it->second.result.msg = "\"Command timeout\"";
++it;
}
else {
std::map<std::string, pending_command>::iterator
to_delete(it);
++it;
_pending.erase(to_delete);
}
}
else if (it->second.invalid_time < _next_invalid) {
_next_invalid = it->second.invalid_time;
++it;
}
else
++it;
}
return ;
}
/**
* Merge partial result.
*
* @param[out] dest The destination of the merge.
* @param[in] res The partial result to merge.
*/
void command_listener::_merge_partial_result(
pending_command& dest,
command_result const& res) {
dest.result.msg.append(res.msg);
}
<|endoftext|> |
<commit_before>//
// Logarithm.cpp
// Calculator
//
// Created by Gavin Scheele on 3/27/14.
// Copyright (c) 2014 Gavin Scheele. All rights reserved.
//
#include "Logarithm.h"
Logarithm::Logarithm(int base, int operand){
this->type = "logarithm";
this->base = base;
this->operand = operand;
}
Logarithm::Logarithm(int base, Expression* eOperand){
this->type = "logarithm";
this->base = base;
this->eOperand = eOperand;
}
Logarithm::Logarithm(Expression* eBase, int operand){
this->type = "logarithm";
this->eBase = eBase;
this->operand = operand;
}
Logarithm::Logarithm(Expression* eBase, Expression* eOperand){
this->type = "logarithm";
this->eBase = eBase;
this->eOperand = eOperand;
}
Logarithm::~Logarithm(){
delete this;
}
Expression* Logarithm::simplify(){
if (base && operand) {
if (base == operand){
Expression* simplified = new Integer(1);
return simplified; }
else if(base == (1/operand){
Expression* simplified = new Integer(-1);
return simplified;}
}
else{
int primefactors[] = primeFactorization(x);
int size;
size = sizeof primefactors/sizeof (int);
Expression* finalsimp;
for (i = 0; i <= size-1; i++) {
if (size ==1) {
finalsimp = new Logarithm(base,operand);
}
Expression* seperatedlogs[i]= new Logarithm(base,primefactors[i]) ;
if (seperatedlogs[i]->simplify() != seperatedlogs[i]){
Expression* simp = seperatedlogs[i]->simplify()
seperatedlogs[i]= simp;
}
for (i = 0; i<= size-2; i++){
finalsimp= seperatedlogs[i]->add(seperatedlogs[i+1]
}
return finalsimp;
}
}
if (base && eOperand) {
}
}
int[] Logarithm::primeFactorization(int n) {
int k = 0;
while (n%2 == 0) {
factors[k] = 2;
k++;
n = n/2;
}
for (i = 3; i <= sqrt(n); i = i + 2) {
while (n%1 == 0) {
factors[k] = 2;
k++;
n = n/i;
}
}
if (n > 2) {
factors[k] = n;
}
return factors;
}
Expression* Logarithm::add(Expression* a){
Expression* c = this;
return c;
}
Expression* Logarithm::subtract(Expression* a){
Expression* c = this;
return c;
}
Expression* Logarithm::multiply(Expression* a){
Expression* c = this;
return c;
}
Expression* Logarithm::divide(Expression* a){
Expression* c = this;
return c;
}
ostream& Logarithm::print(std::ostream& output) const{
output << "Log" << this->base << "(" << this->operand << ")";
return output;
}
// might need later had in simplify metthod not sure
/*int i = 1;
int x = operand;
int y = base;
if(x % y == 0 &&) {
while (x>y) {
x /=y ;
i++;}
Expression* simplified = new Integer(i);
return simplified; }
*/
<commit_msg>Update Logarithm.cpp<commit_after>//
// Logarithm.cpp
// Calculator
//
// Created by Gavin Scheele on 3/27/14.
// Copyright (c) 2014 Gavin Scheele. All rights reserved.
//
#include "Logarithm.h"
Logarithm::Logarithm(int base, int operand){
this->type = "logarithm";
this->base = base;
this->operand = operand;
}
Logarithm::Logarithm(int base, Expression* eOperand){
this->type = "logarithm";
this->base = base;
this->eOperand = eOperand;
}
Logarithm::Logarithm(Expression* eBase, int operand){
this->type = "logarithm";
this->eBase = eBase;
this->operand = operand;
}
Logarithm::Logarithm(Expression* eBase, Expression* eOperand){
this->type = "logarithm";
this->eBase = eBase;
this->eOperand = eOperand;
}
Logarithm::~Logarithm(){
delete this;
}
Expression* Logarithm::simplify(){
if (base && operand) {
if (base == operand){
Expression* simplified = new Integer(1);
return simplified; }
else if(base == (1/operand){
Expression* simplified = new Integer(-1);
return simplified;}
}
else{
int primefactors[] = primeFactorization(x);
int size;
size = sizeof primefactors/sizeof (int);
Expression* finalsimp;
for (i = 0; i <= size-1; i++) {
if (size ==1) {
finalsimp = new Logarithm(base,operand);
}
Expression* seperatedlogs[i]= new Logarithm(base,primefactors[i]) ;
if (seperatedlogs[i]->simplify() != seperatedlogs[i]){
Expression* simp = seperatedlogs[i]->simplify()
seperatedlogs[i]= simp;
}
for (i = 0; i<= size-2; i++){
finalsimp= seperatedlogs[i]->add(seperatedlogs[i+1]
}
return finalsimp;
}
}
if (base && eOperand) {
}
if (eBase && operand) {
}
if (eBase && eOperand){
if (eBase == eOperand){
Expression* simplified = new Integer(1);
return simplified; }
else if(eBase == (1/eOperand){
Expression* simplified = new Integer(-1);
return simplified;}
}
}
int[] Logarithm::primeFactorization(int n) {
int k = 0;
while (n%2 == 0) {
factors[k] = 2;
k++;
n = n/2;
}
for (i = 3; i <= sqrt(n); i = i + 2) {
while (n%1 == 0) {
factors[k] = 2;
k++;
n = n/i;
}
}
if (n > 2) {
factors[k] = n;
}
return factors;
}
Expression* Logarithm::add(Expression* a){
Expression* c = this;
return c;
}
Expression* Logarithm::subtract(Expression* a){
Expression* c = this;
return c;
}
Expression* Logarithm::multiply(Expression* a){
Expression* c = this;
return c;
}
Expression* Logarithm::divide(Expression* a){
Expression* c = this;
return c;
}
ostream& Logarithm::print(std::ostream& output) const{
output << "Log" << this->base << "(" << this->operand << ")";
return output;
}
// might need later had in simplify metthod not sure
/*int i = 1;
int x = operand;
int y = base;
if(x % y == 0 &&) {
while (x>y) {
x /=y ;
i++;}
Expression* simplified = new Integer(i);
return simplified; }
*/
<|endoftext|> |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.